-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathHeaderWriter.java
More file actions
629 lines (526 loc) · 18.3 KB
/
HeaderWriter.java
File metadata and controls
629 lines (526 loc) · 18.3 KB
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
package qimpp;
import qimpp.Type;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.HashMap;
import xtc.tree.GNode;
import xtc.tree.Node;
import xtc.tree.Visitor;
import xtc.tree.Location;
import xtc.tree.Printer;
import xtc.util.Tool;
/** A generator for C++ class header files from a Java syntax tree
*
* This class handles inheritance, function declarations, and vtable generation.
* @author QIMPP
*/
public class HeaderWriter extends Visitor {
private Printer printer;
private ArrayList<GNode> inherited_methods;
private ArrayList<GNode> implemented_methods;
private ArrayList<GNode> methods;
private ArrayList<GNode> fields;
private boolean inherited;
//private String current_class;
/** Constructor. Opens a new file called defined_classes.h
*
* The GNode passed in should contain a modified tree created by InheritanceManager.
* HeaderGenerator should just format and print the fields and methods it is given,
* determining which methods, order of fields, inheritance of fields etc. should not be
* done here.
*
* A single header for all implemented classes is desirable as there may be type
* cross-references in the defined types (Point may contain a Color, and Color may contain
* a method returning a Point, so they must know about each other through
* forward-declarations in C++)
*
*
* Useful Notes:
*
* ClassBody is contained in roots[index].getGeneric(2)
* Use .indent() to indent when needed. The Printer doesn't do it automatically.
* Use .incr() to increase indentation, and .decr() to decrease intentation.
* ATTN: must call .incr() before you can call .indent()! Otherwise .indent() will do nothing
* TODO: Packages
*
*@param roots The QimppClassDeclaration nodes for the classes we want to create a header for
*/
// TODO: Need to change the HeaderWriter to take a GNode, instead of an array of GNodes
public HeaderWriter(Printer printer) {
this.printer = printer;
inherited_methods = new ArrayList<GNode>();
implemented_methods = new ArrayList<GNode>();
methods = new ArrayList<GNode>();
fields = new ArrayList<GNode>();
inherited = false;
//current_class = "";
printer.register(this);
}
// ===================
// VISITOR
// ==================
GNode compilationUnit;
public void visitCompilationUnit(GNode n){
compilationUnit = n;
writeDependencies();
visit(n);
printer.flush();
}
public void visitDeclarations(GNode n){
visit(n);
}
public void visitDeclaration(GNode n){
String[] qualifiers = getNameQualifiedArray(n);
// Declare the types in the correct namespaces
for ( int i = 0; i < qualifiers.length - 1; i++ ) {
indentOut().p("namespace ").p(qualifiers[i]).pln(" {");
printer.incr();
}
writeTypeDeclaration(n);
writeAlias(n);
for ( int i = 0; i < qualifiers.length - 1; i++ ) {
printer.decr();
indentOut().pln("}");
}
}
public void visitClasses(GNode n){
for (int i = n.size() - 1 ; i >= 0; i--) {
dispatch(n.getGeneric(i));
}
}
/** State variable to make sure we get ordering done right */
HashMap<String, Boolean> doneClass;
public void visitClassDeclaration(GNode n){
//current_class = name(n);
if (doneClass == null){
doneClass = new HashMap<String, Boolean>();
}
String name = n.getString(0);
// Print out classes in inheritance order
if (doneClass.get(name) == null) {
doneClass.put(name, true);
if (n.getProperty("ParentClassNode") != null){
visitClassDeclaration((GNode)n.getProperty("ParentClassNode"));
}
try{
visit(n);
// Write out the namespace of the class
String[] qualifiedType = getNameQualifiedArray(n);
for ( int i = 0; i < qualifiedType.length - 1; i++ ) {
indentOut().pln("namespace " + qualifiedType[i] + " {");
printer.incr();
}
writeStruct(n);
writeVTStruct(n);
methods.clear();
inherited_methods.clear();
implemented_methods.clear();
fields.clear();
// Write out the namespace of the class
for ( int i = 0; i < qualifiedType.length - 1; i++ ) {
printer.decr();
indentOut().pln("}");
}
new ArrayTemplatePrinter(printer).dispatch(n);
//current_class = "";
} catch ( Exception e) { e.printStackTrace(); }
}
}
public void visitFields(GNode n){
visit(n);
}
public void visitFieldDeclaration(GNode n){
fields.add(n);
}
/* public void visitBlock(GNode n) {
// do nothing
}
*/
public void visitInheritedMethodContainer(GNode n){
inherited = true;
if (!n.getGeneric(0).getString(0).equals("main"))
//inherited_methods.add(n);
methods.add(n);
inherited = false;
}
//TODO: Hack
//Prints out main methods for other classes differently
boolean didMain = false;
public void visitImplementedMethodDeclaration(GNode n){
if (!name(n).equals("main") || didMain) {
implemented_methods.add(n);
methods.add(n);
}
else {
didMain = true;
}
}
public void visit(GNode n){
for (Object o : n) if (o instanceof Node) dispatch((Node)o);
}
// ================================
// WRITE DEPENDENCIES + DECLARATIONS
// ================================
/** Write out the dependencies for the header */
//TODO: this method should probably do more. Not sure ATM.
private void writeDependencies() {
printer.p("#pragma once").pln();
printer.p("#include \"java_lang.h\"").pln()
.p("#include <stdint.h>").pln()
.p("#include \"qimpp_utils.h\"").pln()
.pln();
}
/** Write out the internal names of the structs and vtables for each class
*
* @param index the index of the class we are writing
*/
public void writeTypeDeclaration(GNode node){
indentOut().p("struct ").p("__").p(name(node)).p(";\n");
indentOut().p("struct ").p("__").p(name(node)).p("_VT;\n").pln();
}
/** Write out the typedefs so pretty-printing class names is easier on the programmer and
* the eyes
*
* @param node the node being examined
*/
private void writeAlias(GNode node){
printer.p("typedef __rt::Ptr<__").p(name(node)).p(" > ").p(name(node));
printer.p(";\n").pln();
}
// ===================
// WRITE STRUCT
// ===================
boolean isOutsideStruct;
/** Write out the struct definition for a given class, with all its newly defined methods
*
* @param node the node being written
*/
// Using java_lang.h as a basis, NOT skeleton.h
private void writeStruct(GNode n){
try{
indentOut().p("struct __").p(name(n)).p(" {\n");
printer.pln();
printer.incr();
writeVPtr(n);
writeFields(n);
printer.pln();
writeConstructor(n);
printer.pln();
writeMethods(n);
printer.pln();
writeClass();
printer.pln();
writeVTable(n);
printer.decr();
indentOut().p("};\n").pln();
printer.pln();
isOutsideStruct = true;
writeFields(n);
isOutsideStruct = false;
printer.pln();
}catch(Exception e) { e.printStackTrace(); }
}
private void writeVPtr(GNode node){
indentOut().p("__").p(name(node)).p("_VT* __vptr;\n");
}
/**
* The constructor.
*
* @param index the index of the class we are writing.
*/
private void writeConstructor(GNode node){
indentOut().p("__").p(name(node)).p("(");
// Now for parameters:
// Iterate through initializing types and fields. Use Type.
// For now, assuming only Object, therefore no parameters in constructor.
printer.p(");\n");
}
/**
* Write the fields that belong each type of object. For example, String
* has <code>std::string data</code>, and Class has <code>String name</code>
* and <code>Class parent</code>.
*
* @param index The index of the class we are writing.
*/
private void writeFields(GNode n) {
//Interate through the FieldDeclarations
for (GNode f : fields) {
writeField(f, n);
}
/**
for(Iterator<Object> iter = node.getGeneric(2).iterator(); iter.hasNext();){
Object objCurrent = iter.next();
if(objCurrent == null || objCurrent instanceof String) continue;
GNode current = (GNode) objCurrent;
if(current.hasName("FieldDeclaration"))
//For now just get the first field declared
indentOut().p(Type.translate(current)).p(" ").p(current.getGeneric(2).getGeneric(0).getString(0)).p(";").pln();
} */
}
private String getTypeDirect(GNode n, boolean isPointer){
GNode newNode = GNode.create("FakeNodeName", "Fake", n);
return getType(newNode, isPointer);
}
private String getType(GNode n, boolean isPointer) {
GNode type = n.getGeneric(1).getGeneric(0);
String ret = "";
if (type.getName().equals("PrimitiveType")) {
ret = Type.primitiveType(type.getString(0));
}
else if (type.getName().equals("QualifiedIdentifier")) {
if (type.size() == 1 && isPointer == false)
ret = "__" + type.getString(0);
for (Object id : type) {
if (type.indexOf(id) == 0)
ret += type.getString(type.indexOf(id));
else if (type.indexOf(id) == type.size() - 1 && isPointer == false)
ret += "::__" + type.getString(type.indexOf(id));
else
ret += "::" + type.getString(type.indexOf(id));
}
}
// HACK
else if (type.getName().equals("Type")){
ret = getTypeDirect(type, isPointer);
}
else {
}
//If the type has a dimension array and it's not null, then add in the dimensions. If it's the return type for a java.lang.Object method (constructed by hand) it won't have a null at 1 index, so we have to check for that.
GNode dimensions = (n.getGeneric(1).size() > 1) ? n.getGeneric(1).getGeneric(1) : null;
if(dimensions != null){
String arrConstructor = "";
for(int i = 0; i < dimensions.size(); i++){
arrConstructor += "__rt::Ptr<__rt::Array<";
}
arrConstructor += ret;
for(int i = 0; i < dimensions.size(); i++){
if(i == 0) arrConstructor += "> >";
else arrConstructor +=" > >";
}
ret = arrConstructor;
}
return (ret.length()!=0) ? ret : "NOT A VALID TYPE";
}
private void writeField(GNode n, GNode k) {
String type = getType(n, true);
if (n.getProperty("static") != null)
if (!isOutsideStruct)
indentOut().p("static ").p(type).p(" ").p(getFieldPrefix(n)).p(";\n");
else
indentOut().p(type).p(" ").p(Type.getClassTypeName(k.getString(0)))
.p("::").p(getFieldPrefix(n)).p(";\n");
else
if (!isOutsideStruct)
indentOut().p(type).p(" ").p(getFieldPrefix(n)).p(";\n");
}
private void writeMethods(GNode n){
String current_class = name(n);
for (GNode m : implemented_methods) {
writeMethod(m, current_class);
}
}
private void writeMethod(GNode n, String current_class) {
boolean isStatic;
indentOut().p("static ");
printer.p(getType(n, true)).p(" ");
printer.p(Type.getCppMangledMethodName(n)).p("(");
if (n.getProperty("static") == null) {
printer.p(current_class);
isStatic = false;
} else { isStatic = true; }
final boolean isStaticFinal = isStatic;
// visit params
new Visitor() {
public void visitFormalParameters(GNode n) {
if (!isStaticFinal && n.size() >= 1) { printer.p(", "); }
for (Iterator<?> iter = n.iterator(); iter.hasNext(); ) {
GNode formalParameter = (GNode)iter.next();
printer.p(getType(formalParameter, true));
if (iter.hasNext()) {
printer.p(", ");
}
}
}
public void visit(GNode n) {
for (Object o : n) if (o instanceof Node) dispatch((Node)o);
}
}.dispatch(n);
printer.p(");\n");
}
private void writeClass(){
indentOut().pln("static java::lang::Class __class();");
}
private void writeVTable(GNode n){
indentOut().p("static __").p(name(n)).pln("_VT __vtable;");
}
// =======================
// WRITE VTABLE STRUCT
// ======================
/** Write out the struct definition of a class's VTable
* @param i the index of the class we are writing
*/
private void writeVTStruct(GNode node) {
indentOut().p("struct __").p(name(node)).p("_VT {\n");
printer.pln();
printer.incr();
// initialize __isa
indentOut().pln("java::lang::Class __isa;\n");
indentOut().p("void (*__delete)(__").p(name(node)).p("*);").pln();
//writeInheritedVTMethods(node);
writeVTMethods(node);
printer.pln();
writeVTConstructor(node);
indentOut().p(": __isa(__").p(name(node)).pln("::__class()),\n");
indentOut().p("__delete(&__rt::__delete<__").p(name(node)).p(" >),").pln();
// writeObjectInheritedVTAddresses(node);
printer.incr();
// writeInheritedVTAddresses(node);
writeVTAddresses(node);
printer.p("{\n");
printer.decr();
indentOut().p("}\n");
printer.decr();
indentOut().p("};\n").pln();
}
/** Write out all the inherited methods of its superclass(es)
* @param i the index of the class we are writing */
// TODO: this
private void writeInheritedVTMethods(GNode n) {
String current_class = name(n);
for (GNode m : inherited_methods) {
//Get the implementedMethodDec node of the inheritedMethodContainer and write the VT method from it.
if (m.getProperty("static") == null && m.getProperty("private") == null)
writeVTMethod(m.getGeneric(0), current_class);
}
}
/** Write out all the classe's own methods
* @param i the index of the class we are writing */
// TODO: this
private void writeVTMethods(GNode n) {
String current_class = name(n);
for (GNode m : methods) {
if (m.getName().equals("InheritedMethodContainer")) {
writeVTMethod(m.getGeneric(0), current_class);
}
else {
if (m.getProperty("static") == null && m.getProperty("private") == null)
writeVTMethod(m, current_class);
}
}
}
private void writeVTMethod(GNode n, String current_class){
indentOut().p(getType(n, true)).p(" ");
printer.p("(*").p(Type.getCppMangledMethodName(n)).p(")(").p(current_class);
// if (n.getGeneric(2).size() != 0)
// printer.p(", <formal params>");
new Visitor() {
public void visitFormalParameter(GNode n) {
printer.p(", ").p(getType(n, true));
}
public void visit(GNode n) {
for (Object o : n) if (o instanceof Node) dispatch((Node)o);
}
}.dispatch(n);
printer.p(");\n");
}
/** Write out the VT Constructor
* @param i the index of the class we are writing */
private void writeVTConstructor(GNode node) {
indentOut().p("__").p(name(node)).p("_VT()\n");
}
/** Write out all the inherited Object VT method addresses
* @param i the index of the class we are writing */
// TODO: not sure if this is exactly what we want
/**
private void writeObjectInheritedVTAddresses(GNode node) {
indentOut().p("hashCode((int32_t(*)(").p(name(node)).p("))&__Object::hashCode),\n");
indentOut().p("equals((bool(*)(").p(name(node)).p(",Object))&__Object::equals),\n");
indentOut().p("getClass((Class(*)(").p(name(node)).p("))&__Object::getClass),\n");
indentOut().p("toString((String(*)(").p(name(node)).p("))&__Object::toString)\n");
} */
/**
* Write out all the inherited VT addresses of the class' superclass(es)' methods
* @param i the index of the class we are writing */
/* TODO: this
private void writeInheritedVTAddresses(GNode n) {
String current_class = name(n);
for (GNode m : inherited_methods) {
if (inherited_methods.indexOf(m) != 0)
printer.p(",\n");
writeInheritedVTAddress(m, current_class);
}
}*/
/** Write out all the VT addresses of the class' own methods
* @param i the index of the class we are writing */
// TODO: this
private void writeVTAddresses(GNode n) {
String current_class = name(n);
boolean hasPrintedComma = false;
for (GNode m : methods) {
if (m.getName().equals("InheritedMethodContainer")) {
if (methods.indexOf(m) != 0)
printer.p(",\n");
writeInheritedVTAddress(m, current_class);
}
else {
if (m.getProperty("static") == null && m.getProperty("private") == null){
if (methods.indexOf(m) != 0)
printer.p(",\n");
writeVTAddress(m, current_class);
}
}
}
}
private void writeInheritedVTAddress(GNode n, String current_class) {
GNode inheritedMethodContainer;
inheritedMethodContainer = n;
n = inheritedMethodContainer.getGeneric(0);
if (n.getString(0).equals("main")) {
return;
}
indentOut().p(Type.getCppMangledMethodName(n)).p("((");
printer.p(getType(n, true));
printer.p("(*)(").p(current_class);
//if (n.getGeneric(2).size() != 0)
new Visitor() {
public void visitFormalParameter(GNode n) {
printer.p(", ").p(getType(n, true));
}
public void visit(GNode n) {
for (Object o : n) if (o instanceof Node) dispatch((Node)o);
}
}.dispatch(n);
//printer.p(", <formal params>");
// following line gets From field from method node
printer.p("))&").p(getTypeDirect(inheritedMethodContainer.getGeneric(1).getGeneric(0), false))
.p("::").p(Type.getCppMangledMethodName(n)).p(")");
}
private void writeVTAddress(GNode n, String current_class) {
indentOut().p(Type.getCppMangledMethodName(n)).p("(&__").p(current_class).p("::")
.p(Type.getCppMangledMethodName(n)).p(")");
}
// =======================
// UTILITY METHODS
// =======================
private String name(GNode n) {
// Get the final identifier from the qualified name
String[] qualifiedNameArray = n.getString(0).split("\\.");
String name = qualifiedNameArray[qualifiedNameArray.length - 1];
return name;
}
private Printer indentOut(){
return printer.indent();
}
private String[] getNameQualifiedArray(GNode n) {
String qualifiedName = n.getString(0);
String[] qualifiedType = qualifiedName.split("\\.");
return qualifiedType;
}
private String getFieldPrefix(GNode n){
return n.getString(0).replace(".", "_");
}
}