Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: Functions #1

Merged
merged 9 commits into from
Jul 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
lark
.vscode
18 changes: 18 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch Package",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}",
"args": ["source.lark"],
"env": {},
"preLaunchTask": "build-lark"
}
]
}
15 changes: 15 additions & 0 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build-lark",
"type": "shell",
"command": "go build -o lark",
"group": "build",
"presentation": {
"reveal": "silent"
},
"problemMatcher": ["$go"]
}
]
}
34 changes: 29 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,17 +53,41 @@ a <-> b;
> functions

```
fn addstatic[] <<
fn addStaticVars[] <<
return 100+500;
>>

fn addwithnoreturn[] <<
fn addWithNoReturn[] <<
a <- 100;
>>

a <- 500;
staticsum <- addstatic();
addwithnoreturn(); // a = 100
fn addWithArgs[a,b] <<
return a+b;
>>

fn addWithArgsAndLocalVar[a,b] <<
local c <- 3;
return a+b+c;
>>

fn addWithDynamicArgs[a,b] <<
return a+b;
>>

fn addWithStaticAndDynamicArgs[a,b] <<
return a+b;
>>

addWithNoReturn();
staticsum <- addStaticVars();
sumOne <- addWithArgs(1, 2); // 3
sumTwo <- addWithArgsAndLocalVar(1, 2); // 6

first <- 100;
second <- 200;
sumThree <- addWithDynamicArgs(first+(5-3)*second, second); // 700

sumFour <- addWithStaticAndDynamicArgs(first, 2000); // 2100
```

### Usage
Expand Down
Binary file added __debug_bin4110900408
Binary file not shown.
10 changes: 8 additions & 2 deletions lark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ func evaluate(t *testing.T, sourceFile string) map[string]interface{} {

root := types.Compound{Children: []types.Node{}}
symbolTable = make(map[string]interface{})
localSymbolTable = make(map[string]interface{})
tokens := token.Tokenize(string(content))
builder := ast.NewAstBuilder(tokens.Tokens)
var tree types.Node
Expand All @@ -26,7 +27,8 @@ func evaluate(t *testing.T, sourceFile string) map[string]interface{} {
}
}
evaluator := ast.Evaluator{
SymbolTable: symbolTable,
SymbolTable: symbolTable,
LocalSymbolTable: localSymbolTable,
}

for _, node := range root.Children {
Expand Down Expand Up @@ -135,8 +137,12 @@ func Test_Parser(t *testing.T) {

func Test_Function(t *testing.T) {
symbolTable := evaluate(t, "test_source_files/function.lark")
assert.Equal(t, len(symbolTable), 4)
assert.Equal(t, 12, len(symbolTable))
assert.Equal(t, 1000, symbolTable["fna"])
assert.Equal(t, 500, symbolTable["fnb"])
assert.Equal(t, 1500, symbolTable["fnval"])
assert.Equal(t, 3, symbolTable["sum"])
assert.Equal(t, 9, symbolTable["localSum"])
assert.Equal(t, 103, symbolTable["dynamicSum"])
assert.Equal(t, 603, symbolTable["expressionSum"])
}
5 changes: 4 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
)

var symbolTable map[string]interface{}
var localSymbolTable map[string]interface{}

func main() {
if len(os.Args) < 2 {
Expand All @@ -24,6 +25,7 @@ func main() {
root := types.Compound{Children: []types.Node{}}

symbolTable = make(map[string]interface{})
localSymbolTable = make(map[string]interface{})
tokens := token.Tokenize(string(content))
builder := ast.NewAstBuilder(tokens.Tokens)
var tree types.Node
Expand All @@ -34,7 +36,8 @@ func main() {
}
}
evaluator := ast.Evaluator{
SymbolTable: symbolTable,
SymbolTable: symbolTable,
LocalSymbolTable: localSymbolTable,
}

for _, node := range root.Children {
Expand Down
45 changes: 38 additions & 7 deletions pkg/ast/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ func (a *AstBuilder) Expr() types.Node {
return nil
}
left := a.Term()
// z := a.getCurrentToken().TokenType
switch a.getCurrentToken().TokenType {
case types.TRUE, types.FALSE, types.NOT:
op := a.getCurrentToken().TokenType
Expand All @@ -65,7 +64,14 @@ func (a *AstBuilder) Expr() types.Node {
right := a.Term()
left = types.BinOP{Left: left, Right: right, Op: op}
}
case types.ASSIGN:
case types.ASSIGN, types.LOCAL:
assignType := types.GLOBAL_ASSIGN
if a.getCurrentToken().TokenType == types.LOCAL {
a.eat(types.LOCAL)
assignType = types.LOCAL_ASSIGN
left = a.Term()
}

a.eat(types.ASSIGN)
right := a.Expr()
switch right.(type) {
Expand All @@ -74,10 +80,18 @@ func (a *AstBuilder) Expr() types.Node {
default:
a.eat(types.SEMICOLON)
}
return types.Assign{Id: left, Value: right}
return types.Assign{Id: left, Value: right, Type: assignType}
case types.FUNCTION_CALL:
fn := types.FunctionCall{Name: a.getCurrentToken().Value.(types.Literal).Value.(string)}
a.eat(types.FUNCTION_CALL)
a.eat(types.FUNCTION_CALL_OPEN)
for a.getCurrentToken().TokenType != types.FUNCTION_CALL_CLOSE {
fn.Arguments = append(fn.Arguments, a.Expr())
if a.getCurrentToken().TokenType == types.FUNCTION_ARGUMENT_SEPARATOR {
a.eat(types.FUNCTION_ARGUMENT_SEPARATOR)
}
}
a.eat(types.FUNCTION_CALL_CLOSE)
a.eat(types.SEMICOLON)
return fn
case types.FUNCTION:
Expand All @@ -87,8 +101,10 @@ func (a *AstBuilder) Expr() types.Node {
function := types.Function{
Name: functionName.(string),
}
a.eat(types.FUNCTION_ARGUMENT_OPEN)
a.eat(types.FUNCTION_ARGUMENT_CLOSE)
for a.getCurrentToken().TokenType == types.FUNCTION_ARGUMENT {
function.Arguments = append(function.Arguments, a.getCurrentToken().Value)
a.eat(types.FUNCTION_ARGUMENT)
}
a.eat(types.FUNCTION_OPEN)
for a.getCurrentToken().TokenType != types.FUNCTION_RETURN && a.getCurrentToken().TokenType != types.FUNCTION_CLOSE {
node := a.Expr()
Expand Down Expand Up @@ -162,11 +178,24 @@ func (a *AstBuilder) Factor() types.Node {
case types.LITERAL:
a.eat(types.LITERAL)
return types.Literal{Value: a.tokens[c].Value, Type: a.tokens[c].LiteralType}
case types.FUNCTION_ARGUMENT:
val := a.getCurrentToken().Value.(types.Literal)
a.eat(types.FUNCTION_ARGUMENT)
switch val.Type {
case types.INTEGER:
return types.Literal{Value: val.Value, Type: types.INTEGER}
case types.STRING:
return types.Literal{Value: val.Value, Type: types.STRING}
case types.FLOAT64:
return types.Literal{Value: val.Value, Type: types.FLOAT64}
}
case types.ID:
a.eat(types.ID)
return types.Id{Name: a.tokens[c].Value.(types.Literal).Value.(string)}
case types.SEMICOLON:
a.eat(types.SEMICOLON)
case types.LOCAL:
return types.Literal{Value: "local", Type: types.KEYWORD}
case types.SEMICOLON, types.FUNCTION_ARGUMENT_SEPARATOR:
a.eat(a.tokens[c].TokenType)
case types.LBRACE:
a.eat(types.LBRACE)
expr := a.Expr()
Expand All @@ -177,5 +206,7 @@ func (a *AstBuilder) Factor() types.Node {
right := a.Expr()
return right
}

// fmt.Println("got nil ", a.getCurrentToken().TokenType)
return nil
}
48 changes: 44 additions & 4 deletions pkg/ast/evaluate.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import (
)

type Evaluator struct {
SymbolTable map[string]interface{}
SymbolTable map[string]interface{}
LocalSymbolTable map[string]interface{}
}

type Comparator interface {
Expand Down Expand Up @@ -148,7 +149,11 @@ func (e *Evaluator) Visit(node types.Node) interface{} {
}
case types.Assign:
right := e.Visit(n.Value)
e.SymbolTable[n.Id.(types.Id).Name] = right
if n.Type == types.GLOBAL_ASSIGN {
e.SymbolTable[n.Id.(types.Id).Name] = right
} else {
e.LocalSymbolTable[n.Id.(types.Id).Name] = right
}
return right
case types.Function:
e.SymbolTable[n.Name] = n
Expand All @@ -157,6 +162,33 @@ func (e *Evaluator) Visit(node types.Node) interface{} {
if !ok {
log.Fatalf("variable '%s' not defined", n.Name)
}
if len(node.(types.FunctionCall).Arguments) != len(e.SymbolTable[n.Name].(types.Function).Arguments) {
log.Fatalf("function arguments mismatch\n")
}

functionCallArgs := node.(types.FunctionCall).Arguments
for i, v := range e.SymbolTable[n.Name].(types.Function).Arguments {
switch functionCallArgs[i].(type) {
case types.Literal:
switch functionCallArgs[i].(types.Literal).Type {
case types.IDENT:
value := e.SymbolTable[functionCallArgs[i].(types.Literal).Value.(string)]
e.LocalSymbolTable[v.(types.Literal).Value.(string)] = value
default:
e.LocalSymbolTable[v.(types.Literal).Value.(string)] = e.Visit(functionCallArgs[i])
}
default:
value := e.Visit(functionCallArgs[i])
variable := e.Visit(v)
e.LocalSymbolTable[variable.(string)] = value
}
}
defer func() {
for _, v := range e.SymbolTable[n.Name].(types.Function).Arguments {
delete(e.LocalSymbolTable, v.(types.Literal).Value.(string))
}
}()

for _, v := range e.SymbolTable[n.Name].(types.Function).Children {
e.Visit(v)
}
Expand All @@ -172,12 +204,20 @@ func (e *Evaluator) Visit(node types.Node) interface{} {
}
e.SymbolTable[n.Left.String()], e.SymbolTable[n.Right.String()] = e.SymbolTable[n.Right.String()], e.SymbolTable[n.Left.String()]
case types.Id:
value, ok := e.SymbolTable[n.Name]
value, ok := e.LocalSymbolTable[n.Name]
if !ok {
log.Fatalf("variable '%s' not defined", n)
value, ok = e.SymbolTable[n.Name]
if !ok {
log.Fatalf("variable '%s' not defined", n)
}
return value
}
return value
case types.Literal:
switch v := n.Value.(type) {
case int, float64, string, bool:
return v
}
nodeValue := n.Value.(types.Literal).Value
switch v := nodeValue.(type) {
case int, float64, string, bool:
Expand Down
Loading
Loading