From 4df7c22b99349dcf2175d69679eafa175d49aa9f Mon Sep 17 00:00:00 2001 From: _ov4 Date: Sun, 26 Jul 2026 12:02:32 +0000 Subject: refactor: batch 1 - correctness and error contract - MID/RIGHT/LEFT integer args now coerced at call sites (RIGHT(s, n/2) no longer emits invalid IR); drop emitLeft's private conversion - FOR loop direction decided at run time via select on STEP sign; descending FOR works, STEP evaluated once per iteration - ArrayHandler: extract emitCheckedIndices/loadElement; index count is validated before emission, fixing a compiler-crash (vector OOB UB) on OUTPUT with too many indices - Error contract: Lexer/Parser/CodeGen track errors; all silent failure paths now print Error: diagnostics with line numbers; unterminated char literal no longer truncates the rest of the program; module is verified with verifyModule; driver exits non-zero on any error Co-Authored-By: Claude Fable 5 --- include/cps/ArithmeticHandler.h | 5 +- include/cps/ArrayHandler.h | 7 +++ include/cps/CodeGen.h | 4 ++ include/cps/FunctionGen.h | 8 ++- include/cps/Lexer.h | 2 + include/cps/Parser.h | 10 +++- lib/CodeGen/ArithmeticHandler.cc | 7 ++- lib/CodeGen/ArrayHandler.cc | 109 ++++++++++++++++------------------- lib/CodeGen/CodeGen.cc | 121 ++++++++++++++++++++++----------------- lib/CodeGen/FunctionGen.cc | 11 ++-- lib/CodeGen/StringHandler.cc | 6 -- lib/Lexer/Lexer.cc | 19 ++++-- lib/Parser/Parser.cc | 31 ++++++++-- lib/Parser/ParserFunction.cc | 16 +++--- tools/driver/main.cc | 2 +- 15 files changed, 207 insertions(+), 151 deletions(-) diff --git a/include/cps/ArithmeticHandler.h b/include/cps/ArithmeticHandler.h index 8d6ea27..ca6266d 100644 --- a/include/cps/ArithmeticHandler.h +++ b/include/cps/ArithmeticHandler.h @@ -8,10 +8,11 @@ namespace cps { class ArithmeticHandler { llvm::LLVMContext &Context; llvm::IRBuilder<> &Builder; + bool &HadError; public: - ArithmeticHandler(llvm::LLVMContext &Ctx, llvm::IRBuilder<> &B) - : Context(Ctx), Builder(B) {} + ArithmeticHandler(llvm::LLVMContext &Ctx, llvm::IRBuilder<> &B, bool &HadErrorFlag) + : Context(Ctx), Builder(B), HadError(HadErrorFlag) {} llvm::Value *emitBinaryOp(int Op, llvm::Value *LHS, llvm::Value *RHS, int Line); }; diff --git a/include/cps/ArrayHandler.h b/include/cps/ArrayHandler.h index f15004f..6f563b7 100644 --- a/include/cps/ArrayHandler.h +++ b/include/cps/ArrayHandler.h @@ -42,6 +42,13 @@ class ArrayHandler { llvm::Value *getArrayBasePointer(const std::string &Name); llvm::Value *getElementPointer(const std::string &Name, llvm::Value *Offset); const ArrayMetadata *getMetadata(const std::string &Name) const; + bool emitCheckedIndices(const std::string &Name, + const std::vector> &IndexExprs, + int Line, + bool RequireExact, + CodeGen &CG, + std::vector &Out); + llvm::Value *loadElement(const std::string &Name, llvm::Value *Offset, CodeGen &CG); void emitPrintLoop(const std::string &Name, int CurrentDim, std::vector CurrentIndices, diff --git a/include/cps/CodeGen.h b/include/cps/CodeGen.h index 07ff3e8..268ba7e 100644 --- a/include/cps/CodeGen.h +++ b/include/cps/CodeGen.h @@ -59,6 +59,8 @@ class CodeGen { llvm::Value *FalseStr; // "FALSE" llvm::Value *EmptyStringStr; // "" + bool HadError = false; + void SetupExternalFunctions(); llvm::AllocaInst *CreateEntryBlockAlloca(llvm::Function *TheFunction, const std::string &VarName); llvm::AllocaInst *CreateEntryBlockAlloca(llvm::Function *TheFunction, llvm::Type *AllocType, const std::string &VarName); @@ -80,6 +82,8 @@ public: ~CodeGen(); void compile(const std::vector> &Statements); void print(); + bool hadError() const { return HadError; } + void reportError(const char *Fmt, ...); llvm::Value *emitExpr(ExprAST *Expr); void emitStmt(StmtAST *Stmt); diff --git a/include/cps/FunctionGen.h b/include/cps/FunctionGen.h index 7ebb7f4..1dc3901 100644 --- a/include/cps/FunctionGen.h +++ b/include/cps/FunctionGen.h @@ -16,9 +16,10 @@ class FunctionGen { llvm::Module &Module; llvm::IRBuilder<> &Builder; TypeSystem &Types; - + std::map &NamedValues; std::map &Symbols; + bool &HadError; void createArgumentAllocas(llvm::Function *F, const std::vector> &Args); @@ -28,8 +29,9 @@ public: llvm::IRBuilder<> &B, TypeSystem &TS, std::map &NV, - std::map &Sym) - : Context(C), Module(M), Builder(B), Types(TS), NamedValues(NV), Symbols(Sym) {} + std::map &Sym, + bool &HadErrorFlag) + : Context(C), Module(M), Builder(B), Types(TS), NamedValues(NV), Symbols(Sym), HadError(HadErrorFlag) {} llvm::Type *getLLVMType(const std::string &TypeName); diff --git a/include/cps/Lexer.h b/include/cps/Lexer.h index e8d2609..f1def3e 100644 --- a/include/cps/Lexer.h +++ b/include/cps/Lexer.h @@ -80,6 +80,7 @@ enum Token { class Lexer { int CurrentLine = 1; + bool HadError = false; public: std::string IdentifierStr; std::string StringVal; @@ -89,6 +90,7 @@ public: int gettok(); int getLine() const { return CurrentLine; } + bool hadError() const { return HadError; } }; } diff --git a/include/cps/Parser.h b/include/cps/Parser.h index 19f49be..87d1dee 100644 --- a/include/cps/Parser.h +++ b/include/cps/Parser.h @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -12,7 +13,8 @@ namespace cps { class Parser { Lexer &Lex; int CurTok; - + unsigned NumErrors = 0; + std::map BinopPrecedence; int getNextToken(); @@ -31,6 +33,7 @@ class Parser { std::unique_ptr ParseStringBuiltin(const std::string &FuncName); std::unique_ptr ParseStatement(); + std::unique_ptr ParseStatementImpl(); std::unique_ptr ParseIfStmt(); std::unique_ptr ParseWhileStmt(); std::unique_ptr ParseRepeatStmt(); @@ -42,11 +45,12 @@ class Parser { std::unique_ptr ParseProcedure(); std::unique_ptr ParseCallStmt(); std::unique_ptr ParseReturnStmt(); - std::vector> ParsePrototypeArgs(); - + std::optional>> ParsePrototypeArgs(); + public: Parser(Lexer &L); std::vector> Parse(); + bool hadError() const { return NumErrors != 0; } }; } // namespace cps diff --git a/lib/CodeGen/ArithmeticHandler.cc b/lib/CodeGen/ArithmeticHandler.cc index 585104d..b909abc 100644 --- a/lib/CodeGen/ArithmeticHandler.cc +++ b/lib/CodeGen/ArithmeticHandler.cc @@ -49,7 +49,8 @@ Value *ArithmeticHandler::emitBinaryOp(int Op, Value *LHS, Value *RHS, int Line) if (Op == tok_div || Op == tok_mod) { if (!LIsInt || !RIsInt) { - fprintf(stderr, "Error: DIV and MOD operators require INTEGER operands.\n"); + fprintf(stderr, "Error: DIV and MOD operators require INTEGER operands (line %d).\n", Line); + HadError = true; return nullptr; } if (Op == tok_div) return Builder.CreateSDiv(LHS, RHS, "div_int_tmp"); @@ -106,6 +107,8 @@ Value *ArithmeticHandler::emitBinaryOp(int Op, Value *LHS, Value *RHS, int Line) case tok_ge: return Builder.CreateICmpSGE(LHS, RHS, "sgetmp"); } } - + + fprintf(stderr, "Error: Unsupported operand types for binary operator (line %d).\n", Line); + HadError = true; return nullptr; } diff --git a/lib/CodeGen/ArrayHandler.cc b/lib/CodeGen/ArrayHandler.cc index fd55009..aa7230a 100644 --- a/lib/CodeGen/ArrayHandler.cc +++ b/lib/CodeGen/ArrayHandler.cc @@ -88,7 +88,7 @@ void ArrayHandler::emitArrayDeclare(ArrayDeclareStmtAST *Stmt, CodeGen &CG) { const TypeInfo *ElemInfo = Types.resolve(Stmt->getType()); if (!ElemInfo || !ElemInfo->LLVMType || ElemInfo->isVoid()) { - fprintf(stderr, "Error: Unknown array element type %s\n", Stmt->getType().c_str()); + CG.reportError("Unknown array element type %s", Stmt->getType().c_str()); return; } @@ -148,30 +148,39 @@ void ArrayHandler::emitArrayDeclare(ArrayDeclareStmtAST *Stmt, CodeGen &CG) { CG.registerSymbol(Name, Alloca, ElemInfo->Name, true); } -Value *ArrayHandler::emitArrayAccess(ArrayAccessExprAST *Expr, CodeGen &CG) { - std::string Name = Expr->getName(); +bool ArrayHandler::emitCheckedIndices(const std::string &Name, + const std::vector> &IndexExprs, + int Line, + bool RequireExact, + CodeGen &CG, + std::vector &Out) { const ArrayMetadata *Meta = getMetadata(Name); if (!Meta) { - fprintf(stderr, "Error: Undeclared array %s\n", Name.c_str()); - return nullptr; + CG.reportError("Undeclared array %s", Name.c_str()); + return false; } - if (Expr->getIndices().size() != static_cast(Meta->Rank)) { - fprintf(stderr, "Error: Incorrect number of indices for %s\n", Name.c_str()); - return nullptr; + size_t Rank = static_cast(Meta->Rank); + if (IndexExprs.size() > Rank || (RequireExact && IndexExprs.size() != Rank)) { + CG.reportError("Incorrect number of indices for %s", Name.c_str()); + return false; } - std::vector Indices; - for (size_t i = 0; i < Expr->getIndices().size(); ++i) { - Value *Idx = CG.emitExpr(Expr->getIndices()[i].get()); + for (size_t i = 0; i < IndexExprs.size(); ++i) { + Value *Idx = CG.emitExpr(IndexExprs[i].get()); Idx = CG.coerceValueToType(Idx, CG.resolveType("INTEGER")); - if (!Idx) return nullptr; + if (!Idx) return false; - Indices.push_back(Idx); - RuntimeChecker.emitIndexCheck(Idx, Meta->LowerBounds[i], Meta->UpperBounds[i], Expr->getLine()); + Out.push_back(Idx); + RuntimeChecker.emitIndexCheck(Idx, Meta->LowerBounds[i], Meta->UpperBounds[i], Line); } + return true; +} + +Value *ArrayHandler::loadElement(const std::string &Name, Value *Offset, CodeGen &CG) { + const ArrayMetadata *Meta = getMetadata(Name); + if (!Meta) return nullptr; - Value *Offset = computeFlatIndex(Name, Indices); Value *ElemPtr = getElementPointer(Name, Offset); if (!ElemPtr) return nullptr; @@ -185,29 +194,23 @@ Value *ArrayHandler::emitArrayAccess(ArrayAccessExprAST *Expr, CodeGen &CG) { return Val; } -void ArrayHandler::emitArrayAssign(ArrayAssignStmtAST *Stmt, CodeGen &CG) { - std::string Name = Stmt->getName(); - const ArrayMetadata *Meta = getMetadata(Name); - if (!Meta) { - fprintf(stderr, "Error: Undeclared array %s\n", Name.c_str()); - return; - } +Value *ArrayHandler::emitArrayAccess(ArrayAccessExprAST *Expr, CodeGen &CG) { + std::string Name = Expr->getName(); + std::vector Indices; + if (!emitCheckedIndices(Name, Expr->getIndices(), Expr->getLine(), true, CG, Indices)) + return nullptr; - if (Stmt->getIndices().size() != static_cast(Meta->Rank)) { - fprintf(stderr, "Error: Incorrect number of indices for %s\n", Name.c_str()); - return; - } + Value *Offset = computeFlatIndex(Name, Indices); + return loadElement(Name, Offset, CG); +} +void ArrayHandler::emitArrayAssign(ArrayAssignStmtAST *Stmt, CodeGen &CG) { + std::string Name = Stmt->getName(); std::vector Indices; - for (size_t i = 0; i < Stmt->getIndices().size(); ++i) { - Value *Idx = CG.emitExpr(Stmt->getIndices()[i].get()); - Idx = CG.coerceValueToType(Idx, CG.resolveType("INTEGER")); - if (!Idx) return; - - Indices.push_back(Idx); - RuntimeChecker.emitIndexCheck(Idx, Meta->LowerBounds[i], Meta->UpperBounds[i], Stmt->getLine()); - } + if (!emitCheckedIndices(Name, Stmt->getIndices(), Stmt->getLine(), true, CG, Indices)) + return; + const ArrayMetadata *Meta = getMetadata(Name); const TypeInfo *ElemInfo = Types.resolve(Meta->ElementTypeName); Value *Val = CG.emitExpr(Stmt->getExpr()); Val = CG.coerceValueToType(Val, ElemInfo); @@ -222,7 +225,8 @@ void ArrayHandler::emitArrayAssign(ArrayAssignStmtAST *Stmt, CodeGen &CG) { bool ArrayHandler::tryEmitArrayOutput(ExprAST *Expr, CodeGen &CG) { std::string Name; - std::vector Indices; + const std::vector> *IndexExprs = nullptr; + int Line = 0; if (auto *Var = dynamic_cast(Expr)) { Name = Var->getName(); @@ -231,27 +235,18 @@ bool ArrayHandler::tryEmitArrayOutput(ExprAST *Expr, CodeGen &CG) { Name = Acc->getName(); const ArrayMetadata *Meta = getMetadata(Name); if (!Meta) return false; - - for (size_t i = 0; i < Acc->getIndices().size(); ++i) { - Value *Idx = CG.emitExpr(Acc->getIndices()[i].get()); - Idx = CG.coerceValueToType(Idx, CG.resolveType("INTEGER")); - if (!Idx) return false; - Indices.push_back(Idx); - RuntimeChecker.emitIndexCheck(Idx, Meta->LowerBounds[i], Meta->UpperBounds[i], Acc->getLine()); - } - - if (Indices.size() > static_cast(Meta->Rank)) { - fprintf(stderr, "Error: Incorrect number of indices for %s\n", Name.c_str()); - return true; + if (Acc->getIndices().size() == static_cast(Meta->Rank)) { + return false; // full element access: handled by the normal expression path } + IndexExprs = &Acc->getIndices(); + Line = Acc->getLine(); } else { return false; } - const ArrayMetadata *Meta = getMetadata(Name); - if (!Meta) return false; - if (Indices.size() == static_cast(Meta->Rank)) { - return false; + std::vector Indices; + if (IndexExprs && !emitCheckedIndices(Name, *IndexExprs, Line, false, CG, Indices)) { + return true; // diagnosed } emitPrintLoop(Name, static_cast(Indices.size()), Indices, CG); @@ -267,16 +262,8 @@ void ArrayHandler::emitPrintLoop(const std::string &Name, if (CurrentDim == Meta->Rank) { Value *Offset = computeFlatIndex(Name, CurrentIndices); - Value *ElemPtr = getElementPointer(Name, Offset); - if (!ElemPtr) return; - - Value *Val = Builder->CreateLoad(Meta->ElementType, ElemPtr, Name + "_print_val"); - if (Meta->ElementTypeName == "STRING") { - Value *IsNull = Builder->CreateICmpEQ(Val, - ConstantPointerNull::get(cast(Meta->ElementType)), - Name + "_print_str_is_null"); - Val = Builder->CreateSelect(IsNull, CG.EmptyStringStr, Val, Name + "_print_safe_str"); - } + Value *Val = loadElement(Name, Offset, CG); + if (!Val) return; CG.emitOutputValue(Val, Types.resolve(Meta->ElementTypeName), true); return; diff --git a/lib/CodeGen/CodeGen.cc b/lib/CodeGen/CodeGen.cc index c77f5d8..439e894 100644 --- a/lib/CodeGen/CodeGen.cc +++ b/lib/CodeGen/CodeGen.cc @@ -3,6 +3,7 @@ #include "cps/Lexer.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Verifier.h" +#include #include using namespace llvm; @@ -10,6 +11,16 @@ using namespace cps; CodeGen::~CodeGen() = default; +void CodeGen::reportError(const char *Fmt, ...) { + va_list Args; + va_start(Args, Fmt); + fprintf(stderr, "Error: "); + vfprintf(stderr, Fmt, Args); + fprintf(stderr, "\n"); + va_end(Args); + HadError = true; +} + CodeGen::CodeGen() { TheContext = std::make_unique(); TheModule = std::make_unique("cps_module", *TheContext); @@ -31,12 +42,13 @@ CodeGen::CodeGen() { *Builder, *Types, NamedValues, - Symbols); + Symbols, + HadError); IntHandler = std::make_unique(*TheContext, *Builder, *TheModule, NamedValues); RealHelper = std::make_unique(*TheContext, *Builder, *TheModule, NamedValues); BoolHandler = std::make_unique(*TheContext, *Builder, *TheModule, NamedValues); - ArithHandler = std::make_unique(*TheContext, *Builder); + ArithHandler = std::make_unique(*TheContext, *Builder, HadError); StrHandler = std::make_unique(*TheContext, *Builder, *TheModule, NamedValues); ChrHandler = std::make_unique(*TheContext, *Builder, *TheModule); StrConvHandler = std::make_unique(*TheContext, *Builder, *TheModule); @@ -282,8 +294,7 @@ Value *CodeGen::coerceValueToType(Value *Val, const TypeInfo *TargetInfo) { break; } - fprintf(stderr, - "Error: Cannot coerce value of LLVM type to target type %s\n", + reportError("Cannot coerce value of LLVM type to target type %s", TargetInfo->Name.c_str()); return nullptr; } @@ -291,7 +302,7 @@ Value *CodeGen::coerceValueToType(Value *Val, const TypeInfo *TargetInfo) { void CodeGen::emitDeclareStmt(DeclareStmtAST *Stmt) { const TypeInfo *Info = resolveType(Stmt->getType()); if (!Info || !Info->LLVMType || Info->isVoid()) { - fprintf(stderr, "Error: Unknown type %s\n", Stmt->getType().c_str()); + reportError("Unknown type %s", Stmt->getType().c_str()); return; } @@ -315,7 +326,7 @@ void CodeGen::emitDeclareStmt(DeclareStmtAST *Stmt) { void CodeGen::emitOutputValue(Value *Val, const TypeInfo *Info, bool AppendNewline) { if (!Val || !Info) return; if (!Info->Printable && Info->Kind == TypeKind::Custom) { - fprintf(stderr, "Error: OUTPUT for custom type %s is not implemented yet\n", Info->Name.c_str()); + reportError("OUTPUT for custom type %s is not implemented yet", Info->Name.c_str()); return; } @@ -382,7 +393,9 @@ void CodeGen::compile(const std::vector> &Statements) { Builder->CreateRet(ConstantInt::get(*TheContext, APInt(32, 0))); } - verifyFunction(*F); + if (verifyModule(*TheModule, &errs())) { + HadError = true; + } } void CodeGen::print() { @@ -415,7 +428,7 @@ Value *CodeGen::emitExpr(ExprAST *Expr) { if (auto *Var = dynamic_cast(Expr)) { const SymbolInfo *Info = getSymbolInfo(Var->getName()); if (!Info) { - fprintf(stderr, "Error: Unknown variable name %s\n", Var->getName().c_str()); + reportError("Unknown variable name %s", Var->getName().c_str()); return nullptr; } if (Info->IsArray) { @@ -424,7 +437,7 @@ Value *CodeGen::emitExpr(ExprAST *Expr) { const TypeInfo *TypeInfo = resolveType(Info->TypeName); if (!TypeInfo || !TypeInfo->LLVMType) { - fprintf(stderr, "Error: Unknown type for variable %s\n", Var->getName().c_str()); + reportError("Unknown type for variable %s", Var->getName().c_str()); return nullptr; } @@ -462,35 +475,41 @@ Value *CodeGen::emitExpr(ExprAST *Expr) { if (auto *Call = dynamic_cast(Expr)) { std::string Name = Call->getCallee(); if (Name == "LENGTH") { - if (Call->getArgs().size() != 1) { fprintf(stderr, "LENGTH expects 1 arg\n"); return nullptr; } + if (Call->getArgs().size() != 1) { reportError("LENGTH expects 1 arg"); return nullptr; } return StrHandler->emitLength(emitExpr(Call->getArgs()[0].get())); } if (Name == "MID") { - if (Call->getArgs().size() != 3) { fprintf(stderr, "MID expects 3 args\n"); return nullptr; } - return StrHandler->emitMid(emitExpr(Call->getArgs()[0].get()), - emitExpr(Call->getArgs()[1].get()), - emitExpr(Call->getArgs()[2].get())); + if (Call->getArgs().size() != 3) { reportError("MID expects 3 args"); return nullptr; } + Value *Str = emitExpr(Call->getArgs()[0].get()); + Value *Start = coerceValueToType(emitExpr(Call->getArgs()[1].get()), resolveType("INTEGER")); + Value *Len = coerceValueToType(emitExpr(Call->getArgs()[2].get()), resolveType("INTEGER")); + if (!Str || !Start || !Len) return nullptr; + return StrHandler->emitMid(Str, Start, Len); } if (Name == "RIGHT") { - if (Call->getArgs().size() != 2) { fprintf(stderr, "RIGHT expects 2 args\n"); return nullptr; } - return StrHandler->emitRight(emitExpr(Call->getArgs()[0].get()), - emitExpr(Call->getArgs()[1].get())); + if (Call->getArgs().size() != 2) { reportError("RIGHT expects 2 args"); return nullptr; } + Value *Str = emitExpr(Call->getArgs()[0].get()); + Value *Len = coerceValueToType(emitExpr(Call->getArgs()[1].get()), resolveType("INTEGER")); + if (!Str || !Len) return nullptr; + return StrHandler->emitRight(Str, Len); } if (Name == "LEFT") { - if (Call->getArgs().size() != 2) { fprintf(stderr, "LEFT expects 2 args\n"); return nullptr; } - return StrHandler->emitLeft(emitExpr(Call->getArgs()[0].get()), - emitExpr(Call->getArgs()[1].get())); + if (Call->getArgs().size() != 2) { reportError("LEFT expects 2 args"); return nullptr; } + Value *Str = emitExpr(Call->getArgs()[0].get()); + Value *Len = coerceValueToType(emitExpr(Call->getArgs()[1].get()), resolveType("INTEGER")); + if (!Str || !Len) return nullptr; + return StrHandler->emitLeft(Str, Len); } if (Name == "LCASE") { - if (Call->getArgs().size() != 1) { fprintf(stderr, "LCASE expects 1 arg\n"); return nullptr; } + if (Call->getArgs().size() != 1) { reportError("LCASE expects 1 arg"); return nullptr; } return StrHandler->emitLCase(emitExpr(Call->getArgs()[0].get())); } if (Name == "UCASE") { - if (Call->getArgs().size() != 1) { fprintf(stderr, "UCASE expects 1 arg\n"); return nullptr; } + if (Call->getArgs().size() != 1) { reportError("UCASE expects 1 arg"); return nullptr; } return StrHandler->emitUCase(emitExpr(Call->getArgs()[0].get())); } if (Name == "ASC") { - if (Call->getArgs().size() != 1) return nullptr; + if (Call->getArgs().size() != 1) { reportError("ASC expects 1 arg"); return nullptr; } Value *ArgVal = emitExpr(Call->getArgs()[0].get()); const TypeInfo *ArgType = getExprTypeInfo(Call->getArgs()[0].get()); Value *CharVal = nullptr; @@ -503,7 +522,7 @@ Value *CodeGen::emitExpr(ExprAST *Expr) { return coerceValueToType(AscVal, resolveType("INTEGER")); } if (Name == "CHR") { - if (Call->getArgs().size() != 1) return nullptr; + if (Call->getArgs().size() != 1) { reportError("CHR expects 1 arg"); return nullptr; } Value *IntVal = coerceValueToType(emitExpr(Call->getArgs()[0].get()), resolveType("INTEGER")); Value *CharVal = ChrHandler->emitChr(IntVal); Function *MallocF = TheModule->getFunction("malloc"); @@ -516,11 +535,11 @@ Value *CodeGen::emitExpr(ExprAST *Expr) { return Mem; } if (Name == "IS_NUM") { - if (Call->getArgs().size() != 1) return nullptr; + if (Call->getArgs().size() != 1) { reportError("IS_NUM expects 1 arg"); return nullptr; } return StrConvHandler->emitIsNum(emitExpr(Call->getArgs()[0].get())); } if (Name == "NUM_TO_STR") { - if (Call->getArgs().size() != 1) return nullptr; + if (Call->getArgs().size() != 1) { reportError("NUM_TO_STR expects 1 arg"); return nullptr; } Value *NumV = emitExpr(Call->getArgs()[0].get()); bool IsReal = NumV->getType()->isDoubleTy(); if (NumV->getType()->isIntegerTy(8)) { @@ -529,7 +548,7 @@ Value *CodeGen::emitExpr(ExprAST *Expr) { return StrConvHandler->emitNumToStr(NumV, IsReal); } if (Name == "STR_TO_NUM") { - if (Call->getArgs().size() != 1) return nullptr; + if (Call->getArgs().size() != 1) { reportError("STR_TO_NUM expects 1 arg"); return nullptr; } return StrConvHandler->emitStrToNum(emitExpr(Call->getArgs()[0].get()), true); } @@ -550,12 +569,12 @@ Value *CodeGen::emitExpr(ExprAST *Expr) { if (auto *Var = dynamic_cast(ArgExpr)) { Value *Ptr = getNamedValue(Var->getName()); if (!Ptr) { - fprintf(stderr, "Error: Unknown variable %s in BYREF call\n", Var->getName().c_str()); + reportError("Unknown variable %s in BYREF call", Var->getName().c_str()); return nullptr; } Args.push_back(Ptr); } else { - fprintf(stderr, "Error: BYREF argument must be a variable.\n"); + reportError("BYREF argument must be a variable."); return nullptr; } } else { @@ -647,11 +666,11 @@ void CodeGen::emitForStmt(ForStmtAST *Stmt) { const SymbolInfo *Symbol = getSymbolInfo(VarName); if (!Symbol) { - fprintf(stderr, "Error: Unknown variable in FOR loop %s\n", VarName.c_str()); + reportError("Unknown variable in FOR loop %s", VarName.c_str()); return; } if (Symbol->TypeName != "INTEGER") { - fprintf(stderr, "Error: FOR loop variable %s must be INTEGER\n", VarName.c_str()); + reportError("FOR loop variable %s must be INTEGER", VarName.c_str()); return; } @@ -673,16 +692,21 @@ void CodeGen::emitForStmt(ForStmtAST *Stmt) { Value *EndVal = coerceValueToType(emitExpr(Stmt->getEnd()), resolveType("INTEGER")); if (!EndVal) return; - bool IsNegativeStep = false; + Value *StepVal = nullptr; if (Stmt->getStep()) { - if (auto *Num = dynamic_cast(Stmt->getStep())) { - if (Num->getVal() < 0) IsNegativeStep = true; - } + StepVal = coerceValueToType(emitExpr(Stmt->getStep()), resolveType("INTEGER")); + if (!StepVal) return; + } else { + StepVal = ConstantInt::get(*TheContext, APInt(64, 1)); } - Value *CondV = IsNegativeStep - ? Builder->CreateICmpSGE(CurVar, EndVal, "forcond_ge") - : Builder->CreateICmpSLE(CurVar, EndVal, "forcond_le"); + // The loop direction depends on the STEP value at run time. + Value *StepNonNeg = Builder->CreateICmpSGE(StepVal, + ConstantInt::get(*TheContext, APInt(64, 0)), + "step_nonneg"); + Value *CondUp = Builder->CreateICmpSLE(CurVar, EndVal, "forcond_le"); + Value *CondDown = Builder->CreateICmpSGE(CurVar, EndVal, "forcond_ge"); + Value *CondV = Builder->CreateSelect(StepNonNeg, CondUp, CondDown, "forcond"); Builder->CreateCondBr(CondV, LoopBB, AfterBB); @@ -692,13 +716,6 @@ void CodeGen::emitForStmt(ForStmtAST *Stmt) { Builder->CreateBr(IncBB); Builder->SetInsertPoint(IncBB); - Value *StepVal = nullptr; - if (Stmt->getStep()) { - StepVal = coerceValueToType(emitExpr(Stmt->getStep()), resolveType("INTEGER")); - } else { - StepVal = ConstantInt::get(*TheContext, APInt(64, 1)); - } - Value *CurValForInc = Builder->CreateLoad(Type::getInt64Ty(*TheContext), Alloca, VarName.c_str()); Value *NextVal = Builder->CreateAdd(CurValForInc, StepVal, "nextval"); Builder->CreateStore(NextVal, Alloca); @@ -749,12 +766,12 @@ void CodeGen::emitStmt(StmtAST *Stmt) { if (auto *Var = dynamic_cast(ArgExpr)) { Value *Ptr = getNamedValue(Var->getName()); if (!Ptr) { - fprintf(stderr, "Error: Unknown variable %s in BYREF call\n", Var->getName().c_str()); + reportError("Unknown variable %s in BYREF call", Var->getName().c_str()); return; } Args.push_back(Ptr); } else { - fprintf(stderr, "Error: BYREF argument must be a variable.\n"); + reportError("BYREF argument must be a variable."); return; } } else { @@ -782,11 +799,11 @@ void CodeGen::emitStmt(StmtAST *Stmt) { if (auto *Assign = dynamic_cast(Stmt)) { const SymbolInfo *Info = getSymbolInfo(Assign->getName()); if (!Info) { - fprintf(stderr, "Error: Unknown variable name %s\n", Assign->getName().c_str()); + reportError("Unknown variable name %s", Assign->getName().c_str()); return; } if (Info->IsArray) { - fprintf(stderr, "Error: Cannot assign array %s without indices\n", Assign->getName().c_str()); + reportError("Cannot assign array %s without indices", Assign->getName().c_str()); return; } @@ -802,17 +819,17 @@ void CodeGen::emitStmt(StmtAST *Stmt) { if (auto *In = dynamic_cast(Stmt)) { const SymbolInfo *Info = getSymbolInfo(In->getName()); if (!Info) { - fprintf(stderr, "Error: Unknown variable name %s\n", In->getName().c_str()); + reportError("Unknown variable name %s", In->getName().c_str()); return; } if (Info->IsArray) { - fprintf(stderr, "Error: INPUT for entire array %s is not supported\n", In->getName().c_str()); + reportError("INPUT for entire array %s is not supported", In->getName().c_str()); return; } const TypeInfo *TypeInfo = resolveType(Info->TypeName); if (!TypeInfo) { - fprintf(stderr, "Error: Unknown type for INPUT %s\n", In->getName().c_str()); + reportError("Unknown type for INPUT %s", In->getName().c_str()); return; } diff --git a/lib/CodeGen/FunctionGen.cc b/lib/CodeGen/FunctionGen.cc index 89aa3d8..0a22278 100644 --- a/lib/CodeGen/FunctionGen.cc +++ b/lib/CodeGen/FunctionGen.cc @@ -9,6 +9,7 @@ Type *FunctionGen::getLLVMType(const std::string &TypeName) { Type *Resolved = Types.getLLVMType(TypeName); if (!Resolved) { fprintf(stderr, "Error: Unknown type %s\n", TypeName.c_str()); + HadError = true; return Type::getInt64Ty(Context); } return Resolved; @@ -78,6 +79,7 @@ Function *FunctionGen::emitFunctionDef(FunctionDefAST *FuncAST, if (!TheFunction) return nullptr; if (!TheFunction->empty()) { fprintf(stderr, "Error: Function %s cannot be redefined.\n", Proto->getName().c_str()); + HadError = true; return nullptr; } @@ -103,7 +105,6 @@ Function *FunctionGen::emitFunctionDef(FunctionDefAST *FuncAST, } } - verifyFunction(*TheFunction); NamedValues = OldNamedValues; Symbols = OldSymbols; return TheFunction; @@ -113,7 +114,8 @@ static Value *GenerateCall(llvm::Module &Module, llvm::IRBuilder<> &Builder, llvm::LLVMContext &Context, const std::string &CalleeName, - const std::vector &Args) { + const std::vector &Args, + bool &HadError) { Function *CalleeF = Module.getFunction(CalleeName); if (!CalleeF) { std::vector ArgTypes; @@ -124,6 +126,7 @@ static Value *GenerateCall(llvm::Module &Module, if (CalleeF->arg_size() != Args.size()) { fprintf(stderr, "Error: Incorrect # arguments passed to %s\n", CalleeName.c_str()); + HadError = true; return nullptr; } @@ -135,11 +138,11 @@ static Value *GenerateCall(llvm::Module &Module, } llvm::Value *FunctionGen::emitCallExpr(CallExprAST *Call, const std::vector &Args) { - return GenerateCall(Module, Builder, Context, Call->getCallee(), Args); + return GenerateCall(Module, Builder, Context, Call->getCallee(), Args, HadError); } void FunctionGen::emitCallStmt(CallStmtAST *Call, const std::vector &Args) { - GenerateCall(Module, Builder, Context, Call->getCallee(), Args); + GenerateCall(Module, Builder, Context, Call->getCallee(), Args, HadError); } void FunctionGen::emitReturn(ReturnStmtAST *Ret, llvm::Value *RetVal) { diff --git a/lib/CodeGen/StringHandler.cc b/lib/CodeGen/StringHandler.cc index f777059..e5971d0 100644 --- a/lib/CodeGen/StringHandler.cc +++ b/lib/CodeGen/StringHandler.cc @@ -114,12 +114,6 @@ Value *StringHandler::emitRight(Value *Str, Value *Len) { Value *StringHandler::emitLeft(Value *Str, Value *Len) { Value *FullLen = emitLength(Str); - if (Len->getType()->isIntegerTy() && Len->getType()->getIntegerBitWidth() != 64) { - Len = Builder.CreateSExt(Len, Type::getInt64Ty(Context), "len_ext"); - } - else if (Len->getType()->isDoubleTy()) { - Len = Builder.CreateFPToSI(Len, Type::getInt64Ty(Context), "len_int"); - } Value *Zero = ConstantInt::get(Context, APInt(64, 0)); Value *IsNeg = Builder.CreateICmpSLT(Len, Zero); diff --git a/lib/Lexer/Lexer.cc b/lib/Lexer/Lexer.cc index 9a8e767..d678097 100644 --- a/lib/Lexer/Lexer.cc +++ b/lib/Lexer/Lexer.cc @@ -27,7 +27,8 @@ int Lexer::gettok() { if (LastChar == '"') { LastChar = getchar(); } else { - fprintf(stderr, "Error: Unterminated string literal\n"); + fprintf(stderr, "Error: Unterminated string literal at line %d\n", CurrentLine); + HadError = true; } return tok_string_literal; @@ -36,16 +37,26 @@ int Lexer::gettok() { if (LastChar == '\'') { int CharCode = getchar(); if (CharCode == EOF || CharCode == '\n') { - fprintf(stderr, "Error: Unterminated char literal\n"); - return tok_eof; + fprintf(stderr, "Error: Unterminated char literal at line %d\n", CurrentLine); + HadError = true; + CharVal = '?'; + StringVal.assign(1, CharVal); + // Leave the newline/EOF for the main loop so line counting stays right. + LastChar = CharCode; + return tok_char_literal; } int ClosingQuote = getchar(); if (ClosingQuote != '\'') { - fprintf(stderr, "Error: CHAR literal must contain exactly one character\n"); + fprintf(stderr, "Error: CHAR literal must contain exactly one character (line %d)\n", CurrentLine); + HadError = true; while (ClosingQuote != EOF && ClosingQuote != '\n' && ClosingQuote != '\'') { ClosingQuote = getchar(); } + CharVal = static_cast(CharCode); + StringVal.assign(1, CharVal); + LastChar = (ClosingQuote == '\'') ? getchar() : ClosingQuote; + return tok_char_literal; } CharVal = static_cast(CharCode); diff --git a/lib/Parser/Parser.cc b/lib/Parser/Parser.cc index 322cdb9..049f99d 100644 --- a/lib/Parser/Parser.cc +++ b/lib/Parser/Parser.cc @@ -271,12 +271,18 @@ std::vector> Parser::Parse() { } std::unique_ptr Parser::ParseDeclare() { - getNextToken(); - if (CurTok != tok_identifier) return nullptr; + getNextToken(); + if (CurTok != tok_identifier) { + fprintf(stderr, "Error: Expected identifier after DECLARE at line %d\n", Lex.getLine()); + return nullptr; + } std::string Name = Lex.IdentifierStr; getNextToken(); - - if (CurTok != tok_colon) return nullptr; + + if (CurTok != tok_colon) { + fprintf(stderr, "Error: Expected ':' after variable name '%s' at line %d\n", Name.c_str(), Lex.getLine()); + return nullptr; + } getNextToken(); if (CurTok == tok_array) { @@ -485,6 +491,12 @@ std::unique_ptr Parser::ParseForStmt() { } std::unique_ptr Parser::ParseStatement() { + auto Stmt = ParseStatementImpl(); + if (!Stmt) ++NumErrors; + return Stmt; +} + +std::unique_ptr Parser::ParseStatementImpl() { if (CurTok == tok_declare) { return ParseDeclare(); } @@ -515,7 +527,10 @@ std::unique_ptr Parser::ParseStatement() { return std::make_unique(Name, std::move(Indices), std::move(Expr), Line); } - if (CurTok != tok_assign) return nullptr; + if (CurTok != tok_assign) { + fprintf(stderr, "Error: Expected '<-' after identifier '%s' at line %d\n", Name.c_str(), Line); + return nullptr; + } getNextToken(); auto Expr = ParseExpression(); if (!Expr) return nullptr; @@ -523,7 +538,10 @@ std::unique_ptr Parser::ParseStatement() { } else if (CurTok == tok_input) { getNextToken(); - if (CurTok != tok_identifier) return nullptr; + if (CurTok != tok_identifier) { + fprintf(stderr, "Error: Expected variable name after INPUT at line %d\n", Lex.getLine()); + return nullptr; + } std::string Name = Lex.IdentifierStr; getNextToken(); return std::make_unique(Name); @@ -559,5 +577,6 @@ std::unique_ptr Parser::ParseStatement() { return ParseReturnStmt(); } + fprintf(stderr, "Error: Unexpected token at line %d when expecting a statement\n", Lex.getLine()); return nullptr; } diff --git a/lib/Parser/ParserFunction.cc b/lib/Parser/ParserFunction.cc index 05b1e12..06348c4 100644 --- a/lib/Parser/ParserFunction.cc +++ b/lib/Parser/ParserFunction.cc @@ -5,7 +5,7 @@ using namespace cps; -std::vector> Parser::ParsePrototypeArgs() { +std::optional>> Parser::ParsePrototypeArgs() { std::vector> Args; if (CurTok != '(') return Args; getNextToken(); @@ -24,21 +24,21 @@ std::vector> Parser::ParsePrototypeAr if (CurTok != tok_identifier) { fprintf(stderr, "Error: Expected argument name\n"); - return Args; + return std::nullopt; } std::string Name = Lex.IdentifierStr; getNextToken(); if (CurTok != tok_colon) { fprintf(stderr, "Error: Expected ':' after argument name\n"); - return Args; + return std::nullopt; } getNextToken(); std::string Type = ParseTypeName(false); if (Type.empty()) { fprintf(stderr, "Error: Expected argument type for '%s'\n", Name.c_str()); - return Args; + return std::nullopt; } Args.emplace_back(Name, Type, IsRef); @@ -46,7 +46,7 @@ std::vector> Parser::ParsePrototypeAr if (CurTok == ')') break; if (CurTok != ',') { fprintf(stderr, "Error: Expected ',' or ')'\n"); - return Args; + return std::nullopt; } getNextToken(); } @@ -65,6 +65,7 @@ std::unique_ptr Parser::ParseFunction() { getNextToken(); auto Args = ParsePrototypeArgs(); + if (!Args) return nullptr; std::string RetType = "INTEGER"; if (CurTok == tok_returns) { @@ -76,7 +77,7 @@ std::unique_ptr Parser::ParseFunction() { } } - auto Proto = std::make_unique(Name, std::move(Args), RetType); + auto Proto = std::make_unique(Name, std::move(*Args), RetType); std::vector> Body; while (CurTok != tok_endfunction && CurTok != tok_eof) { @@ -105,7 +106,8 @@ std::unique_ptr Parser::ParseProcedure() { getNextToken(); auto Args = ParsePrototypeArgs(); - auto Proto = std::make_unique(Name, std::move(Args), "VOID"); + if (!Args) return nullptr; + auto Proto = std::make_unique(Name, std::move(*Args), "VOID"); std::vector> Body; while (CurTok != tok_endprocedure && CurTok != tok_eof) { diff --git a/tools/driver/main.cc b/tools/driver/main.cc index e83a408..ca978b5 100644 --- a/tools/driver/main.cc +++ b/tools/driver/main.cc @@ -13,5 +13,5 @@ int main() { CG.print(); - return 0; + return (Lex.hadError() || Parser.hadError() || CG.hadError()) ? 1 : 0; } -- cgit v1.3.1-4-g156e