interpret.go 14 KB

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