11package pgdp .minijava ;
22
3+ import java .util .ArrayList ;
34import java .util .HashMap ;
5+ import java .util .List ;
46import java .util .Map ;
57
68public class Emitter {
@@ -9,7 +11,44 @@ private Emitter() {
911 }
1012
1113 public static String emit (SyntaxTreeNode node ) {
12- return emitCode (node , new HashMap <>());
14+ Map <String , Integer > variableMap = generateVariableMap (node , new HashMap <>());
15+ return emitCode (node , variableMap );
16+ }
17+
18+ private static Map <String , Integer > generateVariableMap (SyntaxTreeNode node , Map <String , Integer > variableMap ) {
19+ Map <String , Integer > out = new HashMap <>(variableMap );
20+ List <Map <String , Integer >> variableMaps = new ArrayList <>();
21+ int freeID = 0 ;
22+ for (int i = 0 ; i < node .getNumberChildren (); i ++) {
23+ SyntaxTreeNode child = node .getChild (i );
24+ if (child .getType () == SyntaxTreeNode .Type .DECL ) {
25+ for (int j = 0 ; j < child .getNumberChildren (); j ++) {
26+ SyntaxTreeNode n = child .getChild (j );
27+ if (n .getType () == SyntaxTreeNode .Type .NAME ){
28+ if (variableMap .containsKey (n .getValue ())) {
29+ throw new IllegalStateException (n .getValue () + " has already been defined in this context" );
30+ } else {
31+ out .put (n .getValue (), freeID ++);
32+ }
33+ }
34+ }
35+ } else if (child .getType () == SyntaxTreeNode .Type .NAME ) {
36+ if (!(variableMap .containsKey (child .getValue ()) || out .containsKey (child .getValue ()))) {
37+ throw new IllegalStateException (child .getValue () + " hasn't been defined in this context" );
38+ }
39+ } else {
40+ variableMaps .add (generateVariableMap (child , out ));
41+ }
42+ }
43+ return mergeVariableMaps (out , variableMaps );
44+ }
45+
46+ private static Map <String , Integer > mergeVariableMaps (Map <String , Integer > variableMap , List <Map <String , Integer >> list ) {
47+ for (Map <String , Integer > map : list ) {
48+ final int size = variableMap .size ();
49+ map .forEach (((s , integer ) -> {if (!variableMap .containsKey (s )) variableMap .put (s , integer + size );} ));
50+ }
51+ return variableMap ;
1352 }
1453
1554 private static String emitCode (SyntaxTreeNode node , Map <String , Integer > variableMap ) {
@@ -26,6 +65,7 @@ private static String emitCode(SyntaxTreeNode node, Map<String, Integer> variabl
2665 case STMT -> null ;
2766 case LABEL -> emitLabel (node , variableMap );
2867 case SYMBOL -> null ;
68+ case FUNCCALL -> null ;
2969 };
3070 }
3171
@@ -45,8 +85,4 @@ private static String emitLabel(SyntaxTreeNode node, Map<String, Integer> variab
4585 private static String emitDeclaration (SyntaxTreeNode node , Map <String , Integer > variableMap ) {
4686 return "" ;
4787 }
48-
49- private static class CodeUnit {
50-
51- }
5288}
0 commit comments