123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- #include "Compiler.h"
- #include "../Exception.h"
- #include "../data/Stack.h"
- #include "../code/Function.h"
- #include "../code/FloatData.h"
- Compiler::Compiler(string s) : tokenizer(s)
- {
- }
- Compiler::~Compiler()
- {
- }
- void Compiler::compile(Script& sc)
- {
- TokenList tokens;
- try
- {
- tokenizer.tokenize(tokens);
- compile(sc, tokens);
- }
- catch(Exception ex)
- {
- ex.print();
- }
- }
- void Compiler::addInstruction(ArrayList<Instruction*>& code, Stack<Token*>& st, Token* t)
- {
- if(t->getType() == Tokens::FLOAT)
- {
- code.add(new Instruction(0, push, shared_ptr<Data>(new FloatData(t->getFloat()))));
- }
- else if(t->getType() == Tokens::ADD)
- {
- code.add(new Instruction(2, add, nullptr));
- }
- cout << *t << endl;
- }
- void Compiler::compile(Script& sc, TokenList& tokens)
- {
- ArrayList<Instruction*>& code = sc.getInstructions();
- Stack<Token*> st;
- for(int i = 0; i < tokens.getSize(); i++)
- {
- Token* t = tokens.get(i);
- if(t->getType() == Tokens::END_OF_FILE || t->getType() == Tokens::SEMICOLON)
- {
- while(!st.isEmpty())
- {
- addInstruction(code, st, st.pop());
- }
- continue;
- }
- else if(t->getType() == Tokens::OPEN_BRACKET)
- {
- st.push(t);
- continue;
- }
- else if(t->getType() == Tokens::CLOSE_BRACKET)
- {
- while(!st.isEmpty())
- {
- Token* t = st.pop();
- if(t->getType() == Tokens::OPEN_BRACKET)
- {
- break;
- }
- else
- {
- addInstruction(code, st, t);
- }
- }
- continue;
- }
- else if(t->getType() == Tokens::SUB && (st.isEmpty() || st.peek()->getType().getLevel() >= Tokens::UNARY_SUB.getLevel()))
- {
- t->setType(Tokens::UNARY_SUB);
- }
- else if(t->getType() == Tokens::ADD && (st.isEmpty() || st.peek()->getType().getLevel() >= Tokens::UNARY_ADD.getLevel()))
- {
- t->setType(Tokens::UNARY_ADD);
- }
-
- while(!st.isEmpty() && st.peek()->getType().getLevel() <= t->getType().getLevel())
- {
- addInstruction(code, st, st.pop());
- }
- st.push(t);
- }
- }
|