Skip to content

Latest commit

 

History

History
2403 lines (1725 loc) · 123 KB

File metadata and controls

2403 lines (1725 loc) · 123 KB

Baa Roadmap (Updated)

Track the development progress of the Baa programming language. **Current Status:** Phase 4.5 - Reference Compiler Stabilization (v0.5.x) ← IN PROGRESS

---

📚 Documentation Track (Definitive Arabic Book)

Goal: Produce a Kernighan & Ritchie–style first book for Baa, in Arabic, serving as the definitive learning + reference resource.

  • [~] Write the Arabic "Baa Book" — book-length guide in Arabic with exercises. — draft exists in docs/BAA\_BOOK\_AR.md
  • Define terminology glossarydocs/TERMINOLOGY_GLOSSARY.md is the canonical Arabic/English vocabulary source.
  • Create example suite — verified, idiomatic examples that compile with v0.3.7.
  • Add exercises and challenges — per chapter, with expected outputs.
  • Add debugging and performance chapters — common pitfalls, diagnostics, optimization notes.
  • Native technical review — review by Arabic-speaking engineers before release.

---

⚙️ Phase 3: The Intermediate Representation (v0.3.x)

Goal: Decouple the language from x86 Assembly to enable optimizations and multiple backends.

**Design Document:** See [BAA_IR_SPECIFICATION.md](docs/BAA_IR_SPECIFICATION.md) for full IR specification.

v0.3.0: IR Foundation 🏗️

v0.3.0.1: IR Data Structures ✅ COMPLETED (2026-01-15)

  • Define IROp enum — All opcodes: IR\_OP\_ADD, IR\_OP\_SUB, IR\_OP\_MUL, etc.
  • Define IRType enum — Types: IR\_TYPE\_I64, IR\_TYPE\_I32, IR\_TYPE\_I8, IR\_TYPE\_I1, IR\_TYPE\_PTR.
  • Define IRInst struct — Instruction with opcode, type, dest register, operands.
  • Define IRBlock struct — Basic block with label, instruction list, successors.
  • Define IRFunc struct — Function with name, return type, entry block, register counter.
  • Create ir.h — Header file with all IR definitions.
  • Create ir.c — Implementation with helper functions and IR printing.

v0.3.0.2: IR Builder Functions ✅ COMPLETED (2026-01-15)

  • IRBuilder context struct — Builder pattern with insertion point tracking.
  • ir\_builder\_create\_func() — Create a new IR function.
  • ir\_builder\_create\_block() — Create a new basic block with label.
  • ir\_builder\_set\_insert\_point() — Set insertion point for new instructions.
  • ir\_builder\_alloc\_reg() — Allocate next virtual register %م<n>.
  • ir\_builder\_emit\_\*() — Emit instructions (add, sub, mul, div, load, store, br, ret, call, etc.).
  • Control flow helpersir\_builder\_create\_if\_then(), ir\_builder\_create\_while().
  • Create ir\_builder.h — Header file with builder API.
  • Create ir\_builder.c — Implementation of builder functions.

v0.3.0.3: AST to IR Lowering (Expressions) ✅ COMPLETED (2026-01-16)

  • lower\_expr() — Main expression lowering dispatcher.
  • Lower NODE\_INT — Return immediate value.
  • Lower NODE\_VAR\_REF — Generate حمل (load) instruction.
  • Lower NODE\_BIN\_OP — Generate جمع/طرح/ضرب/قسم instructions.
  • Lower NODE\_UNARY\_OP — Generate سالب/نفي instructions.
  • Lower NODE\_CALL\_EXPR — Generate نداء (call) instruction.

v0.3.0.4: AST to IR Lowering (Statements) ✅ COMPLETED (2026-01-16)

  • lower\_stmt() — Main statement lowering dispatcher.
  • Lower NODE\_VAR\_DECL — Generate حجز (alloca) + خزن (store).
  • Lower NODE\_ASSIGN — Generate خزن (store) instruction.
  • Lower NODE\_RETURN — Generate رجوع (return) instruction.
  • Lower NODE\_PRINT — Generate نداء @اطبع() call.
  • Lower NODE\_READ — Generate نداء @اقرأ() call.

v0.3.0.5: AST to IR Lowering (Control Flow) ✅ COMPLETED (2026-01-16)

  • Lower NODE\_IF — Create condition block + true/false blocks + merge block.
  • Lower NODE\_WHILE — Create header/body/exit blocks with back edge.
  • Lower NODE\_FOR — Create init/header/body/increment/exit blocks.
  • Lower NODE\_SWITCH — Create comparison chain + case blocks.
  • Lower NODE\_BREAK — Generate قفز to loop exit.
  • Lower NODE\_CONTINUE — Generate قفز to loop header/increment.

v0.3.0.6: IR Printer ✅ COMPLETED (2026-01-17)

  • ir\_print\_func() — Print function header and all blocks.
  • ir\_print\_block() — Print block label and all instructions.
  • ir\_print\_inst() — Print single instruction with Arabic opcodes.
  • Arabic numeral output — Print register numbers in Arabic (٠١٢٣٤٥٦٧٨٩).
  • --dump-ir CLI flag — Add command-line option to print IR.

v0.3.0.7: Integration & Testing ✅ COMPLETED (2026-01-17)

  • Integrate IR into pipeline — AST → IR (skip direct codegen).
  • Create ir\_test.baa — Simple test programs.
  • Verify IR output — Check IR text matches specification.
  • Update main.c — Add IR phase between analysis and codegen.
  • Add --emit-ir flag — Write IR to .ir file.
  • Fix global variable resolution — Proper lookup in lower\_expr() and lower\_assign().

---

v0.3.1: The Optimizer ⚡

v0.3.1.1: Analysis Infrastructure ✅ COMPLETED (2026-01-21)

  • CFG validation — Verify all blocks have terminators.
  • Predecessor lists — Build predecessor list for each block.
  • Dominator tree — Compute dominance relationships.
  • Define IRPass interface — Function pointer for optimization passes.

v0.3.1.2: Constant Folding (طي_الثوابت) ✅ COMPLETED (2026-01-22)

  • Detect constant operands — Both operands are immediate values.
  • Fold arithmeticجمع ص٦٤ ٥، ٣٨.
  • Fold comparisonsقارن أكبر ص٦٤ ١٠، ٥صواب.
  • Replace instruction — Remove op, use constant result.

v0.3.1.3: Dead Code Elimination (حذف_الميت) ✅ COMPLETED (2026-01-27)

  • Mark used values — Walk from terminators backward.
  • Identify dead instructions — Result never used.
  • Remove dead instructions — Delete from block.
  • Remove unreachable blocks — No predecessors (except entry).

v0.3.1.4: Copy Propagation (نشر_النسخ) ✅ COMPLETED (2026-01-27)

  • Detect copy instructionsIR\_OP\_COPY (نسخ) instruction pattern.
  • Replace uses — Substitute original for copy in operands / call args / phi entries.
  • Remove redundant copies — Delete نسخ instruction after propagation.

v0.3.1.5: Common Subexpression Elimination (حذف_المكرر) ✅ COMPLETED (2026-02-07)

  • Hash expressions — Create signature for each operation.
  • Detect duplicates — Same op + same operands.
  • Replace with existing result — Reuse previous computation.

v0.3.1.6: Optimization Pipeline ✅ COMPLETED (2026-02-07)

  • Pass ordering — Define optimal pass sequence (constfold → copyprop → CSE → DCE).
  • Iteration — Run passes until no changes (fixpoint, max 10 iterations).
  • -O0, -O1, -O2 flags — Control optimization level.
  • --dump-ir-opt — Print IR after optimization.

---

v0.3.2: The Backend (Target Independence) 🎯

v0.3.2.1: Instruction Selection ✅ COMPLETED (2026-02-07)

  • Define MachineInst — Abstract machine instruction.
  • IR to Machine mappingجمعADD, حملMOV, etc.
  • Pattern matching — Select optimal instruction sequences.
  • Handle immediates — Inline constants where possible.

v0.3.2.2: Register Allocation ✅ COMPLETED (2026-02-07)

  • Liveness analysis — Compute live ranges for each virtual register.
  • Linear scan allocator — Simple, fast allocation algorithm.
  • Spilling — Handle register pressure by spilling to stack.
  • Map to x64 registers — RAX, RBX, RCX, RDX, R8-R15.

v0.3.2.3: Code Emission ✅ COMPLETED (2026-02-08)

  • Emit function prologue — Stack setup, callee-saved registers.
  • Emit instructions — Generate AT&T syntax assembly.
  • Emit function epilogue — Stack teardown, return.
  • Emit data section — Global variables and string literals.

v0.3.2.4: Backend Integration

  • Replace old codegen — IR → Backend → Assembly.
  • Verify output — Compare with old codegen results.
  • Performance testing — Ensure no regression.
  • Remove legacy codegen — Retire the legacy AST backend from the build.

0.3.2.4-IR-FIX: ISel Bug Fixes & Backend Testing ✅ COMPLETED (2026-02-08)

  • Fix ISel logical op size mismatchisel\_lower\_logical() forced 64-bit operand size; widened 8-bit boolean vregs to prevent assembler errors.
  • Fix function parameter ABI copiesisel\_lower\_func() prepends MOV from RCX/RDX/R8/R9 to parameter vregs at entry block.
  • Fix IDIV RAX constraintisel\_lower\_div() explicitly routes dividend through RAX (vreg -2) for correct division results.
  • Comprehensive backend testtests/integration/backend/backend\_test.baa: 27 functions, 63 assertions, all PASS.

0.3.2.4-setup: Installer & GCC Bundling ✅ COMPLETED (2026-02-08)

  • Bundle MinGW-w64 GCC — Ship GCC toolchain in gcc/ subfolder inside the installer.
  • Auto-detect bundled GCCresolve\_gcc\_path() in main.c finds gcc.exe relative to baa.exe.
  • Update installer (setup.iss) — Add gcc\\\* files, dual PATH entries, post-install GCC verification.
  • GCC bundle scriptscripts/prepare\_gcc\_bundle.ps1 downloads and prepares the minimal toolchain.
  • Sync version metadatabaa.rc and setup.iss updated to 0.3.2.4, publisher to "Omar Aglan".

---

v0.3.2.5: SSA Construction 🔄

Strategy (Canonical SSA / الطريقة القياسية لـ SSA):

  • Mem2Reg (ترقية الذاكرة إلى سجلات) بأسلوب Cytron/LLVM القياسي:

    • حساب المسيطرات (Dominators) و حدود السيطرة (Dominance Frontiers)
    • إدراج عقد فاي (Phi) عند نقاط الدمج (join points)
    • إعادة التسمية (SSA Renaming) لبناء تعريفات واصلة (reaching definitions)
  • هذا الأسلوب هو الأساس طويل المدى لتحسينات متقدمة لاحقاً مثل: GVN/CSE و LICM و PRE وغيرها.

v0.3.2.5.1: Memory to Register Promotion ✅ COMPLETED (2026-02-09)

  • Identify promotable allocas — Single-block allocas with no escaping (correctness-first baseline; design stays compatible with full Mem2Reg).
  • Replace loads/stores — Convert to direct register use.
  • Remove dead allocas — Delete promoted حجز instructions.

v0.3.2.5.2: Phi Node Insertion ✅ COMPLETED (2026-02-09)

  • Compute dominance frontiers — Where Phi nodes are needed.
  • Insert Phi placeholders — Add فاي at join points.
  • Rename variables — SSA renaming pass with reaching definitions.
  • Connect Phi operands — Link values from predecessor blocks.

v0.3.2.5.3: SSA Validation ✅ COMPLETED (2026-02-09)

  • Verify SSA properties — Each register defined exactly once.
  • Check dominance — Definition dominates all uses.
  • Validate Phi nodes — One operand per predecessor.
  • --verify-ssa flag — Debug option to run SSA checks.

---

v0.3.2.6: IR Stabilization & Polish 🧹

v0.3.2.6.0: Codebase Soldering (مرحلة_تلحيم_القاعدة) ✅ COMPLETED (2026-02-09)

  • Enable compiler warnings (two-tier) — Default warnings on; optional -Werror hardening toggle.
  • Fix unsafe string building in driver — Replace sprintf/strcpy/strcat command construction with bounded appends and overflow checks.
  • Fix symbol-table name overflow — Guard Symbol.name\[32] writes; reject/diagnose identifiers that exceed the limit.
  • Harden updater version parsing — Support multi-part versions like 0.3.2.5.3; replace sprintf with snprintf; check parse results.
  • Audit strncpy usage — Ensure explicit NUL-termination and bounds safety in lexer and helpers.
  • Replace atoi with checked parsing — Use strtoll + validation for integer literals and array sizes; produce safe diagnostics.
  • Warning clean build — Zero warnings under default warning set; -Werror build passes.

v0.3.2.6.1: IR Memory Management

✅ COMPLETED (2026-02-11)

  • Arena allocator for IR — Fast allocation, bulk deallocation.
  • IR cloning — Deep copy of functions/blocks.
  • IR destruction — Clean up all IR memory.
  • Def-use chains for SSA regs — Build and maintain use lists to make IR passes fast and safe (avoid whole-function rescans).
  • Instruction numbering / stable IDs — Deterministic per-function instruction IDs for analyses, debugging, and regression tests.
  • IR mutation helpers — Central utilities to insert/remove instructions and update CFG metadata (pred/succ/dominance caches) consistently.

v0.3.2.6.2: Debug Information

✅ COMPLETED (2026-02-11)

  • Source location tracking — Map IR instructions to source lines.
  • Variable name preservation — Keep original names for debugging.
  • --debug-info flag — Emit debug metadata in assembly.

v0.3.2.6.3: IR Serialization

✅ COMPLETED (2026-02-11)

  • Text IR writer — Output canonical IR text format.
  • Text IR reader — Parse IR text back to data structures.
  • Round-trip testing — Write → Read → Compare.

v0.3.2.6.4: Register Allocator Liveness Fix (إصلاح حيوية مخصص السجلات)

✅ COMPLETED (2026-02-12)

  • Fix liveness across loop back-edges — Linear scan liveness analysis does not correctly propagate live ranges across loop back-edges when many variables are simultaneously live, causing register clobbering and segfaults.
  • Extend live intervals to loop ends — Ensure variables used inside loops have their intervals extended to cover the entire loop body including back-edges.
  • Add block-level scoping in semantic analyzer — Currently function-level only; for-loop variables cannot be redeclared in the same function, requiring unique names.
  • Stress test with high register pressure — Validate fix with functions containing 8+ live variables across multiple nested loops.

v0.3.2.6.5: IR Verification & Canonicalization (تحقق_الـIR_وتوحيده)

✅ COMPLETED (2026-02-13)

  • IR well-formedness verifier (--verify-ir) — Validate operand counts, type consistency, terminator rules, phi placement, and call signatures (separate from --verify-ssa).
  • Verifier gate in optimizer (debug) — Optional mode to run --verify-ir/--verify-ssa after each pass iteration to catch pass bugs early.
  • Canonicalization pass — Normalize commutative operands, constant placement, and comparison canonical forms to make CSE/DCE/constfold more effective.
  • CFG simplification pass — Merge trivial blocks, remove redundant branches, and provide a reusable critical-edge splitting utility for IR passes.

v0.3.2.6.6: IR Semantics & Data Layout (دلالات_الـIR_وتخطيط_البيانات)

  • Define IR arithmetic semantics — Document and enforce overflow behavior (recommended: two’s-complement wrap), and clarify i1 truthiness and div/mod rules for negatives.
  • Data layout helpers — Add size/alignment queries per IRType (incl. pointer size) as the foundation for future Target abstraction and correct aggregate lowering.
  • Memory model contract — Specify and verify rules for حجز/حمل/خزن (typed pointers, aliasing assumptions, and what is/ isn’t legal for optimization).

v0.3.2.6.7: SSA Verification Fix in Switch (إصلاح التحقق من SSA في جملة اختر)

✅ COMPLETED (2026-02-14)

  • Fix SSA verification failure — Resolved dominance issue in CSE pass for switch statements with default cases.

---

v0.3.2.7: Advanced Optimizations 🚀

v0.3.2.7.1: Loop Optimizations

✅ COMPLETED (2026-02-16)

  • Loop detection — Identify natural loops via back edges.
  • Loop invariant code motion — Hoist constant computations.
  • Strength reduction — Replace expensive ops (mul → shift).
  • Loop unrolling — Optional with -funroll-loops.

v0.3.2.7.2: Inlining

✅ COMPLETED (2026-02-16)

  • Inline heuristics — Small functions, single call site.
  • Inline expansion — Copy function body to call site.
  • Post-inline cleanup — Re-run optimization passes.

v0.3.2.7.3: Tail Call Optimization

✅ COMPLETED (2026-02-17)

  • Detect tail callscall immediately followed by ret (بدون تعليمات بينهما).
  • Convert to jump — Replace call+ret with a tail jump (no new return address).
  • Stack reuse — Reuse caller's stack frame + caller shadow space (Windows x64 ABI).
  • Limitation (for v0.3.2.7.3) — initial implementation supports only <= 4 arguments (register args); stack-args tail calls are scheduled in v0.3.2.8.5.

---

v0.3.2.8: Multi-Target Preparation 🌐

v0.3.2.8.1: Target Abstraction

✅ COMPLETED (2026-02-17)

  • Define Target interface — OS/object-format, data layout, calling convention, asm directives.
  • x86-64 Windows target — Keep current behavior as the first concrete target.
  • Host default target — Windows host defaults to x86\_64-windows, Linux host defaults to x86\_64-linux.
  • Target selection--target=x86\_64-windows|x86\_64-linux flag.

v0.3.2.8.2: Calling Convention Abstraction

✅ COMPLETED (2026-02-17)

  • Define CallingConv struct — arg regs order/count, return regs, caller/callee-saved masks.
  • Stack rules — stack alignment + varargs rules are modeled; stack-arg placement is deferred (backend rejects stack args for now).
  • Windows x64 ABI — RCX/RDX/R8/R9 + 32-byte shadow/home space.
  • SystemV AMD64 ABI — RDI/RSI/RDX/RCX/R8/R9, no shadow space, sets AL=0 for calls (conservative).

v0.3.2.8.3: Code Model Options

✅ COMPLETED (2026-02-17)

  • Small code model — Default (only supported model in v0.3.2.8.3).
  • PIC/PIE flags-fPIC/-fPIE (Linux/ELF; initial support).
  • Stack protection — stack canaries on ELF via -fstack-protector\*.

v0.3.2.8.4: Linux x86-64 Target 🐧

✅ COMPLETED (2026-02-17)

  • Native Linux build of compiler — build baa on Linux with GCC/Clang + CMake.
  • SystemV AMD64 ABI implementation — different calling convention from Windows.
  • ELF output support.rodata/.data/.text directives compatible with ELF GAS.
  • Link with host gcc (for now) — produce ELF executables via host toolchain; later reduce/remove GCC dependency.
  • Cross-compilation (later) — optional --target=x86\_64-linux from Windows once a cross toolchain story exists.

v0.3.2.8.5: Windows x64 Stack Args + Full Tail Calls

✅ COMPLETED (2026-02-17)

  • Proper stack-arg calling — outgoing call frames support stack args on Windows x64 and SysV AMD64.
  • Tail calls beyond reg-args — enable TCO with stack args conservatively (requires enough incoming stack-arg area).
  • Varargs home space (Windows) — home/register args are written into shadow space before calls.

v0.3.2.8.6: Aggressive IR & Optimizations (GCC/MSVC-like)

✅ COMPLETED (2026-02-17)

Goal: move toward compiler-grade IR optimizations in pragmatic steps.

  • InstCombine — local simplification patterns (canonical COPY rewrites).
  • SCCP — sparse conditional constant propagation + br\_cond folding.
  • GVN — dominator-scoped global value numbering for pure expressions.
  • Mem2Reg promotability unlock — must-def initialization analysis (instead of “init store must be in alloca block”).
  • Pipeline wiring — run InstCombine+SCCP early; GVN at -O2 before CSE.

---

v0.3.2.9: IR Verification & Benchmarking ✅

v0.3.2.9.1: Comprehensive IR Verification ✅ COMPLETED (2026-02-17)

  • Well-formedness checks — All functions have entry blocks.
  • Type consistency — Operand types match instruction requirements.
  • CFG integrity — All branches point to valid blocks.
  • SSA verification — Run --verify-ssa on all test programs.
  • baa --verify mode — Run all verification passes.

v0.3.2.9.2: Performance Benchmarking ✅ COMPLETED (2026-02-17)

  • Compile-time benchmark — Compare compiler-only (-S) and end-to-end compile wall time.
  • Runtime benchmark — Run deterministic bench/runtime\_\*.baa programs.
  • Memory usage profiling — Track peak RSS on Linux via /usr/bin/time -v and IR arena stats via --time-phases.
  • Benchmark suite — Collection of representative programs (bench/\*.baa).

v0.3.2.9.3: Regression Testing ✅ COMPLETED (2026-02-17)

  • Output comparison — Compare IR-based output against a reference corpus.
  • Test all v0.2.x programs — Ensure backward compatibility.
  • Edge case testing — Complex control flow, nested loops, recursion.
  • Error case testing — Verify error messages unchanged.

v0.3.2.9.4: Documentation & Cleanup

  • Update INTERNALS.md — Document new IR pipeline.
  • IR Developer Guide — How to add new IR instructions.
  • Driver split — Extract CLI parsing, toolchain execution, and per-file compile pipeline into dedicated src/driver\_\*.c/.h modules.
  • Driver link safety — Remove fixed-size argv\_link construction; build link argv dynamically based on object count.
  • Shared file reader — Provide read\_file() as a shared module (src/read\_file.c) for the lexer include system.
  • Line ending normalization — Add .gitattributes to keep the repo LF-normalized and reduce diff churn.
  • Remove deprecated code — Remove legacy AST-based codegen paths and backend-compare mode.
  • Code review checklist — Ensure code quality standards.

---

📚 Phase 3.5: Language Completeness (v0.3.3 - v0.3.12)

Goal: Add essential features to make Baa practical for real-world programs and suitable for future staged bootstrap experiments, without making self-hosting part of the current release path.

v0.3.3: Array Initialization 📊 ✅ COMPLETED (2026-02-18)

Goal: Enable direct initialization of arrays with values.

Features

  • Array Literal Syntax – Initialize arrays with comma-separated values using { } (supports partial init + zero-fill like C).

Syntax:

صحيح قائمة\[٥] = {١، ٢، ٣، ٤، ٥}.

// With Arabic comma (،) or regular comma (,)
صحيح أرقام\[٣] = {١٠، ٢٠، ٣٠}.

Implementation Tasks

  • Parser: Handle { } initializer list after array declaration.
  • Parser: Support both Arabic comma ، (U+060C) and regular comma , as separators.
  • Semantic Analysis: Allow partial init (count <= size) and zero-fill the remainder; reject overflow.
  • Codegen: Emit .data initializers for globals and runtime stores for locals (including zero-fill).

Deferred to v0.3.9

  • Multi-dimensional arrays: صحيح مصفوفة\[٣]\[٤]. ✅ COMPLETED (2026-02-25)
  • Array length operator: صحيح طول = حجم(قائمة) / حجم(صحيح). ✅ COMPLETED (2026-02-25)

---

v0.3.4: Enumerations & Structures 🏗️ ✅ COMPLETED (2026-02-18)

Goal: Add compound types for better code organization and type safety.

Features

  • Enum Declaration – Named integer constants with type safety.
  • Struct Declaration – Group related data into composite types (supports nested structs + enum fields).
  • Member Access – Use : (colon) operator for accessing members.

v0.3.4.5: Union Types (الاتحادات) 🔀 ✅ COMPLETED (2026-02-19)

Goal: Memory-efficient variant types for parsers and data structures.

Features

  • Union Declaration:
  اتحاد قيمة {
      صحيح رقم.
      نص نص\_قيمة.
      منطقي منطق.
  }
  • Union Usage:
  اتحاد قيمة ق.
  ق:رقم = ٤٢.        // All members share same memory
  ق:نص\_قيمة = "مرحبا". // Overwrites previous value
  • Tagged Union Pattern (manual):
  تعداد نوع\_قيمة { رقم، نص\_ق }
   
  هيكل قيمة\_موسومة {
      تعداد نوع\_قيمة نوع.
      اتحاد قيمة بيانات.
  }

Implementation Tasks

  • Token: Add TOKEN\_UNION for اتحاد keyword.
  • Parser: Parse union declaration similar to struct.
  • Semantic: All members start at offset 0.
  • Memory Layout: Size = max member size, align = max member align.
  • Codegen: Generate union storage + member access code.

Complete Example:

// ١. تعريف التعداد (Enumeration)
تعداد لون {
    أحمر،
    أزرق،
    أسود،
    أبيض
}

// ٢. تعريف الهيكل (Structure)
هيكل سيارة {
    نص موديل.
    صحيح سنة\_الصنع.
    تعداد لون لون\_السيارة.
}

صحيح الرئيسية() {
    هيكل سيارة س.
    
    س:موديل = "تويوتا كورولا".
    س:سنة\_الصنع = ٢٠٢٤.
    س:لون\_السيارة = لون:أحمر.
    
    اطبع س:موديل.
    اطبع س:سنة\_الصنع.
    
    إذا (س:لون\_السيارة == لون:أحمر) {
        اطبع "تحذير: السيارات الحمراء سريعة!".
    }
    
    إرجع ٠.
}

Implementation Tasks

Enumerations:

  • Token: Add TOKEN\_ENUM for تعداد keyword.
  • Parser: Parse enum declaration: تعداد <name> { <members> }.
  • Parser: Support Arabic comma ، between enum members.
  • Semantic: Auto-assign integer values (0, 1, 2...).
  • Semantic: Enum values accessible via <enum\_name>:<value\_name>.
  • Type System: Add TYPE\_ENUM to DataType.

Structures:

  • Token: Add TOKEN\_STRUCT for هيكل keyword.
  • Token: Add TOKEN\_COLON for : (already exists, verify usage).
  • Parser: Parse struct declaration: هيكل <name> { <fields> }.
  • Parser: Parse struct instantiation: هيكل <name> <var>.
  • Parser: Parse member access: <var>:<member>.
  • Semantic: Track struct definitions in symbol table.
  • Semantic: Validate member access against struct definition.
  • Memory Layout: Calculate field offsets with padding/alignment (supports nested structs).
  • Codegen: Emit struct storage + member access code.

---

v0.3.5: Character Type 📝 (يشمل تقديم عشري)

Goal: Add a proper character type with UTF-8 source support.

ملاحظة: نوع عشري قُدِّم في v0.3.5 كثوابت/تخزين، واكتمل في v0.3.5.5 (عمليات + ABI).

Features

  • Character Type (حرف) – Unicode scalar value stored as packed UTF-8 bytes plus length in a scalar.
  • String-Char Relationship – Strings (نص) are represented as arrays of حرف (حرف\[]) with indexing (اسم\[٠]).
  • Float Type (عشري)Deferred from v0.3.4.5 (introduced as a basic type + literals in v0.3.5; completed in v0.3.5.5 with ops/ABI).

Syntax:

حرف ح = 'أ'.
نص اسم = "أحمد".  // Equivalent to: حرف اسم\[] = {'أ', 'ح', 'م', 'د', '\\0'}.

Implementation Tasks

  • Token: Already have TOKEN\_CHAR for literals.
  • Token: Add TOKEN\_KEYWORD\_CHAR for حرف type keyword.
  • Type System: Add TYPE\_CHAR to DataType enum.
  • Semantic: Distinguish between char and int.
  • Codegen: Store حرف as packed i64 (bytes + length) and support UTF-8 printing.
  • String Representation: Update internal string handling to use حرف\[].

Deferred to v0.3.9

  • String operations: طول\_نص(), دمج\_نص(), قارن\_نص()

v0.3.5.5: Numeric Types (Sized Integers + عشري) ✅ COMPLETED (2026-02-24)

Goal: Make numeric types practical for systems programming: sized integers + usable عشري (f64).

Features

  • Sized Integer Types:
  ص٨ بايت\_موقع = -١٢٨.        // int8\_t:  -128 to 127
  ص١٦ قصير = -٣٢٠٠٠.          // int16\_t: -32768 to 32767
  ص٣٢ عادي = -٢٠٠٠٠٠٠٠٠٠.     // int32\_t
  ص٦٤ طويل = ٩٠٠٠٠٠٠٠٠٠٠٠٠.   // int64\_t (current صحيح)

  ط٨ بايت = ٢٥٥.               // uint8\_t
  ط١٦ قصير٢ = ٦٥٠٠٠.            // uint16\_t
  ط٣٢ عادي٢ = ٤٠٠٠٠٠٠٠٠٠.       // uint32\_t
  ط٦٤ طويل٢ = ١٨٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠. // uint64\_t
  • C-like semantics:

    • integer promotions + usual arithmetic conversions
    • correct signed/unsigned comparisons
    • correct div/mod semantics for signed vs unsigned
  • عشري usability:

    • arithmetic + - \* /
    • comparisons == != < > <= >=
    • اطبع supports عشري
    • ABI lowering on SysV AMD64 + Windows x64 (XMM regs + SysV varargs rules)

Implementation Tasks

  • Lexer: Tokenize ص٨, ص١٦, ص٣٢, ص٦٤, ط٨, ط١٦, ط٣٢, ط٦٤.
  • Type System: Add size and signedness to integer types.
  • IR: Add unsigned variants and allow f64 ops + verifier updates.
  • Optimizer: Ensure integer/float correctness (avoid invalid float folds; unsigned-aware folds).
  • ISel/Emitter: Generate correct-sized integer ops and scalar SSE2 for f64.
  • ABI (Windows + SystemV): Pass/return عشري in XMM registers; handle SysV varargs rules.
  • Semantic: Warn on implicit narrowing conversions.
  • Semantic: Handle signed/unsigned comparison warnings.

---

v0.3.6: Low-Level Operations 🔧 ✅ COMPLETED (2026-02-24)

Goal: Add bitwise operations and low-level features needed for systems programming.

Features

  • Bitwise Operators:
  صحيح أ = ٥ \& ٣.      // AND: 5 \& 3 = 1
  صحيح ب = ٥ | ٣.      // OR:  5 | 3 = 7
  صحيح ج = ٥ ^ ٣.      // XOR: 5 ^ 3 = 6
  صحيح د = \~٥.         // NOT: \~5 = -6
  صحيح هـ = ١ << ٤.    // Left shift:  1 << 4 = 16
  صحيح و = ١٦ >> ٢.    // Right shift: 16 >> 2 = 4
  • Sizeof Operator:
  صحيح حجم\_صحيح = حجم(صحيح).    // Returns 8
  صحيح حجم\_حرف = حجم(حرف).      // Returns 1
  صحيح حجم\_مصفوفة = حجم(قائمة). // Returns array size in bytes
  • Void Type:
  عدم اطبع\_رسالة() {
      اطبع "مرحباً".
      // No return needed
  }
  • Escape Sequences:
  نص سطر = "سطر١\\س سطر٢".     // Newline (/س)
  نص جدول = "عمود١\\ت عمود٢".  // Tab (/ت)
  نص مسار = "C:\\\\ملفات".     // Backslash
  حرف صفر = '\\٠'.            // Null character

Implementation Tasks

  • Lexer: Tokenize \&, |, ^, \~, <<, >>.
  • Parser: Add bitwise operators with correct precedence.
  • Parser: Parse حجم(type) and حجم(expr) expressions.
  • Lexer: Add عدم keyword for void type.
  • Lexer: Handle escape sequences in string/char literals.
  • Semantic: Type check bitwise operations (integers only).
  • Codegen: Generate bitwise assembly instructions.
  • Codegen: Calculate sizes for حجم operator.

v0.3.6.5: Type Aliases (أسماء الأنواع البديلة) 🏷️ ✅ COMPLETED (2026-02-23)

Goal: Create custom type names for readability and abstraction.

Features

  • Simple Type Alias:
  نوع معرف = ط٦٤.
  نوع نتيجة = ص٣٢.
  
  معرف رقم\_المستخدم = ١٢٣٤٥.
  نتيجة كود\_خطأ = -١.
  • Pointer Type Alias:
  نوع نص\_ثابت = ثابت حرف\*.
  نوع مؤشر\_بايت = ط٨\*.

(Deferred — requires pointer type grammar from v0.3.10.)

Implementation Tasks

  • Token/AST plumbing: Added TOKEN\_TYPE\_ALIAS/NODE\_TYPE\_ALIAS support in shared structures.

  • Parser: Parse نوع <name> = <type>. at top-level with C-like declare-before-use semantics.

  • Semantic: Resolve aliases during type checking and validate alias targets (enum/struct/union).

  • Symbol Table: Store type aliases separately and enforce strict name-collision diagnostics.

    ---

    v0.3.7: System Improvements 🔧 ✅ COMPLETED (2026-02-25)

    Goal: Refine and enhance existing compiler systems.

    Focus Areas

  • Error Messages – Improve clarity and helpfulness of diagnostic messages.

  • Code Quality – Refactor complex functions, improve code organization.

  • Memory Management – Fix memory leaks, improve buffer handling.

  • Performance – Profile and optimize slow compilation paths.

  • Documentation – Update all docs to reflect v0.3.3-0.3.7 changes.

  • Edge Cases – Fix known bugs and handle corner cases.

    Specific Improvements

  • Improve panic mode recovery in parser.

  • Better handling of UTF-8 edge cases in lexer.

  • Optimize symbol table lookups (consider hash table).

  • Add more comprehensive error recovery.

  • Improve assembly output readability (comments in assembly).

    v0.3.7.5: Static Local Variables (متغيرات ساكنة محلية) ✅ COMPLETED (2026-02-25)

    Goal: Variables that persist between function calls.

    Features

  • Static Local Syntax:

    صحيح عداد() {
        ساكن صحيح ع = ٠.  // Initialized once, persists
        ع = ع + ١.
        إرجع ع.
    }
    
    // First call returns 1, second returns 2, etc.
    

    Implementation Tasks

  • Token: Add TOKEN\_STATIC for ساكن keyword.

  • Semantic: Static locals go in .data section, not stack.

  • Codegen: Generate unique global label for static locals.

  • Codegen: Initialize in .data section.

    ---

    v0.3.8: Testing & Quality Assurance ✅ COMPLETED (2026-02-25)

    Goal: Establish robust testing infrastructure and fix accumulated issues.

    Test System

  • Test Framework – Create automated test runner.

    • Script to compile and run .baa test files.
    • Compare actual output vs expected output.
    • Report pass/fail with clear diagnostics.
  • Test Categories:

    • Lexer Tests – Token generation, UTF-8 handling, preprocessor.
    • Parser Tests – Syntax validation, error recovery.
    • Semantic Tests – Type checking, scope validation.
    • Codegen Tests – Correct assembly output, execution results.
    • Integration Tests – Full programs with expected output.
  • Test Coverage:

    • All language features (v0.0.1 - v0.3.7).
    • Edge cases and corner cases.
    • Error conditions (syntax errors, type mismatches, etc.).
    • Multi-file compilation scenarios.
    • Preprocessor directive combinations.

    CI/CD Setup

  • GitHub Actions workflow:

    name: Baa CI
    on: \[push, pull\_request]
    jobs:
      build-and-test:
        runs-on: windows-latest
        steps:
          - uses: actions/checkout@v3
          - name: Build Baa
            run: gcc src/\*.c -o baa.exe
          - name: Run Tests
            run: ./run\_tests.bat

    Bug Fixes & Refinements

  • Known Issues – Fix all open bugs from previous versions.

  • Regression Testing – Ensure new features don't break old code.

  • Stress Testing – Test with large files, deep nesting, many symbols.

  • Arabic Text Edge Cases – Test various Arabic Unicode scenarios.

    ---

    v0.3.9: Advanced Arrays & String Operations 📐 ✅ COMPLETED (2026-02-25)

    Goal: Complete array and string functionality.

    Array Features

  • Multi-dimensional Arrays ✅ COMPLETED (2026-02-25):

    صحيح مصفوفة\[٣]\[٤].
    مصفوفة\[٠]\[٠] = ١٠.
    مصفوفة\[١]\[٢] = ٢٠.
    
  • Array Length Operator ✅ COMPLETED (2026-02-25):

    صحيح قائمة\[١٠].
    صحيح الطول = حجم(قائمة) / حجم(صحيح).  // Returns 10
    
  • Array Bounds Checking (Optional runtime mode) ✅ COMPLETED (2026-02-25; flag contract stabilized 2026-05-05):

    • Runtime checks in explicit -fruntime-checks lowering mode.
    • Deterministic exit(1) path on out-of-bounds access.

    String Operations

  • String Length ✅ COMPLETED (2026-02-25): صحيح الطول = طول\_نص(اسم).

  • String Concatenation ✅ COMPLETED (2026-02-25): نص كامل = دمج\_نص(اسم, " علي").

  • String Comparison ✅ COMPLETED (2026-02-25): صحيح نتيجة = قارن\_نص(اسم, "محمد").

  • String Indexing (read-only) ✅ COMPLETED (2026-02-25): حرف أول = اسم\[٠].

  • String Copy ✅ COMPLETED (2026-02-25): نص نسخة = نسخ\_نص(اسم).

    Implementation

  • Parser: Parse multi-dimensional array declarations and access.

  • Semantic: Track array dimensions in symbol table.

  • Codegen: Calculate offsets for multi-dimensional arrays (row-major order).

  • Standard Library: Create baalib.baa with string functions.

  • UTF-8 Aware: Ensure functions handle multi-byte Arabic characters correctly.

    ---

    v0.3.10: Pointers & References 🎯

    Goal: Add pointer types for manual memory management and data structures.

    Features

  • Pointer Type Declaration ✅ COMPLETED (2026-02-25):

    صحيح\* مؤشر.           // Pointer to integer
    حرف\* نص\_مؤشر.         // Pointer to character (C-string)
    هيكل سيارة\* س\_مؤشر.   // Pointer to struct
    
  • Address-of Operator (\&) ✅ COMPLETED (2026-02-25):

    صحيح س = ١٠.
    صحيح\* م = \&س.         // م points to س
    
  • Dereference Operator (\*) ✅ COMPLETED (2026-02-25):

    صحيح قيمة = \*م.       // قيمة = 10
    \*م = ٢٠.              // س now equals 20
    
  • Null Pointer ✅ COMPLETED (2026-02-25):

    صحيح\* م = عدم.        // Null pointer
    إذا (م == عدم) {
        اطبع "مؤشر فارغ".
    }
    
  • Pointer Arithmetic ✅ COMPLETED (2026-02-25):

    صحيح قائمة\[٥] = {١، ٢، ٣، ٤، ٥}.
    صحيح\* م = \&قائمة\[٠].
    م = م + ١.             // Points to قائمة\[١]
    اطبع \*م.               // Prints 2
    

    Implementation Tasks

  • Lexer/Parser integration: Handle \* في سياق النوع/فك الإشارة والضرب و\& كـ bitwise/address-of.

  • Parser: Parse pointer declarations + عدم كمؤشر فارغ + جملة \*ptr = value..

  • Type System: Add TYPE\_POINTER with base type tracking in AST/symbol metadata.

  • Semantic: Validate pointer operations (dereference/address-of/null/pointer compare/arithmetic).

  • Codegen: Lower address-of/dereference/pointer assignment and pointer arithmetic safely.

    v0.3.10.5: Type Casting (تحويل الأنواع) 🔄 ✅ COMPLETED (2026-02-27)

    Goal: Explicit type conversions for low-level programming.

    Features

  • Cast Syntax:

    صحيح س = ٦٥.
    حرف ح = كـ<حرف>(س).
    
  • Numeric Casts:

    ص٣٢ صغير = كـ<ص٣٢>(قيمة\_كبيرة).  // Truncation
    ص٦٤ كبير = كـ<ص٦٤>(قيمة\_صغيرة).  // Sign extension
    ط٦٤ بدون = كـ<ط٦٤>(موقع).        // Signed to unsigned
    
  • Pointer Casts:

    ط٨\* بايتات = كـ<ط٨\*>(مؤشر\_هيكل).  // Reinterpret
    عدم\* عام = كـ<عدم\*>(أي\_مؤشر).     // To void pointer
    هيكل س\* محدد = كـ<هيكل س\*>(عام). // From void pointer
    
  • Pointer Difference (pointer - pointer):

    صحيح\* أ = \&قائمة\[٠].
    صحيح\* ب = أ + ٣.
    صحيح فرق = ب - أ. // = 3 (فرق عناصر)
    

    Implementation Tasks

  • Lexer: Tokenize كـ keyword and <> for type parameter.

  • Parser: Parse كـ<type>(expr) form.

  • Semantic: Validate cast safety, warn on dangerous casts.

  • Codegen: Generate appropriate conversion instructions.

    v0.3.10.6: Function Pointers (مؤشرات الدوال) 📍

    Goal: First-class function references for callbacks and dispatch tables.

    Features

  • Function Pointer Type:

    // Pointer to function taking two صحيح, returning صحيح
    نوع دالة\_ثنائية = دالة(صحيح، صحيح) -> صحيح.
    
    // Or inline
    دالة(صحيح، صحيح) -> صحيح مؤشر\_دالة.
    
  • Assign Function to Pointer:

    صحيح جمع(صحيح أ، صحيح ب) { إرجع أ + ب. }
    صحيح ضرب(صحيح أ، صحيح ب) { إرجع أ \* ب. }
    
    دالة\_ثنائية عملية = جمع.   // Points to جمع
    عملية = ضرب.               // Now points to ضرب
    
  • Call Through Pointer:

    صحيح نتيجة = عملية(١٠، ٢٠).  // Calls ضرب(10, 20) = 200
    
  • Function Pointer as Parameter:

    صحيح طبق(صحيح\[] قائمة، صحيح حجم، دالة\_ثنائية د) {
        صحيح نتيجة = قائمة\[٠].
        لكل (صحيح ع = ١؛ ع < حجم؛ ع++) {
            نتيجة = د(نتيجة، قائمة\[ع]).
        }
        إرجع نتيجة.
    }
    
    // Usage
    صحيح مجموع = طبق(أرقام، ١٠، جمع).
    
  • Null Function Pointer:

    دالة\_ثنائية فارغ = عدم.
    إذا (فارغ != عدم) {
        فارغ(١، ٢).
    }
    

    Implementation Tasks

  • Parser: Parse function type syntax دالة(...) -> نوع.

  • Type System: Add function pointer type with signature plumbing.

  • Semantic: Type-check function pointer assignments.

  • Semantic: Validate call through pointer matches signature.

  • Codegen: Generate indirect call instructions.

  • IR: Add function pointer type to IR.

    ✅ COMPLETED (2026-02-28)

    ---

    v0.3.11: Dynamic Memory 🧠

    Goal: Enable heap allocation for dynamic data structures.

    Features

  • Memory Allocation:

    // Allocate memory for 10 integers
    صحيح\* قائمة = حجز\_ذاكرة(١٠ \* حجم(صحيح)).
    
    // Allocate memory for a struct
    هيكل سيارة\* س = حجز\_ذاكرة(حجم(هيكل سيارة)).
    
  • Memory Deallocation:

    تحرير\_ذاكرة(قائمة).
    تحرير\_ذاكرة(س).
    
  • Memory Reallocation:

    // Resize array to 20 integers
    قائمة = إعادة\_حجز(قائمة, ٢٠ \* حجم(صحيح)).
    
  • Memory Operations:

    // Copy memory
    نسخ\_ذاكرة(وجهة, مصدر, حجم).
    
    // Set memory to value
    تعيين\_ذاكرة(مؤشر, ٠, حجم).
    

    Implementation Tasks

  • Runtime: ربط مباشر مع libc (malloc/free/realloc/memcpy/memset).

  • Built-in Functions: إضافة حجز\_ذاكرة, تحرير\_ذاكرة, إعادة\_حجز, نسخ\_ذاكرة, تعيين\_ذاكرة.

  • Semantic: دعم عدم\* (void*) كـ مؤشّر عام (تحويلات ضمنية مع مؤشرات الكائنات).

  • Codegen: خفض الدوال إلى استدعاءات C القياسية مع قواعد shadowing.

    ✅ COMPLETED (2026-03-01)

    ---

    v0.3.12: File I/O 📁

    Goal: Enable reading and writing files for systems programs and future staged bootstrap experiments.

    Features

  • File Opening:

    عدم\* ملف = فتح\_ملف("بيانات.txt", "قراءة").
    عدم\* ملف\_كتابة = فتح\_ملف("ناتج.txt", "كتابة").
    عدم\* ملف\_إضافة = فتح\_ملف("سجل.txt", "إضافة").
    
  • File Reading:

    حرف حرف\_واحد = اقرأ\_حرف(ملف).
    نص سطر = اقرأ\_سطر(ملف).
    صحيح بايتات = اقرأ\_ملف(ملف, مخزن, حجم).
    
  • File Writing:

    اكتب\_حرف(ملف, 'أ').
    اكتب\_سطر(ملف, "مرحباً").
    اكتب\_ملف(ملف, بيانات, حجم).
    
  • File Closing:

    اغلق\_ملف(ملف).
    
  • File Status:

    منطقي انتهى = نهاية\_ملف(ملف).
    صحيح موقع = موقع\_ملف(ملف).
    اذهب\_لموقع(ملف, ٠).
    

    Implementation Tasks

  • Runtime: Wrap C stdio functions (fopen, fread, fwrite, fclose, fgetc, fputc, fputs, feof, ftello/fseeko).

  • Built-in Functions: Add file operation functions using عدم\* as an opaque FILE\* handle.

  • Error Handling: Return error codes for failed operations (فتح\_ملف يعيد عدم، و اكتب\_سطر/اكتب\_حرف تعيد -1 عند الفشل).

  • Codegen: Generate direct libc stdio calls with shadowing rules.

    ✅ COMPLETED (2026-03-02)

    v0.3.12.5: Command Line Arguments (معاملات سطر الأوامر) 🖥️

    Goal: Access program arguments for general programs and future staged bootstrap experiments.

    Features

  • Main with Arguments:

    صحيح الرئيسية(صحيح عدد، نص\[] معاملات) {
        // عدد = argument count (like argc)
        // معاملات = argument array (like argv)
        
        إذا (عدد < ٢) {
            اطبع "الاستخدام: برنامج <ملف>".
            إرجع ١.
        }
        
        نص اسم\_البرنامج = معاملات\[٠].
        نص ملف\_إدخال = معاملات\[١].
        
        اطبع "تجميع: ".
        اطبع ملف\_إدخال.
        
        إرجع ٠.
    }
    

    Implementation Tasks

  • Parser: Allow parameters in الرئيسية function.

  • Semantic: Validate main signature matches expected pattern.

  • Codegen: Link with proper C runtime entry point.

  • Codegen (Opt-in): --startup=custom — custom entrypoint symbol (\_\_baa\_start) while keeping CRT/libc init.

  • Codegen (Full Independence): True \_start without CRT/libc (deferred to Phase 8).

    ✅ COMPLETED (2026-03-02)

    ---

    📚 Phase 4: Standard Library & Polish (v0.4.x)

    Goal: Make Baa production-ready with a comprehensive standard library.

    v0.4.0: Formatted Output & Input 🖨️

    Goal: Professional I/O capabilities.

  • Formatted Output:

    اطبع\_منسق("الاسم: %ن، العمر: %ص\\س", اسم, عمر).
    
  • String Formatting:

    نص رسالة = نسق("النتيجة: %ص", قيمة).
    حرر\_نص(رسالة).
    
  • Formatted Input:

    نص سطر = اقرأ\_سطر().
    صحيح رقم = اقرأ\_رقم().
    
    صحيح أ = ٠.
    عشري ب = ٠.
    نص س = عدم.
    
    // ملاحظة: في الإدخال، %ن يتطلب عرضاً رقمياً (مثلاً %10ن).
    صحيح مقروء = اقرأ\_منسق("%ص %ع %10ن", \&أ, \&ب, \&س).
    إذا (مقروء == 3) { حرر\_نص(س). }
    

    ✅ COMPLETED (2026-03-02)

    v0.4.0.5: Variadic Functions (دوال متغيرة المعاملات) ✅

    Goal: Functions accepting variable number of arguments.

    Features

  • Variadic Declaration:

    عدم اطبع\_منسق(نص تنسيق، ...) {
        // Implementation using variadic access
    }
    
  • Variadic Access Macros/Functions:

    عدم اطبع\_أرقام(صحيح عدد، ...) {
        قائمة\_معاملات معاملات.
        بدء\_معاملات(معاملات، عدد).
        
        لكل (صحيح ع = ٠؛ ع < عدد؛ ع++) {
            صحيح قيمة = معامل\_تالي(معاملات، صحيح).
            اطبع قيمة.
        }
        
        نهاية\_معاملات(معاملات).
    }
    
    // Usage
    اطبع\_أرقام(٣، ١٠، ٢٠، ٣٠).
    

    Implementation Tasks

  • Lexer: Tokenize ... (ellipsis).

  • Parser: Parse variadic function declarations (including دالة(...)->... signatures).

  • Type System: Handle variadic function types and variadic call arity/type checks.

  • Codegen (Windows x64): Variadic calls lowered عبر وسيط داخلي موحد (\_\_baa\_va\_base) متوافق مع مسار الباك-إند الحالي.

  • Codegen (Linux x64): نفس وسيط المعاملات الداخلي لضمان سلوك موحد على x86\_64-linux.

  • Built-ins: Implement بدء\_معاملات, معامل\_تالي, نهاية\_معاملات.

    ✅ COMPLETED (2026-03-02)

    v0.4.0.6: Inline Assembly (المجمع المدمج) ✅

    Goal: Embed assembly code for low-level operations.

    Features

  • Basic Inline Assembly:

    مجمع {
        "nop"
    }
    
  • With Outputs and Inputs:

    صحيح قراءة\_عداد() {
        ط٣٢ منخفض.
        ط٣٢ مرتفع.
        مجمع {
            "rdtsc"
            : "=a" (منخفض)، "=d" (مرتفع)
        }
        إرجع (كـ<ص٦٤>(مرتفع) << ٣٢) | كـ<ص٦٤>(منخفض).
    }
    

    Implementation Tasks

  • Token: Add TOKEN\_ASM for مجمع keyword.

  • Parser: Parse inline assembly blocks.

  • Codegen: Emit assembly directly with proper constraints.

  • Semantic: Validate constraint syntax.

    ✅ COMPLETED (2026-03-02)

    Deferred to v3.0

  • Full constraint support (memory, register classes)

  • Clobber lists

    
    

v0.4.1: Standard Library (مكتبة باء) 📚

v0.4.1: Standard Library (مكتبة باء) 📚

  • Math Moduleجذر\_تربيعي(), أس(), مطلق(), عشوائي().

  • String Module — Complete string manipulation.

  • IO Module — File and console operations.

  • System Module — Environment variables, command execution.

  • Time Module — Date/time operations.

    ✅ COMPLETED (2026-03-02)

    v0.4.2: Floating Point Extensions ✅

    Goal: Extend floating point beyond the core عشري (completed in v0.3.5.5).

  • Math functionsجذر\_تربيعي(), أس(), جيب(), جيب\_تمام(), ظل().

  • Formatting — better float printing options (precision + scientific ).

  • Additional float typesعشري٣٢ keyword (current lowering alias to عشري/f64 in v0.4.2).

    ✅ COMPLETED (2026-03-02)

    v0.4.3: Error Handling 🛡️

    Goal: Graceful error management.

  • Assertions:

    تأكد(س > ٠, "س يجب أن يكون موجباً").
    
  • Error Codes – Standardized error return values.

  • Panic Functionتوقف\_فوري("رسالة خطأ").

    ✅ COMPLETED (2026-03-02)

    v0.4.4: Final Polish 🎨

  • Complete Documentation — All features documented.

  • Tutorial Series — Step-by-step learning materials.

  • Example Programs — Comprehensive example collection.

  • Performance Optimization — Profile and optimize compiler.

    ✅ COMPLETED (2026-03-02)

    🧱 Phase 4.5: Reference Compiler Stabilization (v0.5.x)

    Goal: Keep the C implementation as the official reference compiler, stabilize the language/toolchain contracts, and defer self-hosting to a future staged effort after the language has matured.

    v0.5.0: File & Component Organization 🗂️

  • Define canonical component boundaries — Frontend / Middle-End / Backend / Driver / Support.

  • Set module-size policy — target <= 700 lines/file, hard cap 1000 lines for hand-written C modules.

  • Split oversized modules firstanalysis.c, emit.c, ir.c, ir\_lower.c, ir\_text.c, isel.c, lexer.c, parser.c, regalloc.c, and ir\_verify\_ir.c are now under the hard cap via companion implementation splits.

  • Restructure source layout safely — component directories now exist under src/, and the build now targets those files directly.

  • Add local module facadesfrontend\_internal.h, middleend\_internal.h, backend\_internal.h, driver\_internal.h, and support\_internal.h now define component-local include surfaces.

  • Update build graphCMakeLists.txt remains explicit/deterministic and the Windows build uses C-only include propagation while header wrappers remain transitional.

  • Add size-regression guardscripts/check\_module\_sizes.py enforces warn 700 / error 1000 and runs in qa\_run.py + CI before full QA.

  • Document ownership mapdocs/COMPONENT\_OWNERSHIP.md defines module responsibilities + dependency rules.

    ✅ COMPLETED (2026-03-06)

    Partial status update (2026-03-06):

  • policy/guard/documentation are in place for v0.5.0,

  • all remaining hard-cap hotspots were split below the 1000-line limit,

  • scripts/module\_size\_allowlist.txt is now empty,

  • source files were reorganized under src/frontend, src/middleend, src/backend, src/driver, and src/support,

  • CMakeLists.txt now builds directly from component sources, while root-level compatibility is limited to selected header wrappers during header migration.

    v0.5.1: Language + ABI Freeze 🔒

  • Freeze grammar surface — avoid syntax churn before bootstrap.

  • Freeze stdlib signatures — lock callable contracts used by compiler-in-Baa.

  • Freeze target ABI contracts — Windows x64 + SystemV AMD64 invariants.

  • Freeze IR invariants — verifier-enforced guarantees documented.

    ✅ COMPLETED (2026-04-28)

    v0.5.2: Module & Multi-File Hardening 📦

  • Deterministic include/import resolution — include resolution now canonicalizes successful paths before they become active lexer filenames, so equivalent relative spellings collapse to a single resolved path.

  • Cycle diagnostics#تضمين cycles are now rejected early with Arabic diagnostics that print the include chain instead of recursing until depth exhaustion.

  • Symbol visibility rules — top-level functions keep external linkage by default, top-level ساكن globals/arrays keep file-local internal linkage, and multi-file QA now locks this contract with dedicated smoke coverage.

  • Header/API hygienebaa.h is now a compatibility umbrella only; shared declarations were split into component-owned public headers under src/frontend/ and src/support/, diagnostics no longer depend on frontend lexer headers, and the middle-end now consumes a small shared target contract instead of touching backend target layout directly.

    v0.5.3: Build System Maturity ⚙️

  • Incremental compilation model — avoid full rebuilds on small edits.

  • Dependency tracking — reliable invalidation for headers/includes.

  • Reproducible outputs — stable artifacts for same inputs/toolchain.

  • Build profile presets — dev/debug/release/verify presets.

    ✅ COMPLETED (2026-04-28)

    v0.5.4: Diagnostics & Recovery Quality 🩺

  • Improve span accuracy — tighter line/column ranges.

  • Add actionable fix hints — Arabic-first suggestions for common errors.

  • Strengthen panic recovery — fewer cascading diagnostics.

  • Negative test expansion — enforce diagnostic contracts.

    ✅ COMPLETED (2026-05-01)

    v0.5.5: Runtime Safety Layer 🛡️

  • Assertion runtime contract — stable behavior in debug/release modes.

  • Panic/error-code policy — consistent fatal/non-fatal paths.

  • Safety toggles — explicit compile-time/runtime control flags.

  • Document failure semantics — deterministic exit/status behavior.

    ✅ COMPLETED (2026-05-05)

    v0.5.6: Determinism & QA Gates ✅

  • Cross-target parity suite — Linux/Windows behavior consistency.

  • Fuzz + stress expansion — parser/semantic/IR robustness.

  • IR/SSA regression locking — snapshots + verifier gating.

  • Release gate checklist — mandatory pass criteria before Phase 5.

    ✅ COMPLETED (2026-05-09)

    Future Baa0 Bootstrap Subset Definition 📐 — DEFERRED UNTIL AFTER v0.9

    These items are future planning work, not Phase 4.5 release gates. They must not add a Baa-built compiler dependency to the mainline build.

  • Define minimal future subset — features that could later support compiler slices in Baa without depending on unstable language behavior.

  • Ban unstable features in Baa0 — keep any future bootstrap surface conservative and deterministic.

  • Publish Baa0 compliance suite — tests for subset guarantees, but not a production migration gate yet.

  • Document migration policy — C remains the reference compiler; Baa rewrites stay experimental until post-v0.9 staged gates.

    v0.5.8: Reference Compiler Reset 🧭

    Goal: Stop broad compiler migration work and re-anchor the project around a stable C reference compiler.

  • Declare the C compiler as the reference implementationdocs/BOOTSTRAP_CONTRACT.md defines the root CMake target as the official implementation.

  • Move C→Baa migration work to an experimental branchorigin/moving-to-baa preserves the Baa lexer/parser and bootstrap wiring outside the release path.

  • Remove misleading bootstrap assumptions from the main build — the C-only build has no bootstrap input, and scripts/check\_reference\_compiler\_policy.py prevents regressions.

  • Audit migration artifactsdocs/MIGRATION\_ARTIFACT\_AUDIT.md records branch contents and the keep/defer/re-evaluate disposition.

  • Write self-hosting policy notedocs/BOOTSTRAP_CONTRACT.md keeps future work staged, parity-tested, rollback-ready, and outside the v0.9 release path.

  • Update roadmap language — current milestones use future staged bootstrap readiness rather than active rewrite framing.

    ✅ COMPLETED (2026-06-29)

    v0.5.9: Reference Compiler Release Candidate ✅

    Goal: Produce a clean, reproducible, cross-platform baseline before new v0.6.x language work.

  • Windows full QA signoff — strict v0.5.9 C build plus quick 7/7, full 22/22, stress 52/52, and release 53/53 passed in Actions run 28384736088.

  • Linux full QA signoff — strict v0.5.9 C build plus quick 7/7, full 22/22, stress 52/52, and release 53/53 passed in Actions run 28384736088.

  • Reproducible build check — Windows/Linux determinism receipts passed 14/14, including stable version/build-date and manifest bytes/shape.

  • Determinism gate — Windows/Linux receipts lock raw/optimized IR, assembly, diagnostics, manifests, verifier behavior, and snapshots.

  • Known limitations pagedocs/KNOWN\_LIMITATIONS.md lists unsupported targets, language/type restrictions, safety boundaries, and draft-only tooling surfaces.

  • Release branch disciplinedocs/RELEASE\_PROCESS.md limits post-cut work to focused fixes, tests, release gates, metadata, and documentation; both platform prerequisites are green.

    Reproducibility coverage update (2026-06-29): the release gate now compares repeated --version output (including the configured build date) and negative diagnostic text/exit status in addition to IR, assembly, manifests, verifier behavior, and snapshots. Final Windows and Linux receipts are green.

    RC gate reliability update (2026-06-29): compiler discovery now emits a structured compiler-preflight result, including missing/invalid compiler paths in summary JSON instead of aborting before a release receipt is written.

    Cross-platform receipt update (2026-06-29): the manual Baa Release Candidate workflow performs strict Windows/Linux C-reference builds, runs all four QA modes, and uploads both platform receipt sets.

    Version audit update (2026-06-29): authoritative compiler/package/documentation metadata now reports 0.5.9, guarded by scripts/check\_version\_sync.py. The Windows ladder was rebuilt and rerun on the corrected baseline; earlier 0.5.6 receipts remain test history only.

    ✅ COMPLETED (2026-06-29) — final cross-platform run 28384736088 on fef76ca.

    Phase 4.5 Exit Criteria

  • C-reference build is simple — clean checkout builds from C/RC inputs only, with the policy checked in every QA mode.

  • Cross-target QA green — all four QA modes pass on both x86\_64-windows and x86\_64-linux.

  • Determinism checks green — stable IR text and stable diagnostics for identical inputs.

  • File-size governance active — CI guard for module-size budget is enforced.

  • Contracts frozen and publisheddocs/CONTRACT\_FREEZE\_V0\_5.md indexes the versioned v0.5.9 language, stdlib, hosted ABI, and IR baselines and explicitly excludes draft tooling contracts.

  • Future bootstrap policy published — self-hosting is explicitly deferred until after v0.9 stabilization.

    ✅ PHASE 4.5 EXIT CRITERIA SATISFIED (2026-06-29)

    Phase 4.5 Required Artifacts

  • docs/COMPONENT\_OWNERSHIP.md — boundaries + owners + allowed dependencies.

  • docs/BOOTSTRAP\_CONTRACT.md — frozen ABI/IR/language requirements and future bootstrap policy.

  • docs/MIGRATION\_ARTIFACT\_AUDIT.md — experimental-branch inventory and mainline disposition.

  • docs/CONTRACT\_FREEZE\_V0\_5.md — authoritative v0.5.9 core contract publication index.

    Future optional artifacts (not Phase 4.5 gates):

  • docs/BAA0\_SPEC.md — post-v0.9 bootstrap subset definition and exclusions.

  • tests/bootstrap/ — post-v0.9 parity corpus for staged migration experiments.

    ---

    🧭 Ecosystem Ownership Boundaries

    Goal: Keep the Baa repository focused on the compiler, language, ABI, diagnostics, stdlib contracts, and release-quality gates while sibling projects own their own product areas.

  • Takween owns the Arabic-first project build workflow for Baa projects (تكوين تهيئة/بناء/تشغيل/تنظيف). Baa should expose stable compiler flags, manifest formats, include rules, and diagnostics for Takween to consume; Baa should not duplicate Takween as an internal baa build system.

  • Qalam-IDE owns the editor/IDE experience for Arabic-syntax systems languages starting with Baa. Baa should expose stable parser/check/diagnostic surfaces that Qalam can call; Baa should not duplicate Qalam as an internal IDE or editor extension roadmap.

  • Baa owns the compiler core, language specification, standard-library contracts, runtime checks, diagnostics, target ABI behavior, tests, and release artifacts.

    ---

    🧱 Phase 6: Language Usability & Safety (v0.6.x)

    Goal: Make Baa more practical as an Arabic-first systems language without expanding into external build-system or IDE ownership.

    v0.6.0: Systems Language Completeness I 🧱

  • خارجي declarations — explicit external function, scalar-global, and fixed-array declarations are supported in headers and multi-file builds.

  • Global declaration vs definition rules — matching declarations merge with one definition; conflicting types/shapes and duplicate definitions are rejected.

  • Struct field initialization — basic named-field initialization for automatic local هيكل values; static/global aggregate initializers remain deferred.

  • Aggregate assignment policy — whole-aggregate copy assignment is explicitly rejected for variables, members, array elements, and dereferenced aggregate pointers with field-update guidance.

  • Const pointer rulesثابت T* freezes the pointer variable, pointer-to-const types remain unsupported, and taking a mutable pointer to a ثابت object is rejected.

  • Better null-pointer diagnostics — direct dereference of the null literal عدم is rejected with an explicit Arabic diagnostic; broader flow-sensitive null analysis remains deferred.

    v0.6.1: Arabic Diagnostics II 🩺

  • Diagnostic codes — text diagnostics now include stable family identifiers such as B0001, B1000, and warning-specific B110x codes.

  • Multi-line spans — diagnostic spans can cover multiple source lines, with semantic binary-expression errors using the wider range when operands cross lines.

  • Fix-it hints — parser expected-token diagnostics suggest missing ., ؛, and delimiters; semantic assignment type mismatches now suggest matching the value type or using explicit conversion.

  • Diagnostic categories — text diagnostics derive category labels such as syntax, semantic, include, backend, runtime, warning, and internal from stable code families.

  • --explain <CODE> — built-in Arabic explanations for the stable text diagnostic families and current warning codes.

  • Negative diagnostic expansion — representative syntax, semantic, warning, null, hint, and multi-line-span negatives now lock diagnostic counts and selected cascade guards.

    v0.6.2: Standard Library Core 📦

  • Dynamic array/vector APIمتجه provides create/free/length/capacity/data/push/pop helpers for fixed-size element patterns, with byte-copy storage and explicit ownership notes.

  • Byte buffer APIمخزن_بايتات provides create/free/length/capacity/data plus byte append for compiler/tooling-style buffers.

  • Path APIضم_مسار/مجلد_مسار/اسم_ملف_مسار/امتداد_مسار/طبع_مسار provide owned-string lexical path helpers for join, dirname, basename, extension, and separator normalization.

  • String builderباني_نص provides owned incremental text construction with append, clear, length, snapshot, and explicit free helpers.

  • Result/error helpersنتيجة_ناجحة/نتيجة_فاشلة/كود_نتيجة document and bridge the stdlib منطقي success and integer status-code conventions.

  • Ownership documentationdocs/STDLIB_OWNERSHIP.md indexes owned results, borrowed pointers, and release helpers for public stdlib APIs.

    v0.6.3: Runtime Safety Guards 🛡️

  • Null pointer checks-fruntime-checks now emits optional traps before lowered pointer dereferences and *p = value, printing فشل_مؤشر_فارغ before exit(1).

  • Division-by-zero checks-fruntime-checks now emits optional traps before lowered integer division/modulo, printing فشل_قسمة_على_صفر before exit(1).

  • Shift-width checks-fruntime-checks now emits optional traps before lowered shifts when the dynamic count is outside 0..63, printing فشل_إزاحة_غير_صالحة before exit(1).

  • Expanded bounds checks-fruntime-checks now covers static-shape arrays plus نص[i] and inner نص[] character indexes, printing فهرس خارج حدود النص for text bounds failures.

  • Readable panic format — fail-fast runtime paths now print الموقع: file:line:col | الدالة: name between the Arabic failure marker and message.

  • Selective safety flags-fruntime-checks=<list> now accepts all, bounds, null, div-zero/div0/div, shift, and none with comma or plus separators.

    v0.6.4: UTF-8/Text Correctness 📝

  • Clarify حرف representationحرف is documented as one packed Unicode scalar value, not a raw byte or grapheme cluster.

  • String indexing policyنص\[index] is documented as returning the indexed packed حرف/Unicode scalar value, not raw bytes or user-perceived graphemes.

  • UTF-8 validation tests — focused coverage now checks valid UTF-8 identifiers/literals/includes plus malformed identifier, string, char, and included-file diagnostics.

  • Arabic numeral normalization tests — source-token parsing, diagnostic snippets, and --dump-ir Arabic numeral output are covered by focused tests.

  • Text stdlib helpers — safe length/copy/compare behavior is documented and covered for empty text, prefix comparison, bad calls, and owned-copy lifetime.

  • Known Unicode limitations — docs now explicitly disclaim normalization and grapheme-cluster-aware behavior.

    v0.6.5: Documentation Lock 📚

  • Update Baa Book to current scope — stale v0.3.10.6 scope text, warning-flag wording, and example-review baseline were refreshed for current v0.6.x behavior.

  • Verified example suitetests/test_examples.py compiles every public examples/*.baa program in QA with -O2 --verify.

  • Exercises with expected output — Baa Book now includes beginner, intermediate, and systems-level exercises with exact output blocks.

  • Terminology glossary — one preferred Arabic term per core compiler/language concept is recorded in docs/TERMINOLOGY_GLOSSARY.md.

  • Native Arabic technical review — language quality pass by Arabic-speaking engineers.

  • Docs version sync gate — QA now rejects canonical docs whose top-level version header drifts from the CMake project version.

    ---

    🧪 Phase 7: Compiler Testing & Integration Surfaces (v0.7.x)

    Goal: Strengthen Baa’s compiler-facing surfaces for Takween, Qalam-IDE, and future tooling without owning those external products inside this repository.

#### Required integration artifacts

  • docs/ECOSYSTEM\\\_BOUNDARIES.md — ownership rules between Baa, Takween, Qalam-IDE, and PyramidOS, covered by tests/test_integration_artifacts.py.

  • docs/COMPATIBILITY\\\_MATRIX.md — version compatibility table for compiler/tooling contracts, covered by tests/test_integration_artifacts.py.

  • docs/TOOLING\\\_CONTRACTS.md — stable CLI, manifest, exit-code, and machine-readable output contracts, covered by tests/test_integration_artifacts.py.

  • docs/DIAGNOSTICS\\\_JSON\\\_SCHEMA.md — stable diagnostics JSON schema for Takween/Qalam, covered by tests/test_integration_artifacts.py.

  • docs/TARGET\\\_SPECIFICATION.md — target descriptor model for hosted and future freestanding targets, now covered by tests/test_target_specs.py.

  • docs/CONFORMANCE\\\_SUITE.md — language, ABI, stdlib, diagnostics, and target conformance plan, covered by tests/test_integration_artifacts.py.

  • docs/SDK\\\_RELEASE\\\_PLAN.md — future Baa SDK bundle/versioning plan, covered by tests/test_integration_artifacts.py.

  • targets/x86\\\_64-linux.json and targets/x86\\\_64-windows.json — first hosted target descriptors, validated in QA.

    [x] targets/i386-elf.experimental.json and targets/i386-pyramidos.experimental.json — planning descriptors only, not supported targets yet; QA keeps them experimental/freestanding.

    v0.7.0: Takween Integration Contract 🏗️

  • Structured process runtime — hosted Baa tools can launch direct argv with explicit cwd/environment/stdout/stderr, poll/wait/cancel, and collect exit status without shell text.

  • Hosted filesystem bridge — UTF-8 file opening plus guarded recursive mkdir/remove let Takween initialize and clean projects consistently on Windows and Linux.

  • Stable compiler invocation contractdocs/TOOLING_CONTRACTS.md documents the flags Takween may rely on for check/compile/link/object/assembly workflows.

  • Manifest compatibilitydocs/TOOLING_CONTRACTS.md records deterministic fields Takween can consume from --emit-build-manifest.

  • Include/dependency contract — canonical manifest dependencies and invalidation expectations are documented and covered by tests/test_integration_artifacts.py.

  • Exit-code contract — stable compiler exit statuses for build tools are implemented, documented in docs/TOOLING_CONTRACTS.md, and covered by cross-platform QA.

  • Machine-readable diagnostics plandocs/DIAGNOSTICS_JSON_SCHEMA.md defines the future JSON diagnostics shape for Takween/Qalam.

  • No internal Baa project build system — Baa keeps baa build/baa run/baa clean out of compiler-cli-v1; Takween owns Arabic-first project workflow UX.

  • Stable target discovery--target-info=json emits target-info-v1 with the host/selected targets, executable suffix, object format, and host-sensitive capabilities; focused runtime tests cover default and explicit target queries.

    v0.7.1: Module and Visibility Cleanup 🧩

  • Header/source conventiondocs/MODULES_AND_VISIBILITY.md formalizes .baahd vs .baa usage and is covered by tests/test_module_visibility_docs.py.

  • Visibility modifiers — current public/default, خارجي, and ساكن rules for functions and globals are documented and guarded.

  • Include-cycle diagnostics — cycle-chain diagnostics now include an Arabic help hint and focused negative-test coverage.

  • One-definition checks — multi-file link builds now reject duplicate exported function/global definitions before linker fallback diagnostics.

  • Header self-check mode--check-header parses and semantically checks header declarations without emitting code.

  • Migration guidedocs/MODULES_AND_VISIBILITY.md records the path from raw multi-file builds to Takween-managed builds.

    v0.7.2: Qalam-IDE Integration Contract ✍️

  • Fast check mode--check parses and semantically checks sources without IR/codegen/toolchain output for editor feedback.

  • Machine-readable diagnostics--diagnostics=json emits diagnostics-json-v1 with file, line, column, span, code, severity, category, hints, and compiler-owned safe structured fixes for missing delimiters.

  • Token dump mode--dump-tokens=json emits tokens-json-v1 from the compiler-owned raw source scanner for saved or unsaved UTF-8 buffers, preserving comments, directives, literals, and exact byte spans while tolerating incomplete editor syntax.

  • Structural editing ranges--dump-structure=json emits deterministic structure-json-v1 folding and selection candidates from the same tolerant raw scanner, excludes delimiter text inside comments and literals, and preserves partial ranges for incomplete editor buffers.

  • Symbol outline mode--dump-symbols=json emits symbols-json-v1 for functions, parameters, globals, arrays, structs, unions, enums, fields, enum members, and type aliases with exact UTF-8 byte spans.

  • Completion metadata export — keywords, builtins, included declarations, visible locals, and snippets in stable compiler-owned formats.

    • completion-data-json-v1 exports lexer-owned keywords, directives, literals, primitive types, Arabic snippets, and canonical compiler builtin signatures through --completion-data=json.
    • semantic-query-json-v1 exports cursor-visible parameters, locals, globals, types, and explicitly included header declarations with lexical shadowing and future/sibling exclusion.
  • Cursor semantic query--semantic-query=json --position-byte=N emits semantic-query-json-v1 with scope-correct hover declarations, active call signatures, exact definitions, and translation-unit references for saved or unsaved source, including included prototypes, shadowed locals, and temporary typing errors.

  • Translation-unit semantic index--semantic-index=json emits compiler-bound structured identities and definition/declaration/reference occurrences so project-aware tools can fan out without identifier text matching. Identifier kinds distinguish functions, variables, parameters, fields, enum members, arrays, constants, and type declarations for compiler-owned editor coloring as well as navigation.

  • Stable Windows editor paths — semantic query/index output preserves the exact --source-stdin logical root while resolved include and dependency paths expand 8.3 aliases to long Unicode paths.

  • Canonical source formatting--format=json emits idempotent format-json-v1 for saved or unsaved UTF-8 buffers, preserves comments and literals, tolerates incomplete editing states, and keeps formatting policy in Baa rather than the IDE or LSP adapter.

  • No internal Baa IDE roadmapdocs/ECOSYSTEM_BOUNDARIES.md keeps Qalam-facing Baa work limited to compiler/data contracts while Qalam-IDE owns editor UI/UX.

    v0.7.3: Compiler Testing II 🧪

  • Coverage reporting — CI coverage for C compiler core.

  • Fuzz targets — lexer, parser, IR reader, include resolver.

  • Differential tests — compare -O0 vs -O2 runtime output.

  • Crash minimization workflow — reduce failing fuzz cases into committed regressions.

  • Backend stress tests — stack args, calls, structs, arrays, floats, and pointer-heavy programs.

  • Release dashboard — summarize pass/fail, coverage, fuzz corpus size, and determinism checks.

    ---

    🎯 Phase 8: Backend, Optimizer, and Performance Reliability (v0.8.x)

    Goal: Improve generated-code trustworthiness and prevent silent regressions before the v0.9 beta freeze.

    v0.8.0: Backend Correctness Hardening 🎯

  • ABI test matrix — Windows x64 and SysV calls, returns, varargs, and stack args.

  • Struct/union layout tests — size, alignment, and field-offset expectations.

  • Floating-point ABI tests — parameters, returns, varargs edge cases.

  • Stack alignment verifier — static backend checks before emission.

  • Assembly golden tests — stable snippets for sensitive cases.

  • Cross-target -S release gate — both Windows and Linux assembly output.

    v0.8.1: Optimizer Reliability ⚙️

  • Pass pipeline documentation — exact O0/O1/O2 pass order.

  • Per-pass verifier gate — mandatory in CI debug mode.

  • Optimization remarks — report applied and missed optimizations.

  • Alias-analysis baseline — conservative, documented, test-backed.

  • Optimization stress corpus — loops, branches, calls, pointers, and aggregate-heavy cases.

  • No unsafe optimization without verifier coverage — correctness first.

    v0.8.2: Performance Budget 📊

  • Benchmark baselines — compile time, runtime, and memory.

  • Regression thresholds — fail CI on large slowdowns.

  • Phase timing JSON — machine-readable --time-phases output.

  • Memory budget tracking — IR arena, parser allocations, backend allocations.

  • Benchmark documentation — exact local reproduction commands.

  • Performance changelog entries — record meaningful wins and regressions.

    ---

    🚦 Phase 9: Stable Beta and Future Bootstrap Plan (v0.9.x)

    Goal: Freeze a serious pre-1.0 baseline and define a future staged self-hosting plan without executing a production compiler rewrite in this roadmap window.

    v0.9.0: Stable Beta Freeze 🧊

  • Language freeze candidate — syntax and semantics locked for 1.0 review.

  • Stdlib freeze candidate — ownership, errors, memory, text, file, and path APIs documented.

  • ABI freeze candidate — Windows/Linux behavior documented and tested.

  • Diagnostics freeze candidate — diagnostic IDs, spans, hints, and --explain behavior stable.

  • External tooling contracts freeze — Takween/Qalam-facing outputs remain stable through 1.0 review.

  • Full release QA — Windows + Linux quick/full/stress/release gates.

  • Book + spec sync — all docs updated to v0.9.0.

  • Stage-0 bootstrap plan only — define future self-hosting stages, rollback, and parity gates; do not make self-hosting the mainline compiler yet.

  • Freestanding OS-dev profile plan only — define the future i386-elf/i386-pyramidos path for PyramidOS experiments; do not move PyramidOS kernel core to Baa yet.

  • **Compatibility matrix freeze** — Baa/Takween/Qalam contract versions are listed and stable through 1.0 review.

  • **Conformance suite v1 seed** — syntax, semantics, diagnostics, stdlib, ABI, and target tests define the stable-beta behavior.

    ---

    🧬 Future OS Development Profile: Freestanding / PyramidOS Target (post-v0.9)

    Goal: Make Baa capable of compiling small freestanding objects for PyramidOS and OS-development experiments without pretending that the PyramidOS kernel can immediately move from C/Assembly to Baa.

    Scope Decision

  • Baa v0.9 is not an OS-dev-ready release by itself — v0.9 freezes the hosted language/toolchain baseline and only plans the freestanding path.

  • PyramidOS kernel core remains C + Assembly — bootloader, entry code, GDT/IDT/ISR, PMM/VMM, ATA, and panic paths stay in the current reference implementation until explicit gates pass.

  • Baa enters PyramidOS gradually — host tools first, then tiny mixed-link smoke objects, then userland, then carefully selected kernel leaf helpers.

  • No hidden hosted dependencies — freestanding Baa code must not silently call libc/CRT, file I/O, heap allocation, formatted I/O, or startup helpers.

  • Object/linker-script compatibility first — Baa must fit the PyramidOS linker script, section layout, symbols, and QEMU boot gate before any migration claim.

  • Rollback is mandatory — every Baa-in-PyramidOS experiment must be removable without breaking the C/Assembly kernel path.

    v0.10.0: Freestanding Profile Foundation 🧱

    Goal: Add a hosted-vs-freestanding compiler mode split.

  • --freestanding mode — compile with no hosted OS/runtime assumptions.

  • --no-stdlib mode — reject or disable stdlib calls unless explicitly provided by the target.

  • --kernel profile alias — convenience mode for freestanding, no-stdlib, object-only defaults.

  • Disable hosted builtins — no implicit lowering to libc/CRT for print, read, files, time, environment, or allocation.

  • Explicit runtime contract diagnostics — Arabic errors when hosted features are used in freestanding mode.

  • Arbitrary freestanding entry support — allow kernel/userland symbols other than the hosted Arabic الرئيسية_بدء contract.

  • Object-only release gate — freestanding mode initially produces assembly/object outputs only, not hosted executables.

    v0.10.1: i386-elf / i386-pyramidos Target 🎯

    Goal: Add the target shape needed by the current 32-bit PyramidOS kernel.

  • --target=i386-elf baseline — 32-bit x86 freestanding object/assembly output.

  • Optional --target=i386-pyramidos alias — PyramidOS-specific ABI/layout defaults once proven useful.

  • 32-bit data layout — pointer size, integer sizes, stack alignment, and aggregate layout documented and verified.

  • cdecl-style call ABI — stack arguments, return values, caller/callee-saved registers, and name decoration policy.

  • 32-bit instruction selection — lower Baa IR to i386-compatible machine instructions.

  • 32-bit register allocation — EAX/EBX/ECX/EDX/ESI/EDI/EBP/ESP constraints and spilling.

  • GAS/NASM compatibility decision — choose canonical emitted assembly syntax for PyramidOS builds.

  • Cross-toolchain integration — support i686-elf/i386-elf assembler flow where available, without requiring hosted GCC linkage.

    v0.10.2: Kernel-Safety Language Features 🛡️

    Goal: Add the minimum low-level controls required for kernel code.

  • Volatile memory access — explicit volatile load/store for MMIO and hardware registers.

  • Packed structs — stable layout controls for descriptor tables and hardware data structures.

  • Alignment attributes — align variables/types/sections for page tables, stacks, and hardware structures.

  • Custom section attributes — place symbols in .text, .rodata, .data, .bss, boot/kernel-specific sections.

  • Compile-time layout assertions — verify حجم, alignment, and field offsets for ABI-critical structures.

  • Inline assembly hardening — tested patterns for cli, sti, hlt, in, out, lgdt, lidt, and control-register access.

  • Interrupt-wrapper contract — keep ISR/IRQ wrappers in Assembly first; only add Baa interrupt ABI support after wrapper tests pass.

    v0.10.3: PyramidOS Mixed-Link Smoke Gate 🧪

    Goal: Prove one tiny Baa object can link into and boot inside PyramidOS without touching critical paths.

  • Leaf Baa function object — compile a tiny non-critical Baa function to an object file.

  • C-callable ABI test — call the Baa function from C diagnostic code and verify arguments/return value.

  • Linker script compatibility — place Baa sections correctly in the PyramidOS image.

  • Symbol map verification — confirm symbols appear at expected addresses in kernel.map.

  • QEMU boot smoke — boot PyramidOS and run a diagnostic command that exercises the Baa function.

  • No critical subsystem migration — bootloader, GDT/IDT/ISR, PMM/VMM, heap, ATA, and VFS remain C/Assembly in this milestone.

  • Rollback test — removing the Baa object restores the exact C/Assembly-only build behavior.

    v0.10.4: PyramidOS Userland Foundation 👤

    Goal: Prefer Baa first for PyramidOS userland once Ring 3/syscalls exist.

  • Userland target profile — compile small Ring 3 Baa programs for PyramidOS when the OS ABI exists.

  • Syscall wrapper declarations.baahd headers for stable PyramidOS syscalls.

  • Minimal no-stdlib runtime — startup + syscall exit/write path only.

  • Userland hello program — Baa program prints via PyramidOS syscall, not host libc.

  • Userland ABI tests — argument passing, return codes, stack alignment, and failure behavior.

  • Separation policy — userland Baa can advance faster than kernel Baa because it is less boot-critical.

    v0.10.5: Kernel Leaf-Helper Pilot 🌱

    Goal: Try Baa inside the kernel only where failure risk is low and rollback is trivial.

  • Allowed migration list — small pure helpers only: string length, small formatting helpers, table lookup, diagnostics formatting.

  • Forbidden migration list — no bootloader, entry, GDT/IDT/ISR, PMM/VMM, heap allocator, ATA/PIO, scheduler, or panic core.

  • C reference parity tests — compare Baa helper behavior against existing C helpers.

  • No heap by default — kernel Baa code must not allocate unless PyramidOS exposes an explicit allocator contract.

  • No implicit panics — freestanding failure behavior must be explicit and kernel-safe.

  • QEMU regression gate — every helper migration must pass boot + shell + diagnostic smoke tests.

  • Rollback branch discipline — each helper migration lands as an isolated, revertable change.

    OS Development Profile Exit Criteria

  • Freestanding mode is real — no hidden libc/CRT dependency for accepted freestanding programs.

  • i386 target is proven — assembly/object output matches PyramidOS target expectations.

  • Layout controls are tested — packed/aligned/section features are verified with compile-time and binary checks.

  • Mixed-link gate passes — PyramidOS boots in QEMU with one C-called Baa object.

  • Userland path is defined — Baa has a cleaner first real OS role outside the kernel core.

  • Kernel migration remains gated — no critical subsystem is moved without separate design review and rollback plan.

    ---

    Direct Unicode Windows Artifact Pipeline

    Goal: retire the Windows ASCII staging bridge while preserving real Arabic/Unicode artifacts even when the selected GCC cannot open Unicode argv paths. Preserve the real compile/assemble/link phases, remove redundant filesystem copies, and keep compatibility behavior explicit.

    Direct-pipeline admission sequence

  • Measured staging baseline — record assembly copy-in, object copy-out, link-input staging, runtime-archive staging, executable copy-out, tool execution, bytes copied, and multi-file amplification as separate metrics. The retired bridge cost 3N + 2 copies and excluded all copy I/O from phase timers; the exact byte formula is versioned in docs/WINDOWS_TOOLCHAIN_PATHS.md.

  • Windows toolchain capability matrix — prove Arabic assembly input, Arabic object output, Arabic object link input, Arabic executable output, Arabic-plus-space paths, long paths, multiple objects, UTF-8 response files, and the Arabic الرئيسية_بدء entry symbol with the selected GCC/assembler/linker. Native Unicode argv and UTF-8 GCC response paths fail with MSYS2 GCC 15.2; no-copy short aliases to the same real artifacts pass the full matrix.

  • Direct -S output — emit assembly to the requested output path without an ASCII temporary file or copy, because this mode invokes no external assembler.

  • Direct object destination — make the assembler write directly to the Baa/Takween-selected object or cache path. The selected GNU assembler cannot write an object to stdout, so Windows uses a no-copy alias to the real object.

  • Direct linking — pass the real object/runtime entities to GCC/LD and write the executable directly to the requested destination through the same no-copy path adapter.

  • Explicit incompatibility — an arbitrary toolchain that fails the Unicode capability contract returns a stable external-toolchain error; no silent normal-path staging fallback may hide the limitation. A missing filesystem alias is an explicit status-4 failure.

  • Remove staging implementation — delete the ASCII staging directory, copy-in/copy-out helpers, and redundant cleanup once direct mode is the admitted Windows path. Temporary artifact and linker-response names include the process identity to eliminate cross-process collisions.

  • Ecosystem gates — Arabic-path, spaces, a Windows path beyond 260 UTF-16 units, multi-file, concurrent-build, phase-timing, and determinism coverage passes in Baa CI 29685512987 and exact admission 29687846586; Takween cache/build/run/clean/test passes on Windows/Linux in 29689709002.

    Ordering: complete the current Nazm production-admission gate first, then land this direct artifact pipeline before Takween 0.4's content-addressed cache and workspace expansion, so Takween can select final object/cache destinations without Baa copying them through an internal staging tree.

    ---

    🔨 Future Toolchain Independence: Nazm Integration (post-v0.9)

    Goal: replace the external GAS/MASM assembly boundary with the independently tested Nazm assembler without duplicating its parser, encoder, or object writers inside Baa.

    Phase 6 Architecture Scope

  • Boundary contract — freeze baa-nazm-boundary-v0 ownership, text, target, diagnostics, and source-map behavior.

  • Coverage inventory — extract every instruction, operand, directive, section, symbol, and relocation form emitted by the Windows/Linux corpus.

  • Arabic emitter — emit canonical Nazm 0.4 text after register allocation while retaining inspectable -S output.

    • First executable slice: --emit-nazm emits an Arabic-only minimal integer entry for Windows/Linux targets and visibly rejects every unsupported form.
    • PC-relative global slice: scalar global loads/stores and function/global addresses emit [مؤشر_التعليمة+الرمز]; immediate stores lower through a scratch register and duplicate extern-plus-definition declarations emit one definition.
    • Memory arithmetic slice: imul accepts base/displacement memory sources and spilled setcc destinations emit the native Arabic memory form.
    • Scalar-decimal slice: all 16 XMM identities emit only as سجل_عشري_٠ through سجل_عشري_١٥; arithmetic, comparison, bit transport, and integer/decimal conversions assemble to ELF64 and COFF with no Latin source aliases.
    • Arabic fixture and spill-width slice: include-path fixtures use Arabic-only function identities, 32-bit PC-relative globals zero-extend through a 32-bit destination view, and spilled unary bitwise-NOT lowers through a spill-safe scratch register.
    • Conversion-configuration slice: --startup=custom remains a GAS -S presentation option and no longer blocks or duplicates canonical Nazm emission; stack protection retains its own stable blocker contract.
    • Debug-information slice: --debug-info emits Arabic-only .ملف_بايتات/.موضع directives, which Nazm lowers to DWARF v4 line tables in ELF64 and CodeView C13 line tables in COFF.
  • Shadow integration — invoke Nazm without changing the production GAS result and compare object/link/runtime semantics.

    • First executable slice: --nazm-shadow=<path> assembles and links a one-input minimal program beside GAS with visible no-fallback failures and host runtime parity coverage.
  • Guarded embeddingnazm-api-v1 freezes owned result/diagnostic lifetimes and OOM/error status; Baa can call nazm_assemble_buffer() only in an explicitly enabled build and only after --نظم-داخل-العملية, while the subprocess remains the production default.

    v1.5.0: Baa + Nazm Assembler Path 🔧

    v1.5.0.1: Inventory and Contract

  • Generated-form corpus — version baa-nazm-coverage-v1 from the full 100-source, two-target inventory and assemble focused ELF64/COFF fixtures for every currently supported form; partial and unsupported forms remain explicit.

  • Source-level shadow matrix — classify all 100 sources on both targets as Arabic-only emitted, visibly unsupported, or gate error; every rejection carries a stable Arabic blocker kind/detail. Structured architecture operations and target-specific debug line tables now admit all 100 sources on each target with zero unsupported rows and zero gate errors.

  • Source mappingbaa-nazm-source-map-v1 binds generated Nazm line ranges to the original UTF-8 Baa file/line/column, and shadow assembler failures replay the Nazm diagnostic plus its mapped Baa location on Windows/Linux.

  • Inline assembly migration contract — version the breaking move away from raw مجمع { ... } GAS text: common in-function operations become typed Arabic Baa intrinsics backed by Machine IR, while arbitrary assembly lives in first-class .نظم modules.

  • Inline assembly migration implementation — Nazm encodes اقرأ_عداد_الزمن; Baa exposes typed لا_تفعل() and اقرأ_عداد_الزمن() operations backed by structured IR/Machine IR and lowers them to GAS and canonical Arabic Nazm; Takween compiles mixed .baa/.نظم roots; raw مجمع now returns an Arabic source-migration error. A future inline نظم { ... } extension remains optional and must use explicit inputs/outputs/clobbers without embedding or translating GAS text.

  • Target contract — map Baa targets explicitly to Nazm ELF64/COFF modes.

    v1.5.0.2: Shadow and Parity

  • Opt-in shadow flag — assemble with Nazm beside the production GAS path.

  • Object comparison — compare sections, symbols, relocations, and normalized semantics rather than requiring incidental byte identity for every admitted source.

  • Linux PIC/PIE producer parity — default Nazm and explicit GAS compile the string/global/runtime-call fixture under -fPIC and -fPIE; normalized initialized/read-only sections, public symbols, and relocation presence agree, and the Nazm-default -fPIE path links an ET_DYN executable with identical runtime behavior in Baa CI run 29679921655.

  • Link/runtime comparison — link and run both outputs on Windows and Linux for every admitted source.

  • Arabic linker entry — preserve الرئيسية in Nazm ELF64/COFF objects and enter both hosted shadow targets through الرئيسية_بدء without a main alias or direct-function process entry.

  • Arabic production ABI — both assemblers emit الرئيسية unchanged, link through الرئيسية_بدء, and convert Windows UTF-16 argv through بدء_ويندوز without main/wmain aliases; Nazm is now the production default.

  • Arabic shadow startup ABI — Linux reuses the generated الرئيسية_بدء object and returns through __libc_start_main; Windows resolves the same strong Arabic entry through a linker-owned UTF-8 response file and dispatches to بدء_ويندوز.

  • Diagnostics comparison — unsupported forms remain visible Arabic failures.

  • No silent fallback — never substitute guessed bytes or hide unsupported Nazm input behind GAS.

    v1.5.0.3: Production Admission

  • Full gate — quick, full, stress, determinism, release, and cross-target suites pass through Nazm.

    • Windows release receipt — the complete 75-step release orchestrator passes with the 100-source normal/shadow gate and deterministic Nazm source/object/manifest receipt enabled.
    • Linux release receipt — exact Baa 661edd9... and Nazm 7236491... pass 75/75 release steps on hosted Linux in admission run 29687846586.
    • Exact-revision hosted ladder — the read-only Baa Nazm Production Admission workflow requires and verifies full Baa and Nazm commit SHAs, builds both projects, runs quick/full/stress/release on Windows/Linux with explicit BAA/NAZM bindings, and retains revision plus QA receipts.
  • Linker acceptance — real Windows and Linux linkers accept produced objects.

  • Normal assembler selection--assembler=nazm resolves the executable from --nazm-path, BAA_NAZM, or the primary Arabic نظم command on PATH, emits/assembles canonical Arabic source directly to the selected object, and passes it to the normal linker; --assembler=gas remains the explicit measured migration rollback with no silent fallback.

    • 100-source normal-path gate — every admitted host corpus source also builds through --assembler=nazm; runnable programs match the GAS result in exit status, stdout, and stderr on Windows and Linux in exact-SHA hosted CI.
    • Deterministic generated-source identity — keep process-unique physical .نظم intermediates for concurrency, but pass the stable Arabic باء-مولد.نظم identity to Nazm; repeated canonical source, object, and build-manifest outputs are byte-identical.
  • Mixed Baa/Nazm roots — direct .نظم roots bypass Baa parsing, assemble through the same resolved Nazm CLI, record per-unit source/assembler receipts, and join .baa objects in one hosted Arabic-ABI link; source/tool failures remain distinct and never fall back to GAS.

  • Default-on readiness — approved parity report and rollback procedure exist; Nazm is the production default and GAS is the explicit rollback.

    • Automated production admission — exact candidate revisions pass quick/full/stress/release on Windows and Linux with 27/27, 44/44, 74/74, and 75/75 receipts respectively.
    • Decision record approveddocs/NAZM_PRODUCTION_ADMISSION.md records Baa 661edd9..., Nazm 7236491..., Takween da8378e..., terminal runs 29685356936, 29685512987, 29687846586, 29689709002, the explicit GAS rollback drill, and all three owner approvals.
    • Default cutover — omitted assembler selection now chooses Nazm; --assembler=gas is the only normal rollback, and failures never trigger it automatically.
  • In-process equivalence — the Nazm CLI and nazm-api-v1 path produce byte-identical ELF64/COFF objects and matching primary failures; the exact API/version/capability fingerprint is recorded in manifests and cache keys before generated or direct Nazm objects are reused. Default in-process cutover remains a separate future admission decision.

    ---

    🔗 Future Toolchain Independence: Own Linker (post-v0.9)

    Goal: Remove dependency on external linker (ld/link.exe).

    Phase 7 Architecture Scope

  • Object ingestion layer — robust COFF/ELF readers with strict validation.

  • Link graph core — symbol table, section graph, relocation plan, address assignment.

  • Format writers — PE/ELF executable writers with deterministic layout rules.

  • Runtime bridge layer — controlled integration with CRT/system runtime requirements.

  • Verification layer — parity checks vs system linkers + deterministic output checks.

    Phase 7 Operating Rules

  • Deterministic link ordering — stable output independent of host filesystem ordering.

  • No silent symbol resolution — ambiguous/duplicate/undefined symbols must emit explicit diagnostics.

  • Relocation correctness first — overflow and invalid relocation types are hard failures.

  • Target isolation — Windows and Linux paths share abstractions, not target-specific hacks.

    v2.0.0: Baa Linker (رابط باء) 🔗

    v2.0.0.1: Linker Foundation

  • Parse object files — Read COFF/ELF format.

  • Symbol resolution — Match symbol references to definitions.

  • Section merging — Combine sections from multiple objects.

  • Memory layout — Assign virtual addresses to sections.

  • Archive scanning strategy — deterministic one-pass/two-pass policy for .a/.lib.

  • Input validation policy — reject malformed object metadata with Arabic diagnostics.

    v2.0.0.2: Relocation Processing

  • Apply relocations — Fix up addresses in code/data.

  • Handle relocation types — PC-relative, absolute, GOT, PLT.

  • Overflow detection — Check address range limits.

  • Relocation test matrix — per-target coverage for required relocation kinds.

  • Late-binding audit logs — debug trace mode for relocation decisions.

    v2.0.0.3: Executable Generation (Windows)

  • PE header — DOS stub, PE signature, file header.

  • Optional header — Entry point, section alignment, subsystem.

  • Section headers — .text, .data, .rdata, .bss.

  • Import table — For C runtime and Windows API.

  • Export table — If building DLLs (future).

  • Generate .exe — Complete Windows executable.

  • PE conformance checks — verify headers/alignments with tooling (dumpbin/llvm-readobj).

  • Subsystem policies — console/gui/custom-startup rules documented and tested.

    v2.0.0.4: Executable Generation (Linux)

  • ELF header — File identification, entry point.

  • Program headers — Loadable segments.

  • Section headers — .text, .data, .rodata, .bss.

  • Dynamic linking info — For libc linkage.

  • Generate executable — Complete Linux binary.

  • ELF conformance checks — validate segments/sections with readelf/objdump.

  • PIE/non-PIE policy — deterministic handling for code model and relocation mode.

    v2.0.0.5: Linker Features

  • Static libraries — Link .a/.lib archives.

  • Library search paths-L flag support.

  • Entry point selection — Custom entry point support.

  • Strip symbols — Remove debug symbols for release.

  • Map file — Generate link map for debugging.

  • Section GC plan — optional dead-section elimination with safety checks.

  • Weak symbol semantics — explicit target-specific behavior for weak/strong bindings.

    v2.0.0.6: Linker Integration

  • Replace ld/link calls — Use internal linker.

  • --use-internal-linker flag — Optional internal linker.

  • Verify output — Compare with system linker output.

  • End-to-end test — Compile and link without external tools.

  • Dual-link CI mode — run internal and system linker paths on same corpus.

  • Fallback policy — controlled fallback with reasoned diagnostics when unsupported.

    v2.0.0.7: Linker Release Gate

  • Cross-target parity signoff — runtime and symbol behavior match system linker expectations.

  • Determinism signoff — stable binary layout for identical inputs/toolchains.

  • Stress signoff — large multi-object links and archive-heavy workloads remain stable.

    Phase 7 Exit Criteria

  • Default-on readiness — internal linker can be default for supported targets.

  • Regression stability — quick/full/stress QA pass with internal linker enabled.

  • Debuggability baseline — diagnostics + map output sufficient for failure triage.

    ---

    🏆 Future Toolchain Independence: Full Independence (post-v0.9)

    Goal: Zero external dependencies — Baa builds itself with no external tools.

    Phase 8 Architecture Scope

  • Runtime kernel layer — startup, syscall/API bridge, memory primitives, and process exit flow.

  • Native stdlib layer — string/math/memory/io modules implemented in Baa with stable ABI contracts.

  • Bootstrap provenance layer — staged compiler lineage (baa0 -> baa1 -> baa2) with hashable artifacts.

  • Hermetic build layer — controlled inputs, pinned flags, deterministic packaging outputs.

  • Operational verification layer — dependency scans, runtime smoke tests, and cross-target release gates.

    Phase 8 Operating Rules

  • No hidden host dependencies — any required host tool must be explicitly listed in bootstrap docs.

  • Reproducibility-first policy — build determinism regressions block release.

  • Cross-target parity policy — Windows/Linux runtime features must ship together or stay gated.

  • Fail-fast runtime diagnostics — startup/syscall/runtime failures must emit explicit Arabic-first errors.

  • Recovery-path requirement — each independence milestone must define rollback and re-bootstrap steps.

    v3.0.0: Complete Toolchain 🛠️

    v3.0.0.1: Remove C Runtime Dependency

    Windows:

  • Direct Windows API calls — Replace printf with WriteConsoleA.

  • Implement اطبع natively — Direct syscall/API.

  • Implement اقرأ natively — ReadConsoleA.

  • Implement memory functions — HeapAlloc/HeapFree instead of malloc/free.

  • Implement file I/O — CreateFile, ReadFile, WriteFile.

  • Custom entry point — Replace C runtime startup.

  • SEH-aware startup — preserve stable crash/exit semantics without CRT helpers.

  • Win64 ABI compliance checks — stack alignment, shadow space, and return path verified.

    Linux:

  • Direct syscalls — write, read, mmap, exit.

  • Implement اطبع natively — syscall to write(1, ...).

  • Implement اقرأ natively — syscall to read(0, ...).

  • Implement memory functions — mmap/munmap for allocation.

  • Implement file I/O — open, read, write, close syscalls.

  • Custom _start — No libc dependency.

  • Syscall ABI validation — register/stack contracts verified on x86_64 SystemV.

  • Signal/exit behavior checks — deterministic termination semantics across test corpus.

    v3.0.0.2: Native Standard Library

  • Rewrite string functions in Baa — No C dependency.

  • Rewrite math functions in Baa — Pure Baa implementation.

  • Rewrite memory functions in Baa — Custom allocator.

  • Full standard library in Baa — All library code in Baa.

  • Module boundary contracts — document stable APIs for core, memory, string, math, io.

  • Behavioral parity suite — compare stdlib behavior vs prior runtime expectations.

  • Allocator policy gates — fragmentation/throughput baselines for long-running workloads.

    v3.0.0.3: Self-Contained Build

  • Single binary compiler — No external dependencies.

  • Cross-compilation support — Build Linux binary on Windows and vice versa.

  • Reproducible builds — Same source → identical binary.

  • Bootstrap from source — Document minimal bootstrap path.

  • Hermetic manifest — lock source inputs, flags, and artifact metadata per release.

  • Stage replay tooling — deterministic scripts to replay bootstrap on clean machines.

  • Provenance hashing — publish hashes for each stage artifact and final binaries.

    v3.0.0.4: Verification & Release

  • Full test suite passes — All tests without external tools.

  • Benchmark comparison — Performance vs GCC toolchain.

  • Security audit — Review for vulnerabilities.

  • Documentation complete — Full toolchain documentation.

  • Release v3.0.0 — Fully independent Baa! 🎉

  • Supply-chain audit — verify release pipeline does not reintroduce external tool reliance.

  • Disaster-recovery drill — validate clean-room bootstrap from tagged sources.

    v3.0.0.5: Independence Release Gate

  • Zero-dependency signoff — compile/assemble/link/run path requires only Baa-delivered artifacts.

  • Deterministic bootstrap signoff — repeated stage builds are byte-stable per target.

  • Cross-target signoff — Windows + Linux release candidates pass identical gate checklist.

  • Operational signoff — upgrade/rollback/bootstrap recovery procedures validated and documented.

    Phase 8 Exit Criteria

  • Runtime independence — no libc/CRT dependency in default build+run workflow.

  • Toolchain independence — compiler, assembler, linker, and runtime are owned by the Baa ecosystem with explicit repository boundaries.

  • Reproducibility baseline — release artifacts are verifiable and reproducible from source.

  • Sustainability baseline — maintenance docs and on-call triage playbooks are complete.

    Toolchain Comparison

┌────────────────────────────────────────────────────────────────┐ │ Baa Toolchain Evolution │ ├────────────────────────────────────────────────────────────────┤ │ │ │ v0.2.x (Current): │ │ ┌─────────┐ ┌───────────────────────────────────────────┐ │ │ │ Baa │ → │ GCC (assembler + linker + C runtime) │ │ │ │ Compiler│ │ │ │ │ └─────────┘ └───────────────────────────────────────────┘ │ │ │ │ v0.9.x (Stable Beta): │ │ ┌─────────┐ ┌───────────────────────────────────────────┐ │ │ │ Baa │ → │ GCC (assembler + linker + C runtime) │ │ │ │ C ref │ │ + future staged bootstrap plan only │ │ │ └─────────┘ └───────────────────────────────────────────┘ │ │ │ │ v1.5.0 (Nazm Assembler): │ │ ┌─────────┐ ┌─────────┐ ┌─────────────────────────────┐ │ │ │ Baa │ → │ Nazm │ → │ GCC (linker + C runtime) │ │ │ │ Compiler│ │Assembler│ │ │ │ │ └─────────┘ └─────────┘ └─────────────────────────────┘ │ │ │ │ v2.0.0 (Own Linker): │ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌───────────────┐ │ │ │ Baa │ → │ Nazm │ → │ Linker │ → │ C Runtime │ │ │ │ Compiler│ │Assembler│ │ (future)│ │ (printf etc) │ │ │ └─────────┘ └─────────┘ └─────────┘ └───────────────┘ │ │ │ │ v3.0.0 (Full Independence): │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ Baa Ecosystem Toolchain (independently owned) │ │ │ │ Compiler → Assembler → Linker → Native Runtime │ │ │ │ │ │ │ │ No External Dependencies! │ │ │ └─────────────────────────────────────────────────────────┘ │ │ │ └────────────────────────────────────────────────────────────────┘


  \---

  ## 🏗️ Phase 2: Architecture Overhaul - Completed

  <details>
<summary><strong>v0.2.0</strong> — The Driver (CLI \& Build System)</summary>

* \[x] **CLI Argument Parser** — Implement a custom argument parser to handle flags manually.
* \[x] **Input/Output Control** (`-o`, `-S`, `-c`).
* \[x] **Information Flags** (`--version`, `--help`, `-v`).
* \[x] **Build Pipeline** — Orchestrate Lexer -> Parser -> Codegen -> GCC.

  </details>

  <details>
<summary><strong>v0.2.1</strong> — Polish \& Branding</summary>

* \[x] **Executable Icon** — Embed `.ico` resource.
* \[x] **Metadata** — Version info, Copyright, Description in `.exe`.

  </details>

  <details>
<summary><strong>v0.2.2</strong> — The Diagnostic Engine Patch</summary>

* \[x] **Source Tracking** — Update `Token` and `Node` to store Filename, Line, and Column.
* \[x] **Error Module** — Create a dedicated error reporting system.
* \[x] **Pretty Printing** — Display errors with context (`^` pointers).
* \[x] **Panic Recovery** — Continue parsing after errors.

  </details>

  <details>
<summary><strong>v0.2.3</strong> Distribution \& Updater Patch</summary>

* \[x] **Windows Installer** — Create `setup.exe` using Inno Setup.
* \[x] **PATH Integration** — Add compiler to system environment variables.
* \[x] **Self-Updater** — Implement `baa update` command.

  </details>

  <details>
<summary><strong>v0.2.4</strong> The Semantic Pass (Type Checker)</summary>

* \[x] **File Extension Migration** — Change `.b` to `.baa`. Reserved `.baahd` for headers.
* \[x] **Pass Separation** — Completely separate Parsing from Code Generation.

  * `parse()` returns a raw AST.
  * `analyze()` walks the AST to check types and resolve symbols.
  * The backend pipeline consumes a validated AST.
* \[x] **Symbol Resolution** — Check for undefined variables before code generation starts.
* \[x] **Scope Analysis** — Implement scope stack to properly handle nested blocks and variable shadowing.
* \[x] **Type Checking** — Validate assignments (int = string now fails during semantic analysis).

  </details>

  <details>
<summary><strong>v0.2.5</strong> Multi-File \& Include System</summary>

* \[x] **File Extension Migration** — Change `.b` to `.baa`. Reserved `.baahd` for headers.
* \[x] **Include Directive** — `#تضمين "file.baahd"` (C-style `#include`).
* \[x] **Header Files** — `.baahd` extension for declarations (function signatures, extern variables).
* \[x] **Function Prototypes** — Declarations without types `صحيح دالة().` (Added).
* \[x] **Multi-file CLI** — Accept multiple inputs: `baa main.baa lib.baa -o out.exe`.
* \[x] **Linker Integration** — Compile each file to `.o` then link together.

  </details>

  <details>
<summary><strong>v0.2.6</strong> Preprocessor Directives</summary>

* \[x] **Define** — `#تعريف اسم قيمة` for compile-time constants.
* \[x] **Conditional** — `#إذا\_عرف`, `#إذا\_عرف`, `#إذا\_لم\_يعرف`, `#وإلا`, `#وإلا\_إذا`, `#نهاية\_إذا` for conditional compilation.
* \[x] **Undefine** — `#الغاء\_تعريف` to remove definitions.

  </details>

  <details>
<summary><strong>v0.2.7</strong> Constants \& Immutability</summary>

* \[x] **Constant Keyword** — `ثابت` for immutable variables: `ثابت صحيح حد = ١٠٠.`
* \[x] **Const Checking** — Semantic error on reassignment of constants.
* \[x] **Array Constants** — Support constant arrays.

  </details>

  <details>
<summary><strong>v0.2.8</strong> Warnings \& Diagnostics</summary>

* \[x] **Warning System** — Separate warnings from errors (non-fatal).
* \[x] **Unused Variables** — Warn if variable declared but never used.
* \[x] **Dead Code** — Warn about code after `إرجع` or `توقف`.
* \[x] **`-W` Flags** — `-Wall`, `-Werror` to control warning behavior.

  </details>

  <details>
<summary><strong>v0.2.9</strong> — Input \& UX Polish</summary>

* \[x] **Input Statement** — `اقرأ س.` (scanf) for reading user input.
* \[x] **Boolean Type** — `منطقي` type with `صواب`/`خطأ` literals.
* \[x] **Colored Output** — ANSI colors for errors (red), warnings (yellow). *(Implemented in v0.2.8)*
* \[x] **Compile Timing** — Show compilation time with `-v`.

  </details>

  ## 📦 Phase 1: Language Foundation (v0.1.x) - Completed

  <details>
<summary><strong>v0.1.3</strong> — Control Flow \& Optimizations</summary>

* \[x] **Extended If** — Support `وإلا` (Else) and `وإلا إذا` (Else If) blocks.
* \[x] **Switch Statement** — `اختر` (Switch), `حالة` (Case), `افتراضي` (Default)
* \[x] **Constant Folding** — Compile-time math (`١ + ٢` → `٣`)

  </details>

  <details>
<summary><strong>v0.1.2</strong> — Recursion \& Strings</summary>

* \[x] **Recursion** — Stack alignment fix
* \[x] **String Variables** — `نص` type
* \[x] **Loop Control** — `توقف` (Break) \& `استمر` (Continue)

  </details>

  <details>
<summary><strong>v0.1.1</strong> — Structured Data</summary>

* \[x] **Arrays** — Fixed-size stack arrays (`صحيح قائمة\[١٠]`)
* \[x] **For Loop** — `لكل (..؛..؛..)` syntax
* \[x] **Logic Operators** — `\&\&`, `||`, `!` with short-circuiting
* \[x] **Postfix Operators** — `++`, `--`

  </details>

  <details>
<summary><strong>v0.1.0</strong> — Text \& Unary</summary>

* \[x] **Strings** — String literal support (`"..."`)
* \[x] **Characters** — Character literals (`'...'`)
* \[x] **Printing** — Updated `اطبع` to handle multiple types
* \[x] **Negative Numbers** — Unary minus support

  </details>

  <details>
<summary><strong>v0.0.9</strong> — Advanced Math</summary>

* \[x] **Math** — Multiplication, Division, Modulo
* \[x] **Comparisons** — Greater/Less than logic (`<`, `>`, `<=`, `>=`)
* \[x] **Parser** — Operator Precedence Climbing (PEMDAS)

  </details>

  <details>
<summary><strong>v0.0.8</strong> — Functions</summary>

* \[x] **Functions** — Function definitions and calls
* \[x] **Entry Point** — Mandatory `الرئيسية` exported unchanged with an Arabic-only hosted startup ABI
* \[x] **Scoping** — Global vs Local variables
* \[x] **Windows x64 ABI** — Register passing, stack alignment, shadow space

  </details>

  <details>
<summary><strong>v0.0.7</strong> — Loops</summary>

* \[x] **While Loop** — `طالما` implementation
* \[x] **Assignments** — Update existing variables

  </details>

  <details>
<summary><strong>v0.0.6</strong> — Control Flow</summary>

* \[x] **If Statement** — `إذا` with blocks
* \[x] **Comparisons** — `==`, `!=`
* \[x] **Documentation** — Comprehensive Internals \& API docs

  </details>

  <details>
<summary><strong>v0.0.5</strong> — Type System</summary>

* \[x] Renamed `رقم` to `صحيح` (int)
* \[x] Single line comments (`//`)

  </details>

  <details>
<summary><strong>v0.0.4</strong> — Variables</summary>

* \[x] Variable declarations and stack offsets
* \[x] Basic symbol table

  </details>

  <details>
<summary><strong>v0.0.3</strong> — I/O</summary>

* \[x] `اطبع` (Print) via Windows `printf`
* \[x] Multiple statements support

  </details>

  <details>
<summary><strong>v0.0.2</strong> — Math</summary>

* \[x] Arabic numerals (٠-٩)
* \[x] Addition and subtraction

  </details>

  <details>
<summary><strong>v0.0.1</strong> — Foundation</summary>

* \[x] Basic pipeline: Lexer → Parser → Codegen → GCC

  </details>

  \---

  ## 📊 Timeline Summary

|Phase|Version|Milestone|Dependencies / Owner|
|-|-|-|-|
|Phase 3|v0.3.x|IR Complete|GCC|
|Phase 3.5|v0.3.3-v0.3.12|Language Complete|GCC|
|Phase 4|v0.4.x|Standard Library|GCC|
|Phase 4.5|v0.5.x|Reference Compiler Stabilization|GCC|
|Phase 6|v0.6.x|Language Usability \& Safety|Baa compiler|
|Phase 7|v0.7.x|Testing \& External Integration Contracts|Baa + Takween/Qalam contracts|
|Phase 8|v0.8.x|Backend/Optimizer/Performance Reliability|Baa compiler|
|Phase 9|v0.9.x|Stable Beta + Future Bootstrap/OS-dev Plan|Baa compiler|
|Future|v0.10.x / post-v0.9|Freestanding OS Development Profile|Baa compiler + PyramidOS C/ASM reference|
|Future|post-v0.10|Self-hosting / own assembler / own linker|Separate staged decision|

\---

*For detailed changes, see the* [*Changelog*](CHANGELOG.md)