Signed-off-by: erick-alcachofa <erick@artichoke.dev>
Overhaul the expression parsing mechanism to utilize a Pratt (top-down
operator precedence) parser. This change provides a more scalable and
maintainable way to handle operator precedence and associativity
compared to standard recursive descent.
As part of this transition, the nomenclature for operators has been
refined to reflect their position in the grammar (Prefix, Infix,
Postfix) rather than their arity.
* Renamed `UnaryOperator` and `UnaryExpression` to `PrefixOperator` and
`PrefixExpression`.
* Renamed `BinaryOperator` and `BinaryExpression` to `InfixOperator` and
`InfixExpression`.
* Renamed `ScopeAccessExpression` to `ModuleAccessExpression`.
* Introduced `PostfixOperator` enum and associated logic for function
calls, slicing, and reflection attributes.
* Updated `toDot.cpp` and `toString.cpp` to support the new node types
and renamed operators.
* Added `Pratt.hpp` and `Pratt.cpp` to define `BindingPower` and map
operators to their respective precedence levels.
* Added `Operators.cpp` to handle token-to-operator mapping and
classification (isPrefix, isInfix, isPostfix).
* Refactored `Parser::parseExpression` to implement the core Pratt loop
using binding power comparisons.
* Moved literal parsing logic into a dedicated `Literals.cpp`.
* Implemented explicit parsing methods for `Integer`, `Float`, `Char`,
`String`, `Boolean`, and `Null` literals.
* Added support for `this` and `_` (underscore) as identifier
expressions.
* **Prefix**: `!`, `-`, `~`, `&` (MemPtr), `*` (DerefPtr).
* **Infix**: Arithmetic, Comparison, Bitwise, Logical, and all Compound
Assignments.
* **Postfix**: `()` (Call), `[]` (Slice/Access), `.#` (Slice length),
`.*` (Slice pointer), and `.@` (Reflection).
* **Missing Literals**: Struct literals and Array literals are not yet
implemented in the new parsing flow.
* **Node Specialization**: `MemberAccess`, `PointerMemberAccess`, and
`ModuleAccess` currently use generic infix logic and need to be
migrated to their specific AST node types.
* **Error Handling**: Literal parsing (specifically `std::stold` and
`std::stoul`) needs safety checks to prevent potential exceptions
during conversion.
* **Diagnostics**: Refine the error message for unexpected tokens in
postfix expressions to explicitly list supported operators.
* **Generic Ambiguity**: Generic type/function instantiation currently
causes parsing conflicts with comparison operators (e.g., `Foo<T>`).
This is a known issue that will be resolved by transitioning the
grammar to a turbofish-style `::<...>` syntax.
Signed-off-by: erick-alcachofa <erick@artichoke.dev>
Complete the transition from a declarations-only parser to a functional
imperative parser. This commit introduces the implementation for all
major statement types, loop constructs, and core control flow logic.
- **Match Case Update**: Updated `grammar.ebnf` to use pipe delimiters
`|id|` for unwrapped variables in match cases, replacing the previous
parenthetical syntax.
- **Labels**: Implemented loop labeling using the `ident := loop`
syntax. Labels are validated to ensure they only prefix valid loop
constructs.
- **Labels and Ranges**: Standardized the use of the `:=` operator for
both loop labels (`label := loop`) and range-for declarations (`let i
:= range`).
- **Conditional Branches**:
- Fully implemented `if` and `else` statements.
- Added support for optional variable unwrapping (e.g., `if (expr)
|val|`).
- Supported `else if` chaining by recursively parsing if-statements
within else-branches.
- **Loops**:
- **C-Style For**: Implemented `for (init; cond; post)` with
optional initializers and post-loop expressions.
- **Range For**: Implemented `for (let i := range)` with mutability
controls.
- **While & Do-While**: Implemented standard condition-based loops.
- **Infinite Loop**: Added the explicit `loop` keyword for infinite
iteration.
- **Loop Dispatch**: Added a lookahead mechanism in
`parseForLoopStatement` to differentiate between C-style and
Range-style loops based on token positioning.
- **Variables**: Implemented `let`/`def` parsing within local scopes,
including type annotations and initializers.
- **Defer Logic**: Implemented `defer` and `errdefer` for scope-guarded
execution.
- **Jumps**: Implemented `break`, `continue` (with optional label
targets), and `return` (with optional expressions).
- **Match & Switch**: Fully implemented branch parsing, with possible
default cases via the `_` (underscore) keyword.
- **Expression Integration**: Stubbed `parseExpression` in a new
`Expressions.cpp` to serve as the integration point for value parsing.
- **OverloadSet**: Integrated `OverloadSet` utility in `Statements.cpp`
to cleanly handle AST node variant visitation for label injection.
- **Error Handling**: Standardized error reporting across all new paths
using `langException`, providing specific "expected" messages for
delimiters and keywords.
Signed-off-by: erick-alcachofa <erick@artichoke.dev>
Relocate core parsing utility methods from the header to the
implementation file to reduce header bloat and improve compilation
times.
- **Parser API**: Moved the definitions of `consume()`,
`matchAndConsume()`, and `match()` from `Parser.hpp` to `Parser.cpp`.
- **Cleanup**: Removed an unused `<print>` include in `Types.cpp`
discovered during the refactor.
- **Organization**: Methods are now declared in the header and defined
in the source file, maintaining a cleaner separation between interface
and implementation.
Signed-off-by: erick-alcachofa <erick@artichoke.dev>
Major refactoring of the Parser and Tokenizer components to improve code
maintainability, strengthen error messaging, and streamline AST
generation.
This version intentionally focuses on top-level declarations, with
statement parsing stubbed for the next development phase.
- **Path Sanitization**: Added `sanitizePath` to extract filenames from
input paths, ensuring consistent `unitName` identification regardless
of directory depth.
- **Improved Output**: Wrapped AST string output in Markdown code blocks
and added a commented-out entry for the new DOT graph visualization.
- **Unified Consumption**: Replaced manual token checks with a more
robust `consume()` method that leverages `peekExpect()` for
centralized error handling.
- **New Predicates**: Introduced `match()` and `matchAndConsume()`
helpers to handle optional tokens and branching logic without
redundant peek/consume calls.
- **Exception Handling**: Standardized the use of `langException` across
all parsing functions, providing more descriptive "Expected X, found
Y" messages.
- **Declarations**: Refactored `parseTopLevelDeclaration` and
sub-parsers (Module, Struct, Enum, Fn) to use the new matching
patterns.
- **Looping Logic**: Replaced recursive-style parsing loops with
`while(keepParsing)` iterative blocks to prevent stack depth issues
and clarify termination conditions (e.g., finding a closing brace or
failing to find a comma).
- **Namespaced Identifiers**: Rewrote `parseNamespacedIdentifier` to
correctly handle multi-part paths (`A::B::C`) and edge cases.
- **Generic Support**: Improved handling of generic parameter and
argument lists, ensuring strict enforcement of delimiters like `<` and
`>`.
- **Contextual Errors**: Updated `peekExpect` to accept a custom
`message` string, allowing the parser to describe *what* it was
looking for (e.g., "Expected ';'").
- **Token Lookahead**: Enhanced `peek` and `peekExpect` reliability with
better bounds checking and buffer management.
- **Removed `lib/src/Parser/AST/AST.cpp`**: Deleted the monolithic AST
stringification file in favor of the previously introduced modular
implementations.
- **Build System**: Updated `.gitignore` to ignore
`cpm-package-lock.cmake`.
Signed-off-by: erick-alcachofa <erick@artichoke.dev>
This commit introduces the foundational structure for the parser and
Abstract Syntax Tree (AST). It includes a new `Parser.hpp` header that
outlines the primary parsing functions for top-level declarations like
`modules`, `structs`, `enums`, and `functions`. It also adds a
`toString` function for the AST to aid in debugging and visualization.
The commit also updates the `Expected.hpp` utility by adding new error
codes like `ecUnexpectedToken`, `ecExpectedSemicolon`,
`ecImportInsideModule`, and `ecUnimplemented` to provide more granular
and descriptive parsing errors. The `Tokenizer` has been updated to use
these new, more specific exceptions.