├── AST_node.cpp ├── AST_node.h ├── AST_node_python.cpp ├── C_lexical.lex ├── C_syntax.yacc ├── LICENSE ├── Makefile ├── README.md ├── c_code ├── calculating_expression.c ├── factorial.c ├── kmp.c ├── matrix.c └── palindrome.c └── main.cpp /AST_node.cpp: -------------------------------------------------------------------------------- 1 | #include "AST_node.h" 2 | #include "C_syntax.hpp" 3 | 4 | extern int yyparse(); 5 | extern BlockExprNode* root; 6 | bool error = false; 7 | 8 | static Value* cast(Value* value, Type* type, GenContext& context); 9 | 10 | Function* printfFunction(GenContext& context) { 11 | vector printfArgs; 12 | printfArgs.push_back(Type::getInt8PtrTy(getGlobalContext())); 13 | FunctionType* printfType = FunctionType::get(Type::getInt32Ty(getGlobalContext()), printfArgs, true); 14 | Function *printfFunc = Function::Create(printfType, Function::ExternalLinkage, Twine("printf"), context.module); 15 | printfFunc->setCallingConv(CallingConv::C); 16 | return printfFunc; 17 | } 18 | 19 | Function* strlenFunction(GenContext& context) { 20 | vector strlenArgs; 21 | strlenArgs.push_back(Type::getInt8PtrTy(getGlobalContext())); 22 | FunctionType* strlenType = FunctionType::get(Type::getInt64Ty(getGlobalContext()), strlenArgs, false); 23 | Function *strlenFunc = Function::Create(strlenType, Function::ExternalLinkage, Twine("strlen"), context.module); 24 | strlenFunc->setCallingConv(CallingConv::C); 25 | return strlenFunc; 26 | } 27 | 28 | Function* isdigitFunction(GenContext& context) { 29 | vector isdigitArgs; 30 | isdigitArgs.push_back(Type::getInt8Ty(getGlobalContext())); 31 | FunctionType* isdigitType = FunctionType::get(Type::getInt1Ty(getGlobalContext()), isdigitArgs, false); 32 | Function *isdigitFunc = Function::Create(isdigitType, Function::ExternalLinkage, Twine("isdigit"), context.module); 33 | isdigitFunc->setCallingConv(CallingConv::C); 34 | return isdigitFunc; 35 | } 36 | 37 | Function* atoiFunction(GenContext& context) { 38 | vector atoiArgs; 39 | atoiArgs.push_back(Type::getInt8PtrTy(getGlobalContext())); 40 | FunctionType* atoiType =FunctionType::get(Type::getInt64Ty(getGlobalContext()), atoiArgs, false); 41 | Function *atoiFunc = Function::Create(atoiType, Function::ExternalLinkage, Twine("atoi"), context.module); 42 | atoiFunc->setCallingConv(CallingConv::C); 43 | return atoiFunc; 44 | } 45 | 46 | void linkExternalFunctions(GenContext& context) { 47 | printfFunction(context); 48 | strlenFunction(context); 49 | isdigitFunction(context); 50 | atoiFunction(context); 51 | } 52 | 53 | void GenContext::CodeGen(BlockExprNode& root) { 54 | vector arg_types; 55 | FunctionType *ftype = FunctionType::get(Type::getVoidTy(getGlobalContext()), makeArrayRef(arg_types), false); 56 | SmallVector attrs; 57 | AttrBuilder builder; 58 | builder.addAttribute(Attribute::NoUnwind); 59 | attrs.push_back(AttributeSet::get(getGlobalContext(), ~0U, builder)); 60 | AttributeSet funcFunc = AttributeSet::get(getGlobalContext(), attrs); 61 | root.CodeGen(*this); 62 | PassManager pm; 63 | raw_string_ostream *out = new raw_string_ostream(code); 64 | pm.addPass(PrintModulePass(*out)); 65 | pm.run(*module); 66 | } 67 | 68 | void GenContext::OutputCode(ostream &out) { 69 | out << code; 70 | } 71 | 72 | GenericValue GenContext::run() { 73 | ExecutionEngine *ee = EngineBuilder(unique_ptr(module)).create(); 74 | vector noargs; 75 | GenericValue v; 76 | ee->finalizeObject(); 77 | mainFunction = module->getFunction("main"); 78 | v = ee->runFunction(mainFunction, noargs); 79 | return v; 80 | } 81 | 82 | static Type *typeOf(VariableExprNode *var) { 83 | Type *type; 84 | if (var->name == "int") 85 | type = Type::getInt64Ty(getGlobalContext()); 86 | else if (var->name == "char") 87 | type = Type::getInt8Ty(getGlobalContext()); 88 | else if (var->name == "double") 89 | type = Type::getDoubleTy(getGlobalContext()); 90 | else if (var->name == "void") 91 | type = Type::getVoidTy(getGlobalContext()); 92 | return type; 93 | } 94 | 95 | Value* VariableExprNode::CodeGen(GenContext& context) { 96 | Value* val; 97 | if (!context.funcDeclaring || context.locals().find(name) == context.locals().end()) { 98 | if (context.globals().find(name) == context.globals().end()) { 99 | cerr << "Undeclared Variable " << name << endl; 100 | return NULL; 101 | } else 102 | val = context.globals()[name]; 103 | } else 104 | val = context.locals()[name]; 105 | if (((AllocaInst*)val)->getAllocatedType()->isArrayTy()) { 106 | ConstantInt* constInt = ConstantInt::get(getGlobalContext(), APInt(32, StringRef("0"), 10)); 107 | vector args; 108 | args.push_back(constInt); 109 | args.push_back(constInt); 110 | Type* type; 111 | type = ((AllocaInst*)val)->getAllocatedType(); 112 | val = GetElementPtrInst::Create(type, val, args, "", context.context()); 113 | return val; 114 | } else 115 | return new LoadInst(val, "", false, context.context()); 116 | } 117 | 118 | Value* CharExprNode::CodeGen(GenContext& context) { 119 | return ConstantInt::get(Type::getInt8Ty(getGlobalContext()), val, true); 120 | } 121 | 122 | Value* IntExprNode::CodeGen(GenContext& context) { 123 | return ConstantInt::get(Type::getInt64Ty(getGlobalContext()), val, true); 124 | } 125 | 126 | Value* DoubleExprNode::CodeGen(GenContext& context) { 127 | return ConstantFP::get(Type::getDoubleTy(getGlobalContext()), val); 128 | } 129 | 130 | Value* BlockExprNode::CodeGen(GenContext& context) { 131 | Value *returnValue = NULL; 132 | for (auto it = statements->begin(); it != statements->end(); it++) 133 | returnValue = (*it)->CodeGen(context); 134 | return returnValue; 135 | } 136 | 137 | Value* OperatorExprNode::CodeGen(GenContext& context) { 138 | Instruction::BinaryOps instr; 139 | ICmpInst::Predicate pred; 140 | bool floatOp = false; 141 | bool mathOP = false; 142 | Value* leftVal = left->CodeGen(context); 143 | Value* rightVal = right->CodeGen(context); 144 | if (leftVal->getType()->isDoubleTy() || rightVal->getType()->isDoubleTy()) { 145 | leftVal = cast(leftVal, Type::getDoubleTy(getGlobalContext()), context); 146 | rightVal = cast(rightVal, Type::getDoubleTy(getGlobalContext()), context); 147 | floatOp = true; 148 | } else if (leftVal->getType() == rightVal->getType()) { 149 | } else { 150 | leftVal = cast(leftVal, Type::getInt64Ty(getGlobalContext()), context); 151 | rightVal = cast(rightVal, Type::getInt64Ty(getGlobalContext()), context); 152 | } 153 | if (!floatOp) { 154 | switch (op) { 155 | case EQ: 156 | pred = ICmpInst::ICMP_EQ; 157 | break; 158 | case NE: 159 | pred = ICmpInst::ICMP_NE; 160 | break; 161 | case GR: 162 | pred = ICmpInst::ICMP_SGT; 163 | break; 164 | case LW: 165 | pred = ICmpInst::ICMP_SLT; 166 | break; 167 | case GE: 168 | pred = ICmpInst::ICMP_SGE; 169 | break; 170 | case LE: 171 | pred = ICmpInst::ICMP_SLE; 172 | break; 173 | case ADD: 174 | case SADD: 175 | instr = Instruction::Add; 176 | mathOP=true; 177 | break; 178 | case SUB: 179 | case SSUB: 180 | instr = Instruction::Sub; 181 | mathOP=true; 182 | break; 183 | case MUL: 184 | case SMUL: 185 | instr = Instruction::Mul; 186 | mathOP=true; 187 | break; 188 | case DIV: 189 | case SDIV: 190 | instr = Instruction::SDiv; 191 | mathOP=true; 192 | break; 193 | case OR: 194 | instr = Instruction::Or; 195 | mathOP=true; 196 | break; 197 | case AND: 198 | instr = Instruction::And; 199 | mathOP=true; 200 | break; 201 | } 202 | } else { 203 | switch (op) { 204 | case EQ: 205 | pred = ICmpInst::FCMP_OEQ; 206 | break; 207 | case NE: 208 | pred = ICmpInst::FCMP_ONE; 209 | break; 210 | case GR: 211 | pred = ICmpInst::FCMP_OGT; 212 | break; 213 | case LW: 214 | pred = ICmpInst::FCMP_OLT; 215 | break; 216 | case GE: 217 | pred = ICmpInst::FCMP_OGE; 218 | break; 219 | case LE: 220 | pred = ICmpInst::FCMP_OLE; 221 | break; 222 | case ADD: 223 | case SADD: 224 | instr = Instruction::FAdd; 225 | mathOP=true; 226 | break; 227 | case SUB: 228 | case SSUB: 229 | instr = Instruction::FSub; 230 | mathOP=true; 231 | break; 232 | case MUL: 233 | case SMUL: 234 | instr = Instruction::FMul; 235 | mathOP=true; 236 | break; 237 | case DIV: 238 | case SDIV: 239 | instr = Instruction::FDiv; 240 | mathOP=true; 241 | break; 242 | } 243 | } 244 | if (mathOP) 245 | return BinaryOperator::Create(instr, leftVal, rightVal, "", context.context()); 246 | else 247 | return new ICmpInst(*context.context(), pred, leftVal, rightVal, ""); 248 | } 249 | 250 | Value* AssignExprNode::CodeGen(GenContext& context) { 251 | Value* rightVal; 252 | Value* leftVal; 253 | if (!context.funcDeclaring || context.locals().find(left->name) == context.locals().end()) { 254 | if (context.globals().find(left->name) == context.globals().end()) 255 | return NULL; 256 | else 257 | leftVal = context.globals()[left->name]; 258 | } 259 | else 260 | leftVal = context.locals()[left->name]; 261 | rightVal = right->CodeGen(context); 262 | if (leftVal->getType() == Type::getInt64PtrTy(getGlobalContext())) 263 | rightVal = cast(rightVal, Type::getInt64Ty(getGlobalContext()), context); 264 | else if (leftVal->getType() == Type::getDoublePtrTy(getGlobalContext())) 265 | rightVal = cast(rightVal, Type::getDoubleTy(getGlobalContext()), context); 266 | else if (leftVal->getType() == Type::getInt8PtrTy(getGlobalContext())) 267 | rightVal = cast(rightVal, Type::getInt8Ty(getGlobalContext()), context); 268 | return new StoreInst(rightVal, leftVal, false, context.context()); 269 | } 270 | 271 | Value* FuncExprNode::CodeGen(GenContext& context) { 272 | // Get functor 273 | Function *function = context.module->getFunction(functor->name.c_str()); 274 | if (function == NULL) 275 | cerr << "No such function " << functor->name << endl; 276 | vector argsRef; 277 | for (auto it = args->begin(); it != args->end(); it++) 278 | argsRef.push_back((*it)->CodeGen(context)); 279 | CallInst *call = CallInst::Create(function, makeArrayRef(argsRef), "", context.context()); 280 | return call; 281 | } 282 | 283 | Value* CastExprNode::CodeGen(GenContext& context) { 284 | Value* value = expr->CodeGen(context); 285 | Type* castType = typeOf(type); 286 | value = cast(value, castType, context); 287 | return value; 288 | } 289 | 290 | Value* IndexExprNode::CodeGen(GenContext& context) { 291 | Value* array = name->CodeGen(context); 292 | Value* num = cast(expr->CodeGen(context), Type::getInt64Ty(getGlobalContext()), context); 293 | num = new TruncInst(num, Type::getInt32Ty(getGlobalContext()), "", context.context()); 294 | Type* arrayType = cast(array->getType()->getScalarType())->getElementType(); 295 | Instruction* instr; 296 | Value* retInst; 297 | instr = GetElementPtrInst::Create(arrayType, array, num, "", context.context()); 298 | // whether read or write 299 | if (assign == NULL) 300 | retInst = new LoadInst(instr, "", false, context.context()); 301 | else 302 | retInst = new StoreInst(assign->CodeGen(context), instr, false, context.context()); 303 | return retInst; 304 | } 305 | 306 | Value* ExprStatementNode::CodeGen(GenContext& context) { 307 | return expr->CodeGen(context); 308 | } 309 | 310 | Value* VarDecStatementNode::CodeGen(GenContext& context) { 311 | Value* newVar; 312 | newVar = new AllocaInst(typeOf(type), name->name.c_str(), context.context()); 313 | context.locals()[name->name] = newVar; 314 | if (expr != NULL) { 315 | AssignExprNode assign(name, expr); 316 | assign.CodeGen(context); 317 | } 318 | return newVar; 319 | } 320 | 321 | Value* ArrayDecStatementNode::CodeGen(GenContext& context) { 322 | ArrayType* arrayType = ArrayType::get(typeOf(type), size); 323 | AllocaInst *alloc = new AllocaInst(arrayType, name->name.c_str(), context.context()); 324 | context.locals()[name->name] = alloc; 325 | if (init->size() != 0) { 326 | for (auto it = init->begin(); it != init->end(); ++it) { 327 | ExprNode* num = new IntExprNode(it - init->begin()); 328 | IndexExprNode a(name, num, (*it)); 329 | a.CodeGen(context); 330 | delete num; 331 | } 332 | } 333 | return alloc; 334 | } 335 | 336 | Value* ReturnStatementNode::CodeGen(GenContext& context) { 337 | return expr->CodeGen(context); 338 | } 339 | 340 | Value* FuncDecStatementNode::CodeGen(GenContext& context) { 341 | // Function type 342 | vector argTypeRef; 343 | for (auto it = args->begin(); it != args->end(); it++) 344 | argTypeRef.push_back(typeOf((*it)->type)); 345 | FunctionType *funcType = FunctionType::get(typeOf(type), ArrayRef(argTypeRef), false); 346 | Function *function = Function::Create(funcType, GlobalValue::ExternalLinkage, name->name.c_str(), context.module); 347 | function->setCallingConv(CallingConv::C); 348 | SmallVector Attrs; 349 | AttrBuilder Builder; 350 | Builder.addAttribute(Attribute::NoUnwind); 351 | Attrs.push_back(AttributeSet::get(getGlobalContext(), ~0U, Builder)); 352 | AttributeSet funcFuncAttrSet = AttributeSet::get(getGlobalContext(), Attrs); 353 | function->setAttributes(funcFuncAttrSet); 354 | context.currentFunction(function); 355 | context.funcDeclaring = true; 356 | // Start function 357 | BasicBlock *funcBlock = BasicBlock::Create(getGlobalContext(), "", function, 0); 358 | context.push(funcBlock, false); 359 | Function::arg_iterator argsValues = function->arg_begin(); 360 | for (auto it = args->begin(); it != args->end(); it++, argsValues++) { 361 | (*it)->CodeGen(context); 362 | Value *argumentValue = &(*argsValues); 363 | argumentValue->setName((*it)->name->name.c_str()); 364 | StoreInst *inst = new StoreInst(argumentValue, context.locals()[(*it)->name->name], false, funcBlock); 365 | } 366 | // Get return value 367 | Value* returnValue = block->CodeGen(context); 368 | context.funcDeclaring = false; 369 | // Return 370 | BasicBlock *returnBlock = BasicBlock::Create(getGlobalContext(), "", function, 0); 371 | BranchInst::Create(returnBlock, context.context()); 372 | ReturnInst::Create(getGlobalContext(), returnValue, returnBlock); 373 | context.pop(); 374 | return function; 375 | } 376 | 377 | Value* ExternFuncDecStatementNode::CodeGen(GenContext& context) { 378 | vector argTypes; 379 | FunctionType *ftype; 380 | Function *function; 381 | for (auto it = args->begin(); it != args->end(); it++) 382 | argTypes.push_back(typeOf((*it)->type)); 383 | ftype = FunctionType::get(Type::getVoidTy(getGlobalContext()), makeArrayRef(argTypes), false); 384 | function = Function::Create(ftype, GlobalValue::ExternalLinkage, name->name.c_str(), context.module); 385 | return function; 386 | } 387 | 388 | Value* IfStatementNode::CodeGen(GenContext& context) { 389 | BasicBlock* ifTrue = BasicBlock::Create(getGlobalContext(), "", context.currentFunction(), 0); 390 | BasicBlock* ifFalse = BasicBlock::Create(getGlobalContext(), "", context.currentFunction(), 0); 391 | BasicBlock* ifEnd = BasicBlock::Create(getGlobalContext(), "", context.currentFunction(), 0); 392 | BranchInst::Create(ifTrue, ifFalse, condExpr->CodeGen(context), context.context()); 393 | // Entering IF 394 | context.push(ifTrue); 395 | trueBlock->CodeGen(context); 396 | // JMP to END 397 | BranchInst::Create(ifEnd, context.context()); 398 | context.pop(); 399 | // Entering ELSE 400 | context.push(ifFalse); 401 | falseBlock->CodeGen(context); 402 | // JMP to END 403 | BranchInst::Create(ifEnd, context.context()); 404 | context.pop(); 405 | // Return END 406 | context.ret(ifEnd); 407 | return ifEnd; 408 | } 409 | 410 | Value* ForStatementNode::CodeGen(GenContext& context) { 411 | // Initialize 412 | initExpr->CodeGen(context); 413 | BasicBlock* forIter = BasicBlock::Create(getGlobalContext(), "", context.currentFunction(), 0); 414 | BasicBlock* forEnd = BasicBlock::Create(getGlobalContext(), "", context.currentFunction(), 0); 415 | BasicBlock* forCheck = BasicBlock::Create(getGlobalContext(), "", context.currentFunction(), 0); 416 | // Check condition satisfaction 417 | BranchInst::Create(forCheck, context.context()); 418 | context.push(forCheck); 419 | // Whether break the loop 420 | BranchInst::Create(forIter, forEnd, condExpr->CodeGen(context), forCheck); 421 | context.pop(); 422 | // Entering loop block 423 | context.push(forIter); 424 | block->CodeGen(context); 425 | // Iteration 426 | loopExpr->CodeGen(context); 427 | // Jump back to condition checking 428 | BranchInst::Create(forCheck, context.context()); 429 | context.pop(); 430 | // Return END 431 | context.ret(forEnd); 432 | return forEnd; 433 | } 434 | 435 | Value* WhileStatementNode::CodeGen(GenContext& context) { 436 | BasicBlock* whileIter = BasicBlock::Create(getGlobalContext(), "", context.currentFunction(), 0); 437 | BasicBlock* whileEnd = BasicBlock::Create(getGlobalContext(), "", context.currentFunction(), 0); 438 | BasicBlock* whileCheck = BasicBlock::Create(getGlobalContext(), "", context.currentFunction(), 0); 439 | // Check condition satisfaction 440 | BranchInst::Create(whileCheck, context.context()); 441 | context.push(whileCheck); 442 | // Whether break the loop 443 | BranchInst::Create(whileIter, whileEnd, whileExpr->CodeGen(context), context.context()); 444 | context.pop(); 445 | // Entering loop block 446 | context.push(whileIter); 447 | block->CodeGen(context); 448 | // Jump back to condition checking 449 | BranchInst::Create(whileCheck, context.context()); 450 | context.pop(); 451 | // Return END 452 | context.ret(whileEnd); 453 | return whileEnd; 454 | } 455 | 456 | static Value* cast(Value* value, Type* type, GenContext& context) { 457 | if (type == value->getType()) 458 | return value; 459 | if (type == Type::getDoubleTy(getGlobalContext())) { 460 | if (value->getType() == Type::getInt64Ty(getGlobalContext()) || value->getType() == Type::getInt8Ty(getGlobalContext())) 461 | value = new SIToFPInst(value, type, "", context.context()); 462 | else 463 | cout << "Cannot cast this value.\n"; 464 | } 465 | else if (type == Type::getInt64Ty(getGlobalContext())) { 466 | if (value->getType() == Type::getDoubleTy(getGlobalContext())) 467 | value = new FPToSIInst(value, type, "", context.context()); 468 | else if (value->getType() == Type::getInt8Ty(getGlobalContext())) 469 | value = new SExtInst(value, type, "", context.context()); 470 | else if (value->getType() == Type::getInt32Ty(getGlobalContext())) 471 | value = new ZExtInst(value, type, "", context.context()); 472 | else if (value->getType() == Type::getInt8PtrTy(getGlobalContext())) 473 | value = new PtrToIntInst(value, type, "", context.context()); 474 | else if (value->getType() == Type::getInt64PtrTy(getGlobalContext())) 475 | value = new PtrToIntInst(value, type, "", context.context()); 476 | else 477 | cout << "Cannot cast this value.\n"; 478 | } else if (type == Type::getInt8Ty(getGlobalContext())) { 479 | if (value->getType() == Type::getDoubleTy(getGlobalContext())) 480 | value = new FPToSIInst(value, type, "", context.context()); 481 | else if (value->getType() == Type::getInt64Ty(getGlobalContext())) 482 | value = new TruncInst(value, type, "", context.context()); 483 | else 484 | cout << "Cannot cast this value.\n"; 485 | } else 486 | cout << "Cannot cast this value.\n"; 487 | return value; 488 | } 489 | -------------------------------------------------------------------------------- /AST_node.h: -------------------------------------------------------------------------------- 1 | #ifndef AST_NODE_H 2 | #define AST_NODE_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | 42 | using namespace llvm; 43 | using namespace std; 44 | 45 | enum E_TYPE { 46 | E_UNKNOWN = -1, 47 | E_VOID = 0, 48 | E_CHAR, 49 | E_INT, 50 | E_DOUBLE, 51 | E_PTR, 52 | E_FUNC, 53 | }; 54 | 55 | class GenBlock { 56 | public: 57 | BasicBlock *block; 58 | map locals; 59 | }; 60 | 61 | class GenBlockP { 62 | public: 63 | GenBlockP(); 64 | set locals; 65 | set declared_globals; 66 | bool isFunction; 67 | }; 68 | 69 | class BlockExprNode; 70 | 71 | class GenContext { 72 | public: 73 | stack blocks; 74 | map globalVariables; 75 | Function *mainFunction; 76 | Function *tempFunction; 77 | string code; 78 | bool funcDeclaring; 79 | Module *module; 80 | public: 81 | GenContext() { 82 | funcDeclaring = false; 83 | module = new Module("main", getGlobalContext()); 84 | } 85 | void CodeGen(BlockExprNode& root); 86 | void OutputCode(ostream &out); 87 | GenericValue run(); 88 | map& locals() { return blocks.top()->locals; } 89 | map& globals() { return globalVariables; } 90 | BasicBlock *context() { return blocks.top()->block; } 91 | Function* currentFunction() { return tempFunction; } 92 | void currentFunction(Function *function) { tempFunction = function; } 93 | void ret(BasicBlock* block) { blocks.top()->block = block; } 94 | void push(BasicBlock *block, bool copy_locals = true) { 95 | GenBlock* new_block = new GenBlock(); 96 | new_block->block = block; 97 | if(copy_locals) { 98 | map prev_locals = map(blocks.top()->locals); 99 | new_block->locals = prev_locals; 100 | } 101 | blocks.push(new_block); 102 | } 103 | void pop() { 104 | GenBlock *top = blocks.top(); 105 | blocks.pop(); 106 | delete top; 107 | } 108 | }; 109 | 110 | class GenContextP { 111 | public: 112 | stack blocks; 113 | set globalVariables; 114 | stringstream code; 115 | stringstream code_buf; 116 | int indent_num; 117 | bool funcDeclaring; 118 | 119 | public: 120 | GenContextP(); 121 | ~GenContextP(); 122 | void CodeGen(BlockExprNode &root); 123 | void OutputCode(ostream &out); 124 | void clearBuf(); 125 | void applyBuf(); 126 | set& locals(); 127 | set& declared_globals(); 128 | set& globals(); 129 | void declare_global(string name); 130 | GenBlockP *currentBlock(); 131 | void PushBlock(bool copy_locals = true, bool isFunction = false); 132 | void popBlock(); 133 | void indent(bool use_buf = true); 134 | void nextLine(bool use_buf = true); 135 | }; 136 | 137 | class ASTNode { 138 | public: 139 | ASTNode() {}; 140 | virtual ~ASTNode(){}; 141 | virtual Value *CodeGen(GenContext&) = 0; 142 | virtual void CodeGenP(GenContextP&) = 0; 143 | }; 144 | 145 | class ExprNode: public ASTNode { 146 | public: 147 | E_TYPE _type; 148 | }; 149 | 150 | class StatementNode: public ASTNode {}; 151 | 152 | class IntExprNode: public ExprNode { 153 | public: 154 | long long val; 155 | public: 156 | IntExprNode(long long val): val(val) { 157 | _type = E_INT; 158 | } 159 | virtual Value *CodeGen(GenContext&); 160 | virtual void CodeGenP(GenContextP&); 161 | }; 162 | 163 | class CharExprNode: public ExprNode { 164 | public: 165 | char val; 166 | public: 167 | CharExprNode(char val): val(val) { 168 | _type = E_CHAR; 169 | } 170 | virtual Value *CodeGen(GenContext&); 171 | virtual void CodeGenP(GenContextP&); 172 | }; 173 | 174 | class DoubleExprNode: public ExprNode { 175 | double val; 176 | public: 177 | DoubleExprNode(double val): val(val) { 178 | _type = E_DOUBLE; 179 | } 180 | virtual Value *CodeGen(GenContext&); 181 | virtual void CodeGenP(GenContextP&); 182 | }; 183 | 184 | class VariableExprNode: public ExprNode { 185 | public: 186 | string name; 187 | public: 188 | VariableExprNode(const string &name, E_TYPE type = E_UNKNOWN): name(name) { 189 | _type = type; 190 | } 191 | virtual Value *CodeGen(GenContext&); 192 | virtual void CodeGenP(GenContextP&); 193 | }; 194 | 195 | class OperatorExprNode: public ExprNode { 196 | public: 197 | int op; 198 | ExprNode *left, *right; 199 | public: 200 | OperatorExprNode(ExprNode *left, int op, ExprNode *right): left(left), right(right), op(op) {} 201 | virtual Value *CodeGen(GenContext&); 202 | virtual void CodeGenP(GenContextP&); 203 | }; 204 | 205 | class BlockExprNode: public ExprNode { 206 | public: 207 | vector *statements; 208 | public: 209 | BlockExprNode(): statements(new vector()) {} 210 | virtual Value *CodeGen(GenContext&); 211 | virtual void CodeGenP(GenContextP&); 212 | }; 213 | 214 | class AssignExprNode: public ExprNode { 215 | public: 216 | VariableExprNode *left; 217 | ExprNode *right; 218 | public: 219 | AssignExprNode(VariableExprNode *left, ExprNode *right): left(left), right(right) {} 220 | virtual Value *CodeGen(GenContext&); 221 | virtual void CodeGenP(GenContextP&); 222 | }; 223 | 224 | class FuncExprNode: public ExprNode { 225 | public: 226 | VariableExprNode *functor; 227 | vector *args; 228 | public: 229 | FuncExprNode(VariableExprNode *functor): functor(functor), args(new vector()) {} 230 | FuncExprNode(VariableExprNode *functor, vector *args): functor(functor), args(args) {} 231 | virtual Value *CodeGen(GenContext&); 232 | virtual void CodeGenP(GenContextP&); 233 | }; 234 | 235 | class CastExprNode: public ExprNode { 236 | public: 237 | VariableExprNode *type; 238 | ExprNode *expr; 239 | public: 240 | CastExprNode(VariableExprNode *type, ExprNode *expr): type(type), expr(expr) {} 241 | virtual Value *CodeGen(GenContext&); 242 | virtual void CodeGenP(GenContextP&); 243 | }; 244 | 245 | class ExprStatementNode : public StatementNode { 246 | public: 247 | ExprNode *expr; 248 | public: 249 | ExprStatementNode(ExprNode *expr): expr(expr) {} 250 | virtual Value *CodeGen(GenContext&); 251 | virtual void CodeGenP(GenContextP&); 252 | }; 253 | 254 | class ReturnStatementNode : public StatementNode { 255 | public: 256 | ExprNode *expr; 257 | public: 258 | ReturnStatementNode(ExprNode *expr): expr(expr) {} 259 | virtual Value *CodeGen(GenContext&); 260 | virtual void CodeGenP(GenContextP&); 261 | }; 262 | 263 | class VarDecStatementNode : public StatementNode { 264 | public: 265 | VariableExprNode *type; 266 | VariableExprNode *name; 267 | ExprNode *expr; 268 | public: 269 | VarDecStatementNode(VariableExprNode *type, VariableExprNode *name): type(type), name(name), expr(NULL) {} 270 | VarDecStatementNode(VariableExprNode *type, VariableExprNode *name, ExprNode *expr): type(type), name(name), expr(expr) {} 271 | virtual Value *CodeGen(GenContext&); 272 | virtual void CodeGenP(GenContextP&); 273 | }; 274 | 275 | class ArrayDecStatementNode : public StatementNode { 276 | public: 277 | VariableExprNode *type; 278 | VariableExprNode *name; 279 | vector *init; 280 | long long size; 281 | bool isString; 282 | public: 283 | ArrayDecStatementNode(VariableExprNode *type, VariableExprNode *name, long long size): type(type), name(name), init(new vector()), size(size), isString(false) {} 284 | ArrayDecStatementNode(VariableExprNode *type, VariableExprNode *name, vector *init): type(type), name(name), init(init), size(init->size()), isString(false) {} 285 | ArrayDecStatementNode(VariableExprNode *type, VariableExprNode *name, const string &str): type(type), name(name), init(new vector()), isString(true) { 286 | for(auto it = str.begin(); it != str.end(); it++) 287 | init->push_back((ExprNode*)(new CharExprNode(*it))); 288 | init->push_back((ExprNode*)(new CharExprNode(0))); 289 | size = init->size() + 1; 290 | } 291 | virtual Value *CodeGen(GenContext&); 292 | virtual void CodeGenP(GenContextP&); 293 | }; 294 | 295 | class IndexExprNode : public ExprNode { 296 | public: 297 | VariableExprNode *name; 298 | ExprNode *expr; 299 | ExprNode *assign; 300 | public: 301 | IndexExprNode(VariableExprNode *name, ExprNode *expr): name(name), expr(expr), assign(NULL) {} 302 | IndexExprNode(VariableExprNode *name, ExprNode *expr, ExprNode *assign): name(name), expr(expr), assign(assign) {} 303 | virtual Value *CodeGen(GenContext&); 304 | virtual void CodeGenP(GenContextP&); 305 | }; 306 | 307 | class FuncDecStatementNode : public StatementNode { 308 | public: 309 | VariableExprNode *type; 310 | VariableExprNode *name; 311 | vector *args; 312 | BlockExprNode *block; 313 | public: 314 | FuncDecStatementNode(VariableExprNode *type, VariableExprNode *name, vector *args, BlockExprNode *block): type(type), name(name), args(args), block(block) {} 315 | virtual Value *CodeGen(GenContext&); 316 | virtual void CodeGenP(GenContextP&); 317 | }; 318 | 319 | class ExternFuncDecStatementNode : public StatementNode { 320 | public: 321 | VariableExprNode *type; 322 | VariableExprNode *name; 323 | vector *args; 324 | public: 325 | ExternFuncDecStatementNode(VariableExprNode *type, VariableExprNode *name, vector *_args): type(type), name(name), args(_args) { 326 | vector::const_iterator it; 327 | } 328 | virtual Value *CodeGen(GenContext&); 329 | virtual void CodeGenP(GenContextP&); 330 | }; 331 | 332 | class IfStatementNode : public StatementNode { 333 | public: 334 | ExprNode *condExpr; 335 | BlockExprNode *trueBlock; 336 | BlockExprNode *falseBlock; 337 | public: 338 | IfStatementNode(ExprNode *condExpr, BlockExprNode *trueBlock): condExpr(condExpr), trueBlock(trueBlock), falseBlock(new BlockExprNode()) {} 339 | IfStatementNode(ExprNode *condExpr, BlockExprNode *trueBlock, BlockExprNode *falseBlock): condExpr(condExpr), trueBlock(trueBlock), falseBlock(falseBlock) {} 340 | virtual Value *CodeGen(GenContext&); 341 | virtual void CodeGenP(GenContextP&); 342 | }; 343 | 344 | class ForStatementNode : public StatementNode { 345 | public: 346 | ExprNode *initExpr; 347 | ExprNode *condExpr; 348 | ExprNode *loopExpr; 349 | BlockExprNode *block; 350 | public: 351 | ForStatementNode(ExprNode *initExpr, ExprNode *condExpr, ExprNode *loopExpr, BlockExprNode *block): initExpr(initExpr), condExpr(condExpr), loopExpr(loopExpr), block(block) {} 352 | virtual Value *CodeGen(GenContext&); 353 | virtual void CodeGenP(GenContextP&); 354 | }; 355 | 356 | class WhileStatementNode : public StatementNode { 357 | public: 358 | ExprNode *whileExpr; 359 | BlockExprNode *block; 360 | public: 361 | WhileStatementNode(ExprNode *whileExpr, BlockExprNode *block): whileExpr(whileExpr), block(block) {} 362 | virtual Value *CodeGen(GenContext&); 363 | virtual void CodeGenP(GenContextP&); 364 | }; 365 | 366 | #endif 367 | -------------------------------------------------------------------------------- /AST_node_python.cpp: -------------------------------------------------------------------------------- 1 | #include "AST_node.h" 2 | #include "C_syntax.hpp" 3 | 4 | #define INDENTION_LENGHT 4 5 | 6 | extern int yyparse(); 7 | extern BlockExprNode *root; 8 | 9 | // bool error = false; 10 | 11 | string modify_funcname(string name) { 12 | if (name == "strlen") { 13 | return "len"; 14 | } else if (name == "isdigit") { 15 | return "str.isdigit"; 16 | } 17 | return name; 18 | } 19 | 20 | GenBlockP::GenBlockP() { 21 | isFunction = false; 22 | } 23 | 24 | GenContextP::GenContextP() { 25 | funcDeclaring = false; 26 | indent_num = 0; 27 | blocks.push(new GenBlockP()); 28 | } 29 | 30 | GenContextP::~GenContextP() { 31 | 32 | } 33 | 34 | void GenContextP::CodeGen(BlockExprNode &root) { 35 | code << "# -*- coding:utf-8" << endl; 36 | code << "# Authors: Shichen Liu" << endl; 37 | code << "# Mengyang Lv" << endl; 38 | code << "# Dayang Li" << endl; 39 | code << "# Date: 2016.12" << endl; 40 | code << "# Project: Compiler final project" << endl; 41 | code << "def printf(format, *args):\n if len(args):\n new_args = []\n for i,arg in enumerate(args):\n if type(arg) == list and len(arg) > 0 and type(arg[0]) == str:\n new_args.append(''.join(arg))\n else:\n new_args.append(arg)\n print ''.join(format) % tuple(new_args),\n else:\n print ''.join(format),\n\n"; 42 | code << "def atoi(s):\n new_s = []\n for i in s:\n if type(i) != str:\n break\n else:\n new_s.append(i)\n return int(''.join(new_s))\n\n"; 43 | root.CodeGenP(*this); 44 | code << "\nif __name__ == \"__main__\":\n main()\n"; 45 | } 46 | 47 | void GenContextP::OutputCode(ostream& out) { 48 | string c = code.str(); 49 | out << c; 50 | } 51 | 52 | void GenContextP::clearBuf() { 53 | code_buf.str(""); 54 | } 55 | 56 | void GenContextP::applyBuf() { 57 | string s = code_buf.str(); 58 | code << s; 59 | clearBuf(); 60 | } 61 | 62 | set& GenContextP::locals() { 63 | return blocks.top()->locals; 64 | } 65 | 66 | set& GenContextP::declared_globals() { 67 | return blocks.top()->declared_globals; 68 | } 69 | 70 | set& GenContextP::globals() { 71 | return globalVariables; 72 | } 73 | 74 | GenBlockP* GenContextP::currentBlock() { 75 | return blocks.top(); 76 | } 77 | 78 | void GenContextP::PushBlock(bool copy_locals, bool isFunction) { 79 | GenBlockP *block = new GenBlockP(); 80 | if (copy_locals) { 81 | block->locals = blocks.top()->locals; 82 | } 83 | if (!isFunction) { 84 | block->declared_globals = blocks.top()->declared_globals; 85 | } 86 | block->isFunction = isFunction; 87 | blocks.push(block); 88 | indent_num = indent_num + INDENTION_LENGHT; 89 | } 90 | 91 | void GenContextP::popBlock() { 92 | GenBlockP *top = blocks.top(); 93 | blocks.pop(); 94 | indent_num = indent_num - INDENTION_LENGHT; 95 | delete top; 96 | } 97 | 98 | void GenContextP::indent(bool use_buf) { 99 | for (int i = 0; i < indent_num; ++i) { 100 | if (use_buf) { 101 | code_buf << ' '; 102 | } else { 103 | code << ' '; 104 | } 105 | } 106 | } 107 | 108 | void GenContextP::declare_global(string name) { 109 | code << "global " << name; 110 | } 111 | 112 | void GenContextP::nextLine(bool use_buf) { 113 | if (use_buf) { 114 | code_buf << '\n'; 115 | } else { 116 | code << '\n'; 117 | } 118 | } 119 | 120 | void VariableExprNode::CodeGenP(GenContextP &context) { 121 | if (context.funcDeclaring) { 122 | if (context.globals().count(name) == 1) { 123 | fprintf(stderr, "duplicate symbol %s\n", name.c_str()); 124 | } else { 125 | context.locals().insert(name); 126 | context.code << name; 127 | } 128 | } else { 129 | if (context.locals().count(name) == 1) { 130 | context.code_buf << name; 131 | } else if (context.globals().count(name) == 1) { 132 | if (context.declared_globals().count(name) == 1) { 133 | context.code_buf << name; 134 | } else { 135 | context.declared_globals().insert(name); 136 | context.code_buf << name; 137 | } 138 | } else { 139 | fprintf(stderr, "undeclared symbol %s\n", name.c_str()); 140 | } 141 | } 142 | } 143 | 144 | void CharExprNode::CodeGenP(GenContextP &context) { 145 | if (val == '\'' || val == '\\') { 146 | context.code_buf << "\'\\" << val << "\'"; 147 | } else { 148 | context.code_buf << "\'" << val << "\'"; 149 | } 150 | } 151 | 152 | void IntExprNode::CodeGenP(GenContextP &context) { 153 | context.code_buf << val; 154 | } 155 | 156 | void DoubleExprNode::CodeGenP(GenContextP &context) { 157 | context.code_buf << val; 158 | } 159 | 160 | void BlockExprNode::CodeGenP(GenContextP &context) { 161 | for(auto it = statements->begin(); it != statements->end(); it++) { 162 | context.indent(); 163 | (*it)->CodeGenP(context); 164 | context.nextLine(); 165 | } 166 | if (context.currentBlock()->isFunction) { 167 | for (set::iterator it = context.declared_globals().begin(); it != context.declared_globals().end(); it++) { 168 | context.indent(false); 169 | context.declare_global(*it); 170 | context.nextLine(false); 171 | } 172 | context.applyBuf(); 173 | } 174 | } 175 | 176 | void OperatorExprNode::CodeGenP(GenContextP &context) { 177 | string opStr = ""; 178 | switch (op) { 179 | case EQ: 180 | opStr = "=="; 181 | break; 182 | case NE: 183 | opStr = "!="; 184 | break; 185 | case GR: 186 | opStr = ">"; 187 | break; 188 | case LW: 189 | opStr = "<"; 190 | break; 191 | case GE: 192 | opStr = ">="; 193 | break; 194 | case LE: 195 | opStr = "<="; 196 | break; 197 | case AND: 198 | opStr = "and"; 199 | break; 200 | case OR: 201 | opStr = "or"; 202 | break; 203 | case ADD: 204 | case SADD: 205 | opStr = "+"; 206 | break; 207 | case SUB: 208 | case SSUB: 209 | opStr = "-"; 210 | break; 211 | case MUL: 212 | case SMUL: 213 | opStr = "*"; 214 | break; 215 | case DIV: 216 | case SDIV: 217 | opStr = "/"; 218 | break; 219 | } 220 | context.code_buf << "("; 221 | left->CodeGenP(context); 222 | context.code_buf << " " << opStr << " "; 223 | right->CodeGenP(context); 224 | context.code_buf << ")"; 225 | } 226 | 227 | void AssignExprNode::CodeGenP(GenContextP &context) { 228 | left->CodeGenP(context); 229 | context.code_buf << " = "; 230 | right->CodeGenP(context); 231 | } 232 | 233 | void FuncExprNode::CodeGenP(GenContextP &context) { 234 | context.code_buf << modify_funcname(functor->name); 235 | context.code_buf << "("; 236 | vector::iterator it = args->begin(); 237 | if (it != args->end()) { 238 | (*it)->CodeGenP(context); 239 | for (it = it + 1; it != args->end(); it++) { 240 | context.code_buf << ", "; 241 | (*it)->CodeGenP(context); 242 | } 243 | } 244 | context.code_buf << ")"; 245 | } 246 | 247 | void CastExprNode::CodeGenP(GenContextP &context) { 248 | // do no extra moves 249 | expr->CodeGenP(context); 250 | } 251 | 252 | void IndexExprNode::CodeGenP(GenContextP &context) { 253 | name->CodeGenP(context); 254 | context.code_buf << "["; 255 | expr->CodeGenP(context); 256 | context.code_buf << "]"; 257 | if (assign != NULL) { 258 | context.code_buf << " = "; 259 | assign->CodeGenP(context); 260 | } 261 | } 262 | 263 | void ExprStatementNode::CodeGenP(GenContextP &context) { 264 | expr->CodeGenP(context); 265 | } 266 | 267 | void VarDecStatementNode::CodeGenP(GenContextP &context) { 268 | if (context.locals().count(name->name) == 1) { 269 | fprintf(stderr, "redefinition %s\n", name->name.c_str()); 270 | } else { 271 | context.locals().insert(name->name); 272 | } 273 | name->CodeGenP(context); 274 | if (!context.funcDeclaring) { 275 | context.code_buf << " = "; 276 | if (expr != NULL) { 277 | expr->CodeGenP(context); 278 | } else { 279 | context.code_buf << "None"; 280 | } 281 | } 282 | } 283 | 284 | void ArrayDecStatementNode::CodeGenP(GenContextP &context) { 285 | if (context.locals().count(name->name) == 1) { 286 | fprintf(stderr, "redefinition %s\n", name->name.c_str()); 287 | } else { 288 | context.locals().insert(name->name); 289 | } 290 | name->CodeGenP(context); 291 | if (init->size() == 0) { 292 | context.code_buf << " = [None]*" << size; 293 | } else { 294 | context.code_buf << " = ["; 295 | vector::iterator it = init->begin(); 296 | if (it != init->end()) { 297 | (*it)->CodeGenP(context); 298 | for (it = it + 1; it != init->end(); it++) { 299 | if (isString && (it+1) == init->end()) { 300 | break; 301 | } 302 | context.code_buf << ", "; 303 | (*it)->CodeGenP(context); 304 | } 305 | } 306 | context.code_buf << "]"; 307 | } 308 | } 309 | 310 | void ReturnStatementNode::CodeGenP(GenContextP &context) { 311 | context.code_buf << "return "; 312 | expr->CodeGenP(context); 313 | } 314 | 315 | void FuncDecStatementNode::CodeGenP(GenContextP &context) { 316 | context.funcDeclaring = true; 317 | context.PushBlock(false, true); 318 | context.code << "def "; 319 | name->CodeGenP(context); 320 | context.code << "("; 321 | vector::iterator it = args->begin(); 322 | if (it != args->end()) { 323 | (*it)->CodeGenP(context); 324 | for (it = it + 1; it != args->end(); it++) { 325 | context.code << ", "; 326 | (*it)->CodeGenP(context); 327 | } 328 | } 329 | context.code << "):"; 330 | context.nextLine(false); 331 | context.funcDeclaring = false; 332 | block->CodeGenP(context); 333 | context.popBlock(); 334 | } 335 | 336 | void ExternFuncDecStatementNode::CodeGenP(GenContextP &context) { 337 | // don't generate code 338 | } 339 | 340 | void IfStatementNode::CodeGenP(GenContextP &context) { 341 | context.code_buf << "if ("; 342 | condExpr->CodeGenP(context); 343 | context.code_buf << "):"; 344 | context.nextLine(); 345 | context.PushBlock(true, false); 346 | trueBlock->CodeGenP(context); 347 | context.popBlock(); 348 | if (falseBlock->statements->size() == 0) { 349 | return; 350 | } 351 | context.indent(); 352 | context.code_buf << "else:"; 353 | context.nextLine(); 354 | context.PushBlock(true, false); 355 | falseBlock->CodeGenP(context); 356 | context.popBlock(); 357 | } 358 | 359 | void ForStatementNode::CodeGenP(GenContextP &context) { 360 | initExpr->CodeGenP(context); 361 | context.nextLine(); 362 | context.indent(); 363 | context.code_buf << "while "; 364 | condExpr->CodeGenP(context); 365 | context.code_buf << ":"; 366 | context.nextLine(); 367 | context.PushBlock(true, false); 368 | block->statements->push_back(new ExprStatementNode(loopExpr)); 369 | block->CodeGenP(context); 370 | context.popBlock(); 371 | } 372 | 373 | void WhileStatementNode::CodeGenP(GenContextP &context) { 374 | context.code_buf << "while"; 375 | whileExpr->CodeGenP(context); 376 | context.code_buf << ":"; 377 | context.nextLine(); 378 | context.PushBlock(true, false); 379 | block->CodeGenP(context); 380 | context.popBlock(); 381 | } 382 | -------------------------------------------------------------------------------- /C_lexical.lex: -------------------------------------------------------------------------------- 1 | %{ 2 | #include 3 | #include 4 | #include "AST_node.h" 5 | #include "C_syntax.hpp" 6 | #define TOKEN(t) (yylval.token = t) 7 | extern int lineNumber; 8 | %} 9 | 10 | %option noyywrap 11 | 12 | %% 13 | 14 | "extern" return TOKEN(EXTERN); 15 | "return" return TOKEN(RETURN); 16 | 17 | "int" { yylval.string = new string(yytext, yyleng); return INT; } 18 | "double" { yylval.string = new string(yytext, yyleng); return DOUBLE; } 19 | "char" { yylval.string = new string(yytext, yyleng); return CHAR; } 20 | "void" { yylval.string = new string(yytext, yyleng); return VOID; } 21 | 22 | "if" return TOKEN(IF); 23 | "else" return TOKEN(ELSE); 24 | "for" return TOKEN(FOR); 25 | "while" return TOKEN(WHILE); 26 | 27 | ["].*["] { 28 | yylval.string = new string(yytext, yyleng); 29 | yylval.string->erase(yylval.string->begin()); 30 | yylval.string->erase(yylval.string->end() - 1); 31 | return CSTR; 32 | } 33 | [_A-Za-z][_0-9A-Za-z]* { yylval.string = new string(yytext, yyleng); return VAR; } 34 | [0-9]+ { yylval.string = new string(yytext, yyleng); return CINT; } 35 | [0-9]+\.[0-9]* { yylval.string = new string(yytext, yyleng); return CDOUBLE; } 36 | ['].['] { 37 | yylval.string = new string(yytext, yyleng); 38 | yylval.string->erase(yylval.string->begin()); 39 | yylval.string->erase(yylval.string->end() - 1); 40 | return CCHAR; 41 | } 42 | 43 | "(" return TOKEN(LPAREN); 44 | ")" return TOKEN(RPAREN); 45 | "[" return TOKEN(LBRACK); 46 | "]" return TOKEN(RBRACK); 47 | "{" return TOKEN(LBRACE); 48 | "}" return TOKEN(RBRACE); 49 | 50 | "=" return TOKEN(EQUAL); 51 | 52 | "==" return TOKEN(EQ); 53 | "!=" return TOKEN(NE); 54 | ">" return TOKEN(GR); 55 | ">=" return TOKEN(GE); 56 | "<" return TOKEN(LW); 57 | "<=" return TOKEN(LE); 58 | 59 | "&&" return TOKEN(AND); 60 | "||" return TOKEN(OR); 61 | 62 | 63 | "+" return TOKEN(ADD); 64 | "-" return TOKEN(SUB); 65 | "*" return TOKEN(MUL); 66 | "/" return TOKEN(DIV); 67 | 68 | "+=" return TOKEN(SADD); 69 | "-=" return TOKEN(SSUB); 70 | "*=" return TOKEN(SMUL); 71 | "/=" return TOKEN(SDIV); 72 | 73 | "." return TOKEN(DOT); 74 | "," return TOKEN(COMMA); 75 | ":" return TOKEN(COLON); 76 | ";" return TOKEN(SEMICOLON); 77 | 78 | [ \t\r]* ; 79 | 80 | "\n" lineNumber += 1; 81 | 82 | ^"#include ".+ ; 83 | 84 | . cout << "Unknown token! " << yytext << endl; yyterminate(); 85 | 86 | %% 87 | -------------------------------------------------------------------------------- /C_syntax.yacc: -------------------------------------------------------------------------------- 1 | %{ 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include "AST_node.h" 7 | 8 | BlockExprNode *root; 9 | 10 | void yyerror(char *) {}; 11 | 12 | int yylex(void); 13 | 14 | int lineNumber = 1; 15 | map varTable; 16 | void addNewVar(string name, E_TYPE type); 17 | string typeStr(E_TYPE type); 18 | 19 | void setVarType(VariableExprNode *); 20 | E_TYPE checkExprType(ExprNode *lhs, ExprNode *rhs); 21 | void noSemicolonError(); 22 | %} 23 | 24 | %union { 25 | int token; 26 | string *string; 27 | VariableExprNode *var; 28 | ExprNode *expr; 29 | vector *vars; 30 | vector *exprs; 31 | BlockExprNode *block; 32 | StatementNode *statement; 33 | VarDecStatementNode *var_dec; 34 | } 35 | 36 | %token INT DOUBLE CHAR VOID /* Basic Type Names */ 37 | %token CSTR CINT CDOUBLE CCHAR /* Const Literal */ 38 | %token VAR /* Variable Names */ 39 | %token IF ELSE FOR WHILE /* Flow Controllers */ 40 | %token LPAREN RPAREN LBRACK RBRACK LBRACE RBRACE /* Enclosures */ 41 | %token EQ NE GR GE LW LE AND OR EQUAL ADD SUB MUL DIV /* Binary Operators */ 42 | %token SADD SSUB SMUL SDIV /* Self Operators */ 43 | %token DOT COMMA COLON SEMICOLON /* Endings */ 44 | %token EXTERN RETURN /* Others */ 45 | 46 | %type variable type 47 | %type function_args 48 | %type expr const logic_expr 49 | %type invoke_args 50 | %type program block global_block local_block 51 | %type global_statement local_statement 52 | %type variable_declaration 53 | %type array_declaration function_declaration extern_function_declaration 54 | %type condition loop 55 | %type compare 56 | 57 | %left EQUAL 58 | %left EQ NE GR GE LW LE 59 | %left AND OR 60 | %left ADD SUB SADD SSUB 61 | %left MUL DIV SMUL SDIV 62 | 63 | %nonassoc LOWER_THAN_ELSE 64 | %nonassoc ELSE 65 | 66 | %% 67 | 68 | program: global_block { root = $1; }; 69 | 70 | global_block: global_statement { $$ = new BlockExprNode(); $$->statements->push_back($1); } 71 | | global_block global_statement { $$->statements->push_back($2); } 72 | ; 73 | 74 | global_statement: function_declaration { $$ = $1; } 75 | | extern_function_declaration SEMICOLON { $$ = $1; } 76 | | extern_function_declaration error { noSemicolonError(); $$ = $1;} 77 | | expr SEMICOLON { $$ = new ExprStatementNode($1); } 78 | ; 79 | 80 | function_declaration: type variable LPAREN function_args RPAREN block { $$ = new FuncDecStatementNode($1, $2, $4, $6); }; 81 | 82 | extern_function_declaration: EXTERN type variable LPAREN function_args RPAREN { $$ = new ExternFuncDecStatementNode($2, $3, $5); }; 83 | 84 | type: INT { $$ = new VariableExprNode(*$1, E_INT); delete $1; } 85 | | DOUBLE { $$ = new VariableExprNode(*$1, E_DOUBLE); delete $1; } 86 | | CHAR { $$ = new VariableExprNode(*$1, E_CHAR); delete $1; } 87 | | VOID { $$ = new VariableExprNode(*$1, E_VOID); delete $1; } 88 | ; 89 | 90 | variable: VAR { $$ = new VariableExprNode(*$1); delete $1; }; 91 | 92 | function_args: /* NULL */ { $$ = new vector(); } 93 | | variable_declaration { $$ = new vector(); $$->push_back($1); } 94 | | function_args COMMA variable_declaration { $1->push_back($3); $$ = $1; } 95 | ; 96 | 97 | block: LBRACE local_block RBRACE { $$ = $2; } 98 | | local_statement { $$ = new BlockExprNode(); $$->statements->push_back($1); } 99 | ; 100 | 101 | variable_declaration: type variable { $2->_type = $1->_type; $$ = new VarDecStatementNode($1, $2); addNewVar($2->name, $2->_type);} 102 | | type variable EQUAL expr { $2->_type = $1->_type; $$ = new VarDecStatementNode($1, $2, $4); addNewVar($2->name, $2->_type); checkExprType($2, $4); } 103 | ; 104 | 105 | local_block: local_statement { $$ = new BlockExprNode(); $$->statements->push_back($1); } 106 | | local_block local_statement { $$->statements->push_back($2); } 107 | ; 108 | 109 | local_statement: variable_declaration SEMICOLON { $$ = $1; } 110 | | array_declaration SEMICOLON { $$ = $1; } 111 | | condition { $$ = $1; } 112 | | loop { $$ = $1; } 113 | | expr SEMICOLON { $$ = new ExprStatementNode($1); } 114 | | RETURN expr SEMICOLON { $$ = new ReturnStatementNode($2); } 115 | | SEMICOLON { /* NULL */ } 116 | | variable_declaration error { noSemicolonError(); $$ = $1; } 117 | | array_declaration error { noSemicolonError(); $$ = $1; } 118 | | expr error { noSemicolonError(); $$ = new ExprStatementNode($1); } 119 | ; 120 | 121 | expr: variable { $$ = $1; } 122 | | const { $$ = $1; } 123 | | expr ADD expr { $$ = new OperatorExprNode($1, $2, $3); $$->_type = checkExprType($1, $3); } 124 | | expr SUB expr { $$ = new OperatorExprNode($1, $2, $3); $$->_type = checkExprType($1, $3); } 125 | | expr MUL expr { $$ = new OperatorExprNode($1, $2, $3); $$->_type = checkExprType($1, $3); } 126 | | expr DIV expr { $$ = new OperatorExprNode($1, $2, $3); $$->_type = checkExprType($1, $3); } 127 | | variable SADD expr { $$ = new OperatorExprNode($1, $2, $3); $$ = new AssignExprNode($1, $$); setVarType($1); $$->_type = checkExprType($1, $3);} 128 | | variable SSUB expr { $$ = new OperatorExprNode($1, $2, $3); $$ = new AssignExprNode($1, $$); setVarType($1); $$->_type = checkExprType($1, $3);} 129 | | variable SMUL expr { $$ = new OperatorExprNode($1, $2, $3); $$ = new AssignExprNode($1, $$); setVarType($1); $$->_type = checkExprType($1, $3);} 130 | | variable SDIV expr { $$ = new OperatorExprNode($1, $2, $3); $$ = new AssignExprNode($1, $$); setVarType($1); $$->_type = checkExprType($1, $3);} 131 | | expr compare expr { $$ = new OperatorExprNode($1, $2, $3); $$->_type = E_INT; } 132 | | variable EQUAL expr { $$ = new AssignExprNode($1, $3); setVarType($1); checkExprType($1, $3); $$->_type = $1->_type;} 133 | | variable LPAREN invoke_args RPAREN { $$ = new FuncExprNode($1, $3); addNewVar($1->name, E_FUNC); setVarType($1); $$->_type = $1->_type;} 134 | | variable LBRACK expr RBRACK { $$ = new IndexExprNode($1, $3); $$->_type = $1->_type; } 135 | | variable LBRACK expr RBRACK EQUAL expr { $$ = new IndexExprNode($1, $3, $6); checkExprType($1, $6); $$->_type = $1->_type; } 136 | | variable LBRACK expr RBRACK SADD expr { $$ = new IndexExprNode($1, $3); $$ = new OperatorExprNode($$, $5, $6); $$ = new IndexExprNode($1, $3, $$); checkExprType($1, $6); $$->_type = $1->_type; } 137 | | variable LBRACK expr RBRACK SSUB expr { $$ = new IndexExprNode($1, $3); $$ = new OperatorExprNode($$, $5, $6); $$ = new IndexExprNode($1, $3, $$); checkExprType($1, $6); $$->_type = $1->_type; } 138 | | variable LBRACK expr RBRACK SMUL expr { $$ = new IndexExprNode($1, $3); $$ = new OperatorExprNode($$, $5, $6); $$ = new IndexExprNode($1, $3, $$); checkExprType($1, $6); $$->_type = $1->_type; } 139 | | variable LBRACK expr RBRACK SDIV expr { $$ = new IndexExprNode($1, $3); $$ = new OperatorExprNode($$, $5, $6); $$ = new IndexExprNode($1, $3, $$); checkExprType($1, $6); $$->_type = $1->_type; } 140 | | LPAREN expr RPAREN { $$ = $2; } 141 | | LPAREN type RPAREN expr { $$ = new CastExprNode($2, $4); $$->_type = $2->_type;} 142 | ; 143 | 144 | array_declaration: type variable LBRACK CINT RBRACK { $$ = new ArrayDecStatementNode($1, $2, atol($4->c_str())); } 145 | | type variable LBRACK RBRACK EQUAL CSTR { $2->_type = $1->_type; $$ = new ArrayDecStatementNode($1, $2, *$6); } 146 | | type variable LBRACK RBRACK EQUAL LBRACE invoke_args RBRACE { $2->_type = $1->_type; $$ = new ArrayDecStatementNode($1, $2, $7); } 147 | ; 148 | 149 | condition: IF LPAREN logic_expr RPAREN block %prec LOWER_THAN_ELSE { $$ = new IfStatementNode($3, $5); } 150 | | IF LPAREN logic_expr RPAREN block ELSE block { $$ = new IfStatementNode($3, $5, $7); } 151 | ; 152 | 153 | loop: FOR LPAREN expr SEMICOLON logic_expr SEMICOLON expr RPAREN block { $$ = new ForStatementNode($3, $5, $7, $9); } 154 | | WHILE LPAREN logic_expr RPAREN block { $$ = new WhileStatementNode($3, $5); } 155 | ; 156 | 157 | const: CINT { $$ = new IntExprNode(atoi($1->c_str())); delete $1; } 158 | | CDOUBLE { $$ = new DoubleExprNode(atoi($1->c_str())); delete $1; } 159 | | CCHAR { $$ = new CharExprNode($1->front()); delete $1; } 160 | | SUB CINT { $$ = new IntExprNode(-atol($2->c_str())); delete $2; } 161 | | SUB CDOUBLE { $$ = new IntExprNode(-atof($2->c_str())); delete $2; } 162 | ; 163 | 164 | compare: EQ { $$ = $1; } 165 | | NE { $$ = $1; } 166 | | GR { $$ = $1; } 167 | | GE { $$ = $1; } 168 | | LW { $$ = $1; } 169 | | LE { $$ = $1; } 170 | ; 171 | 172 | invoke_args: /* NULL */ { $$ = new vector(); } 173 | | expr { $$ = new vector(); $$->push_back($1); } 174 | | invoke_args COMMA expr { $1->push_back($3); $$ = $1; } 175 | ; 176 | 177 | logic_expr: logic_expr OR logic_expr { $$ = new OperatorExprNode($1, $2, $3); } 178 | | logic_expr AND logic_expr { $$ = new OperatorExprNode($1, $2, $3); } 179 | | expr { $$ = $1; } 180 | ; 181 | 182 | %% 183 | 184 | void addNewVar(string name, E_TYPE type) { 185 | map::iterator it; 186 | it = varTable.find(name); 187 | if (it == varTable.end()) { 188 | varTable[name] = type; 189 | } else if (type == E_FUNC) { 190 | varTable[name] = type; 191 | } else { 192 | cout << "line " << lineNumber << ": redefinition of variable " << name << " from (" << typeStr((*it).second) << ") to (" << typeStr(type) << ")." << endl; 193 | varTable[name] = type; 194 | } 195 | } 196 | string typeStr(E_TYPE type) { 197 | switch (type) { 198 | case E_VOID: 199 | return "void"; 200 | case E_INT: 201 | return "int"; 202 | case E_CHAR: 203 | return "char"; 204 | case E_DOUBLE: 205 | return "double"; 206 | case E_PTR: 207 | return "pointer"; 208 | case E_FUNC: 209 | return "function part"; 210 | default: 211 | return "unknown"; 212 | } 213 | } 214 | 215 | E_TYPE checkExprType(ExprNode *lhs, ExprNode *rhs) { 216 | if (lhs->_type == E_UNKNOWN) { 217 | cout << "line " << lineNumber << ": unknown expression type on lhs" << endl; 218 | return E_UNKNOWN; 219 | } 220 | if (rhs->_type == E_UNKNOWN) { 221 | cout << "line " << lineNumber << ": unknown expression type on rhs" << endl; 222 | return E_UNKNOWN; 223 | } 224 | E_TYPE i, j; 225 | i = lhs->_type > rhs->_type ? rhs->_type : lhs->_type; // smaller one 226 | j = lhs->_type < rhs->_type ? rhs->_type : lhs->_type; // bigger one 227 | 228 | if (j == E_FUNC) { 229 | return i; 230 | } 231 | if (i != j) { 232 | cout << "line " << lineNumber << ": implicitly convert type " << typeStr(i) << " to " << typeStr(j) << "." << endl; 233 | } 234 | return j; 235 | } 236 | 237 | void noSemicolonError() { 238 | cout << "line " << lineNumber << ": missed Semicolon." << endl; 239 | } 240 | 241 | void setVarType(VariableExprNode *var){ 242 | map::iterator it; 243 | it = varTable.find(var->name); 244 | if (it == varTable.end()) { 245 | var->_type = E_UNKNOWN; 246 | } else { 247 | var->_type = (*it).second; 248 | } 249 | } 250 | 251 | void printVarTable() { 252 | std::map::iterator it; 253 | for (it = varTable.begin(); it != varTable.end(); it++) { 254 | cout << (*it).first << " : " << typeStr((*it).second) << std::endl; 255 | } 256 | } 257 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | all: compiler 2 | 3 | OBJS = C_syntax.o \ 4 | AST_node.o \ 5 | main.o \ 6 | C_lexical.o \ 7 | AST_node_python.o 8 | 9 | LLVMCONFIG = llvm-config 10 | CPPFLAGS = `$(LLVMCONFIG) --cppflags` -std=c++11 -g 11 | LDFLAGS = `$(LLVMCONFIG) --ldflags` -lpthread -ldl -lz -lncurses -rdynamic 12 | LIBS = `$(LLVMCONFIG) --libs` 13 | SYSTEMLIBS = `$(LLVMCONFIG) —-system-libs` 14 | 15 | C_syntax.cpp: C_syntax.yacc 16 | bison -d --no-lines -o $@ $^ 17 | 18 | C_syntax.hpp: C_syntax.cpp 19 | 20 | C_lexical.cpp: C_lexical.lex C_syntax.hpp 21 | flex -L -o $@ $^ 22 | 23 | %.o: %.cpp 24 | g++ -c $(CPPFLAGS) -o $@ $< 25 | 26 | compiler: $(OBJS) 27 | llvm-g++ -o $@ $(OBJS) $(LIBS) $(LDFLAGS) 28 | 29 | clean: 30 | $(RM) -rf C_syntax.cpp C_syntax.hpp compiler y.output c_code/*.py c_code/*.ll C_lexical.cpp $(OBJS) 31 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # C-compiler 2 | C to LLVM / Python compiler 3 | 4 | # Configure Environment 5 | 6 | 1. download from [llvm-3.8.0](http://llvm.org/releases/3.8.0/llvm-3.8.0.src.tar.xz) 7 | 2. ```tar xf llvm-3.8.0.src.tar.xz``` 8 | 3. ```cd llvm-3.8.0.src.tar.xz``` 9 | 4. ```mkdir build``` 10 | 5. ```cd build``` 11 | 6. ```../configure``` 12 | 7. ```make``` 13 | 8. ```make install``` 14 | 15 | *Note that make will take about half an hour* 16 | 17 | # Compile 18 | To compile the compiler source code 19 | 20 | 1. ```make clean``` 21 | 2. ```make``` 22 | 23 | # Run code 24 | 25 | - ```./compiler [-vfph] ``` 26 | 27 | - -v: display generated back-end code in the terminal. 28 | - -f: output generated back-end code to ``````. 29 | - -p: alternatively generate python code. 30 | - -h: help 31 | 32 | # Test code 33 | 34 | - using ```lli c_code/your_code.ll``` to test llvm back-end code. 35 | - using ```python c_code/your_code.py``` to test python back-end code. 36 | -------------------------------------------------------------------------------- /c_code/calculating_expression.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | char TIPS_T[] = "EXPR: %s%cRESULT: %d%c"; 6 | char TIPS_F[] = "EXPR: %s%cRESULT: error%c"; 7 | char expr[] = "16/4+((8-5)*(4+3)+1)-10/2*9#"; 8 | 9 | char post[1000]; 10 | char ss[1000]; 11 | char ch; 12 | int sum; 13 | int i; 14 | int t; 15 | int z; 16 | int error = 0; 17 | int top = 0; 18 | sum = strlen(expr); 19 | t = 1; 20 | i = 0; 21 | ch = expr[i]; 22 | i += 1; 23 | while (ch != '#') { 24 | if (ch == '+' || ch == '-') { 25 | while (top != 0 && ss[top] != '(') { 26 | post[t] = ss[top]; 27 | top -= 1; 28 | t += 1; 29 | } 30 | top += 1; 31 | ss[top] = ch; 32 | 33 | } else if (ch == '*' || ch == '/') { 34 | while (ss[top] == '*'|| ss[top] == '/') { 35 | post[t] = ss[top]; 36 | top -= 1; 37 | t += 1; 38 | } 39 | top += 1; 40 | ss[top] = ch; 41 | } else if (ch == '(') { 42 | top += 1; 43 | ss[top] = ch; 44 | } else if (ch == ')') { 45 | while (ss[top] != '(') { 46 | post[t] = ss[top]; 47 | top -= 1; 48 | t += 1; 49 | } 50 | top -= 1; 51 | } else if (ch == ' ') { 52 | z = 1; 53 | } else { 54 | while (isdigit(ch) || ch == '.') { 55 | post[t] = ch; 56 | t += 1; 57 | ch = expr[i]; 58 | i += 1; 59 | } 60 | i -= 1; 61 | post[t] = ' '; 62 | t += 1; 63 | } 64 | ch = expr[i]; 65 | i += 1; 66 | } while (top!= 0) { 67 | post[t] = ss[top]; 68 | t += 1; 69 | top -= 1; 70 | } 71 | post[t] = ' '; 72 | int newstack[100]; 73 | char newstr[100]; 74 | t=1; 75 | top=0; 76 | ch = post[t]; 77 | t=t+1; 78 | char temp; 79 | while (ch!= ' ' && error == 0) { 80 | if (ch == '+') { 81 | newstack[top-1] = newstack[top-1] + newstack[top]; 82 | top -= 1; 83 | } else if (ch == '-') { 84 | newstack[top-1] = newstack[top-1] - newstack[top]; 85 | top -= 1; 86 | } else if (ch == '*') { 87 | newstack[top-1] = newstack[top-1] * newstack[top]; 88 | top -= 1; 89 | } else if(ch == '/') { 90 | if (newstack[top] != 0) 91 | newstack[top-1] = newstack[top-1] / newstack[top]; 92 | else 93 | error = 1; 94 | top -= 1; 95 | } else { 96 | i = 0; 97 | while (isdigit(ch) || ch == '.') { 98 | newstr[i] = ch; 99 | i += 1; 100 | ch = post[t]; 101 | t += 1; 102 | } 103 | temp = 0; 104 | newstr[i] = temp; 105 | top += 1; 106 | newstack[top] = atoi(newstr); 107 | } 108 | ch = post[t]; 109 | t += 1; 110 | } 111 | 112 | if(error == 0) 113 | printf(TIPS_T, expr, 10, newstack[top], 10); 114 | else 115 | printf(TIPS_F, expr, 10, 10); 116 | return 0; 117 | } 118 | -------------------------------------------------------------------------------- /c_code/factorial.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int factorial(int n) { 5 | int rst; 6 | char db[] = "%d%c"; 7 | printf(db, n, 10); 8 | if (n == 0) 9 | rst = 1; 10 | else 11 | rst = n; 12 | if (n != 1 && n != 0) 13 | rst = n * factorial(n-1); 14 | return rst; 15 | } 16 | 17 | int main() { 18 | char result[] = "INPUT: %d%cRESULT: %d"; 19 | int input = 4; 20 | int a = factorial(input); 21 | printf(result, input, 10, a); 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /c_code/kmp.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | char TIPS[] = "TEXT: %s%cPATTERN: %s%cANSWER: "; 7 | char number[] = "%d "; 8 | char charactor[] = "%c"; 9 | char NO_ANSWER[] = "none"; 10 | char text[] = "anpanman"; 11 | char pattern[] = "an"; 12 | int answer[100]; 13 | int a = 0; 14 | int m = strlen(text); 15 | int n = strlen(pattern); 16 | 17 | int i = 0; 18 | int j = -1; 19 | int next[100]; 20 | int x; 21 | int y; 22 | int z; 23 | next[0] = -1; 24 | while (i < n) { 25 | while (j > -1 && pattern[i] != pattern[j]) { 26 | j = next[j]; 27 | } 28 | i += 1; 29 | j += 1; 30 | if ((i != n) && (j != m) && (pattern[i] == pattern[j])) 31 | next[i] = next[j]; 32 | else if ((i == n) && (j == m)) 33 | next[i] = next[j]; 34 | else 35 | next[i] = j; 36 | } 37 | 38 | i = 0; 39 | j = 0; 40 | while (j < m) { 41 | while (i > -1 && text[j] != pattern[i]) 42 | i = next[i]; 43 | i += 1; 44 | j += 1; 45 | if (i >= n) { 46 | answer[a] = j - i; 47 | a += 1; 48 | i = next[i]; 49 | } 50 | } 51 | 52 | // printf(TIPS, text, 10, pattern, 10); 53 | // if (a == 0) 54 | // printf(NO_ANSWER); 55 | // else { 56 | for (i = 0; i < a; i += 1) { 57 | cout << answer[i] << endl; 58 | } 59 | // } 60 | // printf(charactor, 10); 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /c_code/matrix.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 6 | int b[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 7 | int len = 3; 8 | int c[9]; 9 | char number[] = "%d "; 10 | char charactor[] = "%c"; 11 | 12 | int i; 13 | int j; 14 | int m; 15 | for (i = 0; i < len; i += 1) { 16 | for (j = 0; j < len; j += 1) { 17 | c[i*len+j] = 0; 18 | for (m = 0; m < len; m += 1) 19 | c[i*len+j] += a[i*len+m] * b[m*len+j]; 20 | printf(number, c[i*len+j]); 21 | } 22 | printf(charactor, 10); 23 | } 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /c_code/palindrome.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | 6 | char text[] = "ShanghaiZiLaiShuiuhSiaLiZiahgnahS"; 7 | char True[] = "True! '%s' is a palindrome.%c"; 8 | char False[] = "False! '%s' is not a palindrome.%c"; 9 | 10 | int i; 11 | int l = strlen(text); 12 | int lh = l / 2; 13 | int rst = 1; 14 | for (i = 0; i < lh; i += 1) { 15 | if (text[i] != text[l-1-i]) { 16 | rst = 0; 17 | break; 18 | } 19 | } 20 | 21 | if (rst == 1) { 22 | printf(True, text, 10); 23 | } else { 24 | printf(False, text, 10); 25 | } 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "AST_node.h" 5 | 6 | using namespace std; 7 | using namespace llvm; 8 | 9 | extern FILE* yyin; 10 | extern BlockExprNode* root; 11 | extern int yyparse(); 12 | extern void linkExternalFunctions(GenContext &context); 13 | 14 | void usage() { 15 | cout << "\nusage: ./compiler [-fhpv] \n" << endl; 16 | cout << "optional arguments:" << endl; 17 | cout << " -h\thelp" << endl; 18 | cout << " -v\tshow output in terminal" << endl; 19 | cout << " -f\tshow output in *.ll or *.py" << endl; 20 | cout << " -p\toutput python version" << endl; 21 | } 22 | 23 | int main(int argc, char **argv) { 24 | char *filename; 25 | bool f = false, p = false, v = false; 26 | // check args 27 | if (argc == 2) 28 | filename = argv[1]; 29 | else if (argc >= 3) { 30 | filename = argv[argc-1]; 31 | int ch; 32 | while((ch = getopt(argc, argv, "fhpv")) != -1) { 33 | switch(ch) { 34 | case 'h': 35 | usage(); 36 | return 0; 37 | case 'f': 38 | f = true; 39 | break; 40 | case 'p': 41 | p = true; 42 | break; 43 | case 'v': 44 | v = true; 45 | break; 46 | default: 47 | usage(); 48 | return 0; 49 | } 50 | } 51 | } else { 52 | usage(); 53 | return 0; 54 | } 55 | // check filename 56 | int len = strlen(filename); 57 | if (filename[len - 1] != 'c' || filename[len - 2] != '.') { 58 | usage(); 59 | return 0; 60 | } 61 | yyin = fopen(filename, "r"); 62 | if (!yyin) { 63 | perror("File opening failed"); 64 | return EXIT_FAILURE; 65 | } 66 | if (yyparse()){ 67 | cout << "ERROR!" << endl; 68 | return EXIT_FAILURE; 69 | } 70 | // implement options 71 | if (p) { 72 | GenContextP context; 73 | cout << "Generating Python code" << endl; 74 | cout << "----------------------" << endl; 75 | context.CodeGen(*root); 76 | cout << "----------------------" << endl; 77 | cout << "Finished" << endl; 78 | if (f) { 79 | filename[len-1] = 'p'; 80 | filename[len] = 'y'; 81 | filename[len+1] = '\0'; 82 | ofstream outfile; 83 | outfile.open(filename, ios::out); 84 | context.OutputCode(outfile); 85 | outfile.close(); 86 | } 87 | if (v) { 88 | cout << "Python code:" << endl; 89 | cout << "------------" << endl; 90 | context.OutputCode(cout); 91 | cout << "------------" << endl; 92 | cout << "Python code ends" << endl; 93 | } 94 | cout << "+=====================================+" << endl; 95 | cout << "| To Run Python code, please using: |" << endl; 96 | cout << "| python c_code/ |" << endl; 97 | cout << "+=====================================+" << endl; 98 | cout << "finished" << endl; 99 | } else { 100 | GenContext context; 101 | InitializeNativeTarget(); 102 | InitializeNativeTargetAsmPrinter(); 103 | InitializeNativeTargetAsmParser(); 104 | linkExternalFunctions(context); 105 | cout << "Generating LLVM code" << endl; 106 | cout << "--------------------" << endl; 107 | context.CodeGen(*root); 108 | cout << endl; 109 | cout << "--------------------" << endl; 110 | cout << "Finished" << endl; 111 | if (f) { 112 | filename[len-1] = 'l'; 113 | filename[len] = 'l'; 114 | filename[len+1] = '\0'; 115 | ofstream outfile; 116 | outfile.open(filename, ios::out); 117 | context.OutputCode(outfile); 118 | outfile.close(); 119 | } 120 | if (v) { 121 | cout << "LLVM code:" << endl; 122 | cout << "----------" << endl; 123 | context.OutputCode(cout); 124 | cout << "----------" << endl; 125 | cout << "LLVM code ends" << endl; 126 | } 127 | cout << "Run LLVM code" << endl; 128 | cout << "-------------" << endl; 129 | context.run(); 130 | cout << endl; 131 | cout << "-------------" << endl; 132 | cout << "Rnd LLVM code ends" << endl; 133 | cout << "Finished" << endl; 134 | } 135 | fclose(yyin); 136 | return 0; 137 | } 138 | --------------------------------------------------------------------------------