This repository has been archived by the owner on Sep 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 34
/
main.go
99 lines (89 loc) · 2.15 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
package main
import (
"errors"
"fmt"
"os"
"os/exec"
"strings"
"github.com/albrow/fo/ast"
"github.com/albrow/fo/format"
"github.com/albrow/fo/importer"
"github.com/albrow/fo/parser"
"github.com/albrow/fo/token"
"github.com/albrow/fo/transform"
"github.com/albrow/fo/types"
"github.com/urfave/cli"
)
func main() {
app := cli.NewApp()
app.Name = "Fo"
app.Usage = "An experimental language which adds functional programming features to Go."
app.Commands = []cli.Command{
{
Name: "run",
Usage: "run a single .fo file",
Action: run,
},
}
if err := app.Run(os.Args); err != nil {
fmt.Printf("ERROR: %s\n", err)
os.Exit(1)
}
}
func run(c *cli.Context) error {
// Read arguments and open file.
if !c.Args().Present() || len(c.Args().Tail()) != 0 {
return errors.New("run expects exactly one argument: the name of a Fo file to run")
}
f, err := os.Open(c.Args().First())
if err != nil {
return fmt.Errorf("could not open file: %s", err)
}
if !strings.HasSuffix(f.Name(), ".fo") {
return fmt.Errorf("%s is not a Fo file (expected '.fo' extension)", f.Name())
}
// Parse file.
fset := token.NewFileSet()
nodes, err := parser.ParseFile(fset, f.Name(), f, 0)
if err != nil {
return err
}
// Check types.
conf := types.Config{Importer: importer.Default()}
info := &types.Info{
Selections: map[*ast.SelectorExpr]*types.Selection{},
Uses: map[*ast.Ident]types.Object{},
}
pkg, err := conf.Check(f.Name(), fset, []*ast.File{nodes}, info)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
// Transform to pure Go and write the output.
trans := &transform.Transformer{
Fset: fset,
Pkg: pkg,
Info: info,
}
transformed, err := trans.File(nodes)
if err != nil {
return err
}
outputName := strings.TrimSuffix(f.Name(), ".fo") + ".go"
output, err := os.Create(outputName)
if err != nil {
return err
}
if err := format.Node(output, fset, transformed); err != nil {
return err
}
// Invoke Go command to run the resulting Go code.
cmd := exec.Command("go", "run", outputName)
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
if err := cmd.Run(); err != nil {
return err
}
return nil
}