-
Notifications
You must be signed in to change notification settings - Fork 9
/
Octoid.ObjCHeaderTranslator.pas
1966 lines (1836 loc) · 64.8 KB
/
Octoid.ObjCHeaderTranslator.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
unit Octoid.ObjCHeaderTranslator;
// Based on this unit:
// https://github.com/neslib/Chet/blob/master/Classes/Chet.HeaderTranslator.pas
// The author Erik van Bilsen has indicated that users are free to do whatever they like with his work as long as he is not held accountable :-)
interface
uses
System.SysUtils, System.Classes, System.Types, System.Generics.Collections, System.Generics.Defaults,
Neslib.Clang,
Octoid.CustomTranslator;
type
TParamTypeNames = TStringDynArray;
TCursorArray = TArray<TCursor>;
TDelphiMethod = record
DeclarationFormat: string;
Deprecation: string;
Index: Integer;
IsAvailable: Boolean;
IsMismatched: Boolean;
IsOverload: Boolean;
MethodName: string; // Delphi
MethodNamePartsCount: Integer;
ObjCMethodName: string; // Fully qualified
ObjCMethodNameParts: TArray<string>;
ParamTypeNames: TParamTypeNames; // Type names of parameters of the method
ResultTypeName: string;
function GetDeclaration: string;
function Equals(const AMethod: TDelphiMethod): Boolean;
procedure ExpandMethodName;
procedure ExpandObjCMethodName;
function IsNameMismatched: Boolean;
function IsSame(const AMethod: TDelphiMethod): Boolean;
end;
TDelphiMethods = class(TList<TDelphiMethod>)
private
class var FComparer: IComparer<TDelphiMethod>;
public
function AddMethod(AMethod: TDelphiMethod): Integer;
function HasMethod(const AMethod: TDelphiMethod): Boolean;
function MethodExists(const AIndex: Integer): Boolean;
function ResolveCollisions(const AMethod: TDelphiMethod): Boolean;
procedure ResolveMethods;
procedure ResolveOverloads(const AIndex: Integer);
end;
TBlockMethod = record
Declaration: string; // e.g. TMTLDeviceCompletionHandler1 = procedure(Param1: NSUInteger) of object;
ObjCClassName: string; // e.g. MTLDevice
ObjCMethodName: string; // if the declaration applies to a method result type
ObjCMethodNameParts: TArray<string>;
TypeName: string; // e.g. TMTLDeviceBlockMethod1, so this can be used when the method declaration in the class is emitted
procedure ExpandObjCMethodName;
end;
TBlockMethods = class(TList<TBlockMethod>)
private
class var FComparer: IComparer<TBlockMethod>;
public
function AddBlockMethod(const AClassName, ADeclaration: string; const AMethodName: string = ''): Integer;
function ClassBlockMethodCount(const AClassName: string): Integer;
function FindMethod(const AClassName, ADeclaration: string; out AMethod: TBlockMethod; const AMethodName: string = ''): Integer;
procedure SortMethods;
end;
TObjCTranslateOption = (UnsupportedConstTypeComments, DeprecationComments, DeprecationCommentFirst, TodoComments);
TObjCTranslateOptions = set of TObjCTranslateOption;
TObjCTranslateOptionsHelper = record helper for TObjCTranslateOptions
function WantDeprecationComments: Boolean;
function WantDeprecationCommentFirst: Boolean;
function WantDeprecationCommentSameLine: Boolean;
end;
TObjCHeaderProject = class(TCustomTranslatorProject)
private
FClangIncludePath: string;
FFrameworkDirectory: string;
FFrameworkRoot: string;
FIgnoreUmbrellaHeader: Boolean;
FIncludeSubdirectories: Boolean;
FObjCTranslateOptions: TObjCTranslateOptions;
FOutputPath: string;
FSdkRoot: string;
FTargetPlatform: string;
function GetFrameworkName: string;
function GetLibraryPath: string;
procedure SetSdkRoot(const Value: string);
procedure SetTargetPlatform(const Value: string);
protected
function GetLibraryConstant: string; override;
function GetLibraryConstantDeclaration: string; override;
property FrameworkRoot: string read FFrameworkRoot;
public
property ClangIncludePath: string read FClangIncludePath write FClangIncludePath;
property FrameworkName: string read GetFrameworkName;
property FrameworkDirectory: string read FFrameworkDirectory write FFrameworkDirectory;
property IgnoreUmbrellaHeader: Boolean read FIgnoreUmbrellaHeader write FIgnoreUmbrellaHeader;
property IncludeSubdirectories: Boolean read FIncludeSubdirectories write FIncludeSubdirectories;
property OutputPath: string read FOutputPath write FOutputPath;
property ObjCTranslateOptions: TObjCTranslateOptions read FObjCTranslateOptions write FObjCTranslateOptions;
property SdkRoot: string read FSdkRoot write SetSdkRoot;
property TargetPlatform: string read FTargetPlatform write SetTargetPlatform;
end;
TObjCHeaderTranslator = class(TCustomTranslator)
private
const cExportedConstTypeNames: array[0..3] of string = ('NSString', 'Integer', 'Pointer', 'Double');
private
FBlockMethods: TBlockMethods;
FCategories: TList<TCursor>;
FClasses: TList<TCursor>;
FCombinedHeaderFileName: string;
FExportedConsts: TList<TCursor>;
FIncludedFrameworks: TStrings;
FInterfaceUnits: TStrings;
FMethods: TDelphiMethods;
FNeedsMacapiHelpers: Boolean;
FProject: TObjCHeaderProject;
procedure CheckTypeMaps(const ACursor: TCursor);
procedure CheckTypeUnitMap(const ATypeName: string);
function CreateCombinedHeaderFile: Boolean;
procedure DiscoverBlockMethods(const ACursor: TCursor; const AClassName: string = '');
procedure DiscoverBlockMethodParams(const ACursor: TCursor; const AClassName: string);
function GetBlockMethodDeclaration(const ACursor: TCursor; const AClassName: string): string;
function GetBlockMethodTypeDeclaration(const AType: TType): string;
function GetCategoryClassName(const ACursor: TCursor): string;
function GetClassCategories(const AClassName: string): TCursorArray;
function GetDelphiMethod(const ACursor: TCursor; const AClassName: string; const AIsClassMethod: Boolean; const AIsClass: Boolean): TDelphiMethod;
procedure GetDelphiMethodChildren(const ACursor: TCursor; const ABuilder: TStringBuilder; const AClassName: string; const AIsClass: Boolean;
var AMethod: TDelphiMethod);
function GetIsAvailable(const ASource: string): Boolean;
// function HasObjCClassRef(const ACursor: TCursor): Boolean;
function IsPlatformIOS: Boolean;
function IsPlatformMacOS: Boolean;
function IsSupportedDefinedConst(const ACursor: TCursor): Boolean;
function IsSupportedExportedConst(const AType: TType): Boolean;
procedure WriteDelphiMethods;
procedure WriteExportedConstCGFloat(const AConstName: string);
procedure WriteExportedConstFunctions;
procedure WriteExportedConstProtos;
procedure WriteInterfaceType(const ACursor: TCursor);
function WriteInterfaceClassType(const ACursor: TCursor): Boolean;
procedure WriteInterfaceDeclarationHeader(const AClassName, AClassRef: string; const AIsClass: Boolean);
procedure WriteInterfaceInstanceType(const ACursor: TCursor);
protected
function CanIncludeCursor(const ACursor: TCursor): Boolean; override;
function CanWriteToDo: Boolean; override;
procedure DoPrepare; override;
procedure DoSetupTypeMap; override;
procedure DoSetupTypeUnitMap; override;
function GenerateAnonymousTypeName(const AName: string): string; override;
function GetBinaryOperatorTokens(const ASource: string): TArray<string>; override;
function GetDelphiTypeName(AType: TType; const AInParamDecl: Boolean = False; const AOutIsAnonymous: PBoolean = nil): string; override;
function GetUnexposedType(const AType: TType): string; override;
function HandleTypeDeclaration(const ACursor: TCursor): Boolean; override;
function HandleTypeDefinition(const ACursor: TCursor): Boolean; override;
procedure HandleWriteType(const ACursor: TCursor); override;
function IsAnonymous(const AName: string): Boolean; override;
function IsConstIdentifier(const AName: string): Boolean; override;
procedure ProcessErrors(const AErrors: TArray<string>);
function Translate: ITranslationUnit; override;
function RemoveQualifiers(const ATypeName: string): string; override;
procedure SetupTokenMap; override;
procedure WriteClasses; override;
procedure WriteEnumTypeDecl(const ACursor: TCursor); override;
procedure WriteForwardClasses; override;
procedure WriteImplementationContent; override;
procedure WriteImplementationUsesClause; override;
procedure WriteInterfaceUsesClause; override;
public
constructor Create(const AProject: TCustomTranslatorProject); override;
destructor Destroy; override;
end;
implementation
uses
System.IOUtils, System.StrUtils, System.Character,
Neslib.Clang.Api,
Octoid.Consts;
type
TParamTypeNamesHelper = record helper for TParamTypeNames
public
procedure Add(const AParamType: string);
procedure Clear;
function Count: Integer;
function Equals(const AParamTypeNames: TParamTypeNames): Boolean;
end;
TCursorArrayHelper = record helper for TCursorArray
public
procedure Add(const ACursor: TCursor);
end;
TDelphiMethodComparerByMethodName = class (TInterfacedObject, IComparer<TDelphiMethod>)
protected
{ IComparer<T> }
function Compare(const Left, Right: TDelphiMethod): Integer;
end;
TBlockMethodComparerByTypeName = class (TInterfacedObject, IComparer<TBlockMethod>)
protected
{ IComparer<T> }
function Compare(const Left, Right: TBlockMethod): Integer;
end;
const
cCombinedHeaderFileName = '_combinedheaders_.h';
{ TObjCTranslateOptionsHelper }
function TObjCTranslateOptionsHelper.WantDeprecationCommentFirst: Boolean;
begin
Result := WantDeprecationComments and (TObjCTranslateOption.DeprecationCommentFirst in Self);
end;
function TObjCTranslateOptionsHelper.WantDeprecationComments: Boolean;
begin
Result := TObjCTranslateOption.DeprecationComments in Self;
end;
function TObjCTranslateOptionsHelper.WantDeprecationCommentSameLine: Boolean;
begin
Result := WantDeprecationComments and not (TObjCTranslateOption.DeprecationCommentFirst in Self);
end;
{ TParamTypeNamesHelper }
procedure TParamTypeNamesHelper.Add(const AParamType: string);
begin
SetLength(Self, Count + 1);
Self[Count - 1] := AParamType;
end;
procedure TParamTypeNamesHelper.Clear;
begin
SetLength(Self, 0);
end;
function TParamTypeNamesHelper.Count: Integer;
begin
Result := Length(Self);
end;
function TParamTypeNamesHelper.Equals(const AParamTypeNames: TParamTypeNames): Boolean;
var
I: Integer;
begin
Result := False;
if Count = AParamTypeNames.Count then
begin
for I := 0 to Count - 1 do
begin
if not Self[I].Equals(AParamTypeNames[I]) then
Exit(False); // <======
end;
Result := True;
end;
end;
{ TCursorArrayHelper }
procedure TCursorArrayHelper.Add(const ACursor: TCursor);
begin
SetLength(Self, Length(Self) + 1);
Self[Length(Self) - 1] := ACursor;
end;
{ TDelphiMethodComparerByMethodName }
function TDelphiMethodComparerByMethodName.Compare(const Left, Right: TDelphiMethod): Integer;
begin
Result := string.CompareText(Left.MethodName, Right.MethodName);
end;
{ TBlockMethodComparerByTypeName }
function TBlockMethodComparerByTypeName.Compare(const Left, Right: TBlockMethod): Integer;
begin
Result := string.CompareText(Left.TypeName, Right.TypeName);
end;
{ TDelphiMethod }
function TDelphiMethod.Equals(const AMethod: TDelphiMethod): Boolean;
begin
Result := (Index <> AMethod.Index) and AMethod.MethodName.Equals(MethodName) and AMethod.ParamTypeNames.Equals(ParamTypeNames);
end;
procedure TDelphiMethod.ExpandMethodName;
var
I: Integer;
LPart: string;
begin
if (Length(ObjCMethodNameParts) > 1) and (MethodNamePartsCount < Length(ObjCMethodNameParts) - 1) then
begin
Inc(MethodNamePartsCount);
MethodName := ObjCMethodNameParts[0];
for I := 1 to MethodNamePartsCount do
begin
LPart := ObjCMethodNameParts[I];
if not LPart.IsEmpty then
MethodName := MethodName + UpCase(ObjCMethodNameParts[I].Chars[0]) + ObjCMethodNameParts[I].Substring(1);
end;
end;
end;
procedure TDelphiMethod.ExpandObjCMethodName;
begin
ObjCMethodNameParts := ObjCMethodName.Split([':']);
end;
function TDelphiMethod.GetDeclaration: string;
begin
Result := Format(DeclarationFormat, [MethodName]);
end;
function TDelphiMethod.IsNameMismatched: Boolean;
var
LMethodName: string;
begin
LMethodName := MethodName;
// Ignore escaping
if LMethodName.StartsWith('&') then
LMethodName := LMethodName.Substring(1);
Result := IsMismatched or ((Length(ObjCMethodNameParts) > 0) and not LMethodName.Equals(ObjCMethodNameParts[0]));
end;
function TDelphiMethod.IsSame(const AMethod: TDelphiMethod): Boolean;
begin
Result := AMethod.ObjCMethodName.Equals(ObjCMethodName);
end;
{ TBlockMethod }
procedure TBlockMethod.ExpandObjCMethodName;
begin
ObjCMethodNameParts := ObjCMethodName.Split([':']);
end;
{ TDelphiMethods }
function TDelphiMethods.AddMethod(AMethod: TDelphiMethod): Integer;
begin
if AMethod.IsAvailable and not HasMethod(AMethod) then
begin
AMethod.ExpandObjCMethodName;
AMethod.Index := Count;
Result := Add(AMethod);
end
else
Result := -1;
end;
function TDelphiMethods.HasMethod(const AMethod: TDelphiMethod): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to Count - 1 do
begin
if Items[I].IsSame(AMethod) then
begin
Result := True;
Break;
end;
end;
end;
function TDelphiMethods.MethodExists(const AIndex: Integer): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to Count - 1 do
begin
if (AIndex <> I) and Items[I].Equals(Items[AIndex]) then
begin
Result := True;
Break;
end;
end;
end;
procedure TDelphiMethods.ResolveMethods;
var
I: Integer;
LHasCollisions: Boolean;
begin
// Resolve collisions
repeat
LHasCollisions := False;
for I := 0 to Count - 1 do
begin
if MethodExists(I) then
begin
if ResolveCollisions(Items[I]) then
LHasCollisions := True;
end;
end;
until not LHasCollisions;
// Resolve overloads
for I := 0 to Count - 1 do
ResolveOverloads(I);
if FComparer = nil then
FComparer := TDelphiMethodComparerByMethodName.Create;
Sort(FComparer);
end;
function TDelphiMethods.ResolveCollisions(const AMethod: TDelphiMethod): Boolean;
var
I: Integer;
LMethod: TDelphiMethod;
begin
Result := False;
for I := 0 to Count - 1 do
begin
LMethod := Items[I];
if LMethod.Equals(AMethod) then
begin
LMethod.ExpandMethodName;
Result := True;
Items[I] := LMethod;
end;
end;
end;
procedure TDelphiMethods.ResolveOverloads(const AIndex: Integer);
var
I: Integer;
LMethod: TDelphiMethod;
begin
for I := 0 to Count - 1 do
begin
LMethod := Items[I];
if (I <> AIndex) and LMethod.MethodName.Equals(Items[AIndex].MethodName) then
begin
LMethod.IsOverload := True;
Items[I] := LMethod;
end;
end;
end;
{ TBlockMethods }
function TBlockMethods.AddBlockMethod(const AClassName, ADeclaration: string; const AMethodName: string = ''): Integer;
var
LBlockMethod: TBlockMethod;
begin
Result := FindMethod(AClassName, ADeclaration, LBlockMethod, AMethodName);
if Result = -1 then
begin
LBlockMethod.ObjCClassName := AClassName;
LBlockMethod.ObjCMethodName := AMethodName;
LBlockMethod.ExpandObjCMethodName;
LBlockMethod.TypeName := Format('T%sBlockMethod%d', [AClassName, ClassBlockMethodCount(AClassName) + 1]); // e.g. TMTLDeviceBlockMethod1
LBlockMethod.Declaration := ADeclaration;
Add(LBlockMethod);
Result := Count - 1;
end;
end;
function TBlockMethods.ClassBlockMethodCount(const AClassName: string): Integer;
var
LMethod: TBlockMethod;
begin
Result := 0;
for LMethod in Self do
begin
if LMethod.ObjCClassName.Equals(AClassName) then
Inc(Result);
end;
end;
function TBlockMethods.FindMethod(const AClassName, ADeclaration: string; out AMethod: TBlockMethod; const AMethodName: string = ''): Integer;
var
I: Integer;
LMethod: TBlockMethod;
begin
for I := 0 to Count - 1 do
begin
LMethod := Items[I];
if LMethod.ObjCClassName.Equals(AClassName) then
begin
if (AMethodName.IsEmpty and LMethod.Declaration.Equals(ADeclaration))
or (not AMethodName.IsEmpty and LMethod.ObjCMethodName.Equals(AMethodName)) then
begin
AMethod := LMethod;
Exit(I); // <======
end;
end;
end;
Result := -1;
end;
procedure TBlockMethods.SortMethods;
begin
if FComparer = nil then
FComparer := TBlockMethodComparerByTypeName.Create;
Sort(FComparer);
end;
{ TObjCHeaderProject }
function TObjCHeaderProject.GetFrameworkName: string;
begin
Result := TPath.GetFileNameWithoutExtension(FFrameworkDirectory);
end;
function TObjCHeaderProject.GetLibraryConstant: string;
begin
Result := 'lib' + GetFrameworkName;
end;
function TObjCHeaderProject.GetLibraryConstantDeclaration: string;
begin
Result := Format('%s = ''%s'';', [GetLibraryConstant, GetLibraryPath]);
end;
function TObjCHeaderProject.GetLibraryPath: string;
begin
Result := TPath.Combine(FFrameworkDirectory, GetFrameworkName);
Result := Copy(Result, Length(FSdkRoot) + 1, Length(Result));
Result := StringReplace(Result, '\', '/', [rfReplaceAll]);
end;
procedure TObjCHeaderProject.SetSdkRoot(const Value: string);
begin
FSdkRoot := Value;
FFrameworkRoot := TPath.Combine(FSdkRoot, cSDKFrameworksFolder);
end;
procedure TObjCHeaderProject.SetTargetPlatform(const Value: string);
begin
FTargetPlatform := Value.ToUpper;
end;
{ TObjCHeaderTranslator }
constructor TObjCHeaderTranslator.Create(const AProject: TCustomTranslatorProject);
begin
inherited;
FProject := TObjCHeaderProject(AProject);
FIncludedFrameworks := TStringList.Create;
FInterfaceUnits := TStringList.Create;
FBlockMethods := TBlockMethods.Create;
FMethods := TDelphiMethods.Create;
FClasses := TList<TCursor>.Create;
FCategories := TList<TCursor>.Create;
FExportedConsts := TList<TCursor>.Create;
end;
destructor TObjCHeaderTranslator.Destroy;
begin
FIncludedFrameworks.Free;
FInterfaceUnits.Free;
FBlockMethods.Free;
FMethods.Free;
FClasses.Free;
FCategories.Free;
FExportedConsts.Free;
inherited;
end;
procedure TObjCHeaderTranslator.DoPrepare;
begin
FNeedsMacapiHelpers := False;
FClasses.Clear;
FExportedConsts.Clear;
FBlockMethods.Clear;
FIncludedFrameworks.Clear;
FInterfaceUnits.Clear;
end;
procedure TObjCHeaderTranslator.SetupTokenMap;
begin
inherited;
{ C-to-Delphi translations for common tokens.
These are only used when manually converting #define macros. }
{ Surround with spaces to avoid concatenation with other tokens. }
TokenMap.Add('<<', ' shl ');
TokenMap.Add('>>', ' shr ');
TokenMap.Add('&', ' and ');
TokenMap.Add('|', ' or ');
TokenMap.Add('^', ' xor ');
TokenMap.Add('~', ' not ');
TokenMap.Add('&&', ' and ');
TokenMap.Add('||', ' or ');
TokenMap.Add('!', ' not ');
TokenMap.Add('%', ' mod ');
TokenMap.Add('==', '=');
TokenMap.Add('!=', '<>');
end;
procedure TObjCHeaderTranslator.DoSetupTypeMap;
begin
TypeMap.Add('size_t', 'NativeUInt');
TypeMap.Add('intptr_t', 'IntPtr');
TypeMap.Add('uintptr_t', 'UIntPtr');
TypeMap.Add('ptrdiff_t', 'NativeInt');
TypeMap.Add('wchar_t', 'WideChar');
TypeMap.Add('time_t', 'Longint');
// From stdint.h
TypeMap.Add('int8_t', 'Int8');
TypeMap.Add('int16_t', 'Int16');
TypeMap.Add('int32_t', 'Int32');
TypeMap.Add('int64_t', 'Int64');
TypeMap.Add('uint8_t', 'UInt8');
TypeMap.Add('uint16_t', 'UInt16');
TypeMap.Add('uint32_t', 'UInt32');
TypeMap.Add('uint64_t', 'UInt64');
TypeMap.Add('int_least8_t', 'Int8');
TypeMap.Add('int_least16_t', 'Int16');
TypeMap.Add('int_least32_t', 'Int32');
TypeMap.Add('int_least64_t', 'Int64');
TypeMap.Add('uint_least8_t', 'UInt8');
TypeMap.Add('uint_least16_t', 'UInt16');
TypeMap.Add('uint_least32_t', 'UInt32');
TypeMap.Add('uint_least64_t', 'UInt64');
TypeMap.Add('int_fast8_t', 'Int8');
TypeMap.Add('int_fast16_t', 'Int32');
TypeMap.Add('int_fast32_t', 'Int32');
TypeMap.Add('int_fast64_t', 'Int64');
TypeMap.Add('uint_fast8_t', 'UInt8');
TypeMap.Add('uint_fast16_t', 'UInt32');
TypeMap.Add('uint_fast32_t', 'UInt32');
TypeMap.Add('uint_fast64_t', 'UInt64');
TypeMap.Add('intmax_t', 'Int64');
TypeMap.Add('uintmax_t', 'UInt64');
// C functions can have a parameter of type "va_list", containing a variable
// number of arguments. We cannot really use these functions in Delphi (but
// we CAN use "varargs" functions). We set the "va_list" type to a pointer,
// but should probably ignore functions that use it.
TypeMap.Add('va_list', 'Pointer');
// Type FILE the cannot be used in Delphi, so we convert to a Pointer.
TypeMap.Add('FILE', 'Pointer');
TypeMap.Add('ULONG', 'UInt32');
TypeMap.Add('LPVOID', 'Pointer');
TypeMap.Add('Class', 'Pointer');
TypeMap.Add('Protocol', 'Pointer');
TypeMap.Add('BOOL', 'Boolean');
TypeMap.Add('PBOOL', 'PBoolean');
TypeMap.Add('id', 'Pointer');
TypeMap.Add('instancetype', 'Pointer');
// Unexposed types
TypeMap.Add('ObjectType', 'Pointer');
TypeMap.Add('ValueType', 'Pointer');
end;
procedure TObjCHeaderTranslator.DoSetupTypeUnitMap;
begin
TypeUnitMap.Add('id', 'Macapi.ObjCRuntime');
TypeUnitMap.Add('dispatch_queue_t', 'Macapi.Dispatch');
TypeUnitMap.Add('CGSize', 'Macapi.CocoaTypes|iOSapi.CoreGraphics');
end;
function TObjCHeaderTranslator.GenerateAnonymousTypeName(const AName: string): string;
begin
Result := ''; // Todo?
end;
function TObjCHeaderTranslator.GetCategoryClassName(const ACursor: TCursor): string;
var
LClassName: string;
begin
LClassName := '';
ACursor.VisitChildren(
function(const ACursor, AParent: TCursor): TChildVisitResult
begin
if ACursor.Kind = TCursorKind.ObjCClassRef then
begin
LClassName := ACursor.Spelling;
Result := TChildVisitResult.Break;
end
else
Result := TChildVisitResult.Continue;
end
);
Result := LClassName;
end;
function TObjCHeaderTranslator.GetClassCategories(const AClassName: string): TCursorArray;
var
LCursor: TCursor;
begin
for LCursor in FCategories do
begin
if GetCategoryClassName(LCursor).Equals(AClassName) then
Result.Add(LCursor);
end;
end;
function TObjCHeaderTranslator.CanWriteToDo: Boolean;
begin
Result := TObjCTranslateOption.TodoComments in FProject.ObjCTranslateOptions;
end;
procedure TObjCHeaderTranslator.CheckTypeMaps(const ACursor: TCursor);
var
LTypeName: string;
begin
case ACursor.Kind of
TCursorKind.ParmDecl, TCursorKind.FieldDecl:
begin
LTypeName := GetDelphiTypeName(ACursor.CursorType, True);
CheckTypeUnitMap(LTypeName);
end;
end;
end;
procedure TObjCHeaderTranslator.CheckTypeUnitMap(const ATypeName: string);
var
LUnitName: string;
LParts: TArray<string>;
begin
if TypeUnitMap.TryGetValue(ATypeName, LUnitName) then
begin
LParts := LUnitName.Split(['|']);
if Length(LParts) > 1 then
begin
if SameText(FProject.TargetPlatform, cTargetPlatformMacOS) then
LUnitName := LParts[0]
else
LUnitName := LParts[1];
end;
if FInterfaceUnits.IndexOf(LUnitName) = -1 then
FInterfaceUnits.Add(LUnitName);
end;
end;
procedure TObjCHeaderTranslator.DiscoverBlockMethodParams(const ACursor: TCursor; const AClassName: string);
var
LMethodName: string;
LClassName: string;
LIsProperty: Boolean;
begin
LMethodName := ACursor.Spelling;
LClassName := AClassName;
LIsProperty := ACursor.Kind = TCursorKind.ObjCPropertyDecl;
// Has a block pointer as a result type, so add that block method
if not LIsProperty and (ACursor.ResultType.Kind = TTypeKind.BlockPointer) then
FBlockMethods.AddBlockMethod(AClassName, GetBlockMethodTypeDeclaration(ACursor.ResultType.PointeeType), LMethodName)
// else if LIsProperty and (ACursor.CursorType.Kind = TTypeKind.BlockPointer) then
// // This is to allow property declarations (ObjCPropertyDecl) to determine block method defs
// FBlockMethods.AddBlockMethod(AClassName, GetBlockMethodDeclaration(ACursor, AClassName), LMethodName);
else if LIsProperty then
Exit;
// Discover block methods in parameters for this method
ACursor.VisitChildren(
function(const ACursor, AParent: TCursor): TChildVisitResult
begin
if ACursor.Kind = TCursorKind.ParmDecl then
begin
if ACursor.CursorType.Kind = TTypeKind.BlockPointer then
FBlockMethods.AddBlockMethod(AClassName, GetBlockMethodDeclaration(ACursor, AClassName));
end;
Result := TChildVisitResult.Continue;
end
);
end;
procedure TObjCHeaderTranslator.DiscoverBlockMethods(const ACursor: TCursor; const AClassName: string = '');
var
LStructName: string;
LIsAnonymousStruct: Boolean;
begin
if AClassName.IsEmpty then
begin
case ACursor.Kind of
TCursorKind.ObjCInterfaceDecl:
LStructName := GetDelphiTypeName(ACursor.CursorType, False, @LIsAnonymousStruct);
TCursorKind.ObjCCategoryDecl:
LStructName := GetCategoryClassName(ACursor);
else
LStructName := ACursor.Spelling;
end;
end
else
LStructName := AClassName;
ACursor.VisitChildren(
function(const ACursor, AParent: TCursor): TChildVisitResult
begin
case ACursor.Kind of
TCursorKind.ObjCClassMethodDecl, TCursorKind.ObjCInstanceMethodDecl, TCursorKind.ObjCPropertyDecl:
begin
DiscoverBlockMethodParams(ACursor, LStructName);
end;
end;
Result := TChildVisitResult.Continue;
end
);
end;
function TObjCHeaderTranslator.HandleTypeDeclaration(const ACursor: TCursor): Boolean;
begin
Result := True;
case ACursor.Kind of
TCursorKind.ObjCInterfaceDecl:
begin
FClasses.Add(ACursor);
// Methods need to be iterated to determine if there are any unnamed block method types
// Each type is added to a separate list which is emitted after the regular types, but before the protocols and classes
DiscoverBlockMethods(ACursor);
end;
TCursorKind.ObjCCategoryDecl:
begin
FCategories.Add(ACursor);
// Methods need to be iterated to determine if there are any unnamed block method types
// Each type is added to a separate list which is emitted after the regular types, but before the protocols and classes
DiscoverBlockMethods(ACursor);
end;
TCursorKind.EnumDecl:
begin
Types.Add(ACursor);
end;
// Includes exported consts
TCursorKind.VarDecl:
begin
FExportedConsts.Add(ACursor);
end;
else
Result := False;
end;
end;
function TObjCHeaderTranslator.HandleTypeDefinition(const ACursor: TCursor): Boolean;
begin
Result := True;
case ACursor.Kind of
TCursorKind.ObjCProtocolDecl:
begin
FClasses.Add(ACursor);
DiscoverBlockMethods(ACursor);
end;
else
Result := False;
end;
end;
procedure TObjCHeaderTranslator.HandleWriteType(const ACursor: TCursor);
begin
case ACursor.Kind of
TCursorKind.ObjCInterfaceDecl:
WriteInterfaceType(ACursor);
TCursorKind.ObjCProtocolDecl:
// For now, WriteInterfaceClassType will also handle protocol declarations
WriteInterfaceClassType(ACursor);
end;
end;
function TObjCHeaderTranslator.GetBlockMethodTypeDeclaration(const AType: TType): string;
var
LHasResult: Boolean;
LArgument, LTypeName: string;
LBuilder: TStringBuilder;
I: Integer;
begin
LHasResult := not (AType.ResultType.Kind in [TTypeKind.Invalid, TTypeKind.Void]);
LBuilder := TStringBuilder.Create;
try
if LHasResult then
LBuilder.Append('function')
else
LBuilder.Append('procedure');
if AType.ArgTypeCount > 0 then
LBuilder.Append('(');
for I := 0 to AType.ArgTypeCount - 1 do
begin
LTypeName := GetDelphiTypeName(AType.ArgTypes[I], True);
LArgument := Format('param%d: %s', [I + 1, LTypeName]);
LBuilder.Append(LArgument);
if I < AType.ArgTypeCount - 1 then
LBuilder.Append('; ');
end;
if AType.ArgTypeCount > 0 then
LBuilder.Append(')');
// Add the result type, if it's a function
if LHasResult then
begin
LBuilder.Append(': ');
LBuilder.Append(GetDelphiTypeName(AType.ResultType));
end;
LBuilder.Append(' of object;');
Result := LBuilder.ToString;
finally
LBuilder.Free;
end;
end;
function TObjCHeaderTranslator.GetBinaryOperatorTokens(const ASource: string): TArray<string>;
const
cBinaryOperators: array[0..7] of string = ('<<', '>>', '&&', '||', '%', '^', '|', '&'); // *** Put double character operators first! ***
var
LOperator, LSource, LToken: string;
I, LCount: Integer;
begin
SetLength(Result, 0);
LSource := ASource;
LCount := 0;
I := 0;
while not LSource.IsEmpty and (I < Length(LSource)) do
begin
for LOperator in cBinaryOperators do
begin
LToken := LSource.Substring(I, Length(LOperator));
if LToken.Equals(LOperator) then
begin
Inc(LCount, 2);
SetLength(Result, LCount);
Result[LCount - 2] := LSource.Substring(0, I).Trim;
Result[LCount - 1] := LToken.Trim;
LSource := LSource.Substring(I + Length(LToken));
I := -1;
Break;
end;
//
end;
Inc(I);
end;
if not LSource.IsEmpty then
begin
SetLength(Result, LCount + 1);
Result[LCount] := LSource.Trim;
end;
end;
function TObjCHeaderTranslator.GetBlockMethodDeclaration(const ACursor: TCursor; const AClassName: string): string;
var
LHasResult: Boolean;
LArgCount, LArgIndex: Integer;
LPointeeType: TType;
LBuilder: TStringBuilder;
LMethodName, LSpelling: string;
LHasArgs: Boolean;
begin
LMethodName := ACursor.Spelling;
IsProceduralType(ACursor.CursorType, LPointeeType);
LHasResult := not (ACursor.ResultType.Kind in [TTypeKind.Invalid, TTypeKind.Void]);
LBuilder := TStringBuilder.Create;
try
if LHasResult then
LBuilder.Append('function')
else
LBuilder.Append('procedure');
LArgCount := LPointeeType.ArgTypeCount;
LHasArgs := False;
// Pre-check
ACursor.VisitChildren(
function(const ACursor, AParent: TCursor): TChildVisitResult
begin
if ACursor.Kind = TCursorKind.ParmDecl then
begin
LHasArgs := True;
Result := TChildVisitResult.Break;
end
else
Result := TChildVisitResult.Continue;
end
);
if LHasArgs then
begin
LBuilder.Append('(');
LArgIndex := 0;
ACursor.VisitChildren(
function(const ACursor, AParent: TCursor): TChildVisitResult
var
LArgName, LTypeName: string;
LIndex: Integer;
begin
LSpelling := ACursor.Spelling;
if ACursor.Kind = TCursorKind.ParmDecl then
begin
LArgName := GetValidIdentifier(ACursor.Spelling);
if LArgName = '' then
LArgName := 'param' + (LArgIndex + 1).ToString;
LTypeName := 'Unknown';
case ACursor.CursorType.Kind of
TTypeKind.BlockPointer:
begin
LIndex := FBlockMethods.AddBlockMethod(AClassName, GetBlockMethodTypeDeclaration(ACursor.ResultType.PointeeType), ACursor.Spelling);
if LIndex > -1 then
LTypeName := FBlockMethods.Items[LIndex].TypeName;
end;
else
LTypeName := GetDelphiTypeName(ACursor.CursorType, True);
end;
LBuilder.Append(LArgName + ': ' + LTypeName);