init + lexer
This commit is contained in:
commit
9bebc6e307
5 changed files with 493 additions and 0 deletions
78
main.go
Normal file
78
main.go
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
var (
|
||||
file string
|
||||
)
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
args := flag.Args()
|
||||
|
||||
if len(args) > 1 {
|
||||
fmt.Printf("Usage: %s [script]", args[0])
|
||||
os.Exit(64)
|
||||
} else if len(args) == 1 {
|
||||
runFile(args[0])
|
||||
} else {
|
||||
repl()
|
||||
}
|
||||
}
|
||||
|
||||
func runFile(filename string) {
|
||||
bs, err := os.ReadFile(filename)
|
||||
if err != nil {
|
||||
fmt.Printf("unable to read file '%s':\n\t%s", filename, err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if run(string(bs)) {
|
||||
os.Exit(65)
|
||||
}
|
||||
}
|
||||
|
||||
func repl() {
|
||||
s := bufio.NewScanner(os.Stdin)
|
||||
for {
|
||||
fmt.Printf("repl> ")
|
||||
s.Scan()
|
||||
text := s.Text()
|
||||
|
||||
if text == ":q" {
|
||||
return
|
||||
}
|
||||
|
||||
run(text)
|
||||
if err := s.Err(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func run(source string) bool {
|
||||
s := newScanner(source)
|
||||
tokens, ok := s.ScanTokens()
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
|
||||
for _, token := range tokens {
|
||||
fmt.Println(token)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func reportErr(line int, message string) {
|
||||
report(line, "", message)
|
||||
}
|
||||
|
||||
func report(line int, where, message string) {
|
||||
fmt.Printf("[line %d] Error%s: %s\n", line, where, message)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue