79 Commits

Author SHA1 Message Date
1ade6cae50 Mention vsc extension 2022-02-11 13:31:48 +01:00
3e4ed82dc4 Update README 2022-02-11 13:04:45 +01:00
e5edc6b2ba Fix UB non top-level functions 2022-02-11 13:00:41 +01:00
f4286db21d Remove anyhow dependency 2022-02-11 12:36:36 +01:00
3892ea46e0 Update examples 2022-02-11 01:19:45 +01:00
8b7ed96e15 Update nice_panic macro 2022-02-11 01:19:34 +01:00
67b07dfd72 Fix typo 2022-02-11 01:01:31 +01:00
6c0867143b Add toc to README 2022-02-11 00:12:36 +01:00
abefe32300 Update README 2022-02-10 23:02:40 +01:00
742d6706b0 Array values are now pass-by-reference 2022-02-10 21:27:05 +01:00
3806a61756 Allow endless loops with no condition 2022-02-10 20:36:26 +01:00
2880ba81ab Implement break & continue
- Fix return propagation inside loops
2022-02-10 13:13:15 +01:00
4e92a416ed Improve CLI
- Remove unused flags
- Show more helpful error messages
2022-02-10 12:58:09 +01:00
c1bee69fa6 Simplify general program tests 2022-02-10 12:24:20 +01:00
f2331d7de9 Add general test for functions as example 2022-02-10 12:19:01 +01:00
c4d2f89d35 Fix function args 2022-02-10 12:13:30 +01:00
ab059ce18c Add recursive fibonacci as test 2022-02-10 01:32:07 +01:00
aeedfb4ef2 Implement functions
- Implement function declaration and call
- Change the precalculated variable stack positions to contain the
  offset from the end instead of the absolute position. This is
  important for passing fun args on the stack
- Add the ability to offset the stackframes. This is used to delete the
  stack where the fun args have been stored before the block executes
- Implement exit type for blocks in interpreter. This is used to get the
  return values and propagate them where needed
- Add recursive fibonacci examples
2022-02-10 01:26:11 +01:00
f0c2bd8dde Remove panics from interpreter, worse performance
- Replaced the interpreters panics with actual errors and results
- Added a few extra checks for arrays and div-by-zero
- These changes significantly reduced runtime performance, even without
  the extra checks
2022-02-09 18:18:21 +01:00
421fbbc873 Update euler5 example 2022-02-09 17:12:47 +01:00
383da4ae05 Rewrite declaration as statement instead of binop
- Declarations are now separate statements
- Generate unknown var errors when vars are not declared
- Replace Peekable by new custom PutBackIter type that allows for
  unlimited putback and therefore look-ahead
2022-02-09 16:54:06 +01:00
7ea5f67f9c Cleaner unop parsing 2022-02-09 14:23:24 +01:00
235eb460dc Replace panics with errors in parser 2022-02-09 13:49:14 +01:00
2312deec5b Small refactoring for parser 2022-02-09 01:13:22 +01:00
948d41fb45 Update lexer tests 2022-02-09 00:20:56 +01:00
fdef796440 Update token macros 2022-02-08 23:26:23 +01:00
926bdeb2dc Refactor lexer match loop 2022-02-08 22:54:41 +01:00
726dd62794 Big token refactoring
- Extract keywords, literals and combo tokens into separate sub-enums
- Add a macro for quickly generating all tokens including the sub-enum
  tokens. This also takes less chars to write
2022-02-08 18:56:17 +01:00
c723b1c2cb Rename var in parser 2022-02-06 15:31:41 +01:00
e7b67d85a9 Add game of life example 2022-02-05 11:53:01 +01:00
cf2e5348bb Implement arrays 2022-02-04 18:48:45 +01:00
8b67c4d59c Implement block scopes (code inside braces)
- Putting code in between braces will create a new scope
2022-02-04 17:30:23 +01:00
cbf31fa513 Implement simple AST optimizer
- Precalculate operations only containing literals
2022-02-04 17:06:38 +01:00
56665af233 Update examples 2022-02-04 14:25:25 +01:00
22634af554 Precalculate stack positions for variables
- Parser calculates positions for the variables
- This removes the lookup time during runtime
- Consistent high performance
2022-02-04 14:25:25 +01:00
d4c6f3d5dc Implement string interning 2022-02-04 14:25:23 +01:00
4dbc3adfd5 Refactor Ast to ScopedBlock 2022-02-04 14:24:03 +01:00
cbea567d65 Implement vec based scopes
- Replaced vartable hashmap with vec
- Use linear search in reverse to find the variables by name
- This is really fast with a small number of variables but tanks fast
  with more vars due to O(n) lookup times
- Implemented scopes by dropping all elements from the vartable at the
  end of a scope
2022-02-04 14:24:00 +01:00
e4977da546 Use euler examples as tests 2022-02-04 12:45:34 +01:00
588b3b5b2c Autoformat 2022-02-03 17:38:25 +01:00
f6152670aa Small refactor for lexer 2022-02-03 17:25:55 +01:00
c2b9ee71b8 Add project euler example 5 2022-02-03 16:16:38 +01:00
f8e5bd7423 Add comments to parser 2022-02-03 16:01:33 +01:00
d7001a5c52 Refactor, Comments, Bugfix for lexer
- Small refactoring in the lexer
- Added some more comments to the lexer
- Fixed endless loop when encountering comment in last line
2022-02-03 00:44:48 +01:00
bc68d9fa49 Add Result + Err to lexer 2022-02-02 21:59:46 +01:00
264d8f92f4 Update README 2022-02-02 19:40:10 +01:00
d8f5b876ac Implement String Literals
- String literals can be stored in variables, but are fully immutable
  and are not compatible with any operators
2022-02-02 19:38:28 +01:00
8cf6177cbc Update README 2022-02-02 19:15:20 +01:00
39bd4400b4 Implement logical not 2022-02-02 19:14:11 +01:00
75b99869d4 Rework README
- Add full language description
- Fix variable name inconsistency
2022-02-02 19:00:14 +01:00
de0bbb8171 Implement logical and / or 2022-02-02 18:56:45 +01:00
92f59cbf9a Update README 2022-02-02 16:48:26 +01:00
dd9ca660cc Move ast into separate file 2022-02-02 16:43:14 +01:00
7e2ef49481 Move token into separate file 2022-02-02 16:40:05 +01:00
86130984e2 Add example programs (project euler) 2022-02-02 16:26:37 +01:00
c4b146c325 Refactor interpreter to use borrowed Ast
- Should have been like this from the start
- About 9x performance increase
2022-02-02 16:24:42 +01:00
7b6fc89fb7 Implement if 2022-02-02 16:19:46 +01:00
8c9756b6d2 Implement print keyword 2022-02-02 14:05:58 +01:00
02993142df Update README 2022-01-31 23:49:22 +01:00
3348b7cf6d Implement loop keyword
- Loop is a combination of `while` and `for`
- `loop cond { }` acts exactly like `while`
- `loop cond; advance { }` acts like `for` without init
2022-01-31 16:58:46 +01:00
3098dc7e0a Implement simple CLI
- Implement running files
- Implement interactive mode
- Enable printing tokens & ast with flags
2022-01-31 16:24:25 +01:00
e0c00019ff Implement line comments 2022-01-29 23:29:09 +01:00
35fbae8ab9 Implement multi statement code
- Add statements
- Add mandatory semicolons after statements
2022-01-29 23:18:15 +01:00
23d336d63e Implement variables
- Assignment
- Declaration
- Identifier lexing
2022-01-29 22:49:15 +01:00
39351e1131 Slightly refactor lexer 2022-01-29 21:59:48 +01:00
b7872da3ea Move grammar def. to README 2022-01-29 21:54:05 +01:00
5cc89b855a Update grammar 2022-01-29 21:52:31 +01:00
32e4f1ea4f Implement relational binops 2022-01-29 21:48:55 +01:00
b664297c73 Implement comparison binops 2022-01-29 21:37:44 +01:00
ea60f17647 Implement bitwise not 2022-01-29 21:26:14 +01:00
5ffa0ea2ec Update README 2022-01-29 21:18:08 +01:00
2a59fe8c84 Implement unary negate 2022-01-29 21:12:01 +01:00
8f79440219 Update README 2022-01-29 20:52:30 +01:00
128b05b8a8 Implement parenthesis grouping 2022-01-29 20:51:55 +01:00
a9ee8eb66c Update grammar definition 2022-01-28 14:00:51 +01:00
5c7b6a7b41 Update README 2022-01-28 12:20:59 +01:00
a569781691 Implement more operators
- Mod
- Bitwise Or
- Bitwise And
- Bitwise Xor
- Shift Left
- Shift Right
2022-01-27 23:15:16 +01:00
0b75c30784 Implement div & sub 2022-01-27 22:29:06 +01:00
ed2ae144dd Number separator _ 2022-01-27 21:38:58 +01:00
25 changed files with 2666 additions and 1120 deletions

View File

@@ -4,3 +4,4 @@ version = "0.1.0"
edition = "2021"
[dependencies]
thiserror = "1.0.30"

420
README.md
View File

@@ -1,38 +1,391 @@
# NEK-Lang
## Table of contents
- [NEK-Lang](#nek-lang)
- [Table of contents](#table-of-contents)
- [Variables](#variables)
- [Declaration](#declaration)
- [Assignment](#assignment)
- [Datatypes](#datatypes)
- [I64](#i64)
- [String](#string)
- [Array](#array)
- [Expressions](#expressions)
- [General](#general)
- [Mathematical Operators](#mathematical-operators)
- [Bitwise Operators](#bitwise-operators)
- [Logical Operators](#logical-operators)
- [Equality & Relational Operators](#equality--relational-operators)
- [Control-Flow](#control-flow)
- [Loop](#loop)
- [If / Else](#if--else)
- [Block Scopes](#block-scopes)
- [Functions](#functions)
- [Function definition](#function-definition)
- [Function calls](#function-calls)
- [IO](#io)
- [Print](#print)
- [Comments](#comments)
- [Line comments](#line-comments)
- [Feature Tracker](#feature-tracker)
- [High level Components](#high-level-components)
- [Language features](#language-features)
- [Parsing Grammar](#parsing-grammar)
- [Expressions](#expressions-1)
- [Statements](#statements)
- [Examples](#examples)
- [Extras](#extras)
- [Visual Studio Code Language Support](#visual-studio-code-language-support)
## Variables
The variables are all contained in scopes. Variables defined in an outer scope can be accessed in
inner scoped. All variables defined in a scope that has ended do no longer exist and can't be
accessed.
### Declaration
- Declare and initialize a new variable
- Declaring a previously declared variable again is currently equivalent to an assignment
- Declaration is needed before assignment or other usage
- The variable name is on the left side of the `<-` operator
- The assigned value is on the right side and can be any expression
```
a <- 123;
```
Create a new variable named `a` and assign the value `123` to it.
### Assignment
- Assigning a value to a previously declared variable
- The variable name is on the left side of the `=` operator
- The assigned value is on the right side and can be any expression
```
a = 123;
```
The value `123` is assigned to the variable named `a`. `a` needs to be declared before this.
## Datatypes
The available variable datatypes are `i64` (64-bit signed integer), `string` (`"this is a string"`) and `array` (`[10]`)
### I64
- The normal default datatype is `i64` which is a 64-bit signed integer
- Can be created by just writing an integer literal like `546`
- Inside the number literal `_` can be inserted for visual separation `100_000`
- The i64 values can be used as expected in calculations, conditions and so on
-
```
my_i64 <- 123_456;
```
### String
- Strings mainly exist for formatting the text output of a program
- Strings can be created by using doublequotes like in other languages `"Hello world"`
- There is no way to access or change the characters of the string
- Unicode characters are supported `"Hello 🌎"`
- Escape characters `\n`, `\r`, `\t`, `\"`, `\\` are supported
- String can still be assigned to variables, just like i64
```
world <- "🌎";
print "Hello ";
print world;
print "\n";
```
### Array
- Arrays can contain any other datatypes and don't need to have the same type in all cells
- Arrays can be created by using brackets with the size in between `[size]`
- Arrays must be assigned to a variable to be used
- All cells will be initialized with i64 0 values
- The size can be any expression that results in a positive i64 value
- The array size can't be changed after creation
- The arrays data is always allocated on the heap
- The array cells can be accessed by using the variable name and brackets `my_arr[index]`
- The index can be any expression that results in a positive i64 value in the range of the arrays
indices
- The indices start with 0
- When an array is passed to a function, it is passed by reference
```
width <- 5;
heigt <- 5;
// Initialize array of size 25 with 25x 0
my_array = [width * height];
// Modify first value
my_array[0] = 5;
// Print first value
print my_array[0];
```
## Expressions
The operator precedence is the same order as in `C` for all implemented operators.
Refer to the
[C Operator Precedence Table](https://en.cppreference.com/w/c/language/operator_precedence)
to see the different precedences.
### General
- Parentheses `(` and `)` can be used to modify evaluation oder just like in any other
programming language.
- For example `(a + b) * c` will evaluate the addition before the multiplication, despite the multiplication having higher binding power
### Mathematical Operators
Supported mathematical operations:
- Addition `a + b`
- Subtraction `a - b`
- Multiplication `a * b`
- Division `a / b`
- Modulo `a % b`
- Negation `-a`
### Bitwise Operators
- And `a & b`
- Or `a | b`
- Xor `a ^ b`
- Bitshift left (by `b` bits) `a << b`
- Bitshift right (by `b` bits) `a >> b`
- "Bit flip" (One's complement) `~a`
### Logical Operators
The logical operators evaluate the operands as `false` if they are equal to `0` and `true` if they are not equal to `0`
- And `a && b`
- Or `a || b`
- Not `!a` (if `a` is equal to `0`, the result is `1`, otherwise the result is `0`)
### Equality & Relational Operators
The equality and relational operations result in `1` if the condition is evaluated as `true` and in `0` if the condition is evaluated as `false`.
- Equality `a == b`
- Inequality `a != b`
- Greater than `a > b`
- Greater or equal than `a >= b`
- Less than `a < b`
- Less or equal than `a <= b`
## Control-Flow
For conditions like in if or loops, every non zero value is equal to `true`, and `0` is `false`.
### Loop
- The `loop` keyword can be used as an infinite loop, as a while loop or as a while loop with advancement (an expression that is executed after the loop body)
- If only `loop` is used, directly followed by the body, it is an infinite loop that needs to be
terminated by using the `break` keyword
- The `loop` keyword is followed by the condition (an expression) without needing parentheses
- *Optional:* If there is a `;` after the condition, there must be another expression which is used as the advancement
- The loops body is wrapped in braces (`{ }`) just like in C/C++
- The `continue` keyword can be used to end the current loop iteration early
- The `break` keyword can be used to fully break out of the current loop
```
// Print the numbers from 0 to 9
// With endless loop
i <- 0;
loop {
if i >= 10 {
break;
}
print i;
i = i + 1;
}
// Without advancement
i <- 0;
loop i < 10 {
print i;
i = i + 1;
}
// With advancement
k <- 0;
loop k < 10; k = k + 1 {
print k;
}
```
### If / Else
- The language supports `if` and an optional `else`
- After the `if` keyword must be the deciding condition, parentheses are not needed
- The block *if-true* block is wrapped in braces (`{ }`)
- *Optional:* If there is an `else` after the *if-block*, there must be a following *if-false*, aka. else block
```
a <- 1;
b <- 2;
if a == b {
// a is equal to b
print 1;
} else {
// a is not equal to b
print 0;
}
```
### Block Scopes
- It is possible to create a limited scope for local variables that will no longer exist once the
scope ends
- Shadowing variables by redefining a variable in an inner scope is supported
```
var_in_outer_scope <- 5;
{
var_in_inner_scope <- 3;
// Inner scope can access both vars
print var_in_outer_scope;
print var_in_inner_scope;
}
// Outer scope is still valid
print var_in_outer_scope;
// !!! THIS DOES NOT WORK !!!
// The inner scope has ended
print var_in_inner_scope;
```
## Functions
### Function definition
- Functions can be defined by using the `fun` keyword, followed by the function name and the
parameters in parentheses. After the parentheses, the body is specified inside a braces block
- The function parameters are specified by only the names
- The function body has its own scope
- Parameters are only accessible inside the body
- Variables from the outer scope can be accessed and modified if the are defined before the function
- Variables from the outer scope are shadowed by parameters with the same name
- The `return` keyword can be used to return a value from the function and exit it immediately
- If no return is specified, a `void` value is returned
- Functions can only be defined at the top-level. So defining a function inside of any other scoped
block (like inside another function, if, loop, ...) is invalid
- Functions can only be used after definition and there is no forward declaration right now
- However a function can be called recursively inside of itself
- Functions can't be redefined, so defining a function with an existing name is invalid
```
fun add_maybe(a, b) {
if a < 100 {
return a;
} else {
return a + b;
}
}
fun println(val) {
print val;
print "\n";
}
```
### Function calls
- Function calls are primary expressions, so they can be directly used in calculations (if they
return appropriate values)
- Function calls are performed by writing the function name, followed by the arguments in parentheses
- The arguments can be any expressions, separated by commas
```
b <- 100;
result <- add_maybe(250, b);
// Prints 350 + new-line
println(result);
```
## IO
### Print
Printing is implemented via the `print` keyword
- The `print` keyword is followed by an expression, the value of which will be printed to the terminal.
- Print currently automatically adds a linebreak
```
a <- 1;
// Outputs `"1"` to the terminal
print a;
```
## Comments
### Line comments
Line comments can be initiated by using `//`
- Everything after `//` up to the end of the current line is ignored and not parsed
```
// This is a comment
```
# Feature Tracker
## High level Components
- [x] Lexer: Transforms text into Tokens
- [x] Parser: Transforms Tokens into Abstract Syntax Tree
- [x] Interpreter (tree-walk-interpreter): Walks the tree and evaluates the expressions / statements
- [ ] Abstract Syntax Tree Optimizer
- [x] Simple optimizer: Apply trivial optimizations to the Ast
- [x] Precalculate binary ops / unary ops that have only literal operands
## Language features
- [x] Math expressions
- [x] Unary operators
- [x] Negate `-X`
- [x] Parentheses `(X+Y)*Z`
- [x] General expressions
- [x] Arithmetic operations
- [x] Addition `a + b`
- [x] Subtraction `a - b`
- [x] Multiplication `a * b`
- [x] Division `a / b`
- [x] Modulo `a % b`
- [x] Negate `-a`
- [x] Parentheses `(a + b) * c`
- [x] Logical boolean operators
- [x] Equal `a == b`
- [x] Not equal `a != b`
- [x] Greater than `a > b`
- [x] Less than `a < b`
- [x] Greater than or equal `a >= b`
- [x] Less than or equal `a <= b`
- [x] Logical operators
- [x] And `a && b`
- [x] Or `a || b`
- [x] Not `!a`
- [x] Bitwise operators
- [x] Bitwise AND `a & b`
- [x] Bitwise OR `a | b`
- [x] Bitwise XOR `a ^ b`
- [x] Bitwise NOT `~a`
- [x] Bitwise left shift `a << b`
- [x] Bitwise right shift `a >> b`
- [x] Variables
- [x] Declaration
- [x] Assignment
- [x] While loop `while X { ... }`
- [x] Local variables (for example inside loop, if, else, functions)
- [x] Scoped block for specific local vars `{ ... }`
- [x] Statements with semicolon & Multiline programs
- [x] Control flow
- [x] Loops
- [x] While-style loop `loop X { ... }`
- [x] For-style loop without with `X` as condition and `Y` as advancement `loop X; Y { ... }`
- [x] Infinite loop `loop { ... }`
- [x] Break `break`
- [x] Continue `continue`
- [x] If else statement `if X { ... } else { ... }`
- [x] If Statement
- [x] Else statement
- [ ] Line comments `//`
- [x] Line comments `//`
- [x] Strings
- [x] For loops `for X; Y; Z { ... }`
- [ ] IO Intrinsics
- [x] Arrays
- [x] Creating array with size `X` as a variable `arr <- [X]`
- [x] Accessing arrays by index `arr[X]`
- [x] IO Intrinsics
- [x] Print
- [ ] ReadLine
- [x] Functions
- [x] Function declaration `fun f(X, Y, Z) { ... }`
- [x] Function calls `f(1, 2, 3)`
- [x] Function returns `return X`
- [x] Local variables
- [x] Pass arrays by-reference, i64 by-vale, string is a const ref
## Grammar
### Expressions
# Parsing Grammar
## Expressions
```
LITERAL = I64 | Str
expr_primary = LITERAL | IDENT | "(" expr ")" | "-" expr_primary
ARRAY_LITERAL = "[" expr "]"
ARRAY_ACCESS = IDENT "[" expr "]"
FUN_CALL = IDENT "(" (expr ",")* expr? ")"
LITERAL = I64_LITERAL | STR_LITERAL | ARRAY_LITERAL
expr_primary = LITERAL | IDENT | FUN_CALL | ARRAY_ACCESS | "(" expr ")" | "-" expr_primary
| "~" expr_primary
expr_mul = expr_primary (("*" | "/" | "%") expr_primary)*
expr_add = expr_mul (("+" | "-") expr_mul)*
expr_shift = expr_add ((">>" | "<<") expr_add)*
@@ -41,17 +394,38 @@ expr_equ = expr_rel (("==" | "!=") expr_rel)*
expr_band = expr_equ ("&" expr_equ)*
expr_bxor = expr_band ("^" expr_band)*
expr_bor = expr_bxor ("|" expr_bxor)*
expr = expr_bor
expr_land = expr_bor ("&&" expr_bor)*
expr_lor = expr_land ("||" expr_land)*
expr = expr_lor
```
## Statements
```
stmt_expr = expr
stmt_let = "let" IDENT "=" expr
stmt_while = "while" expr "{" (stmt)* "}"
stmt_for = "for" stmt_let ";" expr ";" expr "{" (stmt)* "}"
stmt_if = "if" expr "{" (stmt)* "}" ( "else" "{" (stmt)* "}" )
stmt_dbgprint = "$$" expr
stmt_print = "$" expr
stmt = stmt_expr | stmt_let | stmt_while | stmt_for | stmt_if | stmt_dbgprint | stmt_print
stmt_return = "return" expr ";"
stmt_break = "break" ";"
stmt_continue = "continue" ";"
stmt_var_decl = IDENT "<-" expr ";"
stmt_fun_decl = "fun" IDENT "(" (IDENT ",")* IDENT? ")" "{" stmt* "}"
stmt_expr = expr ";"
stmt_block = "{" stmt* "}"
stmt_loop = "loop" (expr (";" expr)?)? "{" stmt* "}"
stmt_if = "if" expr "{" stmt* "}" ("else" "{" stmt* "}")?
stmt_print = "print" expr ";"
stmt = stmt_return | stmt_break | stmt_continue | stmt_var_decl | stmt_fun_decl
| stmt_expr | stmt_block | stmt_loop | stmt_if | stmt_print
```
# Examples
There are a bunch of examples in the [examples](examples/) directory. Those include (non-optimal) solutions to the first five project euler problems, as well as a [simple Game of Life implementation](examples/game_of_life.nek).
To run an example via `cargo-run`, use:
```
cargo run --release -- examples/[NAME]
```
# Extras
## Visual Studio Code Language Support
A VSCode extension that provides simple syntax highlighing for nek is also available on
[gitlab](https://code.fbi.h-da.de/advanced-systems-programming-ws21/x4/nek-lang-vscode). Since this
is a very small scale project, the extension was not published and instuctions on how to install it
can be found in the mentioned repository.

15
examples/euler1.nek Normal file
View File

@@ -0,0 +1,15 @@
// If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
// The sum of these multiples is 23.
// Find the sum of all the multiples of 3 or 5 below 1000.
//
// Correct Answer: 233168
sum <- 0;
i <- 0;
loop i < 1_000; i = i + 1 {
if i % 3 == 0 || i % 5 == 0 {
sum = sum + i;
}
}
print sum;

24
examples/euler2.nek Normal file
View File

@@ -0,0 +1,24 @@
// Each new term in the Fibonacci sequence is generated by adding the previous two terms.
// By starting with 1 and 2, the first 10 terms will be:
// 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
// By considering the terms in the Fibonacci sequence whose values do not exceed four million,
// find the sum of the even-valued terms.
//
// Correct Answer: 4613732
sum <- 0;
a <- 0;
b <- 1;
loop a < 4_000_000 {
if a % 2 == 0 {
sum = sum + a;
}
tmp <- a;
a = b;
b = b + tmp;
}
print sum;

29
examples/euler3.nek Normal file
View File

@@ -0,0 +1,29 @@
// The prime factors of 13195 are 5, 7, 13 and 29.
// What is the largest prime factor of the number 600851475143 ?
//
// Correct Answer: 6857
number <- 600_851_475_143;
result <- 0;
div <- 2;
loop number > 1 {
loop number % div == 0 {
if div > result {
result = div;
}
number = number / div;
}
div = div + 1;
if div * div > number {
if number > 1 && number > result {
result = number;
}
break;
}
}
print result;

31
examples/euler4.nek Normal file
View File

@@ -0,0 +1,31 @@
// A palindromic number reads the same both ways. The largest palindrome made from the product of
// two 2-digit numbers is 9009 = 91 × 99.
// Find the largest palindrome made from the product of two 3-digit numbers.
//
// Correct Answer: 906609
fun reverse(n) {
rev <- 0;
loop n {
rev = rev * 10 + n % 10;
n = n / 10;
}
return rev;
}
res <- 0;
i <- 100;
loop i < 1_000; i = i + 1 {
k <- i;
loop k < 1_000; k = k + 1 {
num <- i * k;
num_rev <- reverse(num);
if num == num_rev && num > res {
res = num;
}
}
}
print res;

24
examples/euler4.py Normal file
View File

@@ -0,0 +1,24 @@
# A palindromic number reads the same both ways. The largest palindrome made from the product of
# two 2-digit numbers is 9009 = 91 × 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
#
# Correct Answer: 906609
def reverse(n):
rev = 0
while n:
rev = rev * 10 + n % 10
n //= 10
return rev
res = 0
for i in range(100, 1_000):
for k in range(i, 1_000):
num = i * k
num_rev = reverse(num)
if num == num_rev and num > res:
res = num
print(res)

23
examples/euler5.nek Normal file
View File

@@ -0,0 +1,23 @@
// 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
// What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
//
// Correct Answer: 232_792_560
fun gcd(x, y) {
loop y {
tmp <- x;
x = y;
y = tmp % y;
}
return x;
}
result <- 1;
i <- 1;
loop i <= 20; i = i + 1 {
result = result * (i / gcd(i, result));
}
print result;

15
examples/euler5.py Normal file
View File

@@ -0,0 +1,15 @@
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
#
# Correct Answer: 232_792_560
def gcd(x, y):
while y:
x, y = y, x % y
return x
result = 1
for i in range(1, 21):
result *= i // gcd(i, result)
print(result)

134
examples/game_of_life.nek Normal file
View File

@@ -0,0 +1,134 @@
fun print_field(field, width, height) {
y <- 0;
loop y < height; y = y+1 {
x <- 0;
loop x < width; x = x+1 {
if field[y*height + x] {
print "# ";
} else {
print ". ";
}
}
print "\n";
}
print "\n";
}
fun count_neighbours(field, x, y, width, height) {
neighbours <- 0;
if y > 0 {
if x > 0 {
if field[(y-1)*width + (x-1)] {
// Top left
neighbours = neighbours + 1;
}
}
if field[(y-1)*width + x] {
// Top
neighbours = neighbours + 1;
}
if x < width-1 {
if field[(y-1)*width + (x+1)] {
// Top right
neighbours = neighbours + 1;
}
}
}
if x > 0 {
if field[y*width + (x-1)] {
// Left
neighbours = neighbours + 1;
}
}
if x < width-1 {
if field[y*width + (x+1)] {
// Right
neighbours = neighbours + 1;
}
}
if y < height-1 {
if x > 0 {
if field[(y+1)*width + (x-1)] {
// Bottom left
neighbours = neighbours + 1;
}
}
if field[(y+1)*width + x] {
// Bottom
neighbours = neighbours + 1;
}
if x < width-1 {
if field[(y+1)*width + (x+1)] {
// Bottom right
neighbours = neighbours + 1;
}
}
}
return neighbours;
}
fun copy(from, to, len) {
i <- 0;
loop i < len; i = i + 1 {
to[i] = from[i];
}
}
// Set the width and height of the field
width <- 10;
height <- 10;
// Create the main and temporary field
field <- [width*height];
field2 <- [width*height];
// Preset the main field with a glider
field[1] = 1;
field[12] = 1;
field[20] = 1;
field[21] = 1;
field[22] = 1;
fun run_gol(num_rounds) {
runs <- 0;
loop runs < num_rounds; runs = runs + 1 {
// Print the field
print_field(field, width, height);
// Calculate next stage from field and store into field2
y <- 0;
loop y < height; y = y+1 {
x <- 0;
loop x < width; x = x+1 {
// Get the neighbours of the current cell
neighbours <- count_neighbours(field, x, y, width, height);
// Set the new cell according to the neighbour count
if neighbours < 2 || neighbours > 3 {
field2[y*width + x] = 0;
} else {
if neighbours == 3 {
field2[y*width + x] = 1;
} else {
field2[y*width + x] = field[y*width + x];
}
}
}
}
// Transfer from field2 to field
copy(field2, field, width*height);
}
}
run_gol(32);

View File

@@ -0,0 +1,9 @@
fun fib(n) {
if n <= 1 {
return n;
} else {
return fib(n-1) + fib(n-2);
}
}
print fib(30);

View File

@@ -0,0 +1,6 @@
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
print(fib(30))

View File

@@ -0,0 +1,31 @@
fun square(a) {
return a * a;
}
fun add(a, b) {
return a + b;
}
fun mul(a, b) {
return a * b;
}
// Funtion with multiple args & nested calls to different functions
fun addmul(a, b, c) {
return mul(add(a, b), c);
}
a <- 10;
b <- 20;
c <- 3;
result <- addmul(a, b, c) + square(c);
// Access and modify outer variable. Argument `a` must not be used from outer var
fun sub_from_result(a) {
result = result - a;
}
sub_from_result(30);
print result;

View File

@@ -1,5 +1,7 @@
use std::rc::Rc;
use crate::stringstore::{StringStore, Sid};
/// Types for binary operators
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum BinOpType {
@@ -18,6 +20,24 @@ pub enum BinOpType {
/// Modulo
Mod,
/// Compare Equal
EquEqu,
/// Compare Not Equal
NotEqu,
/// Less than
Less,
/// Less than or Equal
LessEqu,
/// Greater than
Greater,
/// Greater than or Equal
GreaterEqu,
/// Bitwise OR (inclusive or)
BOr,
@@ -27,78 +47,135 @@ pub enum BinOpType {
/// Bitwise Xor (exclusive or)
BXor,
/// Logical And
LAnd,
/// Logical Or
LOr,
/// Shift Left
Shl,
/// Shift Right
Shr,
/// Check equality
Equ,
/// Check unequality
Neq,
/// Check greater than
Gt,
/// Check greater or equal
Ge,
/// Check less than
Lt,
/// Check less or equal
Le,
/// Assign to a variable
/// Assign value to variable
Assign,
}
/// Types for unary operators
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum UnOpType {
/// Negation
Neg,
}
/// Unary Negate
Negate,
/// A full program abstract syntax tree. This consists of zero or more statements that represents
/// a program.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Ast {
pub prog: Vec<Stmt>,
/// Bitwise Not
BNot,
/// Logical Not
LNot,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Stmt {
/// Just a simple expression. This might be an assignment, a function call or a calculation.
Expr(Expr),
/// A variable declaration and assignment. (variable name, assigned value)
Let(String, Expr),
/// A while loop consisting of a condition and a body. (condition, body)
While(Expr, Ast),
/// A for loop consisting of an initialization declaration, a condition, an advancement and a
/// body. ((variable name, initial value), condition, advancement, body)
For((String, Expr), Expr, Expr, Ast),
/// If statement consisting of a condition, a true_body and a false_body.
/// (condition, true_body, false_body)
If(Expr, Ast, Ast),
/// Debug print the value of an expression (show the internal type together with the value)
DbgPrint(Expr),
/// Print the value of an expression
Print(Expr),
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Expr {
pub enum Expression {
/// Integer literal (64-bit)
I64(i64),
/// String literal
Str(Rc<String>),
/// Identifier (variable name)
Ident(String),
String(Sid),
/// Array with size
ArrayLiteral(Box<Expression>),
/// Array access with name, stackpos and position
ArrayAccess(Sid, usize, Box<Expression>),
FunCall(Sid, usize, Vec<Expression>),
/// Variable
Var(Sid, usize),
/// Binary operation. Consists of type, left hand side and right hand side
BinOp(BinOpType, Box<Expr>, Box<Expr>),
/// Unary operation. Consists of type and the value that is operated on
UnOp(UnOpType, Box<Expr>),
BinOp(BinOpType, Box<Expression>, Box<Expression>),
/// Unary operation. Consists of type and operand
UnOp(UnOpType, Box<Expression>),
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Loop {
/// The condition that determines if the loop should continue
pub condition: Option<Expression>,
/// This is executed after each loop to advance the condition variables
pub advancement: Option<Expression>,
/// The loop body that is executed each loop
pub body: BlockScope,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct If {
/// The condition
pub condition: Expression,
/// The body that is executed when condition is true
pub body_true: BlockScope,
/// The if body that is executed when the condition is false
pub body_false: BlockScope,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct FunDecl {
pub name: Sid,
pub fun_stackpos: usize,
pub argnames: Vec<Sid>,
pub body: Rc<BlockScope>,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct VarDecl {
pub name: Sid,
pub var_stackpos: usize,
pub rhs: Expression,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Statement {
Return(Expression),
Break,
Continue,
Declaration(VarDecl),
FunDeclare(FunDecl),
Expr(Expression),
Block(BlockScope),
Loop(Loop),
If(If),
Print(Expression),
}
pub type BlockScope = Vec<Statement>;
#[derive(Clone, Default)]
pub struct Ast {
pub stringstore: StringStore,
pub main: BlockScope,
}
impl BinOpType {
/// Get the precedence for a binary operator. Higher value means the OP is stronger binding.
/// For example Multiplication is stronger than addition, so Mul has higher precedence than Add.
///
/// The operator precedences are derived from the C language operator precedences. While not all
/// C operators are included or the exact same, the precedence oder is the same.
/// See: https://en.cppreference.com/w/c/language/operator_precedence
pub fn precedence(&self) -> u8 {
match self {
BinOpType::Assign => 1,
BinOpType::LOr => 2,
BinOpType::LAnd => 3,
BinOpType::BOr => 4,
BinOpType::BXor => 5,
BinOpType::BAnd => 6,
BinOpType::EquEqu | BinOpType::NotEqu => 7,
BinOpType::Less | BinOpType::LessEqu | BinOpType::Greater | BinOpType::GreaterEqu => 8,
BinOpType::Shl | BinOpType::Shr => 9,
BinOpType::Add | BinOpType::Sub => 10,
BinOpType::Mul | BinOpType::Div | BinOpType::Mod => 11,
}
}
}

111
src/astoptimizer.rs Normal file
View File

@@ -0,0 +1,111 @@
use crate::ast::{Ast, BlockScope, Expression, If, Loop, Statement, BinOpType, UnOpType, VarDecl};
pub trait AstOptimizer {
fn optimize(ast: Ast) -> Ast;
}
pub struct SimpleAstOptimizer;
impl AstOptimizer for SimpleAstOptimizer {
fn optimize(mut ast: Ast) -> Ast {
Self::optimize_block(&mut ast.main);
ast
}
}
impl SimpleAstOptimizer {
fn optimize_block(block: &mut BlockScope) {
for stmt in block {
match stmt {
Statement::Expr(expr) => Self::optimize_expr(expr),
Statement::Block(block) => Self::optimize_block(block),
Statement::Loop(Loop {
condition,
advancement,
body,
}) => {
if let Some(condition) = condition {
Self::optimize_expr(condition);
}
if let Some(advancement) = advancement {
Self::optimize_expr(advancement)
}
Self::optimize_block(body);
}
Statement::If(If {
condition,
body_true,
body_false,
}) => {
Self::optimize_expr(condition);
Self::optimize_block(body_true);
Self::optimize_block(body_false);
}
Statement::Print(expr) => Self::optimize_expr(expr),
Statement::Declaration(VarDecl { name: _, var_stackpos: _, rhs}) => Self::optimize_expr(rhs),
Statement::FunDeclare(_) => (),
Statement::Return(expr) => Self::optimize_expr(expr),
Statement::Break | Statement::Continue => (),
}
}
}
fn optimize_expr(expr: &mut Expression) {
match expr {
Expression::BinOp(bo, lhs, rhs) => {
Self::optimize_expr(lhs);
Self::optimize_expr(rhs);
// Precalculate binary operations that consist of 2 literals. No need to do this at
// runtime, as all parts of the calculation are known at *compiletime* / parsetime.
match (lhs.as_mut(), rhs.as_mut()) {
(Expression::I64(lhs), Expression::I64(rhs)) => {
let new_expr = match bo {
BinOpType::Add => Expression::I64(*lhs + *rhs),
BinOpType::Mul => Expression::I64(*lhs * *rhs),
BinOpType::Sub => Expression::I64(*lhs - *rhs),
BinOpType::Div => Expression::I64(*lhs / *rhs),
BinOpType::Mod => Expression::I64(*lhs % *rhs),
BinOpType::BOr => Expression::I64(*lhs | *rhs),
BinOpType::BAnd => Expression::I64(*lhs & *rhs),
BinOpType::BXor => Expression::I64(*lhs ^ *rhs),
BinOpType::LAnd => Expression::I64(if (*lhs != 0) && (*rhs != 0) { 1 } else { 0 }),
BinOpType::LOr => Expression::I64(if (*lhs != 0) || (*rhs != 0) { 1 } else { 0 }),
BinOpType::Shr => Expression::I64(*lhs >> *rhs),
BinOpType::Shl => Expression::I64(*lhs << *rhs),
BinOpType::EquEqu => Expression::I64(if lhs == rhs { 1 } else { 0 }),
BinOpType::NotEqu => Expression::I64(if lhs != rhs { 1 } else { 0 }),
BinOpType::Less => Expression::I64(if lhs < rhs { 1 } else { 0 }),
BinOpType::LessEqu => Expression::I64(if lhs <= rhs { 1 } else { 0 }),
BinOpType::Greater => Expression::I64(if lhs > rhs { 1 } else { 0 }),
BinOpType::GreaterEqu => Expression::I64(if lhs >= rhs { 1 } else { 0 }),
BinOpType::Assign => unreachable!(),
};
*expr = new_expr;
},
_ => ()
}
}
Expression::UnOp(uo, operand) => {
Self::optimize_expr(operand);
// Precalculate unary operations just like binary ones
match operand.as_mut() {
Expression::I64(val) => {
let new_expr = match uo {
UnOpType::Negate => Expression::I64(-*val),
UnOpType::BNot => Expression::I64(!*val),
UnOpType::LNot => Expression::I64(if *val == 0 { 1 } else { 0 }),
};
*expr = new_expr;
}
_ => (),
}
}
_ => (),
}
}
}

View File

@@ -1,211 +0,0 @@
use std::collections::HashMap;
use crate::ast::{Ast, Expr, Stmt, BinOpType};
type OpcodeSize = u32;
#[repr(u32)]
#[derive(Debug, Clone, Copy)]
pub enum OP {
Push,
Pop,
Load,
Store,
Add,
Subtract,
Multiply,
Divide,
Modulo,
BOr,
BAnd,
BXor,
Shl,
Shr,
Eq,
Neq,
Gt,
Ge,
Lt,
Le,
Jump,
JumpTrue,
JumpFalse,
Print,
DbgPrint,
}
#[derive(Debug, Default)]
pub struct Compiler {
ops: Vec<u32>,
global_vars: HashMap<String, u64>,
}
impl Compiler {
pub fn new() -> Self {
Compiler::default()
}
pub fn compile(&mut self, ast: &Ast) {
for stmt in &ast.prog {
match stmt {
Stmt::Expr(expr) => {
self.compile_expr(expr);
self.ops.push(OP::Pop as OpcodeSize);
}
Stmt::Let(name, rhs) => {
let id = self.global_vars.len() as u64;
self.global_vars.insert(name.clone(), id);
self.compile_expr(rhs);
self.gen_store(id);
}
Stmt::While(cond, body) => {
let idx_start = self.ops.len();
self.compile_expr(cond);
self.ops.push(OP::JumpFalse as OpcodeSize);
let idx_jmp = self.ops.len();
self.gen_i64(0);
self.compile(body);
self.ops.push(OP::Jump as OpcodeSize);
self.gen_i64(idx_start as i64);
self.overwrite_i64(idx_jmp, self.ops.len() as i64);
}
Stmt::For(_, _, _, _) => todo!(),
Stmt::If(cond, if_block, else_block) => {
self.compile_expr(cond);
self.ops.push(OP::JumpFalse as OpcodeSize);
let idx_if = self.ops.len();
self.gen_i64(0);
self.compile(if_block);
self.ops.push(OP::Jump as OpcodeSize);
let idx_else = self.ops.len();
self.gen_i64(0);
self.overwrite_i64(idx_if, self.ops.len() as i64);
self.compile(else_block);
self.overwrite_i64(idx_else, self.ops.len() as i64);
},
Stmt::DbgPrint(expr) => {
self.compile_expr(expr);
self.ops.push(OP::DbgPrint as OpcodeSize);
}
Stmt::Print(expr) => {
self.compile_expr(expr);
self.ops.push(OP::Print as OpcodeSize);
}
}
}
}
pub fn into_ops(self) -> Vec<u32> {
self.ops
}
pub fn compile_expr(&mut self, expr: &Expr) {
match expr {
Expr::I64(val) => {
self.ops.push(OP::Push as OpcodeSize);
self.gen_i64(*val)
}
Expr::Ident(name) => {
match self.global_vars.get(name).copied() {
Some(addr) => self.gen_load(addr),
None => panic!("Variable '{}' used before declaration", name),
}
},
Expr::BinOp(bo, lhs, rhs) => self.compile_binop(bo, lhs, rhs),
Expr::UnOp(_, _) => todo!(),
Expr::Str(_) => todo!(),
}
}
fn compile_binop(&mut self, bo: &BinOpType, lhs: &Expr, rhs: &Expr) {
if matches!(bo, BinOpType::Assign) {
self.compile_expr(rhs);
if let Expr::Ident(name) = lhs {
let addr = *self.global_vars.get(name).expect("Trying to assign var before decl");
self.gen_store(addr);
} else {
panic!("Trying to assign value to rvalue");
}
return;
}
self.compile_expr(lhs);
self.compile_expr(rhs);
match bo {
BinOpType::Add => self.ops.push(OP::Add as OpcodeSize),
BinOpType::Sub => self.ops.push(OP::Subtract as OpcodeSize),
BinOpType::Mul => self.ops.push(OP::Multiply as OpcodeSize),
BinOpType::Div => self.ops.push(OP::Divide as OpcodeSize),
BinOpType::Mod => self.ops.push(OP::Modulo as OpcodeSize),
BinOpType::BOr => self.ops.push(OP::BOr as OpcodeSize),
BinOpType::BAnd => self.ops.push(OP::BAnd as OpcodeSize),
BinOpType::BXor => self.ops.push(OP::BXor as OpcodeSize),
BinOpType::Shl => self.ops.push(OP::Shl as OpcodeSize),
BinOpType::Shr => self.ops.push(OP::Shr as OpcodeSize),
BinOpType::Equ => self.ops.push(OP::Eq as OpcodeSize),
BinOpType::Neq => self.ops.push(OP::Neq as OpcodeSize),
BinOpType::Gt => self.ops.push(OP::Gt as OpcodeSize),
BinOpType::Ge => self.ops.push(OP::Ge as OpcodeSize),
BinOpType::Lt => self.ops.push(OP::Lt as OpcodeSize),
BinOpType::Le => self.ops.push(OP::Le as OpcodeSize),
BinOpType::Assign => unreachable!(),
}
}
fn gen_i64(&mut self, val: i64) {
// for i in 0 .. 8 {
// self.ops.push(((val >> i*8) & 0xff) as OpcodeSize);
// }
for i in 0 .. 2 {
self.ops.push(((val >> i*32) & 0xffffffff) as OpcodeSize);
}
}
fn overwrite_i64(&mut self, idx: usize, val: i64) {
// for i in 0 .. 8 {
// self.ops[idx+i] = ((val >> i*8) & 0xff) as OpcodeSize;
// }
for i in 0 .. 2 {
self.ops[idx+i] = ((val >> i*32) & 0xffffffff) as OpcodeSize;
}
}
fn gen_load(&mut self, addr: u64) {
self.ops.push(OP::Load as OpcodeSize);
self.gen_i64(addr as i64)
}
fn gen_store(&mut self, addr: u64) {
self.ops.push(OP::Store as OpcodeSize);
self.gen_i64(addr as i64)
}
}
pub fn compile(ast: &Ast) -> Vec<u32> {
let mut compiler = Compiler::new();
compiler.compile(ast);
compiler.into_ops()
}

View File

@@ -1,175 +1,472 @@
use std::{collections::HashMap, fmt::Display, rc::Rc};
use std::{cell::RefCell, rc::Rc};
use thiserror::Error;
use crate::{
ast::{Ast, BinOpType, Expr, Stmt, UnOpType},
ast::{Ast, BinOpType, BlockScope, Expression, FunDecl, If, Statement, UnOpType},
astoptimizer::{AstOptimizer, SimpleAstOptimizer},
lexer::lex,
nice_panic,
parser::parse,
stringstore::{Sid, StringStore},
};
#[derive(Debug, Error)]
pub enum RuntimeError {
#[error("Invalid array Index: {}", 0.to_string())]
InvalidArrayIndex(Value),
#[error("Variable used but not declared: {0}")]
VarUsedNotDeclared(String),
#[error("Can't index into non-array variable: {0}")]
TryingToIndexNonArray(String),
#[error("Invalid value type for unary operation: {}", 0.to_string())]
UnOpInvalidType(Value),
#[error("Incompatible binary operations. Operands don't match: {} {}", 0.to_string(), 1.to_string())]
BinOpIncompatibleTypes(Value, Value),
#[error("Array access out of bounds: Accessed {0}, size is {1}")]
ArrayOutOfBounds(usize, usize),
#[error("Division by zero")]
DivideByZero,
#[error("Invalid number of arguments for function {0}. Expected {1}, got {2}")]
InvalidNumberOfArgs(String, usize, usize),
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Value {
I64(i64),
Str(Rc<String>),
String(Sid),
Array(Rc<RefCell<Vec<Value>>>),
Void,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum BlockExit {
Normal,
Break,
Continue,
Return(Value),
}
#[derive(Default)]
pub struct Interpreter {
/// The variable table maps all variables by their names to their values
vartable: HashMap<String, Value>,
pub optimize_ast: bool,
pub print_tokens: bool,
pub print_ast: bool,
pub capture_output: bool,
output: Vec<Value>,
// Variable table stores the runtime values of variables
vartable: Vec<Value>,
funtable: Vec<FunDecl>,
stringstore: StringStore,
}
impl Interpreter {
pub fn new() -> Self {
let vartable = HashMap::new();
Self { vartable }
Self {
optimize_ast: true,
..Self::default()
}
}
pub fn run_text(&mut self, code: &str, print_tokens: bool, print_ast: bool) {
let tokens = lex(code);
if print_tokens {
pub fn output(&self) -> &[Value] {
&self.output
}
fn get_var(&self, idx: usize) -> Option<Value> {
self.vartable.get(self.vartable.len() - idx - 1).cloned()
}
fn get_var_mut(&mut self, idx: usize) -> Option<&mut Value> {
let idx = self.vartable.len() - idx - 1;
self.vartable.get_mut(idx)
}
pub fn run_str(&mut self, code: &str) {
let tokens = match lex(code) {
Ok(tokens) => tokens,
Err(e) => nice_panic!("Lexing error: {}", e),
};
if self.print_tokens {
println!("Tokens: {:?}", tokens);
}
let ast = parse(tokens);
if print_ast {
println!("Ast:\n{:#?}", ast);
let ast = match parse(tokens) {
Ok(ast) => ast,
Err(e) => nice_panic!("Parsing error: {}", e),
};
match self.run_ast(ast) {
Ok(_) => (),
Err(e) => nice_panic!("Runtime error: {}", e),
}
self.run(&ast);
}
pub fn run(&mut self, prog: &Ast) {
for stmt in &prog.prog {
pub fn run_ast(&mut self, mut ast: Ast) -> Result<(), RuntimeError> {
if self.optimize_ast {
ast = SimpleAstOptimizer::optimize(ast);
}
if self.print_ast {
println!("{:#?}", ast.main);
}
self.stringstore = ast.stringstore;
self.run_block(&ast.main)?;
Ok(())
}
pub fn run_block(&mut self, prog: &BlockScope) -> Result<BlockExit, RuntimeError> {
self.run_block_fp_offset(prog, 0)
}
pub fn run_block_fp_offset(
&mut self,
prog: &BlockScope,
framepointer_offset: usize,
) -> Result<BlockExit, RuntimeError> {
let framepointer = self.vartable.len() - framepointer_offset;
for stmt in prog {
match stmt {
Stmt::Expr(expr) => {
self.resolve_expr(expr);
}
Stmt::DbgPrint(expr) => {
let result = self.resolve_expr(expr);
println!("{:?}", result);
}
Stmt::Print(expr) => {
let result = self.resolve_expr(expr);
print!("{}", result);
}
Stmt::Let(name, rhs) => {
let result = self.resolve_expr(rhs);
self.vartable.insert(name.clone(), result);
}
Stmt::For(init, condition, advance, body) => {
// Execute initital let instruction
let init_val = self.resolve_expr(&init.1);
self.vartable.insert(init.0.clone(), init_val);
Statement::Break => return Ok(BlockExit::Break),
Statement::Continue => return Ok(BlockExit::Continue),
loop {
// Check condition
match self.resolve_expr(condition) {
Value::I64(val) if val == 0 => break,
Value::I64(_) => (),
Statement::Return(expr) => {
let val = self.resolve_expr(expr)?;
Value::Str(text) if text.is_empty() => break,
Value::Str(_) => (),
self.vartable.truncate(framepointer);
return Ok(BlockExit::Return(val));
}
// Execute loop body
self.run(body);
// Execute advancement
self.resolve_expr(advance);
}
}
Stmt::While(condition, body) => {
loop {
// Check condition
match self.resolve_expr(condition) {
Value::I64(val) if val == 0 => break,
Value::I64(_) => (),
Value::Str(text) if text.is_empty() => break,
Value::Str(_) => (),
Statement::Expr(expr) => {
self.resolve_expr(expr)?;
}
// Execute loop body
self.run(body);
}
}
Stmt::If(condition, body_if, body_else) => {
if matches!(self.resolve_expr(condition), Value::I64(0)) {
self.run(body_else);
} else {
self.run(body_if);
}
}
}
}
Statement::Declaration(decl) => {
let rhs = self.resolve_expr(&decl.rhs)?;
self.vartable.push(rhs);
}
fn resolve_expr(&mut self, expr: &Expr) -> Value {
match expr {
Expr::I64(val) => Value::I64(*val),
Expr::Str(name) => Value::Str(name.clone()),
Expr::BinOp(bo, lhs, rhs) => self.resolve_binop(bo, &lhs, &rhs),
Expr::UnOp(uo, val) => self.resolve_unop(uo, &val),
Expr::Ident(name) => match self.vartable.get(name) {
None => panic!("Runtime error: Use of undeclared variable '{}'", name),
Some(val) => val.clone(),
Statement::Block(block) => match self.run_block(block)? {
// Propagate return, continue and break
be @ (BlockExit::Return(_) | BlockExit::Continue | BlockExit::Break) => {
self.vartable.truncate(framepointer);
return Ok(be);
}
_ => (),
},
Statement::Loop(looop) => {
// loop runs as long condition != 0
loop {
if let Some(condition) = &looop.condition {
if matches!(self.resolve_expr(condition)?, Value::I64(0)) {
break;
}
}
fn resolve_binop(&mut self, bo: &BinOpType, lhs: &Expr, rhs: &Expr) -> Value {
// Treat assignment separate from the other expressions
if matches!(bo, BinOpType::Assign) {
match lhs {
Expr::Ident(name) => {
let rhs = self.resolve_expr(rhs);
self.vartable.get_mut(name).map(|var| *var = rhs.clone());
return rhs;
let be = self.run_block(&looop.body)?;
match be {
// Propagate return
be @ BlockExit::Return(_) => {
self.vartable.truncate(framepointer);
return Ok(be);
}
BlockExit::Break => break,
BlockExit::Continue | BlockExit::Normal => (),
}
if let Some(adv) = &looop.advancement {
self.resolve_expr(&adv)?;
}
_ => panic!("Runtime error: Left hand side of assignment must be an identifier"),
}
}
let lhs = self.resolve_expr(lhs);
let rhs = self.resolve_expr(rhs);
Statement::Print(expr) => {
let result = self.resolve_expr(expr)?;
match (lhs, rhs) {
if self.capture_output {
self.output.push(result)
} else {
print!("{}", self.value_to_string(&result));
}
}
Statement::If(If {
condition,
body_true,
body_false,
}) => {
let exit = if matches!(self.resolve_expr(condition)?, Value::I64(0)) {
self.run_block(body_false)?
} else {
self.run_block(body_true)?
};
match exit {
// Propagate return, continue and break
be @ (BlockExit::Return(_) | BlockExit::Continue | BlockExit::Break) => {
self.vartable.truncate(framepointer);
return Ok(be);
}
_ => (),
}
}
Statement::FunDeclare(fundec) => {
self.funtable.push(fundec.clone());
}
}
}
self.vartable.truncate(framepointer);
Ok(BlockExit::Normal)
}
fn resolve_expr(&mut self, expr: &Expression) -> Result<Value, RuntimeError> {
let val = match expr {
Expression::I64(val) => Value::I64(*val),
Expression::ArrayLiteral(size) => {
let size = match self.resolve_expr(size)? {
Value::I64(size) if !size.is_negative() => size,
val => return Err(RuntimeError::InvalidArrayIndex(val)),
};
Value::Array(Rc::new(RefCell::new(vec![Value::I64(0); size as usize])))
}
Expression::String(text) => Value::String(text.clone()),
Expression::BinOp(bo, lhs, rhs) => self.resolve_binop(bo, lhs, rhs)?,
Expression::UnOp(uo, operand) => self.resolve_unop(uo, operand)?,
Expression::Var(name, idx) => self.resolve_var(*name, *idx)?,
Expression::ArrayAccess(name, idx, arr_idx) => {
self.resolve_array_access(*name, *idx, arr_idx)?
}
Expression::FunCall(fun_name, fun_stackpos, args) => {
let args_len = args.len();
// All of the arg expressions must be resolved before pushing the vars on the stack,
// otherwise the stack positions are incorrect while resolving
let args = args
.iter()
.map(|arg| self.resolve_expr(arg))
.collect::<Vec<_>>();
for arg in args {
self.vartable.push(arg?);
}
// Function existance has been verified in the parser, so unwrap here shouldn't fail
let expected_num_args = self.funtable.get(*fun_stackpos).unwrap().argnames.len();
if expected_num_args != args_len {
let fun_name = self
.stringstore
.lookup(*fun_name)
.cloned()
.unwrap_or("<unknown>".to_string());
return Err(RuntimeError::InvalidNumberOfArgs(
fun_name,
expected_num_args,
args_len,
));
}
match self.run_block_fp_offset(
&Rc::clone(&self.funtable.get(*fun_stackpos).unwrap().body),
expected_num_args,
)? {
BlockExit::Normal | BlockExit::Continue | BlockExit::Break => Value::Void,
BlockExit::Return(val) => val,
}
}
};
Ok(val)
}
fn resolve_array_access(
&mut self,
name: Sid,
idx: usize,
arr_idx: &Expression,
) -> Result<Value, RuntimeError> {
let arr_idx = match self.resolve_expr(arr_idx)? {
Value::I64(size) if !size.is_negative() => size,
val => return Err(RuntimeError::InvalidArrayIndex(val)),
};
let val = match self.get_var(idx) {
Some(val) => val,
None => {
return Err(RuntimeError::VarUsedNotDeclared(
self.stringstore
.lookup(name)
.cloned()
.unwrap_or_else(|| "<unknown>".to_string()),
))
}
};
let arr = match val {
Value::Array(arr) => arr,
_ => {
return Err(RuntimeError::TryingToIndexNonArray(
self.stringstore
.lookup(name)
.cloned()
.unwrap_or_else(|| "<unknown>".to_string()),
))
}
};
let arr = arr.borrow_mut();
arr.get(arr_idx as usize)
.cloned()
.ok_or(RuntimeError::ArrayOutOfBounds(arr_idx as usize, arr.len()))
}
fn resolve_var(&mut self, name: Sid, idx: usize) -> Result<Value, RuntimeError> {
match self.get_var(idx) {
Some(val) => Ok(val),
None => {
return Err(RuntimeError::VarUsedNotDeclared(
self.stringstore
.lookup(name)
.cloned()
.unwrap_or_else(|| "<unknown>".to_string()),
))
}
}
}
fn resolve_unop(&mut self, uo: &UnOpType, operand: &Expression) -> Result<Value, RuntimeError> {
let operand = self.resolve_expr(operand)?;
Ok(match (operand, uo) {
(Value::I64(val), UnOpType::Negate) => Value::I64(-val),
(Value::I64(val), UnOpType::BNot) => Value::I64(!val),
(Value::I64(val), UnOpType::LNot) => Value::I64(if val == 0 { 1 } else { 0 }),
(val, _) => return Err(RuntimeError::UnOpInvalidType(val)),
})
}
fn resolve_binop(
&mut self,
bo: &BinOpType,
lhs: &Expression,
rhs: &Expression,
) -> Result<Value, RuntimeError> {
let rhs = self.resolve_expr(rhs)?;
match (&bo, &lhs) {
(BinOpType::Assign, Expression::Var(name, idx)) => {
match self.get_var_mut(*idx) {
Some(val) => *val = rhs.clone(),
None => {
return Err(RuntimeError::VarUsedNotDeclared(
self.stringstore
.lookup(*name)
.cloned()
.unwrap_or_else(|| "<unknown>".to_string()),
))
}
}
return Ok(rhs);
}
(BinOpType::Assign, Expression::ArrayAccess(name, idx, arr_idx)) => {
let arr_idx = match self.resolve_expr(arr_idx)? {
Value::I64(size) if !size.is_negative() => size,
val => return Err(RuntimeError::InvalidArrayIndex(val)),
};
let val = match self.get_var_mut(*idx) {
Some(val) => val,
None => {
return Err(RuntimeError::VarUsedNotDeclared(
self.stringstore
.lookup(*name)
.cloned()
.unwrap_or_else(|| "<unknown>".to_string()),
))
}
};
match val {
Value::Array(arr) => arr.borrow_mut()[arr_idx as usize] = rhs.clone(),
_ => {
return Err(RuntimeError::TryingToIndexNonArray(
self.stringstore
.lookup(*name)
.cloned()
.unwrap_or_else(|| "<unknown>".to_string()),
))
}
}
return Ok(rhs);
}
_ => (),
}
let lhs = self.resolve_expr(lhs)?;
let result = match (lhs, rhs) {
(Value::I64(lhs), Value::I64(rhs)) => match bo {
BinOpType::Add => Value::I64(lhs + rhs),
BinOpType::Mul => Value::I64(lhs * rhs),
BinOpType::Sub => Value::I64(lhs - rhs),
BinOpType::Div => Value::I64(lhs / rhs),
BinOpType::Mod => Value::I64(lhs % rhs),
BinOpType::Div => {
Value::I64(lhs.checked_div(rhs).ok_or(RuntimeError::DivideByZero)?)
}
BinOpType::Mod => {
Value::I64(lhs.checked_rem(rhs).ok_or(RuntimeError::DivideByZero)?)
}
BinOpType::BOr => Value::I64(lhs | rhs),
BinOpType::BAnd => Value::I64(lhs & rhs),
BinOpType::BXor => Value::I64(lhs ^ rhs),
BinOpType::LAnd => Value::I64(if (lhs != 0) && (rhs != 0) { 1 } else { 0 }),
BinOpType::LOr => Value::I64(if (lhs != 0) || (rhs != 0) { 1 } else { 0 }),
BinOpType::Shr => Value::I64(lhs >> rhs),
BinOpType::Shl => Value::I64(lhs << rhs),
BinOpType::Equ => Value::I64(if lhs == rhs { 1 } else { 0 }),
BinOpType::Neq => Value::I64(if lhs != rhs { 1 } else { 0 }),
BinOpType::Gt => Value::I64(if lhs > rhs { 1 } else { 0 }),
BinOpType::Ge => Value::I64(if lhs >= rhs { 1 } else { 0 }),
BinOpType::Lt => Value::I64(if lhs < rhs { 1 } else { 0 }),
BinOpType::Le => Value::I64(if lhs <= rhs { 1 } else { 0 }),
BinOpType::EquEqu => Value::I64(if lhs == rhs { 1 } else { 0 }),
BinOpType::NotEqu => Value::I64(if lhs != rhs { 1 } else { 0 }),
BinOpType::Less => Value::I64(if lhs < rhs { 1 } else { 0 }),
BinOpType::LessEqu => Value::I64(if lhs <= rhs { 1 } else { 0 }),
BinOpType::Greater => Value::I64(if lhs > rhs { 1 } else { 0 }),
BinOpType::GreaterEqu => Value::I64(if lhs >= rhs { 1 } else { 0 }),
BinOpType::Assign => unreachable!(),
},
_ => panic!("Value types are not compatible"),
}
(lhs, rhs) => return Err(RuntimeError::BinOpIncompatibleTypes(lhs, rhs)),
};
Ok(result)
}
fn resolve_unop(&mut self, uo: &UnOpType, val: &Expr) -> Value {
let val = self.resolve_expr(val);
fn value_to_string(&self, val: &Value) -> String {
match val {
Value::I64(val) => match uo {
UnOpType::Neg => Value::I64(-val),
},
_ => panic!("Invalid unary operation for type"),
}
}
}
impl Display for Value {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Value::I64(val) => write!(f, "{}", val),
Value::Str(text) => write!(f, "{}", text),
Value::I64(val) => format!("{}", val),
Value::Array(val) => format!("{:?}", val.borrow()),
Value::String(text) => format!(
"{}",
self.stringstore
.lookup(*text)
.unwrap_or(&"<invalid string>".to_string())
),
Value::Void => format!("void"),
}
}
}
@@ -177,27 +474,32 @@ impl Display for Value {
#[cfg(test)]
mod test {
use super::{Interpreter, Value};
use crate::ast::{BinOpType, Expr};
use crate::ast::{BinOpType, Expression};
#[test]
fn test_interpreter_expr() {
// Expression: 1 + 2 * 3 + 4
// With precedence: (1 + (2 * 3)) + 4
let ast = Expr::BinOp(
let ast = Expression::BinOp(
BinOpType::Add,
Expr::BinOp(
Expression::BinOp(
BinOpType::Add,
Expr::I64(1).into(),
Expr::BinOp(BinOpType::Mul, Expr::I64(2).into(), Expr::I64(3).into()).into(),
Expression::I64(1).into(),
Expression::BinOp(
BinOpType::Mul,
Expression::I64(2).into(),
Expression::I64(3).into(),
)
.into(),
Expr::I64(4).into(),
)
.into(),
Expression::I64(4).into(),
);
let expected = Value::I64(11);
let mut interpreter = Interpreter::new();
let actual = interpreter.resolve_expr(&ast);
let actual = interpreter.resolve_expr(&ast).unwrap();
assert_eq!(expected, actual);
}

View File

@@ -1,115 +1,120 @@
use std::{iter::Peekable, str::Chars};
use thiserror::Error;
use crate::token::{Keyword, Literal, Token};
use crate::{token::Token, T};
#[derive(Debug, Error)]
pub enum LexErr {
#[error("Failed to parse '{0}' as i64")]
NumericParse(String),
#[error("Invalid escape character '\\{0}'")]
InvalidStrEscape(char),
#[error("Lexer encountered unexpected char: '{0}'")]
UnexpectedChar(char),
#[error("Missing closing string quote '\"'")]
MissingClosingString,
}
/// Lex the provided code into a Token Buffer
pub fn lex(code: &str) -> Vec<Token> {
let mut lexer = Lexer::new(code);
pub fn lex(code: &str) -> Result<Vec<Token>, LexErr> {
let lexer = Lexer::new(code);
lexer.lex()
}
struct Lexer<'a> {
/// The sourcecode text as an iterator over the chars
code: Peekable<Chars<'a>>,
/// The lexed tokens
tokens: Vec<Token>,
/// The sourcecode character that is currently being lexed
current_char: char,
}
impl<'a> Lexer<'a> {
fn new(code: &'a str) -> Self {
let code = code.chars().peekable();
Self { code }
let tokens = Vec::new();
let current_char = '\0';
Self {
code,
tokens,
current_char,
}
}
/// Advance to next character and return the removed char. If there is no next char, '\0'
/// is returned.
fn next(&mut self) -> char {
self.code.next().unwrap_or('\0')
}
/// Get the next character without removing it. If there is no next char, '\0' is returned.
fn peek(&mut self) -> char {
self.code.peek().copied().unwrap_or('\0')
}
fn lex(&mut self) -> Vec<Token> {
let mut tokens = Vec::new();
fn lex(mut self) -> Result<Vec<Token>, LexErr> {
loop {
match self.next() {
// End of text
'\0' => break,
self.current_char = self.next();
match (self.current_char, self.peek()) {
// Stop lexing at EOF
('\0', _) => break,
// Skip whitespace
' ' | '\r' | '\n' | '\t' => (),
(' ' | '\t' | '\n' | '\r', _) => (),
// Handle tokens that span two characters
'>' if matches!(self.peek(), '>') => {
self.next();
tokens.push(Token::Shr);
}
'<' if matches!(self.peek(), '<') => {
self.next();
tokens.push(Token::Shl);
}
'=' if matches!(self.peek(), '=') => {
self.next();
tokens.push(Token::Equ);
}
'!' if matches!(self.peek(), '=') => {
self.next();
tokens.push(Token::Neq);
}
'<' if matches!(self.peek(), '=') => {
self.next();
tokens.push(Token::Le);
}
'>' if matches!(self.peek(), '=') => {
self.next();
tokens.push(Token::Ge);
}
'$' if matches!(self.peek(), '$') => {
self.next();
tokens.push(Token::DoubleDollar);
}
// Line comment. Consume every char until linefeed (next line)
('/', '/') => while !matches!(self.next(), '\n' | '\0') {},
// Handle tokens that span one character
'+' => tokens.push(Token::Add),
'-' => tokens.push(Token::Sub),
'*' => tokens.push(Token::Mul),
'/' => tokens.push(Token::Div),
'%' => tokens.push(Token::Mod),
'|' => tokens.push(Token::BOr),
'&' => tokens.push(Token::BAnd),
'^' => tokens.push(Token::BXor),
'(' => tokens.push(Token::LParen),
')' => tokens.push(Token::RParen),
'<' => tokens.push(Token::Lt),
'>' => tokens.push(Token::Gt),
'=' => tokens.push(Token::Assign),
';' => tokens.push(Token::Semicolon),
'{' => tokens.push(Token::LBrace),
'}' => tokens.push(Token::RBrace),
'$' => tokens.push(Token::Dollar),
// Double character tokens
('>', '>') => self.push_tok_consume(T![>>]),
('<', '<') => self.push_tok_consume(T![<<]),
('=', '=') => self.push_tok_consume(T![==]),
('!', '=') => self.push_tok_consume(T![!=]),
('<', '=') => self.push_tok_consume(T![<=]),
('>', '=') => self.push_tok_consume(T![>=]),
('<', '-') => self.push_tok_consume(T![<-]),
('&', '&') => self.push_tok_consume(T![&&]),
('|', '|') => self.push_tok_consume(T![||]),
// Handle special multicharacter tokens
// Single character tokens
(',', _) => self.push_tok(T![,]),
(';', _) => self.push_tok(T![;]),
('+', _) => self.push_tok(T![+]),
('-', _) => self.push_tok(T![-]),
('*', _) => self.push_tok(T![*]),
('/', _) => self.push_tok(T![/]),
('%', _) => self.push_tok(T![%]),
('|', _) => self.push_tok(T![|]),
('&', _) => self.push_tok(T![&]),
('^', _) => self.push_tok(T![^]),
('(', _) => self.push_tok(T!['(']),
(')', _) => self.push_tok(T![')']),
('~', _) => self.push_tok(T![~]),
('<', _) => self.push_tok(T![<]),
('>', _) => self.push_tok(T![>]),
('=', _) => self.push_tok(T![=]),
('{', _) => self.push_tok(T!['{']),
('}', _) => self.push_tok(T!['}']),
('!', _) => self.push_tok(T![!]),
('[', _) => self.push_tok(T!['[']),
(']', _) => self.push_tok(T![']']),
// Lex numbers
ch @ '0'..='9' => tokens.push(self.lex_number(ch)),
// Special tokens with variable length
// Lex strings
'"' => tokens.push(self.lex_string()),
// Lex multiple characters together as numbers
('0'..='9', _) => self.lex_number()?,
// Lex identifiers
ch @ ('a'..='z' | 'A'..='Z' | '_') => tokens.push(self.lex_ident(ch)),
// Lex multiple characters together as a string
('"', _) => self.lex_str()?,
// Any other character is unexpected
ch => panic!("Lexer encountered unexpected char: '{}'", ch),
// Lex multiple characters together as identifier
('a'..='z' | 'A'..='Z' | '_', _) => self.lex_identifier()?,
(ch, _) => Err(LexErr::UnexpectedChar(ch))?,
}
}
tokens
Ok(self.tokens)
}
fn lex_number(&mut self, first_char: char) -> Token {
let mut sval = String::from(first_char);
/// Lex multiple characters as a number until encountering a non numeric digit. The
/// successfully lexed i64 literal token is appended to the stored tokens.
fn lex_number(&mut self) -> Result<(), LexErr> {
// String representation of the integer value
let mut sval = String::from(self.current_char);
// Do as long as a next char exists and it is a numeric char
loop {
@@ -127,112 +132,160 @@ impl<'a> Lexer<'a> {
}
}
// TODO: We only added numeric chars to the string, but the conversion could still fail
Token::Literal(Literal::I64(sval.parse().unwrap()))
// Try to convert the string representation of the value to i64
let i64val = sval.parse().map_err(|_| LexErr::NumericParse(sval))?;
self.push_tok(T![i64(i64val)]);
Ok(())
}
/// Lex an identifier from the character stream. The first char has to have been consumed
/// from the stream already and is passed as an argument instead.
fn lex_ident(&mut self, first_char: char) -> Token {
let mut ident = String::from(first_char);
/// Lex characters as a string until encountering an unescaped closing doublequoute char '"'.
/// The successfully lexed string literal token is appended to the stored tokens.
fn lex_str(&mut self) -> Result<(), LexErr> {
// Opening " was consumed in match
// Do as long as a next char exists and it is a valid ident char
while let 'a'..='z' | 'A'..='Z' | '_' | '0'..='9' = self.peek() {
// The next char is verified to be Some, so unwrap is safe
ident.push(self.next());
}
// Check if the identifier is a keyword
match ident.as_str() {
"true" => Token::Literal(Literal::I64(1)),
"false" => Token::Literal(Literal::I64(0)),
"let" => Token::Keyword(Keyword::Let),
"while" => Token::Keyword(Keyword::While),
"if" => Token::Keyword(Keyword::If),
"else" => Token::Keyword(Keyword::Else),
"for" => Token::Keyword(Keyword::For),
_ => Token::Ident(ident),
}
}
/// Lex a string token from the character stream. This requires the initial quote '"' to be
/// consumed before.
fn lex_string(&mut self) -> Token {
let mut text = String::new();
let mut escape = false;
// Do as long as a next char exists and it is not '"'
// Read all chars until encountering the closing "
loop {
if escape {
escape = false;
// Escape characters
match self.next() {
'\\' => text.push('\\'),
match self.peek() {
'"' => break,
// If the end of file is reached while still waiting for '"', error out
'\0' => Err(LexErr::MissingClosingString)?,
_ => match self.next() {
// Backshlash indicates an escaped character
'\\' => match self.next() {
'n' => text.push('\n'),
'r' => text.push('\r'),
't' => text.push('\t'),
ch => panic!("Invalid string escape: '{:?}'", ch),
'\\' => text.push('\\'),
'"' => text.push('"'),
ch => Err(LexErr::InvalidStrEscape(ch))?,
},
// All other characters are simply appended to the string
ch => text.push(ch),
},
}
} else {
}
// Consume closing "
self.next();
self.push_tok(T![str(text)]);
Ok(())
}
/// Lex characters from the text as an identifier. The successfully lexed ident or keyword
/// token is appended to the stored tokens.
fn lex_identifier(&mut self) -> Result<(), LexErr> {
let mut ident = String::from(self.current_char);
// Do as long as a next char exists and it is a valid char for an identifier
loop {
match self.peek() {
// Doublequote '"' ends the string lexing
'"' => {
// In the middle of an identifier numbers are also allowed
'a'..='z' | 'A'..='Z' | '0'..='9' | '_' => {
ident.push(self.next());
}
// Next char is not valid, so stop and finish the ident token
_ => break,
}
}
// Check for pre-defined keywords
let token = match ident.as_str() {
"loop" => T![loop],
"print" => T![print],
"if" => T![if],
"else" => T![else],
"fun" => T![fun],
"return" => T![return],
"break" => T![break],
"continue" => T![continue],
// If it doesn't match a keyword, it is a normal identifier
_ => T![ident(ident)],
};
self.push_tok(token);
Ok(())
}
/// Push the given token into the stored tokens
fn push_tok(&mut self, token: Token) {
self.tokens.push(token);
}
/// Same as `push_tok` but also consumes the next token, removing it from the code iter
fn push_tok_consume(&mut self, token: Token) {
self.next();
break;
}
// Backslash '\' escapes the next character
'\\' => {
self.next();
escape = true;
self.tokens.push(token);
}
// Reached end of text but didn't encounter closing doublequote '"'
'\0' => panic!("String is never terminated (missing '\"')"),
_ => text.push(self.next()),
}
}
/// Advance to next character and return the removed char
fn next(&mut self) -> char {
self.code.next().unwrap_or('\0')
}
Token::Literal(Literal::Str(text))
/// Get the next character without removing it
fn peek(&mut self) -> char {
self.code.peek().copied().unwrap_or('\0')
}
}
#[cfg(test)]
mod tests {
use crate::token::Literal;
use super::{lex, Token};
use crate::{lexer::lex, T};
#[test]
fn test_lexer() {
let code = "33 +5*2 + 4456467*2334+3 % - / << ^ | & >>";
let code = r#"53+1-567_000 * / % | ~ ! < > & ^ ({[]});= <- >= <=
== != && || << >> loop if else print my_123var "hello \t world\r\n\"\\""#;
let expected = vec![
Token::Literal(Literal::I64(33)),
Token::Add,
Token::Literal(Literal::I64(5)),
Token::Mul,
Token::Literal(Literal::I64(2)),
Token::Add,
Token::Literal(Literal::I64(4456467)),
Token::Mul,
Token::Literal(Literal::I64(2334)),
Token::Add,
Token::Literal(Literal::I64(3)),
Token::Mod,
Token::Sub,
Token::Div,
Token::Shl,
Token::BXor,
Token::BOr,
Token::BAnd,
Token::Shr,
T![i64(53)],
T![+],
T![i64(1)],
T![-],
T![i64(567_000)],
T![*],
T![/],
T![%],
T![|],
T![~],
T![!],
T![<],
T![>],
T![&],
T![^],
T!['('],
T!['{'],
T!['['],
T![']'],
T!['}'],
T![')'],
T![;],
T![=],
T![<-],
T![>=],
T![<=],
T![==],
T![!=],
T![&&],
T![||],
T![<<],
T![>>],
T![loop],
T![if],
T![else],
T![print],
T![ident("my_123var".to_string())],
T![str("hello \t world\r\n\"\\".to_string())],
];
let actual = lex(code);
let actual = lex(code).unwrap();
assert_eq!(expected, actual);
}
}

View File

@@ -1,7 +1,61 @@
pub mod ast;
pub mod interpreter;
pub mod lexer;
pub mod parser;
pub mod interpreter;
pub mod token;
pub mod ast;
pub mod bytecode;
pub mod vm;
pub mod stringstore;
pub mod astoptimizer;
pub mod util;
#[cfg(test)]
mod tests {
use crate::interpreter::{Interpreter, Value};
use std::fs::read_to_string;
fn run_example_check_single_i64_output(filename: &str, correct_result: i64) {
let mut interpreter = Interpreter::new();
interpreter.capture_output = true;
let code = read_to_string(format!("examples/{filename}")).unwrap();
interpreter.run_str(&code);
let expected_output = [Value::I64(correct_result)];
assert_eq!(interpreter.output(), &expected_output);
}
#[test]
fn test_euler1() {
run_example_check_single_i64_output("euler1.nek", 233168);
}
#[test]
fn test_euler2() {
run_example_check_single_i64_output("euler2.nek", 4613732);
}
#[test]
fn test_euler3() {
run_example_check_single_i64_output("euler3.nek", 6857);
}
#[test]
fn test_euler4() {
run_example_check_single_i64_output("euler4.nek", 906609);
}
#[test]
fn test_euler5() {
run_example_check_single_i64_output("euler5.nek", 232792560);
}
#[test]
fn test_recursive_fib() {
run_example_check_single_i64_output("recursive_fib.nek", 832040);
}
#[test]
fn test_functions() {
run_example_check_single_i64_output("test_functions.nek", 69);
}
}

View File

@@ -1,63 +1,56 @@
use std::{env::args, io::Write};
use std::{env::args, fs, process::exit};
use nek_lang::{interpreter::Interpreter, lexer::lex, parser::parse, bytecode::compile, vm::Vm};
use nek_lang::{interpreter::Interpreter, nice_panic};
#[derive(Debug, Default)]
struct CliConfig {
print_tokens: bool,
print_ast: bool,
interactive: bool,
no_optimizations: bool,
file: Option<String>,
}
fn main() {
let mut cfg = CliConfig::default();
let mut conf = CliConfig::default();
// Go through all commandline arguments except the first (filename)
for arg in args().skip(1) {
match arg.as_str() {
"--tokens" | "-t" => cfg.print_tokens = true,
"--ast" | "-a" => cfg.print_ast = true,
"--interactive" | "-i" => cfg.interactive = true,
file if cfg.file.is_none() => cfg.file = Some(file.to_string()),
_ => panic!("Invalid argument: '{}'", arg),
"--token" | "-t" => conf.print_tokens = true,
"--ast" | "-a" => conf.print_ast = true,
"--no-opt" | "-n" => conf.no_optimizations = true,
"--help" | "-h" => print_help(),
file if !arg.starts_with("-") && conf.file.is_none() => {
conf.file = Some(file.to_string())
}
_ => nice_panic!("Error: Invalid argument '{}'", arg),
}
}
let mut interpreter = Interpreter::new();
if let Some(file) = &cfg.file {
let code = std::fs::read_to_string(file).expect(&format!("File not found: '{}'", file));
let tokens = lex(&code);
let ast = parse(tokens);
interpreter.print_tokens = conf.print_tokens;
interpreter.print_ast = conf.print_ast;
interpreter.optimize_ast = !conf.no_optimizations;
let prog = compile(&ast);
// println!("{:?}", prog);
let mut vm = Vm::new(prog);
vm.run();
// interpreter.run_text(&code, cfg.print_tokens, cfg.print_ast);
}
if cfg.interactive || cfg.file.is_none() {
let mut code = String::new();
loop {
print!(">> ");
std::io::stdout().flush().unwrap();
code.clear();
std::io::stdin().read_line(&mut code).unwrap();
let code = code.trim();
if code == "exit" {
break;
}
interpreter.run_text(&code, cfg.print_tokens, cfg.print_ast);
if let Some(file) = &conf.file {
let code = match fs::read_to_string(file) {
Ok(code) => code,
Err(_) => nice_panic!("Error: Could not read file '{}'", file),
};
interpreter.run_str(&code);
} else {
println!("Error: No file given\n");
print_help();
}
}
fn print_help() {
println!("Usage nek-lang [FLAGS] [FILE]");
println!("FLAGS: ");
println!("-t, --token Print the lexed tokens");
println!("-a, --ast Print the abstract syntax tree");
println!("-n, --no-opt Disable the AST optimizations");
println!("-h, --help Show this help screen");
exit(0);
}

View File

@@ -1,186 +1,328 @@
use std::iter::Peekable;
use thiserror::Error;
use crate::{
ast::{Ast, BinOpType, Expr, Stmt, UnOpType},
token::{Keyword, Literal, Token},
ast::{Ast, BlockScope, Expression, FunDecl, If, Loop, Statement, VarDecl},
stringstore::{Sid, StringStore},
token::Token,
util::{PutBackIter, PutBackableExt},
T,
};
#[derive(Debug, Error)]
pub enum ParseErr {
#[error("Unexpected Token \"{0:?}\", expected \"{1}\"")]
UnexpectedToken(Token, String),
#[error("Left hand side of declaration is not a variable")]
DeclarationOfNonVar,
#[error("Use of undefined variable \"{0}\"")]
UseOfUndeclaredVar(String),
#[error("Use of undefined function \"{0}\"")]
UseOfUndeclaredFun(String),
#[error("Redeclation of function \"{0}\"")]
RedeclarationFun(String),
#[error("Function not declared at top level \"{0}\"")]
FunctionOnNonTopLevel(String),
}
type ResPE<T> = Result<T, ParseErr>;
macro_rules! validate_next {
($self:ident, $expected_tok:pat, $expected_str:expr) => {
match $self.next() {
$expected_tok => (),
tok => return Err(ParseErr::UnexpectedToken(tok, format!("{}", $expected_str))),
}
};
}
/// Parse the given tokens into an abstract syntax tree
pub fn parse<T: Iterator<Item = Token>, A: IntoIterator<IntoIter = T>>(tokens: A) -> ResPE<Ast> {
let parser = Parser::new(tokens);
parser.parse()
}
struct Parser<T: Iterator<Item = Token>> {
tokens: Peekable<T>,
tokens: PutBackIter<T>,
string_store: StringStore,
var_stack: Vec<Sid>,
fun_stack: Vec<Sid>,
nesting_level: usize,
}
impl<T: Iterator<Item = Token>> Parser<T> {
/// Create a new parser to parse the given Token Stream
fn new<A: IntoIterator<IntoIter = T>>(tokens: A) -> Self {
let tokens = tokens.into_iter().peekable();
Self { tokens }
pub fn new<A: IntoIterator<IntoIter = T>>(tokens: A) -> Self {
let tokens = tokens.into_iter().putbackable();
let string_store = StringStore::new();
let var_stack = Vec::new();
let fun_stack = Vec::new();
Self {
tokens,
string_store,
var_stack,
fun_stack,
nesting_level: 0,
}
}
/// Get the next Token without removing it
fn peek(&mut self) -> &Token {
self.tokens.peek().unwrap_or(&Token::EoF)
pub fn parse(mut self) -> ResPE<Ast> {
let main = self.parse_scoped_block()?;
Ok(Ast {
main,
stringstore: self.string_store,
})
}
/// Advance to next Token and return the removed Token
fn next(&mut self) -> Token {
self.tokens.next().unwrap_or(Token::EoF)
fn parse_scoped_block(&mut self) -> ResPE<BlockScope> {
self.parse_scoped_block_fp_offset(0)
}
fn parse(&mut self) -> Ast {
/// Parse tokens into an abstract syntax tree. This will continuously parse statements until
/// encountering end-of-file or a block end '}' .
fn parse_scoped_block_fp_offset(&mut self, framepoint_offset: usize) -> ResPE<BlockScope> {
self.nesting_level += 1;
let framepointer = self.var_stack.len() - framepoint_offset;
let mut prog = Vec::new();
loop {
match self.peek() {
T![;] => {
self.next();
}
T![EoF] | T!['}'] => break,
T!['{'] => {
self.next();
prog.push(Statement::Block(self.parse_scoped_block()?));
validate_next!(self, T!['}'], "}");
}
// By default try to lex a statement
_ => prog.push(self.parse_stmt()?),
}
}
self.var_stack.truncate(framepointer);
self.nesting_level -= 1;
Ok(prog)
}
/// Parse a single statement from the tokens.
fn parse_stmt(&mut self) -> ResPE<Statement> {
let stmt = match self.peek() {
Token::Semicolon => {
T![break] => {
self.next();
continue;
}
Token::EoF => break,
Token::RBrace => break,
Token::Keyword(keyword) => match keyword {
Keyword::Let => self.parse_let_stmt(),
Keyword::While => self.parse_while(),
Keyword::If => self.parse_if(),
Keyword::For => self.parse_for(),
Keyword::Else => panic!("Unexpected else keyword"),
},
validate_next!(self, T![;], ";");
Token::Dollar => {
self.next();
Stmt::Print(self.parse_expr())
Statement::Break
}
Token::DoubleDollar => {
T![continue] => {
self.next();
Stmt::DbgPrint(self.parse_expr())
validate_next!(self, T![;], ";");
Statement::Continue
}
// By default try to parse an expression
_ => Stmt::Expr(self.parse_expr()),
T![loop] => Statement::Loop(self.parse_loop()?),
T![print] => {
self.next();
let expr = self.parse_expr()?;
// After a statement, there must be a semicolon
validate_next!(self, T![;], ";");
Statement::Print(expr)
}
T![return] => {
self.next();
let stmt = Statement::Return(self.parse_expr()?);
// After a statement, there must be a semicolon
validate_next!(self, T![;], ";");
stmt
}
T![if] => Statement::If(self.parse_if()?),
T![fun] => {
self.next();
let fun_name = match self.next() {
T![ident(fun_name)] => fun_name,
tok => return Err(ParseErr::UnexpectedToken(tok, "<ident>".to_string())),
};
prog.push(stmt);
if self.nesting_level > 1 {
return Err(ParseErr::FunctionOnNonTopLevel(fun_name));
}
Ast { prog }
let fun_name = self.string_store.intern_or_lookup(&fun_name);
if self.fun_stack.contains(&fun_name) {
return Err(ParseErr::RedeclarationFun(
self.string_store
.lookup(fun_name)
.cloned()
.unwrap_or("<unknown>".to_string()),
));
}
fn parse_for(&mut self) -> Stmt {
if !matches!(self.next(), Token::Keyword(Keyword::For)) {
panic!("Error parsing for: Expected for token");
}
let fun_stackpos = self.fun_stack.len();
self.fun_stack.push(fun_name);
let init = match self.parse_let_stmt() {
Stmt::Let(name, rhs) => (name, rhs),
let mut arg_names = Vec::new();
validate_next!(self, T!['('], "(");
while matches!(self.peek(), T![ident(_)]) {
let var_name = match self.next() {
T![ident(var_name)] => var_name,
_ => unreachable!(),
};
if !matches!(self.next(), Token::Semicolon) {
panic!("Error parsing for: Expected semicolon token");
let var_name = self.string_store.intern_or_lookup(&var_name);
arg_names.push(var_name);
// Push the variable onto the varstack
self.var_stack.push(var_name);
// If there are more args skip the comma so that the loop will read the argname
if self.peek() == &T![,] {
self.next();
}
}
let condition = self.parse_expr();
validate_next!(self, T![')'], ")");
if !matches!(self.next(), Token::Semicolon) {
panic!("Error parsing for: Expected semicolon token");
validate_next!(self, T!['{'], "{");
// Create the scoped block with a stack offset. This will pop the args that are
// added to the stack while parsing args
let body = self.parse_scoped_block_fp_offset(arg_names.len())?;
validate_next!(self, T!['}'], "}");
Statement::FunDeclare(FunDecl {
name: fun_name,
fun_stackpos,
argnames: arg_names,
body: body.into(),
})
}
let advance = self.parse_expr();
_ => {
let first = self.next();
if !matches!(self.next(), Token::LBrace) {
panic!("Error parsing for: Expected '{{' token");
}
let body = self.parse();
if !matches!(self.next(), Token::RBrace) {
panic!("Error parsing for: Expected '}}' token");
}
Stmt::For(init, condition, advance, body)
}
fn parse_if(&mut self) -> Stmt {
if !matches!(self.next(), Token::Keyword(Keyword::If)) {
panic!("Error parsing if: Expected if token");
}
let condition = self.parse_expr();
if !matches!(self.next(), Token::LBrace) {
panic!("Error parsing if: Expected '{{' token");
}
let body_if = self.parse();
if !matches!(self.next(), Token::RBrace) {
panic!("Error parsing if: Expected '}}' token");
}
let mut body_else = Ast { prog: Vec::new() };
if matches!(self.peek(), Token::Keyword(Keyword::Else)) {
let stmt = match (first, self.peek()) {
(T![ident(name)], T![<-]) => {
self.next();
if !matches!(self.next(), Token::LBrace) {
panic!("Error parsing else: Expected '{{' token");
let rhs = self.parse_expr()?;
let sid = self.string_store.intern_or_lookup(&name);
let sp = self.var_stack.len();
self.var_stack.push(sid);
Statement::Declaration(VarDecl {
name: sid,
var_stackpos: sp,
rhs,
})
}
body_else = self.parse();
if !matches!(self.next(), Token::RBrace) {
panic!("Error parsing else: Expected '}}' token");
(first, _) => {
self.putback(first);
Statement::Expr(self.parse_expr()?)
}
}
Stmt::If(condition, body_if, body_else)
}
fn parse_while(&mut self) -> Stmt {
if !matches!(self.next(), Token::Keyword(Keyword::While)) {
panic!("Error parsing while: Expected while token");
}
let condition = self.parse_expr();
if !matches!(self.next(), Token::LBrace) {
panic!("Error parsing while: Expected '{{' token");
}
let body = self.parse();
if !matches!(self.next(), Token::RBrace) {
panic!("Error parsing while: Expected '}}' token");
}
Stmt::While(condition, body)
}
fn parse_let_stmt(&mut self) -> Stmt {
if !matches!(self.next(), Token::Keyword(Keyword::Let)) {
panic!("Error parsing let: Expected let token");
}
let name = match self.next() {
Token::Ident(name) => name,
_ => panic!("Error parsing let: Expected identifier after let"),
};
if !matches!(self.next(), Token::Assign) {
panic!("Error parsing let: Expected assignment token");
// After a statement, there must be a semicolon
validate_next!(self, T![;], ";");
stmt
}
};
Ok(stmt)
}
let rhs = self.parse_expr();
/// Parse an if statement from the tokens
fn parse_if(&mut self) -> ResPE<If> {
validate_next!(self, T![if], "if");
Stmt::Let(name, rhs)
let condition = self.parse_expr()?;
validate_next!(self, T!['{'], "{");
let body_true = self.parse_scoped_block()?;
validate_next!(self, T!['}'], "}");
let mut body_false = BlockScope::default();
if self.peek() == &T![else] {
self.next();
validate_next!(self, T!['{'], "{");
body_false = self.parse_scoped_block()?;
validate_next!(self, T!['}'], "}");
}
fn parse_expr(&mut self) -> Expr {
let lhs = self.parse_primary();
Ok(If {
condition,
body_true,
body_false,
})
}
/// Parse a loop statement from the tokens
fn parse_loop(&mut self) -> ResPE<Loop> {
validate_next!(self, T![loop], "loop");
let mut condition = None;
let mut advancement = None;
if !matches!(self.peek(), T!['{']) {
condition = Some(self.parse_expr()?);
if matches!(self.peek(), T![;]) {
self.next();
advancement = Some(self.parse_expr()?);
}
}
validate_next!(self, T!['{'], "{");
let body = self.parse_scoped_block()?;
validate_next!(self, T!['}'], "}");
Ok(Loop {
condition,
advancement,
body,
})
}
/// Parse a single expression from the tokens
fn parse_expr(&mut self) -> ResPE<Expression> {
let lhs = self.parse_primary()?;
self.parse_expr_precedence(lhs, 0)
}
/// Parse binary expressions with a precedence equal to or higher than min_prec
fn parse_expr_precedence(&mut self, mut lhs: Expr, min_prec: u8) -> Expr {
fn parse_expr_precedence(&mut self, mut lhs: Expression, min_prec: u8) -> ResPE<Expression> {
while let Some(binop) = &self.peek().try_to_binop() {
// Stop if the next operator has a lower binding power
if !(binop.precedence() >= min_prec) {
@@ -191,117 +333,191 @@ impl<T: Iterator<Item = Token>> Parser<T> {
// valid
let binop = self.next().try_to_binop().unwrap();
let mut rhs = self.parse_primary();
let mut rhs = self.parse_primary()?;
while let Some(binop2) = &self.peek().try_to_binop() {
if !(binop2.precedence() > binop.precedence()) {
break;
}
rhs = self.parse_expr_precedence(rhs, binop.precedence() + 1);
rhs = self.parse_expr_precedence(rhs, binop.precedence() + 1)?;
}
lhs = Expr::BinOp(binop, lhs.into(), rhs.into());
lhs = Expression::BinOp(binop, lhs.into(), rhs.into());
}
lhs
Ok(lhs)
}
/// Parse a primary expression (for now only number)
fn parse_primary(&mut self) -> Expr {
match self.next() {
Token::Literal(Literal::I64(val)) => Expr::I64(val),
fn parse_primary(&mut self) -> ResPE<Expression> {
let primary = match self.next() {
// Literal i64
T![i64(val)] => Expression::I64(val),
Token::Literal(Literal::Str(text)) => Expr::Str(text.into()),
// Literal String
T![str(text)] => Expression::String(self.string_store.intern_or_lookup(&text)),
Token::Ident(name) => Expr::Ident(name),
// Array literal. Square brackets containing the array size as expression
T!['['] => {
let size = self.parse_expr()?;
Token::LParen => {
// The tokens was an opening parenthesis, so parse a full expression again as the
// expression inside the parentheses `"(" expr ")"`
let inner = self.parse_expr();
validate_next!(self, T![']'], "]");
// If there is no closing parenthesis after the expression, it is a syntax error
if !matches!(self.next(), Token::RParen) {
panic!("Error parsing primary expr: Missing closing parenthesis ')'");
Expression::ArrayLiteral(size.into())
}
inner
// Array sccess, aka indexing. An ident followed by square brackets containing the
// index as an expression
T![ident(name)] if self.peek() == &T!['['] => {
let sid = self.string_store.intern_or_lookup(&name);
let stackpos = self.get_stackpos(sid)?;
self.next();
let index = self.parse_expr()?;
validate_next!(self, T![']'], "]");
Expression::ArrayAccess(sid, stackpos, index.into())
}
Token::Sub => Expr::UnOp(UnOpType::Neg, self.parse_primary().into()),
T![ident(name)] if self.peek() == &T!['('] => {
// Skip the opening parenthesis
self.next();
tok => panic!("Error parsing primary expr: Unexpected Token '{:?}'", tok),
let sid = self.string_store.intern_or_lookup(&name);
let mut args = Vec::new();
while !matches!(self.peek(), T![')']) {
let arg = self.parse_expr()?;
args.push(arg);
// If there are more args skip the comma so that the loop will read the argname
if self.peek() == &T![,] {
self.next();
}
}
validate_next!(self, T![')'], ")");
let fun_stackpos = self.get_fun_stackpos(sid)?;
Expression::FunCall(sid, fun_stackpos, args)
}
pub fn parse<T: Iterator<Item = Token>, A: IntoIterator<IntoIter = T>>(tokens: A) -> Ast {
let mut parser = Parser::new(tokens);
parser.parse()
T![ident(name)] => {
let sid = self.string_store.intern_or_lookup(&name);
let stackpos = self.get_stackpos(sid)?;
Expression::Var(sid, stackpos)
}
impl BinOpType {
/// Get the precedence for a binary operator. Higher value means the OP is stronger binding.
/// For example Multiplication is stronger than addition, so Mul has higher precedence than Add.
///
/// The operator precedences are derived from the C language operator precedences. While not all
/// C operators are included or the exact same, the precedence oder is the same.
/// See: https://en.cppreference.com/w/c/language/operator_precedence
fn precedence(&self) -> u8 {
match self {
BinOpType::Assign => 0,
BinOpType::BOr => 1,
BinOpType::BXor => 2,
BinOpType::BAnd => 3,
BinOpType::Equ | BinOpType::Neq => 4,
BinOpType::Gt | BinOpType::Ge | BinOpType::Lt | BinOpType::Le => 5,
BinOpType::Shl | BinOpType::Shr => 6,
BinOpType::Add | BinOpType::Sub => 7,
BinOpType::Mul | BinOpType::Div | BinOpType::Mod => 8,
// Parentheses grouping
T!['('] => {
let inner_expr = self.parse_expr()?;
// Verify that there is a closing parenthesis
validate_next!(self, T![')'], ")");
inner_expr
}
// Unary operations or invalid token
tok => match tok.try_to_unop() {
Some(uot) => Expression::UnOp(uot, self.parse_primary()?.into()),
None => return Err(ParseErr::UnexpectedToken(tok, "primary".to_string())),
},
};
Ok(primary)
}
fn get_stackpos(&self, varid: Sid) -> ResPE<usize> {
self.var_stack
.iter()
.rev()
.position(|it| *it == varid)
.map(|it| it)
.ok_or(ParseErr::UseOfUndeclaredVar(
self.string_store
.lookup(varid)
.map(String::from)
.unwrap_or("<unknown>".to_string()),
))
}
fn get_fun_stackpos(&self, varid: Sid) -> ResPE<usize> {
self.fun_stack
.iter()
.rev()
.position(|it| *it == varid)
.map(|it| self.fun_stack.len() - it - 1)
.ok_or(ParseErr::UseOfUndeclaredFun(
self.string_store
.lookup(varid)
.map(String::from)
.unwrap_or("<unknown>".to_string()),
))
}
/// Get the next Token without removing it
fn peek(&mut self) -> &Token {
self.tokens.peek().unwrap_or(&T![EoF])
}
fn putback(&mut self, tok: Token) {
self.tokens.putback(tok);
}
/// Advance to next Token and return the removed Token
fn next(&mut self) -> Token {
self.tokens.next().unwrap_or(T![EoF])
}
}
#[cfg(test)]
mod tests {
use super::{parse, BinOpType, Expr};
use crate::{
parser::{Ast, Stmt},
token::{Literal, Token},
ast::{BinOpType, Expression, Statement},
parser::parse,
T,
};
#[test]
fn test_parser() {
// Expression: 1 + 2 * 3 + 4
// With precedence: (1 + (2 * 3)) + 4
// Expression: 1 + 2 * 3 - 4
// With precedence: (1 + (2 * 3)) - 4
let tokens = [
Token::Literal(Literal::I64(1)),
Token::Add,
Token::Literal(Literal::I64(2)),
Token::Mul,
Token::Literal(Literal::I64(3)),
Token::Sub,
Token::Literal(Literal::I64(4)),
T![i64(1)],
T![+],
T![i64(2)],
T![*],
T![i64(3)],
T![-],
T![i64(4)],
T![;],
];
let expected = Expr::BinOp(
let expected = Statement::Expr(Expression::BinOp(
BinOpType::Sub,
Expr::BinOp(
Expression::BinOp(
BinOpType::Add,
Expr::I64(1).into(),
Expr::BinOp(BinOpType::Mul, Expr::I64(2).into(), Expr::I64(3).into()).into(),
Expression::I64(1).into(),
Expression::BinOp(
BinOpType::Mul,
Expression::I64(2).into(),
Expression::I64(3).into(),
)
.into(),
Expr::I64(4).into(),
);
)
.into(),
Expression::I64(4).into(),
));
let expected = Ast {
prog: vec![Stmt::Expr(expected)],
};
let expected = vec![expected];
let actual = parse(tokens);
assert_eq!(expected, actual);
let actual = parse(tokens).unwrap();
assert_eq!(expected, actual.main);
}
}

31
src/stringstore.rs Normal file
View File

@@ -0,0 +1,31 @@
use std::collections::HashMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Sid(usize);
#[derive(Clone, Default)]
pub struct StringStore {
strings: Vec<String>,
sids: HashMap<String, Sid>,
}
impl StringStore {
pub fn new() -> Self {
Self { strings: Vec::new(), sids: HashMap::new() }
}
pub fn intern_or_lookup(&mut self, text: &str) -> Sid {
self.sids.get(text).copied().unwrap_or_else(|| {
let sid = Sid(self.strings.len());
self.strings.push(text.to_string());
self.sids.insert(text.to_string(), sid);
sid
})
}
pub fn lookup(&self, sid: Sid) -> Option<&String> {
self.strings.get(sid.0)
}
}

View File

@@ -1,147 +1,371 @@
use crate::ast::BinOpType;
use crate::{
ast::{BinOpType, UnOpType},
T,
};
/// Language keywords
#[derive(Debug, PartialEq, Eq)]
pub enum Keyword {
/// Loop keyword ("loop")
Loop,
/// Print keyword ("print")
Print,
/// If keyword ("if")
If,
/// Else keyword ("else")
Else,
/// Function declaration keyword ("fun")
Fun,
/// Return keyword ("return")
Return,
/// Break keyword ("break")
Break,
/// Continue keyword ("continue")
Continue,
}
/// Literal values
#[derive(Debug, PartialEq, Eq)]
pub enum Literal {
/// Integer literal (64-bit)
I64(i64),
/// String literal ("Some string")
Str(String),
/// String literal
String(String),
}
/// Combined tokens that consist of a combination of characters
#[derive(Debug, PartialEq, Eq)]
pub enum Keyword {
/// Let identifier (let)
Let,
pub enum Combo {
/// Equal Equal ("==")
Equal2,
/// While (while)
While,
/// Exclamation mark Equal ("!=")
ExclamationMarkEqual,
/// For (for)
For,
/// Ampersand Ampersand ("&&")
Ampersand2,
/// If (if)
If,
/// Pipe Pipe ("||")
Pipe2,
/// Else (else)
Else,
/// LessThan LessThan ("<<")
LessThan2,
/// GreaterThan GreaterThan (">>")
GreaterThan2,
/// LessThan Equal ("<=")
LessThanEqual,
/// GreaterThan Equal (">=")
GreaterThanEqual,
/// LessThan Minus ("<-")
LessThanMinus,
}
#[derive(Debug, PartialEq, Eq)]
pub enum Token {
/// Literal values
/// Literal value token
Literal(Literal),
/// Identifier (variable / function / ... name)
Ident(String),
/// Specific identifiers that have a special meaning as keywords
/// Keyword token
Keyword(Keyword),
/// Left parenthesis ('(')
LParen,
/// Identifier (name for variables, functions, ...)
Ident(String),
/// Right parentheses (')')
RParen,
/// Combined tokens consisting of multiple characters
Combo(Combo),
/// Left brace ({)
LBrace,
/// Comma (",")
Comma,
/// Right brace (})
RBrace,
/// Equal Sign ("=")
Equal,
/// Dollar sign ($)
Dollar,
/// Double Dollar sign ($$)
DoubleDollar,
/// Assignment (single equal) (=)
Assign,
/// Plus (+)
Add,
/// Minus (-)
Sub,
/// Asterisk (*)
Mul,
/// Slash (/)
Div,
/// Percent (%)
Mod,
/// Pipe (|)
BOr,
/// Ampersand (&)
BAnd,
/// Circumflex (^)
BXor,
/// Shift Left (<<)
Shl,
/// Shift Right (>>)
Shr,
/// Equal sign (==)
Equ,
/// Not Equal sign (!=)
Neq,
/// Greater than (>)
Gt,
/// Greater or equal (>=)
Ge,
/// Less than (<)
Lt,
/// Less or equal (<=)
Le,
/// Semicolon (;)
/// Semicolon (";")
Semicolon,
/// End of file
EoF,
/// Left Bracket ("[")
LBracket,
/// Right Bracket ("]")
RBracket,
/// Left Parenthesis ("(")
LParen,
/// Right Parenthesis (")"")
RParen,
/// Left curly braces ("{")
LBraces,
/// Right curly braces ("}")
RBraces,
/// Plus ("+")
Plus,
/// Minus ("-")
Minus,
/// Asterisk ("*")
Asterisk,
/// Slash ("/")
Slash,
/// Percent ("%")
Percent,
/// Pipe ("|")
Pipe,
/// Tilde ("~")
Tilde,
/// Logical not ("!")
Exclamationmark,
/// Left angle bracket ("<")
LessThan,
/// Right angle bracket (">")
GreaterThan,
/// Ampersand ("&")
Ampersand,
/// Circumflex ("^")
Circumflex,
}
impl Token {
/// If the Token can be used as a binary operation type, get the matching BinOpType. Otherwise
/// return None.
pub fn try_to_binop(&self) -> Option<BinOpType> {
Some(match self {
Token::Add => BinOpType::Add,
Token::Sub => BinOpType::Sub,
T![+] => BinOpType::Add,
T![-] => BinOpType::Sub,
Token::Mul => BinOpType::Mul,
Token::Div => BinOpType::Div,
Token::Mod => BinOpType::Mod,
T![*] => BinOpType::Mul,
T![/] => BinOpType::Div,
T![%] => BinOpType::Mod,
Token::BAnd => BinOpType::BAnd,
Token::BOr => BinOpType::BOr,
Token::BXor => BinOpType::BXor,
T![&] => BinOpType::BAnd,
T![|] => BinOpType::BOr,
T![^] => BinOpType::BXor,
Token::Shl => BinOpType::Shl,
Token::Shr => BinOpType::Shr,
T![&&] => BinOpType::LAnd,
T![||] => BinOpType::LOr,
Token::Equ => BinOpType::Equ,
Token::Neq => BinOpType::Neq,
T![<<] => BinOpType::Shl,
T![>>] => BinOpType::Shr,
Token::Gt => BinOpType::Gt,
Token::Ge => BinOpType::Ge,
Token::Lt => BinOpType::Lt,
Token::Le => BinOpType::Le,
T![==] => BinOpType::EquEqu,
T![!=] => BinOpType::NotEqu,
Token::Assign => BinOpType::Assign,
T![<] => BinOpType::Less,
T![<=] => BinOpType::LessEqu,
T![>] => BinOpType::Greater,
T![>=] => BinOpType::GreaterEqu,
T![=] => BinOpType::Assign,
_ => return None,
})
}
pub fn try_to_unop(&self) -> Option<UnOpType> {
Some(match self {
T![-] => UnOpType::Negate,
T![!] => UnOpType::LNot,
T![~] => UnOpType::BNot,
_ => return None,
})
}
}
/// Macro to quickly create a token of the specified kind
#[macro_export]
macro_rules! T {
// Keywords
[loop] => {
crate::token::Token::Keyword(crate::token::Keyword::Loop)
};
[print] => {
crate::token::Token::Keyword(crate::token::Keyword::Print)
};
[if] => {
crate::token::Token::Keyword(crate::token::Keyword::If)
};
[else] => {
crate::token::Token::Keyword(crate::token::Keyword::Else)
};
[fun] => {
crate::token::Token::Keyword(crate::token::Keyword::Fun)
};
[return] => {
crate::token::Token::Keyword(crate::token::Keyword::Return)
};
[break] => {
crate::token::Token::Keyword(crate::token::Keyword::Break)
};
[continue] => {
crate::token::Token::Keyword(crate::token::Keyword::Continue)
};
// Literals
[i64($($val:tt)*)] => {
crate::token::Token::Literal(crate::token::Literal::I64($($val)*))
};
[str($($val:tt)*)] => {
crate::token::Token::Literal(crate::token::Literal::String($($val)*))
};
// Ident
[ident($($val:tt)*)] => {
crate::token::Token::Ident($($val)*)
};
// Combo crate::token::Tokens
[==] => {
crate::token::Token::Combo(crate::token::Combo::Equal2)
};
[!=] => {
crate::token::Token::Combo(crate::token::Combo::ExclamationMarkEqual)
};
[&&] => {
crate::token::Token::Combo(crate::token::Combo::Ampersand2)
};
[||] => {
crate::token::Token::Combo(crate::token::Combo::Pipe2)
};
[<<] => {
crate::token::Token::Combo(crate::token::Combo::LessThan2)
};
[>>] => {
crate::token::Token::Combo(crate::token::Combo::GreaterThan2)
};
[<=] => {
crate::token::Token::Combo(crate::token::Combo::LessThanEqual)
};
[>=] => {
crate::token::Token::Combo(crate::token::Combo::GreaterThanEqual)
};
[<-] => {
crate::token::Token::Combo(crate::token::Combo::LessThanMinus)
};
// Normal Tokens
[,] => {
crate::token::Token::Comma
};
[=] => {
crate::token::Token::Equal
};
[;] => {
crate::token::Token::Semicolon
};
[EoF] => {
crate::token::Token::EoF
};
['['] => {
crate::token::Token::LBracket
};
[']'] => {
crate::token::Token::RBracket
};
['('] => {
crate::token::Token::LParen
};
[')'] => {
crate::token::Token::RParen
};
['{'] => {
crate::token::Token::LBraces
};
['}'] => {
crate::token::Token::RBraces
};
[+] => {
crate::token::Token::Plus
};
[-] => {
crate::token::Token::Minus
};
[*] => {
crate::token::Token::Asterisk
};
[/] => {
crate::token::Token::Slash
};
[%] => {
crate::token::Token::Percent
};
[|] => {
crate::token::Token::Pipe
};
[~] => {
crate::token::Token::Tilde
};
[!] => {
crate::token::Token::Exclamationmark
};
[<] => {
crate::token::Token::LessThan
};
[>] => {
crate::token::Token::GreaterThan
};
[&] => {
crate::token::Token::Ampersand
};
[^] => {
crate::token::Token::Circumflex
};
}

167
src/util.rs Normal file
View File

@@ -0,0 +1,167 @@
/// Exit the program with error code 1 and format-print the given text on stderr. This pretty much
/// works like panic, but doesn't show the additional information that panic adds. Those can be
/// interesting for debugging, but don't look that great when building a release executable for an
/// end user.
/// When running tests or running in debug mode, panic is used to ensure the tests working
/// correctly.
#[macro_export]
macro_rules! nice_panic {
($fmt:expr) => {
{
if cfg!(test) || cfg!(debug_assertions) {
panic!($fmt);
} else {
eprintln!($fmt);
std::process::exit(1);
}
}
};
($fmt:expr, $($arg:tt)*) => {
{
if cfg!(test) || cfg!(debug_assertions) {
panic!($fmt, $($arg)*);
} else {
eprintln!($fmt, $($arg)*);
std::process::exit(1);
}
}
};
}
/// The PutBackIter allows for items to be put back back and to be peeked. Putting an item back
/// will cause it to be the next item returned by `next`. Peeking an item will get a reference to
/// the next item in the iterator without removing it.
///
/// The whole PutBackIter behaves analogous to `std::iter::Peekable` with the addition of the
/// `putback` function. This is slightly slower than `Peekable`, but allows for an unlimited number
/// of putbacks and therefore an unlimited look-ahead range.
pub struct PutBackIter<T: Iterator> {
iter: T,
putback_stack: Vec<T::Item>,
}
impl<T> PutBackIter<T>
where
T: Iterator,
{
/// Make the given iterator putbackable, wrapping it in the PutBackIter type. This effectively
/// adds the `peek` and `putback` functions.
pub fn new(iter: T) -> Self {
Self {
iter,
putback_stack: Vec::new(),
}
}
/// Put the given item back into the iterator. This causes the putbacked items to be returned by
/// next in last-in-first-out order (aka. stack order). Only after all previously putback items
/// have been returned, the actual underlying iterator is used to get items.
/// The number of items that can be put back is unlimited.
pub fn putback(&mut self, it: T::Item) {
self.putback_stack.push(it);
}
/// Peek the next item, getting a reference to it without removing it from the iterator. This
/// also includes items that were previsouly put back and not yet removed.
pub fn peek(&mut self) -> Option<&T::Item> {
if self.putback_stack.is_empty() {
let it = self.next()?;
self.putback(it);
}
self.putback_stack.last()
}
}
impl<T> Iterator for PutBackIter<T>
where
T: Iterator,
{
type Item = T::Item;
fn next(&mut self) -> Option<Self::Item> {
match self.putback_stack.pop() {
Some(it) => Some(it),
None => self.iter.next(),
}
}
}
pub trait PutBackableExt {
/// Make the iterator putbackable, wrapping it in the PutBackIter type. This effectively
/// adds the `peek` and `putback` functions.
fn putbackable(self) -> PutBackIter<Self>
where
Self: Iterator + Sized,
{
PutBackIter::new(self)
}
}
impl<T: Iterator> PutBackableExt for T {}
#[cfg(test)]
mod tests {
use super::PutBackableExt;
#[test]
fn putback_iter_next() {
let mut iter = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter();
let mut pb_iter = iter.clone().putbackable();
// Check if next works
for _ in 0..iter.len() {
assert_eq!(pb_iter.next(), iter.next());
}
}
#[test]
fn putback_iter_peek() {
let mut iter_orig = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter();
let mut iter = iter_orig.clone();
let mut pb_iter = iter.clone().putbackable();
for _ in 0..iter.len() {
// Check if peek gives a preview of the actual next element
assert_eq!(pb_iter.peek(), iter.next().as_ref());
// Check if next still returns the next (just peeked) element and not the one after
assert_eq!(pb_iter.next(), iter_orig.next());
}
}
#[test]
fn putback_iter_putback() {
let mut iter_orig = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter();
let mut iter = iter_orig.clone();
let mut pb_iter = iter.clone().putbackable();
// Get the first 5 items with next and check if they match
let it0 = pb_iter.next();
assert_eq!(it0, iter.next());
let it1 = pb_iter.next();
assert_eq!(it1, iter.next());
let it2 = pb_iter.next();
assert_eq!(it2, iter.next());
let it3 = pb_iter.next();
assert_eq!(it3, iter.next());
let it4 = pb_iter.next();
assert_eq!(it4, iter.next());
// Put one value back and check if `next` works as expected, returning the just put back
// item
pb_iter.putback(it0.unwrap());
assert_eq!(pb_iter.next(), it0);
// Put all values back
pb_iter.putback(it4.unwrap());
pb_iter.putback(it3.unwrap());
pb_iter.putback(it2.unwrap());
pb_iter.putback(it1.unwrap());
pb_iter.putback(it0.unwrap());
// After all values have been put back, the iter should match the original again
for _ in 0..iter.len() {
assert_eq!(pb_iter.next(), iter_orig.next());
}
}
}

187
src/vm.rs
View File

@@ -1,187 +0,0 @@
use crate::{bytecode::OP, interpreter::Value};
#[derive(Debug, Default)]
pub struct Vm {
prog: Vec<u32>,
ip: usize,
stack: Vec<Value>,
/// This isn't actually a heap. It's actually still more of a f*cked up stack
heap: Vec<Value>,
}
impl Vm {
pub fn new(prog: Vec<u32>) -> Self {
Self {
prog,
..Default::default()
}
}
pub fn run(&mut self) {
while let Some(op) = self.prog.get(self.ip).copied().map(|op| unsafe { std::mem::transmute::<u32, OP>(op) }) {
self.ip += 1;
match op {
OP::Push => {
let val = self.read_i64();
self.stack.push(Value::I64(val));
}
OP::Pop => {
self.stack.pop();
}
OP::Load => {
let addr = self.read_i64() as usize;
if let Some(val) = self.heap.get(addr) {
self.stack.push(val.clone());
} else {
panic!("Trying to load from uninitialized heap");
}
}
OP::Store => {
let val = self
.stack
.pop()
.expect("Trying to pop value from stack for storing");
let addr = self.read_i64() as usize;
if self.heap.len() == addr {
self.heap.push(val);
} else {
self.heap[addr] = val;
}
}
OP::Print => {
let val = self
.stack
.pop()
.expect("Trying to pop value from stack for printing");
print!("{}", val);
}
OP::DbgPrint => {
let val = self
.stack
.pop()
.expect("Trying to pop value from stack for printing");
print!("{:?}", val);
}
OP::Add => {
let vals = self.pop2_i64();
self.stack.push(Value::I64(vals.0 + vals.1))
}
OP::Subtract => {
let vals = self.pop2_i64();
self.stack.push(Value::I64(vals.0 - vals.1))
}
OP::Multiply => {
let vals = self.pop2_i64();
self.stack.push(Value::I64(vals.0 * vals.1))
}
OP::Divide => {
let vals = self.pop2_i64();
self.stack.push(Value::I64(vals.0 / vals.1))
}
OP::Modulo => {
let vals = self.pop2_i64();
self.stack.push(Value::I64(vals.0 % vals.1))
}
OP::Eq => {
let vals = self.pop2_i64();
self.stack
.push(Value::I64(if vals.0 == vals.1 { 1 } else { 0 }))
}
OP::Neq => {
let vals = self.pop2_i64();
self.stack
.push(Value::I64(if vals.0 != vals.1 { 1 } else { 0 }))
}
OP::Gt => {
let vals = self.pop2_i64();
self.stack
.push(Value::I64(if vals.0 > vals.1 { 1 } else { 0 }))
}
OP::Ge => {
let vals = self.pop2_i64();
self.stack
.push(Value::I64(if vals.0 >= vals.1 { 1 } else { 0 }))
}
OP::Lt => {
let vals = self.pop2_i64();
self.stack
.push(Value::I64(if vals.0 < vals.1 { 1 } else { 0 }))
}
OP::Le => {
let vals = self.pop2_i64();
self.stack
.push(Value::I64(if vals.0 <= vals.1 { 1 } else { 0 }))
}
OP::BOr => {
let vals = self.pop2_i64();
self.stack.push(Value::I64(vals.0 | vals.1))
}
OP::BAnd => {
let vals = self.pop2_i64();
self.stack.push(Value::I64(vals.0 & vals.1))
}
OP::BXor => {
let vals = self.pop2_i64();
self.stack.push(Value::I64(vals.0 ^ vals.1))
}
OP::Shl => {
let vals = self.pop2_i64();
self.stack.push(Value::I64(vals.0 << vals.1))
}
OP::Shr => {
let vals = self.pop2_i64();
self.stack.push(Value::I64(vals.0 >> vals.1))
}
OP::Jump => {
self.ip = self.read_i64() as usize;
}
OP::JumpTrue => {
let jmp_target = self.read_i64() as usize;
if !matches!(self.stack.pop(), Some(Value::I64(0))) {
self.ip = jmp_target;
}
}
OP::JumpFalse => {
let jmp_target = self.read_i64() as usize;
if matches!(self.stack.pop(), Some(Value::I64(0))) {
self.ip = jmp_target;
}
}
}
}
}
fn pop2_i64(&mut self) -> (i64, i64) {
let rhs = self.stack.pop();
let lhs = self.stack.pop();
match (lhs, rhs) {
(Some(Value::I64(lhs)), Some(Value::I64(rhs))) => (lhs, rhs),
_ => panic!("Invalid data for add"),
}
}
fn read_i64(&mut self) -> i64 {
let mut val = *self.prog.get(self.ip).unwrap() as i64;
val |= (*self.prog.get(self.ip + 1).unwrap() as i64) << 32;
// let mut bytes = [0; 8];
// bytes.copy_from_slice(&self.prog[self.ip..self.ip+8]);
// val = i64::from_le_bytes(bytes);
// for i in 0 .. 8 {
// if let Some(tmp) = self.prog.get(self.ip + i).copied() {
// val |= ((tmp as i64) << i*8) as i64;
// } else {
// panic!("Expected Value as next OP")
// }
// }
self.ip += 2;
val
}
}