-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathphilomath.go
125 lines (106 loc) · 2.46 KB
/
philomath.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package main
import (
"fmt"
"flag"
"io/ioutil"
"log"
"os"
"github.com/kestred/philomath/code/ast"
"github.com/kestred/philomath/code/bytecode"
"github.com/kestred/philomath/code/interpreter"
"github.com/kestred/philomath/code/parser"
"github.com/kestred/philomath/code/semantics"
)
var ArgTrace = flag.Bool("trace", false, "")
func init() {
log.SetFlags(0)
log.SetPrefix("phi: ")
flag.Parse()
flag.Usage = usage
}
func usage() {
fmt.Fprintln(os.Stderr, `
Phi is the compiler for Philomath.
Usage:
phi COMMAND [OPTIONS] [ARGS]
Commands:
run interpret a .phi source file
`[1:])
}
func main() {
args := flag.Args()
if len(args) == 0 {
usage()
os.Exit(1)
}
// handle command
command := args[0]
switch command {
case "run":
doRun(args[1:])
default:
if len(command) > 14 {
command = command[:10] + " ..."
}
log.Printf(`error: unknown command "%v"`, command)
usage()
os.Exit(1)
}
}
func doRun(args []string) {
if len(args) == 0 {
log.Fatalln(`error: no input files`)
}
file, err := os.Open(args[0])
if err != nil {
log.Fatalln("error:", err)
}
source, err := ioutil.ReadAll(file)
if err != nil {
log.Fatalln("error:", err)
}
psr := parser.Make(args[0], *ArgTrace, []byte(source))
tree := psr.ParseTop()
errcount := len(psr.Errors)
if errcount > 0 {
for _, err := range psr.Errors {
fmt.Printf("%v\n", err)
}
if errcount >= parser.MaxErrors {
log.Fatalf("aborted after the first %v errors...\n", errcount)
} else {
log.Fatalf("found %v syntax error(s)\n", errcount)
}
}
for _, decl := range tree.Decls {
if decl.GetName().Literal == "main" {
if imm, ok := decl.(*ast.ImmutableDecl); ok {
if con, ok := imm.Defn.(*ast.ConstantDefn); ok {
if _, ok := con.Expr.(*ast.ProcedureExpr); ok {
break
}
}
log.Fatalf(`expected "main" to be a procedure (eg. "main :: () { ... }")`)
} else {
log.Fatalf(`your "main" procedure must use "::" instead of ":="`)
}
}
}
section := semantics.FlattenTree(tree, nil)
semantics.ResolveNames(§ion)
semantics.InferTypes(§ion)
// TODO: maybe add an errors list to Section?
errs := semantics.CheckTypes(§ion)
if len(errs) > 0 {
for _, err := range errs {
fmt.Printf("%v\n", err)
}
log.Fatalf("found %v semantic error(s)\n", len(errs))
}
program := bytecode.NewProgram()
program.Extend(tree)
if _, ok := program.Text["main"]; !ok {
log.Fatalf(`unable to find a procedure named "main"`)
}
interpreter.Run(program)
}