Skip to content

Commit 4ccf870

Browse files
committed
repl: very basic REPL
1 parent cae96e7 commit 4ccf870

File tree

3 files changed

+62
-3
lines changed

3 files changed

+62
-3
lines changed

main.go

+4-2
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"fmt"
88

99
_ "github.com/ncw/gpython/builtin"
10+
"github.com/ncw/gpython/repl"
1011
//_ "github.com/ncw/gpython/importlib"
1112
"io/ioutil"
1213
"log"
@@ -52,8 +53,9 @@ func main() {
5253
flag.Usage = syntaxError
5354
flag.Parse()
5455
args := flag.Args()
55-
if len(args) != 1 {
56-
fatal("Need program to run")
56+
if len(args) == 0 {
57+
repl.Run()
58+
return
5759
}
5860
prog := args[0]
5961
fmt.Printf("Running %q\n", prog)

repl/repl.go

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Read Eval Print Loop
2+
package repl
3+
4+
import (
5+
"bufio"
6+
"fmt"
7+
"io"
8+
"log"
9+
"os"
10+
11+
"github.com/ncw/gpython/compile"
12+
"github.com/ncw/gpython/py"
13+
"github.com/ncw/gpython/vm"
14+
)
15+
16+
func Run() {
17+
fmt.Printf("Gpython 3.4.0\n")
18+
bio := bufio.NewReader(os.Stdin)
19+
module := py.NewModule("__main__", "", nil, nil)
20+
prog := "<stdin>"
21+
module.Globals["__file__"] = py.String(prog)
22+
for {
23+
fmt.Printf(">>> ")
24+
line, hasMoreInLine, err := bio.ReadLine()
25+
if err == io.EOF {
26+
break
27+
}
28+
if err != nil {
29+
log.Printf("Error: %v", err)
30+
break
31+
}
32+
if hasMoreInLine {
33+
log.Printf("Line truncated")
34+
}
35+
// FIXME need +"\n" because "single" is broken
36+
obj, err := compile.Compile(string(line)+"\n", prog, "single", 0, true)
37+
if err != nil {
38+
fmt.Printf("Compile error: %v\n", err)
39+
continue
40+
}
41+
code := obj.(*py.Code)
42+
_, err = vm.Run(module.Globals, module.Globals, code, nil)
43+
if err != nil {
44+
py.TracebackDump(err)
45+
}
46+
}
47+
}

vm/eval.go

+11-1
Original file line numberDiff line numberDiff line change
@@ -470,7 +470,17 @@ func do_DELETE_SUBSCR(vm *Vm, arg int32) {
470470
// expression statement is terminated with POP_STACK.
471471
func do_PRINT_EXPR(vm *Vm, arg int32) {
472472
defer vm.CheckException()
473-
vm.NotImplemented("PRINT_EXPR", arg) // FIXME
473+
// FIXME this should be calling sys.displayhook
474+
475+
// Print value except if None
476+
// After printing, also assign to '_'
477+
// Before, set '_' to None to avoid recursion
478+
value := vm.POP()
479+
vm.frame.Globals["_"] = py.None
480+
if value != py.None {
481+
fmt.Printf("%#v\n", value)
482+
}
483+
vm.frame.Globals["_"] = value
474484
}
475485

476486
// Terminates a loop due to a break statement.

0 commit comments

Comments
 (0)