Initial rework additions

This commit is contained in:
Mattia Giambirtone 2023-07-20 14:32:42 +02:00
parent fe568afc68
commit e6e9b3965c
Signed by: nocturn9x
GPG Key ID: 8270F9F467971E59
20 changed files with 7378 additions and 2 deletions

LICENSE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
implied, including, without limitation, any warranties or conditions
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -1,3 +1,126 @@
# peon-rewrite
# The peon programming language
Work in progress for Peon 0.2.x
Peon is a modern, multi-paradigm, async-first programming language with a focus on correctness and speed.
[Go to the Manual](docs/
## What's peon?
__Note__: For simplicity reasons, the verbs in this section refer to the present even though part of what's described here is not implemented yet.
Peon is a multi-paradigm, statically-typed programming language inspired by C, Nim, Python, Rust and C++: it supports modern, high-level
features such as automatic type inference, parametrically polymorphic generic types, pure functions, closures, interfaces, single inheritance,
reference types, templates, coroutines, raw pointers and exceptions.
The memory management model is rather simple: a Mark and Sweep garbage collector is employed to reclaim unused memory, although more garbage
collection strategies (such as generational GC or deferred reference counting) are planned to be added in the future.
Peon features a native cooperative concurrency model designed to take advantage of the inherent waiting of typical I/O workloads, without the use of more than one OS thread (wherever possible), allowing for much greater efficiency and a smaller memory footprint. The asynchronous model used forces developers to write code that is both easy to reason about, thanks to the [Structured concurrency]( model that is core to peon's async event loop implementation, and works as expected every time (without dropping signals, exceptions, or task return values).
Other notable features are the ability to define (and overload) custom operators with ease by implementing them as language-level functions, [Universal function call syntax](, [Name stropping]( and named scopes.
In peon, all objects are first-class (this includes functions, iterators, closures and coroutines).
## Disclaimers
**Disclaimer 1**: The project is still in its very early days: lots of stuff is not implemented, a work in progress or
otherwise outright broken. Feel free to report bugs!
**Disclaimer 2**: Currently, the `std` module has to be _always_ imported explicitly for even the most basic snippets to work. This is because intrinsic types and builtin operators are defined within it: if it is not imported, peon won't even know how to parse `2 + 2` (and even if it could, it would have no idea what the type of the expression would be). You can have a look at the [peon standard library](src/peon/stdlib) to see how the builtins are defined (be aware that they heavily rely on compiler black magic to work) and can even provide your own implementation if you're so inclined.
### TODO List
In no particular order, here's a list of stuff that's done/to do (might be incomplete/out of date):
- User-defined types
- Function calls ✅
- Control flow (if-then-else, switch) ✅
- Looping (while) ✅
- Iteration (foreach)
- Type conversions
- Type casting
- Intrinsics ✅
- Type unions ✅
- Functions ✅
- Closures
- Managed references
- Unmanaged references
- Named scopes/blocks ✅
- Inheritance
- Interfaces
- Generics ✅
- Automatic types ✅
- Iterators/Generators
- Coroutines
- Pragmas ✅
- Attribute resolution ✅
- Universal Function Call Syntax
- Import system ✅
- Exceptions
- Templates (_not_ like C++ templates) ✅
- Optimizations (constant folding, branch and dead code elimination, inlining)
## Feature wishlist
Here's a random list of high-level features I would like peon to have and that I think are kinda neat (some may
have been implemented alredady):
- Reference types are not nullable by default (must use `#pragma[nullable]`)
- The `commutative` pragma, which allows to define just one implementation of an operator
and have it become commutative
- Easy C/Nim interop via FFI
- C/C++ backend
- Nim backend
- [Structured concurrency]( (must-have!)
- Simple OOP (with multiple dispatch!)
- RTTI, with methods that dispatch at runtime based on the true (aka runtime) type of a value
- Limited compile-time evaluation (embed the Peon VM in the C/C++/Nim backend and use that to execute peon code at compile time)
## The name
The name for peon comes from [Productive2's]( genius cute brain, and is a result of shortening
the name of the fastest animal on earth: the **Pe**regrine Falc**on**. I guess I wanted this to mean peon will be blazing fast (I
certainly hope so!)
# Peon needs you.
No, but really. I need help. This project is huge and (IMHO) awesome, but there's a lot of non-trivial work to do and doing
it with other people is just plain more fun and rewarding. If you want to get involved, definitely try [contacting]( me
or open an issue/PR!
# Credits
- Araq, for creating the amazing language that is [Nim]( (as well as all of its contributors!)
- Guido Van Rossum, aka the chad who created [Python]( and its awesome community and resources
- The Nim community and contributors, for making Nim what it is today
- Bob Nystrom, for his amazing [book]( that inspired me
and taught me how to actually make a programming language (kinda, I'm still very dumb)
- [Njsmith](, for his awesome articles on structured concurrency
- All the amazing people in the [r/ProgrammingLanguages]( subreddit and its [Discord]( server
- [Art]( <3
- Everyone to listened (and still listens to) me ramble about compilers, programming languages and the likes (and for giving me ideas and testing peon!)
- ... More? (I'd thank the contributors but it's just me :P)
- Me! I guess
## Ok, cool, how do I use it?
Great question! If this README somehow didn't turn you away already (thanks, by the way), then you may want to try peon
out for yourself. Fortunately, the process is quite straightforward:
- First, you're gonna have to install [Nim](, the language peon is written in. I highly recommend
using [choosenim]( to manage your Nim installations as it makes switching between them and updating them a breeze
- Then, clone this repository and compile peon in release mode with `nim c -d:release --passC:"-flto" -o:peon src/main`, which should produce`peon` binary
ready for you to play with (if your C toolchain doesn't support LTO then you can just omit the `--passC` option, although that would be pretty weird for
a modern linker)
- If you want to move the executable to a different directory (say, into your `PATH`), you should copy peon's standard
library (found in `/src/peon/stdlib`) into a known folder, edit the `moduleLookupPaths` variable inside `src/config.nim`
by adding said folder to it so that the peon compiler knows where to find modules when you `import std;` and then recompile
peon. Hopefully I will automate this soon, but as of right now the work is all manual
__Note__: On Linux, peon will also look into `~/.local/peon/stdlib` by default, so you can just create the `~/.local/peon` folder and copy `src/peon/stdlib` there

docs/.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
"makefile.extensionOutputFolder": "./.vscode"

docs/ Normal file
View File

@ -0,0 +1,113 @@
# Peon - Bytecode Specification
This document aims to document peon's bytecode as well as how it is (de-)serialized to/from files and
other file-like objects. Note that the segments in a bytecode dump appear in the order they are listed
in this document.
## Code Structure
A peon program is compiled into a tightly packed sequence of bytes that contain all the necessary information
the VM needs to execute said program. There is no dependence between the frontend and the backend outside of the
bytecode format (which is implemented in a separate serialiazer module) to allow for maximum modularity.
A peon bytecode file contains the following:
- Constants
- The program's code
- Debugging information (file and version metadata, module info. Optional)
## File Headers
A peon bytecode file starts with the header, which is structured as follows:
- The literal string `PEON_BYTECODE`
- A 3-byte version number (the major, minor and patch version numbers of the compiler that generated the file)
- The branch name of the repository the compiler was built from, prepended with its length as a 1 byte integer
- The commit hash (encoded as a 40-byte hex-encoded string) in the aforementioned branch from which the compiler was built from (particularly useful in development builds)
- An 8-byte UNIX timestamp (with Epoch 0 starting at 1/1/1970 12:00 AM) representing the exact date and time of when the file was generated
## Debug information
The following segments contain extra information and metadata about the compiled bytecode to aid debugging, but they may be missing
in release builds.
### Line data segment
The line data segment contains information about each instruction in the code segment and associates them
1:1 with a line number in the original source file for easier debugging using run-length encoding. The segment's
size is fixed and is encoded at the beginning as a sequence of 4 bytes (i.e. a single 32 bit integer). The data
in this segment can be decoded as explained in [this file](../src/frontend/compiler/targgets/bytecode/opcodes.nim#L29), which is quoted
## lines maps bytecode instructions to line numbers using Run
## Length Encoding. Instructions are encoded in groups whose structure
## follows the following schema:
## - The first integer represents the line number
## - The second integer represents the number of
## instructions on that line
## For example, if lines equals [1, 5], it means that there are 5 instructions
## at line 1, meaning that all instructions in code[0..4] belong to the same line.
## This is more efficient than using the naive approach, which would encode
## the same line number multiple times and waste considerable amounts of space.
### Functions segment
This segment contains details about each function in the original file. The segment's size is fixed and is encoded at the
beginning as a sequence of 4 bytes (i.e. a single 32 bit integer). The data in this segment can be decoded as explained
in [this file](../src/frontend/compiler/targets/bytecode/opcodes.nim#L39), which is quoted below:
## functions encodes the following information:
## - Function name
## - Argument count
## - Function boundaries
## The encoding for functions is the following:
## - First, the position into the bytecode where the function begins is encoded (as a 3 byte integer)
## - Second, the position into the bytecode where the function ends is encoded (as a 3 byte integer)
## - After that follows the argument count as a 1 byte integer
## - Lastly, the function's name (optional) is encoded in ASCII, prepended with
## its size as a 2-byte integer
### Modules segment
This segment contains details about the modules that make up the original source code which produced a given bytecode dump.
The data in this segment can be decoded as explained in [this file](../src/frontend/compiler/targets/bytecode/opcodes.nim#L49), which is quoted below:
## modules contains information about all the peon modules that the compiler has encountered,
## along with their start/end offset in the code. Unlike other bytecode-compiled languages like
## Python, peon does not produce a bytecode file for each separate module it compiles: everything
## is contained within a single binary blob. While this simplifies the implementation and makes
## bytecode files entirely "self-hosted", it also means that the original module information is
## lost: this segment serves to fix that. The segment's size is encoded at the beginning as a 4-byte
## sequence (i.e. a single 32-bit integer) and its encoding is similar to that of the functions segment:
## - First, the position into the bytecode where the module begins is encoded (as a 3 byte integer)
## - Second, the position into the bytecode where the module ends is encoded (as a 3 byte integer)
## - Lastly, the module's name is encoded in ASCII, prepended with its size as a 2-byte integer
## Constant segment
The constant segment contains all the read-only values that the code will need at runtime, such as hardcoded
variable initializers or constant expressions. It is similar to the `.rodata` section of Assembly files, although
the implementation is different. Constants are encoded as a linear sequence of bytes with no type information about
them whatsoever: it is the code that, at runtime, loads each constant (whose type is determined at compile time) onto
the stack accordingly. For example, a 32 bit integer constant would be encoded as a sequence of 4 bytes, which would
then be loaded by the appropriate `LoadInt32` instruction at runtime. The segment's size is fixed and is encoded at
the beginning as a sequence of 4 bytes (i.e. a single 32 bit integer). The constant segment may be empty, although in
real-world scenarios it likely won't be.
## Code segment
The code segment contains the linear sequence of bytecode instructions of a peon program to be fed directly to
peon's virtual machine. The segment's size is fixed and is encoded at the beginning as a sequence of 3 bytes
(i.e. a single 24 bit integer). All the instructions are documented [here](../src/frontend/compiler/targgets/bytecode/opcodes.nim)

docs/ Normal file
View File

@ -0,0 +1,32 @@
# Peon design scratchpad
This is just a random doc I made to keep track of all the design changes I have
in mind for Peon: with this being my first serious attempt at making a programming
language that's actually _useful_, I want to get the design right the first time
(no one wants to make JavaScript 2.0, right? _Right?_).
The basic idea is:
- Some peon code comes in (from a file or as command-line input, doesn't matter)
- It gets tokenized and parsed into a typeless AST
- The compiler processes the typeless AST into a typed one
- The typed AST is passed to an optional optimizer module, which spits
out another (potentially identical) typed AST representing the optimized
program. The optimizer is always run even when optimizations are disabled,
as it takes care of performing closure conversion and other cool stuff
- The typed AST is passed to a code generator module that is specific to every
backend/platform, which actually takes care of producing the code that will
then be executed
The current design is fairly modular and some parts of the codebase are more final
than others: for example, the lexer and parser are more or less complete and unlikely
to undergo massive changes in the future as opposed to the compiler which has been subject
to many major refactoring steps as the project went along, but I digress.
The typed AST format should ideally be serializable to binary files so that I can slot in
different optimizer/code generator modules written in different languages without the need
to use FFI. The format will serve a similar purpose to the IR used by gcc (GIMPLE), but instead
of being an RTL-like language it'll operate on a much higher level since we don't really need to
support any other programming language other than peon itself (while gcc has to be interoperable
with FORTRAN and other stuff).

docs/ Normal file
View File

@ -0,0 +1,179 @@
# Peon - Formal Grammar Specification
__Note__: This document is currently a draft and is therefore incomplete
## Rationale
The purpose of this document is to provide an unambiguous formal specification of peon's syntax for use in automated
compiler generators (known as "compiler compilers") and parsers.
Our grammar is inspired by (and extended from) the Lox language as described in Bob Nystrom's book "Crafting Interpreters",
available at, and follows the EBNF standard, but for clarity the relevant syntax will
be explained below.
## Disclaimer
"OPTIONAL" in this document are to be interpreted as described in [RFC2119](
Literals in this document will be often surrounded by double quotes to make it obvious they're not part of a sentence. To
avoid ambiguity, this document will always specify explicitly if double quotes need to be considered as part of a term or not,
which means that if it is not otherwise stated they are to be considered part of said term. In addition to quotes, literals
may be formatted in monospace to make them stand out more in the document.
## EBNF Syntax & Formatting rules
As a refresher to experienced users as well as to facilitate reading to newcomers, the variation of EBNF used in this document
is detailed below:
- The literal `"LF"` (without quotes) is a shorthand for "Line Feed". It symbolizes the end of a line and it's platform-independent
- A pair of 2 forward-slashes (character code 47) is used to mark comments. A comment lasts until the
the end of a line is encountered. It is RECOMMENDED to use them to clarify each rule, or a group of rules,
to simplify human inspection of the specification
- The name of non-terminal productions MUST be in lowercase (such as `foo`), while for terminals it MUST be in uppercase (such as `FOO`)
- Whitespaces, tabs, newlines and form feeds (character codes 32, 9, 10 and 12 respectively) are not
relevant to the grammar and MUST be ignored by automated parsers and parser generators
- `"*"` (without quotes, character code 42) is used for repetition of a rule, meaning it MUST match 0 or more times
- `"?"` (without quotes, character code 63) means a rule can match 0 or 1 times
- `"+"` (character code 43) is used for repetition of a rule, meaning it MUST match 1 or more times
- `"|"` (without quotes, character code 123) is used to indicate alternatives and means a rule may match either the first or
the second rule. This operator can be chained to obtain something like `"foo" | "bar" | "baz"`, meaning that either
the literal strings foo, bar or baz are valid matches for the rule
- `"{x,y}"` (without quotes) is used for repetition, meaning a rule MUST match from x to y times (start to end, inclusive).
Omitting x means the rule MUST match at least 0 times and at most x times, while omitting y means the rule
MUST match exactly y times. Omitting both x and y is the same as using `*`
- Production rules are terminated with an ASCII semicolon (`COLON` without quotes, character code 59)
- Rules are listed in descending order: the last rule is the highest-precedence one. Think of it as a "more complex rules
come first"
- An "arrow" (character code 8594) MUST be used to separate rule names from their definition.
A rule definition, then, looks something like this (without quotes): `"name → rule definition here; // optional comment"`
- Literal numbers can be expressed in their decimal form (i.e. with arabic numbers). Other supported formats are
hexadecimal using the prefix `0x`, octal using the prefix `0o`, and binary using the prefix `0b`. For example,
the literals `0x7F`, `0b1111111` and `0o177` all represent the decimal number `127` in hexadecimal, binary and
octal respectively
- The literal `"EOF"` (without quotes), represents the end of the input stream and is a shorthand for "End Of File"
- Ranges can be defined by separating the start and the end of the range with three dots (character code 46) and
are inclusive at both ends. Both the start and the end of the range are mandatory and it is RECOMMENDED that they
be separated by the three dots with a space for ease of reading. Ranges can define numerical sets like in `"0 ... 9"`
(without quotes), or lexicographical ones such as `"'a' ... 'z'"` (without quotes), in which case the range should be
interpreted as a sequence of the character codes between the start and end of the range. Ranges are inclusive at both
ends. It is REQUIRED that the first element in the range is greater or equal to the last one: backwards ranges are illegal.
In addition to this, although numerical ranges can use any combination of the supported number representation
(meaning `'0 ... 0x10'` is a valid range encompassing all decimal numbers from 0 to 16) it is RECOMMENDED that
the representation used is consistent across the start and end of the range. Finally, ranges can have a character
and a number as either start or end of them, in which case the character is to be interpreted as its character code in decimal
- For readability purposes, it is RECOMMENTED that the grammar text be left aligned and that spaces are used between
- Literal strings MUST be delimited by matching pairs of double or single quotes (character code 34 and 39) and SHOULD be separated
by any other term in the grammar by a space
- Characters inside strings can be escaped using backslashes. For example, to add a literal double quote inside a double-quoted string, one MUST
write `"\""` (without quotes), althoguh it is recommended to use single quotes in this case (i.e. `'"'` instead)
## EBNF Grammar
Below you can find the EBNF specification of peon's grammar.
// Top-level code
program → declaration* EOF; // An entire program (Note: an empty program *is* a valid program)
// Declarations (rules that bind a name to an object in the current scope and produce no side effects)
// A program is composed by a list of declarations
declaration → funDecl | varDecl | coroDecl | statement;
// Function declarations
funDecl → "fn" function;
coroDecl → "coro" function;
// Constants still count as "variable" declarations in the grammar
varDecl → ("var" | "let" | "const") IDENTIFIER ( "=" expression )? COLON;
// Statements (rules that produce side effects, without binding a name. Well, mostly: import, foreach and others do, but they're exceptions to the rule)
statement → exprStmt | ifStmt | returnStmt| whileStmt| blockStmt; // The set of all statements
// Any expression followed by a semicolon is an expression statement
exprStmt → expression COLON;
// Returns from a function, illegal in top-level code. An empty return statement is illegal
// in non-void functions
returnStmt → "return" expression? COLON;
// Defers the evaluation of the given expression right before a function exits, illegal in top-level code.
// Semantically and functionally equivalent to wrapping a function in a big try block and executing the
// expression in the finally block, but less verbose
deferStmt → "defer" expression COLON;
// Breaks out of a loop or named block
breakStmt → "break" IDENTIFIER? COLON;
// Skips to the next iteration in a loop or jumps to the
// beginning of a named block
continueStmt → "continue" IDENTIFIER? COLON;
importStmt -> ("from" IDENTIFIER)? "import" (IDENTIFIER ("as" IDENTIFIER)? ","?)+ COLON; // Imports one or more modules in the current scope. Creates a namespace
assertStmt → "assert" expression COLON;
yieldStmt → "yield" expression? COLON;
// Pauses the execution of the calling coroutine and calls the given coroutine. Execution continues when the callee returns
awaitStmt → "await" expression COLON;
// Exception handling
tryStmt → "try" "{" statement* "}" (except+ "finally" statement | "finally" statement | "else" statement | except+ "else" statement | except+ "else" statement "finally" statement);
// Blocks create a new scope that lasts until they're closed
blockStmt → "{" declaration* "}";
// Named blocks are useful for breaking out of deeply nested loops
namedBlock → "block" IDENTIFIER "{" declaration* "}";
// If statements are conditional jumps
ifStmt → "if" expression "{" statement* "}" ("else" "{" statement* "}")?;
// While loops run until their condition is true
whileStmt → "while" expression "{" statement* "}";
// For-each loops iterate over a collection type
foreachStmt → "foreach" "(" (IDENTIFIER ":" expression) ")" "{" statement* "}";
// Expressions (rules that produce a value and may have side effects)
// Assignment is the highest-level expression
expression → assignment;
assignment → (call ".")? IDENTIFIER ASSIGNTOKENS assignment | lambdaExpr;
lambdaExpr → "lambda" lambda; // Lambdas are anonymous functions, so they act as expressions
yieldExpr → "yield" expression?; // Empty yield equals yield nil
awaitExpr → "await" expression;
logic_or → logic_and ("and" logic_and)*;
logic_and → equality ("or" equality)*;
equality → comparison (("!=" | "==") comparison)*;
comparison → term ((">" | ">=" | "<" | "<=" | "as" | "is" | "of") term)*;
term → factor (("-" | "+") factor)*; // Precedence for + and - in operations
factor → unary (("/" | "*" | "**" | "^" | "&") unary)*; // All other binary operators have the same precedence
unary → ("!" | "-" | "~") unary | call;
slice → expression "[" expression (":" expression){0,2} "]"
call → primary ("(" arguments? ")" | "." IDENTIFIER)*;
// Below are some collection literals: lists, sets, dictionaries and tuples
listExpr → "[" arguments* "]";
// Note: "{}" is an empty dictionary, NOT an empty set
setExpr → "{" arguments? "}";
dictExpr → "{" (expression ":" expression ("," expression ":" expression)*)* "}"; // {key: value, ...}
tupleExpr → "(" arguments* ")";
primary → "nan" | "true" | "false" | "nil" | "inf" | NUMBER | STRING | IDENTIFIER | "(" expression ")" "." IDENTIFIER;
// Utility rules to avoid repetition
function → IDENTIFIER ("(" parameters? ")")? blockStmt;
lambda → ("(" parameters? ")")? blockStmt;
// ident: type [, ident2: type2, ...]
arguments → expression ("," expression)*;
except → ("except" expression? statement)
// These are all the terminals (i.e. productions defined non-recursively)
SINGLEMULTI → QUOTE{3} UNICODE* QUOTE{3}; // Single quoted multi-line strings
DOUBLEMULTI → DOUBLEQUOTE{3} UNICODE* DOUBLEQUOTE{3}; // Double quoted multi-line string
FLOAT → DIGIT+ ("." DIGIT+)? (("e" | "E") DIGIT+)?;
BIN → "0b" ("0" | "1")+;
OCT → "0o" ("0" ... "7")+;
HEX → "0x" ("0" ... "9" | "A" ... "F" | "a" ... "f")+;
IDENTIFIER → ALPHA (ALPHA | DIGIT)*; // Valid identifiers are only alphanumeric!
QUOTE → "'";
IDENTCHARS → "a" ... "z" | "A" ... "Z" | "_";
UNICODE → 0x00 ... 0x10FFFD; // This covers the whole unicode range
DIGIT → "0" ... "9";
ASSIGNTOKENS → "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>=" | "**=" | "//=" | "="

docs/ Normal file
View File

@ -0,0 +1,301 @@
# Peon - Manual
Peon is a statically typed, garbage-collected, C-like programming language with
a focus on speed and correctness, but whose main feature is the ability to natively
perform highly efficient parallel I/O operations by implementing the [structured concurrency](
__Note__: Peon is currently a WIP (Work In Progress), and much of the content of this manual is purely theoretical as
of now. If you want to help make this into a reality, feel free to contribute!
## Table of contents
- [Manual](#peon---manual)
- [Design Goals](#design-goals)
- [Examples](#peon-by-example)
- [Grammar](
- [Bytecode](
## Design Goals
While peon is inspired from Bob Nystrom's [book](, where he describes a simple toy language
named Lox, the aspiration for it is to become a programming language that could actually be used in the real world. For that
to happen, we need:
- Exceptions (`try/except/finally`)
- An import system (with namespaces, like Python)
- Multithreading support (with a global VM lock when GC'ing)
- Built-in collections (list, tuple, set, etc.)
- Coroutines (w/ structured concurrency)
- Generators
- Generics
- C/Nim FFI
- A C backend (for native speed)
- A package manager
Peon ~~steals~~ borrows many ideas from Python, Nim (the the language peon itself is written in), C and many others.
## Peon by Example
Here follow a few examples of peon code to make it clear what the end product should look like. Note that
not all examples represent working functionality and some of these examples might not be up to date either.
For somewhat more updated code snippets, check the [tests](../tests/) directory.
### Variable declarations
var x = 5; # Inferred type is int64
var y = 3'u16; # Type is specified as uint16
x = 6; # Works: type matches
x = 3.0; # Error: Cannot assign float64 to x
var x = 3.14; # Error: cannot re-declare x
const z = 6.28; # Constant declaration
let a = "hi!"; # Cannot be reassigned/mutated
var b: int32 = 5; # Explicit type declaration (TODO)
__Note__: Peon supports [name stropping](, meaning
that almost any ASCII sequence of characters can be used as an identifier, including language
keywords, but stropped names need to be enclosed by matching pairs of backticks (`\``)
### Comments
# This is a single-line comment
# Peon has no specific syntax for multi-line comments.
fn id[T: any](x: T): T {
## Documentation comments start
## with two dashes. They are currently
## unused, but will be semantically
## relevant in the future. They can
## be used to document types, modules
## and functions
return x;
### Functions
fn fib(n: int): int {
if n < 3 {
return n;
return fib(n - 1) + fib(n - 2);
### Type declarations (TODO)
type Foo = object { # Can also be "ref object" for reference types (managed automatically)
fieldOne*: int # Asterisk means the field is public outside the current module
fieldTwo*: int
### Enumeration types (TODO)
type SomeEnum = enum { # Can be mapped to an integer
### Operator overloading
operator `+`(a, b: Foo): Foo {
return Foo(fieldOne: a.fieldOne + b.fieldOne, fieldTwo: a.fieldTwo + b.fieldTwo);
Foo(fieldOne: 1, fieldTwo: 3) + Foo(fieldOne: 2, fieldTwo: 3); # Foo(fieldOne: 3, fieldTwo: 6)
__Note__: Custom operators (e.g. `foo`) can also be defined. The backticks around the plus sign serve to mark it
as an identifier instead of a symbol (which is a requirement for function names, since operators are basically
functions in peon). In fact, even the built-in peon operators are implemented partially in peon (actually, just
their stubs are) and they are then specialized in the compiler to get rid of unnecessary function call overhead.
### Function calls
foo(1, 2 + 3, 3.14, bar(baz));
__Note__: Operators can be called as functions; If their name is a symbol, just wrap it in backticks like so:
`+`(1, 2) # Identical to 1 + 2
__Note__: Code the likes of `a.b()` is (actually, will be) desugared to `b(a)` if there exists a function
`b` whose signature is compatible with the value of `a` (assuming `a` doesn't have a field named `b`,
in which case the attribute resolution takes precedence)
### Generics
fn genericSum[T: Number](a, b: T): T { # Note: "a, b: T" means that both a and b are of type T
return a + b;
# This allows for a single implementation to be
# re-used multiple times without any code duplication
genericSum(1, 2);
genericSum(3.14, 0.1);
genericSum(1'u8, 250'u8);
__Note__: Peon generics are implemented according to a paradigm called [parametric polymorphism]( In constrast to the model employed by other languages such as C++, called [ad hoc polymorphism](,
where each time a generic function is called with a new type signature it is instantiated and
typechecked (and then compiled), peon checks generics at declaration time and only once: this
not only saves precious compilation time, but it also allows the compiler to generate a single
implementation for the function (although this is not a requirement) and catches type errors right
when they occur even if the function is never called, rather than having to wait for the function
to be called and specialized. Unfortunately, this means that some of the things that are possible
in, say, C++ templates are just not possible with peon generics. As an example, take this code snippet:
fn add[T: any](a, b: T): T {
return a + b;
While the intent of this code is clear and makes sense semantically speaking, peon will refuse
to compile it because it cannot prove that the `+` operator is defined on every type (in fact,
it's only defined for numbers): this is a feature. If peon allowed it, `any` could be used to
escape the safety of the type system (for example, calling `add` with `string`s, which may or
may not be what you want).
Since the goal for peon is to not constrain the developer into one specific programming paradigm,
it also implements a secondary, different, generic mechanism using the `auto` type. The above code
could be rewritten to work as follows:
fn add(a, b: auto): auto {
return a + b;
When using automatic types, peon will behave similarly to C++ (think: templates) and only specialize,
typecheck and compile the function once it is called with a given type signature. For this reason,
automatic and parametrically polymorphic types cannot be used together in peon code.
Another noteworthy concept to keep in mind is that of type unions. For example, take this snippet:
fn foo(x: int32): int32 {
return x;
fn foo(x: int): int {
return x;
fn identity[T: int | int32](x: T): T {
return foo(x);
This code will, again, fail to compile: this is because as far as peon is concerned, `foo` is not
defined for both `int` and `int32` _at the same time_. In order for that to work, `foo` would need
to be rewritten with `T: int32 | int` as its generic argument type in order to avoid the ambiguity
(or `identity` could be rewritten to use automatic types instead, both are viable options). Obviously,
the above snippet would fail to compile if `foo` were not defined for all the types specified in the
type constraint for `identity` as well (this is because, counterintuitively, matching a generic constraint
such as `int32 | int` does _not_ mean "either of these types", but rather "_both_ of these types at
#### More generics
fn genericSth[T: someTyp, K: someTyp2](a: T, b: K) { # Note: no return type == void function
# code...
genericSth(1, 3.0);
#### Even more generics
type Box*[T: Number] = object {
num: T;
var boxFloat = Box[float](1.0);
var boxInt = Box[int](1);
__Note__: The `*` modifier to make a name visible outside the current module must be put
__before__ the generic constraints, so only `fn foo*[T](a: T) {}` is the correct syntax.
### Forward declarations
fn someF: int; # Semicolon and no body == forward declaration
print(someF()); # Prints 42
fn someF: int {
return 42;
__Note__: A function that is forward-declared __must__ be implemented in the same module as
the forward declaration.
### Generators
generator count(n: int): int {
while n > 0 {
yield n;
n -= 1;
foreach n in count(10) {
### Coroutines
import concur;
import http;
coroutine req(url: string): string {
return (await http.AsyncClient().get(url)).content;
coroutine main(urls: list[string]) {
pool = concur.pool(); # Creates a task pool: like a nursery in njsmith's article
foreach url in urls {
pool.spawn(req, urls);
# The pool has internal machinery that makes the parent
# task wait until all child exit! When this function
# returns, ALL child tasks will have exited somehow.
# Exceptions and return values propagate neatly, too.
}, newList[string]("", ""))

nim.cfg Normal file
View File

@ -0,0 +1 @@

src/backend/bytecode/vm.nim Normal file

File diff suppressed because it is too large Load Diff

src/config.nim Normal file
View File

@ -0,0 +1,81 @@
# Copyright 2022 Mattia Giambirtone & All Contributors
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# See the License for the specific language governing permissions and
# limitations under the License.
import std/strformat
import std/os
# These variables can be tweaked to debug and test various components of the toolchain
var debugLexer* = false # Print the tokenizer's output
var debugParser* = false # Print the AST generated by the parser
var debugCompiler* = false # Disassemble and/or print the code generated by the compiler
const debugVM* {.booldefine.} = false # Enable the runtime debugger in the bytecode VM
const debugGC* {.booldefine.} = false # Debug the Garbage Collector (extremely verbose)
const debugAlloc* {.booldefine.} = false # Trace object allocation (extremely verbose)
const debugMem* {.booldefine.} = false # Debug the memory allocator (extremely verbose)
var debugSerializer* = false # Validate the bytecode serializer's output
const debugStressGC* {.booldefine.} = false # Make the GC run a collection at every allocation (VERY SLOW!)
const debugMarkGC* {.booldefine.} = false # Trace the marking phase object by object (extremely verbose)
const PeonBytecodeMarker* = "PEON_BYTECODE" # Magic value at the beginning of bytecode files
const HeapGrowFactor* = 2 # The growth factor used by the GC to schedule the next collection
const FirstGC* = 1024 * 1024; # How many bytes to allocate before running the first GC
const enableVMChecks* {.booldefine.} = true; # Enables all types of compiler (nim-wise) checks in the VM
# List of paths where peon looks for modules, in order (empty path means current directory, which always takes precedence)
const moduleLookupPaths*: seq[string] = @["", "src/peon/stdlib", absolutePath(joinPath(".local", "peon", "stdlib"), getenv("HOME"))]
when HeapGrowFactor <= 1:
{.fatal: "Heap growth factor must be > 1".}
const PeonVersion* = (major: 0, minor: 1, patch: 0)
const PeonRelease* = "alpha"
const PeonCommitHash* = staticExec("git rev-parse HEAD")
const PeonBranch* = staticExec("git symbolic-ref HEAD 2>/dev/null | cut -f 3 -d /")
const PeonVersionString* = &"Peon {PeonVersion.major}.{PeonVersion.minor}.{PeonVersion.patch} {PeonRelease} ({PeonBranch}, {CompileDate}, {CompileTime}, {PeonCommitHash[0..PeonCommitHash.high() mod 8]}) [Nim {NimVersion}] on {hostOS} ({hostCPU})"
const HelpMessage* = """The peon programming language, Copyright (C) 2023 Mattia Giambirtone & All Contributors
This program is free software, see the license distributed with this program or check for more info.
Basic Usage
$ peon Run the given Peon source file
$ peon file.pbc Run the given Peon bytecode file
-h, --help Show this help text and exit
-v, --version Print the current peon version and exit
-s, --string Execute the passed string as if it was a file
-n, --noDump Don't dump the result of compilation to a file.
Note that no dump is created when using -s/--string
-b, --breakpoints Run the debugger at specific bytecode offsets (comma-separated).
Only available with --target:bytecode and when compiled with VM
debugging on (-d:debugVM at build time)
-d, --disassemble Disassemble the output of compilation (only makes sense with --target:bytecode)
-m, --mode Set the compilation mode. Acceptable values are 'debug' and
'release'. Defaults to 'debug'
-c, --compile Compile the code, but do not execute it. Useful along with -d
-w, --warnings Turn warnings on or off (default: on). Acceptable values are
yes/on and no/off
--noWarn Disable a specific warning (for example, --noWarn:unusedVariable)
--showMismatches Show all mismatches when function dispatching fails (output is really verbose)
--target Select the compilation target (valid values are: 'c' and 'bytecode'). Defaults to
-o, --output Rename the output file with this value (with --target:bytecode, a '.pbc' extension
is added if not already present)
--debug-dump Debug the bytecode serializer. Only makes sense with --target:bytecode
--debug-lexer Show the lexer's output
--debug-parser Show the parser's output

src/errors.nim Normal file
View File

@ -0,0 +1,21 @@
# Copyright 2022 Mattia Giambirtone & All Contributors
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# See the License for the specific language governing permissions and
# limitations under the License.
PeonException* = ref object of CatchableError
## A Nim exception for a generic internal
## peon failure (not to be used directly)
file*: string # The file where the error occurred
line*: int # The line where the error occurred

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,71 @@
# Copyright 2022 Mattia Giambirtone & All Contributors
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# See the License for the specific language governing permissions and
# limitations under the License.
## The code generator for translating peon to C code
import std/tables
import std/strformat
import std/algorithm
import std/parseutils
import std/strutils
import std/sequtils
import std/sets
import std/os
import frontend/compiler/compiler
import frontend/parsing/lexer
import frontend/parsing/parser
import frontend/parsing/ast
CompilerFunc = object
## An internal compiler function called
## by pragmas
kind: PragmaKind
handler: proc (self: NativeCCompiler, pragma: Pragma, name: Name)
NativeCCompiler* = ref object of Compiler
## The peon to C compiler
# Compiler procedures called by pragmas
compilerProcs: TableRef[string, CompilerFunc]
proc newNativeCCompiler*(replMode: bool = false): NativeCCompiler =
## Initializes a new, blank, NativeCCompiler
## object
result.ast = @[]
result.current = 0
result.file = ""
result.names = @[]
result.depth = 0
result.lines = @[]
result.currentFunction = nil
result.replMode = replMode
result.currentModule = nil
result.compilerProcs = newTable[string, CompilerFunc]()
result.source = ""
result.lexer = newLexer()
result.parser = newParser()
result.isMainModule = false
result.disabledWarnings = @[]
method literal*(self: Compiler, node: ASTNode, compile: bool = true): Type {.discardable.} =
## Compiles literal expressions

View File

@ -0,0 +1,849 @@
# Copyright 2022 Mattia Giambirtone & All Contributors
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# See the License for the specific language governing permissions and
# limitations under the License.
## An Abstract Syntax Tree (AST) structure for our recursive-descent
## top-down parser. For more info, check out docs/
import std/strformat
import std/strutils
import token
export token
NodeKind* = enum
## Enumeration of the AST
## node types, sorted by
## precedence
# Declarations
typeDecl = 0'u8
# Statements
# An expression followed by a semicolon
# Expressions
setItemExpr, # Set expressions like a.b = "c"
getItemExpr, # Get expressions like a.b
# Primary expressions
groupingExpr, # Parenthesized expressions such as (true) and (3 + 4)
identExpr, # Identifier
# Here I would've rather used object variants, and in fact that's what was in
# place before, but not being able to re-declare a field of the same type in
# another case branch is kind of a deal breaker long-term, so until that is
# fixed (check out for more info).
# I'll stick to using inheritance instead
# Generic AST node types
ASTNode* = ref object of RootObj
## An AST node
kind*: NodeKind
# Regardless of the type of node, we keep the token in the AST node for internal usage.
# This is not shown when the node is printed, but makes it a heck of a lot easier to report
# errors accurately even deep in the compilation pipeline
token*: Token
file*: string
# This weird inheritance chain is needed for the parser to
# work properly
Declaration* = ref object of ASTNode
## A declaration
isPrivate*: bool
pragmas*: seq[Pragma]
generics*: seq[tuple[name: IdentExpr, cond: Expression]]
Statement* = ref object of Declaration
## A statement
Expression* = ref object of Statement
## An expression
LiteralExpr* = ref object of Expression
# Using a string for literals makes it much easier to handle numeric types, as
# there is no overflow nor underflow or float precision issues during parsing.
# Numbers are just serialized as strings and then converted back to numbers
# before being passed to the VM, which also keeps the door open in the future
# to implementing bignum arithmetic that can take advantage of natively supported
# machine types, meaning that if a numeric type fits into a 64 bit signed/unsigned
# int then it is stored in such a type to save space, otherwise it is just converted
# to a bigint. Bigfloats with arbitrary-precision arithmetic would also be nice,
# although arguably less useful (and probably significantly slower than bigints)
literal*: Token
IntExpr* = ref object of LiteralExpr
OctExpr* = ref object of LiteralExpr
HexExpr* = ref object of LiteralExpr
BinExpr* = ref object of LiteralExpr
FloatExpr* = ref object of LiteralExpr
StrExpr* = ref object of LiteralExpr
CharExpr* = ref object of LiteralExpr
TrueExpr* = ref object of LiteralExpr
FalseExpr* = ref object of LiteralExpr
IdentExpr* = ref object of Expression
name*: Token
depth*: int
GroupingExpr* = ref object of Expression
expression*: Expression
GetItemExpr* = ref object of Expression
obj*: Expression
name*: IdentExpr
SetItemExpr* = ref object of GetItemExpr
# Since a setItem expression is just
# a getItem one followed by an assignment,
# inheriting it from getItem makes sense
value*: Expression
CallExpr* = ref object of Expression
callee*: Expression # The object being called
arguments*: tuple[positionals: seq[Expression], keyword: seq[tuple[
name: IdentExpr, value: Expression]]]
closeParen*: Token # Needed for error reporting
GenericExpr* = ref object of Expression
ident*: IdentExpr
args*: seq[Expression]
UnaryExpr* = ref object of Expression
operator*: Token
a*: Expression
BinaryExpr* = ref object of UnaryExpr
# Binary expressions can be seen here as unary
# expressions with an extra operand so we just
# inherit from that and add a second operand
b*: Expression
YieldExpr* = ref object of Expression
expression*: Expression
AwaitExpr* = ref object of Expression
expression*: Expression
LambdaExpr* = ref object of Expression
body*: Statement
arguments*: seq[tuple[name: IdentExpr, valueType: Expression]]
defaults*: seq[Expression]
isGenerator*: bool
isAsync*: bool
isPure*: bool
returnType*: Expression
depth*: int
SliceExpr* = ref object of Expression
expression*: Expression
ends*: seq[Expression]
AssignExpr* = ref object of Expression
name*: IdentExpr
value*: Expression
ExprStmt* = ref object of Statement
expression*: Expression
ImportStmt* = ref object of Statement
moduleName*: IdentExpr
ExportStmt* = ref object of Statement
name*: IdentExpr
AssertStmt* = ref object of Statement
expression*: Expression
RaiseStmt* = ref object of Statement
exception*: Expression
BlockStmt* = ref object of Statement
code*: seq[Declaration]
NamedBlockStmt* = ref object of BlockStmt
name*: IdentExpr
ForStmt* = ref object of Statement
discard # Unused
ForEachStmt* = ref object of Statement
identifier*: IdentExpr
expression*: Expression
body*: Statement
WhileStmt* = ref object of Statement
condition*: Expression
body*: BlockStmt
AwaitStmt* = ref object of Statement
expression*: Expression
BreakStmt* = ref object of Statement
label*: IdentExpr
ContinueStmt* = ref object of Statement
label*: IdentExpr
ReturnStmt* = ref object of Statement
value*: Expression
IfStmt* = ref object of Statement
condition*: Expression
thenBranch*: Statement
elseBranch*: Statement
YieldStmt* = ref object of Statement
expression*: Expression
VarDecl* = ref object of Declaration
name*: IdentExpr
value*: Expression
isConst*: bool
isLet*: bool
valueType*: Expression
FunDecl* = ref object of Declaration
name*: IdentExpr
body*: Statement
arguments*: seq[tuple[name: IdentExpr, valueType: Expression]]
defaults*: seq[Expression]
isAsync*: bool
isGenerator*: bool
isPure*: bool
returnType*: Expression
depth*: int
TypeDecl* = ref object of Declaration
name*: IdentExpr
# Empty if type is an enum
fields*: seq[tuple[name: IdentExpr, valueType: Expression, isPrivate: bool]]
# Empty if type is a structure
members*: seq[TypeDecl]
isEnum*: bool
isRef*: bool
parent*: Expression
value*: Expression
Pragma* = ref object of Expression
name*: IdentExpr
args*: seq[LiteralExpr]
Var* = ref object of Expression
value*: Expression
Ref* = ref object of Expression
value*: Expression
Ptr* = ref object of Expression
value*: Expression
Lent* = ref object of Expression
value*: Expression
SwitchStmt* = ref object of Statement
switch*: Expression
branches*: seq[tuple[cond: Expression, body: BlockStmt]]
default*: BlockStmt
proc isConst*(self: ASTNode): bool =
## Returns true if the given
## AST node represents a value
## of constant type. All integers,
## strings and singletons count as
## constants
case self.kind:
of intExpr, hexExpr, binExpr, octExpr, strExpr, falseExpr, trueExpr,
return true
return false
## AST node constructors
proc newASTNode*(kind: NodeKind, token: Token): ASTNode =
## Initializes a new generic ASTNode object
result.kind = kind
result.token = token
proc newPragma*(name: IdentExpr, args: seq[LiteralExpr]): Pragma =
result.kind = pragmaExpr
result.args = args = name
result.token = name.token
proc newRefExpr*(expression: Expression, token: Token): Ref =
result.kind = refExpr
result.value = expression
result.token = token
proc newPtrExpr*(expression: Expression, token: Token): Ptr =
result.kind = ptrExpr
result.value = expression
result.token = token
proc newLentExpr*(expression: Expression, token: Token): Lent =
result.kind = lentExpr
result.value = expression
result.token = token
proc newSwitchStmt*(switch: Expression, branches: seq[tuple[cond: Expression, body: BlockStmt]], default: BlockStmt, token: Token): SwitchStmt =
result.kind = switchStmt
result.switch = switch
result.branches = branches
result.token = token
result.default = default
proc newIntExpr*(literal: Token): IntExpr =
result = IntExpr(kind: intExpr)
result.literal = literal
result.token = literal
proc newOctExpr*(literal: Token): OctExpr =
result = OctExpr(kind: octExpr)
result.literal = literal
result.token = literal
proc newHexExpr*(literal: Token): HexExpr =
result = HexExpr(kind: hexExpr)
result.literal = literal
result.token = literal
proc newBinExpr*(literal: Token): BinExpr =
result = BinExpr(kind: binExpr)
result.literal = literal
result.token = literal
proc newFloatExpr*(literal: Token): FloatExpr =
result = FloatExpr(kind: floatExpr)
result.literal = literal
result.token = literal
proc newTrueExpr*(token: Token): LiteralExpr = LiteralExpr(kind: trueExpr,
token: token, literal: token)
proc newFalseExpr*(token: Token): LiteralExpr = LiteralExpr(kind: falseExpr,
token: token, literal: token)
proc newStrExpr*(literal: Token): StrExpr =
result = StrExpr(kind: strExpr)
result.literal = literal
result.token = literal
proc newCharExpr*(literal: Token): CharExpr =
result = CharExpr(kind: charExpr)
result.literal = literal
result.token = literal
proc newIdentExpr*(name: Token, depth: int = 0): IdentExpr =
result = IdentExpr(kind: identExpr) = name
result.token = name
result.depth = depth
proc newGroupingExpr*(expression: Expression, token: Token): GroupingExpr =
result = GroupingExpr(kind: groupingExpr)
result.expression = expression
result.token = token
proc newLambdaExpr*(arguments: seq[tuple[name: IdentExpr, valueType: Expression]], defaults: seq[Expression],
body: Statement, isAsync, isGenerator: bool,
token: Token, depth: int, pragmas: seq[Pragma] = @[],
returnType: Expression, generics: seq[tuple[name: IdentExpr, cond: Expression]] = @[]): LambdaExpr =
result = LambdaExpr(kind: lambdaExpr)
result.body = body
result.arguments = arguments
result.defaults = defaults
result.isGenerator = isGenerator
result.isAsync = isAsync
result.token = token
result.returnType = returnType
result.isPure = false
result.pragmas = pragmas
result.generics = generics
result.depth = depth
proc newGetItemExpr*(obj: Expression, name: IdentExpr,
token: Token): GetItemExpr =
result = GetItemExpr(kind: getItemExpr)
result.obj = obj = name
result.token = token
proc newSetItemExpr*(obj: Expression, name: IdentExpr, value: Expression,
token: Token): SetItemExpr =
result = SetItemExpr(kind: setItemExpr)
result.obj = obj = name
result.value = value
result.token = token
proc newCallExpr*(callee: Expression, arguments: tuple[positionals: seq[
Expression], keyword: seq[tuple[name: IdentExpr, value: Expression]]],
token: Token): CallExpr =
result = CallExpr(kind: callExpr)
result.callee = callee
result.arguments = arguments
result.token = token
proc newGenericExpr*(ident: IdentExpr, args: seq[Expression]): GenericExpr =
result = GenericExpr(kind: genericExpr)
result.ident = ident
result.args = args
result.token = ident.token
proc newSliceExpr*(expression: Expression, ends: seq[Expression], token: Token): SliceExpr =
result = SliceExpr(kind: sliceExpr)
result.expression = expression
result.ends = ends
result.token = token
proc newUnaryExpr*(operator: Token, a: Expression): UnaryExpr =
result = UnaryExpr(kind: unaryExpr)
result.operator = operator
result.a = a
result.token = result.operator
proc newBinaryExpr*(a: Expression, operator: Token, b: Expression): BinaryExpr =
result = BinaryExpr(kind: binaryExpr)
result.operator = operator
result.a = a
result.b = b
result.token = operator
proc newYieldExpr*(expression: Expression, token: Token): YieldExpr =
result = YieldExpr(kind: yieldExpr)