interpret.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. /*
  2. * ECAL
  3. *
  4. * Copyright 2020 Matthias Ladkau. All rights reserved.
  5. *
  6. * This Source Code Form is subject to the terms of the MIT
  7. * License, If a copy of the MIT License was not distributed with this
  8. * file, You can obtain one at https://opensource.org/licenses/MIT.
  9. */
  10. package tool
  11. import (
  12. "flag"
  13. "fmt"
  14. "io"
  15. "io/ioutil"
  16. "os"
  17. "strings"
  18. "devt.de/krotik/common/fileutil"
  19. "devt.de/krotik/common/stringutil"
  20. "devt.de/krotik/common/termutil"
  21. "devt.de/krotik/ecal/config"
  22. "devt.de/krotik/ecal/interpreter"
  23. "devt.de/krotik/ecal/parser"
  24. "devt.de/krotik/ecal/scope"
  25. "devt.de/krotik/ecal/stdlib"
  26. "devt.de/krotik/ecal/util"
  27. )
  28. /*
  29. CLICustomHandler is a handler for custom operations.
  30. */
  31. type CLICustomHandler interface {
  32. CLIInputHandler
  33. /*
  34. LoadInitialFile clears the global scope and reloads the initial file.
  35. */
  36. LoadInitialFile(tid uint64) error
  37. }
  38. /*
  39. CLIInterpreter is a commandline interpreter for ECAL.
  40. */
  41. type CLIInterpreter struct {
  42. GlobalVS parser.Scope // Global variable scope
  43. RuntimeProvider *interpreter.ECALRuntimeProvider // Runtime provider of the interpreter
  44. // Customizations of output and input handling
  45. CustomHandler CLICustomHandler
  46. CustomWelcomeMessage string
  47. CustomHelpString string
  48. EntryFile string // Entry file for the program
  49. // Parameter these can either be set programmatically or via CLI args
  50. Dir *string // Root dir for interpreter
  51. LogFile *string // Logfile (blank for stdout)
  52. LogLevel *string // Log level string (Debug, Info, Error)
  53. // User terminal
  54. Term termutil.ConsoleLineTerminal
  55. // Log output
  56. LogOut io.Writer
  57. }
  58. /*
  59. NewCLIInterpreter creates a new commandline interpreter for ECAL.
  60. */
  61. func NewCLIInterpreter() *CLIInterpreter {
  62. return &CLIInterpreter{scope.NewScope(scope.GlobalScope), nil, nil, "", "", "", nil, nil, nil, nil, os.Stdout}
  63. }
  64. /*
  65. ParseArgs parses the command line arguments. Call this after adding custon flags.
  66. Returns true if the program should exit.
  67. */
  68. func (i *CLIInterpreter) ParseArgs() bool {
  69. if i.Dir != nil && i.LogFile != nil && i.LogLevel != nil {
  70. return false
  71. }
  72. wd, _ := os.Getwd()
  73. i.Dir = flag.String("dir", wd, "Root directory for ECAL interpreter")
  74. i.LogFile = flag.String("logfile", "", "Log to a file")
  75. i.LogLevel = flag.String("loglevel", "Info", "Logging level (Debug, Info, Error)")
  76. showHelp := flag.Bool("help", false, "Show this help message")
  77. flag.Usage = func() {
  78. fmt.Fprintln(flag.CommandLine.Output())
  79. fmt.Fprintln(flag.CommandLine.Output(), fmt.Sprintf("Usage of %s run [options] [file]", osArgs[0]))
  80. fmt.Fprintln(flag.CommandLine.Output())
  81. flag.PrintDefaults()
  82. fmt.Fprintln(flag.CommandLine.Output())
  83. }
  84. if len(osArgs) >= 2 {
  85. flag.CommandLine.Parse(osArgs[2:])
  86. if cargs := flag.Args(); len(cargs) > 0 {
  87. i.EntryFile = flag.Arg(0)
  88. }
  89. if *showHelp {
  90. flag.Usage()
  91. }
  92. }
  93. return *showHelp
  94. }
  95. /*
  96. CreateRuntimeProvider creates the runtime provider of this interpreter. This function expects Dir,
  97. LogFile and LogLevel to be set.
  98. */
  99. func (i *CLIInterpreter) CreateRuntimeProvider(name string) error {
  100. var logger util.Logger
  101. var err error
  102. if i.RuntimeProvider != nil {
  103. return nil
  104. }
  105. // Check if we should log to a file
  106. if i.LogFile != nil && *i.LogFile != "" {
  107. var logWriter io.Writer
  108. logFileRollover := fileutil.SizeBasedRolloverCondition(1000000) // Each file can be up to a megabyte
  109. logWriter, err = fileutil.NewMultiFileBuffer(*i.LogFile, fileutil.ConsecutiveNumberIterator(10), logFileRollover)
  110. logger = util.NewBufferLogger(logWriter)
  111. } else {
  112. // Log to the console by default
  113. logger = util.NewStdOutLogger()
  114. }
  115. // Set the log level
  116. if err == nil {
  117. if i.LogLevel != nil && *i.LogLevel != "" {
  118. logger, err = util.NewLogLevelLogger(logger, *i.LogLevel)
  119. }
  120. if err == nil {
  121. // Get the import locator
  122. importLocator := &util.FileImportLocator{Root: *i.Dir}
  123. // Create interpreter
  124. i.RuntimeProvider = interpreter.NewECALRuntimeProvider(name, importLocator, logger)
  125. }
  126. }
  127. return err
  128. }
  129. /*
  130. LoadInitialFile clears the global scope and reloads the initial file.
  131. */
  132. func (i *CLIInterpreter) LoadInitialFile(tid uint64) error {
  133. var err error
  134. if i.CustomHandler != nil {
  135. i.CustomHandler.LoadInitialFile(tid)
  136. }
  137. i.GlobalVS.Clear()
  138. if i.EntryFile != "" {
  139. var ast *parser.ASTNode
  140. var initFile []byte
  141. initFile, err = ioutil.ReadFile(i.EntryFile)
  142. if err == nil {
  143. if ast, err = parser.ParseWithRuntime(i.EntryFile, string(initFile), i.RuntimeProvider); err == nil {
  144. if err = ast.Runtime.Validate(); err == nil {
  145. _, err = ast.Runtime.Eval(i.GlobalVS, make(map[string]interface{}), tid)
  146. }
  147. defer func() {
  148. if i.RuntimeProvider.Debugger != nil {
  149. i.RuntimeProvider.Debugger.RecordThreadFinished(tid)
  150. }
  151. }()
  152. }
  153. }
  154. }
  155. return err
  156. }
  157. /*
  158. CreateTerm creates a new console terminal for stdout.
  159. */
  160. func (i *CLIInterpreter) CreateTerm() error {
  161. var err error
  162. if i.Term == nil {
  163. i.Term, err = termutil.NewConsoleLineTerminal(os.Stdout)
  164. }
  165. return err
  166. }
  167. /*
  168. Interpret starts the ECAL code interpreter. Starts an interactive console in
  169. the current tty if the interactive flag is set.
  170. */
  171. func (i *CLIInterpreter) Interpret(interactive bool) error {
  172. if i.ParseArgs() {
  173. return nil
  174. }
  175. err := i.CreateTerm()
  176. if interactive {
  177. fmt.Fprintln(i.LogOut, fmt.Sprintf("ECAL %v", config.ProductVersion))
  178. }
  179. // Create Runtime Provider
  180. if err == nil {
  181. if err = i.CreateRuntimeProvider("console"); err == nil {
  182. tid := i.RuntimeProvider.NewThreadID()
  183. if interactive {
  184. if lll, ok := i.RuntimeProvider.Logger.(*util.LogLevelLogger); ok {
  185. fmt.Fprint(i.LogOut, fmt.Sprintf("Log level: %v - ", lll.Level()))
  186. }
  187. fmt.Fprintln(i.LogOut, fmt.Sprintf("Root directory: %v", *i.Dir))
  188. if i.CustomWelcomeMessage != "" {
  189. fmt.Fprintln(i.LogOut, fmt.Sprintf(i.CustomWelcomeMessage))
  190. }
  191. }
  192. // Execute file if given
  193. if err = i.LoadInitialFile(tid); err == nil {
  194. // Drop into interactive shell
  195. if interactive {
  196. // Add history functionality without file persistence
  197. i.Term, err = termutil.AddHistoryMixin(i.Term, "",
  198. func(s string) bool {
  199. return i.isExitLine(s)
  200. })
  201. if err == nil {
  202. if err = i.Term.StartTerm(); err == nil {
  203. var line string
  204. defer i.Term.StopTerm()
  205. fmt.Fprintln(i.LogOut, "Type 'q' or 'quit' to exit the shell and '?' to get help")
  206. line, err = i.Term.NextLine()
  207. for err == nil && !i.isExitLine(line) {
  208. trimmedLine := strings.TrimSpace(line)
  209. i.HandleInput(i.Term, trimmedLine, tid)
  210. line, err = i.Term.NextLine()
  211. }
  212. }
  213. }
  214. }
  215. }
  216. }
  217. }
  218. return err
  219. }
  220. /*
  221. isExitLine returns if a given input line should exit the interpreter.
  222. */
  223. func (i *CLIInterpreter) isExitLine(s string) bool {
  224. return s == "exit" || s == "q" || s == "quit" || s == "bye" || s == "\x04"
  225. }
  226. /*
  227. HandleInput handles input to this interpreter. It parses a given input line
  228. and outputs on the given output terminal. Requires a thread ID of the executing
  229. thread - use the RuntimeProvider to generate a unique one.
  230. */
  231. func (i *CLIInterpreter) HandleInput(ot OutputTerminal, line string, tid uint64) {
  232. // Process the entered line
  233. if line == "?" {
  234. // Show help
  235. ot.WriteString(fmt.Sprintf("ECAL %v\n", config.ProductVersion))
  236. ot.WriteString(fmt.Sprint("\n"))
  237. ot.WriteString(fmt.Sprint("Console supports all normal ECAL statements and the following special commands:\n"))
  238. ot.WriteString(fmt.Sprint("\n"))
  239. ot.WriteString(fmt.Sprint(" @reload - Clear the interpreter and reload the initial file if it was given.\n"))
  240. ot.WriteString(fmt.Sprint(" @sym [glob] - List all available inbuild functions and available stdlib packages of ECAL.\n"))
  241. ot.WriteString(fmt.Sprint(" @std <package> [glob] - List all available constants and functions of a stdlib package.\n"))
  242. if i.CustomHelpString != "" {
  243. ot.WriteString(i.CustomHelpString)
  244. }
  245. ot.WriteString(fmt.Sprint("\n"))
  246. ot.WriteString(fmt.Sprint("Add an argument after a list command to do a full text search. The search string should be in glob format.\n"))
  247. } else if strings.HasPrefix(line, "@reload") {
  248. // Reload happens in a separate thread as it may be suspended on start
  249. go i.LoadInitialFile(i.RuntimeProvider.NewThreadID())
  250. ot.WriteString(fmt.Sprintln(fmt.Sprintln("Reloading interpreter state")))
  251. } else if strings.HasPrefix(line, "@sym") {
  252. i.displaySymbols(ot, strings.Split(line, " ")[1:])
  253. } else if strings.HasPrefix(line, "@std") {
  254. i.displayPackage(ot, strings.Split(line, " ")[1:])
  255. } else if i.CustomHandler != nil && i.CustomHandler.CanHandle(line) {
  256. i.CustomHandler.Handle(ot, line)
  257. } else {
  258. var ierr error
  259. var ast *parser.ASTNode
  260. var res interface{}
  261. if line != "" {
  262. if ast, ierr = parser.ParseWithRuntime("console input", line, i.RuntimeProvider); ierr == nil {
  263. if ierr = ast.Runtime.Validate(); ierr == nil {
  264. if res, ierr = ast.Runtime.Eval(i.GlobalVS, make(map[string]interface{}), tid); ierr == nil && res != nil {
  265. ot.WriteString(fmt.Sprintln(stringutil.ConvertToString(res)))
  266. }
  267. defer func() {
  268. if i.RuntimeProvider.Debugger != nil {
  269. i.RuntimeProvider.Debugger.RecordThreadFinished(tid)
  270. }
  271. }()
  272. }
  273. }
  274. if ierr != nil {
  275. ot.WriteString(fmt.Sprintln(ierr.Error()))
  276. }
  277. }
  278. }
  279. }
  280. /*
  281. displaySymbols lists all available inbuild functions and available stdlib packages of ECAL.
  282. */
  283. func (i *CLIInterpreter) displaySymbols(ot OutputTerminal, args []string) {
  284. tabData := []string{"Inbuild function", "Description"}
  285. for name, f := range interpreter.InbuildFuncMap {
  286. ds, _ := f.DocString()
  287. if len(args) > 0 && !matchesFulltextSearch(ot, fmt.Sprintf("%v %v", name, ds), args[0]) {
  288. continue
  289. }
  290. tabData = fillTableRow(tabData, name, ds)
  291. }
  292. if len(tabData) > 2 {
  293. ot.WriteString(stringutil.PrintGraphicStringTable(tabData, 2, 1,
  294. stringutil.SingleDoubleLineTable))
  295. }
  296. packageNames, _, _ := stdlib.GetStdlibSymbols()
  297. tabData = []string{"Package name", "Description"}
  298. for _, p := range packageNames {
  299. ps, _ := stdlib.GetPkgDocString(p)
  300. if len(args) > 0 && !matchesFulltextSearch(ot, fmt.Sprintf("%v %v", p, ps), args[0]) {
  301. continue
  302. }
  303. tabData = fillTableRow(tabData, p, ps)
  304. }
  305. if len(tabData) > 2 {
  306. ot.WriteString(stringutil.PrintGraphicStringTable(tabData, 2, 1,
  307. stringutil.SingleDoubleLineTable))
  308. }
  309. }
  310. /*
  311. displayPackage list all available constants and functions of a stdlib package.
  312. */
  313. func (i *CLIInterpreter) displayPackage(ot OutputTerminal, args []string) {
  314. _, constSymbols, funcSymbols := stdlib.GetStdlibSymbols()
  315. tabData := []string{"Constant", "Value"}
  316. for _, s := range constSymbols {
  317. if len(args) > 0 && !strings.HasPrefix(s, args[0]) {
  318. continue
  319. }
  320. val, _ := stdlib.GetStdlibConst(s)
  321. tabData = fillTableRow(tabData, s, fmt.Sprint(val))
  322. }
  323. if len(tabData) > 2 {
  324. ot.WriteString(stringutil.PrintGraphicStringTable(tabData, 2, 1,
  325. stringutil.SingleDoubleLineTable))
  326. }
  327. tabData = []string{"Function", "Description"}
  328. for _, f := range funcSymbols {
  329. if len(args) > 0 && !strings.HasPrefix(f, args[0]) {
  330. continue
  331. }
  332. fObj, _ := stdlib.GetStdlibFunc(f)
  333. fDoc, _ := fObj.DocString()
  334. fDoc = strings.Replace(fDoc, "\n", " ", -1)
  335. fDoc = strings.Replace(fDoc, "\t", " ", -1)
  336. if len(args) > 1 && !matchesFulltextSearch(ot, fmt.Sprintf("%v %v", f, fDoc), args[1]) {
  337. continue
  338. }
  339. tabData = fillTableRow(tabData, f, fDoc)
  340. }
  341. if len(tabData) > 2 {
  342. ot.WriteString(stringutil.PrintGraphicStringTable(tabData, 2, 1,
  343. stringutil.SingleDoubleLineTable))
  344. }
  345. }