-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.go
112 lines (101 loc) · 2.27 KB
/
main.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
// Turbo Pascal to Go transpiler
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"strings"
"unicode/utf8"
)
func main() {
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, "usage: pas2go [lex | parse | convert] [file.pas] [unit1.pas ...]\n")
os.Exit(1)
}
command := os.Args[1]
var src []byte
if len(os.Args) > 2 {
path := os.Args[2]
var err error
src, err = ioutil.ReadFile(path)
if err != nil {
fmt.Fprintf(os.Stderr, "error reading file: %v\n", err)
os.Exit(1)
}
} else {
var err error
src, err = ioutil.ReadAll(os.Stdin)
if err != nil {
fmt.Fprintf(os.Stderr, "error reading stdin: %v", err)
os.Exit(1)
}
}
switch command {
case "lex":
lex(src)
case "parse":
file := parse(src)
fmt.Print(file)
case "convert":
file := parse(src)
units := []*Unit{}
for _, path := range os.Args[3:] {
unitSrc, err := ioutil.ReadFile(path)
if err != nil {
fmt.Fprintf(os.Stderr, "error reading file: %v\n", err)
os.Exit(1)
}
unitFile := parse(unitSrc)
unit, ok := unitFile.(*Unit)
if !ok {
continue
}
units = append(units, unit)
}
Convert(file, units, os.Stdout)
default:
fmt.Fprintf(os.Stderr, "command must be 'lex' or 'parse'")
os.Exit(1)
}
}
func lex(src []byte) {
lexer := NewLexer(src)
for {
pos, tok, val := lexer.Scan()
if tok == EOF {
break
}
fmt.Printf("%d:%d %s %q\n", pos.Line, pos.Column, tok, val)
if tok == ILLEGAL {
break
}
}
}
func parse(src []byte) File {
file, err := Parse(src)
if err != nil {
errMsg := fmt.Sprintf("%s", err)
if err, ok := err.(*ParseError); ok {
showSourceLine(src, err.Position, len(errMsg))
}
fmt.Fprintf(os.Stderr, "%s\n", errMsg)
os.Exit(1)
}
return file
}
func showSourceLine(src []byte, pos Position, dividerLen int) {
divider := strings.Repeat("-", dividerLen)
if divider != "" {
fmt.Fprintln(os.Stderr, divider)
}
lines := bytes.Split(src, []byte{'\n'})
srcLine := string(lines[pos.Line-1])
numTabs := strings.Count(srcLine[:pos.Column-1], "\t")
runeColumn := utf8.RuneCountInString(srcLine[:pos.Column-1])
fmt.Fprintln(os.Stderr, strings.Replace(srcLine, "\t", " ", -1))
fmt.Fprintln(os.Stderr, strings.Repeat(" ", runeColumn)+strings.Repeat(" ", numTabs)+"^")
if divider != "" {
fmt.Fprintln(os.Stderr, divider)
}
}