Compiler.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include "Compiler.h"
  2. #include "../Exception.h"
  3. #include "../data/Stack.h"
  4. #include "../code/Function.h"
  5. #include "../code/FloatData.h"
  6. Compiler::Compiler(string s) : tokenizer(s)
  7. {
  8. }
  9. Compiler::~Compiler()
  10. {
  11. }
  12. void Compiler::compile(Script& sc)
  13. {
  14. TokenList tokens;
  15. try
  16. {
  17. tokenizer.tokenize(tokens);
  18. compile(sc, tokens);
  19. }
  20. catch(Exception ex)
  21. {
  22. ex.print();
  23. }
  24. }
  25. void Compiler::addInstruction(ArrayList<Instruction*>& code, Stack<Token*>& st, Token* t)
  26. {
  27. if(t->getType() == Tokens::FLOAT)
  28. {
  29. code.add(new Instruction(0, push, shared_ptr<Data>(new FloatData(t->getFloat()))));
  30. }
  31. else if(t->getType() == Tokens::ADD)
  32. {
  33. code.add(new Instruction(2, add, nullptr));
  34. }
  35. cout << *t << endl;
  36. }
  37. void Compiler::compile(Script& sc, TokenList& tokens)
  38. {
  39. ArrayList<Instruction*>& code = sc.getInstructions();
  40. Stack<Token*> st;
  41. for(int i = 0; i < tokens.getSize(); i++)
  42. {
  43. Token* t = tokens.get(i);
  44. if(t->getType() == Tokens::END_OF_FILE || t->getType() == Tokens::SEMICOLON)
  45. {
  46. while(!st.isEmpty())
  47. {
  48. addInstruction(code, st, st.pop());
  49. }
  50. continue;
  51. }
  52. else if(t->getType() == Tokens::OPEN_BRACKET)
  53. {
  54. st.push(t);
  55. continue;
  56. }
  57. else if(t->getType() == Tokens::CLOSE_BRACKET)
  58. {
  59. while(!st.isEmpty())
  60. {
  61. Token* t = st.pop();
  62. if(t->getType() == Tokens::OPEN_BRACKET)
  63. {
  64. break;
  65. }
  66. else
  67. {
  68. addInstruction(code, st, t);
  69. }
  70. }
  71. continue;
  72. }
  73. else if(t->getType() == Tokens::SUB && (st.isEmpty() || st.peek()->getType().getLevel() >= Tokens::UNARY_SUB.getLevel()))
  74. {
  75. t->setType(Tokens::UNARY_SUB);
  76. }
  77. else if(t->getType() == Tokens::ADD && (st.isEmpty() || st.peek()->getType().getLevel() >= Tokens::UNARY_ADD.getLevel()))
  78. {
  79. t->setType(Tokens::UNARY_ADD);
  80. }
  81. while(!st.isEmpty() && st.peek()->getType().getLevel() <= t->getType().getLevel())
  82. {
  83. addInstruction(code, st, st.pop());
  84. }
  85. st.push(t);
  86. }
  87. }