Browse Source

type fix bytes

eugeniucarvalho 5 years ago
parent
commit
d676e473f3
100 changed files with 1455 additions and 1740 deletions
  1. 2 1
      .gitignore
  2. 1 1
      build/built-jar.properties
  3. BIN
      build/classes/API/Api.class
  4. BIN
      build/classes/API/BuildParams.class
  5. BIN
      build/classes/API/Functions.class
  6. BIN
      build/classes/API/Imports.class
  7. BIN
      build/classes/API/Utils.class
  8. BIN
      build/classes/compiler/IVANNOSYS.class
  9. BIN
      build/classes/compiler/IvannosysCompiler.class
  10. 7 2
      build/classes/grammar/IvannosysGrammar.g4
  11. BIN
      build/classes/grammar/IvannosysGrammarBaseListener.class
  12. BIN
      build/classes/grammar/IvannosysGrammarBaseVisitor.class
  13. BIN
      build/classes/grammar/IvannosysGrammarListener.class
  14. BIN
      build/classes/grammar/IvannosysGrammarParser$Anon_fieldContext.class
  15. BIN
      build/classes/grammar/IvannosysGrammarParser$ArrayTypeContext.class
  16. BIN
      build/classes/grammar/IvannosysGrammarParser$BaseTypeContext.class
  17. BIN
      build/classes/grammar/IvannosysGrammarParser$Base_stmtContext.class
  18. BIN
      build/classes/grammar/IvannosysGrammarParser$Build_stmtContext.class
  19. BIN
      build/classes/grammar/IvannosysGrammarParser$BuildtagsContext.class
  20. BIN
      build/classes/grammar/IvannosysGrammarParser$BuildvalueContext.class
  21. BIN
      build/classes/grammar/IvannosysGrammarParser$CallExprContext.class
  22. BIN
      build/classes/grammar/IvannosysGrammarParser$Catch_exceptionContext.class
  23. BIN
      build/classes/grammar/IvannosysGrammarParser$CompositeContext.class
  24. BIN
      build/classes/grammar/IvannosysGrammarParser$Def_blockContext.class
  25. BIN
      build/classes/grammar/IvannosysGrammarParser$Def_forContext.class
  26. BIN
      build/classes/grammar/IvannosysGrammarParser$DeleteContext.class
  27. BIN
      build/classes/grammar/IvannosysGrammarParser$Element_listContext.class
  28. BIN
      build/classes/grammar/IvannosysGrammarParser$ExpressionContext.class
  29. BIN
      build/classes/grammar/IvannosysGrammarParser$Expression_listContext.class
  30. BIN
      build/classes/grammar/IvannosysGrammarParser$Expression_seletorContext.class
  31. BIN
      build/classes/grammar/IvannosysGrammarParser$FallthroughStmtContext.class
  32. BIN
      build/classes/grammar/IvannosysGrammarParser$FieldDeclContext.class
  33. BIN
      build/classes/grammar/IvannosysGrammarParser$Finally_tryContext.class
  34. BIN
      build/classes/grammar/IvannosysGrammarParser$Flux_controlContext.class
  35. BIN
      build/classes/grammar/IvannosysGrammarParser$For_clauseContext.class
  36. BIN
      build/classes/grammar/IvannosysGrammarParser$For_eachContext.class
  37. BIN
      build/classes/grammar/IvannosysGrammarParser$Func_literalContext.class
  38. BIN
      build/classes/grammar/IvannosysGrammarParser$Inc_decContext.class
  39. BIN
      build/classes/grammar/IvannosysGrammarParser$IncrementContext.class
  40. BIN
      build/classes/grammar/IvannosysGrammarParser$IndexedTypeContext.class
  41. BIN
      build/classes/grammar/IvannosysGrammarParser$InitializationContext.class
  42. BIN
      build/classes/grammar/IvannosysGrammarParser$Keyed_elementContext.class
  43. BIN
      build/classes/grammar/IvannosysGrammarParser$Label_stmtContext.class
  44. BIN
      build/classes/grammar/IvannosysGrammarParser$LiteralContext.class
  45. BIN
      build/classes/grammar/IvannosysGrammarParser$LiteralTypeContext.class
  46. BIN
      build/classes/grammar/IvannosysGrammarParser$Literal_valueContext.class
  47. BIN
      build/classes/grammar/IvannosysGrammarParser$MapTypeContext.class
  48. BIN
      build/classes/grammar/IvannosysGrammarParser$NewstmtContext.class
  49. BIN
      build/classes/grammar/IvannosysGrammarParser$OperandContext.class
  50. BIN
      build/classes/grammar/IvannosysGrammarParser$Primary_exprContext.class
  51. BIN
      build/classes/grammar/IvannosysGrammarParser$QualifiedIdContext.class
  52. BIN
      build/classes/grammar/IvannosysGrammarParser$RangeContext.class
  53. BIN
      build/classes/grammar/IvannosysGrammarParser$Return_stmtContext.class
  54. BIN
      build/classes/grammar/IvannosysGrammarParser$StatementContext.class
  55. BIN
      build/classes/grammar/IvannosysGrammarParser$StructTypeContext.class
  56. BIN
      build/classes/grammar/IvannosysGrammarParser$TestContext.class
  57. BIN
      build/classes/grammar/IvannosysGrammarParser$ThrowStmtContext.class
  58. BIN
      build/classes/grammar/IvannosysGrammarParser$Try_catchContext.class
  59. BIN
      build/classes/grammar/IvannosysGrammarParser$TypeContext.class
  60. BIN
      build/classes/grammar/IvannosysGrammarParser$TypenameContext.class
  61. BIN
      build/classes/grammar/IvannosysGrammarParser$Unary_exprContext.class
  62. BIN
      build/classes/grammar/IvannosysGrammarParser.class
  63. BIN
      build/classes/grammar/IvannosysGrammarVisitor.class
  64. 0 1
      build/classes/samples/program.go
  65. 15 15
      build/classes/tools/mips/memory/md.memory
  66. 40 34
      build/classes/tools/mips/memory/mi.memory
  67. 1 1
      nbproject/private/private.properties
  68. 6 8
      nbproject/private/private.xml
  69. 40 30
      src/API/Api.java
  70. 1 1
      src/API/BuildParams.java
  71. 13 3
      src/API/Functions.java
  72. 6 5
      src/API/Imports.java
  73. 1 1
      src/API/TargetGen.java
  74. 120 649
      src/API/Types.java
  75. 23 0
      src/API/Utils.java
  76. 3 3
      src/API/Variables.java
  77. 61 25
      src/IntermediaryCode/IRGenerator.java
  78. 48 15
      src/IntermediaryCode/IRTemplate.java
  79. 5 0
      src/Processors/CodeOtimizadorProcessor.java
  80. 23 21
      src/Processors/RemoveUnusedLabelsProcessor.java
  81. 6 7
      src/common/Block.java
  82. 6 6
      src/common/Code.java
  83. 16 50
      src/common/DataFrame.java
  84. 2 1
      src/compiler/IVANNOSYS.java
  85. 17 27
      src/compiler/IvannosysCompiler.java
  86. 46 40
      src/frontend/Ivannosys/IvannosysListener.java
  87. 14 22
      src/frontend/Ivannosys/IvannosysVisitor.java
  88. 7 2
      src/grammar/IvannosysGrammar.g4
  89. 13 0
      src/grammar/IvannosysGrammarBaseListener.java
  90. 8 0
      src/grammar/IvannosysGrammarBaseVisitor.java
  91. 11 0
      src/grammar/IvannosysGrammarListener.java
  92. 781 726
      src/grammar/IvannosysGrammarParser.java
  93. 7 0
      src/grammar/IvannosysGrammarVisitor.java
  94. 19 0
      src/libs/sync/sync.go
  95. 0 1
      src/samples/program.go
  96. 23 10
      src/samples/program_jun_bit_count.go
  97. 50 19
      src/samples/program_mult_manycore.go
  98. 5 5
      build/classes/samples/program_mult_manycore.go
  99. 8 8
      src/targets/mips/Gen.java
  100. 0 0
      src/targets/mips/MipsOTMinActivationRegister.java

+ 2 - 1
.gitignore

@@ -1,2 +1,3 @@
 build
-src/tools/mips/memory
+src/tools/mips/memory
+/dist/

+ 1 - 1
build/built-jar.properties

@@ -1,4 +1,4 @@
-#Thu, 05 Jul 2018 03:07:34 -0300
+#Fri, 06 Jul 2018 00:49:37 -0300
 
 
 C\:\\Users\\EUGENIO\ CARVALHO\\Desktop\\projects\\Ivannosys=

BIN
build/classes/API/Api.class


BIN
build/classes/API/BuildParams.class


BIN
build/classes/API/Functions.class


BIN
build/classes/API/Imports.class


BIN
build/classes/API/Utils.class


BIN
build/classes/compiler/IVANNOSYS.class


BIN
build/classes/compiler/IvannosysCompiler.class


+ 7 - 2
build/classes/grammar/IvannosysGrammar.g4

@@ -163,8 +163,9 @@ def_if_block
 // Fim If -> Ini Lacos
 
 def_for
-    : R_FOR ( for_clause | for_each )? def_block // Like for
+    : R_FOR (for_clause | for_each | test ) def_block // Like for
     ;
+
 for_clause
     : (initialization R_PT_VIRG)? test (R_PT_VIRG increment)?
     ;
@@ -173,6 +174,9 @@ initialization
     :base_stmt
     ;
 
+empty_block
+    : R_COL_E R_COL_D
+    ;
 test 
     : expression
     | base_stmt (R_PT_VIRG expression)? 
@@ -305,7 +309,8 @@ expression_seletor
 
 // Definicao de um bloco de instrucoes
 def_block locals[HashMap<String, String> retornos = new HashMap<>();]
-    : R_COL_E statement+ R_COL_D
+    : R_COL_E statement* R_COL_D
+    //|empty_block
     ;
 
 callExpr:

BIN
build/classes/grammar/IvannosysGrammarBaseListener.class


BIN
build/classes/grammar/IvannosysGrammarBaseVisitor.class


BIN
build/classes/grammar/IvannosysGrammarListener.class


BIN
build/classes/grammar/IvannosysGrammarParser$Anon_fieldContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$ArrayTypeContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$BaseTypeContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$Base_stmtContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$Build_stmtContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$BuildtagsContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$BuildvalueContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$CallExprContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$Catch_exceptionContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$CompositeContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$Def_blockContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$Def_forContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$DeleteContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$Element_listContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$ExpressionContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$Expression_listContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$Expression_seletorContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$FallthroughStmtContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$FieldDeclContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$Finally_tryContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$Flux_controlContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$For_clauseContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$For_eachContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$Func_literalContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$Inc_decContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$IncrementContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$IndexedTypeContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$InitializationContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$Keyed_elementContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$Label_stmtContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$LiteralContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$LiteralTypeContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$Literal_valueContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$MapTypeContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$NewstmtContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$OperandContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$Primary_exprContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$QualifiedIdContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$RangeContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$Return_stmtContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$StatementContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$StructTypeContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$TestContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$ThrowStmtContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$Try_catchContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$TypeContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$TypenameContext.class


BIN
build/classes/grammar/IvannosysGrammarParser$Unary_exprContext.class


BIN
build/classes/grammar/IvannosysGrammarParser.class


BIN
build/classes/grammar/IvannosysGrammarVisitor.class


+ 0 - 1
build/classes/samples/program.go

@@ -41,7 +41,6 @@ func laplaciano() {
     var (
         l int
         //LM1,CM1 int
-        
     )
     LM1 := LIN - 1
     CM1 := COL - 1

+ 15 - 15
build/classes/tools/mips/memory/md.memory

@@ -1,5 +1,5 @@
-0000:	82
-0004:	2
+0000:	1
+0004:	164
 0008:	3
 0012:	4
 0016:	1
@@ -4071,26 +4071,26 @@
 16280:	0
 16284:	0
 16288:	0
-16292:	0
+16292:	163
 16296:	0
 16300:	0
 16304:	0
 16308:	0
-16312:	0
+16312:	7
 16316:	0
-16320:	0
+16320:	7
 16324:	0
-16328:	0
-16332:	0
-16336:	0
+16328:	-48
+16332:	52
+16336:	81
 16340:	0
 16344:	0
 16348:	0
-16352:	0
+16352:	10053
 16356:	0
-16360:	0
-16364:	0
-16368:	7
-16372:	81
-16376:	10053
-16380:	10
+16360:	7
+16364:	-12
+16368:	10
+16372:	0
+16376:	10033
+16380:	0

+ 40 - 34
build/classes/tools/mips/memory/mi.memory

@@ -1,55 +1,61 @@
-0666763252
+0666763216
 0001962017
 0605028352
 2949644288
 0605103921
-2949709828
-0605159424
-2949775368
-0134217756
+2949709840
+0605159425
+2945581056
+0605224960
+2949840928
+0134217758
 0000000000
-2412969988
+2413035536
 0000000000
-0001253409
-0201326630
+0001318945
+0201326632
 0000000000
-0000153633
-2413035520
+0000155681
+2413101056
 0000000000
-0042704929
-2949906432
-2413101060
+0044869665
+2949971968
+2413166608
 0000000000
-0649396226
-2949971972
-2413166600
+0651558914
+2950037520
+2413232160
 0000000000
-0651558913
-2950037512
-2413232136
+0653721601
+2950103072
+2412773408
 0000000000
-0604897290
-0049156131
+0604962826
+0034541603
 0071368681
 0000000000
-2412773376
+2412838912
 0000000000
-0001052705
+0001118241
 4294967295
-0666763256
+0666763232
 0001962017
+2412773376
+0000000000
 2948857856
 0605093888
-2949709828
+2949709840
 2412773376
 0000000000
 0033558563
-0406847507
+0406847509
+0000000000
+0134217798
 0000000000
-2412904452
+2412904464
 0000000000
 0642908161
-2949775364
+2949775376
 2412969984
 0000000000
 0644677631
@@ -62,16 +68,16 @@
 0000000000
 0308281347
 0000000000
-0134217776
+0134217782
 0000000000
-2408841216
-2413101060
+2408841220
+2413101072
 0000000000
 0043360289
-2945712128
-2413101060
+2945712132
+2413101072
 0000000000
 0001380385
-0666697736
+0666697760
 0001962017
 0065011720

+ 1 - 1
nbproject/private/private.properties

@@ -3,4 +3,4 @@ do.depend=false
 do.jar=true
 javac.debug=true
 javadoc.preview=true
-user.properties.file=C:\\Users\\EUGENIO CARVALHO\\AppData\\Roaming\\NetBeans\\8.2\\build.properties
+user.properties.file=C:\\Users\\EUGENIO CARVALHO\\AppData\\Roaming\\NetBeans\\7.4\\build.properties

+ 6 - 8
nbproject/private/private.xml

@@ -13,7 +13,7 @@
             <url>src/samples/program.go</url>
             <bookmark id="3">
                 <name/>
-                <line>90</line>
+                <line>89</line>
                 <key/>
             </bookmark>
         </file>
@@ -28,13 +28,11 @@
     </editor-bookmarks>
     <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
         <group>
-            <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/common/Code.java</file>
-            <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/targets/mips/Gen.java</file>
-            <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/Export/MultCoreJun.java</file>
-            <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/templates/Functions.java</file>
-            <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/IntermediaryCode/IRTemplate.java</file>
-            <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/templates/TListener.java</file>
-            <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/targets/mips/MipsTemplate.java</file>
+            <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/templates/Template.g4</file>
+            <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/templates/input.txt</file>
+            <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/libs/sync/sync.go</file>
+            <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/samples/program_jun_bit_count.go</file>
+            <file>file:/C:/Users/EUGENIO%20CARVALHO/Desktop/projects/Ivannosys/src/grammar/IvannosysGrammar.g4</file>
         </group>
     </open-files>
 </project-private>

+ 40 - 30
src/API/Api.java

@@ -34,34 +34,34 @@ public class Api {
         /*Inicializando tipos*/
         Types._init();
 
-        Types.Add(Types.INTEGER, new Node(Types.INTEGER)
-                .Set("type", Types.INTEGER)
-                .S("size", 1)
-                .Set("file", "std")
-                .Set("scope", "")
-                .Set("primitive", "true")
-                .Set("class", "type")
-                .Set("public", "true")
-        );
-        Types.Add(Types.BOOLEAN, new Node(Types.BOOLEAN)
-                .Set("type", Types.BOOLEAN)
-                .S("size", 1)
-                .Set("file", "std")
-                .Set("scope", "")
-                .Set("primitive", "true")
-                .Set("class", "type")
-                .Set("public", "true")
-        );
-        Types.Add(Types.CHAR, new Node(Types.CHAR)
-                .Set("type", Types.CHAR)
-                .S("size", 1)
-                .Set("file", "std")
-                .Set("scope", "")
-                .Set("primitive", "true")
-                .Set("class", "type")
-                .Set("public", "true")
-        );
-
+//
+//        Types.Add(Types.INTEGER, new Node(Types.INTEGER)
+//                .Set("type", Types.INTEGER)
+//                .S("size", 1)
+//                .Set("file", "std")
+//                .Set("scope", "")
+//                .Set("primitive", "true")
+//                .Set("class", "type")
+//                .Set("public", "true")
+//        );
+//        Types.Add(Types.BOOLEAN, new Node(Types.BOOLEAN)
+//                .Set("type", Types.BOOLEAN)
+//                .S("size", 1)
+//                .Set("file", "std")
+//                .Set("scope", "")
+//                .Set("primitive", "true")
+//                .Set("class", "type")
+//                .Set("public", "true")
+//        );
+//        Types.Add(Types.CHAR, new Node(Types.CHAR)
+//                .Set("type", Types.CHAR)
+//                .S("size", 1)
+//                .Set("file", "std")
+//                .Set("scope", "")
+//                .Set("primitive", "true")
+//                .Set("class", "type")
+//                .Set("public", "true")
+//        );
         // Registra os processadores de codigo padrão
         CodeProcessor.Add("ir.clear.labels", new Processors.RemoveUnusedLabelsProcessor());
         CodeProcessor.Add("ir.basic.blocks", new Processors.BasicBlockProcessor());
@@ -168,7 +168,6 @@ public class Api {
 //    public static String reg2bin5(String reg) throws Exception {
 //        return reg2Bin(reg, 5);
 //    }
-
 //    public static String reg2Bin(String reg, int SizeBits) throws Exception {
 //        if (reg.equals("")) {
 //            return num2bin(0, SizeBits);
@@ -178,7 +177,6 @@ public class Api {
 ////        System.out.println(":val:" + val);
 //        return num2bin(val, SizeBits);
 //    }
-
     public static String bin2Hex(String bin, int size) {
 //        System.out.println("bin:[" + bin + "]");
         if (bin.equals("")) {
@@ -214,4 +212,16 @@ public class Api {
         return id.replace("*", "").replace("&", "");
     }
 
+    public static void Update() throws Exception {
+        Types.Update();
+    }
+
+    public static void List() {
+        BuildParams.List();
+        Types.List();
+        Interfaces.List();
+        Variables.List();
+        Functions.List();
+    }
+
 }

+ 1 - 1
src/API/BuildParams.java

@@ -56,7 +56,7 @@ public class BuildParams {
     public static void List() {
         System.out.println("BuildParams:\n");
         for (Map.Entry<String, ArrayList<String>> entry : params.entrySet()) {
-            System.out.println(entry.getKey() + ": " + entry.getValue());
+            System.out.println("\t" + entry.getKey() + ": " + entry.getValue());
         }
     }
 

+ 13 - 3
src/API/Functions.java

@@ -55,7 +55,13 @@ public class Functions {
     }
 
     public static void List() {
-        System.out.println("Funcoes:\n" + funcs.keySet());
+        StringBuilder sb = new StringBuilder();
+
+        for (String name : funcs.keySet()) {
+            sb.append("\t" + name + "\n");
+        }
+
+        System.out.println("Funcoes:\n" + sb.toString());
     }
 
     public static void Add(String id, Node func) throws Exception {
@@ -72,7 +78,10 @@ public class Functions {
 //        System.out.println("Funcs:" + funcs.keySet());
     }
 
-    public static boolean Defined(String id) {
+    public static boolean Defined(String id) throws Exception {
+        if (!funcs.containsKey(id)) {
+            throw new Exception(String.format("A função '%s' não foi definida. Disponiveis '%s'", id, funcs.keySet()));
+        }
         return funcs.containsKey(id);
     }
 
@@ -107,7 +116,8 @@ public class Functions {
             for (Node e : T.findAll("type", "class", 1)) {
                 type = e.Get("type");
                 packageName = type.split("\\.")[0];
-                id = packageName + ".method.(" + type + ")." + method;
+//                id = packageName + ".method.(" + type + ")." + method;
+                id = "method.(" + type + ")." + method;
 //                System.out.println("Deep:" + id);
                 def = Get(id);
                 if (def != null) {

+ 6 - 5
src/API/Imports.java

@@ -6,7 +6,6 @@
 package API;
 
 import compiler.IvannosysCompiler;
-import java.util.Arrays;
 import java.util.HashMap;
 
 /**
@@ -24,8 +23,8 @@ public class Imports {
         Imports.compiler = compiler;
     }
 
-    public static void add(String path) {
-        add(path, "");
+    public static void Add(String path) throws Exception {
+        Imports.Add(path, "");
     }
 
     public static boolean Load(String alias) throws Exception {
@@ -40,16 +39,18 @@ public class Imports {
         return true;
     }
 
-    public static void add(String path, String alias) {
+    public static void Add(String path, String alias) throws Exception {
+
         if (alias.equals("")) {
             String[] parts = path.split("/");
             alias = parts[parts.length - 1];
         }
-//        System.out.println("Add, " + path + ":" + alias);
 
         if (!imports.containsKey(alias)) {
             imports.put(alias, path);
         }
+
+        Load(alias);
     }
 
     public static HashMap<String, String> imports() {

+ 1 - 1
src/API/TargetGen.java

@@ -76,7 +76,7 @@ public abstract class TargetGen implements IvannosysTargetArch {
         }
 
         IR = tac;
-        target.GData().copy(tac.GData());
+        target.GlobalData().copy(tac.GlobalData());
         target.Parent = IR;
         return this;
     }

+ 120 - 649
src/API/Types.java

@@ -5,10 +5,11 @@
  */
 package API;
 
-import ast.AbstractSyntaxTree;
 import ast.Node;
 import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
 
 /**
  *
@@ -16,29 +17,106 @@ import java.util.HashMap;
  */
 public class Types {
 
-    public static AbstractSyntaxTree ast;
+//    public static AbstractSyntaxTree ast;
     public static HashMap<String, Node> _types = new HashMap<>();
+    // Tamanho em bytes de cada tipo 
     public static HashMap<String, Integer> _sizes = new HashMap<>();
+
     public static HashMap<String, Integer> primitiveTypes = new HashMap<>();
     public static HashMap<String, HashMap<String, String>> _propList = new HashMap<>();
     public static HashMap<String, Integer> _offsetList = new HashMap<>();
-    public static String REFERENCE = "reference";
-    public static String INTEGER = "int";
-    public static String BOOLEAN = "bool";
-    public static String UNDEFINED = "undefined";
-    public static String CHAR = "char";
-    public static String VOID = "void";
-    private static String STRING = "string";
-    private static int SIZE_POINTER = 1;
 
     public static HashMap<String, Integer> getSizes() {
         return _sizes;
     }
 
-    public static void _init() {
+    public static void _init() throws Exception {
+        HashMap<String, Integer> types = new HashMap<String, Integer>() {
+            {
+                //Numeric types
+//                uint8       the set of all unsigned  8-bit integers (0 to 255)
+//                uint16      the set of all unsigned 16-bit integers (0 to 65535)
+//                uint32      the set of all unsigned 32-bit integers (0 to 4294967295)
+//                uint64      the set of all unsigned 64-bit integers (0 to 18446744073709551615)
+//                int8        the set of all signed  8-bit integers (-128 to 127)
+//                int16       the set of all signed 16-bit integers (-32768 to 32767)
+//                int32       the set of all signed 32-bit integers (-2147483648 to 2147483647)
+//                int64       the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)
+//                float32     the set of all IEEE-754 32-bit floating-point numbers
+//                float64     the set of all IEEE-754 64-bit floating-point numbers
+//                complex64   the set of all complex numbers with float32 real and imaginary parts
+//                complex128  the set of all complex numbers with float64 real and imaginary parts
+//                byte        alias for uint8
+//                rune        alias for int32
+                put("byte", 1);
+                put("uint8", 1);
+                put("uint16", 2);
+                put("uint32", 4);
+                put("uint64", 8);
+                put("int8", 1);
+                put("int16", 2);
+                put("int32", 4);
+                put("int64", 8);
+                put("float32", 4);
+                put("float64", 8);
+                put("complex64", 8);
+                put("complex128", 16);
+                put("bool", 1);
+                put("char", 1);
+            }
+        };
+        String type;
+        for (Map.Entry<String, Integer> entry : types.entrySet()) {
+            type = entry.getKey();
+            Add(type, new Node(type)
+                    .Set("size", entry.getValue())
+                    .Set("file", "std")
+                    .Set("scope", "")
+                    .Set("primitive", "true")
+                    .Set("block", "true") // Diz que não deve editar o tipo
+                    .Set("class", "type")
+                    .Set("public", "true")
+            );
+        }
 
     }
 
+    // Deve ser chamada no fim da leitura do listner para atuaizar os tamanhos dos tipos
+    public static void Update() throws Exception {
+        Node def;
+
+        for (Map.Entry<String, Node> entry : _types.entrySet()) {
+            Node type = entry.getValue();
+
+            if (type.eq("block", "true")) {
+                continue;
+            }
+
+            // Completa a definicao da struct importando os atributos herdados
+            for (Node t : type.findAll("type", "class", 1)) {
+
+                def = Get(t.Get("type"));
+
+                for (Node attr : def.findAll("attr", "class")) {
+                    attr.Set("path", def.getText());
+                    type.addFilho(attr);
+                }
+            }
+            UpdateSize(type);
+        }
+
+    }
+
+    protected static void UpdateSize(Node type) throws Exception {
+        // Atualiza o tamanho to tipo
+        int size = 0;
+
+        for (Node attr : type.findAll("attr", "class")) {
+            size += Size(attr.childrens().get(0).Get("type"));
+        }
+        _sizes.put(type.getText(), size);
+    }
+
     /**
      * Adiciona um tipo a linguagem
      *
@@ -51,41 +129,20 @@ public class Types {
         if (_types.containsKey(id)) {
             throw new Exception(String.format("Tipo '%s' previamente definido na linha %s", id, _types.get(id).Get("line", "")));
         }
-//        System.out.println("AddType:" + id);
+
         if (!type.Has("public")) {
             type.Set("public", Base.IsPublic(id) ? "true" : "false");
         }
-        Node def;
-        // Completa a definicao da struct importando os atributos herdados
-        for (Node t : type.findAll("type", "class", 1)) {
-//            System.out.println("import type:" + t.Get("type"));
-
-//            if (t.Get("type").equals("null")) {
-//                // todo - adicionar erro ja que o tipo deveria existir
-//                continue;
-//            }
-//            System.out.println("Include type:" + t.Get("type"));
-            def = Get(t.Get("type"));
-            if (def == null) {
-                continue;
-            }
-            for (Node attr : def.findAll("attr", "class")) {
-                attr.Set("path", def.getText());
-                type.addFilho(attr);
-            }
-        }
-        // Atualiza o tamanho to tipo
-        int size = 0;
+        type.Set("type", id)
+                .Set("value", id);
+
         if (type.Has("size")) {
-            size = type.getInt("size");
-        } else {
-            for (Node attr : type.findAll("attr", "class")) {
-//            System.out.println("Add(" + id + "|" + attr.Get("type") + "):" + attr.childrens().Get(0));
-                size += _sizes.get(attr.childrens().get(0).Get("type"));
-            }
+            _sizes.put(id, type.getInt("size"));
         }
+
         _types.put(id, type);
-        _sizes.put(id, size);
+
+        // Adiciona ao controle de tipos primitivos
         if (type.eq("primitive", "true")) {
             getPrimitiveTypes().put(type.Get("value"), 1);
         }
@@ -98,7 +155,10 @@ public class Types {
      * @return true Se o tipo exiSte
      * @throws Exception caSo tipo não exiSta
      */
-    public static Node Get(String id) {
+    public static Node Get(String id) throws Exception {
+        if (!_types.containsKey(id)) {
+            throw new Exception(String.format("Tipo '%s' não definido.", id));
+        }
         return _types.get(id);
     }
 
@@ -107,19 +167,23 @@ public class Types {
     }
 
     public static void List() {
-        System.out.println("Types:\n" + _types.keySet() + "\n" + _sizes);
+        System.out.println("Types:\n\t" + _sizes);
     }
 
-    public static int Size(String type) {
-//        System.out.println("Size of " + type + ">" + _sizes);
+    public static int Size(String type) throws Exception {
+        if (!_sizes.containsKey(type)) {
+            Node t = Get(type);
+            UpdateSize(t);
+        }
+//        System.out.println("Size of <" + type + ">" + _sizes.);
         return _sizes.get(type);
     }
 
-    public static int Shift(String type, ArrayList<String> path) {
+    public static int Shift(String type, ArrayList<String> path) throws Exception {
         return Shift(type, path.get(path.size() - 1));
     }
 
-    public static int Shift(String type, String attrib) {
+    public static int Shift(String type, String attrib) throws Exception {
 
         Node T = Get(type);
         String attrType;
@@ -150,607 +214,14 @@ public class Types {
         return primitiveTypes.containsKey(type);
     }
 
-    /**
-     * Metodos velhos
-     */
-//    /**
-//     * Retorna verdadeiro se o tipo existir ou lança uma exceção caso contrario
-//     *
-//     * @param type
-//     * @return true se o tipo existe
-//     * @throws Exception caso tipo não exista
-//     */
-//    public static boolean exist(String type) {
-//        return _types.containsKey(type);
-//    }
-//
-//    /**
-//     * Adiciona um tipo primitivo a linguagem
-//     *
-//     * @param tname
-//     * @param tamanho quantidade de palavras que precisa para armazenamento em
-//     * memoria
-//     */
-//    public static void add(String tname, int tamanho) {
-//        Node n = new Node(tname);
-//        n.Set("primitive", "t");
-//        _types.put(tname, n);
-//        _sizes.put(tname, tamanho);
-//    }
-//
-//    /**
-//     * Adiciona um tipo a linguagem
-//     *
-//     * @param tname
-//     * @param tipo Node com dados do tipo
-//     * @param pl
-//     */
-//    public static void add(String tname, Node tipo, HashMap<String, String> pl) throws Exception {
-//        int Set = 0, _ts;
-//        tipo.Set("primitive", "f");
-//        _types.put(tname, tipo);
-//        _propList.put(tname, pl);
-//
-//        for (Node prop : tipo.childrens()) {
-//            for (Node var : prop.find("vars").childrens()) {
-//                _ts = size(var) * sumIndexes(var);
-//                _offsetList.put(tname + "." + var.getText(), _ts);
-//                var.Set("size", _ts);
-//                Set += _ts;
-//            }
-//        }
-//        tipo.Set("size", Set);
-//        _sizes.put(tname, Set);
-//    }
-//
-//    protected static int sumIndexes(Node var) throws Exception {
-//        int sum = 1, tmp;
-//        Node indexes = var.find("indexes");
-//
-//        if (indexes != null) {
-//            for (Node index : indexes.childrens()) {
-//                if (index.isNumber("value")) {
-//                    tmp = index.getInt("value");
-//                } else {
-//                    tmp = Constantes.intVal(index);
-//                }
-//                sum *= tmp;
-//            }
-//        }
-//        return sum;
-//    }
-//
-//    public static int size(Node prop) throws Exception {
-//        return size(prop.Get("type"));
-//    }
-//
-//    public static int size(String type) throws Exception {
-//        if (type.contains("*")) {
-//            return Types.SIZE_POINTER;
-//        }
-//
-//        if (!exist(type)) {
-//            throw new Exception("Type " + type + " not defined!");
-//        }
-//        return _sizes.Get(type);
-//    }
-//
-//    /**
-//     * Retorna o tipo com base no valor, apenas funciona com tipos primitivos
-//     * com exceção de thread
-//     *
-//     * @param valor
-//     * @return
-//     */
-//    public static String byValue(String value) {
-//
-//        Pattern p = Pattern.compile("(true|false)", Pattern.CASE_INSENSITIVE);
-//
-//        if (value.matches("-?[0-9]+")) {
-//            return Types.INTEGER;
-//        } else if (p.matcher(value).matches()) {
-//            return Types.BOOLEAN;
-//        } else if (value.matches("'.'")) {
-//            return Types.CHAR;
-//        } else if (value.matches("\".*\"")) {
-//            return Types.STRING;
-//        }
-//
-//        return Types.UNDEFINED;
-//    }
-//
-//    public static int offset(String type, String prop) throws Exception {
-//        if (!exist(type)) {
-//            throw new Exception("Type " + type + " not defined!");
-//        }
-//        int offset = 0;
-//
-//        if (_propList.Get(type).containsKey(prop)) {
-//            offset = _offsetList.Get(type + "." + prop);
-//        }
-//
-//        return offset;
-//
-////        for (Map.Entry<String, String> i : .entrySet()) {
-////            if (i.getKey().equals("prop")) {
-////                return i.getValue()
-////            }
-////            break;
-////        }
-//    }
-//
-//    public static String typeOfProp(String type, String prop) throws Exception {
-//
-//        if (!exist(type)) {
-//            throw new Exception("Type " + type + " not defined!");
-//        }
-//
-//        String t = "undefined";
-//
-//        if (_propList.Get(type).containsKey(prop)) {
-//            t = _propList.Get(type).Get(prop);
-//        }
-//
-//        return t;
-//    }
-//
-//    /**
-//     *
-//     *
-//     * Daqui pra cima
-//     *
-//     *
-//     *
-//     */
-////    /**
-////     * Checa se um valor e de um determinado tipo
-////     *
-////     * @param tipo tipo esperado
-////     * @param valor valor a ser testado
-////     * @return true | false
-////     */
-////    public static boolean testeTipoValor(String tipo, String valor) {
-////        switch (tipo) {
-////            case "int":
-////                return valor.matches("-?[0-9]+");
-////            case "bool":
-////                return valor.matches("(TRUE|FALSE)");
-////            case "char":
-////                return valor.matches("'.'");
-////            case "string":
-////                return valor.matches("\".*\"");
-////            case "void":
-////                return valor.equals("") || valor.equals("void");
-////            case "thread":
-////            case "undefined":
-////                return false;
-////        }
-////        return true;
-////    }
-////    public static Node Get(String tipo) {
-////        tipo = clearName(tipo);
-////        if (_types.containsKey(tipo)) {
-////            return _types.Get(tipo);
-////        }
-////        return null;
-////    }
-////
-////    public static String clearName(String tipo) {
-////        return tipo.replace("*", "");
-////    }
-////
-////    /**
-////     * Remove o nome list do tipo.
-////     *
-////     * @param nome
-////     * @return
-////     */
-////    protected static String baseName(String nome) {
-////        return nome.replace("*", "");
-////    }
-////
-//////    public static String tipoOfMatrixAccess() {
-//////
-//////    }
-////    public static String tipoMatrixAcesso(String acesso, String tipo) {
-////        int indices = Api.countRegexOcorrences("\\[[0-9A-Za-z_\\(.*\\)]+\\]", acesso);
-////        int numinde = (Api.countRegexOcorrences("\\*", tipo) - indices);
-//////        int numinde = (Api.countChatOcorrece(tipo, '*') - indices);
-//////        System.out.println("num:" + numinde + "::" + indices);
-////        String t = baseName(tipo);
-////        if (numinde > 0) {
-////            t += String.format("%0" + numinde + "d", 0).replace("0", "*");
-////        }
-////        return t;
-////    }
-////
-////    public static String tipoDe(Node n, String tipo) throws Exception {
-////        if (ePrimitivo(tipo)) {
-////            return (n.igual("matrix", "true"))
-////                    ? tipoMatrixAcesso(n.getText(), tipo) : tipo;
-////
-////        }
-////        if (n.temAtributo("fullAccess")) {
-////            return byAcesso(n);
-////        } else if (n.igual("class", "dec::var")) {
-////            return tipo;
-////        }
-////        return tipo;
-////    }
-////
-////    public static String tipoDe(String acesso, String tipo) throws Exception {
-//////        tipo = baseName(tipo);
-////        String[] lista = acesso.split("\\.");
-////        ArrayList<String> a = new ArrayList<>(Arrays.asList(lista));
-////        // Se for acesso a um atributo de uma variavel
-////        if (a.size() > 1) {
-////            //Remove a base do nome da variavel
-////            a.remove(0);
-////            return tipoDe(a, tipo);
-////        } else {
-////            return tipo;
-////        }
-////
-////    }
-////
-////    public static String tipoDe(ArrayList<String> parts, String tipo) throws Exception {
-////
-////        if (tipo.equals("magica")) {
-////            return "undefined";
-////        }
-////
-////        String esperado;
-////        if (!exist(tipo)) {
-////            throw new Exception("Tipo inválido. Tipo {" + baseName(tipo) + "} não existe ou não foi declarado!");
-//////            return "undefined";
-////        }
-////
-////        String atributo = parts.remove(0);
-////
-////        if (!temAtributo(tipo, atributo)) {
-////            throw new Exception("Tentando acessar um atributo {" + atributo + "} não existente no {" + baseName(tipo) + "}!");
-////        }
-////        esperado = getTipoAtributo(tipo, atributo);
-//////        System.out.println("TIPO_ESPERADO:[" + atributo + "]" + esperado);
-////
-////        if (parts.size() != 0) {
-////            if (ePrimitivo(esperado)) {
-////                throw new Exception("Tentativas de acessar um atributo {" + atributo
-////                        + "} de um tipo primitivo { " + esperado + " } não são permitidas");
-////            }
-////            esperado = tipoDe(parts, esperado);
-////        }
-//////        System.out.println("atributo::" + atributo);
-////        if (atributo.matches(".*(\\[.*\\])+")) {
-////            esperado = esperado.replace("*", "");
-////        }
-////        return esperado;
-////    }
-////
-////    public static boolean ePrimitivo(String tipo) {
-////        tipo = baseName(tipo);
-////        return primitives.containsKey(tipo);
-////    }
-////
-////    public static String getTipoAtributo(String tipo, String atributo) {
-////        tipo = baseName(tipo);
-////        atributo = ivannosysUtils.clearName(atributo);
-////        Node attrib = _types.Get(tipo).first().encontre(atributo);
-////        return (null == attrib) ? "undefined" : attrib.Get("tipo");
-////    }
-////
-////    /**
-////     * Verifica se um tipo possui um determinado atributo.
-////     *
-////     * @param tipo nome do tipo
-////     * @param atributo atributo a ser identificado
-////     * @return true | false
-////     */
-////    public static boolean temAtributo(String tipo, String atributo) {
-////        tipo = baseName(tipo);
-////        if (!exist(tipo)) {
-////            return false;
-////        }
-////        atributo = ivannosysUtils.clearName(atributo);
-//////        System.out.println("TemATRIBUTO:" + tipo + ":" + atributo);
-////        if (!_types.containsKey(tipo)) {
-////            return false;
-////        }
-////        Node declaracao = _types.Get(tipo).first().encontre(atributo);
-////        return !(declaracao == null);
-//////        if (declaracao == null) {
-//////            return false;
-//////        }
-//////        return true;
-////    }
-////
-////    /**
-////     *
-////     * @param dec variavel node
-////     * @return quantidade de palavras de um tipo
-////     * @throws Exception caso o tipo não exista ou caso o indice seja uma
-////     * contante e a mesma não exista
-////     */
-////    public static int tamanho(Node dec) {
-////        int count = 1;
-////
-////        if (dec.igual("matrix", "true")) {
-////            for (Node indice : dec.encontre("indices").filhos()) {
-////                count *= __indiceValor(indice);
-////            }
-////        }
-////
-////        return tamanho(dec.Get("tipo"), count);
-////    }
-////
-////    /**
-////     * Retorna o valor do indice de um vetor ou uma matrix, valor inteiro. Caso
-////     * seja uma constante o valor e substituido pelo valor da constante caso
-////     * exista, caso contrario é lançado uma exceção para constante indefinida.
-////     *
-////     * @param indice
-////     * @return
-////     * @throws Exception
-////     */
-////    protected static int __indiceValor(Node indice) {
-////        int sizet = 0;
-////        String indValor;
-////        if (indice.isNumber("value")) {
-////            try {
-////                sizet = indice.getInt("value");
-////            } catch (Exception ex) {
-////                Logger.getLogger(Types.class.getName()).log(Level.SEVERE, null, ex);
-////            }
-////        } else {
-////            indValor = indice.getText();
-////            Constantes.existe(indValor);
-//////            sizet = Constantes.intVal(indValor);
-////        }
-////        return sizet;
-////    }
-////
-////    /**
-////     *
-////     * @param tipo identificador do tipo
-////     * @return quantidade de palavras de um tipo
-////     * @throws Exception caso o tipo não exista
-////     */
-////    public static int tamanho(String tipo, int vetorSize) {
-////        return _size(tipo, vetorSize);
-////    }
-////
-////    /**
-////     *
-////     * @param tipo identificador do tipo
-////     * @return quantidade de palavras de um tipo
-////     * @throws Exception caso o tipo não exista
-////     */
-////    public static int tamanho(String tipo) {
-////        return _size(tipo, 1);
-////    }
-////
-////    protected static int _size(String tipo, int vetorSize) {
-////        tipo = baseName(tipo);
-////
-//////        System.out.println("Tamanho:{" + tipo + "}{" + vetorSize + "} {" + tamanhos.Get(tipo) + "}");
-//////        System.out.println("tamanhos:" + tamanhos);
-////        return (exist(tipo) ? _sizes.Get(tipo) * vetorSize : -1);
-////    }
-////
-////
-////
-//////    public static void testeTipoLista(String retornoTipo, HashMap<String, String> retornos, String escopo) {
-//////        for (Map.Entry<String, String> en : retornos.entrySet()) {
-//////            String tipo = en.getValue();
-//////            String[] nome = en.getKey().split(":");
-////////            System.out.println("TIPO:" + tipo + ":" + nome[0] + ":" + escopo + "\n");
-//////            if (tipo.equals("undefined")) {
-////////                System.out.println("==>" + nome[0] + "--" + escopo);
-////////                tipo = Variaveis.getVariavelCascade(nome[0], escopo).getTipo();
-////////                Node n = Variaveis.find(nome[0], escopo);
-//////                tipo = (n == null) ? "undefined" : n.Get("tipo");
-//////
-//////            }
-//////            if (!tipo.equals(retornoTipo)) {
-//////                System.out.println("ERROR:Linha[" + nome[1] + "]Incorreto retorno tipo[" + tipo + "] esperando [" + retornoTipo + "]");
-//////            }
-//////        }
-//////    }
-////    public static int tamanhoVariavel(Node var) throws Exception {
-////
-////        int size = Types.tamanho(var);
-////
-////        if (var.igual("matrix", "true")) {
-////            Node declaracao = ast.encontreDeclaracao(var, var.parent);
-////            Node indices = getIndicesDaMatriz(declaracao);
-////            for (Node ind : indices.filhos()) {
-////                size = size * ind.getInt("value");
-////            }
-////        }
-////        return size;
-////    }
-////
-////    protected static Node getIndicesDaMatriz(Node n) {
-////        if (n.igual("class", "assign::op")) {
-////            n = n.first();
-////        }
-////        return n.encontre("indices");
-////    }
-////
-////    /**
-////     * Valida acesso a um atributo de uma determinada variavel do tipo estrutura
-////     *
-////     * @param current
-////     */
-////    public static void validarAtribuicao(Node current, String atribuicao) throws Exception {
-////        Types.temAtributo(null, null);
-////        String tipoEsperado = tipoDe(atribuicao, atribuicao);
-////        String tipoAtribuido = porValor(atribuicao);
-////        if (!tipoEsperado.equals(tipoAtribuido)) {
-////            throw new Exception("Atribuição invalida tipo esperado {" + tipoEsperado + "} e o tipo atribuido foi{" + tipoAtribuido + "}");
-////        }
-////    }
-////
-////    static boolean structAcesso(String varpath) {
-////        return varpath.indexOf(".") >= 0;
-////    }
-////
-////    public static ArrayList<String> getIndices(Node acesso) {
-//////        System.out.println("tipos:_intd:" + acesso);
-////        ArrayList<String> indices = new ArrayList<>();
-////
-////        if (acesso.igual("class", "atributo")) {
-////            String tipo = acesso.parent.Get("tipo");
-////            if (exist(tipo)) {
-////                Node t = _types.Get(tipo).encontre("variaveis").encontre(ivannosysUtils.clearName(acesso.getText()));
-////                for (Node n : t.encontre("indices").filhos()) {
-////                    indices.add(n.getText());
-////                }
-////            }
-////        } else {
-////            indices = acesso.getList("indices");
-////        }
-////        return indices;
-////
-////    }
-////
-////    public static ArrayList<String> getIndicesOfAttrib(String tipo, ArrayList<String> parts) {
-////        ArrayList<String> lista = new ArrayList<>();
-////        Node t = _types.Get(tipo);
-////        String attrOrigin = parts.remove(0);
-////        String attr = ivannosysUtils.clearName(attrOrigin);
-////        Node atributo = t.first().encontre(attr);
-////        /*Equanto houver atributo segue com recursao, caso seja o ultimo sera avaliado*/
-////        if (!parts.isEmpty()) {
-////            if (!Types.temAtributo(tipo, attr)) {
-////                return lista;
-////            }
-////            if (atributo.igual("matrix", "true")) {
-////                ArrayList<String> indices = getIndicesOfAttrib(tipo, parts);
-////
-////            }
-////            return getIndicesOfAttrib(atributo.Get("tipo"), parts);
-////        }
-////
-////        if (atributo.igual("matrix", "true")) {
-////            for (Node indice : atributo.encontre("indices").filhos()) {
-////                lista.add(indice.getText());
-////            }
-////        }
-////        return lista;
-////
-////    }
-////
-////    public static void avaliarIndices(Node current, ArrayList<String> decindices, boolean eDeclaracao) {
-////        int i = 0, limit, acesso;
-////
-////        System.out.println("xxxx:" + decindices);
-////        try {
-////            for (Node indice : current.filhos()) {
-//////                System.out.println("decindices.Get(i++):" + decindices.Get(i));
-////                limit = Integer.parseInt(decindices.Get(i++));
-////                if (!indice.isNumber("value")) {
-////                    AnalizadorSemantico.testExist(indice);
-////                    continue;
-////                }
-////                if (eDeclaracao) {
-////                    continue;
-////                }
-////                acesso = indice.getInt("value");
-////                if (acesso >= limit || acesso < 0) {
-////                    AnalizadorSemantico.addErroComPosicao("Acesso indevido a um array, limite {"
-////                            + (limit - 1) + "} enquanto a tentativa foi {"
-////                            + acesso + "} na posição {" + i + "}");
-////                }
-////            }
-////        } catch (Exception ex) {
-//////            Logger.getLogger(AnalizadorSemantico.class.getName()).log(Level.SEVERE, null, ex);
-////            AnalizadorSemantico.addErroComPosicao(ex.getMessage());
-//////            System.err.println(e.getMessage());
-////            ex.printStackTrace();
-////        }
-////    }
-////
-////    public static int validarAcesso(Node current) {
-////
-////        return 1;
-////
-////    }
-////
-////    /**
-////     * Retorna o tipo de um atributo a partir do no var
-////     *
-////     * @param param
-////     * @return
-////     * @throws Exception
-////     */
-////    public static String byAcesso(Node param) throws Exception {
-////        Node atribute = param.encontreByClass("atributo");
-////        if (null != atribute) {
-////            return byAcesso(atribute);
-////        }
-////        return param.Get("tipo");
-////    }
-////
-////    /**
-////     * Retorna o Node de um atributo de um tipo
-////     *
-////     * @param tipo
-////     * @param atributo
-////     * @return
-////     */
-////    public static Node getAtributo(String tipo, String atributo) {
-////        tipo = baseName(tipo);
-//////        System.out.println("GerATributo::" + tipo + ":::" + atributo);
-////        return _types.Get(tipo).encontre("variaveis").encontre(Variaveis.clearName(atributo));
-////    }
-////
-////    /**
-////     * Retorna o node da ast contendo os dados do tipo declarado
-////     *
-////     * @param tipo
-////     * @return
-////     */
-////    public static Node declaracao(String tipo) {
-////        return _types.Get(tipo);
-////    }
-////
-////    /**
-////     * Retorna o deslocamento ate o endereco base de um atributo dentro de um
-////     * tipo.
-////     *
-////     * @param tipo a ser analisado
-////     * @param atributo atributo do tipo analisado
-////     * @return inteiro referente ao deslocamento ate a base do atributo
-////     * @throws Exception
-////     */
-////    public static int enderecoBase(String tipo, String atributo) throws Exception {
-////        tipo = baseName(tipo);
-////        atributo = Variaveis.clearName(atributo);
-////        Node t = _types.Get(tipo).encontre("variaveis");
-////        int base = 0;
-////        for (Node n : t.filhos()) {
-////            if (n.igual("value", atributo)) {
-////                break;
-////            }
-////            base += Types.tamanho(n);
-////        }
-////        return base;
-////    }
-////
-////    public static String toAsteriscoNotation(Node declaracao, Node atributo) {
-////        String nome = atributo.getText();
-////        String baseTipo = "undefined";
-////
-////        Node decAtributo = declaracao.first().encontre(Variaveis.clearName(nome));
-////
-////        if (decAtributo.igual("matrix", "true")) {
-////
-//////          decAtributo.Get("tipo")  
-////        }
-////
-////        System.out.println("Dec:" + decAtributo + "\natr:" + atributo);
-////
-////        return baseTipo;
-////    }
+    public static String[] getPrimitiveTypesList() {
+        Set<String> set = primitiveTypes.keySet();
+        String[] ret = new String[set.size()];
+        int i = 0;
+        for (String s : set) {
+            ret[i++] = s;
+        }
+        return ret;
+    }
+
 }

+ 23 - 0
src/API/Utils.java

@@ -16,6 +16,7 @@ import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
 import java.util.List;
+import java.util.Objects;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 
@@ -252,6 +253,28 @@ public class Utils {
         return null;
     }
 
+    public static boolean ResolveExprBool(String op, String p1, String p2) throws Exception {
+        return ResolveExprBool(op, Integer.parseInt(p1), Integer.parseInt(p2));
+    }
+
+    public static boolean ResolveExprBool(String op, Integer p1, Integer p2) {
+        switch (op) {
+            case "<":
+                return p1 < p2;
+            case "<=":
+                return p1 <= p2;
+            case ">":
+                return p1 > p2;
+            case ">=":
+                return p1 >= p2;
+            case "==":
+                return Objects.equals(p1, p2);
+            case "!=":
+                return !Objects.equals(p1, p2);
+        }
+        return false;
+    }
+
     public static String ComplementOperation(String op) {
         return Complements.get(op);
     }

+ 3 - 3
src/API/Variables.java

@@ -5,8 +5,8 @@
  */
 package API;
 
-import common.Instruction;
 import ast.Node;
+import common.Instruction;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
@@ -588,7 +588,7 @@ public class Variables {
             for (Node i : v.childrens()) {
                 index += "[" + i.getText() + "]";
             }
-            s.append(var + ": " + index + v.Get("type") + " [" + Public + " " + constant + "]\n");
+            s.append("\t" + var + ": " + index + v.Get("type") + " [" + Public + " " + constant + "]\n");
         }
         System.out.println("Vars:\n" + s.toString());
     }
@@ -601,7 +601,7 @@ public class Variables {
         return var.Get("type");
     }
 
-    public static int Shift(String id) {
+    public static int Shift(String id) throws Exception {
         Node var = Get(id);
         if (var == null) {
             return 0;

+ 61 - 25
src/IntermediaryCode/IRGenerator.java

@@ -61,6 +61,8 @@ public final class IRGenerator implements IRGenInterface {
     };
     public static Pattern AddressOperator = Pattern.compile("(\\&|\\*)");
 
+    protected String[] primitives = Types.getPrimitiveTypesList();
+
     public IRGenerator() throws Exception {
 
     }
@@ -360,7 +362,7 @@ public final class IRGenerator implements IRGenInterface {
 //        FindShiftPath(size, m4, op, path);
     }
 
-    protected int Size(String type) {
+    protected int Size(String type) throws Exception {
         return Types.Size(type) * 4;
     }
 
@@ -702,7 +704,7 @@ public final class IRGenerator implements IRGenInterface {
 //        gerarVariavel(n.Get(label, label));
 //        getLabel("C", n);
 //        if (n.closest("block", "class") != null) {
-//            code.registerVar(n.Get("_return"), 1, DataFrame.TYPE_VAR);
+//            code.registerVar(n.Get("_return"), 1, DataLayout.TYPE_VAR);
 //        }
     }
 
@@ -1124,46 +1126,76 @@ public final class IRGenerator implements IRGenInterface {
             op = Utils.ComplementOperation(op);
         }
 //        return Branch(op, p0, p1, next);
-        Instruction r1 = new Instruction();
+        Instruction r1 = new Instruction().Set("label", n.Get("next"));
 
-        r1.Set("format", "branch")
-                .Set("type", "branch")
-                .Set("op", op)
-                .Set("p1", p0)
-                .Set("p2", p1)
-                .Set("p1value", "" + Api.IsValue(p0))
-                .Set("p2value", "" + Api.IsValue(p1))
-                .Set("label", n.Get("next"));
+        Boolean p0IsValue = Api.IsValue(p0), p1IsValue = Api.IsValue(p1);
+
+        if (p0IsValue && p1IsValue) {
+
+            // Se a expressão for resolvivel e o resultado é positivo
+            // A instrução de saldo é adicionada 
+            if (Utils.ResolveExprBool(op, p0, p1)) {
+                Add(r1.Set("type", "jump").Set("format", "jump"));
+            }
 
+        } else {
+
+            r1.Set("format", "branch")
+                    .Set("type", "branch")
+                    .Set("op", op)
+                    .Set("p1", p0)
+                    .Set("p2", p1)
+                    .Set("p1value", "" + p0IsValue)
+                    .Set("p2value", "" + Api.IsValue(p1));
+            Add(r1);
+        }
 //        System.out.println("Add branch:" + branckInvert.peek() + branckInvert + ">>" + (!branckInvert.isEmpty() && branckInvert.peek()) + "\n" + r1);
-        Add(r1);
         return r1;
     }
 
     protected Instruction Store(String attr) throws Exception {
-        return code.Add(new Instruction().Set("type", "store").Set("format", "memory").Set("p1", attr));
+        return Add(new Instruction().Set("type", "store").Set("format", "memory").Set("p1", attr));
     }
 
     protected Instruction Load(String attr) throws Exception {
-        return code.Add(new Instruction().Set("type", "load").Set("format", "memory").Set("p1", attr));
+        return Add(new Instruction().Set("type", "load").Set("format", "memory").Set("p1", attr));
     }
 
     protected Instruction Add(Instruction i) throws Exception {
 
 //        System.out.println("ADD:" + i);
-        String loop = "" + loopScope.peek();
+        String loop = "" + loopScope.peek(), type, paramValue;
 
-        boolean ignoreLoadStore = !i.in("type", new String[]{"jump", "goto", "label", "pop_param", "pop_return"});
+        boolean temporary,
+                ignoreLoadStore = !i.in("type", new String[]{"jump", "goto", "label"});
 
         // Inseri a carga dos parametros
         if (ignoreLoadStore) {
             for (String param : new String[]{"p1", "p2"}) {
-                if (i.Has(param)
-                        && !i.contem(param, "_T")
-                        && i.eq(param + "value", "false")) {
+                if (!i.Has(param)) {
+                    continue;
+                }
+
+                temporary = i.contem(param, "_T");
+                paramValue = i.Get(param);
+
+                if (!temporary && i.eq(param + "value", "false")) {
+                    Load(paramValue).Set("inloop", loop);
+                }
 
-                    Load(i.Get(param)).Set("inloop", loop);
+                if (i.isNumber(param)) {
+                    continue;
                 }
+
+                if (temporary) {
+                    type = "int32";
+                } else {
+//                    System.out.println("ADD:TYPEOF:" + paramValue + ":" + varGenMap.get(paramValue));
+                    type = Variables.TypeOf(varGenMap.get(paramValue));
+                }
+
+//                System.out.println(param + ".type = " + type);
+                i.Set(param + ".type", type);
             }
         }
         // Adiciona a instrução
@@ -1855,6 +1887,7 @@ public final class IRGenerator implements IRGenInterface {
             argsNum += args.getChildrenCount();
         }
 
+//        System.out.println("GetMETHOD" + n.getText());
         Node def = Functions.Get(n.getText());
         String id = def.getText();
 //        System.out.println("GenCall:" + id + "\n" + def);
@@ -2191,9 +2224,11 @@ public final class IRGenerator implements IRGenInterface {
     }
 
     protected String gerarVariavel(Node n) throws Exception {
-        String id = n.getText();
+        String id = n.getText(), g;
         if (!varGenMap.containsKey(id)) {
-            varGenMap.put(id, gerarVariavelSet(id, n));
+            g = gerarVariavelSet(id, n);
+            varGenMap.put(id, g);
+            varGenMap.put(g, id);
         }
         return varGenMap.get(id);
     }
@@ -2244,8 +2279,10 @@ public final class IRGenerator implements IRGenInterface {
             n.copy("pointer", var);
 
             varGenMap.put(varname, alias);
+            varGenMap.put(alias, varname);
 //            vn = var.Get("scope");
 
+//            System.out.println("var:" + var);
             int size = Types.Size(var.Get("type")), elementCount = 1;
             var.Set("size", size);
 
@@ -2266,12 +2303,11 @@ public final class IRGenerator implements IRGenInterface {
             }
 //            size *= elementCount;
 
-            if (!var.eq("constant", "true") || !var.in("type", new String[]{"int", "char", "bool"})) {
+            if (!var.eq("constant", "true") || !var.in("type", primitives)) {
                 // Adiciona variaveis no frame global ou da funcao
-                (prefix.equals("G") ? code.GData() : code.Block().Data())
+                (prefix.equals("G") ? code.GlobalData() : code.Block().Data())
                         .Add(alias, var, elementCount);
             } else {
-//                System.out.println("var:" + var);
                 alias = var.Get("default.value");
             }
         }

+ 48 - 15
src/IntermediaryCode/IRTemplate.java

@@ -23,30 +23,63 @@ public class IRTemplate implements templates.TemplateDescription {
                         + "{[PAD(block.position,G.addressLen,' ')]':'}"
                         + "{[T(2)]}";
 
-                String end = "{[T(2)]}"
+                String end = " {' --'[comment]}"
+                        + "{[T(2)]}"
                         + "{'  T< '[type]' >'} "
                         + "{[T(2)]}"
                         + "{[basicBlock]}";
 
                 put("label", "{[PAD(global.position,G.addressLen,' ')]':'}{[T(2)]}{'<'[label]'>'}':'");
-                put("assign", base + "{[dst]}' := '{[p1]}{' '[op]' '}{[p2]}{' --'[comment]}" + end);
-                put("pointer_assign", base + "{[dst.pointer]}{[dst]' := '}{[op]}{[p1]}{' --'[comment]}" + end);
-                put("unary", base + " {[dst]} ' := '{[op]' '}{[p1]} {' --'[comment]}" + end);
-                put("copy", base + " {[dst]} ' := '{[p1]} {' --'[comment]}" + end);
-                put("memory", base + " {[type]} ' '{[p1]} {' --'[comment]}" + end);
-                put("jump", base + " 'goto ' {'<'[label]'>'} {' --'[comment]}" + end);
-                put("branch", base + " 'if '{[p1]} {' '[op]' '} {[p2]} ' goto ' {'<'[label]'>'} {' --'[comment]}" + end);
-                put("call", base + " {[dst]' := '} 'call <' {[funcname]} '>, ' {[nump]} {' --'[comment]}" + end);
-                put("return", base + " 'return ' {[p1]} {' --'[comment]}" + end);
-                put("push_param", base + " 'push_param '{[p1]} {' --'[comment]}" + end);
-                put("push_return", base + " 'push_return '{[p1]} {' --'[comment]}" + end);
-                put("pop_param", base + " 'pop_param '{[p1]} {' --'[comment]}" + end);
-                put("pop_return", base + " 'pop_return '{[p1]} {' --'[comment]}" + end);
+                put("assign", base + "{[dst]}' := '{[TYPE('p1')]' '}{[p1]' '}{[op]' '}{[TYPE('p2')]' '}{[p2]}" + end);
+                put("pointer_assign", base + "{[dst.pointer]}{[dst]' := '}{[op]' '}{[TYPE('p1')]' '}{[p1]}" + end);
+                put("unary", base + " {[dst]} ' := '{[op]' '}{[TYPE('p1')]' '}{[p1]}" + end);
+                put("copy", base + " {[dst]} ' := '{[TYPE('p1')]' '}{[p1]}" + end);
+                put("memory", base + " {[type]' '}{[TYPE('p1')]' '}{[p1]}" + end);
+                put("jump", base + " 'goto ' {'<'[label]'>'}" + end);
+                put("branch", base + " 'if '{[TYPE('p1')]' '}{[p1]} {' '[op]' '}{[TYPE('p2')]' '}{[p2]} ' goto ' {'<'[label]'>'}" + end);
+//                put("call", base + " {[dst]' := '} 'call <' {[funcname]} '>, ' {[nump]}" + end);
+                put("call", base + "'call <' {[funcname]} '>, ' {[nump]}" + end);
+                put("return", base + " 'return '{[TYPE('p1')]' '}{[p1]}" + end);
+                put("push_param", base + " 'push_param '{[TYPE('p1')]' '}{[p1]}" + end);
+                put("push_return", base + " 'push_return '{[TYPE('p1')]' '}{[p1]}" + end);
+                put("pop_param", base + " 'pop_param '{[TYPE('p1')]' '}{[p1]}" + end);
+                put("pop_return", base + " 'pop_return '{[TYPE('p1')]' '}{[p1]}" + end);
             }
         };
     }
 
+    public HashMap<String, String> aliases = new HashMap<String, String>() {
+        {
+            put("char", "i8");
+            put("bool", "i8");
+            put("byte", "i8");
+            put("int8", "i8");
+            put("int16", "i16");
+            put("int32", "i32");
+            put("int64", "i64");
+            put("float32", "f32");
+            put("float64", "f64");
+        }
+    };
+
     public HashMap<String, FunctionInterface> Functions() throws Exception {
-        return null;
+        return new HashMap<String, FunctionInterface>() {
+            {
+                put("TYPE", (ctx, args) -> {
+                    String attr = args.get(0) + ".type";
+                    if (!ctx.Has(attr)) {
+                        return "";
+                    }
+
+                    String type = ctx.Get(attr);
+
+                    if (!aliases.containsKey(type)) {
+                        throw new Exception(String.format("Nenhum alias foi definido para o tipo '%s'", type));
+                    }
+
+                    return "(" + aliases.get(type) + ")";
+                });
+            }
+        };
     }
 }

+ 5 - 0
src/Processors/CodeOtimizadorProcessor.java

@@ -98,6 +98,11 @@ public class CodeOtimizadorProcessor implements CodeProcessorInterface {
                 //                        block.CurrentAddress--;
                 //                        instructions.remove();
                 //                    }
+                case "branch":
+//                    if (Utils.re) {
+//                        inst.Set("type", "jump");
+//                    }
+                    break;
             }
             last = inst;
             index++;

+ 23 - 21
src/Processors/RemoveUnusedLabelsProcessor.java

@@ -5,8 +5,8 @@
  */
 package Processors;
 
-import API.Utils;
 import API.CodeProcessorInterface;
+import API.Utils;
 import common.Block;
 import common.Code;
 import common.Instruction;
@@ -36,8 +36,7 @@ public class RemoveUnusedLabelsProcessor implements CodeProcessorInterface {
         Instruction instruction = null;
         block = c.Block();
         currentBlock = block.getName();
-
-        HashMap<String, Integer> rc = c.labelsReferenceCount;
+        HashMap<String, Integer> referenceCount = c.labelsReferenceCount;
         LinkedList<Instruction> instructions = block.Instructions();
         ArrayList<Instruction> remover = new ArrayList();
         Iterator<Instruction> interator = instructions.iterator();
@@ -46,29 +45,31 @@ public class RemoveUnusedLabelsProcessor implements CodeProcessorInterface {
         int position = 0;
 
         System.out.println("block:" + block.getName() + "-------------------------------");
+//        System.out.println("\n\n####referenceCount:" + referenceCount + "\n\n");
 
+        // Salta o primeiro label
+        if (interator.hasNext()) {
+            interator.next();
+        }
         // Remove todos os labels não referenciados
         while (interator.hasNext()) {
             position++;
             last = instruction;
             instruction = interator.next();
 
-//            System.out.println("instruction:" + instruction);
             if (instruction.eq("type", "branch")) {
                 branch = instruction;
                 position = 0;
             }
 
-            if (position == 3 && branch != null && last.eq("type", "jump")) {
+            // Quando salta um jump altera o enredeco para o endereco do jump e inverte o teste
+            if (branch != null && last.eq("type", "jump") && instruction.eq("label", branch.Get("label"))) {
+//                position == 3 && 
 
-//                System.out.println(":" + branch + last);
                 branch.Set("op", Utils.ComplementOperation(branch.Get("op")))
                         .Set("label", last.Get("label"));
                 branch = null;
-//                instructions.remove(last);
-//                interator.remove();
 
-//                interator.remove(last);
                 remover.add(last);
                 remover.add(instruction);
 
@@ -80,24 +81,26 @@ public class RemoveUnusedLabelsProcessor implements CodeProcessorInterface {
                 // Unifica labels sequenciais e atualiza as chamadas dos outros labels
             }
 
+            // A instrucão é um label
             label = instruction.Get("label");
-            if (!rc.containsKey(label) || rc.get(label) == 0) {
+            // Se o label não existe ou não foi referenciado remove
+            if (!referenceCount.containsKey(label) || referenceCount.get(label) == 0) {
+//                System.out.println("Removendo o label " + label);
                 interator.remove();
             }
         }
 
-//        System.out.println("Remover:" + remover);
         Instruction r;
+        // Remove as instruções sinalizadas
         while (!remover.isEmpty()) {
-            r = remover.remove(0);
-            instructions.remove(r);
+            block.Remove(remover.remove(0));
         }
 
         // Remove labels sequenciais
         for (Instruction i : block.Instructions()) {
             if (last != null) {
                 if (i.eq("type", "label") && last.eq("type", "label")) {
-                    UpdateLabel(last.Get("label"), i.Get("label"));
+                    UpdateLabel(c, last.Get("label"), i.Get("label"));
                     last.copy("label", i);
                     remover.add(last);
                 }
@@ -106,14 +109,13 @@ public class RemoveUnusedLabelsProcessor implements CodeProcessorInterface {
         }
 
         while (!remover.isEmpty()) {
-            r = remover.remove(0);
-            instructions.remove(r);
+            block.Remove(remover.remove(0));
         }
     }
 
-    protected void UpdateLabel(String old, String newl) {
+    protected void UpdateLabel(Code c, String old, String newl) {
         HashMap<String, ArrayList<Instruction>> lab;
-        ArrayList<Instruction> labelInstructions;
+//        ArrayList<Instruction> labelInstructions;
         String label;
         // Cria o mapa de labels para o bloco atual caso não exista
         if (!labelMap.containsKey(currentBlock)) {
@@ -132,11 +134,11 @@ public class RemoveUnusedLabelsProcessor implements CodeProcessorInterface {
         } else {
             lab = labelMap.get(currentBlock);
         }
-//            System.out.println("lab:" + lab);
-//        System.out.println("update label:" + old + "." + newl);
+//        System.out.println("lab:" + lab);
+//        System.out.println("update label:" + old + "----" + newl);
 
         if (lab.containsKey(old)) {
-
+//            c.RegisterLabelAddress(old);
             for (Instruction instruction : lab.get(old)) {
                 instruction.Set("label", newl);
             }

+ 6 - 7
src/common/Block.java

@@ -18,7 +18,7 @@ public class Block {
     protected Code code;
     protected HashMap<String, Instruction> labels = new HashMap<>();
     protected HashMap<String, Boolean> dependences = new HashMap<>();
-    protected DataFrame Data;
+    protected DataLayout Data;
     public int BaseAddress = 0;
     public int CurrentAddress = 0;
     public boolean HasCall;
@@ -30,7 +30,7 @@ public class Block {
         BaseAddress = c.Position();
 //        BaseAddress = c.PosicaoLabel;
         this.name = name;
-        Data = new DataFrame(name, code.GData());
+        Data = new DataLayout(name, code.GlobalData());
 
 //        labels = new HashMap<>();
 //        Data = new LinkedHashMap<>();
@@ -80,7 +80,7 @@ public class Block {
      *
      * @return
      */
-    public DataFrame Data() {
+    public DataLayout Data() {
         return this.Data;
     }
 
@@ -89,11 +89,11 @@ public class Block {
      *
      * @return
      */
-    public DataFrame GData() {
-        return this.code.GData();
+    public DataLayout GData() {
+        return this.code.GlobalData();
     }
 
-    public DataFrame Data(DataFrame d) {
+    public DataLayout Data(DataLayout d) {
         return this.Data.copy(d);
     }
 
@@ -103,7 +103,6 @@ public class Block {
 
     public void Update() throws Exception {
         CurrentAddress = 0;
-        System.out.println("Update positions from:" + getName() + "-" + code.Name());
 
         for (Instruction n : instructions) {
 //            System.out.println("Update->:" + CurrentAddress + ":" + code.Position());

+ 6 - 6
src/common/Code.java

@@ -38,7 +38,7 @@ public class Code {
     public Boolean HasCall = false;
     public Block current;
     public Code Parent;
-    public DataFrame Data;
+    public DataLayout Data;
     public HashMap<String, ArrayList<String>> labels = new HashMap<>();
     public HashMap<String, Integer> labelsReferenceCount = new HashMap<>();
     public Integer PosicaoLabel = 0;
@@ -53,7 +53,7 @@ public class Code {
     public Code(String id, AbstractSyntaxTree tree) {
         name = id;
         ast = tree;
-        Data = new DataFrame(id, null);
+        Data = new DataLayout(id, null);
     }
 
     public boolean HasCall() {
@@ -64,14 +64,14 @@ public class Code {
         name = id;
 //        currentBlock = new LinkedList<>();
 //        stmts = new HashMap<>();
-        Data = new DataFrame(id, null);
+        Data = new DataLayout(id, null);
     }
 
-    public DataFrame GData() {
+    public DataLayout GlobalData() {
         return Data;
     }
 
-    public void SetData(DataFrame Data) {
+    public void SetData(DataLayout Data) {
         this.Data = Data;
     }
 
@@ -96,7 +96,7 @@ public class Code {
 //        incEndereco = 0;
 //        ocorrences = new LinkedHashMap<>();
 //        ocorrencesPerBlocks.put(id, ocorrences);
-//        dataFrame = new DataFrame(id);
+//        dataFrame = new DataLayout(id);
 //        dataFrames.put(id, dataFrame);
 //        current = new ArrayList<>();
 //        stmts.put(id, current);

+ 16 - 50
src/common/DataFrame.java

@@ -19,19 +19,19 @@ import java.util.regex.Pattern;
  *
  * @author Eugenio
  */
-public class DataFrame {
+public class DataLayout {
 
     protected String name;
     protected LinkedHashMap<String, Node> values = new LinkedHashMap<>();
     // address guarda o endereço de cada variavel
     protected LinkedHashMap<String, Integer> address = new LinkedHashMap<>();
+    protected boolean initialized = false;
+    protected Pattern normalId = Pattern.compile("(?<id>[\\w_]+)(\\[(?<index>\\w+)\\])?");
+
 //    protected LinkedList<Node> values = new LinkedList<>();//Map< String, String> copy = new TreeMap<>();
 //    protected HashMap<String, Integer> size = new LinkedHashMap<>();
 //    protected HashMap<String, Integer> type = new LinkedHashMap<>();
 //    protected HashMap<String, Integer> _offset_ = new LinkedHashMap<>();
-    protected boolean initialized = false;
-    protected Pattern normalId = Pattern.compile("(?<id>[\\w_]+)(\\[(?<index>\\w+)\\])?");
-
 //    protected static AbstractSyntaxTree ast;
     public static int TYPE_ARGUMENT = 0;
     public static int TYPE_VAR = 1;
@@ -39,13 +39,17 @@ public class DataFrame {
     public static int TYPE_STACK = 3;
 
     public int offsetctrl = 0;
-    protected DataFrame global;
-    // Guarda o tamanho do frame
-    // É atualizado sempre que o mapeamento dos endereços sofre alteração.
 
+    protected DataLayout global;
+
+    // Guarda a quantidade de palavras do frame
+    // É atualizado sempre que o mapeamento dos endereços sofre alteração.
     private int frameSize;
+    // Tamanho de uma palavra de memoria em bytes 
+    // 4 bytes = 32 bits
+    protected int WordInBytes = 4;
 
-    public DataFrame(String name, DataFrame data) {
+    public DataLayout(String name, DataLayout data) {
         this.name = name;
         this.global = data;
     }
@@ -64,7 +68,7 @@ public class DataFrame {
         frameSize += copy.getInt("size");
     }
 
-    public DataFrame Add(String alias, Node var, int elements) throws Exception {
+    public DataLayout Add(String alias, Node var, int elements) throws Exception {
         //        System.out.println("Add global to frame:" + var);
 //        int vSize = 1;
 //        int size = var.getInt("size"), vSize = 1;
@@ -108,7 +112,7 @@ public class DataFrame {
     }
 
 //    public static void setAbstractSyntaxTree(AbstractSyntaxTree ast) {
-//        DataFrame.ast = ast;
+//        DataLayout.ast = ast;
 //    }
     public int Size() {
         return frameSize;
@@ -117,7 +121,7 @@ public class DataFrame {
 //            try {
 //                val += v.getValue().getInt("size");
 //            } catch (Exception ex) {
-//                Logger.getLogger(DataFrame.class.getName()).log(Level.SEVERE, null, ex);
+//                Logger.getLogger(DataLayout.class.getName()).log(Level.SEVERE, null, ex);
 //            }
 //        }
 //        return val;
@@ -178,25 +182,6 @@ public class DataFrame {
             throw new Exception("Invalid offset!");
         }
         return offset;
-
-//        int offset = 0;
-//        try {
-////            String cp = id;
-//            id = normalize(id);
-//
-//            for (Map.Entry<String, Node> x : values.entrySet()) {
-////                System.out.println("Offset:(" + id + ")" + x.getKey());
-//
-//                if (!x.getKey().equals(id)) {
-//                    offset += x.getValue().getInt("size");
-//                    continue;
-//                }
-//                break;
-//            }
-//        } catch (Exception ex) {
-//            Logger.getLogger(DataFrame.class.getName()).log(Level.SEVERE, null, ex);
-//        }
-//        return offset;
     }
 
     protected String normalize(String id) {
@@ -217,7 +202,7 @@ public class DataFrame {
         return id;
     }
 
-    public DataFrame copy(DataFrame data) {
+    public DataLayout copy(DataLayout data) {
         String k;
         for (Map.Entry<String, Node> x : data.values().entrySet()) {
             System.out.println("Copy:" + x.getKey() + "-" + x.getValue());
@@ -246,7 +231,6 @@ public class DataFrame {
             }
         }
         this.values = add;
-//        System.out.println("Replace << " + this.values);
     }
 
     void Remove(String dst) throws Exception {
@@ -276,21 +260,3 @@ public class DataFrame {
     }
 
 }
-
-//    public DataFrame Add(String alias, Node var) throws Exception {
-////        System.out.println("Add global to frame:" + var);
-//        int size = var.getInt("size"), vSize = 1;
-////        boolean isArray = var.eq("array", "true");
-//
-////        if (isArray) {
-////            vSize = Tipos.Size(var.Get("type"));
-////        }
-//        for (int i = 0; i < size; i++) {
-//            values.put(
-//                    alias + "." + i,
-//                    var.copy().Set("size", vSize)
-//            );
-//        }
-//
-//        return this;
-//    }

+ 2 - 1
src/compiler/IVANNOSYS.java

@@ -46,6 +46,7 @@ public class IVANNOSYS {
                             "UTF-8",
                             IvannosysCompiler.INPUT_FILE)
                             .include(".\\src\\samples")
+                            .include(".\\src\\libs")
                             // Especifica a classe de geração de codigo de tres enderecos
                             .IRGenerator(new IRGenerator());
                     // Extensao dos arquivos 
@@ -98,10 +99,10 @@ public class IVANNOSYS {
 
                     // file = "src\\samples\\program.go";
                     // file = "src\\samples\\program.go";
-                    // file = "src\\samples\\program_mult_manycore.go";
                     // file = "src\\samples\\program_mult_jon.go";
 //                    file = "src\\samples\\program_mult.go";
                     file = "src\\samples\\program_jun_bit_count.go";
+//                    file = "src\\samples\\program_jun_mult_manycore.go";
 
                     // Compila o arquivo de entrada
                     COM.Compile(file);

+ 17 - 27
src/compiler/IvannosysCompiler.java

@@ -5,11 +5,11 @@
  */
 package compiler;
 
+import API.Api;
 import API.BuildParams;
 import API.Target;
 import IntermediaryCode.IRGenInterface;
 import ast.AbstractSyntaxTree;
-import ast.Semantic;
 import common.Code;
 import common.ErrorReport;
 import common.Instruction;
@@ -45,24 +45,19 @@ public final class IvannosysCompiler {
     protected String userInput = "";
     protected String encType = "UTF-8";
     protected int inputType = 0;
-    public ArrayList<String> path;
-    public ArrayList<String> pathLibs;
+    public ArrayList<String> path = new ArrayList<>();
     protected ParseTreeWalker walker;
     protected IvannosysListener listener;
     protected IRGenInterface IR;
     protected AbstractSyntaxTree ast;
     protected String ExtensionLibrary = ".go";
-    protected HashMap<String, AbstractSyntaxTree> asts;
     protected IvannosysGrammarParser.InitContext tree;
+    protected HashMap<String, AbstractSyntaxTree> asts = new HashMap<>();
     protected HashMap<String, IvannosysTargetArch> targets = new HashMap<>();
 
     IvannosysCompiler(String enc, int inputType) throws Exception {
         ast = AbstractSyntaxTree.getAbstractSyntaxTree();
-        asts = new HashMap<>();
-        path = new ArrayList<>();
         encType = enc;
-        pathLibs = new ArrayList<>();
-
     }
 
     public IvannosysCompiler IRGenerator(IRGenInterface ir) {
@@ -116,6 +111,7 @@ public final class IvannosysCompiler {
             walker = new ParseTreeWalker();
 
             Log be = new IvannosysVisitor(tree, parser.getTokenNames(), this).Error();
+
             if (be.HasError()) {
                 abortarPorErro(be, "visitor");
                 return this;
@@ -132,18 +128,20 @@ public final class IvannosysCompiler {
                 return this;
             }
 
-            DisplayAST(parser);
+            Api.Update();
+            Api.List();
 
-            Semantic semantic = new Semantic(ast);
+            DisplayAST(parser);
 
-            if (semantic.Execute().HasError()) {
-                abortarPorErro(semantic, "semantic");
-            }
+//            Semantic semantic = new Semantic(ast);
+//
+//            if (semantic.Execute().HasError()) {
+//                abortarPorErro(semantic, "semantic");
+//            }
 //            Funcoes.genCallTree(ast);
             /**
              * Etapa de geração de codigo de 3 enderecos
              */
-
             Log.PrintInfo("TAC", new Instruction().Set("msg", "Gerando código de três endereços"));
 
             Code code = IR.Create(ast);
@@ -227,12 +225,11 @@ public final class IvannosysCompiler {
             IvannosysGrammarParser parser = new IvannosysGrammarParser((TokenStream) tokens);
             IvannosysGrammarParser.InitContext ltree = parser.init(); // begin parsing at init rule
 
-            if (BuildParams.GetFirst("displaParserTree").equals("true")) {
-//            ((ParserRuleContext) ltree).inspect(parser); //mostra a arvore grafica
-                System.out.println(ltree.toStringTree(parser)); // print LISP-style tree
-                displayTree(parser);//mostra a arvore grafica
-            }
-
+//            if (BuildParams.GetFirst("displaParserTree").equals("true")) {
+////            ((ParserRuleContext) ltree).inspect(parser); //mostra a arvore grafica
+//                System.out.println(ltree.toStringTree(parser)); // print LISP-style tree
+//                displayTree(parser);//mostra a arvore grafica
+//            }
             walker.walk(getListener(), ltree); // walk parse tree
         }
         if (inc == 0) {
@@ -248,13 +245,6 @@ public final class IvannosysCompiler {
         return this;
     }
 
-    public IvannosysCompiler includeLib(String srcinput) {
-        if (!pathLibs.contains(srcinput)) {
-            pathLibs.add(srcinput);
-        }
-        return this;
-    }
-
     public String GetFileInPath(String file) {
         this.path.add(0, ".");
         for (String x : this.path) {

+ 46 - 40
src/frontend/Ivannosys/IvannosysListener.java

@@ -142,17 +142,9 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
         scopeStack.pop();
         scopeFile.pop();
         // Extracao de contantes, variaveis, funcoes e metodos
-        if (packageNames.peek().equals("main")) {
-//            ExtractMeta();
-
-            Types.List();
-//            Constantes.List();
-            BuildParams.List();
-            Variables.List();
-            Functions.List();
-            Interfaces.List();
-
-        }
+//        if (packageNames.peek().equals("main")) {
+//
+//        }
         packageNames.pop();
 //        InitConstantes(ctx);
         super.exitInit(ctx); //To change body of generated methods, choose Tools | Templates.
@@ -230,12 +222,14 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
         Node variable,
                 exprs = node.find("exprs"),
                 type = node.find("type");
+
         ArrayList<ArrayList<String>> valuesGroup = new ArrayList<>();
         ArrayList<String> types = new ArrayList<>(), values;
         ArrayList<Node> ids = node.find("ids").childrens();
         ArrayList<ArrayList<Node>> indexes = new ArrayList<>();
 
         if (type != null) {
+//            System.out.println("DeclVar:" + type);
             // Quando declarado normal
             t = type.Get("type");
             for (int k = 0; k < ids.size(); k++) {
@@ -311,6 +305,7 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
             }
         }
 
+//        System.out.println("types:" + types);
         for (Node var : node.find("ids").childrens()) {
             varname = scopeStack.peek() + "." + var.getText();
             t = types.get(i);
@@ -427,11 +422,11 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
 
     public String getTypeOfPrimitive(IvannosysGrammarParser.Primitive_valueContext ctx) {
         if (ctx.T_BOOL_FALSE() != null || ctx.T_BOOL_TRUE() != null) {
-            return Types.BOOLEAN;
+            return "bool";
         } else if (ctx.T_CHAR() != null) {
-            return Types.CHAR;
+            return "char";
         } else if (ctx.T_INTEIRO() != null) {
-            return Types.INTEGER;
+            return "int32";
         }
         return "undefined";
     }
@@ -441,30 +436,35 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
         if (!this.ReadId.peek()) {
             return;
         }
-        String classe = "", type = "", subclasse = "";
-
-        if (ctx.T_BOOL_FALSE() != null || ctx.T_BOOL_TRUE() != null) {
-            type = Types.BOOLEAN;
-            classe = "value";
-            subclasse = "boolean";
+        String classe = "value",
+                type = getTypeOfPrimitive(ctx),
+                subclasse = "";
 
-        } else if (ctx.T_CHAR() != null) {
-            type = Types.CHAR;
-            classe = "value";
-            subclasse = "char";
-        } else if (ctx.T_INTEIRO() != null) {
-            type = Types.INTEGER;
-            classe = "value";
-            subclasse = "integer";
-        } else {
-            System.out.println("Error tipo desconhecido");
+        if (!Types.Primitive(type)) {
+            errors.AddError((Instruction) new Instruction()
+                    .Set("class", "Import")
+                    .Set("msg", "Primitive type undefined.")
+                    .Set("line", ctx.getStart().getLine())
+                    .Set("col", ctx.getStart().getCharPositionInLine()));
             return;
         }
 
+//        if (ctx.T_BOOL_FALSE() != null || ctx.T_BOOL_TRUE() != null) {
+//            type = "bool";
+//            subclasse = "boolean";
+//        } else if (ctx.T_CHAR() != null) {
+//            type = "char";
+//            subclasse = "char";
+//        } else if (ctx.T_INTEIRO() != null) {
+//            type = "int32";
+//            subclasse = "integer";
+//        } else {
+//            return;
+//        }
         astSetCurrentNode(ctx.getText(), ctx);
         astSetAtributo("type", type);
         astSetAtributo("class", classe);
-        astSetAtributo("subclass", subclasse);
+        astSetAtributo("subclass", classe);
         astBaseSet(ctx);
         super.enterPrimitive_value(ctx); //To change body of generated methods, choose Tools | Templates.
     }
@@ -530,15 +530,19 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
         // Adiciona o pacote local se não for um tipo primitivo e não possui um pacote
 
         if (!Types.Primitive(typename)) {
-            // local type
-            if (typename.indexOf(".") < 0) {
+            String pack = packageNames.peek();
+            // Se não tem formato "pacote.tipo"
+            if (typename.indexOf(".") < 0 && !pack.equals("main")) {
+                // local type
                 typename = packageNames.peek() + "." + typename;
-
+//                System.out.println("ExitTypeL:" + typename + "::" + pack);
             } else {
                 // imported type
                 // Carrega pacote se não for o pacote local
                 String[] parts = typename.split("\\.");
-                if (!parts[0].equals(packageNames.peek())) {
+//                System.out.println("ExitType:" + typename + "::" + pack);
+
+                if (!parts[0].equals(pack)) {
                     try {
                         Imports.Load(parts[0]);
                     } catch (Exception ex) {
@@ -546,7 +550,8 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
                         return;
                     }
 
-                    Node imports = ast.getPackage(packageNames.peek()).find("imports");
+                    Node imports = ast.getPackage(pack).find("imports");
+
                     if (imports != null) {
                         Node impt = imports.find(ctx.ltype);
                         if (impt != null) {
@@ -771,7 +776,7 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
 //                astBaseSet(ctx, id);
 //                id.Set("class", "attr");
 //                id.addFilho(type);
-//                attribs.add(id);
+//                attribs.Add(id);
 //            }
 //        }
 //        decl.childrens = attribs;
@@ -868,7 +873,7 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
         if (ctx.receive_type() != null) {
             astSetAtributo("method", "true");
             name = new ArrayList<String>();
-            name.add(packageNames.peek());
+//            name.add(packageNames.peek());
             name.add("method");
             name.add("(" + node.find("receive.type").find("type").Get("type") + ")"); // type
         } else {
@@ -1276,7 +1281,8 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
 
                     funcname = parts[parts.length - 1];
                     name = funcname;
-                    base = packageNames.peek() + ".method.(" + t + ")." + funcname;
+//                    base = packageNames.peek() + ".method.(" + t + ")." + funcname;
+                    base = "method.(" + t + ")." + funcname;
 
                 } else {
                     name = funcname = parts[1];
@@ -1346,7 +1352,7 @@ public class IvannosysListener extends IvannosysGrammarBaseListener {
         } else if (ctx.arguments() != null) {
 //            System.out.println("packageName:" + packageName);
 
-//            Functions.add(, null);
+//            Functions.Add(, null);
 //            base = ctx.primary_expr().getText();
 //            classe = "call";
 //            subclasse = "arguments";

+ 14 - 22
src/frontend/Ivannosys/IvannosysVisitor.java

@@ -13,33 +13,23 @@ import org.antlr.v4.runtime.tree.ParseTree;
 /**
  *
  * @author Eugenio ThiS claSS provideS an empty implementation of
- {@link IvannosysGrammarVisitor}, which can be extended to create a viSitor
- which only needS to handle a SubS of the available methodS.
-
- operationS with no return type.
+ * {@link IvannosysGrammarVisitor}, which can be extended to create a viSitor
+ * which only needS to handle a SubS of the available methodS.
+ *
+ * operationS with no return type.
  */
 public class IvannosysVisitor extends IvannosysGrammarBaseVisitor<String> {
 
-//    protected TabelaDeSimbolos ts;
-//    protected ParseTree tree;
-//    protected Stack<String> escopoStack;
-//    protected Stack<String> matrizStoreStack;
-//    protected ArrayList<String> matrizStoreContainer;
     protected IvannosysCompiler compiler;
-    protected Log errors;
-    protected String extensionLibrary = "ivan";
     protected LinkedList<String> importSequence = new LinkedList<>();
+    protected String extensionLibrary = "go";
+    protected Log errors;
 
     public IvannosysVisitor(ParseTree tree, String[] tokens, IvannosysCompiler comp) throws Exception {
         super();
         errors = new Log();
         compiler = comp;
-//        this.ts = comp.tabSymb;
-//        this.tree = tree;
-//        escopoStack = new Stack<>();
-//        matrizStoreStack = new Stack<>();
-//        matrizStoreContainer = new ArrayList<>();
-
+        System.out.println("IvannosysVisitor");
         this.visit(tree);
     }
 
@@ -52,15 +42,17 @@ public class IvannosysVisitor extends IvannosysGrammarBaseVisitor<String> {
         }
 
         try {
+
             String path = ctx.T_STRING().getText().replace("\"", "");
 
             // Verificar importacao ciclica
             if (importSequence.contains(path)) {
                 return "";
             }
+
             importSequence.add(path);
 
-            Imports.add(path, alias);
+            Imports.Add(path, alias);
 //            System.out.println("Visitor import " + alias + " >> " + path);
 //            compiler.LoadPackage(alias, path.replace("\"", ""));
 //                throw new Exception(String.format("O pacote '%Set' não foi encontrado no path.", path));
@@ -68,10 +60,10 @@ public class IvannosysVisitor extends IvannosysGrammarBaseVisitor<String> {
 
             errors.AddError(
                     (Instruction) new Instruction()
-                    .Set("class", "Import")
-                    .Set("msg", ex.getMessage())
-                    .Set("line", ctx.getStart().getLine())
-                    .Set("col", ctx.getStart().getCharPositionInLine()));
+                            .Set("class", "Import")
+                            .Set("msg", ex.getMessage())
+                            .Set("line", ctx.getStart().getLine())
+                            .Set("col", ctx.getStart().getCharPositionInLine()));
         } finally {
             return super.visitImport_part(ctx); //To change body of generated methods, choose Tools | Templates.
         }

+ 7 - 2
src/grammar/IvannosysGrammar.g4

@@ -163,8 +163,9 @@ def_if_block
 // Fim If -> Ini Lacos
 
 def_for
-    : R_FOR ( for_clause | for_each )? def_block // Like for
+    : R_FOR (for_clause | for_each | test ) def_block // Like for
     ;
+
 for_clause
     : (initialization R_PT_VIRG)? test (R_PT_VIRG increment)?
     ;
@@ -173,6 +174,9 @@ initialization
     :base_stmt
     ;
 
+empty_block
+    : R_COL_E R_COL_D
+    ;
 test 
     : expression
     | base_stmt (R_PT_VIRG expression)? 
@@ -305,7 +309,8 @@ expression_seletor
 
 // Definicao de um bloco de instrucoes
 def_block locals[HashMap<String, String> retornos = new HashMap<>();]
-    : R_COL_E statement+ R_COL_D
+    : R_COL_E statement* R_COL_D
+    //|empty_block
     ;
 
 callExpr:

+ 13 - 0
src/grammar/IvannosysGrammarBaseListener.java

@@ -939,6 +939,19 @@ public class IvannosysGrammarBaseListener implements IvannosysGrammarListener {
 	 */
 	@Override public void exitArguments(@NotNull IvannosysGrammarParser.ArgumentsContext ctx) { }
 
+	/**
+	 * {@inheritDoc}
+	 *
+	 * <p>The default implementation does nothing.</p>
+	 */
+	@Override public void enterEmpty_block(@NotNull IvannosysGrammarParser.Empty_blockContext ctx) { }
+	/**
+	 * {@inheritDoc}
+	 *
+	 * <p>The default implementation does nothing.</p>
+	 */
+	@Override public void exitEmpty_block(@NotNull IvannosysGrammarParser.Empty_blockContext ctx) { }
+
 	/**
 	 * {@inheritDoc}
 	 *

+ 8 - 0
src/grammar/IvannosysGrammarBaseVisitor.java

@@ -584,6 +584,14 @@ public class IvannosysGrammarBaseVisitor<T> extends AbstractParseTreeVisitor<T>
 	 */
 	@Override public T visitArguments(@NotNull IvannosysGrammarParser.ArgumentsContext ctx) { return visitChildren(ctx); }
 
+	/**
+	 * {@inheritDoc}
+	 *
+	 * <p>The default implementation returns the result of calling
+	 * {@link #visitChildren} on {@code ctx}.</p>
+	 */
+	@Override public T visitEmpty_block(@NotNull IvannosysGrammarParser.Empty_blockContext ctx) { return visitChildren(ctx); }
+
 	/**
 	 * {@inheritDoc}
 	 *

+ 11 - 0
src/grammar/IvannosysGrammarListener.java

@@ -793,6 +793,17 @@ public interface IvannosysGrammarListener extends ParseTreeListener {
 	 */
 	void exitArguments(@NotNull IvannosysGrammarParser.ArgumentsContext ctx);
 
+	/**
+	 * Enter a parse tree produced by {@link IvannosysGrammarParser#empty_block}.
+	 * @param ctx the parse tree
+	 */
+	void enterEmpty_block(@NotNull IvannosysGrammarParser.Empty_blockContext ctx);
+	/**
+	 * Exit a parse tree produced by {@link IvannosysGrammarParser#empty_block}.
+	 * @param ctx the parse tree
+	 */
+	void exitEmpty_block(@NotNull IvannosysGrammarParser.Empty_blockContext ctx);
+
 	/**
 	 * Enter a parse tree produced by {@link IvannosysGrammarParser#literal_value}.
 	 * @param ctx the parse tree

File diff suppressed because it is too large
+ 781 - 726
src/grammar/IvannosysGrammarParser.java


+ 7 - 0
src/grammar/IvannosysGrammarVisitor.java

@@ -512,6 +512,13 @@ public interface IvannosysGrammarVisitor<T> extends ParseTreeVisitor<T> {
 	 */
 	T visitArguments(@NotNull IvannosysGrammarParser.ArgumentsContext ctx);
 
+	/**
+	 * Visit a parse tree produced by {@link IvannosysGrammarParser#empty_block}.
+	 * @param ctx the parse tree
+	 * @return the visitor result
+	 */
+	T visitEmpty_block(@NotNull IvannosysGrammarParser.Empty_blockContext ctx);
+
 	/**
 	 * Visit a parse tree produced by {@link IvannosysGrammarParser#literal_value}.
 	 * @param ctx the parse tree

+ 19 - 0
src/libs/sync/sync.go

@@ -0,0 +1,19 @@
+package sync;
+
+type Mutex struct {
+    locked bool 
+}
+
+func (m *Mutex) Lock(){
+    if !m.locked {
+        // Se não está travado ativa o bloqueio
+        m.locked = true
+    } else {
+        // Se estiver com bloqueio ativo aguarda liberação
+        for ; m.locked ; {}
+    }
+}
+
+func (m *Mutex) Unlock(){
+    m.locked = false
+}

+ 0 - 1
src/samples/program.go

@@ -41,7 +41,6 @@ func laplaciano() {
     var (
         l int
         //LM1,CM1 int
-        
     )
     LM1 := LIN - 1
     CM1 := COL - 1

+ 23 - 10
src/samples/program_jun_bit_count.go

@@ -1,10 +1,11 @@
 // Aplica o back-end do juninho
 @target          : mips 
 // Especifica o tipo de metodo empregado para salvar o resultado da compilação
+//@export          : MultCoreJun
 @export          : simulation
 
 // Diretorio onde o resultado da compilação será gravado
-@outputDirectory : `C:\Users\EUGENIO CARVALHO\Desktop\tmp\comp`
+@outputDirectory : `C:\Users\EUGENIO CARVALHO\Desktop\tmp\bitCount`
 
 // Quantidade de palavras de um bloco 32 palavras de 4bytes
 @cacheBlockSize: `32`
@@ -44,34 +45,48 @@
     }
 ]`
 
+package main;
 
+import "sync"
 
-package main;
+type x struct {
+    a int32
+}
 
-var result = 0
+var (
+    result = 0
+    bolena bool 
+    //mut sync.Mutex
+    x1 x
+)
 
-func bitCount(x int) int {
+
+
+func bitCount(x int32) int {
     n := 0
-    
     if x > 0 {
-        for {
+        for true {
             n++
             if x = x & (x-1); x == 0 {
                     break
             }
         }
     }
+    //mut.Lock()
     result += n
+    //mut.Unlock()
+
     return n
 }
 
-
 func main(){
     var (
 	n     = 0
 	seed  = 10033
     )
     
+    bolena = true
+
     for i := 0; i < 10; i++ {
     //for i := 0; i < 2; i++ {
         n += bitCount(seed)
@@ -80,6 +95,4 @@ func main(){
     }
 
     return n
-}
-/**
-*/
+}

+ 50 - 19
src/samples/program_mult_manycore.go

@@ -1,8 +1,10 @@
 // Aplica o back-end do juninho
-@target          : mipsjun 
+@target          : mips 
+// Especifica o tipo de metodo empregado para salvar o resultado da compilação
+@export          : MultCoreJun
 
 // Diretorio onde o resultado da compilação será gravado
-@outputDirectory : `C:\Users\EUGENIO CARVALHO\Desktop\tmp\comp`
+@outputDirectory : `C:\Users\EUGENIO CARVALHO\Desktop\tmp\laplaciano`
 
 // Quantidade de palavras de um bloco 32 palavras de 4bytes
 @cacheBlockSize: `32`
@@ -46,30 +48,59 @@
 package main;
 
 const (
-    LIN             = 20
-    COL             = 20
-    NUM_LINHAS_MULT = 5
+    LIN = 5
+    COL = 5
 )
 
 var (
-    matrizA [LIN][COL]int
-    matrizB [LIN][COL]int
-    matrizR [LIN][COL]int
+    origin [LIN][COL]int
+    result [LIN][COL]int
 )
 
-func multiplica(initial int) {
-    tmp   := 10
-    aux   := 0
-    x     := tmp + 1
-    limit := initial + NUM_LINHAS_MULT
-    for i := initial; i < x; i++ {
-    //for i := initial; i < limit; i++ {
+func preenche_matriz() {
+    var (
+        w = 1
+        value int
+    )
+    
+    LM1 := LIN - 1
+    CM1 := COL - 1
+
+    for i := 0; i < LIN; i++ {
         for j := 0; j < COL; j++ {
-            for k := 0; k < LIN; k++ {
-                aux = aux + (matrizA[i][k] * matrizB[k][j])
+            switch {
+                case i == 0, i == LM1: // Primeira  e ultima linha
+                    value = 0
+                case j == 0, j == CM1: // Primeira e ultima coluna
+                    value = 0
+                default:               // Elementos do interior da matriz
+                    value = w
+                    w++
             }
-            matrizR[i][j] = aux
-            aux = 0
+            origin[i][j] = value
         }
     }
+}
+
+func laplaciano() {
+    var (
+        l int
+        //LM1,CM1 int
+    )
+    LM1 := LIN - 1
+    CM1 := COL - 1
+
+    for i:= 1; i < LM1; i++ {
+        for j := 1; j < CM1; j++ {
+            l = origin[i-1][j] + origin[i][j-1] + origin[i][j+1] + origin[i+1][j] - (4 * origin[i][j])
+
+            if l > 255 { l = 255 }
+            result[i][j] = l
+        }
+    }
+}
+
+func main() {
+  preenche_matriz()
+  laplaciano()
 }

+ 5 - 5
build/classes/samples/program_mult_manycore.go

@@ -1,8 +1,10 @@
 // Aplica o back-end do juninho
-@target          : mipsjun 
+@target          : mips 
+// Especifica o tipo de metodo empregado para salvar o resultado da compilação
+@export          : MultCoreJun
 
 // Diretorio onde o resultado da compilação será gravado
-@outputDirectory : `C:\Users\EUGENIO CARVALHO\Desktop\tmp\comp`
+@outputDirectory : `C:\Users\EUGENIO CARVALHO\Desktop\tmp\mult`
 
 // Quantidade de palavras de um bloco 32 palavras de 4bytes
 @cacheBlockSize: `32`
@@ -60,10 +62,8 @@ var (
 func multiplica(initial int) {
     tmp   := 10
     aux   := 0
-    x     := tmp + 1
     limit := initial + NUM_LINHAS_MULT
-    for i := initial; i < x; i++ {
-    //for i := initial; i < limit; i++ {
+    for i := initial; i < limit; i++ {
         for j := 0; j < COL; j++ {
             for k := 0; k < LIN; k++ {
                 aux = aux + (matrizA[i][k] * matrizB[k][j])

+ 8 - 8
src/targets/mips/Gen.java

@@ -7,7 +7,7 @@ package targets.mips;
 
 import ast.Node;
 import common.Code;
-import common.DataFrame;
+import common.DataLayout;
 import common.Instruction;
 import common.IvannosysTargetArch;
 import java.util.ArrayList;
@@ -48,7 +48,7 @@ public class Gen extends API.TargetGen {
         super("mips");
     }
 
-    public void Init() {
+    public void Init() throws Exception {
         getTarget().Template(new MipsTemplate());
     }
 
@@ -308,7 +308,7 @@ public class Gen extends API.TargetGen {
 
     @Override
     public void Prolog(String id) throws Exception {
-        DataFrame data = getTarget().Block().Data();
+        DataLayout data = getTarget().Block().Data();
 
         // Copia os dados para block target
         //Updata size in 4 bytes
@@ -372,7 +372,7 @@ public class Gen extends API.TargetGen {
      */
     @Override
     public void Epilog(String id) throws Exception {
-        DataFrame data = getTarget().Block().Data();
+        DataLayout data = getTarget().Block().Data();
         if (!getTarget().Block().getName().equals("main")) {
             // Restaura o fp
             // Restaura o ra
@@ -568,7 +568,7 @@ public class Gen extends API.TargetGen {
     }
 
 //    public void CopyData(LinkedHashMap<String, Node> dst, LinkedHashMap<String, Node> src) throws Exception {
-    public void CopyData(DataFrame dst, DataFrame src) throws Exception {
+    public void CopyData(DataLayout dst, DataLayout src) throws Exception {
         Node value;
         LinkedHashMap<String, Node> svalues = src.values(),
                 dvalues = dst.values();
@@ -590,10 +590,10 @@ public class Gen extends API.TargetGen {
             Init();
 
 //            getTarget().AfterTranslateBlock("copy.dep", new CopyDeps(tac));
-//            CopyData(target.GData().values(), IR.GData().values());
+//            CopyData(target.GlobalData().values(), IR.GlobalData().values());
             CopyData(
-                    target.GData(),
-                    tac.GData()
+                    target.GlobalData(),
+                    tac.GlobalData()
             );
 
         } catch (Exception ex) {

+ 0 - 0
src/targets/mips/MipsOTMinActivationRegister.java


Some files were not shown because too many files changed in this diff