Skip to content

Commit

Permalink
Add option for no output from assignments
Browse files Browse the repository at this point in the history
  • Loading branch information
firelizzard18 committed Apr 14, 2021
1 parent 9aeb78f commit 7b8eb13
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
25 changes: 25 additions & 0 deletions interp/interp.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ type opt struct {
stdin io.Reader // standard input
stdout io.Writer // standard output
stderr io.Writer // standard error

supressAssignmentResult bool
}

// Interpreter contains global resources and state.
Expand Down Expand Up @@ -244,6 +246,8 @@ type Options struct {
// They default to os.Stding, os.Stdout and os.Stderr respectively.
Stdin io.Reader
Stdout, Stderr io.Writer

SupressAssignmentResult bool
}

// New returns a new interpreter.
Expand Down Expand Up @@ -294,6 +298,8 @@ func New(options Options) *Interpreter {

// fastChan disables the cancellable version of channel operations in evalWithContext
i.opt.fastChan, _ = strconv.ParseBool(os.Getenv("YAEGI_FAST_CHAN"))

i.opt.supressAssignmentResult = options.SupressAssignmentResult
return &i
}

Expand Down Expand Up @@ -475,6 +481,13 @@ func isFile(path string) bool {
return err == nil && fi.Mode().IsRegular()
}

// EmptyResult is the result of statements that have no result.
var EmptyResult emptyResult

type emptyResult struct{}

func (emptyResult) IsNone() bool { return false }

func (interp *Interpreter) eval(src, name string, inc bool) (res reflect.Value, err error) {
if name != "" {
interp.name = name
Expand Down Expand Up @@ -582,6 +595,18 @@ func (interp *Interpreter) eval(src, name string, inc bool) (res reflect.Value,
for _, n := range initNodes {
interp.run(n, interp.frame)
}

if interp.supressAssignmentResult {
n := root
for n.kind == blockStmt || n.kind == declStmt {
n = n.lastChild()
}
switch n.kind {
case defineStmt, assignStmt, varDecl:
return reflect.ValueOf(EmptyResult), err
}
}

v := genValue(root)
res = v(interp.frame)

Expand Down
12 changes: 12 additions & 0 deletions interp/interp_eval_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1490,3 +1490,15 @@ func TestREPLDivision(t *testing.T) {
t.Fatal("timeout")
}
}

func TestEvalSupressAssignmentResult(t *testing.T) {
i := interp.New(interp.Options{SupressAssignmentResult: true})
runTests(t, i, []testCase{
{desc: "define", src: "a := 1", res: "{}"},
{desc: "define multiple", src: "a, b := 1, 2", res: "{}"},
{desc: "assign", src: "a = 2", res: "{}"},
{desc: "assign multiple", src: "a, b = 2, 3", res: "{}"},
{desc: "declare", src: `var c = 1.2`, skip: "can't test for new(interface{})"},
{desc: "declare after code", src: `_ = ""; var d = 1.2`, res: "{}"},
})
}

0 comments on commit 7b8eb13

Please sign in to comment.