PageRenderTime 47ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/src/org/rascalmpl/library/demo/lang/Pico/Compile.rsc

https://github.com/jimivdw/rascal
Unknown | 91 lines | 66 code | 25 blank | 0 comment | 0 complexity | e1b44503a83b8e32db3059db3b44f0b4 MD5 | raw file
  1. module demo::lang::Pico::Compile
  2. import Prelude;
  3. import demo::lang::Pico::Abstract;
  4. import demo::lang::Pico::Assembly;
  5. import demo::lang::Pico::Load;
  6. alias Instrs = list[Instr]; /*1*/
  7. // compile Expressions.
  8. Instrs compileExp(natCon(int N)) = [pushNat(N)]; /*2*/
  9. Instrs compileExp(strCon(str S)) = [pushStr(substring(S,1,size(S)-1))];
  10. Instrs compileExp(id(PicoId Id)) = [rvalue(Id)];
  11. public Instrs compileExp(add(EXP E1, EXP E2)) = /*3*/
  12. [*compileExp(E1), *compileExp(E2), add2()];
  13. Instrs compileExp(sub(EXP E1, EXP E2)) =
  14. [*compileExp(E1), *compileExp(E2), sub2()];
  15. Instrs compileExp(conc(EXP E1, EXP E2)) =
  16. [*compileExp(E1), *compileExp(E2), conc2()];
  17. // Unique label generation
  18. private int nLabel = 0; /*4*/
  19. private str nextLabel() {
  20. nLabel += 1;
  21. return "L<nLabel>";
  22. }
  23. // Compile a statement
  24. Instrs compileStat(asgStat(PicoId Id, EXP Exp)) =
  25. [lvalue(Id), *compileExp(Exp), assign()];
  26. Instrs compileStat(ifElseStat(EXP Exp, /*5*/
  27. list[STATEMENT] Stats1,
  28. list[STATEMENT] Stats2)){
  29. elseLab = nextLabel();
  30. endLab = nextLabel();
  31. return [*compileExp(Exp),
  32. gofalse(elseLab),
  33. *compileStats(Stats1),
  34. go(endLab),
  35. label(elseLab),
  36. *compileStats(Stats2),
  37. label(endLab)];
  38. }
  39. Instrs compileStat(whileStat(EXP Exp,
  40. list[STATEMENT] Stats1)) {
  41. entryLab = nextLabel();
  42. endLab = nextLabel();
  43. return [label(entryLab),
  44. *compileExp(Exp),
  45. gofalse(endLab),
  46. *compileStats(Stats1),
  47. go(entryLab),
  48. label(endLab)];
  49. }
  50. // Compile a list of statements
  51. Instrs compileStats(list[STATEMENT] Stats1) = /*6*/
  52. [ *compileStat(S) | S <- Stats1 ];
  53. // Compile declarations
  54. Instrs compileDecls(list[DECL] Decls) =
  55. [ ((tp == natural()) ? dclNat(Id) : dclStr(Id)) | /*7*/
  56. decl(PicoId Id, TYPE tp) <- Decls
  57. ];
  58. // Compile a Pico program
  59. public Instrs compileProgram(PROGRAM P){
  60. nLabel = 0;
  61. if(program(list[DECL] Decls, list[STATEMENT] Series) := P){
  62. return [*compileDecls(Decls), *compileStats(Series)];
  63. } else
  64. throw "Cannot happen";
  65. }
  66. public Instrs compileProgram(str txt) = compileProgram(load(txt));