Skip to content

Commit 24ef00c

Browse files
committed
feat: iOS 部分适配 DartNative 0.4 版本
1 parent 2308e1c commit 24ef00c

File tree

8 files changed

+84
-53
lines changed

8 files changed

+84
-53
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
## [2.0.0] - 2021-11-08
2+
3+
* Adapted to version 0.4 of dart_native.
4+
15
## [1.0.2] - 2020-05-25
26

37
* Support generating Flutter package.

bin/codegen.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import { program } from 'commander'
33
import { main } from '../lib/main.js'
44

5-
program.version('1.2.2')
5+
program.version('2.0.0')
66

77
program
88
.arguments('<input>', 'Iutput directory')

lib/main.js

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ const dnPartExtension = 'dnpart'
1010
var outputDir
1111
var projectName
1212
var packageSet = new Set()
13+
var enumeratorTypeNames = []
1314
var isMainThread = false
1415

1516
const scriptForObjC = './lib/objc/DNObjectiveCConverter.js'
@@ -85,10 +86,12 @@ function writeOutputToFileByPath(result, srcPath) {
8586
}
8687

8788
function mergeFiles(filePaths) {
88-
if (!filePaths || filePaths.length <= 1) {
89-
return
89+
if (!filePaths || filePaths.length == 0) {
90+
return ''
91+
}
92+
if (filePaths.length == 1) {
93+
return filePaths[0]
9094
}
91-
9295
let result = filePaths.sort().map(filePath => {
9396
if (!filePath) {
9497
return ''
@@ -100,6 +103,22 @@ function mergeFiles(filePaths) {
100103
filePaths.forEach((filePath) => {
101104
fs.unlinkSync(filePath)
102105
})
106+
return mergedFilePath
107+
}
108+
109+
function postprocessingFiles(filePaths) {
110+
filePaths.forEach((filePath) => {
111+
if (!filePath || filePath == '') {
112+
return
113+
}
114+
var content = fs.readFileSync(filePath, { encoding: 'utf8' })
115+
// handle enumeratorTypeNames
116+
enumeratorTypeNames.forEach(type => {
117+
const keyword = type + '.fromPointer(result)'
118+
content = content.replace(keyword, 'result.address')
119+
})
120+
fs.writeFileSync(filePath, content)
121+
})
103122
}
104123

105124
function formatDartFile(dartPath) {
@@ -161,7 +180,9 @@ function generateDartWithWorker(content, path, script) {
161180
}
162181

163182
let dartFilePath = writeOutputToFileByPath(result.dartCode, path)
164-
183+
// collect all enumeratorTypeNames
184+
result.enumeratorTypeNames.forEach(item => enumeratorTypeNames.push(item))
185+
// collect all packages
165186
if (projectName) {
166187
result.packages.forEach(item => packageSet.add(item))
167188
}
@@ -201,10 +222,10 @@ async function runWorkItems(workItems) {
201222
})
202223
return Promise.all(ps).then((results) => {
203224
// merge files
204-
mergeFiles(results.filter((f) => f != undefined))
225+
return mergeFiles(results.filter((f) => f != undefined))
205226
})
206227
})
207-
await Promise.all(promises)
228+
return await Promise.all(promises)
208229
}
209230

210231
function checkTemplateValid(template) {
@@ -260,7 +281,8 @@ export async function main(input, options, onMainThread = false) {
260281
workItems.set(file, script)
261282
})
262283
})
263-
await runWorkItems(workItems)
284+
const filePaths = await runWorkItems(workItems)
285+
postprocessingFiles(filePaths)
264286

265287
outputDir = baseOutputDir
266288
formatDartFile(outputDir)

lib/objc/DNObjectiveCContext.js

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
11
import DNObjectiveCTypeConverter from './DNObjectiveCTypeConverter.js'
22
import { rawGenericType, convertMutableTypeIfNeed } from '../common/utils.js'
33

4+
export class DNResult {
5+
constructor(dartCode, packages, enumeratorTypeNames) {
6+
this.dartCode = dartCode
7+
this.packages = packages
8+
this.enumeratorTypeNames = enumeratorTypeNames
9+
}
10+
}
11+
412
export class DNContext {
513
constructor(internal) {
614
this.internal = internal
@@ -81,14 +89,12 @@ export class DNBlockDefContext extends DNContext {
8189
parse() {
8290
var argList = ''
8391
this.args.forEach((element, index) => {
84-
if (index == this.args.length - 1) {
85-
argList += element.type + ' ' + element.name
86-
} else {
87-
argList += element.type + ' ' + element.name + ', '
92+
argList += element.type + '? ' + element.name
93+
if (index != this.args.length - 1) {
94+
argList += ', '
8895
}
8996
})
90-
var result = 'typedef '
91-
result += this.returnType + ' ' + this.defName + '(' + argList + ');'
97+
const result = 'typedef ' + this.defName + ' = ' + this.returnType + '? Function(' + argList + ');'
9298
return result
9399
}
94100
}
@@ -107,8 +113,7 @@ export class DNEnumItemContext extends DNContext {
107113
var result = this.availability.map((a) => a.parse()).join(' ') + '\n'
108114
this.value = this.value.toString().replace('UL','')
109115
if (this.type) {
110-
result += 'const ' + this.type + ' ' + this.name + ' = ' +
111-
this.type + '(' + this.value + ');\n'
116+
result += 'const ' + this.type + ' ' + this.name + ' = ' + this.value + ';\n'
112117
} else {
113118
result += 'const int ' + this.name + ' = ' + this.value + ';\n'
114119
}
@@ -132,15 +137,12 @@ export class DNEnumDefContext extends DNContext {
132137
var result = '\n'
133138
if (this.defName) {
134139
var availability = this.availability.map((a) => a.parse()).join(' ') + '\n'
135-
var superClass = 'NSEnum'
140+
var aliasType = 'NSEnum'
136141
if (this.type == 'NS_OPTIONS') {
137-
superClass = 'NSOptions'
142+
aliasType = 'NSOptions'
138143
}
139144
result += availability +
140-
'class ' + this.defName + ' extends ' + superClass + ' {\n' +
141-
' const ' + this.defName + '(dynamic raw) : super(raw);\n' +
142-
' ' + this.defName + '.fromPointer(Pointer<Void> ptr) : super(ptr.address);\n' +
143-
'}\n\n'
145+
'typedef ' + this.defName + ' = ' + aliasType + ';\n\n'
144146
}
145147

146148
for (const key in this.enumMap) {
@@ -475,7 +477,7 @@ export class DNClassContext extends DNContext {
475477
result += ' with ' + this.protocols.join(',')
476478
}
477479
result += ' {\n'
478-
result += ' ' + this.name + '([Class isa]) : super(isa ?? Class(\'' + this.name + '\'));\n'
480+
result += ' ' + this.name + '([Class? isa]) : super(isa ?? Class(\'' + this.name + '\'));\n'
479481
result += ' ' + this.name + '.fromPointer(Pointer<Void> ptr) : super.fromPointer(ptr);\n'
480482
this.properties.forEach(element => {
481483
var parseRet = element.parse()
@@ -589,10 +591,11 @@ export class DNImportContext extends DNContext {
589591
}
590592

591593
export class DNRootContext extends DNContext {
592-
constructor(internal, needExport, isPartOfFile = false) {
594+
constructor(internal, needExport, isPartOfFile = false, enumeratorTypeNames = []) {
593595
super(internal)
594596
this.needExport = needExport
595597
this.isPartOfFile = isPartOfFile
598+
this.enumeratorTypeNames = enumeratorTypeNames
596599
}
597600

598601
parse() {
@@ -617,10 +620,7 @@ export class DNRootContext extends DNContext {
617620
}
618621
return childResult
619622
}).join('\n')
620-
return {
621-
dartCode: result,
622-
packages: packageSet
623-
}
623+
return new DNResult(result, packageSet, this.enumeratorTypeNames)
624624
}
625625
}
626626

lib/objc/DNObjectiveCParserListener.js

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,9 @@ export default class DNObjectiveCParserListener extends ObjectiveCParserListener
1414
this.isPartOfFile = isPartOfFile
1515
}
1616

17-
buildDart() {
18-
var dart = this.rootContext.parse()
19-
this.cb(dart, null)
17+
buildResult() {
18+
var result = this.rootContext.parse()
19+
this.cb(result, null)
2020
}
2121

2222
// Enter a parse tree produced by ObjectiveCParser#translationUnit.
@@ -37,7 +37,7 @@ export default class DNObjectiveCParserListener extends ObjectiveCParserListener
3737
}
3838
// Exit a parse tree produced by ObjectiveCParser#translationUnit.
3939
exitTranslationUnit(ctx) {
40-
this.buildDart()
40+
this.buildResult()
4141
}
4242
// Enter a parse tree produced by ObjectiveCParser#topLevelDeclaration.
4343
enterTopLevelDeclaration(ctx) {
@@ -584,6 +584,8 @@ export default class DNObjectiveCParserListener extends ObjectiveCParserListener
584584
}
585585
// Exit a parse tree produced by ObjectiveCParser#enumDeclaration.
586586
exitEnumDeclaration(ctx) {
587+
// Add Enumerator to global array for postprocessing.
588+
this.rootContext.enumeratorTypeNames.push(this.currentContext.defName)
587589
this.currentContext = this.currentContext.parent
588590
}
589591
// Enter a parse tree produced by ObjectiveCParser#varDeclaration.
@@ -729,11 +731,10 @@ export default class DNObjectiveCParserListener extends ObjectiveCParserListener
729731
returnType = this.currentContext.parent.name
730732
}
731733
this.currentContext.returnType = TC.convert(returnType)
732-
// FIXME: pointer to struct
733-
/// Both CString and NSString can be converted to Dart String.
734-
/// But converting CString to Dart String is under auto encoding,
735-
/// which doesn't need call `fromPointer`.
736-
var isDartPointerType =!DNObjectiveCTypeConverter.basicAutoConvertReturnTypes.includes(this.currentContext.returnType) &&
734+
/// FIXME: pointer to struct
735+
/// Both CString and NSString can be converted to Dart String automatically,
736+
/// those don't need call `fromPointer`.
737+
var isDartPointerType = !DNObjectiveCTypeConverter.basicAutoConvertReturnTypes.includes(this.currentContext.returnType) &&
737738
(!DNObjectiveCTypeConverter.ObjcBasicType.includes(returnType) || (pointer != null && returnType != 'char *'));
738739
this.currentContext.callFromPointer = isDartPointerType
739740
} else if (this.currentContext instanceof DNArgumentContext) {
@@ -759,10 +760,9 @@ export default class DNObjectiveCParserListener extends ObjectiveCParserListener
759760
}
760761
this.currentContext.type = TC.convert(type)
761762
}
762-
// FIXME: pointer to struct
763-
/// Both CString and NSString can be converted to Dart String.
764-
/// But converting CString to Dart String is under auto encoding,
765-
/// which doesn't need call `fromPointer`.
763+
/// FIXME: pointer to struct
764+
/// Both CString and NSString can be converted to Dart String automatically,
765+
/// those don't need call `fromPointer`.
766766
this.currentContext.isDartPointerType = !DNObjectiveCTypeConverter.basicAutoConvertReturnTypes.includes(this.currentContext.type) &&
767767
(!DNObjectiveCTypeConverter.ObjcBasicType.includes(type) || (pointer != null && type != 'char *'));
768768
}

lib/objc/DNObjectiveCTypeConverter.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ export default class DNObjectiveCTypeConverter {
88

99
convert(objcType, isTypeInBlock = false) {
1010
var result = objcType
11-
//basic type not need to remove * symbol
11+
// basic type not need to remove * symbol
1212
if (!DNObjectiveCTypeConverter.ObjcBasicType.includes(result)) {
1313
result = result.replace(/\s+\*+/g,"")
1414
}
@@ -47,6 +47,7 @@ DNObjectiveCTypeConverter.DNOCBuiltinTypeToDartMap = {
4747
'NSArray': 'List',
4848
'NSDictionary': 'Map',
4949
'NSSet': 'Set',
50+
'NSString': 'String',
5051
}
5152

5253
DNObjectiveCTypeConverter.DNOCBlockTypeToDartMap = {
@@ -61,10 +62,12 @@ DNObjectiveCTypeConverter.basicAutoConvertReturnTypes = [
6162
'double',
6263
'bool',
6364
'CString',
65+
'String',
6466
'Pointer<Void>',
6567
// TODO: built-in Structs
6668
]
6769

70+
// Objective-C basic type will not remove * symbol
6871
DNObjectiveCTypeConverter.ObjcBasicType = [
6972
'void',
7073
'void *',
@@ -94,7 +97,7 @@ DNObjectiveCTypeConverter.ObjcBasicType = [
9497
'CGFloat',
9598
'BOOL',
9699
'bool',
97-
'_Bool'
100+
'_Bool',
98101
]
99102

100103
//ignore mutable type

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@dartnative/codegen",
3-
"version": "1.2.2",
3+
"version": "2.0.0",
44
"type": "module",
55
"description": "Code generator for dart_native.",
66
"main": "index.js",

test/objc/RuntimeStub.h

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,9 @@
99

1010
NS_ASSUME_NONNULL_BEGIN
1111

12-
typedef NS_OPTIONS(NSUInteger, TestOptions) {
13-
TestOptionsNone = 0,
14-
TestOptionsOne = 1 << 0,
15-
TestOptionsTwo = 1 << 1,
12+
typedef NS_OPTIONS(NSUInteger, ItemIndex) { ItemIndexNone = 0,
13+
ItemIndexOne = 1 << 0,
14+
ItemIndexTwo = 1 << 1,
1615
};
1716

1817
@protocol SampleDelegate
@@ -22,9 +21,10 @@ typedef NS_OPTIONS(NSUInteger, TestOptions) {
2221

2322
@end
2423

25-
typedef NSObject * _Nonnull (^BarBlock)(NSObject *a);
24+
typedef NSObject *_Nonnull (^BarBlock)(NSObject *a);
2625
typedef CGAffineTransform (^StretBlock)(CGAffineTransform a);
27-
typedef char * _Nonnull (^CStringRetBlock)(char *a);
26+
typedef char *_Nonnull (^CStringRetBlock)(char *a);
27+
typedef NSDictionary *_Nonnull (^NSDictionaryRetBlock)(NSDictionary *a);
2828
typedef CGFloat (^CGFloatRetBlock)(CGFloat a);
2929

3030
@interface RuntimeStub : NSObject
@@ -56,6 +56,7 @@ typedef CGFloat (^CGFloatRetBlock)(CGFloat a);
5656
- (NSDirectionalEdgeInsets)fooNSDirectionalEdgeInsets:(NSDirectionalEdgeInsets)insets
5757
API_AVAILABLE(ios(11.0));
5858
- (CGAffineTransform)fooCGAffineTransform:(CGAffineTransform)transform;
59+
- (CATransform3D)fooCATransform3D:(CATransform3D)transform3D;
5960
- (NSArray *)fooNSArray:(NSArray *)array;
6061
- (NSMutableArray *)fooNSMutableArray:(NSMutableArray *)array;
6162
- (NSDictionary *)fooNSDictionary:(NSDictionary *)dict;
@@ -64,14 +65,15 @@ typedef CGFloat (^CGFloatRetBlock)(CGFloat a);
6465
- (NSMutableSet *)fooNSMutableSet:(NSMutableSet *)set;
6566
- (void)fooBlock:(BarBlock)block;
6667
- (void)fooStretBlock:(StretBlock)block;
68+
- (void)fooCompletion:(void (^)(void))block;
6769
- (void)fooCStringBlock:(CStringRetBlock)block;
68-
- (void)fooCompletion:(void(^)(void))block;
70+
- (void)fooNSDictionaryBlock:(NSDictionaryRetBlock)block;
6971
- (void)fooDelegate:(id<SampleDelegate>)delegate;
7072
- (void)fooStructDelegate:(id<SampleDelegate>)delegate;
7173
- (NSString *)fooNSString:(NSString *)str;
7274
- (NSMutableString *)fooNSMutableString:(NSMutableString *)str;
73-
- (void)fooWithError:(out NSError **)error;
74-
- (TestOptions)fooWithOptions:(TestOptions)options;
75+
- (BOOL)fooWithError:(out NSError **)error;
76+
- (ItemIndex)fooWithOptions:(ItemIndex)options;
7577

7678
@end
7779

0 commit comments

Comments
 (0)