aboutsummaryrefslogtreecommitdiff
path: root/lib/CodeGen/CodeGen.cc
AgeCommit message (Collapse)Author
2026-10-13feat: support comma-separated OUTPUT expressions_ov4
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-13fix: check division and modulo for zero divisors_ov4
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-13fix: compare strings by content_ov4
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-13feat: compile source files with configurable IR output_ov4
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-07-26fix: top-level RETURN and READFILE designator targets error cleanly_ov4
- RETURN outside any FUNCTION/PROCEDURE used to emit an i64/void ret inside i32 main — a verifier dump instead of a diagnostic. It is now a clean compile error (no signature means top level: pseudocode cannot name a function 'main', it is a reserved runtime symbol). - READFILE "f.txt", r.f mis-parsed into an error cascade the same way INPUT r.f did before its fix; the target now consumes the designator and reports one clear 'must be a plain STRING variable' error. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26fix: close type-safety holes found by adversarial review; update docs_ov4
Review findings (all reproduced, then fixed and re-verified): - '^x' leaked as a raw address into any builtin context (s <- ^x printed the variable's bytes as a C string; NOT ^x, '&', and ^x = ^x compiled). Address-of is now rejected everywhere except a pointer-typed target. - A whole-array variable passed the nominal gate as a value of its ELEMENT type (s <- arrayOfSeason stored the raw data pointer; = on it emitted invalid IR). Whole arrays are now rejected as operands and as coercion sources; array parameters are unaffected. - Enum values smuggled into INTEGER through array subscripts and DECLARE bounds (a[Autumn], ARRAY[Spring:Winter]); both now go through emitCoercedExpr like every other INTEGER context. - An array DECLAREd inside an IF/WHILE/REPEAT/FOR body and used after the block was a wild-pointer write (constant bounds) or a verifier dump (runtime bounds). Arrays are now block-scoped: control-flow bodies snapshot and restore the ArrayTable, so escape is a clean compile error. - Duplicate parameter names silently shadowed (BYREF write-back defeated); now a parse error. Trailing comma in parameter lists accepted; now a parse error consistent with every other list. - A variable/array/parameter/function could reuse a TYPE name; reserved. - RETURN with a value inside a PROCEDURE was silently discarded (control did not return); now an error, as is a bare RETURN in a FUNCTION. - INPUT r.f mis-parsed into a three-error cascade; now one clear error. - Assigning to an enum constant now says so instead of 'Unknown variable'. Docs: ARCH/CONVENTIONS/EXTENDING/SUBSYSTEMS/PITFALLS rewritten for the TYPE system (ABI additions, nominal-typing invariants, admission-gate doors, array-parameter ABI, new recipes, new sharp edges); README features/TODO updated — random files are unblocked. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26feat: whole arrays (and records) as FUNCTION/PROCEDURE parameters_ov4
- Parameter syntax lands end-to-end: ARRAY OF T (rank 1, bounds travel with the argument) and ARRAY[l:u,...] OF T (any rank, literal bounds as a checked contract). Element type and rank must match exactly. - Flattened ABI: each rank-R array parameter becomes a data pointer plus kBoundArgsPerDim i64 bounds per dimension. The callee rebuilds ArrayMetadata from those bounds (ArrayHandler::bindArrayParameter via a binder callback injected by CodeGen, so FunctionGen stays ignorant of the array subsystem); the checked-indexing pipeline is reused unchanged. - BYVAL (the CIE default) copies the whole buffer at callee entry (malloc+memcpy, never freed — consistent with the string policy) so callee writes stay invisible; BYREF binds the caller's buffer. - Bounded-parameter contract: compile-time comparison when the caller's bounds are constants, else a runtime [Fatal] check (RuntimeCheck::emitArrayArgBoundsCheck). - marshalCallArgs gains the array branch and a call-site line number (CallStmtAST now carries one); whole-array-to-scalar keeps a clear error, FUNCTION RETURNS ARRAY is a dedicated parse error. - Verified: BYREF fill/sort-style mutation, BYVAL copy invisibility, 2-D bounded params, ARRAY OF <record> with field writes through the parameter, bounds-contract mismatches at compile time and run time. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26feat: records with designator lvalues, and pointer types (CIE 4.1/4.2)_ov4
- New CodeGen::emitLValue resolves any designator — variable, checked array element, record field chain (CreateStructGEP via the record payload), pointer deref (with the null-pointer [Fatal] check) — to an address + type name; loadFromLValue centralizes the rvalue read and the STRING null->"" guard, so zero-initialized STRING fields read as "". - Designator assignment stores through emitLValue + emitCoercedExpr; whole-record copies (r2 <- r1, array elements, BYVAL args, RETURN) are aggregate loads/stores with name-checked admission. - getExprTypeInfo walks designator chains statically (field types from the record payload, deref to the pointee), so records/pointers type correctly in every expression context. - Address-of ^x admits into a pointer target only when the designator's type name equals the declared pointee exactly (nominal, strict: the guide's own ^INTEGER-at-a-Season example is a compile error by design); ^arr[i] and ^rec.field work through the same lvalue path. - Verified: the guide's §4.2 StudentRecord example (minus DATE), nested records, arrays of records with Form[i].YearGroup writes, record BYREF/BYVAL params, NodePtr = ^Node forward reference with writes through n1.Next^.Data, unset-pointer deref dying with [Fatal]. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26feat: user type registry and enumerated types (CIE 4.1/4.2)_ov4
- TypeSystem: TypeKinds Enum/Record/Pointer with per-kind payloads and checked accessors; two-pass registration (names first, then definitions in source order) so pointer TYPEs may forward-reference; enum-constant table owned by TypeSystem so constants stay visible inside function bodies across the Symbols save/clear/restore. Dead surface removed (Custom kind, Printable/Builtin/ReferenceLike, ElementSize, hasType, CodeGen::getNamedValue/getLLVMType). - Enums are i64 with 0-based ordinals (constexpr kEnumOrdinalBase); all type identity is by NAME. New emitCoercedExpr is the single admission gate, replacing raw coercion at assignments, array stores, BYVAL args, RETURN, IF/WHILE/REPEAT/FOR operands, file operands and builtin args; coerceValueToType now hard-errors if a user-kind target reaches it. - Binary ops with user-kind operands are intercepted ahead of ArithmeticHandler ('&'-intercept precedent): same-enum comparisons, enum +/- INTEGER (with a runtime range check, [Fatal] on overflow, the only site that can manufacture an invalid ordinal), same-name pointer =/<>; everything else is a compile error naming the operator. - OUTPUT is an exhaustive switch over TypeKind (enum prints its ordinal; record/pointer are compile errors, also covering whole-array OUTPUT); INPUT's silent %lld fallback for unknown kinds is now an explicit error. - Enum value names are globally reserved: collisions with DECLARE, array names, parameters and function names are compile errors. - RuntimeCheck: emitEnumRangeCheck + emitNullDerefCheck (used by the pointer phase) following the emitIndexCheck recipe. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26feat: TYPE-system front end — tokens, designators, ParamDecl grammar_ov4
- Reserve TYPE/ENDTYPE/SET/DEFINE (-600 token block); SET/DEFINE parse to dedicated not-implemented errors (RANDOM precedent). - New TypeAST.h: enum/pointer/record decl nodes, designator chain (DesignatorExprAST + Index/Field/Deref accessors), AddrOfExprAST, DesignatorAssignStmtAST. Bare-name and single-index shapes degrade to their legacy nodes, so existing programs produce identical ASTs. - ParserType.cc: TYPE declarations (top-level only, enforced via a ParseBlock depth counter), DECLARE-only record bodies with local field-level error recovery. - Postfix [ ] . ^ chain in ParseIdentifierExpr; prefix ^ (address-of, designator operand only) in ParseUnary; assignment targets rebuilt on the same suffix parser. - Parameters: ParamDecl{name, type, mode, array rank/bounds} replaces the (name, type, byref) tuple. Pass mode is sticky across parameters and BYREF is rejected in FUNCTIONs, both per guide §8.3 (the old per-param reset made the guide's own SWAP example pass Y by value). ARRAY OF T / ARRAY[l:u,...] OF T parameter syntax parses; codegen rejects it until the parameter-passing phase lands. - CodeGen stubs report clear not-implemented errors for the new nodes so nothing is silently ignored. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26refactor: groundwork for TYPE — sizeof constants, string guard, array scoping_ov4
- Element sizes now flow as target-folded null-GEP sizeof constants (TypeSystem::getSizeOfConstant); the module has no DataLayout string, so host-side size math would diverge from the backend on padded structs. - Extract the triplicated STRING null->"" select into CodeGen::emitStringNullGuard. - Scope ArrayTable per function via ArrayHandler::exchangeTable, mirroring the Symbols save/clear/restore discipline. - Promote checked element addressing to public ArrayHandler::emitElementAddress for the upcoming lvalue layer. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26feat: implement CIE 9.1 text file handling ↵_ov4
(OPENFILE/READFILE/WRITEFILE/CLOSEFILE/EOF) Front end: OPENFILE/READFILE/WRITEFILE/CLOSEFILE plus reserved mode keywords READ/WRITE/APPEND (RANDOM reserved with a dedicated not-implemented error); statement nodes in new FileAST.h, parsing in new ParserFile.cc; EOF joins the Builtins table as the 12th builtin and CallExprAST now carries a line number for its runtime diagnostics. Runtime: new FileHandler (StringHandler-shaped leaf) lazily synthesizes internal __cps_file_* helper functions and a 16-slot open-file table keyed by filename content (strcmp — STRING '=' is pointer identity). EOF is an fgetc/ungetc peek; READFILE grows a malloc/realloc line buffer and strips a trailing CR; fopen uses text modes so mingw-w64 line translation works. File-free programs get byte-identical IR. All misuse (not open, wrong mode, reopen, fopen failure, read past EOF, table full) dies with the existing "[Fatal] line N:" pattern via a new RuntimeCheck::emitErrorAndExit overload taking runtime printf args. Also fixes a pre-existing ArithmeticHandler hole surfaced by adversarial review: mixed-width integer operands (i1 BOOLEAN / i8 CHAR vs i64) now widen via ZExt instead of emitting invalid IR, and remaining type mismatches get a clean diagnostic; -EOF(f) and -IS_NUM(x) compile. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26fix: close correctness gaps found by post-refactor adversarial review_ov4
Confirmed by a 17-agent review pass over the refactor diff (12 findings verified against the code and reproduced end-to-end): - marshalCallArgs: BYREF arguments must match the declared parameter type exactly (was: silent bit-reinterpretation, e.g. REAL passed to BYREF INTEGER printed garbage with exit 0); whole-array arguments are rejected (was: callee assignment smashed the array data pointer -> runtime SIGSEGV) - Null guards for CHR/LCASE/UCASE/IS_NUM/NUM_TO_STR/STR_TO_NUM/ASC argument emission (was: compiler SIGSEGV on e.g. CHR(undeclared)), matching the guards MID/RIGHT/LEFT already had - ParseReturnStmt: propagate expression-parse failure (was: diagnostic printed but exit 0) and recognize bare RETURN before ENDWHILE/UNTIL/NEXT (was: bogus diagnostic on legal early return) - emitPrototype rejects FUNCTION/PROCEDURE names that collide with runtime/libc symbols (was: FUNCTION strlen silently hijacked the string runtime; arity mismatch crashed createArgumentAllocas) or with builtins (was: silently shadowed); conflicting redefinitions keep the first signature - FOR STEP is evaluated exactly once, before the loop (was: once per iteration; the runtime-direction refactor had moved it to N+1) - RETURN values are coerced to the declared return type via the signature table (RETURN n in a RETURNS REAL function now compiles) - '&' coerces its operands to STRING (CHAR/number operands work); OUTPUT of a PROCEDURE call reports a clean error AGENTS docs updated to match. All positive samples remain byte-identical to the pre-refactor baseline. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26refactor: drop per-type micro handlers and the parallel NamedValues map_ov4
Integer/Real/Boolean/CharHandler carried only five one-line LLVM API wrappers (now inlined at their call sites in CodeGen.cc) plus dead emitDeclare methods that violated the documented two-table lock-step invariant. StringHandler::emitDeclare (also dead) and its NamedValues reference go too. With the dead writers gone, NamedValues held no information not already in Symbols[].Storage, so the parallel map is removed: getNamedValue reads Symbols, ArrayHandler/FunctionGen take one table, and function bodies save/restore a single map. Behavior unchanged. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26refactor: centralize libc declarations, move '&' concat into StringHandler_ov4
CodeGen declares its own MallocFunc in SetupExternalFunctions and uses it for char->STRING coercion and INPUT STRING buffers, removing two bare getFunction("malloc") calls that null-deref'd if no handler happened to declare malloc first. The CHR branch reuses the char->STRING coercion path instead of a second hand-rolled heap wrapper. String concatenation moves from ArithmeticHandler (which re-declared four externs per '&' and was the LLVM 19 build-pin root cause) to StringHandler::emitConcat; ArithmeticHandler no longer touches the Module. Dead FreeFunc declarations removed. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26refactor: keep pseudocode signatures, single call-marshalling path_ov4
emitPrototype now records each FUNCTION/PROCEDURE's pseudocode signature (FuncSig: return type + per-param type/BYREF flag). CodeGen:: marshalCallArgs replaces the two verbatim-duplicated marshalling blocks and dispatches on the declared signature instead of inferring BYREF from pointer-typed LLVM params: BYVAL STRING params now receive the string data pointer (no more runtime garbage), and BYVAL args are coerced to the declared type (INTEGER->REAL args no longer emit invalid IR). Top-level prototypes are pre-registered in compile(), so calls may precede definitions; GenerateCall no longer fabricates i64 externs for unknown names - an unregistered callee is a compile error. OUTPUT reports an error when it cannot infer the expression type instead of printing with the INTEGER format. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26refactor: single builtin registry, retire keyword route for builtins_ov4
All 11 builtins now live in one static {Name, Arity, ReturnTypeName} table in CodeGen.cc: emitExpr checks arity against it (uniform "Error: X expects N args" diagnostics) and getExprTypeInfo reads return types from it, removing the duplicated hard-coded table. LENGTH/MID/RIGHT/LEFT/LCASE/UCASE lose their lexer tokens and ParseStringBuiltin; they parse as ordinary identifier calls exactly like ASC/CHR/IS_NUM/NUM_TO_STR/STR_TO_NUM already did. Behavior note: these six names are no longer reserved words. AGENTS docs updated for the new builtin story and the batch-1 error contract (exit codes, verifyModule, fixed descending FOR). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26refactor: batch 1 - correctness and error contract_ov4
- 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 <noreply@anthropic.com>
2026-03-27feat: generalize typed array support_ov4
2026-03-03Added all built-in functions_ov4
2026-02-02Added STRING_ov4
2026-02-02Added logical operators_ov4
2026-02-02Added REAL and BOOLEAN types, DIV and MOD operators_ov4
2026-01-30Added BYREF and BYVAL_ov4
2026-01-30Added FUNCTION and PROCEDURE_ov4
2026-01-30Changed INTEGER from i32 to i64ov-4
2026-01-30Added runtime check for array index and divisionov-4
2026-01-29Added arrayov-4
2026-01-29Added loop statements, FOR, WHILE and REPEATov-4
2026-01-29Added half way of IF statementov-4
2026-01-29Added binary operations +-*/ov-4
2026-01-29Added INPUT, OUTPUT and DECLAREov-4