Commit graph

96 commits

Author SHA1 Message Date
Graeme Geldenhuys e4f3b9e38b feat: Low() / High() for static arrays
Low(A) and High(A) on a static array variable now emit compile-time
constants (copy LowBound / copy HighBound) rather than a runtime slot
load. The semantic pass accepts tyStaticArray alongside tyOpenArray.
4 new tests; all 892 tests pass.
2026-04-28 12:35:05 +01:00
Graeme Geldenhuys c365b77f56 feat: static array array[L..H] of T — stack-allocated fixed-size arrays
Adds TStaticSubscriptAssign AST node, ParseTypeName extension for
array[L..H] of T syntax (tkDotDot token), TStaticArrayTypeDesc with
RawSize for correct element-footprint sizing (1 for Byte, 4 for Integer),
and full codegen: alloc4/alloc8 + memset zero-init, storeb/storew for
writes, loadub/loadw for reads, LowBound subtraction for non-zero ranges.

Also includes array literal ['a','b','c'] call-site support (step 4):
TArrayLiteralExpr, open-array formal matching, stack buffer allocation,
and codegen emitting two QBE args (data ptr + compile-time high index).

13 new static-array tests + 9 new array-literal tests; all 888 tests pass.
2026-04-27 17:22:29 +01:00
Graeme Geldenhuys 4feb1b3867 feat: const open array param (array of T) — two-register ABI
Adds support for open-array parameters of the form `const A: array of T`
using the standard Pascal two-register ABI: a data pointer (`%_par_A`)
and a high-index value (`%_par_A_high`, count − 1).

- uLexer: add tkArray keyword token
- uAST: add IsOpenArray / IsConstParam fields to TMethodParam
- uSymbolTable: add tyOpenArray kind, TOpenArrayTypeDesc, NewOpenArrayType
- uParser: extend ParseParamList to recognise `array of T` syntax
- uSemantic: add ResolveParamType helper; handle High/Low builtins (moved
  before the FProcIndex lookup so they fire without a symbol-table entry);
  open-array subscript in AnalyseStringSubscriptExpr; open-array
  compatibility in CheckTypesMatch
- uCodeGenQBE: emit two params + two alloc slots per open-array formal;
  High/Low intrinsic emission; pointer-arithmetic subscript; two-arg
  forwarding at call sites; exclude open arrays from ARC addref/release
- Tests: 16 new tests covering parser, semantic, and codegen paths
- docs/grammar.ebnf: add ParamType rule (ARRAY OF TypeName | TypeName)
- docs/language-rationale.adoc: document open-array ABI decision
2026-04-27 16:31:04 +01:00
Graeme Geldenhuys a644803516 docs: add platform interoperability section to language-rationale
Documents how Blaise's UTF-8 string type interacts with OS APIs:
POSIX/Xlib work directly via PChar; Windows W APIs require UTF-8 to
UTF-16LE conversion at the RTL boundary. Explains why this does not
motivate adding a UTF-16 string type to the language. Phase 6 item.
2026-04-27 14:29:27 +01:00
Graeme Geldenhuys 674d3edc8e docs: add language-rationale.adoc; confirm #N literals work
language-rationale.adoc records design decisions for the Blaise dialect:
single string type, no Char type, Byte subscript semantics, char literal
coercion, PChar (planned), ARC, out parameters, build-tool-drives-compiler,
and three open questions (integer width, enum storage, Result convention).

CLAUDE.md updated to require all future language design decisions to be
documented in language-rationale.adoc.

#N numeric char literals (e.g. #45 = Ord('-')) work without additional
implementation: UnescapeString converts them to single-byte strings,
CoerceToCharOrd handles the rest. Test added to lock in the behaviour.
2026-04-27 14:00:03 +01:00
Graeme Geldenhuys 5dbdc35c1e feat: string subscript S[N] — byte access
S[N] returns the Nth byte (1-based) of a string as Integer.
Single-quoted ASCII literals coerce to their Ord value when compared
with a subscript result; multi-byte literals (e.g. emoji) are a
compile-time error.

Character data lives at string_ptr + 12 (after the 12-byte ARC header),
so S[N] emits: extuw index; add index, 11; add str_ptr, offset; loadub.

4 new tests in cp.test.stringops cover codegen (loadub, copy 104),
non-string subscript error, and multi-byte char literal error.
2026-04-27 13:34:41 +01:00
Graeme Geldenhuys 1ea878000d feat: multi-file compilation (v0.2.0)
Implement whole-programme multi-file compilation. The compiler now
resolves `uses` clauses, locates unit source files via `--unit-path`
search directories, compiles them, and merges exported symbols into
the programme scope. Combined QBE IR is emitted in dependency order.

New components:
- uUnitLoader: post-order DFS unit loader with cycle detection
  (EUnitNotFound, ECircularDependency); skips FPC RTL builtins
- TSemanticAnalyser.AnalyseUnitForExport: promotes unit interface
  symbols to global scope; implementation symbols stay scoped
- TCodeGenQBE.AppendUnit / AppendProgram: accumulate combined IR;
  FStrLitsEmitted tracks emitted string literals to avoid duplicates
- 8 new tests in cp.test.multifile covering loader, semantic export,
  and combined codegen

Language additions:
- `out` parameter modifier (treated as var — pass by reference)
- implementation-section `uses` clause in units

Blaise.pas wired to use loader pipeline; --unit-path flag is
repeatable; -Fu<path> FPC-style flags are honoured.

Design doc updated: Phase 4 (multi-file), phases 5–8 renumbered;
--unit-path added to CLI table; build-tool-drives-compiler principle
documented in constraints.

End-to-end verified: two-unit programme compiles and executes correctly.
2026-04-27 11:35:26 +01:00
Graeme Geldenhuys 2b87f4cdbd release: open development branch towards v0.2.0 2026-04-27 09:26:17 +01:00
Graeme Geldenhuys 87734277b5 release: promote version to 0.1.0
Remove the -alpha suffix now that the compiler has reached self-hosting
fixpoint: stage-3 (hand source compiled by stage-2, itself compiled by
stage-1) produces byte-identical IR to stage-2.  This is the first
official release of the Blaise compiler.
2026-04-27 09:17:23 +01:00
Graeme Geldenhuys 7a88335393 hand source: emit short-circuit and/or to fix self-hosting fixpoint
EmitExpr for TBinaryExpr now checks for boAnd/boOr first and emits
short-circuit branches (jnz to sc_rhs/sc_end labels) before evaluating
either operand.  The eager `and` instruction previously emitted was
safe for bitwise use but caused a null-pointer crash when the compiler
compiled itself: TSymbolTable.FindType evaluated Sym.Kind even when Sym
was nil, because the code generator did not short-circuit the guard
`(Sym <> nil) and (Sym.Kind = skTypeAlias)`.

Stage-3 now produces byte-identical IR to stage-2 (fixpoint reached).
2026-04-27 09:06:37 +01:00
Graeme Geldenhuys 71b7fd5aae hand source: fix four self-hosting gaps toward stage-3 fixpoint
1. ImplicitSelfField ARC: emit _ClassAddRef/_ClassRelease (or
   _StringAddRef/_StringRelease) around storel when assigning to a
   class- or string-typed implicit-Self field.  Without this, the
   TCodeGenQBE.FLines StringList was freed at Generate() exit, so
   GetOutput returned garbage and stage-3 produced empty output.

2. UnescapeString: rewrite to handle both 'quoted' strings and #N
   decimal char-code literals (the old version only handled
   single-quoted forms, so #10 → empty string and GetText joined
   all lines without newlines).

3. Chr builtin: add to symbol table, semantic pass, and codegen
   (emits _Chr(w arg) → l result), required by the new UnescapeString.

4. AnalyseFieldAccess: set ResolvedMethod on parameterless constructor
   TFieldAccessExpr nodes so the codegen can emit the Create body call
   (companion to the EmitExpr IsConstructorCall fix from the previous
   commit).
2026-04-26 10:29:28 +01:00
Graeme Geldenhuys cf923852bd hand source: implement QBE sret convention for record-returning functions
Add the full structure-return (sret) convention to the hand source so
stage-2 generates correct IR for functions/methods that return tyRecord:

- EmitMethodDef/EmitFuncDef: declare record-returning functions as void
  with a hidden first param `l %_par__sret`; initialise %_var_Result
  from it; emit bare `ret` at exit.

- IsRecordCall / EmitRecordCallSret: detect record-returning call
  expressions (TFuncCallExpr, TMethodCallExpr, TFieldAccessExpr) and
  emit them with the sret address as the first argument.  Handles the
  IsImplicitSelf path with correct Self+offset pointer arithmetic.

- EmitRecordCopy / EmitRecordReleaseFields: field-by-field ARC-correct
  copy and release helpers for record types.

- EmitAssignment tyRecord branch: for record-typed lhs, either call
  EmitRecordCallSret (when the rhs is a call) or EmitRecordCopy.

- ImplicitSelfField tyRecord branch in EmitAssignment: same logic for
  assignments to record fields reached via implicit Self.

- TIdentExpr IsImplicitSelf tyRecord fix: return the field address
  rather than loading through it (callers need the address for copies).

- TIdentExpr local/global record variable fix: return VarRef address
  directly instead of an extra loadl.

All fixes mirror what the real multi-file source already had; this
brings the hand source to parity for record-return code generation.
2026-04-25 19:44:30 +01:00
Graeme Geldenhuys c547ab2f16 hand source: sync five codegen/semantic gaps for self-hosting fixpoint
- TSymbol gains ConstString field; AnalyseConstDecls stores CD.StrVal
- TIdentExpr gains ConstString and NoArgFuncDecl fields
- AnalyseIdent propagates ConstString to identifier exprs
- EmitExpr: string constants emit 'l copy $__sN' not 'w copy 0'
- IsNoArgFuncCall now set unconditionally for any skFunction with a
  return type; NoArgFuncDecl is looked up from FProcIndex so codegen
  can emit a proper call $FuncName() for user-defined zero-arg functions
- EmitExpr no-arg call path forwards NoArgFuncDecl as ResolvedDecl so
  EmitFuncCall finds the declaration instead of falling through to
  builtin dispatch and raising ECodeGenError
- TFieldAccessExpr IsMethodCall/PropRead/IsClassAccess paths use
  VarRef(RecordName, IsGlobal) instead of hardcoded %%_var_ prefix,
  fixing global-variable receivers such as Source.GetText
2026-04-25 13:06:04 +01:00
Graeme Geldenhuys 2ca052a271 fix: free intermediate string temps in chained string concatenation
When EmitExpr generates code for A + B + C (string concat), the
intermediate temp T1 = A + B (from _StringConcat) starts with
refcnt=0.  Before this fix that temp was silently abandoned:

  calling _StringRelease(T1) with refcnt=0 would decrement to -1
  (the IMMORTAL sentinel), so the string was never freed and the
  compiler slowly exhausted all available memory when processing
  large source files.

The correct pattern is to temporarily own the intermediate before
the second concat and release it after, so _StringConcat has a
chance to copy its bytes first:

  _StringAddRef(T1)           ; 0 -> 1 (temporary ownership)
  T2 = _StringConcat(T1, C)  ; copies T1's bytes into T2
  _StringRelease(T1)          ; 1 -> 0 -> freed

The same ownership pattern is applied to the right operand when
it is itself an unowned string expression (TBinaryExpr, TFuncCallExpr,
or TMethodCallExpr).

Also mirrors EmitMethodCall var-param forwarding fix (IsVarParam
check for both ObjExpr path and main path) and the previously-landed
EmitVarArgAddr, IsGlobal, vtable-in-ctor-with-args fixes to the hand
source (tests/blaise-compiler.pas).

With this fix stage-2 (blaise-compiler compiled by itself) compiles
the full hand source in 17s using 23MB RSS instead of hitting the OOM
killer at 47GB.
2026-04-25 10:58:04 +01:00
Graeme Geldenhuys f6ac68f537 codegen: store vtable in constructor calls with arguments
TMethodCallExpr.IsConstructorCall (TypeName.Create with args) was missing
the storel $vtable_X instruction after _ClassAlloc.  The TFieldAccessExpr
path (no-arg Create) already had it.  The missing store left vtable pointer
as zero, causing _IsInstance to crash with null vtable dereference during
type analysis of TTypeDesc subclasses.

Also adds virtual Destroy to TTypeDesc in the hand source so TTypeDesc and
its subclasses (TRecordTypeDesc, TEnumTypeDesc, TInterfaceTypeDesc) get
vtable slots, making HasVTable return true and field offsets correct.

Regression tests added for both the no-arg and with-arg constructor vtable
store paths.
2026-04-25 00:01:12 +01:00
Graeme Geldenhuys 50c746996b codegen: fix var-param forwarding to use loaded pointer
When a var-param actual argument is itself a var parameter, the local
alloc slot holds the caller's address rather than being the address.
Passing %_var_Name directly gave the callee a pointer-to-slot instead
of the original caller's address, causing reads/writes to land in the
wrong location.

Add EmitVarArgAddr() which detects this case and emits loadl %_var_Name
to obtain the stored pointer before passing it. Applied at all seven
call-emission sites in uCodeGenQBE.

Root cause of TStringList_FindSorted writing Mid into Find's local slot
(overwriting the Idx pointer) instead of into the caller's Idx variable,
so LookupLocal always read Idx=0 after a sorted search.

Two regression tests added to cp.test.varparams.
2026-04-24 23:26:40 +01:00
Graeme Geldenhuys 5907e1d314 hand source: TObjectList takes strong refs to stored objects
The hand-written self-hosting TObjectList stored bare Pointers and
took no ARC ref when adding.  In loops like

    while Check(tkIdent) do
    begin
      CD := TConstDecl.Create;
      ...
      ABlock.ConstDecls.Add(CD);
    end;

reassigning CD on the next iteration released the prior CD (its only
strong ref) and the list's pointer dangled.  When a later allocation
reused that heap slot, the list silently contained the wrong object,
and semantic analysis crashed in TSymbol.Create reading CD.Name from
an unrelated object's memory.

Add/Put/Delete/Clear/Destroy now AddRef on insert and Release on
remove or destroy, gated on FOwnsObjects so the semantics match the
real compiler's TObjectList.  Extract continues to transfer the ref
to the caller without release.

Lets stage-2 compile the hand source far enough to hit the next bug
(currently a nil Self in TRecordTypeDesc.AddVTableSlot during
AnalyseTypeDecls) — more hand-source polish to follow.
2026-04-24 17:59:21 +01:00
Graeme Geldenhuys 4797ce71a9 fix: drain child process output to avoid pipe deadlock
RunProcess used poWaitOnExit combined with poUsePipes, which
deadlocks when the child fills the stderr pipe buffer before we
read — the child blocks waiting for the reader, we block waiting for
exit.  Drain the pipe in a loop while the child runs, then wait on
exit separately.  Also fold stderr into stdout so qbe/cc diagnostics
round-trip through a single handle.

rtl/Makefile: install blaise_rtl.a into compiler/target (not
compiler/target/bin) so it lives next to the blaise binary produced
by pasbuild.
2026-04-24 17:42:54 +01:00
Graeme Geldenhuys 979943d274 codegen: short-circuit boolean and/or, fix class-expr field assign
Two codegen bugs surfaced while debugging self-hosting. Both were
previously invisible in unit tests because they only bite when the
compiled programme exercises the affected shapes.

EmitFieldAssignment emitted a spurious `loadl` for the receiver when
ObjExpr was set and IsClassAccess was True, dereferencing the class
pointer a second time. That read the object's vtable, and the ARC
write-barrier then released a method pointer and stored nil into the
vtable slot. Broke statements like `TFoo(X).Field := nil`.

boAnd and boOr were emitted as bitwise `and`/`or`, evaluating both
sides unconditionally. FPC and Delphi use short-circuit by default,
and guarded nil-checks like `(P <> nil) and P.IsX` rely on it. Now
emit a stack-slot-backed branch that skips the RHS when the result is
already determined.

The two boolean-op codegen tests updated to look for the new sc_rhs
and sc_end labels.
2026-04-24 17:42:34 +01:00
Graeme Geldenhuys 2cc192cd57 Stub program unit for the migration analyser. 2026-04-24 08:12:30 +01:00
Graeme Geldenhuys 916bf12af7 build: disable blaise-rtl from default reactor build
RTL Pascal sources (System.pas, Classes.pas, etc.) are compiled by
the Blaise compiler, not FPC. C sources are compiled separately via
GCC. Marking blaise-rtl as activeByDefault=false excludes it from
'pasbuild compile' and 'pasbuild test' reactor runs; it can still be
built explicitly with 'pasbuild compile -m blaise-rtl'.

Also adds a bootstrapExclude entry for System.pas so that if
blaise-rtl is compiled explicitly, the FPC bootstrap program does not
include System (FPC provides it implicitly).
2026-04-24 08:06:01 +01:00
Graeme Geldenhuys 9c4df99aca chore: clean-up .gitkeep files we don't need any more 2026-04-24 07:43:04 +01:00
Graeme Geldenhuys f66260093e Achieve self-hosting for hello-world compilation
The blaise compiler now compiles its own source (tests/blaise-compiler.pas)
into a second-stage binary that successfully compiles and runs a hello-world
program. All 834 compiler tests still pass.

Codegen and RTL fixes that unblocked self-hosting:

- String literal interning (uCodeGenQBE): set FStrLits.CaseSensitive := True.
  FPC's TStringList.IndexOf is case-insensitive by default, so distinct
  literals like 'WRITELN' and 'WriteLn' collapsed to the same label.

- ARC on implicit Self.Field assignments (uCodeGenQBE): EmitAssignment's
  implicit-Self branch did a raw storel for class/string fields. Fresh
  _ClassAlloc'ed objects start at refcnt 0, so without the addref they were
  freed by later local releases. Now addrefs new value and releases old.

- #nn character literals (uLexer): UnescapeString handled only 'text'.
  Extended to decode #nn decimal literals and concatenated forms like
  'abc'#13#10'def'. Local OrdAt helper lets the body parse under FPC and
  the self-hosted compiler.

- Chr() builtin: registered in uSymbolTable, handled in uSemantic, emitted
  in uCodeGenQBE as _Chr, implemented in rtl/blaise_str.c.

- LF line separator (Classes.pas): TStringList.GetText used #13#10; QBE
  rejects CR in its input. Changed to #10.

Self-hosting source (tests/blaise-compiler.pas) — needs a virtual Destroy
on TASTNode and Exception (post-TObject-stripping they became root classes
without a vtable, breaking `is` checks and exception message layout).
TAST* descendants chain `override`.

Migration tooling: add tools/migrate_full.py — the script that generates
tests/blaise-compiler.pas by flattening the eight compiler units and RTL
Classes unit into a single self-contained Pascal source. The postprocess()
step injects virtual Destroy on TASTNode / TTypeDesc and strips `override`
from non-vtable root classes.
2026-04-24 00:21:43 +01:00
Graeme Geldenhuys 49a1a0f478 Add implicit Self field access, OrdAt builtin, and migration infrastructure
Implicit Self: bare field names inside methods (e.g. FPos := FPos + 1)
now work without explicit Self. prefix. TIdentExpr.IsImplicitSelf /
ImplicitFieldInfo flags set by AnalyseExpr when lookup fails but a class
field matches; TAssignment.ImplicitSelfField set by AnalyseAssignment.
Codegen emits loadl %_var_Self + offset for reads, storew/storel through
Self + offset for writes. Required for migrating the compiler source which
was written in FPC style without explicit Self.

OrdAt(s, i): integer RTL function — returns ASCII ordinal of character at
1-based position i. Replaces FSource[FPos] (array indexing) in the
migrated uPasTokeniser.

Migration script (tests/blaise-compiler.pas): initial work-in-progress
self-hosting source. Script handles: const→class body stripping, inline
qualifier removal, inline-var removal, Exit(expr) expansion, shr/shl
conversion, constructor/destructor→procedure, access modifier stripping,
keyword array → TStringList/InitKeywords, FSource[expr] → OrdAt(FSource, expr),
char-range in [...] → integer comparisons, repeat...until → while True.

834 tests pass.
2026-04-23 15:24:13 +01:00
Graeme Geldenhuys 5c0083abee Add constructor-with-args, const blocks; begin self-hosting source
Constructor calls with arguments: TMethodCallExpr.IsConstructorCall flag;
AnalyseMethodCallExpr handles TypeName.Create(args) → allocate via
_ClassAlloc then call user-defined Create method; EmitCaseStmt generates
dispatch, EmitExpr handles the new constructor path.

const block: TConstDecl AST node; TBlock.ConstDecls list; ParseConstBlock;
AnalyseConstDecls registers each constant as skConstant in the symbol table.

tests/blaise-compiler.pas: initial self-hosting source stub — program header,
CHR_* character constants, Exception hierarchy, and Classes.pas RTL content.
The file is built incrementally; this commit has sections 1-2.

834 tests pass.
2026-04-23 15:04:01 +01:00
Graeme Geldenhuys 926b594516 Add const blocks, fix ParseBlock ordering, and stub blaise-compiler.pas
const: TConstDecl AST node; ParseConstBlock (integer and string literal values);
AnalyseConstDecls (registers each as skConstant in symbol table). Enables
CHR_* character constants and dupAccept/dupIgnore/dupError in self-hosting source.

ParseBlock: add tkConst to the multi-section loop.
Blaise now supports: case, enum, const, multi-type/var blocks, all file I/O
builtins — the complete language surface needed for the source migration.

834 tests pass.
2026-04-23 14:37:39 +01:00
Graeme Geldenhuys fb89879f86 Add OrdAt builtin for character-level string access in self-hosting migration
_OrdAt(s, i): returns ASCII ordinal of character at 1-based position i.
Required for migrating uPasTokeniser to Blaise: replaces FSource[FPos] and
char set-membership checks with integer comparisons.
2026-04-23 13:50:30 +01:00
Graeme Geldenhuys 1e8ebf04f1 Add case statements and enum types — required for self-hosting migration
case statement: TCaseStmt + TCaseBranch AST nodes; tkCase/tkOf tokens;
ParseCaseStmt (multi-value branches, optional else); AnalyseCaseStmt
(ordinal selector check); EmitCaseStmt (ceqw dispatch chain + jmp).

enum types: TEnumTypeDef AST node; TEnumTypeDesc symbol-table descriptor
(tyEnum, ByteSize=4, QBE 'w'); ParseEnumDef; AnalyseTypeDecls enum path
registers each member as skConstant with ordinal value 0..N-1; IsNumeric,
IsOrdinal, ByteSize, AllocAlign, QbeTypeOf all updated for tyEnum.
Variable alloc path handles tyEnum identically to tyInteger.

These two features unblock the self-hosting source migration: the compiler
source uses TTokenKind, TTypeKind, TBinaryOp, and TSymbolKind enums
throughout, all wrapped in case dispatch.

834 tests pass, zero Valgrind errors.
2026-04-23 13:47:17 +01:00
Graeme Geldenhuys 637369aa10 Close self-hosting gaps: multi-section blocks, file I/O, CLI args, process
Parser: allow any number of type/var/procedure/function sections in any
order within a single block. Required for single-file concatenation of
compiler units during self-hosting migration.

RTL (blaise_io.c): _SetArgs, _ParamCount, _ParamStr, _ReadFile, _WriteFile,
_AppendFile, _FileExists, _GetEnvVar, _Exec, _Halt. All exposed as Blaise
builtins via uSymbolTable/uSemantic/uCodeGenQBE.

$main now emits (w %argc, l %argv) and calls _SetArgs at startup so
ParamStr/ParamCount work at runtime.

TIdentExpr: IsNoArgFuncCall flag for builtin functions called without parens
(e.g. ParamCount without ()). Codegen synthesises a temporary TFuncCallExpr
so the existing builtin dispatch handles it transparently.

IR comment: removed stale "(Phase 2)" tag.

815 tests pass, zero Valgrind errors.
2026-04-23 13:00:34 +01:00
Graeme Geldenhuys 6688f32926 Add TObjectList and TStringList to RTL; fix string ARC via typed pointers
New builtins: CompareStr, CompareText (→ _StringCompare/_StringCompareText),
ZeroMem (→ memset), _ClassAddRef/_ClassRelease for manual ARC management.

EmitPointerWrite now emits retain/release when the base type is tyString,
enabling ARC-correct string storage in ^string arrays. ZeroMem is used to
zero-initialise newly grown string slots so the "release old" half of ARC
never sees uninitialised memory.

Classes.pas: TObjectList (^Pointer array, no ARC overhead) and TStringList
(^string + ^Pointer parallel arrays, sorted binary search via CompareText,
complete Delete/Insert/Clear with correct ARC). Generics.Collections and
phase3_milestone updated to zero-init new array slots, fixing previously
hidden memory safety issues revealed by the EmitPointerWrite ARC fix.

785 tests pass, zero Valgrind errors.
2026-04-23 12:32:59 +01:00
Graeme Geldenhuys 3b9339ae70 Add Format() built-in with variadic tagged dispatch
Format(fmt, arg0, arg1, ...) emits a variadic call to the C RTL
function _StringFormat using tagged (tag, value) pairs after the
variadic marker '...':
  tag=0 → integer arg (w QBE type)
  tag=1 → string arg  (l QBE type)

The C implementation (blaise_str.c) scans the format string for
%d and %s specifiers across two passes (length calculation then fill)
and builds a new Blaise ARC-managed string.

7 new IR-level tests in cp.test.stringops; 3 new e2e tests verify:
  Format('val=%d', 42)         → 'val=42'
  Format('hello %s', 'world')  → 'hello world'
  Format('%s=%d', 'Alice', 30) → 'Alice=30'
All 765 tests pass.
2026-04-23 11:56:00 +01:00
Graeme Geldenhuys 3258679445 Add built-in string operation functions (Length, Pos, Copy, etc.)
Implements 8 string RTL functions as compiler built-ins:

Compiler changes (uSymbolTable, uSemantic, uCodeGenQBE):
  - Length(s)              → $_StringLength  → Integer
  - Pos(sub, s)            → $_StringPos     → Integer (1-based)
  - Copy(s, from, count)   → $_StringCopy    → string
  - UpperCase(s)           → $_StringUpperCase → string
  - LowerCase(s)           → $_StringLowerCase → string
  - SameText(s1, s2)       → $_StringSameText → Boolean
  - IntToStr(n)            → $_IntToStr      → string
  - StrToInt(s)            → $_StrToInt      → Integer

RTL (blaise_str.c + Makefile):
  Implements all 8 functions against the BlaiseStrHdr layout defined
  in blaise_arc.c. All return new strings with RefCount=0 (ARC picks
  them up at the assignment site).

Tests: 31 new IR-level tests in cp.test.stringops.pas;
       7 new e2e tests in cp.test.e2e.pas verifying correct runtime
       output (e.g. Length("hello")=5, Pos=7, Copy=ell, etc.).
All 755 tests pass.
2026-04-23 11:50:06 +01:00
Graeme Geldenhuys 103e5231e8 Implement 'inherited' keyword for static parent-class dispatch
Adds full lexer→parser→semantic→codegen support for the 'inherited
MethodName(args)' statement form:

- uLexer: new tkInherited token
- uAST: new TInheritedCallStmt node (Name, Args, ResolvedParentType,
  ResolvedMethod)
- uParser: ParseInheritedStmt; dispatched from ParseStmt
- uSemantic: tracks FCurrentClass in AnalyseMethodDecl; new
  AnalyseInheritedCall resolves the parent chain and validates args
- uCodeGenQBE: EmitInheritedCall emits a direct static call to
  $ParentType_MethodName, bypassing vtable dispatch

6 new tests in cp.test.inherit.pas; all 724 tests pass.
2026-04-23 11:33:05 +01:00
Graeme Geldenhuys 29c32344f7 Mark Phase 3 complete; document Destroy hook and RTL rewrite
Updates the implementation status table to reflect:
- ARC for interface references: done (class/interface addref/release,
  [Weak] cycle-breaking, Free rewired to _ClassRelease).
- RTL rewrite under ARC rules: done (Destroy replaces Free on
  collections, EmitFieldCleanupFn Destroy dispatch, milestone updated).

Closes out all outstanding Phase 3 follow-up items.
2026-04-23 10:53:12 +01:00
Graeme Geldenhuys 0508b6cdc6 Rewrite RTL under ARC rules; add Destroy destructor hook
Compiler:
- TRecordTypeDesc gains HasDestroyMethod boolean property, set by the
  semantic analyser whenever a class (regular or generic instantiation)
  declares a 'Destroy' method.
- EmitFieldCleanupFn emits a call to $<TypeName>_Destroy before the
  ARC field-release loop when HasDestroyMethod is set, giving classes a
  hook to free raw resources (malloc buffers etc.) at refcount zero.

RTL (Generics.Collections):
- TList<T> and TDictionary<K,V> replace 'procedure Free' with
  'procedure Destroy'. Destroy frees the internal raw buffers (FData /
  FKeys / FValues) and nils them, making re-entrant calls safe.
  Free is no longer user-defined on these classes so List.Free uses
  the built-in ARC release path (_ClassRelease + slot nil-out).

tests/phase3_milestone.pas:
- TIntList and TStrIntDict migrated to Destroy (removed FreeMem(Self)
  which was unsafe under universal ARC on TObject).

Tests (718 total, 0 failures):
- cp.test.arc: 3 new IR tests for Destroy dispatch in field cleanup fn
  (non-generic, absent-on-class-without-Destroy, generic instantiation).
- cp.test.e2e: 4 new end-to-end / valgrind tests — ClassDestroy frees
  buffer, TList ARC lifecycle, Phase3Milestone stdout and valgrind-clean.
2026-04-23 10:51:56 +01:00
Graeme Geldenhuys 6569c1f82b Implement [Weak] attribute for cycle-breaking under ARC
A weak reference is a slot that does not contribute to the target's
refcount and is automatically nil'd when the target is freed.  This
breaks reference cycles that would otherwise leak under universal ARC.

Attribute model (Delphi-compatible)

    type
      TNode = class
        Other: TNode;            // strong, default
        [Weak] Back: TNode;      // weak, no refcount, zeroed on free
      end;

The parser accepts `[Ident]` and `[Ident(args)]` attribute lists before
var and class-field declarations.  Attribute names are captured
verbatim on TVarDecl.Attributes / TFieldDecl.Attributes; unknown
attributes are accepted silently so user-defined attributes (which
will materialise with RTTI) don't need to wait for the syntax.

Semantic analysis resolves `[Weak]` with the Delphi convention that
the `Attribute` suffix is optional — `[Weak]` and `[WeakAttribute]`
both resolve to the recognised marker.  Applying [Weak] to a non-
reference type (Integer, string, record) is an error at declaration
time.  Resolved weakness is surfaced on TVarDecl.IsWeak / TFieldInfo.IsWeak
and TSymbol.IsWeak for codegen consumption.

Lexer: tkLBracket / tkRBracket added.

RTL (blaise_weak.c): global chained hash table maps target pointers to
lists of registered weak slot addresses.  _WeakAssign registers a new
slot (and unregisters any prior), _WeakClear unregisters and zeros,
_WeakZeroSlots nils all slots registered against a target.  The last
is called from _ClassRelease at refcount zero, before field cleanup
and free, so weak readers never see dangling memory.

Codegen: weak class/interface vars bypass addref/release entirely.
Variable assignment, field assignment, scope-exit cleanup, exception-
path cleanup, and per-class _FieldCleanup functions all branch on the
weak flag to emit _WeakAssign / _WeakClear against the slot address
instead of strong refcount operations.

Tests

  * cp.test.weakref.pas — 14 unit tests covering lexer, parser,
    semantic validation (including the suffix-drop rule), and codegen
    emission at every insertion point.
  * cp.test.e2e.TestRun_WeakRef_BreaksCycle_Valgrind — compile and run
    a two-node mutual-reference program with [Weak].  Without the
    attribute, valgrind reports both nodes as definitely lost; with it,
    the run is leak-free.

All 711 compiler tests pass.

Deferred: TCustomAttribute / WeakAttribute Pascal-side class
declarations.  The compiler resolves `[Weak]` purely by attribute
name, so the RTL classes are not load-bearing today.  They will be
added as empty marker types when RTTI arrives and RTTI-queryable
attributes become meaningful.
2026-04-23 10:15:00 +01:00
Graeme Geldenhuys 3e4219dd48 Extend ARC to interface references; fix two latent IR bugs
Interface variables are fat pointers (obj + itab); only the obj slot is
refcounted.  Adds addref/release around every interface assignment path
(as-cast, class-to-interface, and the previously unhandled
interface-to-interface case), scope-exit release of the obj slot, and
exception-path release with obj-slot zeroing.  itab slots point at
static rodata and are left alone.

Two pre-existing latent bugs surfaced while wiring the new valgrind
e2e test and are fixed here rather than deferred:

  1. Indirect call IR emitted `call %%_tN(...)` (double percent) at
     three sites in EmitProcCall and EmitExpr.  QBE rejected it with
     'invalid character %'.  No passing test previously exercised the
     affected paths — the matching expression-form code at line 1938
     used the correct single-percent form.  Fixed to `call %s` which
     renders FPtrTemp (already prefixed with %) correctly.

  2. Classes declared as `class(TObject, IFoo)` emitted a reference to
     $typeinfo_TObject with no corresponding data item, causing the
     linker to fail.  Emit a stub `data $typeinfo_TObject = { l 0, l 0 }`
     unconditionally at the top of EmitTypeInfoDefs.

Added four IR-level tests covering the three interface-assignment
paths and scope-exit release, plus two valgrind-clean end-to-end
tests (one class-only, one interface) that assert leak-freedom without
any explicit Free call in the source.  All 696 tests pass.
2026-04-23 01:07:25 +01:00
Graeme Geldenhuys 6e18aba8f1 Insert ARC on class vars, class fields, params; rewire Free as release
Completes the variable/field/param ARC insertion pass for class types
and wires the destructor path for ARC-managed fields.

Compiler changes:
  * EmitAssignment: tyClass branch mirrors string ARC (addref new, release
    old, store)
  * EmitFieldAssignment: same pattern for string and class field stores
  * EmitStringCleanup renamed EmitArcCleanup; releases class locals
    alongside string locals at block exit
  * EmitExcPathArcCleanup: releases class locals on exception unwind
  * EmitFuncDef / EmitMethodDef: addref class value params on entry and
    release on exit (matches the existing string convention for standalone
    funcs; closes the gap for methods)
  * Obj.Free lowered to _ClassRelease + nil-out of the variable slot —
    Free is now a sanctioned synonym for immediate release, and the
    scope-exit release on the zeroed slot becomes a safe no-op
  * New EmitFieldCleanupDefs emits a $_FieldCleanup_<Class> function per
    class (and per generic instantiation) that releases each ARC-managed
    field; _ClassRelease invokes it before free() when the refcount
    reaches zero

Inherited fields are already merged into the derived class's Fields list
by the semantic analyser, so the derived cleanup is authoritative — no
parent chain, which would otherwise double-release.

RTL changes:
  * Object header grows from 8 to 16 bytes to carry the cleanup fn pointer
  * _ClassAlloc takes (size, cleanup_fn); refcount still starts at 0
  * _ClassRelease calls cleanup before free when rc reaches zero

Absorbs Task 4 (Free as release synonym).  phase2_milestone valgrind
test remains leak-clean with the new ARC rules in force; 5 new codegen
assertions cover the insertion points explicitly.
2026-04-23 00:52:55 +01:00
Graeme Geldenhuys c36709e627 Add _ClassAddRef and _ClassRelease RTL helpers
Nil-safe addref/release that operates on the hidden 8-byte header
introduced by _ClassAlloc.  _ClassRelease frees the block when the
refcount reaches zero.  Destructor dispatch is deferred: Blaise has no
user-defined Destroy mechanism yet, and when one lands the vptr slot
will be invoked before free().

Helpers are not yet called by codegen; Task 3 inserts addref at class
assignment and release at scope exit.
2026-04-23 00:25:23 +01:00
Graeme Geldenhuys e08284d8a7 Add 8-byte refcount header to every class allocation
Introduces _ClassAlloc and _ClassFree in blaise_arc.c.  _ClassAlloc
prefixes an 8-byte header (4B refcount + 4B padding) before the user
pointer; the user pointer still points at the vptr, so field offsets
and virtual dispatch are unchanged.  Refcount starts at 0 to match the
string ARC convention (the compiler's addref-on-assignment pass will
bring it to 1 once Task 3 lands).

Obj.Free is temporarily lowered to _ClassFree, which bypasses the
refcount but accounts for the hidden header.  Task 4 will rewire this
to _ClassRelease so Free becomes a sanctioned synonym for immediate
release under the full ARC rules.

First step of the universal-ARC-on-TObject work documented in the
class-ownership decision record (commit 0c09b42).
2026-04-23 00:23:08 +01:00
Graeme Geldenhuys 0c09b4228c Document class-ownership decision: universal ARC on TObject
Record the decision (option A) in docs/design.adoc with full pros/cons
analysis of the three options considered. Update the Phase 3 status
table so interface-ref ARC reads "Planned — option A chosen" rather
than "Deferred — design-blocked". Mirror the commitment in README.adoc
under Design Philosophy and list the TObject/TInterfacedObject split
as dropped.
2026-04-23 00:08:55 +01:00
Graeme Geldenhuys 2d4a005f56 Collapse Write+WriteLn pairs into multi-arg WriteLn in milestone tests 2026-04-22 23:19:55 +01:00
Graeme Geldenhuys cbb1af5ffc Replace force-exit workarounds with break now that Break is supported 2026-04-22 23:18:47 +01:00
Graeme Geldenhuys b38a486a0e Add boolean operators, Exit/Break, multi-arg WriteLn, chained field access, generic constraints
Five language features that surfaced as missing during prior sessions,
plus test coverage. All 685 tests pass (634 previously); the five new
end-to-end tests compile-link-run against the RTL to verify real
behaviour beyond IR shape.

- AND/OR/NOT with standard Pascal precedence; operands must be Boolean.
- Exit jumps to a per-function/main exit label so ARC cleanup still
  runs on early return. Break uses a loop-end label stack; rejected
  outside a loop.
- Write/WriteLn now accept any number of arguments, emitting one printf
  per value plus one trailing newline call for WriteLn.
- TFieldAccessExpr gained an optional Base expression; parser wraps
  each additional .IDENT, semantic recurses to type the chain, codegen
  uses a new EmitInstancePtr helper for nested record/class storage.
- <T: class>, <T: record>, <T: TypeName> constraints on generic types,
  interfaces, and standalone functions; validated at instantiation
  (class-kind, value-type, or subclass/interface-implementor check).

Side effect: EmitVarAllocs now memset(0)s record storage so QBE's SSA
checker accepts reads from zero-initialised record fields. Matches
Pascal's defined default-zero semantics.

New test units split by concern: cp.test.booleanops, cp.test.flowjumps,
cp.test.multiwrite, cp.test.chainedfields, cp.test.genericconstraints
(46 new IR-level tests in total). cp.test.e2e gains 5 smoke tests
covering the same features through qbe + cc + run.
2026-04-22 23:06:50 +01:00
Graeme Geldenhuys b897f3e08d Add copyright headers and compiler output
Add BSD-3-Clause copyright header to all source files (44 .pas files).
Update compiler to output copyright line in version/usage output.
2026-04-22 19:00:46 +01:00
Graeme Geldenhuys 6ef9cd8c7e Add end-to-end test harness; fix EmitDataSection skipping format strings
The existing fptest suite is IR-only: tests generate QBE text and grep for
expected strings. That harness missed two runtime bugs — the alloc16 32
exception frame (fixed in 00e44e8) and, now, an EmitDataSection early-exit
that omitted unconditional printf format strings when the program had no
string literals.

cp.test.e2e.pas is a new test unit that compiles Pascal through the full
pipeline (Lexer -> Parser -> Semantic -> CodeGenQBE -> qbe -> cc -> native
binary), executes the result, and asserts on stdout, exit code, or valgrind
output. It walks up from CWD to locate vendor/qbe and rtl so it runs both
from the project root and from compiler/target/ (where PasBuild invokes
TestRunner). Scratch artefacts live under compiler/target/test-e2e/ and
are preserved on failure for post-mortem debugging. Tests Ignore()
gracefully when qbe, the RTL, or valgrind is not available.

Initial cases: bare try/finally, try/finally with locals (stack-corruption
regression for the alloc16 bug), nested try/finally, virtual dispatch in
expression position inside try/finally, Phase 2 milestone stdout, and
Phase 2 milestone valgrind-clean.

On first run the virtual-dispatch case surfaced the latent EmitDataSection
bug: the procedure exited early when FStrLits.Count = 0, skipping the
$__fmt_d_nl / $__fmt_nl definitions that WriteLn(Integer) and bare WriteLn
always reference. Any program that printed an integer without also
containing a string literal failed to link. Fix: emit the format strings
unconditionally; the literals loop is the only block now gated on count.

634/634 tests green, ~0.9 s total.
2026-04-22 18:43:15 +01:00
Graeme Geldenhuys 00e44e8876 Fix try/finally and try/except exception frame size (alloc16 32 → 512)
The exception frame was allocated as alloc16 32 (32 × 16 = 512 bytes on paper,
but QBE's alloc16 N means N items of 16 bytes: so 32 × 16 = 512 is actually
correct). Wait - re-reading: alloc16 N in QBE allocates N bytes aligned to 16.
So alloc16 32 was only 32 bytes — far less than sizeof(BlaiseExcFrame) which
needs ~216 bytes on Linux x86_64 (200-byte jmp_buf + two pointer fields).

setjmp writes its full jmp_buf into the undersized slot, silently corrupting
whatever sat above it on the stack: saved registers, local variables, and the
virtual method pointer loaded for virtual dispatch. Any try block followed by
a virtual method call in expression position crashed with a bad function pointer.

Fix: alloc16 32 → alloc16 512 in both EmitTryFinallyStmt and EmitTryExceptStmt,
matching the RTL contract documented in blaise_exc.c lines 8-13.

Two new regression tests assert alloc16 512 appears in emitted IR for both
try forms. 628 tests pass (was 626).

Also adds tests/phase2_milestone.pas: linked list with virtual dispatch,
inheritance, try/finally, and 'is' type test — zero valgrind leaks.
Updates design.adoc Phase 3 status table to reflect current implementation.
2026-04-22 18:22:48 +01:00
Graeme Geldenhuys d49ebb4f51 Phase 3 milestone: TList<Integer> + TDictionary<string,Integer> zero leaks
Four bugs fixed on the path to the milestone:

1. Non-generic class fields resolved with FindType instead of
   FindTypeOrInstantiate — typed pointer fields (^Integer, ^string) in
   concrete classes failed with 'Unknown type'.

2. Integer/Boolean/Int64 local variables not zero-initialised — QBE
   validator rejected 'slot read but never stored to' for variables
   written only through var-param pointers.

3. Class method var-param signature wrong — EmitMethodDef emitted the
   param type (w for Integer) rather than 'l' (pointer) for var params;
   EmitParamAllocs spilled the pointer with storew instead of storel.

4. Method call sites did not pass addresses for var-param arguments —
   EmitMethodCallExpr always called EmitExpr (value load) rather than
   forwarding %_var_Name (address) for IsVarParam params.

Milestone result (valgrind --leak-check=full):
  7 allocs, 7 frees, 0 bytes in use at exit, ERROR SUMMARY: 0 errors
2026-04-22 16:58:36 +01:00
Graeme Geldenhuys 266a42b05d Add _StringEquals RTL helper and string equality codegen
blaise_arc.c: content-aware _StringEquals compares two Blaise string pointers
by length then memcmp; nil treated as empty string; returns int32 1/0.

Codegen: string '=' and '<>' now route through _StringEquals instead of
ceql (pointer equality) — the '<>' case negates by ceqw result, 0.

3 new tests in cp.test.codegen.pas confirm IR contains $_StringEquals.
626 total tests, 0 failures.
2026-04-22 16:40:17 +01:00
Graeme Geldenhuys c07b28138f Add True and False as built-in Boolean constants
Registers True (1) and False (0) as skConstant symbols in the symbol table.
TIdentExpr gains IsConstant/ConstValue fields set by the semantic pass; codegen
emits 'copy N' rather than loading from a non-existent stack slot.

Idiomatic Boolean returns (Result := True / Result := False) now work in
all Blaise source including the RTL TDictionary.TryGetValue method.
6 new tests in cp.test.codegen.pas — 623 total, 0 failures.
2026-04-22 16:37:31 +01:00