Length() previously only accepted strings — calling it on an open-array
parameter raised "Length argument must be a string".
Semantic: allow tyOpenArray and tyStaticArray in addition to tyString.
Codegen:
- tyOpenArray: load the _high slot and add 1 (same pattern as High()+1)
- tyStaticArray: emit HighBound - LowBound + 1 as a compile-time constant
- tyString: unchanged — delegates to _StringLength RTL call
Tests: 4 IR-level tests in cp.test.openarray.pas and 1 e2e run test.
When a method call appears in expression context (result assigned or
passed as an argument) and the receiver is an implicit-self field, the
analyser was calling FindMethodDecl — which returns the first registered
match — instead of ResolveMethodOverload. This caused the arity check
to fire against the wrong overload (e.g. a 4-param open-array overload
was selected for a 3-arg call, producing a spurious "expects 4 args but
got 3" error).
Fix: mirror the statement path — analyse args first, then call
ResolveMethodOverload to score and pick the correct candidate.
Regression test added in cp.test.overload.pas. As a result, the
CompileAndRunNoArgs workaround in cp.test.e2e.pas is reverted: the
no-args variant is now a proper overload of CompileAndRun.
On a clean checkout, compiler/target/blaise does not exist yet, so
plain `make` in rtl/ produces empty .ssa files and a silently broken
RTL archive. The fix is to pass BLAISE=../releases/v0.7.0/blaise to
make on the first RTL build. Document this in both README.adoc and
CLAUDE.md with the correct three-step cold-bootstrap sequence.
Replace FPC prerequisites with Blaise release binary. Update build
instructions to show bootstrap-from-release workflow. Update test
count to 1268 and note that the test suite compiles under Blaise.
When stage-1 is an older release with different codegen, stage-2 and
stage-3 IR will differ. The script now automatically extends to
stage-3 -> stage-4 and checks that fixpoint instead of failing.
Bump version to 0.7.0. Update fixpoint.sh to use the latest release
binary as stage-1 instead of FPC — FPC is no longer needed anywhere
in the toolchain.
Five fixes that together bring the Blaise-compiled test suite from
1053 to 1268 tests with zero failures:
- Blaise.pas: remove {$IFDEF FPC} guards; cast exception variable to
Exception(E) for Blaise compatibility
- uCodeGenQBE.pas: fix implicit-self method calls that pass var/out or
open-array parameters (two symmetric paths in EmitProcCall and
EmitExpr TFuncCallExpr)
- cp.test.e2e.pas: rename CompileAndRun no-args overload to
CompileAndRunNoArgs (overload-resolution workaround); lowercase unit
names for case-sensitive loader; fix 0-based Pos/Copy indexing in
TObjectList test assertion; revert debug DeleteFile guard
- blaise_io.c: fix buffer overflow in _GetTempFileName when dir is
empty and TMPDIR is set
- process.pas: rename from Process.pas for case-sensitive unit loader
Fixpoint verified: stage-2 IR == stage-3 IR (116462 lines).
Switch pasbuild test goal to use Blaise as compiler by adding the RTL
unit path to the build <unitPaths> in compiler/project.xml. This mirrors
the fixpoint pipeline exactly: Blaise compiles itself, then compiles the
test runner.
Core fixes to make the Blaise-compiled test suite green:
bcl.testing.pas: rename duplicate on E: variable names (EAF/EIT/ETO)
to prevent ARC triple-release of the caught exception object (KI-3).
bcl.testing.runner.text.pas: implement --suite / --suite Class.Method
CLI filtering (Step 15); also adds TestClassName() via typeinfo[2]
read for the class name lookup. Fixes 0-based Pos split for --suite
argument parsing.
uParser.pas, uSemantic.pas: guard explicit-receiver .Free + reassign
patterns with { FPC} so ARC does not double-release the field
slot (KI-2). Three call sites: GID.IntfDef, GD.ClassDef in the
parser, and GII.IntfDef in InstantiateGenericInterface.
cp.test.sets.pas: rename duplicate on ESE/EEx exception variables.
cp.test.exceptions.pas, cp.test.multiwrite.pas: fix PosEx loop
termination — Blaise returns -1 (not 0) for not-found; start index
is 0-based.
cp.test.arc.pas and seven other test files: fix absence checks that
used Pos(...) = 0 (FPC not-found sentinel); changed to < 0.
cp.test.stringops.pas: replace emoji literal '😀' with 'AB' to work
around parser limitation with bytes > 127 in string literals (KI-1);
test still exercises the same CoerceToCharOrd semantic-error path.
Result: pasbuild test -m blaise-compiler --compiler ./compiler/target/blaise
passes with 1053 tests, 0 failures, 0 errors.
Chained field access like Prog.Block.TypeDecls[0] was passing the
intermediate base pointer (TBlock) directly to TObjectList_Get instead
of first loading the TypeDecls field value. Fixes the EmitExpr chained
path to match the ImplicitSelf path which already handled this correctly.
- Move RTL unitPath from <build> to <test> section in project.xml —
FPC picks up Blaise's system.pas when RTL is on the build path
- Guard IR caching code (TSearchRec/FindFirst) with { FPC} —
Blaise doesn't support these SysUtils types
- Add LineEnding constant under { FPC} in bcl.testing for
Blaise-compiled test units
- Replace empty array literal [] with 3-arg CompileAndRun overload
- Migrate cp.test.tokenkindname from fpcunit to bcl.testing; replace
Format/Low/High with Blaise-compatible alternatives
- Increase QBE NString from 80 to 160 — method names like
TInterfaceTests_TestSemantic_ClassWithInterfaceAsFirstParent_
InheritsFromTObject exceed the old limit
Nested record field assignment (O.A.V := 10):
EmitFieldAssignment called EmitExpr on ObjExpr for record-typed bases,
which loaded the contents instead of returning the storage address.
Fixed to use EmitInstancePtr, which correctly returns the address of
inline record storage and the heap pointer for class-typed bases.
Int64 literals exceeding int32 range:
TIntLiteral always emitted =w copy N even for values like 3000000000
that overflow 32-bit signed range. The semantic pass also always
assigned TypeInteger to int literals regardless of value. Both now
check whether the value fits in [-2147483648..2147483647] and use
TypeInt64 / =l copy N when it does not.
Byte(X) type cast not truncating:
The type-cast emit path (ResolvedDecl=nil) used =w copy for all
word-typed targets. Byte casts now emit =w and %t, 255 to mask to
8 bits, matching the expected truncation semantics.
inherited call not setting Result:
EmitInheritedCall always emitted a plain call statement, discarding
the return value of function overrides. It now captures the return
value and stores it into %_var_Result when the parent method has a
non-void return type.
@Obj.MethodName compiler crash:
AnalyseAddrOfExpr only handled TIdentExpr; TFieldAccessExpr with a
method field caused AnalyseFieldAccess to return nil (procedure has
no return type), then crashed on nil.Name. Added a branch that
recognises both RecordName (simple) and Base (chained) forms, builds
a method-pointer TProceduralTypeDesc (IsMethodPtr=True), and sets it
on the expression. EmitAddrOfExpr now allocates a 16-byte block and
stores the static code pointer and loaded object pointer into it.
Also adds ~50 e2e tests covering these features and more:
control flow, records (nested, string fields), pointers, text blocks,
sets, procedural types, default params, open arrays, var/const params,
string ops, Int64, type casts, is/as, inheritance, and interfaces.
Add four end-to-end for..in tests (string/Byte, string/Integer, array,
class enumerator) that compile through QBE+gcc and assert stdout.
IR-substring tests cannot detect promoted-scalar or invalid-pointer
bugs because QBE only rejects invalid IR at assembly time.
The array test exposed two pre-existing global static array bugs:
- EmitStaticSubscriptAssign hardcoded %%_var_ prefix instead of
VarRef(name, IsGlobal), breaking writes to global array variables.
- EmitGlobalVarData had no tyStaticArray case, emitting { l 0 }
(8 bytes) instead of { z N } for the correct element storage size.
Both fixed; all 1382 tests pass and fixpoint verified.
The synthetic index variable and user loop variable in for..in array
and string iterations are scalar integers/bytes that EmitVarAllocs
promotes to QBE register mode (=w copy 0). The old codegen
unconditionally emitted storew/loadw, which require a memory pointer
and cause a QBE error when the variable is a promoted register.
Apply the same IsPromoted checks used by the regular for loop: emit
=w copy for promoted scalars, storew/loadw for memory-backed ones.
In FPC/Delphi, for..in over a string yields Char, requiring Ord() to get
the numeric value. In Blaise, S[N] and for B in S already yield Byte
directly, so Ord() is superfluous for strings. Added a note to the
No Char Type section explaining this, and clarifying that Ord() remains
relevant for enumerations.
Low(S) always returns 0; High(S) returns Length(S)-1, consistent with
0-based string indexing. The semantic pass previously rejected both with
"must be an array"; codegen for High(S) reads the ARC header length field
directly (data_ptr-8, loadsw) and subtracts 1.
for B in S (B: Byte or Integer) was already implemented; this commit
documents the decision in language-rationale.adoc and grammar.ebnf.
language-rationale.adoc:
- Fix stale "1-based" description in String Subscript section
- Add "Low and High on Strings" section (decision, rationale, alternatives)
- Add "for B in S — String Byte Iteration" section
grammar.ebnf:
- Extend Low/High signatures to show Array | String
- Add ForStmt element-type annotation block
future-improvements.adoc:
- Add migration analyser suggestion to recommend for..in as replacement
for pure character-walk index loops
7 new tests in cp.test.stringops.pas, all passing (1378 total, 0 failures).
Fixpoint verified.
Blaise strings are now 0-based: S[0] is the first character, Pos returns
a 0-based index (-1 = not found), Copy takes a 0-based From argument.
Compiler changes:
- Add uStrCompat.pas bootstrap shim with StrAt, StrHead, StrCopyFrom,
StrCopyTail, StrPos — thin wrappers that translate between FPC's
1-based and Blaise's 0-based conventions
- Convert all string operations in Blaise.pas, uLexer.pas, uCodeGenQBE.pas,
and uSemantic.pas to use the 0-based shims
- Add PosOrd/PosSubstr shims in uPasTokeniser.pas to keep its internal
1-based FPos convention while translating at the boundary
- Fix UpCase codegen to extract ordinal via OrdAt when argument is a string
- Fix vtable emission in AppendUnit to use StrAt/StrCopyTail instead of
1-based E.ImplName[1] and Copy
ARC fixes uncovered during self-hosting:
- Add string param AddRef/Release to EmitMethodDef (was only on EmitFuncDef)
- Add string and class ARC to var/out parameter assignment path
RTL changes:
- _StringPos, _StringPosEx: return 0-based index, -1 for not found
- _StringCopy, _StringDelete: accept 0-based From/Idx
- _OrdAt: accept 0-based index
- SplitIntoList in classes.pas: convert to 0-based loop
Tests: add coverage for method string param ARC, var-param string ARC,
constructor prefix matching (CreateFmt), pointer type aliases, metaclass
aliases. Update E2E tests for 0-based Copy/Pos semantics.
Docs: add 0-based string rationale to language-rationale.adoc and
migration analyser checklist to future-improvements.adoc.
Self-hosting fixpoint verified (114758 lines, stage-2 == stage-3).
A class declared without an explicit parent (TFoo = class) was copying
TObject's vtable slot but leaving RT.Parent nil. This caused the typeinfo
parent pointer to be zero, breaking is/as/InheritsFrom checks against
TObject and any ancestor. Set RT.Parent := TObject's descriptor in the
implicit-parent branch, making TFoo = class identical to TFoo = class(TObject).
Updated the existing typeinfo test to assert the correct parent pointer.
Calling a method on an uninitialised (nil) class variable silently
succeeded when the method body didn't dereference Self. Add _CheckNil()
to the RTL (blaise_exc.c) which prints a clear error and aborts if the
pointer is nil. Codegen now emits call $_CheckNil(l %self) immediately
after loading the object pointer for every explicit variable method call.
One new codegen test verifies _CheckNil appears in the IR.
When a class declaration lists only interface names in its parent list
(e.g. TFoo = class(IFoo)), the first name was incorrectly rejected with
'Unknown parent class'. Fix: if the first name in class(...) resolves to
an interface type rather than a class, move it to ImplementsNames and
clear ParentName, allowing the existing implicit-TObject logic to fire.
Two new semantic tests cover the fix.
Add TokenKindName() to uLexer, mapping every TTokenKind to a readable
string (e.g. ';', '.', 'begin', 'identifier'). Update TParser.Expect to
use it — errors now read "Expected ';' but got 'var'" instead of
"Expected token 78 but got 79". The actual source value is appended only
when it differs from the kind name (e.g. 'identifier' ('Foo')).
Add cp.test.tokenkindname with 105 tests: a max-ordinal guard on tkAt=82
that fails if a new kind is added without updating TokenKindName, two
completeness sweeps, and a spot-check per token kind.
Add detailed design considerations for TThread under Blaise's automatic
reference counting: the fire-and-forget safety problem and the recommended
self-referential threading solution. Include practical code examples,
async/await vs TThread comparison table, state-machine explanations for
async/await transformation, and effort estimates for implementation.
gprof showed that 99.95% of stage-2 time was in MemCopy (via _StringFormat),
called 186,116 times from EmitLine(Format(...)). The previous fix replaced the
byte-loop with libc memcpy (2.5x speedup). This change eliminates the
_StringFormat calls entirely.
Replace FOutput: TStringList with TIRBuffer — a plain growable byte buffer.
EmitLine now appends raw bytes with a direct memcpy, bypassing all string
allocation and reference counting. AppendBuffer bulk-copies sub-buffers in
one call, replacing the line-by-line TStringList.AddStrings pattern. GetOutput
returns FOutput.Text which does a single SetLength + memcpy.
Portability:
- FPC: uses Move() via {$IFDEF FPC} guards in BufCopy.
- Blaise: uses _ir_memcpy (external 'memcpy') since Move is not yet a Blaise
built-in; {$linklib c} ensures the symbol is available at link time.
Result:
stage-2 self-hosting compile time: 1m 20s -> 0.40s (200x speedup)
Combined with the MemCopy RTL fix: 3m 18s -> 0.40s (490x total)
FIXPOINT_OK confirmed. All 1275 tests pass.
gprof profiling of the stage-2 self-hosted binary revealed that 99.95%
of execution time was in MemCopy, called via _StringFormat from every
EmitLine(Format(...)) call in the codegen (186,116 calls per compile).
Both blaise_str.pas and blaise_arc.pas had hand-rolled byte-copy loops:
for I := 0 to N - 1 do D[I] := S[I];
Replace with external bindings to libc memcpy/memcmp, which use SIMD
instructions and are orders of magnitude faster for typical string sizes.
Result: stage-2 self-hosting compile time drops from ~3m 18s to ~1m 20s
— a 2.5× speedup with a 4-line change.
FIXPOINT_OK confirmed after this change.
Replace the alloc+load+store pattern with direct QBE temp reuse for
scalar local variables. QBE supports non-SSA IR natively: assigning
the same temp name multiple times is valid and QBE inserts phi nodes
internally.
Promoted types: Integer, UInt32, Boolean, Byte, Enum, Int64, Double,
Single, Set. Excluded (address-taken or ARC-complex): tyClass,
tyString, tyPointer, tyPChar, tyMetaClass — these require a loadl from
the slot in ~30 call sites that are not yet promotion-aware.
Pre-pass per function:
- BlockHasTry: suppresses promotion entirely when the block contains
try/finally or try/except — promoted temps live in registers and do
not survive setjmp/longjmp used by the exception frame.
- CollectAddressTaken: marks locals whose address is taken (@X or
passed as var-arg) as non-promotable.
Updated codegen sites:
- EmitVarAllocs: emits '%_var_X =QT copy 0' instead of alloc+store.
- EmitAssignment: writes use '%_var_X =QT copy val' instead of store*.
- EmitArcCleanup: reads use 'copy %_var_X' instead of loadl.
- EmitExpr (TIdentExpr): reads use 'copy %_var_X' instead of load*.
- EmitForStmt: loop variable init/test/step use copy instead of
load/store.
- EmitProcCall (Inc/Dec): in-place add/sub uses copy instead of
load/store for promoted locals.
- Return value: 'ret %_var_Result' uses copy instead of loadw/loadl.
Fixpoint: stage-2 IR = stage-3 IR (FIXPOINT_OK).
All 1275 tests pass.
Symbol table lookup is case-insensitive, but the AST node retained the
as-typed casing from source. The code generator used that casing to emit
QBE temp and global names, producing mismatched names (e.g. %_var_result
vs %_var_Result) that QBE rejected with "invalid type for second operand".
Fix: after a successful Lookup, copy Sym.Name back onto the AST node for
both TAssignment (AAssign.Name) and TIdentExpr (TIdentExpr(AExpr).Name).
Add two regression tests in cp.test.codegen:
- TestResult_LowercaseAssign_CompilesOK: 'result := x + y' compiles cleanly
- TestIdent_WrongCase_NormalisedInIR: 'n := 42' uses the declared $N global
Reported by the community: https://github.com/graemeg/blaise/discussions/15
An integer literal constant (untyped) should score 2 (exact) against
integer-family types (Integer, Int64, UInt32, Byte) and score 1 (widening)
against floating-point types (Double, Single).
Previously the literal scored 2 against *any* numeric type, so F(42) with
overloads F(Int64) and F(Double) was incorrectly flagged as ambiguous —
both scored 2. Now Int64 wins over Double as expected.
Update SrcAmbiguousOverload in cp.test.overload.pas to use Double vs Single
(two float overloads) which remain equally-scored from an integer literal,
preserving the ambiguity test intent.
Adds a unified postfix chaining loop at the end of ParseFactor that
handles .Field, .Method(...), [subscript], and ^ dereference after any
expression. Previously Ident.Method(...) and Expr[i] exited without
checking for further postfix access, so patterns like Obj.GetRec().X,
Tokens[0].Kind, and A.GetB().GetC().Val failed to parse.
The poUsePipes option was removed during self-hosting adaptation since
the Blaise RTL TProcess always uses pipes. FPC's TProcess requires
the option explicitly, causing an access violation on Output.Read when
compiling with --output.
Simplify RunProc() output capture: accumulate pipe bytes directly into a
string via SetString instead of routing through TStringStream. Replace
sLineBreak with #10 in error messages to reduce SysUtils dependencies
ahead of the Blaise test-suite migration.
Add GetProcessID, DirectoryExists, GetTempDir, ForceDirectories, and
Sleep as compiler builtins backed by C RTL functions. These are needed
by the e2e test infrastructure (cp.test.e2e.pas) before switching the
test suite from FPC to Blaise compilation (v0.6.0 Step 2a).
Add '''...''' multi-line string literal syntax to the lexer and
tokeniser. Opening ''' followed by a newline starts a text block;
closing ''' on its own line sets the indentation baseline for margin
stripping. Single quotes inside the block require no escaping.
Disambiguation: ''' followed by a newline opens a text block; followed
by any other character falls back to the classic '' escape parse.
11 new tests in cp.test.textblock.pas cover basic blocks, margin
stripping, embedded quotes, empty blocks, relative indentation
preservation, disambiguation from '''', trailing content, tabs,
and blank line preservation. All 1264 tests pass; fixpoint verified.
Add _InheritsFrom RTL helper in blaise_arc.pas that walks the typeinfo
parent chain to check class identity. Wire IsBuiltinInheritsFrom through
the semantic analyser (tyPointer, tyMetaClass, tyClass receivers) and
codegen (emits call $_InheritsFrom with correct typeinfo loading).
Update punit with AssertInheritsFrom, AssertInheritsFromClass, and class
identity checks in AssertException and RunTestHandler. Update testpunit2
so DoTest21 correctly fails on a class mismatch (EError expected, EFail
raised). Add 5 unit tests and 6 e2e tests; all 1253 tests pass, fixpoint
confirmed.
Removes const sections, Abs(), ClassName/ClassType (all confirmed
implemented). Updates Str() workaround note now that DoubleToStr/
SingleToStr exist. Updates InheritsFrom effort note now that ClassType
vmt slots are in place.
Fixpoint achieved on the full multi-file source (105865 lines of QBE IR).
Ships indexed-property getter codegen and string-field char byte-load, fixing
the self-hosting crash introduced by overloading support in v0.4.0.