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 refactors the AST printing functionality by moving the
human-readable `toString` implementation into its own file
(`lib/src/Parser/AST/toString.cpp`) and introducing a new `toDot`
function in `lib/src/Parser/AST/toDot.cpp` for generating Graphviz DOT
format output.
The `AST.hpp` header is updated to declare both the new `toDot` function
and the modified `toString` function, which now uses an optional
`prefix` parameter for prettier tree output. The `Token.hpp`/`Token.cpp`
files are also adjusted to have `toString(const TokenV &)` return a
`std::string_view`, and `toString(const Token &)` provides a cleaner
string representation using only the token's value.
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.
Signed-off-by: erick-alcachofa <erick@artichoke.dev>
This commit changes the `OverloadSet` utility class to publicly inherit
from its template parameters `Ts...`. This allows the `operator()` from
each provided type to be brought into the overload set, efectively
fixing it's functionality that would be broken otherwise.
It also includes the missing `<ranges>` header in the test utilities.
Signed-off-by: erick-alcachofa <erick@artichoke.dev>
This commit refactors several AST nodes to use `Optional<T>` for fields
that are not always present. This includes `attribute` in
`ReflectionExpression`, `elseBranch` in `IfStatement` and
`WhileStatement`, `defaultCase` in `MatchStatement` and
`SwitchStatement`, and `preLoop` and `postLoop` in `CForStatement`. This
change improves the robustness and clarity of the AST by explicitly
modeling optionality.
Signed-off-by: erick-alcachofa <erick@artichoke.dev>
This commit adds `Uninitialized` to several enums in `Common.hpp` to
ensure they are properly initialized.
It also adds missing binary operators like `BitAnd`, `BitXor`,
`Adition`, and `Multiplication`. This change improves the robustness and
functionality of the AST parser.
Signed-off-by: erick-alcachofa <erick@artichoke.dev>
This commit updates the language grammar to expand the capabilities of
`using` aliases and C-style `for` loops. It also refines where aliases
can be declared. This changes are made after re-analizing the grammar
while creating the AST node types.
* **Aliases:** A `using` alias can now map to any valid `<type>`, such
as a pointer (`*i32`) or optional (`?string`), instead of just a
simple `<namespaced_identifier>`.
* **For Loops:** The initializer in a C-style `for` loop can now be a
general `<expression>` (e.g., `i = 0`) in addition to a full
`<variable_declaration>`.
* **Scope:** Alias declarations are now restricted to the top level
(declarations) and are no longer permitted as statements inside
function bodies.
BREAKING CHANGE: Alias declarations (`using`) are no longer valid inside
function bodies and must be declared at a module or global scope.
Signed-off-by: erick-alcachofa <erick@artichoke.dev>
This commit introduces an utility factory function and structural
improvements to the Abstract Syntax Tree (AST).
* Adds a new `ASTNodePtr` C++20 concept to constrain template types to
be `std::unique_ptr`s pointing to AST nodes.
* Introduces a `MakeNode<T>()` factory function that uses this concept
to simplify and standardize the creation of new nodes.
* Fixed `NamespacedType` and added the missing `NamespacedIdentifier`
node.
Signed-off-by: erick-alcachofa <erick@artichoke.dev>
This commit refactors the AST (Abstract Syntax Tree) to improve code
organization, clarity, and maintainability. The large single-file AST
definition has been split into multiple, logically grouped header files.
The key changes are:
- **New File Structure**: The single `Node.hpp` file is replaced by a
modular structure consisting of `Common.hpp`, `Declarations.hpp`,
`Expressions.hpp`, `Literals.hpp`, `Statements.hpp`, and a new central
`AST.hpp` header.
- **Improved Naming**: All AST node structs and their aliases have been
renamed to follow a consistent `[NodeName][NodeType]` convention, such
as `StructDeclaration` and `StructDeclNode`.
- **Namespace Change**: The `node` namespace has been replaced by
`arti::lang::ast::nodes` to provide better encapsulation and prevent
naming conflicts.
- **Type Aliases**: Helper aliases like `String`, `Vector`, and
`Variant` have been introduced to simplify the code.
Signed-off-by: erick-alcachofa <erick@artichoke.dev>
Introduces the comprehensive header file for the Abstract Syntax Tree,
providing the foundational structures for the parser and subsequent
compiler stages.
This initial version defines all node types required to represent the
language's grammar, including:
- Top-level program structure and module declarations.
- All statement types, including control flow, loops, and deferrals.
- A semantic expression tree designed for a Pratt parser (Unary, Binary,
Function Calls, etc.).
- A robust, recursive type system for handling complex type signatures.
The design employs modern C++ for safety and clarity:
- `std::unique_ptr` establishes clear ownership of child nodes.
- `std::variant` provides type-safe polymorphism for Statement,
Expression, and Declaration nodes.
- `std::optional` is used to accurately model optional grammar rules.
- `SourceLocation` is included in every node to support detailed error
reporting.
Signed-off-by: erick-alcachofa <erick@artichoke.dev>
The grammar contained several structural issues and ambiguities,
particularly in expression parsing, operator precedence, and the
`export` keyword. This commit restructures significant parts of the
grammar to resolve these problems and improve its formal correctness,
making it more suitable for parser generation.
The most relevant changes include:
* **Centralized Export Handling:** Corrects the definition of exports by
introducing a top-level `<declaration>` rule that distinguishes
between `<exportable_declaration>` and `<non_exportable_declaration>`.
This removes the repetitive and ambiguous `export?` prefix from
multiple individual declarations (`module`, `struct`, `fn`, etc.).
* **Unified Postfix Operations:** Integrates scoped access into the
suffix operations . This provides an unambiguous and unified
definition for these common constructs.
* **Updated Identifier Chain Issue:** Several rules in the precedence
chain ultimately resolved into starting with an identifier, this
caused ambiguitiy and issues for parsing, this was refactored in order
to correctly handle the cases.
* **Reduced Ambiguity in Statements:** Refactors complex rules like
`<variable_declaration>` and `<else_statement>` into smaller, more
explicit sub-rules (`<variable_declaration_tail>`,
`<else_statement_tail>`). This eliminates potential parsing conflicts
and improves the overall clarity of the grammar.
* **Simplified Access Expressions:** Removes the separate
`<scoped_access_expression>` and `<reflection_expression>` rules.
Their logic has been integrated directly into the more generic and
powerful postfix expression system, simplifying the grammar.
Signed-off-by: erick-alcachofa <erick@artichoke.dev>
The error message string for unexpected tokens was prepended with an
erroneous 'O'. This commit removes the typo.
Signed-off-by: erick-alcachofa <erick@artichoke.dev>
Introduced `peekExpect(std::size_t, TokenV)` to the Tokenizer class, enabling
token lookahead with explicit token type checks. This method returns an
`Unexpected` error with diagnostic info if the expected token type does not
match the peeked token.
Includes a special case handling (workaround) for distinguishing between
`>` and `>>` tokens when parsing the token stream.
Signed-off-by: erick-alcachofa <erick@artichoke.dev>
The EBNF grammar definition contained several redundancies,
inconsistencies, and minor omissions. This commit refactors the grammar
to make it more concise, readable, and robust for parsing.
Key changes include:
- **Rule Simplification**: Redundant intermediate rules (`fn_params`,
`statements`, `assign_expression`) have been removed. Rules like
`code_block` and `import_target` are now more concisely expressed
using standard EBNF operators (`?`, `*`).
- **EOF Enforcement**: The top-level `program` rule now requires an
`<eof>` token. This is a crucial fix to ensure the parser consumes the
entire file and fails on trailing invalid tokens.
- **Optional Generics**: Generic parameters (`<... >`) are now correctly
marked as optional on `function`, `struct`, and `enum` declarations,
which was the original intent.
- **Flexible For-Loops**: The update/increment expression (the third
part) in a C-style `for` loop is now optional, aligning with behavior
in languages like C and C++.
- **Primary Expressions**: Primary type expressions failed to parse
correctly namespaced elements and types, now it's fixed and improved.
Signed-off-by: erick-alcachofa <erick@artichoke.dev>
This commit introduces a comprehensive test suite for the tokenizer
using the Catch2 framework. To support this and improve the project
structure, the build system and the tokenizer's API have been
significantly updated.
- Removed `cmake/testing.cmake` as it's no longer needed.
- A new `TokenizerRange` class provides a C++20-style range interface,
allowing for simple `for-each` loop iteration over tokens. This is
used extensively in the new tests.
- The CMake build system has been refactored:
- An `ENABLE_TESTING` option (OFF by default) now controls whether
the test suite is built.
- The core library is now compiled into an object library, which is
then used to produce both a shared (`.so`/`.dll`) and a static
(`.a`/`.lib`) library. This improves build efficiency and provides
more flexible linkage options.
- The frontend executable now links against the static version of
the library.
- Implemented tests for tokenizer using Catch2 framework, covering
various cases like identifiers, keywords, numbers, etc. that already
catched some issues in current implementation.
- Several parsing bugs and edge cases in the tokenizer were fixed,
including the handling of unterminated strings and invalid numeric
literals. The README has been updated with instructions for building
and running tests.
Signed-off-by: erick-alcachofa <erick@artichoke.dev>
This commit lays the foundational groundwork for the artichoke language
parser by introducing the formal language grammar specification.
The tokenizer was updated to include new operators and keywords, also
added the posibility to handle comments.
Key Additions:
- Implemented support for C-style block comments (`/* ... */`),
including error handling for unclosed comments.
- Added all necessary tokens for missing keywords (e.g., `module`,
`export`, `using`, `match`, `loop`) and operators (e.g., `+=`, `:=`,
`.#`, `.*`, `.@`).
- The `Token` enum has been expanded to reflect the full language
feature set.
Documentation:
- Added `docs/grammar.ebnf` which contains the official, well-structured
EBNF grammar for the language.
- Added `docs/readme.md` providing a detailed technical overview of the
language's features, syntax, and semantics.
BREAKING CHANGE: The `kwVariant` and `kwMut` tokens have been removed to
align with the updated language design defined in the new grammar.
Fixed some minor mistakes (wrong messages/errors) due to copy/pasting
code.
Fixed that digits weren't allowed in identifiers before.
Also minor improvements in some functions/code parts.
Initial version of Tokenizer and Token
Generator template for coroutines (used in tokenizer)
Utilities like string related functions, TrieMap, and error handling
TODO: Add tests for Tokenizer
TODO: Add tests for Generator