-
Notifications
You must be signed in to change notification settings - Fork 591
/
Copy pathParser.java
4817 lines (4661 loc) · 232 KB
/
Parser.java
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
/*
* Copyright (C) 2013-2023 Samuel Audet
*
* Licensed either under the Apache License, Version 2.0, or (at your option)
* under the terms of the GNU General Public License as published by
* the Free Software Foundation (subject to the "Classpath" exception),
* either version 2, or any later version (collectively, the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.gnu.org/licenses/
* http://www.gnu.org/software/classpath/license.html
*
* or as provided in the LICENSE.txt file that accompanied this code.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bytedeco.javacpp.tools;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bytedeco.javacpp.ClassProperties;
import org.bytedeco.javacpp.Loader;
/**
* The Parser, just like the Generator, is a mess that is not meant to support the
* entirety of C++, but an appropriate subset as used by typical C/C++ header files.
* To figure out what that subset is and what the output should be, the idea is to
* apply it on as many C/C++ libraries as possible, and patch the code as we go.
* At one point in time, when this prototype code appears to have stabilized, we can
* start to redesign it in a more meaningful way.
* <p>
* That said, to understand how it is supposed to function in its present state,
* one can step through the code at runtime: It is quite friendly to debuggers.
* <p>
* Moreover, it relies on {@link Info} objects created as part of the execution
* of {@link InfoMapper#map(InfoMap)}. We can understand better how the parsing
* is supposed to get accomplished by studying that documentation as well.
* <p>
* To do:
* - Inherit constructors from helper classes, if possible
* - etc.
*
* @see Info
* @see InfoMap
* @see InfoMapper
*
* @author Samuel Audet
*/
public class Parser {
public Parser(Logger logger, Properties properties) {
this(logger, properties, null, null);
}
public Parser(Logger logger, Properties properties, String encoding, String lineSeparator) {
this.logger = logger;
this.properties = properties;
this.encoding = encoding;
this.lineSeparator = lineSeparator;
}
Parser(Parser p, String text) {
this.logger = p.logger;
this.properties = p.properties;
this.encoding = p.encoding;
this.infoMap = p.infoMap;
this.upcasts = p.upcasts;
Token t = p.tokens != null ? p.tokens.get() : Token.EOF;
this.tokens = new TokenIndexer(infoMap, new Tokenizer(text, t.file, t.lineNumber).tokenize(), false);
this.lineSeparator = p.lineSeparator;
}
final Logger logger;
final Properties properties;
final String encoding;
InfoMap infoMap = null;
InfoMap leafInfoMap = null;
TokenIndexer tokens = null;
String lineSeparator = null;
/** Java names of classes needing upcast from their subclasses. */
Set<String> upcasts = new HashSet<>();
/** Classes that have a base class appearing as a key in this map need a downcast constructor.
* The associated value gives the class to downcast from and whether the inheritance is virtual. */
Map<String, Map<Type, Boolean>> downcasts = new HashMap<>();
/** Java names of classes recognized as polymorphic. */
Set<String> polymorphicClasses = new HashSet<>();
private void addDowncast(String base, Type from, boolean virtual) {
Map<Type, Boolean> inheritance = downcasts.get(base);
if (inheritance == null) {
downcasts.put(base, inheritance = new HashMap<>(1));
}
inheritance.put(from, virtual);
}
static String removeAnnotations(String s) {
return s.substring(s.lastIndexOf(' ') + 1);
}
static String desugarVarargs(String s) {
return s.trim().endsWith("...") ? s.trim().substring(0, s.length() - 3) + "[]" : s;
}
static String upcastMethodName(String javaName) {
String shortName = javaName.substring(javaName.lastIndexOf('.') + 1);
return "as" + Character.toUpperCase(shortName.charAt(0)) + shortName.substring(1);
}
/**
* Constructors have 2 kinds of fully qualified name:
* the calling name of a constructor, used when calling the constructor, e.g.:
* NS::CN(int)
* and the declaration name, used when defining the constructor outside its class or when referencing a constructor
* with using to inherit constructors of base class.
* NS::CN::CN(int)
* Declarator.cppName contains the calling name, and this method returns the declaration name.
* Keys in info map should use the declaration name, because the calling name cannot specify
* arguments in case of constructor templates, and to avoid confusion between classes and constructores info.
*/
static String constructorName(String cppName) {
String constructorName = Templates.strip(cppName);
int namespace = constructorName.lastIndexOf("::");
if (namespace >= 0) {
constructorName = constructorName.substring(namespace + 2);
}
return cppName + "::" + constructorName;
}
String translate(String text) {
Info info = infoMap.getFirst(text);
if (info != null && info.javaNames != null && info.javaNames.length > 0) {
return info.javaNames[0];
}
int namespace = text.lastIndexOf("::");
if (namespace >= 0) {
Info info2 = infoMap.getFirst(text.substring(0, namespace));
String localName = text.substring(namespace + 2);
if (info2 != null && info2.pointerTypes != null) {
text = info2.pointerTypes[0] + "." + localName;
} else if (localName.length() > 0 && Character.isJavaIdentifierStart(localName.charAt(0))) {
for (char c : localName.toCharArray()) {
if (!Character.isJavaIdentifierPart(c)) {
localName = null;
break;
}
}
if (localName != null) {
text = localName;
}
}
}
int castStart = text.lastIndexOf('(');
int castEnd = text.indexOf(')', castStart);
if (castStart >= 0 && castStart < castEnd) {
Info info2 = infoMap.getFirst(text.substring(castStart + 1, castEnd));
if (info2 != null && info2.valueTypes != null && info2.valueTypes.length > 0) {
text = text.substring(0, castStart + 1) + info2.valueTypes[0] + text.substring(castEnd);
}
}
return text;
}
void containers(Context context, DeclarationList declList) throws ParserException {
List<String> basicContainers = new ArrayList<>();
for (Info info : infoMap.get("basic/containers")) {
basicContainers.addAll(Arrays.asList(info.cppTypes));
}
for (String containerName : basicContainers) {
LinkedHashSet<Info> infoSet = new LinkedHashSet<>();
infoSet.addAll(leafInfoMap.get("const " + containerName));
infoSet.addAll(leafInfoMap.get(containerName));
for (Info info : infoSet) {
Declaration decl = new Declaration();
if (info == null || info.skip || !info.define || !info.cppNames[0].contains(containerName)) {
if (info != null && info.javaText != null) {
decl.type = new Type(info.pointerTypes[0]);
decl.text = info.javaText;
declList.add(decl);
}
continue;
}
int dim = containerName.toLowerCase().endsWith("optional")
|| containerName.toLowerCase().endsWith("variant")
|| containerName.toLowerCase().endsWith("tuple")
|| containerName.toLowerCase().endsWith("function")
|| containerName.toLowerCase().endsWith("pair") ? 0 : 1;
boolean string = containerName.toLowerCase().endsWith("string");
boolean constant = info.cppNames[0].startsWith("const "), resizable = !constant;
Type containerType = new Parser(this, info.cppNames[0]).type(context),
indexType, valueType, firstType = null, secondType = null;
if (containerType.arguments == null || containerType.arguments.length == 0 || containerType.arguments[0] == null
|| containerType.arguments[containerType.arguments.length - 1] == null) {
continue;
} else if (containerType.arguments.length > 1 && containerType.arguments[1].javaName.length() > 0) {
resizable = false;
indexType = containerType.arguments[0];
valueType = containerType.arguments[1];
} else {
resizable &= containerType.arguments.length == 1; // assume second argument is the fixed size
indexType = new Type();
indexType.value = true;
indexType.cppName = "size_t";
indexType.javaName = "long";
valueType = containerType.arguments[0];
}
String indexFunction = "(function = \"at\")";
String iteratorType = "iterator";
String keyVariable = "first";
String valueVariable = "second";
boolean dict = false;
boolean list = resizable; // also vector, etc
boolean tuple = false;
boolean function = false;
if (valueType.javaName == null || valueType.javaName.length() == 0
|| containerName.toLowerCase().endsWith("bitset")) {
indexFunction = "";
valueType.javaName = "boolean";
resizable = false;
} else if (containerName.toLowerCase().endsWith("dict")) {
indexFunction = "(function = \"operator []\")";
iteratorType = "Iterator";
keyVariable = "key()";
valueVariable = "value()";
dict = true;
} else if (containerName.toLowerCase().endsWith("list")
|| containerName.toLowerCase().endsWith("optional")
|| containerName.toLowerCase().endsWith("variant")
|| containerName.toLowerCase().endsWith("tuple")
|| containerName.toLowerCase().endsWith("function")
|| containerName.toLowerCase().endsWith("set")) {
if (containerType.arguments.length > 1) {
valueType = indexType;
}
indexType = null;
resizable = false;
list = containerName.toLowerCase().endsWith("list");
tuple = containerName.toLowerCase().endsWith("tuple");
function = containerName.toLowerCase().endsWith("function");
} else if (!constant && !resizable) {
indexFunction = ""; // maps need operator[] to be writable
}
while (valueType.cppName.startsWith(containerName)
&& leafInfoMap.get(valueType.cppName, false).size() == 0) {
// increase dimension, unless the user has provided info for the intermediate type
dim++;
valueType = valueType.arguments[0];
}
int valueTemplate = valueType.cppName.indexOf("<");
if (containerName.toLowerCase().endsWith("pair")) {
firstType = containerType.arguments[0];
secondType = containerType.arguments[1];
} else if (dim > 0 && valueTemplate >= 0 && valueType.cppName.substring(0, valueTemplate).toLowerCase().endsWith("pair")) {
firstType = valueType.arguments[0];
secondType = valueType.arguments[1];
}
if (function) {
int n = valueType.cppName.indexOf('(');
Info info2 = infoMap.getFirst(valueType.cppName, false);
if (info2 != null && info2.pointerTypes != null && info2.pointerTypes.length > 0) {
valueType.javaName = info2.pointerTypes[0];
valueType.javaNames = info2.pointerTypes;
} else {
valueType.javaName = "";
valueType.javaNames = null;
}
Declarator dcl = new Parser(this, "typedef " + valueType.cppName.substring(0, n)
+ "(*" + valueType.javaName + ")" + valueType.cppName.substring(n)).declarator(context, containerType.javaName, -1, false, 0, false, true);
valueType.javaName = dcl.type.javaName;
dcl.definition.text = "\n" + dcl.definition.text;
decl.declarator = dcl;
}
ArrayList<Type> types = new ArrayList<>(4 + containerType.arguments.length);
types.addAll(Arrays.asList(firstType, secondType, indexType, valueType));
types.addAll(Arrays.asList(containerType.arguments));
for (Type type : types) {
if (type == null) {
continue;
} else if (type.annotations == null || type.annotations.length() == 0) {
type.annotations = (type.constValue ? "@Const " : "") + (type.indirections == 0 && !type.value ? "@ByRef " : "");
}
Info info2 = infoMap.getFirst(type.cppName);
if (info2 != null && info2.cast && !type.annotations.contains("@Cast") && !type.javaName.contains("@Cast")) {
String cast = type.cppName;
if (type.constValue && !cast.startsWith("const ")) {
cast = "const " + cast;
}
if (type.indirections > 0) {
for (int i = 0; i < type.indirections; i++) {
cast += "*";
}
} else if (!type.value) {
cast += "*";
}
if (type.reference) {
cast += "&";
}
if (type.rvalue) {
cast += "&&";
}
if (type.constPointer && !cast.endsWith(" const")) {
cast = cast + " const";
}
type.annotations = "@Cast(\"" + cast + "\") " + type.annotations;
}
}
String arrayBrackets = "";
for (int i = 0; i < dim - 1; i++) {
arrayBrackets += "[]";
}
int annotation = containerType.javaName.lastIndexOf(' ');
containerType.annotations += containerType.javaName.substring(0, annotation + 1);
containerType.javaName = containerType.javaName.substring(annotation + 1); // get rid of any annotations
decl.type = new Type(containerType.javaName);
decl.text += (dim == 0 ? "\n@NoOffset " : "\n")
+ "@Name(\"" + containerType.cppName + "\") public static class " + containerType.javaName + " extends Pointer {\n"
+ " static { Loader.load(); }\n"
+ " /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */\n"
+ " public " + containerType.javaName + "(Pointer p) { super(p); }\n";
boolean purify = info != null && info.purify;
if (!constant && !purify && (dim == 0 || (containerType.arguments.length == 1 && indexType != null)) && firstType != null && secondType != null) {
String[] firstNames = firstType.javaNames != null ? firstType.javaNames : new String[] {firstType.javaName};
String[] secondNames = secondType.javaNames != null ? secondType.javaNames : new String[] {secondType.javaName};
String brackets = arrayBrackets + (dim > 0 ? "[]" : "");
for (int n = 0; n < firstNames.length || n < secondNames.length; n++) {
decl.text += " public " + containerType.javaName + "(" + firstNames[Math.min(n, firstNames.length - 1)] + brackets + " firstValue, "
+ secondNames[Math.min(n, secondNames.length - 1)] + brackets + " secondValue) "
+ "{ this(" + (dim > 0 ? "Math.min(firstValue.length, secondValue.length)" : "") + "); put(firstValue, secondValue); }\n";
}
} else if (resizable && !purify && firstType == null && secondType == null) {
for (String javaName : valueType.javaNames != null ? valueType.javaNames : new String[] {valueType.javaName}) {
if (dim < 2 && !javaName.equals("int") && !javaName.equals("long")) {
decl.text += " public " + containerType.javaName + "(" + javaName + " value) { this(1); put(0, value); }\n";
}
decl.text += " public " + containerType.javaName + "(" + javaName + arrayBrackets + " ... array) { this(array.length); put(array); }\n";
}
} else if (indexType == null && dim == 0 && !constant && !purify) {
int n = 0;
String valueNames = "", valueNames2 = "", separator = "";
for (Type type : containerType.arguments) {
if (tuple) {
valueNames += separator + type.annotations + type.javaName + " value" + n;
valueNames2 += separator + "value" + n;
separator = ", ";
n++;
} else for (String javaName : type.javaNames != null ? type.javaNames : new String[] {type.javaName}) {
// variant, optional, etc
if (!javaName.substring(javaName.indexOf(' ') + 1).equals("Pointer")) {
decl.text += " public " + containerType.javaName + "(" + javaName + " value) { this(); put(value); }\n";
}
}
}
if (tuple) {
decl.text += " public " + containerType.javaName + "(" + valueNames + ") { allocate(" + valueNames2 + "); }\n"
+ " private native void allocate(" + valueNames + ");\n";
}
}
if (!purify) {
String initArg = "", initParam = "";
if (string) {
initArg = ", (" + removeAnnotations(valueType.javaName) + ")0";
initParam = ", " + removeAnnotations(valueType.javaName) + " value";
}
decl.text += " public " + containerType.javaName + "() { allocate(); }\n" + (!resizable ? ""
: " public " + containerType.javaName + "(long n) { allocate(n" + initArg + "); }\n")
+ " private native void allocate();\n" + (!resizable ? ""
: " private native void allocate(@Cast(\"size_t\") long n" + initParam + ");\n") + (constant ? "\n\n"
: " public native @Name(\"operator =\") @ByRef " + containerType.javaName + " put(@ByRef " + containerType.annotations + containerType.javaName + " x);\n\n");
}
for (int i = 0; i < dim; i++) {
String indexAnnotation = i > 0 ? ("@Index(" + (i > 1 ? "value = " + i + ", " : "" ) + "function = \"at\") ") : "";
String indices = "", indices2 = "", separator = "";
for (int j = 0; indexType != null && j < i; j++) {
indices += separator + indexType.annotations + indexType.javaName + " " + (char)('i' + j);
indices2 += separator + (char)('i' + j);
separator = ", ";
}
decl.text += " public boolean empty(" + indices + ") { return size(" + indices2 + ") == 0; }\n"
+ " public native " + indexAnnotation + "long size(" + indices + ");\n" + (!resizable ? ""
: " public void clear(" + indices + ") { resize(" + indices2 + separator + "0); }\n"
+ " public native " + indexAnnotation + "void resize(" + indices + separator + "@Cast(\"size_t\") long n);\n");
}
String params = "", separator = "";
for (int i = 0; indexType != null && i < dim; i++) {
params += separator + indexType.annotations + indexType.javaName + " " + (char)('i' + i);
separator = ", ";
}
if ((dim == 0 || indexType != null) && firstType != null && secondType != null) {
String indexAnnotation = dim == 0 ? "@MemberGetter " : "@Index(" + (dim > 1 ? "value = " + dim + ", " : "") + "function = \"at\") ";
decl.text += "\n"
+ " " + indexAnnotation + "public native " + firstType.annotations + firstType.javaName + " first(" + params + ");"
+ " public native " + containerType.javaName + " first(" + params + separator + removeAnnotations(firstType.javaName) + " first);\n"
+ " " + indexAnnotation + "public native " + secondType.annotations + secondType.javaName + " second(" + params + "); "
+ " public native " + containerType.javaName + " second(" + params + separator + removeAnnotations(secondType.javaName) + " second);\n";
for (int i = 1; !constant && firstType.javaNames != null && i < firstType.javaNames.length; i++) {
decl.text += " @MemberSetter @Index" + indexFunction + " public native " + containerType.javaName + " first(" + params + separator + firstType.annotations + firstType.javaNames[i] + " first);\n";
}
for (int i = 1; !constant && secondType.javaNames != null && i < secondType.javaNames.length; i++) {
decl.text += " @MemberSetter @Index" + indexFunction + " public native " + containerType.javaName + " second(" + params + separator + secondType.annotations + secondType.javaNames[i] + " second);\n";
}
} else {
if (indexType != null) {
decl.text += "\n";
if (dim == 1 && indexType.javaName.equals("long")) {
decl.text += " public " + removeAnnotations(valueType.javaName) + " front() { return get(0); }\n"
+ " public " + removeAnnotations(valueType.javaName) + " back() { return get(size() - 1); }\n";
}
decl.text += " @Index" + indexFunction + " public native " + valueType.annotations + valueType.javaName + " get(" + params + ");\n";
if (!constant) {
decl.text += " public native " + containerType.javaName + " put(" + params + separator + removeAnnotations(valueType.javaName) + " value);\n";
}
for (int i = 1; !constant && valueType.javaNames != null && i < valueType.javaNames.length; i++) {
decl.text += " @ValueSetter @Index" + indexFunction + " public native " + containerType.javaName + " put(" + params + separator + valueType.annotations + valueType.javaNames[i] + " value);\n";
}
} else if (dim == 0 && !function) {
int n = 0;
for (Type type : containerType.arguments) {
if (containerType.arguments.length == 1 && !tuple) {
decl.text += " public native boolean has_value();\n"
+ " public native void reset();\n"
+ " public native @Name(\"value\") " + type.annotations + type.javaName + " get();\n";
} else {
int namespace = containerName.lastIndexOf("::");
String ns = containerName.substring(0, namespace);
decl.text += " public " + type.annotations + type.javaName + " get" + n + "() { return get" + n + "(this); }\n"
+ " @Namespace @Name(\"" + ns + "::get<" + n + ">\") public static native " + type.annotations + type.javaName + " get" + n + "(@ByRef " + containerType.javaName + " container);\n";
}
if (!constant && !tuple) {
decl.text += " @ValueSetter public native " + containerType.javaName + " put(" + type.annotations + type.javaName + " value);\n";
}
for (int i = 1; !constant && !tuple && type.javaNames != null && i < type.javaNames.length; i++) {
decl.text += " @ValueSetter public native " + containerType.javaName + " put(" + type.annotations + type.javaNames[i] + " value);\n";
}
n++;
}
}
if (dim == 1 && !containerName.toLowerCase().endsWith("bitset") && containerType.arguments.length >= 1 && containerType.arguments[containerType.arguments.length - 1].javaName.length() > 0) {
decl.text += "\n";
if (indexType == null || (!indexType.javaName.equals("long") && containerType.arguments.length == 1)) {
decl.text += " public " + removeAnnotations(valueType.javaName) + " front() { try (Iterator it = begin()) { return it.get(); } }\n";
}
if (!constant) {
if (list) {
decl.text += " public native @ByVal Iterator insert(@ByVal Iterator pos, " + valueType.annotations + valueType.javaName + " value);\n"
+ " public native @ByVal Iterator erase(@ByVal Iterator pos);\n";
} else if (indexType == null) {
decl.text += " public native void insert(" + valueType.annotations + valueType.javaName + " value);\n"
+ " public native void erase(" + valueType.annotations + valueType.javaName + " value);\n";
} else if (!dict) {
// XXX: need to figure out something for insert() on maps
decl.text += " public native void erase(@ByVal Iterator pos);\n";
}
}
if (indexType != null && !indexType.annotations.contains("@Const") && !indexType.annotations.contains("@Cast") && !indexType.value) {
indexType.annotations += "@Const ";
}
if (!valueType.annotations.contains("@Const") && !valueType.value) {
valueType.annotations += "@Const ";
}
decl.text += " public native @ByVal Iterator begin();\n"
+ " public native @ByVal Iterator end();\n"
+ " @NoOffset @Name(\"" + iteratorType + "\") public static class Iterator extends Pointer {\n"
+ " public Iterator(Pointer p) { super(p); }\n"
+ " public Iterator() { }\n\n"
+ " public native @Name(\"operator ++\") @ByRef Iterator increment();\n"
+ " public native @Name(\"operator ==\") boolean equals(@ByRef Iterator it);\n"
+ (containerType.arguments.length > 1 && indexType != null ?
" public native @Name(\"operator *()." + keyVariable + "\") @MemberGetter " + indexType.annotations + indexType.javaName + " first();\n"
+ " public native @Name(\"operator *()." + valueVariable + "\") @MemberGetter " + valueType.annotations + valueType.javaName + " second();\n"
:
" public native @Name(\"operator *\") " + valueType.annotations + valueType.javaName + " get();\n")
+ " }\n";
if (infoMap.getFirst(containerType.cppName + "::" + iteratorType) == null) {
infoMap.put(new Info(containerType.cppName + "::" + iteratorType).pointerTypes(containerType.javaName + ".Iterator"));
}
}
if (resizable) {
valueType.javaName = removeAnnotations(valueType.javaName);
decl.text += "\n"
+ " public " + valueType.javaName + arrayBrackets + "[] get() {\n";
String indent = " ", indices = "", args = "", brackets = arrayBrackets;
separator = "";
for (int i = 0; i < dim; i++) {
char c = (char)('i' + i);
decl.text +=
indent + (i == 0 ? valueType.javaName + brackets + "[] " : "") + "array" + indices + " = new " + valueType.javaName
+ "[size(" + args + ") < Integer.MAX_VALUE ? (int)size(" + args + ") : Integer.MAX_VALUE]" + brackets + ";\n" +
indent + "for (int " + c + " = 0; " + c + " < array" + indices + ".length; " + c + "++) {\n";
indent += " ";
indices += "[" + c + "]";
args += separator + c;
brackets = brackets.length() < 2 ? "" : brackets.substring(2);
separator = ", ";
}
decl.text += indent + "array" + indices + " = get(" + args + ");\n";
for (int i = 0; i < dim; i++) {
indent = indent.substring(4);
decl.text += indent + "}\n";
}
decl.text += " return array;\n"
+ " }\n"
+ " @Override public String toString() {\n"
+ " return java.util.Arrays." + (dim < 2 ? "toString" : "deepToString" ) + "(get());\n"
+ " }\n";
}
}
if (!constant && (dim == 0 || (containerType.arguments.length == 1 && indexType != null)) && firstType != null && secondType != null) {
String[] firstNames = firstType.javaNames != null ? firstType.javaNames : new String[] {firstType.javaName};
String[] secondNames = secondType.javaNames != null ? secondType.javaNames : new String[] {secondType.javaName};
String brackets = arrayBrackets + (dim > 0 ? "[]" : "");
for (int n = 0; n < firstNames.length || n < secondNames.length; n++) {
String firstName = firstNames[Math.min(n, firstNames.length - 1)];
String secondName = secondNames[Math.min(n, secondNames.length - 1)];
firstName = removeAnnotations(firstName);
secondName = removeAnnotations(secondName);
decl.text += "\n"
+ " public " + containerType.javaName + " put(" + firstName + brackets + " firstValue, "
+ secondName + brackets + " secondValue) {\n";
String indent = " ", indices = "", args = "";
separator = "";
for (int i = 0; i < dim; i++) {
char c = (char)('i' + i);
decl.text +=
indent + "for (int " + c + " = 0; " + c + " < firstValue" + indices + ".length && "
+ c + " < secondValue" + indices + ".length; " + c + "++) {\n";
indent += " ";
indices += "[" + c + "]";
args += separator + c;
separator = ", ";
}
decl.text += indent + "first(" + args + separator + "firstValue" + indices + ");\n"
+ indent + "second(" + args + separator + "secondValue" + indices + ");\n";
for (int i = 0; i < dim; i++) {
indent = indent.substring(4);
decl.text += indent + "}\n";
}
decl.text += " return this;\n"
+ " }\n";
}
} else if (resizable && firstType == null && secondType == null) {
boolean first = true;
for (String javaName : valueType.javaNames != null ? valueType.javaNames : new String[] {valueType.javaName}) {
javaName = removeAnnotations(javaName);
decl.text += "\n";
if (dim < 2) {
if (first) {
decl.text += " public " + javaName + " pop_back() {\n"
+ " long size = size();\n"
+ " " + javaName + " value = get(size - 1);\n"
+ " resize(size - 1);\n"
+ " return value;\n"
+ " }\n";
}
decl.text += " public " + containerType.javaName + " push_back(" + javaName + " value) {\n"
+ " long size = size();\n"
+ " resize(size + 1);\n"
+ " return put(size, value);\n"
+ " }\n"
+ " public " + containerType.javaName + " put(" + javaName + " value) {\n"
+ " if (size() != 1) { resize(1); }\n"
+ " return put(0, value);\n"
+ " }\n";
}
decl.text += " public " + containerType.javaName + " put(" + javaName + arrayBrackets + " ... array) {\n";
String indent = " ", indices = "", args = "";
separator = "";
for (int i = 0; i < dim; i++) {
char c = (char)('i' + i);
decl.text +=
indent + "if (size(" + args + ") != array" + indices + ".length) { resize(" + args + separator + "array" + indices + ".length); }\n" +
indent + "for (int " + c + " = 0; " + c + " < array" + indices + ".length; " + c + "++) {\n";
indent += " ";
indices += "[" + c + "]";
args += separator + c;
separator = ", ";
}
decl.text += indent + "put(" + args + separator + "array" + indices + ");\n";
for (int i = 0; i < dim; i++) {
indent = indent.substring(4);
decl.text += indent + "}\n";
}
decl.text += " return this;\n"
+ " }\n";
first = false;
}
}
if (function && decl.declarator != null) {
Declarator dcl = decl.declarator.definition.declarator;
decl.text += " public native @Name(\"operator =\") @ByRef " + containerType.javaName + " put(@ByRef " + valueType.javaName + " value);\n"
+ " public native @Name(\"operator ()\") " + dcl.type.annotations + dcl.type.javaName + " call" + dcl.parameters.list + ";\n";
}
if (info != null && info.javaText != null) {
declList.spacing = "\n ";
decl.text += declList.rescan(info.javaText) + "\n";
declList.spacing = null;
}
decl.text += "}\n";
declList.add(decl);
}
}
}
TemplateMap template(Context context) throws ParserException {
if (!tokens.get().match(Token.TEMPLATE)) {
return null;
}
TemplateMap map = new TemplateMap(context.templateMap);
tokens.next().expect('<');
for (Token token = tokens.next(); !token.match(Token.EOF); token = tokens.next()) {
if (token.match(Token.CLASS, Token.TYPENAME)) {
Token t = tokens.next();
if (t.match("...")) {
map.variadic = true;
t = tokens.next();
}
if (t.match(Token.IDENTIFIER)) {
String key = t.value;
map.put(key, map.get(key));
token = tokens.next();
}
} else if (token.match(Token.IDENTIFIER)) {
Type type = type(context); // ignore?
Token t = tokens.get();
if (t.match(Token.IDENTIFIER)) {
String key = t.value;
map.put(key, map.get(key));
token = tokens.next();
} else if (type != null) {
String key = type.cppName;
map.put(key, map.get(key));
}
}
if (!token.match(',', '>')) {
// ignore default argument
int count = 0;
for (token = tokens.get(); !token.match(Token.EOF); token = tokens.next()) {
if (count == 0 && token.match(',', '>')) {
break;
} else if (token.match('<', '(')) {
count++;
} else if (token.match('>', ')')) {
count--;
}
}
}
if (token.expect(',', '>').match('>')) {
if (tokens.next().match(Token.TEMPLATE)) {
tokens.next().expect('<');
} else {
break;
}
}
}
return map;
}
Type[] templateArguments(Context context) throws ParserException {
if (!tokens.get().match('<')) {
return null;
}
List<Type> arguments = new ArrayList<>();
for (Token token = tokens.next(); !token.match(Token.EOF); token = tokens.next()) {
if (token.match('>')) {
break;
}
Type type = type(context);
arguments.add(type);
token = tokens.get();
if (token.match('(')) {
Parameters p = parameters(context, 0, false);
if (p != null) {
// Build prototype string, without space after comma
type.cppName += "(";
String separator = "";
for (Declarator d : p.declarators) {
if (d != null) {
String s = d.type.cppName;
if (d.type.constValue && !s.startsWith("const ")) {
s = "const " + s;
}
for (int i = 0; i < d.indirections; i++) {
s += "*";
}
if (d.reference) {
s += "&";
}
if (d.rvalue) {
s += "&&";
}
if (d.type.constPointer && !s.endsWith(" const")) {
s = s + " const";
}
type.cppName += separator + s;
separator = ",";
}
}
type.cppName += ")";
token = tokens.get();
if (token.match('<')) {
// probably an actual less than, skip.
tokens.next();
token = tokens.get();
}
}
}
if (!token.match(',', '>') && type != null) {
// may not actually be a type
int count = 0;
for (token = tokens.get(); !token.match(Token.EOF); token = tokens.next()) {
if (count == 0 && token.match(',', '>')) {
break;
} else if (token.match('<', '(')) {
count++;
} else if (token.match('>', ')')) {
count--;
if (tokens.get(1).match('<')) {
// probably an actual less than
tokens.next();
}
}
for (int i = 0; i < type.indirections; i++) {
// this is not actually a type -> add back the "*"
type.cppName += "*";
}
type.indirections = 0;
type.cppName += token;
if (token.match(Token.CONST, Token.__CONST)) {
type.cppName += " ";
}
}
if (type.cppName.endsWith("*")) {
type.javaName = "PointerPointer";
type.annotations += "@Cast(\"" + type.cppName + "*\") ";
}
}
if (token.expect(',', '>').match('>')) {
break;
}
}
return arguments.toArray(new Type[0]);
}
/**
* Read and return the operator following an operator keyword:
* any of {@code new, delete, + - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= <=>(since C++20) && || ++ -- , ->* -> ( ) [ ]}
* taking care of template arguments, if any.
*/
private String operator(Context context) throws ParserException {
String res = tokens.get().toString(); // Can be '('
int lenFirstToken = res.length();
String s = "";
tokens.next();
int backIndex = tokens.index;
for (Token token = tokens.get(); !token.match('(', ';', Token.EOF); token = tokens.next()) {
s += token;
}
s = Templates.strip(s);
tokens.index = backIndex;
for (Token token = tokens.get(); s.length() > res.length() - lenFirstToken; token = tokens.next()) {
res += token;
}
return res;
}
Type type(Context context) throws ParserException {
return type(context, false);
}
Type type(Context context, boolean definition) throws ParserException {
Type type = new Type();
List<Attribute> attributes = new ArrayList<>();
for (Token token = tokens.get(); !token.match(Token.EOF); token = tokens.get()) {
if (token.match("::")) {
Info info = infoMap.getFirst(type.cppName, false);
if (info != null && info.pointerTypes != null && info.pointerTypes.length > 0
&& !type.cppName.contains("::") && token.spacing.length() > 0) {
break;
}
type.cppName += token;
} else if (token.match(Token.DECLTYPE)) {
type.cppName += token.toString() + tokens.next().expect('(');
int count = 1;
for (token = tokens.next(); !token.match(Token.EOF); token = tokens.next()) {
if (token.match('(')) {
count++;
} else if (token.match(')')) {
count--;
}
type.cppName += token;
if (count == 0) {
break;
}
}
tokens.next();
break;
} else if (token.match('<')) {
type.arguments = templateArguments(context);
type.cppName += "<";
String separator = "";
for (Type t : type.arguments) {
if (t == null) {
// skip over variadic templates
continue;
}
type.cppName += separator;
Info info = infoMap.getFirst(t.cppName);
String s = info != null && info.cppTypes != null && info.cppTypes.length > 0 ? info.cppTypes[0] : t.cppName;
if (t.constValue && !s.startsWith("const ")) {
s = "const " + s;
}
int n = s.indexOf('(');
for (int i = 0; i < t.indirections; i++) {
if (n >= 0) {
// return value from function type
s = s.substring(0, n) + "*" + s.substring(n);
} else {
s += "*";
}
}
if (t.reference) {
if (n >= 0) {
// return value from function type
s = s.substring(0, n) + "&" + s.substring(n);
} else {
s += "&";
}
}
if (t.rvalue) {
if (n >= 0) {
// return value from function type
s = s.substring(0, n) + "&&" + s.substring(n);
} else {
s += "&&";
}
}
if (t.constPointer && !s.endsWith(" const")) {
s = s + " const";
}
type.cppName += s;
separator = ",";
}
type.cppName += type.cppName.endsWith(">") ? " >" : ">";
} else if (token.match(Token.CONST, Token.__CONST, Token.CONSTEXPR)) {
String simpleName = Templates.strip(type.cppName);
if (!simpleName.trim().contains(" ") || type.simple) {
type.constValue = true;
} else {
type.constPointer = true;
}
if (token.match(Token.CONSTEXPR)) {
type.constExpr = true;
}
} else if (token.match('*')) {
type.indirections++;
tokens.next();
break;
} else if (token.match('&')) {
type.reference = true;
tokens.next();
break;
} else if (token.match("&&")) {
type.rvalue = true;
tokens.next();
break;
} else if (token.match('~')) {
type.cppName += "~";
type.destructor = true;
} else if (token.match(Token.STATIC)) {
type.staticMember = true;
} else if (token.match(Token.OPERATOR)) {
if (type.cppName.length() == 0) {
type.operator = true;
tokens.next();
continue;
} else if (type.cppName.endsWith("::")) {
type.operator = true;
tokens.next();
type.cppName += operator(context);
continue;
} else {
break;
}
} else if (token.match(Token.USING)) {
type.using = true;
} else if (token.match(Token.FRIEND)) {
type.friend = true;
} else if (token.match(Token.TYPEDEF)) {
type.typedef = true;
} else if (token.match(Token.VIRTUAL)) {
type.virtual = true;
} else if (token.match(Token.ENUM, Token.EXPLICIT, Token.EXTERN, Token.INLINE, Token.CLASS, Token.FINAL,
Token.INTERFACE, Token.__INTERFACE, Token.MUTABLE, Token.NAMESPACE, Token.STRUCT, Token.UNION,
Token.TYPENAME, Token.REGISTER, Token.THREAD_LOCAL, Token.VOLATILE)) {
tokens.next();
continue;
} else if (token.match((Object[])infoMap.getFirst("basic/types").cppTypes) && !tokens.get(1).match('<') && (type.cppName.length() == 0 || type.simple)) {
type.cppName += token.value + " ";
type.simple = true;
} else if (token.match(Token.IDENTIFIER, "[[")) {
int backIndex = tokens.index;
Attribute attr = attribute();
if (attr != null && (attr.annotation || token.match("[["))) {
type.annotations += attr.javaName;
attributes.add(attr);
continue;
} else {
tokens.index = backIndex;
if (type.cppName.length() == 0 || type.cppName.endsWith("::") || type.cppName.endsWith("~")) {
type.cppName += token.value;
} else if (type.cppName.endsWith("::template")) {
type.cppName += " " + token.value;
} else {
Info info = infoMap.getFirst(tokens.get(1).value);
if ((info != null && info.annotations != null) ||
!tokens.get(1).match('*', '&', Token.IDENTIFIER, Token.CONST, Token.__CONST, Token.CONSTEXPR, Token.FINAL)) {
// we probably reached a variable or function name identifier
break;
}
}
}
} else {
if (token.match('}')) {
type.anonymous = true;
tokens.next();
}
break;
}
tokens.next();
}
if (attributes.size() > 0) {
type.attributes = attributes.toArray(new Attribute[0]);
}
type.cppName = type.cppName.trim();
if (tokens.get().match("...")) {
// skip over variable arguments
tokens.next();
boolean paren;
if (paren = tokens.get().match('(')) {
tokens.next();
}
if (tokens.get().match(Token.IDENTIFIER)) {
// skip over template parameter packs as well
tokens.next();
}
if (paren && tokens.get().match(')')) {
tokens.next();
}
return null;
} else if (type.operator) {
for (Token token = tokens.get(); !token.match(Token.EOF, '(', ';'); token = tokens.next()) {
type.cppName += token;
}
}
// remove * and & to query template map
if (type.cppName.endsWith("*")) {
type.indirections++;
type.cppName = type.cppName.substring(0, type.cppName.length() - 1);
}
if (type.cppName.endsWith("&")) {
type.reference = true;
type.cppName = type.cppName.substring(0, type.cppName.length() - 1);
}
if (type.cppName.endsWith("&&")) {
type.rvalue = true;
type.cppName = type.cppName.substring(0, type.cppName.length() - 2);
}
// perform template substitution
if (context.templateMap != null) {
List<String> types = Templates.splitNamespace(type.cppName, true);
String separator = "";