Skip to content

Commit

Permalink
Moved run to main and fixed binary parsing bug
Browse files Browse the repository at this point in the history
  • Loading branch information
jesperkha committed Nov 25, 2021
1 parent 8ae770e commit 9e3d37a
Show file tree
Hide file tree
Showing 12 changed files with 138 additions and 136 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ This roadmap highlights progress for Fizz's development:
- ✔️ Expression parsing
- ✔️ Conditional statements
- ✔️ Loops
- Functions
- ✔️ Functions
- ❌ Classes
- ❌ Arrays
- ❌ File import
Expand Down
8 changes: 8 additions & 0 deletions expr/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,14 @@ func parsePTokens(tokens []ParseToken) *Expression {
}
}

// Invalid expression might have lowest as end token
// Move to middle and let evaluation handle error
if lowestIdx == len(tokens) - 1 {
newIdx := int(len(tokens)/2)
lowestIdx = newIdx
lowest = tokens[lowestIdx].Token
}

right, left := parsePTokens(tokens[lowestIdx+1:]), parsePTokens(tokens[:lowestIdx])
return &Expression{Type: Binary, Line: line, Operand: lowest, Left: left, Right: right}
}
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
module github.com/jesperkha/Fizz

go 1.16

require github.com/daviddengcn/go-colortext v1.0.0
7 changes: 7 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
github.com/daviddengcn/go-colortext v1.0.0 h1:ANqDyC0ys6qCSvuEK7l3g5RaehL/Xck9EX8ATG8oKsE=
github.com/daviddengcn/go-colortext v1.0.0/go.mod h1:zDqEI5NVUop5QPpVJUxE9UO10hRnmkD5G4Pmri9+m4c=
github.com/golangplus/bytes v0.0.0-20160111154220-45c989fe5450/go.mod h1:Bk6SMAONeMXrxql8uvOKuAZSu8aM5RUGv+1C6IJaEho=
github.com/golangplus/bytes v1.0.0/go.mod h1:AdRaCFwmc/00ZzELMWb01soso6W1R/++O1XL80yAn+A=
github.com/golangplus/fmt v1.0.0/go.mod h1:zpM0OfbMCjPtd2qkTD/jX2MgiFCqklhSUFyDW44gVQE=
github.com/golangplus/testing v1.0.0 h1:+ZeeiKZENNOMkTTELoSySazi+XaEhVO0mb+eanrSEUQ=
github.com/golangplus/testing v1.0.0/go.mod h1:ZDreixUV3YzhoVraIDyOzHrr76p6NUh6k/pPg/Q3gYA=
2 changes: 1 addition & 1 deletion run/interp.go → interp.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package run
package main

import (
"github.com/jesperkha/Fizz/lexer"
Expand Down
4 changes: 1 addition & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ package main

import (
"os"

"github.com/jesperkha/Fizz/run"
)

func main() {
run.RunInterpeter(os.Args)
RunInterpeter(os.Args)
}
114 changes: 114 additions & 0 deletions run.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package main

import (
"bufio"
"bytes"
"errors"
"fmt"
"os"
"strings"

ct "github.com/daviddengcn/go-colortext"
)

var (
ErrFileNotFound = errors.New("cannot find file with name: '%s'")
ErrNonFizzFile = errors.New("cannot run non-Fizz file")
)

var cmdOptions = map[string]func(){
"help": func() {
fmt.Println("use: fizz [filename.fizz | --option]")
},
}

func RunInterpeter(args []string) {
if len(args) == 2 {
arg := args[1]

// Run option commands
if strings.HasPrefix(arg, "--") {
option, ok := cmdOptions[strings.TrimLeft(arg, "-")]
if !ok {
formatError(fmt.Errorf("unknown option: '%s'", arg))
return
}

option()
}

// Run fizz file
filename := args[1]
if !strings.HasSuffix(filename, ".fizz") {
filename += ".fizz"
}

if err := runFile(filename); err != nil {
formatError(err)
}

return
}

// Run terminal mode
runTerminal()
}

// Prints errors with red color to terminal
func formatError(err error) {
ct.Foreground(ct.Red, true)
fmt.Println(err.Error())
ct.ResetColor()
}

// Leaves the interpreter running as the user inputs code to the terminal.
// Prints out errors but does not terminate until ^C or 'exit'.
func runTerminal() {
scanner := bufio.NewScanner(os.Stdin)
totalString := ""
numBlocks := 0
indent := " "

fmt.Println("type 'exit' to terminate session")
for {
fmt.Print("::: " + strings.Repeat(indent, numBlocks))
scanner.Scan()
input := scanner.Text()

if input == "exit" {
break
}

// Continue with indent after braces
numBlocks += strings.Count(input, "{") - strings.Count(input, "}")
totalString += input + "\n" // Better error handling

if numBlocks <= 0 {
err := Interperate(totalString)
if err != nil {
formatError(err)
}

totalString = ""
numBlocks = 0
}
}

fmt.Println("session ended")
}

// Interperates code found in file specified in commandline arguments
func runFile(filename string) (err error) {
if !strings.HasSuffix(filename, ".fizz") {
return ErrNonFizzFile
}

if file, err := os.Open(filename); err == nil {
var buf bytes.Buffer
bufio.NewReader(file).WriteTo(&buf)
return Interperate(buf.String())
}

// Assumes path error
return fmt.Errorf(ErrFileNotFound.Error(), filename)
}
26 changes: 0 additions & 26 deletions run/file.go

This file was deleted.

52 changes: 0 additions & 52 deletions run/run.go

This file was deleted.

44 changes: 0 additions & 44 deletions run/terminal.go

This file was deleted.

7 changes: 4 additions & 3 deletions stmt/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,21 +191,22 @@ func parseFunc(tokens []lexer.Token, idx *int) (stmt Statement, err error) {
if len(tokens) < 6 {
return stmt, ErrInvalidStatement
}

nameToken := tokens[*idx+1]
if nameToken.Type != lexer.IDENTIFIER || tokens[*idx+2].Type != lexer.LEFT_PAREN {
return stmt, ErrInvalidStatement // Missing identifier or block
}

*idx += 3 // Skip to start of param list
endIdx, eof := seekToken(tokens, *idx, lexer.RIGHT_PAREN)
if eof {
return stmt, ErrInvalidStatement
}

// Get param names
params := []string{}
for _, p := range tokens[*idx:endIdx] {
// Todo: Add actual comma separation for function declarations
switch p.Type {
case lexer.COMMA:
continue
Expand Down
6 changes: 0 additions & 6 deletions todo.txt

This file was deleted.

0 comments on commit 9e3d37a

Please sign in to comment.