github.com/goplus/gossa@v0.3.25/cmd/internal/repl/repl.go (about)

     1  package repl
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  
     7  	"github.com/goplus/gossa"
     8  	"github.com/goplus/gossa/cmd/internal/base"
     9  	_ "github.com/goplus/gossa/pkg"
    10  	"github.com/goplus/gossa/repl"
    11  	"github.com/peterh/liner"
    12  )
    13  
    14  // Cmd - gossa test
    15  var Cmd = &base.Command{
    16  	UsageLine: "gossa repl",
    17  	Short:     "gossa repl mode",
    18  }
    19  
    20  var (
    21  	flag          = &Cmd.Flag
    22  	flagGoplus    bool
    23  	flagDumpInstr bool
    24  	flagTrace     bool
    25  )
    26  
    27  func init() {
    28  	Cmd.Run = runCmd
    29  	flag.BoolVar(&flagGoplus, "gop", true, "support goplus")
    30  	flag.BoolVar(&flagDumpInstr, "dump", false, "dump SSA instruction code")
    31  	flag.BoolVar(&flagTrace, "trace", false, "trace interpreter code")
    32  }
    33  
    34  // LinerUI implements repl.UI interface.
    35  type LinerUI struct {
    36  	state  *liner.State
    37  	prompt string
    38  }
    39  
    40  // SetPrompt is required by repl.UI interface.
    41  func (u *LinerUI) SetPrompt(prompt string) {
    42  	u.prompt = prompt
    43  }
    44  
    45  // Printf is required by repl.UI interface.
    46  func (u *LinerUI) Printf(format string, a ...interface{}) {
    47  	fmt.Printf(format, a...)
    48  }
    49  
    50  var (
    51  	welcomeGo  string = "Welcome to Go REPL!"
    52  	welcomeGop string = "Welcome to Go+ REPL!"
    53  )
    54  
    55  var (
    56  	supportGoplus bool
    57  )
    58  
    59  func runCmd(cmd *base.Command, args []string) {
    60  	flag.Parse(args)
    61  	if supportGoplus && flagGoplus {
    62  		fmt.Println(welcomeGop)
    63  	} else {
    64  		fmt.Println(welcomeGo)
    65  	}
    66  
    67  	state := liner.NewLiner()
    68  	defer state.Close()
    69  
    70  	// state.SetCtrlCAborts(true)
    71  	state.SetMultiLineMode(true)
    72  	ui := &LinerUI{state: state}
    73  	var mode gossa.Mode
    74  	if flagDumpInstr {
    75  		mode |= gossa.EnableDumpInstr
    76  	}
    77  	if flagTrace {
    78  		mode |= gossa.EnableTracing
    79  	}
    80  	r := repl.NewREPL(mode)
    81  	r.SetUI(ui)
    82  	if supportGoplus && flagGoplus {
    83  		r.SetFileName("main.gop")
    84  	}
    85  	for {
    86  		line, err := ui.state.Prompt(ui.prompt)
    87  		if err != nil {
    88  			if err == liner.ErrPromptAborted || err == io.EOF {
    89  				fmt.Printf("exit\n")
    90  				break
    91  			}
    92  			fmt.Printf("Problem reading line: %v\n", err)
    93  			continue
    94  		}
    95  		if line != "" {
    96  			state.AppendHistory(line)
    97  		}
    98  		r.Run(line)
    99  	}
   100  }