Commit graph

859 commits

Author SHA1 Message Date
Graeme Geldenhuys ef19c01cb7 fix(codegen): QBE stores float to implicit-Self field with stored/stores
Assigning a float value to a class field via an implicit Self reference
(e.g. `V := d` in a method/constructor where V: Double) emitted a hardcoded
`storel` on a `d`/`s` SSA value, which QBE rejects ("invalid type for first
operand in storel"). The implicit-Self field-store path in EmitAssignment
fell through to a literal `storel` instead of StoreInstrFor(field type), and
lacked the d<->s width coercion the EmitFieldAssignment path already has.

Use StoreInstrFor(ISFld.TypeDesc) (-> stored/stores for tyDouble/tySingle) and
add the Single<->Double truncd/exts coercion before the store. Surfaced by the
new float-constructor e2e tests, which run on both backends.
2026-06-22 14:16:21 +01:00
Graeme Geldenhuys 74da3eadcc test(bif-coverage): extend drift guard to .bif interface types
bif-coverage verified that every AST node field round-trips through the .bif
encoder/decoder, but the .bif interface-container types (TRoutineSig,
TUnitInterface, TMethodParam, TConstEntry, TVarEntry) were hand-serialised in
WriteMeta/EncodeMethodSig/etc. with no drift guard. Every cached-rebuild bug
just fixed was a serialised field on one of those types dropped from one side
of the round-trip — invisible to the tool, surfacing only as a runtime
miscompile.

Generalise the class scanner to ScanClassFile(path, names, objs, allowList);
add ScanInterfaceTypes() over an allow-list of the container types in
uUnitInterface.pas. Split uUnitInterfaceIO.pas into encoder-side and
decoder-side text and assert each serialised interface-type field's identifier
appears in both — the same looseness as the AST mechanism. Status file gains
the interface-type entries (serialise/safe); mutator-repopulated owning
collections are { no-bif }-exempt (their element data round-trips through the
per-entry encoders).

Negative test confirmed: dropping ImplUsedUnits/HasInitialization/VTableSlot
from either side is now reported as a gap with exit 1. Clean tree exits 0.
2026-06-22 12:38:28 +01:00
Graeme Geldenhuys 2f6ee4588a test(fixpoint): add warm-cache rebuild guard
None of the existing fixpoint scripts exercise the incremental warm-cache
rebuild path: fixpoint.sh uses --emit-ir (no cache), fixpoint-native.sh diffs
.s (no cache), fixpoint-native-internal.sh compiles a tiny program. So a
regression in the cached-interface import/round-trip (dropped field, wrong
vtable slot, duplicate global, missing init) passes all of them and only
surfaces later as a corrupt binary — exactly the class of bug just fixed.

scripts/fixpoint-warmcache.sh builds the whole compiler twice into the same
--unit-cache (clean then warm), asserts the warm rebuild is non-empty and not
drastically smaller than the clean build, and compiles+runs hello-world with
both stage-2 binaries to prove the warm-cache-rebuilt compiler is correct, not
just present. Prints WARMCACHE_FIXPOINT_OK on success.
2026-06-22 12:24:41 +01:00
Graeme Geldenhuys 915077d7c8 fix(incremental): make cached-interface rebuild lossless and coherent
Incremental compilation (per-unit .o + embedded .bif, the default) produced
silently corrupt binaries when rebuilding into a populated --unit-cache: the
clean build worked, but any rebuild that loaded a unit from its cached .bif
instead of source dropped or mishandled state the in-memory path carried.
Root cause is uniform across every symptom: the .bif round-trip was not a
complete projection of the unit interface, and the cached-load path in the
loader/driver diverged from the source-load path.

.bif format bumped to version 3 (IFACE_VERSION; CompilerId +bif tag) so stale
caches are cleanly rejected and recompiled from source.

Fixes (each was a field/decision present on the source path, absent on the
cached path):

- Loader: a unit's implementation-section `uses` were never recorded in the
  .bif, so on rebuild the impl-only dependency's object was dropped from the
  link (undefined symbol). Record ImplUsedUnits in the .bif and collect those
  objects for LINK ONLY (CollectLinkOnlyObject) — not semantic import, which
  would break the leaf-first iface import on interface/impl-use cycles.

- Native codegen: a global var owned by a cached unit was re-defined by the
  recompiled top program (`multiple definition of GTarget`). The program now
  references imported-unit globals as external (FImportedUnits / IsImportedGlobal
  gate in EmitDataSection); NoteDepInitUnit records every imported unit.

- Unit initialization: <Unit>_init calls for cached deps were never emitted, so
  initialization sections silently never ran. Record HasInitialization in the
  .bif and note prebuilt-iface inits in dependency order at program codegen.

- SynthesiseMethodDecl dropped VTableSlot/IsVirtual/IsOverride from cached
  method imports, degrading virtual dispatch to direct calls into the abstract
  base (SIGABRT at run time). Propagate them.

- Generic-instance field/param types now resolve via the analyser's generic-
  aware resolver on import (ResolveImportedTypeName); generic instantiation
  during import no longer nil-derefs FProg/FCurrentUnit (pending-instance flush).

- .bif round-trip completeness: serialise block-local var decls, Exit(value)
  return values, parameter default values, free-routine ResolvedQbeName,
  generic-class template properties, and fix implements-interface name
  stripping (strip to the last dot, not the first).

Adds TestIncrementalRebuild_ImplOnlyUses_LinksDependency (e2e) and updates the
magic/version assertion. Full suite OK (3722 tests); QBE, native, and
internal-assembler fixpoints pass; clean and warm-cache rebuilds both produce
correct binaries.
2026-06-22 12:23:28 +01:00
Graeme Geldenhuys baf5079d6d fix(parser,codegen): Self.Field[Index].SubField := ... parse and codegen
The parser's Ident.Ident[Index] path unconditionally expected ']:=' after
the subscript, rejecting chains like Self.FStack[0].Count := value. Add a
chain loop after ']' that handles '.Field :=', '.Method()', and further
'[Index]' suffixes.

Additionally, the QBE backend's EmitInstancePtr did not handle
TFieldAccessExpr nodes with IsArrayAccess set — it returned the field slot
address instead of the dereferenced array element pointer. Delegate to
EmitExpr when IsArrayAccess is true so the dynarray pointer is loaded and
the element offset is computed correctly.
2026-06-22 01:38:27 +01:00
Graeme Geldenhuys 57c1699d32 fix(test): prefer fp_blaise2 over fp_blaise3 for internal-asm e2e tests
fp_blaise3 predates the movq %xmm0,%rax encoding fix, so
TestFormatFloatArg always failed when fp_blaise3 was present.
2026-06-22 00:15:07 +01:00
Graeme Geldenhuys 05892561fe perf(linker): fix O(n²) string concatenation in internal linker (80s → 3s)
LkZeros built zero-padding strings by appending one byte at a time
(Result := Result + Chr(0)), which for a ~2.7 MB executable produced
trillions of byte copies. Replace with SetLength + PChar fill.

Also fix LkLE to pre-allocate via SetLength instead of concatenating
per-byte, and add an early-exit guard to LkCopyInto.
2026-06-21 23:53:36 +01:00
Andrew Haines 9d876b46aa feat(types): resolve qualified type names UnitName.TypeName
A type written as 'UnitName.TypeName' (the unit qualifier may itself be
dotted, e.g. System.SysUtils.TFormatSettings) was a parse error: after
reading the leading identifier ParseTypeName only accepted a generic
'<...>' argument list, not a '.' continuation.

Parse the full dotted path into the type name, then resolve it by its
final component — a type is always a single identifier; the leading
components name a unit already loaded by the 'uses' clause. The strip is
centralised in TSymbolTable.FindType (via UnitQualifierTail) so every
type position benefits uniformly — var/field decls, parameters, and the
several routine return-type sites — and FindTypeOrInstantiate strips the
qualifier off a generic instance (Unit.TList<Integer>) before
instantiation. Plain dotted identifier paths only: the bracket/space/
caret/angle encodings for array, pointer, set and generic types are left
untouched.

Tested: dotted-name capture in the parser, semantic resolution of a
qualified builtin (System.Integer), and end-to-end compile+run of a
program using a cross-unit qualified type.

(cherry picked from commit 7e9c3d1f61d42769bc3341195220a25190637e15)
2026-06-21 13:35:37 +01:00
Graeme Geldenhuys cf994dcca4 fix(parser): parse nested-proc-first bodies in unit impl routines (Andrew 82e770ac)
A unit implementation-section routine whose body opens with a nested
procedure/function declaration (before any var/const/type section) was
mis-parsed: ParseUnit called ParseMethodDecl without ACanHaveNestedProcs, so a
leading 'procedure'/'function' was treated as the next top-level decl and
parsing failed at the outer 'begin' ("Expected 'end' but got 'begin'").

Pass ACanHaveNestedProcs=True for the two impl-section ParseMethodDecl calls.
The IsForward guard already present in ParseMethodDecl (our commit 33db0f6)
keeps a forward decl from claiming the following sibling as its nested body, so
only the call-site change was needed — Andrew's branch independently added the
same forward-flag mechanism, which we already have.

Note: this is a PARSER fix (the unit body now parses correctly).  Resolving a
CALL to such a nested procedure is a separate, pre-existing semantic-pass gap
that affects program routines too (Inner() reports "Cannot find declaration");
it is out of scope here.  Andrew's tests are likewise parse-level.

Tests: cp.test.units.pas parse-level tests (outer routine is one decl with a
body holding the nested proc).

Cherry-pick policy: the forward-flag half was a duplicate of our work and
skipped; the ACanHaveNestedProcs threading + tests are taken.

Verified: FIXPOINT_OK, NATIVE_FIXPOINT_OK, NATIVE_INTERNAL_OK; full suite green
on both the QBE-built and native-built runners (3717 tests).
2026-06-21 13:35:37 +01:00
Graeme Geldenhuys 54cfe37e62 fix(pasbuild): fix the Release and Debug profiles to use Blaise compiler settings 2026-06-21 13:31:58 +01:00
Graeme Geldenhuys 3cf5333b16 fix(stdlib): make TStringList.Strings the default array property 2026-06-21 13:31:16 +01:00
Graeme Geldenhuys d91d9ee65a feat(lexer): conditional compilation with predefined BLAISE (issue #131)
Implements real symbol-presence conditional compilation in the lexer.
Previously {$IFDEF} was hardcoded false (always took {$ELSE}) and
{$DEFINE}/{$UNDEF} were silently consumed, with no define table and no
command-line flag.

- A case-insensitive define table on TLexer.  {$DEFINE sym} / {$UNDEF sym}
  add and remove symbols; {$IFDEF sym} keeps its body when defined (and
  {$IFNDEF sym} when not), with an optional {$ELSE} and a closing {$ENDIF}.
  IFDEF/IFNDEF blocks nest (the existing depth-tracking skip helpers are
  reused, now driven by the real truth value).
- Predefined symbols, seeded in every lexer: BLAISE (the headline
  cross-compiler use case — {$IFDEF BLAISE} ... {$ELSE} ... {$ENDIF}) plus
  the target CPU/OS symbols CPUX86_64, CPUAMD64, LINUX, UNIX.  No version
  macro yet.
- A -d / --define <sym> command-line flag (FPC -dSYM / Delphi -D), carried
  on TFrontEndOpts and threaded to the program's lexer AND to every unit the
  TUnitLoader compiles, so {$IFDEF} resolves consistently across the program
  and its units.

Tests:
- cp.test.lexer.pas: predefined BLAISE keeps the body, undefined takes ELSE,
  IFNDEF, DEFINE-then-IFDEF, UNDEF-then-IFDEF, and AddDefine (the -d path).
- cp.test.e2e.misc.pas (dual-backend): the {$IFDEF BLAISE} cross-compiler
  pattern, and a combined DEFINE/UNDEF/IFNDEF/CPU-OS/nested program.

Docs: grammar.ebnf documents the directives and predefines; language-
rationale.adoc records the decision (symbol-presence only, no {$IF} expr
form yet; BLAISE + CPU/OS predefined, no version macro) and alternatives.

Verified: FIXPOINT_OK, NATIVE_FIXPOINT_OK, NATIVE_INTERNAL_OK; full suite
green on both the QBE-built and native-built runners (3715 tests).
2026-06-20 20:16:16 +01:00
Graeme Geldenhuys 2a6d0c5912 fix(assembler): encode movq/movd between an XMM and a GP register (SSE MOVQ)
The internal assembler routed every `movq`/`movd` to the integer mov encoder,
which reads both operands as general-purpose registers.  So `movq %xmm0, %rax`
was emitted as `mov %rax,%rax` (48 89 C0) — register 0 in both fields — silently
discarding the XMM value.

The native backend emits `movq %xmm0, %rax` to box a Double's raw bits into an
array-of-const (the Format() argument path) and to spill float bit patterns, so
ANY float passed to Format() under the internal assembler (now the default
toolchain) arrived as garbage and printed 0.0000.  A regression vs v0.11.0,
which used the external assembler.  The e2e test harness assembles native via
cc, so only the internal-assembler suite exercises this path.

Fix: `movq`/`movd` with an XMM operand is an SSE move and is routed to a new
EncodeMovqXmm:
  gp/mem -> xmm :  66 [REX.W] 0F 6E /r
  xmm -> gp/mem :  66 [REX.W] 0F 7E /r
with the XMM operand as the ModRM.reg field and REX.W set for movq (64-bit),
clear for movd (32-bit).

Tests:
- cp.test.assembler.pas TAsmEncodingTests: byte-level encoding of
  `movq %xmm0,%rax` (66 48 0F 7E C0, and asserts it is NOT 48 89 C0) and
  `movq %rax,%xmm0` (66 48 0F 6E C0).
- TInternalAsmE2ETests.TestFormatFloatArg: Format('%.4f',[1.25]) through the
  internal assembler prints 1.2500.

Verified: FIXPOINT_OK, NATIVE_FIXPOINT_OK, NATIVE_INTERNAL_OK; full suite green
on both the QBE-built and native-built runners (3707 tests).
2026-06-20 19:09:56 +01:00
Graeme Geldenhuys c5d49ba03e fix: 64-bit integer constants — no truncation, accept full bit pattern (issue #133)
Two related defects in integer constant handling:

- A large hex literal that needs more than 32 bits (e.g. $080808080808 =
  8830587504648) was silently TRUNCATED to 32 bits (printed 134744072).  An
  untyped integer constant was unconditionally typed as Integer regardless of
  its magnitude, so codegen treated it as a 32-bit word.

- A literal above High(Int64) (e.g. $8080808080808080) was REJECTED at parse
  time with "Integer literal exceeds Int64 range", even though it is a valid
  64-bit bit pattern and is accepted by FPC/Delphi.

Fixes:

- uParser: the bare-integer-literal const path now uses ParseIntOrUInt64Literal
  (which already existed for the tolerant case) instead of ParseIntLiteral, so a
  value in the UInt64 range is captured as a bit pattern and flagged via a new
  TConstDecl.IsUInt64.

- uSemantic (AnalyseConstDecls): an untyped integer constant now picks its type
  by magnitude — Integer when it fits in signed 32-bit, Int64 when larger, and
  UInt64 when the value exceeds High(Int64) (matching Delphi, which prints
  $8080808080808080 as 9259542123273814144).  A typed const (e.g. A: Int64 =
  $8080808080808080) keeps its declared type and stores the bit pattern, so it
  prints -9187201950435737472.

Tests (cp.test.e2e.misc.pas, dual-backend): large hex not truncated, typed
Int64 bit pattern, typed UInt64 bit pattern, and untyped-above-Int64 widening
to UInt64.

Verified: FIXPOINT_OK, NATIVE_FIXPOINT_OK, NATIVE_INTERNAL_OK; full suite green
on both the QBE-built and native-built runners (3704 tests).
2026-06-20 18:30:12 +01:00
Graeme Geldenhuys fe5460f79b fix: var open-array parameter element read and write (issue #130 bug5)
A `var` open-array parameter was broken three ways; a `const` open array with
the same body worked, so the defects were specific to the var/open-array path.

- Semantic (uSemantic, AnalyseStaticSubscriptAssign): writing an element of an
  open-array parameter raised "'a' is not a static array or dynamic array" —
  there was no tyOpenArray case.  Added one: a var open array allows element
  writes; a const open array is rejected with a clear "declare it 'var'"
  message.

- QBE codegen (element READ): an open-array ident value-read fell into the
  scalar var-param branch, which dereferences the slot twice.  An open-array
  param slot already holds the data pointer directly (for both const and var),
  so the second load read garbage and segfaulted.  Added a tyOpenArray case
  that loads the data pointer once.

- Native codegen (element WRITE): tyOpenArray fell through to the static-array
  store and raised "static subscript assign on non-static-array".  Open arrays
  now share the dynamic-array element-write path, with the var-param extra
  deref suppressed (the open-array slot is already the data pointer).

Tests:
- cp.test.e2e.openarray.pas (dual-backend): element read (the issue repro),
  element write mutating caller storage, and read-modify-write mixing var and
  const open arrays.
- cp.test.semantic.pas: var open-array element write is accepted; const
  open-array element write is rejected.

Verified: FIXPOINT_OK, NATIVE_FIXPOINT_OK, NATIVE_INTERNAL_OK; full suite green
on both the QBE-built and native-built runners (3700 tests).
2026-06-20 17:29:47 +01:00
Graeme Geldenhuys 56e73c8ce4 fix: class recognised as implementing an interface inherited from an ancestor (issue #130 bug3)
A class that inherits an interface from its ancestor (the ancestor declares
the interface; the descendant does not re-list it) was not recognised as
implementing it.  `g := TLoud.Create` where TLoud < TPerson(IGreeter) failed
with "Type mismatch", and after the semantic gate was opened the codegen
referenced a non-existent itab.

Three coordinated fixes:

- uSemantic (CheckTypesMatch): the class->interface compatibility check
  scanned only the class's own ImplementsList.  It now walks the whole class
  parent chain, so a descendant inherits its ancestors' interface
  implementations.

- blaise.codegen.qbe / blaise.codegen.native (EmitInterfaceDefs): itab/impllist
  generation likewise only considered a class's own ImplementsList, so no itab
  was emitted for an inherited interface.  Both backends now:
    * skip a class only when neither it nor any ancestor implements an
      interface (and, on native, point the typeinfo at the impllist on the same
      condition);
    * collect implemented interfaces by walking the class parent chain;
    * resolve each itab method ref via the vtable slot's ImplName, so an
      overridden method points at the descendant's body and an inherited
      (non-overridden) method at the ancestor's — uniformly correct across
      arbitrary inheritance depth.

Tests (cp.test.e2e.interfaces.pas, dual-backend via AssertRunsOnAll): the
exact issue repro (descendant assigned to an interface var, dispatching to its
override), and a three-level chain through an interface parameter mixing an
overridden method with an inherited non-overridden one.

Verified: FIXPOINT_OK, NATIVE_FIXPOINT_OK, NATIVE_INTERNAL_OK; full suite green
on both the QBE-built and native-built runners (3695 tests).
2026-06-20 16:56:33 +01:00
Graeme Geldenhuys 33db0f699e fix(parser): forward; routine in a program declaration section (issue #130 bug2)
A `forward;`-declared routine in a program's declaration section swallowed the
following separate implementation (and everything up to the program's `end.`)
as its own body, producing "Expected ';' but got '.'".

Root cause: in ParseMethodDecl, when ACanHaveNestedProcs is true (the
standalone-proc context used for program/unit blocks), a bare
`procedure`/`function` keyword after the signature triggers body parsing so a
nested sub-routine is absorbed into the enclosing routine.  A forward decl has
no body, so the keyword that follows it is the SEPARATE implementation — but
the body-trigger fired anyway and consumed it.

Fix: track a local IsForward flag (set when the `forward` directive is seen)
and suppress the body-parse trigger for it, exactly as IsExternal already does.
Mutually-recursive routines declared with forward now parse and run.

Tests: a parser test asserts the forward decl and its implementation are two
separate ProcDecls (forward has no body, impl has one); a dual-backend e2e
test runs mutually-recursive IsEven/IsOdd and checks the computed parity.

Verified: FIXPOINT_OK, NATIVE_FIXPOINT_OK, NATIVE_INTERNAL_OK; full suite green
on both the QBE-built and native-built runners (3693 tests).
2026-06-20 16:20:01 +01:00
Graeme Geldenhuys 8c68b09245 fix(parser): accept named integer subrange types (issue #130 bug1)
`type TByte = 0..255;` failed to parse — ParseTypeDecl had no case for an
integer-literal subrange, so the RHS fell through to the generic "expected
record/class/..." error.

Blaise does not range-check, so a named subrange is treated as an alias to
the narrowest STANDARD integer type that holds both bounds (0..255 -> Byte,
-10..10 -> SmallInt, etc.).  This keeps record/array element layout correct
(TByte is byte-sized) while the value behaves as an ordinary integer.  Two
parser helpers do the work: SubrangeAhead (lookahead: IntLit.. or -IntLit..)
and ParseIntegerSubrangeBaseType (parse lo..hi, pick the base type, reject a
descending range).  Note Blaise has no 8-bit signed alias, so a signed
subrange that would fit in ShortInt widens to SmallInt.

Only integer-literal bounds form a named type; identifier/enum-bounded
subranges (TLow..THigh, red..blue) are intentionally not handled here (they
are ambiguous as a named-type form).

Tests: parser tests (named subrange, negative bounds, descending-is-error)
and dual-backend e2e tests (named subrange runs; subrange as a record field
and array element with a negative range).  grammar.ebnf gains the
IntSubrange rule.

Verified: FIXPOINT_OK, NATIVE_FIXPOINT_OK, NATIVE_INTERNAL_OK; full suite
green on both the QBE-built and native-built runners (3691 tests).
2026-06-20 15:56:18 +01:00
Graeme Geldenhuys 3e94044550 ci(bootstrap): add branch-scoped validate-only pre-flight runs
The rolling-bootstrap workflow only triggered on master, so a risky change
could not be proven against the bootstrap chain before merging — and a bad
commit on master cannot be removed without a force-push on a public repo.

Trigger the workflow on push to ci/**, feature/** and bootstrap/** branches
(plus master and the existing workflow_dispatch).  Branch runs are
VALIDATE-ONLY:

- The carry-forward cache (stage + save steps) is written ONLY on
  refs/heads/master, so a branch never overwrites master's resume anchor and
  a broken branch's -pre binary can never leak into a later master run.
- Branch runs still restore the cache read-only, so a branch off recent
  master resumes from master's latest good -pre and replays only its own new
  commits; a diverged branch falls back to the cold-start anchor as before.
- The -pre artifact upload still runs on branches (keyed by commit SHA, so it
  never collides with master's and is pull-only).

concurrency is already keyed on github.ref, so per-branch runs don't cancel
each other or master.

Note: this only takes effect once pushed, so like the other Phase 4 CI
changes it cannot be exercised until the v0.12.0 cut.
2026-06-20 15:20:32 +01:00
Graeme Geldenhuys 909684c57f chore: remove stale info from code comment. 2026-06-20 15:09:09 +01:00
Graeme Geldenhuys 008cc12785 feat(stdlib): configurable rounding for TMoney
TMoney previously hard-wired banker's rounding (rmHalfEven) at its single
normalisation point.  The underlying TDecimal already supports all eight
TRoundingMode values plus custom IRoundingStrategy, so expose that through
TMoney: every constructor and rounding-sensitive operation gains overloads
taking an explicit TRoundingMode or an IRoundingStrategy.

  MoneyFromStr('1.005','USD')            -> 1.00  (banker's, unchanged default)
  MoneyFromStr('1.005','USD', rmHalfUp)  -> 1.01
  C := A.Add(B, rmCeiling);
  M := MoneyFromStr('9.999','USD', myCashRoundingStrategy);

Overloaded: MoneyFromStr, MoneyFromDecimal, Add, Subtract, Multiply (each
gains a TRoundingMode form and an IRoundingStrategy form).  MoneyFromInt,
MoneyZero, MultiplyInt and Negate are exact (no fraction introduced) and
need no mode.  The existing no-mode calls are unchanged and keep banker's
rounding, so this is fully backward-compatible.

Internally a single MakeMoneyS(strategy) core does the normalisation; the
mode form delegates via StandardRounding(Mode) and the default via
rmHalfEven — one rounding code path.

Tests: 5 IR/semantic tests and 8 dual-backend e2e tests covering the mode
overloads (HalfUp/Down/Ceiling), the custom-strategy overload, the
default-stays-banker's guarantee, and rounding on Add/Multiply/constructors.

Docs: language-rationale.adoc updated to record that rounding is swappable
per call (default banker's), not hard-wired.

Verified: FIXPOINT_OK, NATIVE_FIXPOINT_OK, NATIVE_INTERNAL_OK; full suite
green on both the QBE-built and native-built runners (3686 tests).
2026-06-20 13:38:40 +01:00
Graeme Geldenhuys 77aa15a8d8 fix(native): interface argument to a record-returning free function
EmitSretCall (the sret path for free-function record returns) pushed one
stack slot per LOGICAL argument, so an interface argument — a fat pointer
that occupies TWO integer-register slots (obj + itab) — had its second slot
dropped.  The arguments landed in the wrong registers and the stack was
left unbalanced, crashing.  This is the free-function sibling of the method
fix in 077f13b (EmitMethodSretCall).

Fix: in EmitSretCall's <=5-slot register path, push interface args as two
slots (obj then itab, via EmitMethodArgPush for the direct case and the
saved fat pointer for the hoisted akIntfConsume case), track bytes pushed so
the hoisted-value reloads stay correct, and pop one register per SLOT.  The
register-vs-spill guard now uses a new SretUserSlots helper that counts
interface params as two.  The >5-slot overflow path raises a precise error
for the (not-yet-supported, untested) interface-in-overflow combination
rather than silently mis-placing registers.

Surfaced by Numerics.Money's rounding overloads: MoneyFromStr(amount,
currency, IRoundingStrategy) is a free function returning a record (TMoney)
with an interface argument, which hit this path.

Regression tests in cp.test.e2e.recordret.pas cover a free function
returning an sret record with an interface arg, with and without a leading
scalar arg, via AssertRunsOnAll (QBE + native parity).

Verified: FIXPOINT_OK, NATIVE_FIXPOINT_OK, NATIVE_INTERNAL_OK; full suite
green on both the QBE-built and native-built runners (3686 tests).
2026-06-20 13:38:20 +01:00
Graeme Geldenhuys 36cad37423 feat(stdlib): add Numerics.Money — currency-aware TMoney
TMoney is a thin value-type wrapper layering an ISO-4217 currency tag onto
an exact TDecimal amount.  The numeric core (TDecimal) stays currency- and
locale-agnostic; currency policy lives entirely in this wrapper, matching
Moneta / money-gem / rusty-money.

Design:
- Currency is an upper-cased ISO-4217 string code; the set is open (unknown
  codes are accepted at the fallback minor-unit scale of 2).
- A built-in registry gives each currency its default scale (JPY 0, USD 2,
  KWD 3, fallback 2); every TMoney is normalised to its currency's scale on
  construction and after every operation, using banker's rounding.
- Cross-currency Add/Subtract/Compare raise EMoneyMismatch (no implicit
  conversion); Equals is total (False, not raise, across currencies).
- Immutable value semantics, mirroring TDecimal.

API: free-function constructors (MoneyFromStr / MoneyFromDecimal /
MoneyFromInt / MoneyZero), record methods (Amount, CurrencyCode, IsZero,
Sign, Add, Subtract, Negate, Multiply, MultiplyInt, Compare, Equals,
AmountString, ToString), and the CurrencyScale registry function.

Tests:
- cp.test.numerics.money.pas: 22 IR/semantic tests (resolution, IR shape,
  type errors) via TUnitLoader.
- cp.test.e2e.numerics.money.pas: 24 dual-backend e2e tests
  (CompileAndRunWithRTL) covering construction + per-currency normalisation,
  banker's rounding, case-folding, arithmetic, mismatch raising,
  Compare/Equals/IsZero/Sign, the registry, and a realistic invoice flow.

Docs: language-rationale.adoc gains "Currency Amounts — TMoney Wraps
TDecimal, Currency Is a String Tag" (decision + alternatives);
future-improvements.adoc marks Numerics.Money as implemented.

Verified: FIXPOINT_OK, NATIVE_FIXPOINT_OK, NATIVE_INTERNAL_OK; full suite
green on both the QBE-built and native-built runners (3671 tests).
2026-06-20 10:33:35 +01:00
Graeme Geldenhuys 62331de986 fix(qbe): record copy must use field-width loads/stores
EmitRecordCopy copied every non-managed scalar field with loadw/storew (or
loadl/storel), ignoring the field's actual width.  A sub-word field —
Boolean or Byte (1 byte), SmallInt or Word (2 bytes) — was therefore
stored with a 4-byte storew that overran into the following field.  When a
Boolean sat immediately before a managed (string / class / dynarray) field,
the wide store clobbered the low bytes of that pointer; the subsequent
_StringRelease / _DynArrayRelease then dereferenced a garbage address and
crashed.

This is exactly TDecimal's layout (FNegative/FInflated Booleans ahead of a
carrier with a managed field), so it blocked Numerics.Money on QBE:
MakeMoney rounds into a TDecimal local and stores it into TMoney.FAmount,
copying the record by value.  The native backend was always width-correct.

Fix: route scalar field copies through LoadInstrFor/StoreInstrFor (the same
width-correct helpers already used for element and variable loads), and copy
inline aggregate fields (static array / jumbo-set bitmap) with memcpy.

Regression test in cp.test.e2e.records.pas reproduces the TDecimal-shaped
layout (Boolean flags before a string field, copied through an sret Result
field) and asserts QBE/native parity via AssertRunsOnAll.

Verified: FIXPOINT_OK, NATIVE_FIXPOINT_OK, NATIVE_INTERNAL_OK; full suite
green on both the QBE-built and native-built runners (3625 tests).
2026-06-20 09:34:19 +01:00
Graeme Geldenhuys 077f13b669 fix(native): interface argument to a record-returning method
A record-returning method that takes an interface parameter crashed (sret
return) or produced garbage (register return) on the native backend.  An
interface is a fat pointer (obj + itab) occupying TWO integer-register
slots, but EmitMethodSretCall popped one register per LOGICAL argument
instead of per ABI slot.  The interface's second slot was never consumed:
the user arguments landed in the wrong registers, and in the sret case a
stack slot was left unpopped, unbalancing the frame and corrupting return
addresses (the observed 0x1 / 0xffffffffffffffff backtrace).

Fix: in both EmitMethodSretCall register-passing paths (register-return
record and sret-return record, <=4-arg form), pop CountArgSlots(Params)
registers — counting interface params as two — into the integer registers
after sret/Self, rather than ACall.Args.Count.  The <=4 register-path
guard is likewise changed to gate on slot count (UserSlots + 2 <= 6), so
an interface arg cannot silently overflow the register file.

This is the root cause of the TDecimal.Divide / RoundTo / SetScale native
crash: each takes a `const IRoundingStrategy` (interface) and returns a
record.  With the fix, the full division/rounding battery — all eight
rounding modes, banker's rounding, custom IRoundingStrategy, rmUnnecessary,
the arbitrary-precision inflated path, and div-by-zero — runs identically
on native and QBE.

Tests:
- cp.test.e2e.recordret.pas: three new regression tests for an interface
  argument to a record-returning method (sret return, register return,
  and a scalar-before-interface ordering check), via AssertRunsOnAll.
- cp.test.e2e.numerics.decimal.pas: the 14 Divide/RoundTo/SetScale/float
  e2e tests that were CompileAndRunWithRTLQBEOnly now run dual-backend
  (CompileAndRunWithRTL), giving native parity coverage for the whole
  decimal arithmetic surface.

Verified: FIXPOINT_OK, NATIVE_FIXPOINT_OK, NATIVE_INTERNAL_OK; full suite
green on both the QBE-built and native-built test runners (3624 tests).
2026-06-20 03:57:08 +01:00
Graeme Geldenhuys 06a6bc0d1e fix(native): method call on a transient record-returning result
A method call whose receiver is itself a record-returning call —
A.Plus(B).Val() — crashed on the native backend.  The receiver
expression was lowered with EmitExprToEax, leaving the record VALUE
(the register-return payload, or the first bytes of the sret buffer) in
%rax, which was then used directly as the Self POINTER.  Dereferencing
that garbage segfaulted.  QBE handled the chained form correctly, so the
dual-backend e2e harness flagged it as a native/QBE parity divergence.

Fix: when a record method's receiver is a record-returning call,
materialise the call result into a stack buffer and pass its ADDRESS as
Self.  The buffer address is carried in callee-saved %rbx so it survives
the argument push/pop sequence; both are freed after the call.  Applied
to both EmitMethodCallExpr paths (<=6 and >6 arg slots) and all four
receiver sites in EmitMethodSretCall.

For the sret path, a forwarded %rsp-relative destination (the nested
chain A.Plus(B).Plus(A), where EmitRecordCallSretAt forwards '(%rsp)')
is resolved to an absolute pointer in callee-saved %r14 BEFORE the
receiver-materialisation prologue moves %rsp, so the destination no
longer drifts.

Regression tests in cp.test.e2e.recordret.pas cover the register-return
chain, the sret-record chain, the >5-arg overflow path, the nested
double chain, and the managed-field (TDecimal-shaped) record — all via
AssertRunsOnAll (QBE + native parity).

Verified: FIXPOINT_OK, NATIVE_FIXPOINT_OK, NATIVE_INTERNAL_OK; full
suite green on both the QBE-built and native-built test runners
(3621 tests).
2026-06-20 03:25:31 +01:00
Graeme Geldenhuys 718ee45e20 feat(stdlib): add Numerics.Decimal — exact decimal (TDecimal)
A single exact base-10 decimal type for financial / exact-decimal use,
replacing the historical Currency/Comp/Extended proliferation with one type.

  - Construction: DecFromInt/Int64/Str, plus a safe/exact float split
    (DecFromFloat takes the shortest decimal — 0.1 stays 0.1 — while the
    dangerous binary-exact path is the explicitly-named DecFromFloatExact).
  - Value semantics + value-based equality: 2.0 = 2.00 with a consistent hash,
    so it is safe as a dictionary key (unlike Java BigDecimal).
  - Arithmetic: Add/Subtract (scale = max), Multiply (scale = sum), Negate, Abs,
    arbitrary precision via a decimal-digit magnitude (compact Int64 fast path
    inflating on overflow).
  - Division + rounding: a layered design — a TRoundingMode enum (8 modes,
    banker's default) over an IRoundingStrategy interface users can implement
    for custom rounding.  Division always carries an explicit scale + mode.
  - Formatting: ToString/ToPlainString never use scientific notation;
    StripTrailingZeros keeps integer zeros (600 stays 600, never 6E+2).
  - Conversions out: ToDouble (lossy), ToInt64 (truncating).

IR tests (32) + e2e tests (46).  Add/Subtract/Multiply and the value-semantics
run dual-backend; Divide/RoundTo and float conversion run QBE-only pending
native codegen fixes (logic verified on QBE; see bugs.txt).
2026-06-20 02:10:12 +01:00
Graeme Geldenhuys 13a8a39af0 fix(compiler): incremental unit-mode crash (nil Prog.SymbolTable)
Compiling a UNIT (top source is a `unit`, so the pipeline runs in unit-mode and
Prog stays nil) via the default incremental path segfaulted: the incremental
worker setup unconditionally read `Prog.SymbolTable` to seed each dep worker,
dereferencing nil.  In unit-mode the symbol table comes from the semantic pass,
not a program node.  This is exactly the invocation the runtime Makefile drives
(`blaise --source X.pas --output X.o` per RTL unit), so it broke `make` in
runtime/ once incremental became the default; it was a latent pre-existing bug
in the opt-in incremental path (reproduces at de0ea5d with --incremental).

Fix: seed the worker symbol table from Semantic.GetSymbolTable() when Prog is
nil, matching the non-incremental unit-mode path.

Also pin the runtime Makefile to --no-incremental.  That Makefile is itself a
hand-managed separate-compilation system (one object per unit + an explicit
archive list); the compiler's incremental mode would additionally write
per-dependency side-effect objects and skip inlining a used unit's bodies, but
those side-effect objects are not in the archive list — so a cross-unit symbol
(e.g. typeinfo_TRtlPlatform, referenced by the derived TRtlPlatformPosix in a
different unit) was left undefined at link.  Whole-program per unit keeps each
unit object self-contained.

Regression test (cp.test.e2e.sepcompile.pas): compile a unit that uses another
unit in unit-mode via the default incremental path, then build and run a
program over the emitted object.
2026-06-20 02:04:58 +01:00
Graeme Geldenhuys 47ca10d7d3 fix(native): float arguments on the managed-record sret call path
A float (Double/Single) by-value argument passed to a function or method that
returns a record with a managed field (dynamic array / string, i.e. the true
sret return path) was mis-handled by the native backend: every argument was
materialised via EmitExprToEax, the integer-only emitter.  A float LITERAL hit
"unsupported expression form TFloatLiteral", and a float VARIABLE would have
been routed through %rax into an integer argument register instead of an %xmm
register — wrong per the SysV ABI.  QBE compiled these correctly, so it was a
native/QBE parity divergence.

This blocked DecFromFloat / DecFromFloatExact (TDecimal has a dynamic-array
field) and any MoneyFromFloat-style constructor in Numerics.Money.

Fix: both EmitSretCall (free functions) and EmitMethodSretCall (methods) now
detect a float-typed by-value argument and, when present, evaluate arguments
into stack slots and load them into registers per the SysV ABI — integer args
into the integer argument registers (after %rdi=sret and, for methods,
%rsi=Self), float args into %xmm0.. with an independent counter, and %al set to
the vector-register count.  The pure-integer path is unchanged, so the common
case (and native self-compile) is byte-for-byte identical.

Adds three e2e regression tests (cp.test.e2e.recordret.pas), run on both
backends via AssertRunsOnAll: single float arg to a managed-record-returning
function, two float args, and a single float arg to a managed-record-returning
method.

Verified: FIXPOINT_OK, NATIVE_FIXPOINT_OK, NATIVE_INTERNAL_OK; the new tests
pass on both the QBE and native arms.
2026-06-20 01:13:58 +01:00
Graeme Geldenhuys 738e080407 feat(compiler): make incremental compilation the default; fix dropped unit init
Incremental compilation (per-unit .o emission with embedded .bif) is now the
default for every build; --no-incremental opts out and builds a single
whole-program object.  The old --incremental opt-in flag is removed.

Fix a latent incremental-mode bug the flip exposed: in incremental /
--skip-dep-codegen mode the dependency unit BODIES are compiled into their own
objects and AppendUnit is skipped for them in the main program codegen.  But
AppendUnit was also where a unit's initialization section got registered into
the init-call list, so the program startup ($main) emitted no
`call <Unit>_init` for any dep — every dependency's initialization section
silently never ran.  This affected BOTH backends and was why a native-built
TestRunner (built incrementally by default) registered zero tests: each
cp.test.* unit's `initialization`/RegisterTest never executed.

Fix: add ICodeGen.NoteDepInitUnit(name, hasInit), implemented on the QBE
backend and the native backend (virtual on TNativeBackend, overridden by the
x86_64 backend), which records a dep unit's init symbol in dependency order
without emitting its body.  The driver calls it for each skipped dep in
incremental mode, so $main emits the calls and they resolve against the
<Unit>_init symbols exported by the per-unit objects.  Verified across the full
matrix (native/qbe x incremental/--no-incremental), including chained
multi-unit init ordering (a dep that uses another dep sees the other's init
having run first).

Guard the incremental block so it never runs in --emit-ir / --emit-asm /
--dump-ast modes (those produce stdout text and no objects); this keeps
fixpoint.sh, fixpoint-native.sh and rolling-bootstrap.sh — all of which use
--emit-ir/--emit-asm — unaffected.

Tests: replace the --incremental e2e test with one that exercises the default
incremental path (no flag), plus a new --no-incremental test asserting the
whole-program path leaves no per-unit .o behind.

Remove the eight TestCodegen_Win64_* record-return IR tests and the GenIRWin64
helper.  They pinned aspirational QBE Win64-ABI IR for a target the native
backend does not support (only linux-x86_64 is implemented) and that is being
deprecated along with QBE.  The native backend miscompiled the in-process
GTarget-global Win64 path these tests drove; rather than carry IR tests for an
unsupported, unrunnable, soon-to-be-removed target, they are dropped.  Native
Win64 will be addressed when Windows support is actually built.

Verified: FIXPOINT_OK, NATIVE_FIXPOINT_OK, NATIVE_INTERNAL_OK; full suite
3534 tests / 0 failures on both the QBE-built and native-built test runners.
2026-06-19 21:05:24 +01:00
Graeme Geldenhuys de0ea5defb chore(phase3): deprecate QBE in help text, guard internal linker, document toolchain
Phase 3 of the native-default drive — the locally-verifiable items (CI and
rolling-bootstrap changes are deferred to Phase 4, where they become correct
once v0.12.0 is the rolling-bootstrap anchor):

- Help text now marks the backends explicitly: "qbe (deprecated) | native
  (default)". QBE is retained as the e2e parity oracle and QBE-fixpoint guard;
  removal is a later release.

- fixpoint-native-internal.sh now drives the FULL internal pipeline (internal
  assembler + internal linker) against an all-external (gcc assemble + gcc link)
  reference, instead of only differing on the assembler. Both internal tools are
  now the default toolchain, so the conformance guard must exercise both. Header
  comments updated to reflect that it guards the internal linker too and why it
  stays a differential probe (the internal assembler buffers the whole object in
  memory and OOMs on the compiler's own ~631k-line .s).

- language-rationale.adoc records the decision: native backend + internal
  assembler + internal linker as the default toolchain (no external tools beyond
  the C runtime startup objects), why QBE is kept-but-deprecated, and the
  per-invocation escape hatches (--assembler external, --linker external,
  --backend qbe, --incremental).

Verified: FIXPOINT_OK, NATIVE_FIXPOINT_OK, NATIVE_INTERNAL_OK; full suite
3541 tests / 0 failures on both the QBE-built and native-built test runners.
2026-06-19 18:16:46 +01:00
Graeme Geldenhuys 91b7354c8f fix(native): SetLength(A, N) must evaluate N before loading the array pointer
The native dynamic-array SetLength lowering loaded the array's current data
pointer into %rdi (the first argument to _DynArraySetLength) BEFORE evaluating
the new-length expression. When that expression itself emitted a call — most
commonly SetLength(Result, Length(A)), where Length(A) lowers to a
_DynArrayLength call — the call clobbered %rdi, so _DynArraySetLength resized
the wrong array (the length-expression's operand) instead of the intended one.

The visible symptom: a function taking a dynamic-array parameter and returning
a dynamic array had its Result aliased to the first array parameter's buffer.
SetLength(Result, Length(A)) resized A instead of Result, every Result[I] write
was lost, and the caller got back the first argument unchanged. QBE was correct
throughout; this was a native-only parity divergence.

Fix: evaluate the length expression into %esi first, then load the array
pointer into %rdi immediately before the call — matching the safe ordering the
string and field-receiver SetLength paths already used.

Adds five e2e regression tests (cp.test.e2e.dynarray.pas) covering the result-
from-param-length case, the const-array-param subtract, global-from-global
length, local-from-local length, and length-from-a-user-function-call. All run
on both backends via AssertRunsOnAll; the native arm would have failed before
this fix. This closes a test-coverage gap: no existing test exercised a
SetLength whose length argument emitted a call.
2026-06-19 17:33:39 +01:00
Graeme Geldenhuys 30d577daae fix(assembler): handle @tpoff relocations and %fs:disp numeric TLS access
The internal assembler had two TLS-related bugs that caused undefined
symbols in .o files compiled from runtime units using threadvars:

1. sym@tpoff(%reg) operands: the parser included '@tpoff' as part of
   the symbol name instead of recognising it as a relocation modifier.
   Fixed by stopping symbol-name accumulation at '@', detecting the
   'tpoff' suffix, and setting a TpOff flag that emits R_X86_64_TPOFF32.

2. %fs:0 (thread base read): the parser fell through to symbol parsing
   and created an undefined reference to literal "0". Fixed by checking
   for a numeric displacement before attempting symbol parsing in the
   %fs: handler.

Also fix the --help text to show 'native (default)' instead of
'qbe (default)' now that the native backend is the default.
2026-06-19 16:35:11 +01:00
Graeme Geldenhuys cf274eeb89 feat(native): default to internal assembler and linker
The native backend now uses --assembler internal and --linker internal
by default when the user does not explicitly pass these flags. This
eliminates the dependency on external tools (gcc/as/ld) for native
backend compilation.

Also fixes a linker bug where writing to a currently-executing binary
on Linux would fail with EStreamError — the linker now calls
DeleteFile before creating the output file.
2026-06-19 14:32:58 +01:00
Graeme Geldenhuys dc19f39620 fix(assembler): handle \x hex escapes and # inside quoted strings in .ascii
The internal assembler had two bugs in .ascii directive parsing:

1. Comment stripping treated '#' as a comment start even inside quoted
   strings, silently truncating string literals containing '#'. This
   corrupted .rodata for any program with '#' in string constants
   (e.g. QBE IR format strings like "# String literals").

2. The \xHH hex escape syntax was not handled. Bytes encoded as \xE2
   etc. were emitted as literal ASCII 'xE2' (3 bytes) instead of the
   single byte 0xE2, corrupting UTF-8 string data.

Both bugs were invisible when using the external assembler (gcc) and
only manifested when --assembler internal was used on large programs
with non-ASCII string literals or '#' characters in strings.
2026-06-19 14:32:42 +01:00
Graeme Geldenhuys fb0baa229f docs: mark internal linker Phases C and D as implemented 2026-06-19 10:51:09 +01:00
Graeme Geldenhuys 3d5fdf86c8 test(linker): add internal linker e2e tests via --linker internal
Four tests exercise the full compiler-driver pipeline with
--backend native --assembler internal --linker internal:
HelloWorld, StringOps (Format/UpperCase/IntToStr), exception
handling (raise + try/except), and virtual method dispatch.

These catch regressions in TLS relocation, CRT discovery,
duplicate-symbol handling, and PIE emission.
2026-06-19 10:48:04 +01:00
Graeme Geldenhuys db309c85ea feat(linker): wire internal linker into compiler driver + fix TLS relocations
Add --linker internal|external option to the native backend driver,
routing the link step through TLinker instead of shelling out to cc.
FindCrtObjects discovers CRT startup objects (Scrt1.o, crti.o, crtn.o,
crtbeginS.o, crtendS.o) on Debian and RedHat layouts.

Fix SHF_TLS constant from $200 to the correct ELF spec value $400 in
both the reader and writer — the wrong value caused .tbss sections to
be placed twice (once in the normal NOBITS loop, once in the TLS
section), producing doubled negative TPOFF32 offsets and segfaults.

Fix FTlsAddr to use the post-alignment address from PlaceSection rather
than the pre-alignment cursor, which caused off-by-padding TPOFF values.

Change duplicate global symbol handling from error to first-wins
semantics (matching ld behaviour), needed because the main program
object and archive members may both define system runtime functions.

Verified: FIXPOINT_OK, NATIVE_FIXPOINT_OK, NATIVE_INTERNAL_OK,
3532 tests pass on both QBE-built and native-built test runners.
2026-06-19 10:43:33 +01:00
Graeme Geldenhuys 078dc81e46 feat(linker): Phase C dynamic linking — GOT/PLT, CRT objects, PIE emission
Implement Phase C of the internal ELF linker: produce position-independent
ET_DYN executables linked against libc through dynamic GOT/PLT dispatch.

New capabilities:
- SetDynamic(True) switches the linker to PIE mode
- AddCrtObject() loads system CRT startup objects (Scrt1.o, crti.o,
  crtn.o, crtbeginS.o, crtendS.o)
- CollectExternals scans undefined non-weak symbols and creates PLT entries
- CollectGotSlots creates non-PLT GOT slots for GOTPCREL references to
  locally-defined symbols (e.g. main, __dso_handle)
- BuildDynamic generates .interp, .dynstr, .dynsym, SysV .hash, .got
  (3 reserved + N PLT + M non-PLT slots), .plt (header + stubs),
  .rela.plt (JUMP_SLOT entries)
- LayoutDynamic assigns PIE virtual addresses (base 0): RO metadata →
  .text/.plt → RELRO (.init_array, .fini_array, .dynamic, .got) →
  .data/.bss, with page-aligned PT_LOAD boundaries
- EmitDynExecutable writes the full PIE byte image with ELF header,
  10 program headers (PHDR, INTERP, 4×LOAD, DYNAMIC, TLS, GNU_STACK,
  GNU_RELRO), and section data at virtual offsets

Relocation handling extended:
- R_X86_64_64 → R_X86_64_RELATIVE in .rela.dyn
- R_X86_64_32/32S for absolute symbol references
- R_X86_64_GOTPCREL/GOTPCRELX/REX_GOTPCRELX → GOT slot lookup
- R_X86_64_TPOFF32 → TLS offset calculation

Tests: TDynLinkerTests (2 structural), TDynLinkerE2ETests (1 E2E that
links a main() calling write via PLT, runs the binary, asserts exit
code 42 + correct stdout). All 3528 tests pass.
2026-06-19 10:00:08 +01:00
Graeme Geldenhuys 8f38fd1416 feat(stdlib): add CodePointToString UTF-8 encoder to strutils
Adds CodePointToString(CP: Integer): string, the inverse of CodePointAt /
CodePointFromByteIndex.  It encodes a Unicode codepoint (0..U+10FFFF) as
its 1..4 byte UTF-8 sequence, providing the codepoint-aware replacement for
the Char(n) cast used in other Pascal dialects.  Chr(n) only writes a single
raw byte, which is invalid for codepoints above 127; CodePointToString emits
the correct multi-byte form.  Out-of-range values yield an empty string.

E2E tests cover single-byte ASCII, the two-byte 0xC2 0xB1 encoding of U+00B1,
a round-trip across all four UTF-8 length classes, and out-of-range handling.
2026-06-19 09:28:53 +01:00
Graeme Geldenhuys 12613ab68e docs: mark internal linker Phases A and B as implemented 2026-06-19 07:56:13 +01:00
Graeme Geldenhuys 0d47c5f996 feat(backend): default to native backend; fix codegen bugs exposed by the switch
The native x86-64 backend is now the default (bkNative).  QBE remains
available via --backend qbe.  Several codegen bugs that were invisible
while QBE was the default are fixed in this commit:

Native backend fixes:
- EmitLeaqGlobal helper: threadvar globals now emit the correct
  fs:0 + @tpoff TLS sequence instead of bare %rip-relative leaq.
  Fixes static array write (FreeLists), string subscript assignment,
  EmitExprAddr, record memcpy, method-ptr cast, and open-array push
  paths that all used raw leaq %s(%rip).
- EmitIncDec: unified local/global paths through VarOperand so
  threadvar scalar Inc/Dec (e.g. LargeFreeCount) gets TLS addressing.
- EmitIncDec FAE.Base: Inc(P^.Field) where P is a pointer now
  evaluates the base expression instead of leaq on the stack slot.
- FinalizeEmit: data section (.data/.bss/.rodata) now emits once at
  the end of unit compilation via FinalizeEmit, not inside each
  EmitUnit call.  Fixes duplicate/missing string literals in sep-compile.
- EmitFunctionDef AExported: implementation-only helpers in monolithic
  mode stay file-local (.globl suppressed) to avoid symbol collisions
  with the RTL archive.

QBE backend fixes:
- AppendUnit typeinfo: export prefix added to data $typeinfo_TObject,
  $typeinfo_TCustomAttribute, $vtable_TObject, $vtable_TCustomAttribute
  so native-built RTL can resolve them.
- FSuppressSystemDefs: decoupled from FExportAll so CreateUnitCodeGen
  can export all symbols without suppressing system defs.

Infrastructure:
- runtime/Makefile: BLAISE_FLAGS variable for passing extra compiler
  flags (e.g. --backend qbe) from build scripts.
- fixpoint.sh: make clean before RTL rebuild to pick up backend change.
2026-06-19 04:27:41 +01:00
Graeme Geldenhuys 070a229e20 Revert "fix(native): suppress duplicate built-in system defs in unit-to-.o compilation"
This reverts commit 87c17ee589.
2026-06-19 00:26:53 +01:00
Graeme Geldenhuys 60217f9026 Revert "feat(backend): default to the native backend; QBE is now opt-in"
This reverts commit d56bdbf84f.
2026-06-19 00:26:53 +01:00
Graeme Geldenhuys d56bdbf84f feat(backend): default to the native backend; QBE is now opt-in
Flip the compiler's default --backend from qbe to native.  Native has full
feature parity with QBE (the v0.11.0 cycle's 116 fixes plus the dual-backend
e2e harness brought them level), self-hosts, and gives no external codegen
dependency, source-level debugging, and a path to cross-compilation — so it
is the right default to exercise everywhere.

QBE stays fully supported via --backend qbe and remains the cold-bootstrap
root: --emit-ir still routes to QBE regardless of the default (PickTopDriver
ignores --backend for emit modes), so scripts/rolling-bootstrap.sh,
fixpoint.sh, and CI — all of which pass --emit-ir explicitly — are unaffected
by this change.  The only behaviour change is that a plain
'blaise --source X --output Y' (and a plain 'make' in runtime/) now uses the
native backend.

Flipping the default surfaced and fixed a real native gap first (the
unit-to-.o duplicate-system-defs link collision, previous commit); the full
suite is green with the TestRunner built by BOTH a QBE-built and a
native-built compiler, and all three fixpoints pass.
2026-06-18 18:43:23 +01:00
Graeme Geldenhuys 87c17ee589 fix(native): suppress duplicate built-in system defs in unit-to-.o compilation
Compiling a unit to a standalone .o with the native backend
(blaise --source U.pas --output U.o) emitted the built-in system
definitions — typeinfo_/vtable_/_FieldCleanup_ for TObject and
TCustomAttribute — into the unit .o.  Linking that .o against a consumer
program (which emits its own copies) failed with
'multiple definition of vtable_TCustomAttribute'.

Two gaps fed this:
- The unit-as-top-level path in Blaise.pas built its codegen via
  Driver.CreateCodeGen (the program path, separate-compile = False) instead
  of Driver.CreateUnitCodeGen (separate-compile = True), so the backend's
  FSeparateCompile gate (which already suppresses the system defs) never
  engaged.  Switched the IsUnitMode branch to CreateUnitCodeGen, with a
  CreateCodeGen fallback for any backend lacking a unit codegen.
- TCodeGenNative.GenerateUnit did not propagate FSeparateCompile to the
  backend (AppendUnit already did); added the missing propagation for
  defensive correctness.

The QBE backend was unaffected (its unit path already suppresses these).
Adds TestNativeBackend_RoundTrip_NoDuplicateSystemDefs in
cp.test.e2e.sepcompile, which pins --backend native so the guard holds
regardless of the compiler's default backend.
2026-06-18 18:23:12 +01:00
Graeme Geldenhuys e9f705fdc8 fix(native): stage-stable char-literal byte RHS in string subscript write
EmitByteRhsToEax lowered a single-character string-literal RHS via
Ord(TStringLiteral(AExpr).Value[0]).  That subscript-then-Ord idiom is
miscompiled by the self-hosted native stage: a native-built compiler baked a
pointer-sized garbage immediate (movl $0xd291f9ec) instead of the byte, so
S[i] := 'c' wrote junk.  It only surfaced in CI, where the test runner is
built by the native-bootstrapped -pre binary; local verification used the
QBE-built fixpoint binary, which lowers the idiom correctly, so the bug was
invisible.

Use StrAt(Value, 0) — the OrdAt-backed byte-read helper already used
elsewhere in this backend and stage-stable — instead of Ord(Value[0]).
Matches the QBE backend, which uses StrAt and was never affected.

Verified by building the test runner with a native-built compiler (the CI
configuration): full suite passes; all three fixpoints clean.
2026-06-18 15:55:33 +01:00
Graeme Geldenhuys 07aac3322f feat(string): writable string subscript S[i] := ch with copy-on-write
S[I] := <byte> was rejected by the semantic pass ('is not a static array
or dynamic array') for any string — local, global, or var-param — on both
backends.  It is now supported as the symmetric counterpart of the S[I]
read: an in-place byte store into a 0-based UTF-8 string.

Because strings are reference-counted and literals are immortal (stored in
read-only memory; the native backend put them in .rodata, so a naive store
segfaulted, while QBE silently mutated the shared literal), the write
performs copy-on-write.  New RTL helper _StringUnique(S) returns S when it
is uniquely owned (rc=1) and otherwise allocates a fresh rc=1 copy, releases
the old reference, and returns the copy.  Both backends emit
_StringUnique -> write the result back to the slot -> storeb, so the slot
keeps exactly one owned reference and mutating one alias never disturbs
another (Delphi/FPC UniqueString semantics).

The RHS accepts a numeric ordinal, Chr(n), or a single-character literal
(the byte-shaped forms used in place of a Char type).  PChar subscript
writes keep their existing in-place path (raw pointer, no ARC header).

Dual-backend e2e tests (write, copy-on-write aliasing + literal reuse,
var-param) in cp.test.e2e.stringops.  Updates language-rationale.adoc
(writable subscript + COW) and grammar.ebnf (string as a subscript-assign
base).
2026-06-18 15:39:38 +01:00
Graeme Geldenhuys 5b5b95c18f fix(const): accept hex/octal/binary literals in array-const elements (#129)
$hex, %binary and &octal integer literals were rejected inside an
array-constant initialiser — 'array[0..1] of Int64 = ($1, $2)' failed
with 'Cannot resolve array-const element' while the scalar form '= $1'
worked.  The parser stores array elements verbatim (prefix and all), and
ResolveConstArrayElem only recognised decimal digits, so any radix-prefixed
element fell through to an identifier lookup and errored.

Fold radix-prefixed elements (with optional leading sign) through
ParseIntLiteral — the same canonical parser the rest of the compiler uses
for scalar and typed consts — so all four radixes, plus underscore digit
separators, behave identically inside an array initialiser.  Keeps FPC's
&-octal (the project prefers FPC syntax where FPC and Delphi diverge; the
lexer already tokenised all four radixes).

Documents the radix-prefix rule in language-rationale.adoc.
2026-06-18 15:39:18 +01:00
Graeme Geldenhuys fe4e5602cf feat(linker): Phase B — symbol resolution, static relocations, ET_EXEC emission
Implement the Phase B internal-linker pipeline (TLinker in
blaise.linker.elf) on top of the Phase A section merger:

- Symbol resolution: build the global symbol table from merged
  sections (STB_GLOBAL over STB_WEAK; two globals = duplicate error),
  define the five linker-synthesised symbols (_GLOBAL_OFFSET_TABLE_,
  __bss_start, _edata, _end, __TMC_END__), resolve weak-undefined
  references to 0 and raise on strong-undefined.
- Static relocations: patch R_X86_64_PC32 / R_X86_64_PLT32 as S+A-P
  (PLT32 against an internal symbol relaxes to the direct form, no
  PLT). Reject the dynamic-only forms (R_X86_64_64, GOT/TLS) and
  absolute 32-bit symbol references with a diagnostic — deferred to
  Phase C.
- Layout + emission: assign virtual addresses at a fixed base
  (0x400000) in an executable run (.text + .rodata, sharing the first
  page with the headers) and a writable run (.data + .bss) on a fresh
  page; write a non-PIE ET_EXEC with two PT_LOAD program headers, the
  relocated section payloads, and a section-header table for tooling;
  mark the file executable.

Platform/arch-variable values (Is64, OSABI, EMachine, BaseAddr,
PageSize) live in TLinkTarget rather than being hard-coded, so FreeBSD
and a future i386 ELF target are a new target record and a PE/Mach-O
container would be a sibling writer behind the same symbol/relocation
core.

The linker is not wired into the compiler driver — it is a standalone
unit exercised only by tests; all backends still link via cc. Driver
integration behind --linker internal is Phase D.

Tests: TLinkerTests (symbol resolution, PC32 cross-object displacement,
R_X86_64_64 rejection, ELF-header/entry-point structure) and
TLinkerE2ETests (hand-written write+exit syscall object linked
internally to an ET_EXEC, executed, asserted on stdout + exit code;
readelf -a reports a clean statically-linked x86-64 executable).

Two native-backend codegen constraints were worked around in this unit:
no string-element assignment through a var-string parameter (append-
style byte building + PChar-local in-place writes), and no capturing
nested functions (private methods instead).
2026-06-18 14:58:24 +01:00