IvannosysCompiler.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package compiler;
  7. import common.SyntaxError;
  8. import common.IvannosysTargetArch;
  9. import API.Api;
  10. import API.BuildParams;
  11. import common.Instruction;
  12. import common.Code;
  13. import IntermediaryCode.IRGenInterface;
  14. import ast.AbstractSyntaxTree;
  15. import ast.Semantic;
  16. import common.ErrorReport;
  17. import common.Log;
  18. import grammar.IvannosysGrammarLexer;
  19. import grammar.IvannosysGrammarParser;
  20. import frontend.Ivannosys.IvannosysListener;
  21. import frontend.Ivannosys.IvannosysVisitor;
  22. import java.io.File;
  23. import java.io.IOException;
  24. import java.util.ArrayList;
  25. import java.util.Arrays;
  26. import java.util.HashMap;
  27. import javax.swing.JFrame;
  28. import javax.swing.JPanel;
  29. import org.antlr.v4.gui.TreeViewer;
  30. import org.antlr.v4.runtime.ANTLRFileStream;
  31. import org.antlr.v4.runtime.ANTLRInputStream;
  32. import org.antlr.v4.runtime.CommonTokenStream;
  33. import org.antlr.v4.runtime.TokenStream;
  34. import org.antlr.v4.runtime.tree.ParseTreeWalker;
  35. /**
  36. *
  37. * @author Eugenio
  38. */
  39. public final class IvannosysCompiler {
  40. public static final int INPUT_FILE = 0;
  41. public static final int INPUT_STREAM = 1;
  42. protected String inputFile = "";
  43. protected String inputStream = "";
  44. protected String encType = "UTF-8";
  45. protected int inputType = 0;
  46. public ArrayList<String> path;
  47. public ArrayList<String> pathLibs;
  48. protected ParseTreeWalker walker;
  49. protected IvannosysListener listener;
  50. protected IvannosysGrammarParser.InitContext tree;
  51. // protected IvannosysVisitor iVisitor;
  52. protected HashMap<String, IvannosysTargetArch> targets = new HashMap<>();
  53. // protected HashMap<String, IvannosysVisitor> visitors;
  54. protected HashMap<String, AbstractSyntaxTree> asts;
  55. protected AbstractSyntaxTree ast;
  56. protected HashMap<String, String> settings;
  57. protected String ExtensionLibrary = ".go";
  58. protected String EnvPathVarName = "IVANPATH";
  59. protected String EnvBinVarName = "IVANBIN";
  60. protected String EnvRootVarName = "IVANROOT";
  61. protected IRGenInterface IR;
  62. IvannosysCompiler(String srcinputprogram, String enc, int inputType) throws Exception {
  63. settings = new HashMap<>();
  64. path = new ArrayList<>();
  65. pathLibs = new ArrayList<>();
  66. // visitors = new HashMap<>();
  67. asts = new HashMap<>();
  68. ast = AbstractSyntaxTree.getAbstractSyntaxTree();
  69. if (inputType == INPUT_STREAM) {
  70. inputStream = srcinputprogram;
  71. } else {
  72. inputFile = srcinputprogram;
  73. }
  74. encType = enc;
  75. initSrcPath();
  76. initOptions();
  77. }
  78. protected IvannosysCompiler RegisterTarget(String id, IvannosysTargetArch target) {
  79. targets.put(id, target);
  80. return this;
  81. }
  82. protected boolean HasTarget(String id) {
  83. return targets.containsKey(id);
  84. }
  85. protected void initSrcPath() throws Exception {
  86. String[] variavies = new String[]{this.EnvPathVarName, this.EnvRootVarName};
  87. for (String variavel : variavies) {
  88. variavel = System.getenv(variavel);
  89. if (variavel == null) {
  90. throw new Exception(String.format("Não encontrou a variável de ambeinte %s.", variavel));
  91. }
  92. include(variavel);
  93. }
  94. }
  95. /**
  96. * StingS.put("clearCode", true);<br>
  97. * StingS.put("developement",falSe);<br>
  98. * StingS.put("diSplayASt", falSe);<br>
  99. * StingS.put("diSplayErroS", falSe);<br>
  100. * StingS.put("diSplaParSerTree", falSe);
  101. *
  102. * @return
  103. */
  104. public IvannosysCompiler initOptions() {
  105. settings.put("clearCode", "true");
  106. settings.put("developement", "false");
  107. settings.put("displayAst", "false");
  108. settings.put("displayErros", "false");
  109. settings.put("displaParserTree", "false");
  110. return this;
  111. }
  112. public IvannosysCompiler SetOption(String prop, String valor) {
  113. settings.put(prop, valor);
  114. return this;
  115. }
  116. public IvannosysCompiler SetClearCode(String lc) {
  117. settings.put("clearCode", lc);
  118. return this;
  119. }
  120. public IvannosysListener getListener() throws Exception {
  121. if (null == listener) {
  122. listener = new IvannosysListener(this);
  123. }
  124. return listener;
  125. }
  126. public IvannosysCompiler Compile() throws IOException, Exception {
  127. try {
  128. // create a CharStream that reads from standard input
  129. ANTLRInputStream input;
  130. if (inputType == INPUT_STREAM) {
  131. input = new ANTLRInputStream(inputStream);
  132. } else {
  133. input = new ANTLRFileStream(inputFile, encType);
  134. }
  135. SyntaxError se = new SyntaxError();
  136. IvannosysGrammarLexer lexer = new IvannosysGrammarLexer(input);
  137. lexer.removeErrorListeners();
  138. lexer.addErrorListener(se);
  139. CommonTokenStream tokens = new CommonTokenStream(lexer);
  140. IvannosysGrammarParser parser = new IvannosysGrammarParser((TokenStream) tokens);
  141. parser.removeErrorListeners();
  142. parser.addErrorListener(se);
  143. tree = parser.init(); // begin parsing at init rule
  144. if (se.HasError()) {
  145. abortarPorErro(se, "parser");
  146. return this;
  147. }
  148. Api.inicializar(this);
  149. listener = getListener();
  150. walker = new ParseTreeWalker();
  151. Log be = new IvannosysVisitor(tree, parser.getTokenNames(), this).Error();
  152. if (be.HasError()) {
  153. abortarPorErro(be, "visitor");
  154. return this;
  155. }
  156. /**
  157. * Etapa de geração da arvore sintatica e analise semantica
  158. */
  159. walker.walk(listener, tree);
  160. be = listener.Error();
  161. if (be.HasError()) {
  162. abortarPorErro(be, "listener");
  163. return this;
  164. }
  165. DisplayAST(parser);
  166. Semantic semantic = new Semantic(ast);
  167. if (semantic.Execute().HasError()) {
  168. abortarPorErro(semantic, "semantic");
  169. }
  170. // Funcoes.genCallTree(ast);
  171. /**
  172. * Etapa de geração de codigo de 3 enderecos
  173. */
  174. Log.PrintInfo("TAC", new Instruction().S("msg", "Gerando código de três endereços"));
  175. Code code = IR.Create(ast, settings);
  176. for (String arch : BuildParams.Get("target")) {
  177. Log.PrintInfo("TAC → TARGET", new Instruction().S("msg", "Gerando código " + arch));
  178. Generate(arch, code);
  179. }
  180. } catch (Exception e) {
  181. System.out.println(e.getMessage());
  182. if (settings.get("developement").equals("true")) {
  183. e.printStackTrace();
  184. }
  185. }
  186. return this;
  187. }
  188. public void Generate(String arch, Code code) throws Exception {
  189. if (!HasTarget(arch)) {
  190. throw new Exception(String.format("Arch '%s' não definida.", arch));
  191. }
  192. this.targets.get(arch)
  193. .SetTAC(code)
  194. .Compile()
  195. .Format()
  196. .Export();
  197. }
  198. protected void DisplayAST(IvannosysGrammarParser parser) {
  199. if (settings.get("displaParserTree").equals("true")) {
  200. // ((ParserRuleContext) tree).inspect(parser);
  201. displayTree(parser);//mostra a arvore grafica
  202. System.out.println(tree.toStringTree(parser)); // print LISP-style tree
  203. }
  204. if (settings.get("displayAst").equals("true")) {
  205. System.out.println("...................................Abstract Syntax Tree");
  206. System.out.println(ast.stringfy());
  207. }
  208. }
  209. protected void displayTree(IvannosysGrammarParser parser) {
  210. JFrame frame = new JFrame("Antlr AST");
  211. JPanel panel = new JPanel();
  212. TreeViewer viewr = new TreeViewer(Arrays.asList(
  213. parser.getRuleNames()), tree);
  214. viewr.setScale(1.5);//scale a little
  215. panel.add(viewr);
  216. frame.add(panel);
  217. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  218. frame.setSize(200, 200);
  219. frame.setVisible(true);
  220. }
  221. protected void abortarPorErro(ErrorReport er, String onde) throws Exception {
  222. System.out.println("Foram encontrados erros durante a compilação[" + onde + "]:");
  223. er.PrintErros();
  224. throw new Exception("Compilação abortada");
  225. }
  226. public IvannosysCompiler LoadPackage(String alias, String path) throws IOException, Exception {
  227. // System.out.println("Carregando biblioteca ......................... " + path);
  228. // System.out.println("Load:" + alias + ":" + path);
  229. String absPath = GetFileInPath(path);
  230. if (absPath == null) {
  231. throw new Exception(String.format("O pacote '%s' não foi encontrado no path.", path));
  232. }
  233. File folder = new File(absPath);
  234. int inc = 0;
  235. for (File file : folder.listFiles()) {
  236. if (!file.isFile()) {
  237. continue;
  238. }
  239. inc++;
  240. // System.out.println("Read file " + file.getAbsolutePath());
  241. ANTLRInputStream input = new ANTLRFileStream(file.getAbsolutePath(), encType);
  242. IvannosysGrammarLexer lexer = new IvannosysGrammarLexer(input);
  243. CommonTokenStream tokens = new CommonTokenStream(lexer);
  244. IvannosysGrammarParser parser = new IvannosysGrammarParser((TokenStream) tokens);
  245. IvannosysGrammarParser.InitContext ltree = parser.init(); // begin parsing at init rule
  246. if (settings.get("displaParserTree").equals("true")) {
  247. // ((ParserRuleContext) ltree).inspect(parser); //mostra a arvore grafica
  248. System.out.println(ltree.toStringTree(parser)); // print LISP-style tree
  249. displayTree(parser);//mostra a arvore grafica
  250. }
  251. walker.walk(getListener(), ltree); // walk parse tree
  252. }
  253. if (inc == 0) {
  254. throw new Exception(String.format("Diretório '%s' não possui arquivos fonte.", absPath));
  255. }
  256. return this;
  257. }
  258. public IvannosysCompiler setDisplayParserTree(boolean b) {
  259. settings.put("displaParserTree", b ? "true" : "false");
  260. return this;
  261. }
  262. public IvannosysCompiler setDisplayErros(boolean b) {
  263. settings.put("displayErros", b ? "true" : "false");
  264. return this;
  265. }
  266. public IvannosysCompiler include(String srcinput) {
  267. if (!path.contains(srcinput)) {
  268. path.add(srcinput);
  269. }
  270. return this;
  271. }
  272. public IvannosysCompiler includeLib(String srcinput) {
  273. if (!pathLibs.contains(srcinput)) {
  274. pathLibs.add(srcinput);
  275. }
  276. return this;
  277. }
  278. public String GetFileInPath(String file) {
  279. this.path.add(0, ".");
  280. for (String x : this.path) {
  281. File f = new File(x + "\\" + file);
  282. if (f.exists() && f.isDirectory()) {
  283. return f.getAbsolutePath();
  284. }
  285. }
  286. return null;
  287. }
  288. public String getExtensionLibrary() {
  289. return ExtensionLibrary;
  290. }
  291. public IvannosysCompiler setExtensionLibrary(String ExtensionLibrary) {
  292. this.ExtensionLibrary = ExtensionLibrary;
  293. return this;
  294. }
  295. public IvannosysCompiler EnvPathVar(String ivanpath) {
  296. this.EnvPathVarName = ivanpath;
  297. return this;
  298. }
  299. public IvannosysCompiler TacGen(IRGenInterface tac) {
  300. this.IR = tac;
  301. return this;
  302. }
  303. }