interpret.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. }
  54. /*
  55. NewCLIInterpreter creates a new commandline interpreter for ECAL.
  56. */
  57. func NewCLIInterpreter() *CLIInterpreter {
  58. return &CLIInterpreter{scope.NewScope(scope.GlobalScope), nil, nil, "", "", "", nil, nil, nil}
  59. }
  60. /*
  61. ParseArgs parses the command line arguments. Call this after adding custon flags.
  62. Returns true if the program should exit.
  63. */
  64. func (i *CLIInterpreter) ParseArgs() bool {
  65. if i.Dir != nil && i.LogFile != nil && i.LogLevel != nil {
  66. return false
  67. }
  68. wd, _ := os.Getwd()
  69. i.Dir = flag.String("dir", wd, "Root directory for ECAL interpreter")
  70. i.LogFile = flag.String("logfile", "", "Log to a file")
  71. i.LogLevel = flag.String("loglevel", "Info", "Logging level (Debug, Info, Error)")
  72. showHelp := flag.Bool("help", false, "Show this help message")
  73. flag.Usage = func() {
  74. fmt.Println()
  75. fmt.Println(fmt.Sprintf("Usage of %s run [options] [file]", os.Args[0]))
  76. fmt.Println()
  77. flag.PrintDefaults()
  78. fmt.Println()
  79. }
  80. if len(os.Args) >= 2 {
  81. flag.CommandLine.Parse(os.Args[2:])
  82. if cargs := flag.Args(); len(cargs) > 0 {
  83. i.EntryFile = flag.Arg(0)
  84. }
  85. if *showHelp {
  86. flag.Usage()
  87. }
  88. }
  89. return *showHelp
  90. }
  91. /*
  92. Create the runtime provider of this interpreter. This function expects Dir,
  93. LogFile and LogLevel to be set.
  94. */
  95. func (i *CLIInterpreter) CreateRuntimeProvider(name string) error {
  96. var logger util.Logger
  97. var err error
  98. if i.RuntimeProvider != nil {
  99. return nil
  100. }
  101. // Check if we should log to a file
  102. if i.LogFile != nil && *i.LogFile != "" {
  103. var logWriter io.Writer
  104. logFileRollover := fileutil.SizeBasedRolloverCondition(1000000) // Each file can be up to a megabyte
  105. logWriter, err = fileutil.NewMultiFileBuffer(*i.LogFile, fileutil.ConsecutiveNumberIterator(10), logFileRollover)
  106. logger = util.NewBufferLogger(logWriter)
  107. } else {
  108. // Log to the console by default
  109. logger = util.NewStdOutLogger()
  110. }
  111. // Set the log level
  112. if err == nil {
  113. if i.LogLevel != nil && *i.LogLevel != "" {
  114. logger, err = util.NewLogLevelLogger(logger, *i.LogLevel)
  115. }
  116. if err == nil {
  117. // Get the import locator
  118. importLocator := &util.FileImportLocator{Root: *i.Dir}
  119. // Create interpreter
  120. i.RuntimeProvider = interpreter.NewECALRuntimeProvider(name, importLocator, logger)
  121. }
  122. }
  123. return err
  124. }
  125. /*
  126. LoadInitialFile clears the global scope and reloads the initial file.
  127. */
  128. func (i *CLIInterpreter) LoadInitialFile(tid uint64) error {
  129. var err error
  130. if i.CustomHandler != nil {
  131. i.CustomHandler.LoadInitialFile(tid)
  132. }
  133. i.GlobalVS.Clear()
  134. if i.EntryFile != "" {
  135. var ast *parser.ASTNode
  136. var initFile []byte
  137. initFile, err = ioutil.ReadFile(i.EntryFile)
  138. if ast, err = parser.ParseWithRuntime(i.EntryFile, string(initFile), i.RuntimeProvider); err == nil {
  139. if err = ast.Runtime.Validate(); err == nil {
  140. _, err = ast.Runtime.Eval(i.GlobalVS, make(map[string]interface{}), tid)
  141. }
  142. }
  143. }
  144. return err
  145. }
  146. /*
  147. Interpret starts the ECAL code interpreter. Starts an interactive console in
  148. the current tty if the interactive flag is set.
  149. */
  150. func (i *CLIInterpreter) Interpret(interactive bool) error {
  151. if i.ParseArgs() {
  152. return nil
  153. }
  154. clt, err := termutil.NewConsoleLineTerminal(os.Stdout)
  155. if interactive {
  156. fmt.Println(fmt.Sprintf("ECAL %v", config.ProductVersion))
  157. }
  158. // Create Runtime Provider
  159. if err == nil {
  160. if err = i.CreateRuntimeProvider("console"); err == nil {
  161. tid := i.RuntimeProvider.NewThreadID()
  162. if interactive {
  163. if lll, ok := i.RuntimeProvider.Logger.(*util.LogLevelLogger); ok {
  164. fmt.Print(fmt.Sprintf("Log level: %v - ", lll.Level()))
  165. }
  166. fmt.Println(fmt.Sprintf("Root directory: %v", *i.Dir))
  167. if i.CustomWelcomeMessage != "" {
  168. fmt.Println(fmt.Sprintf(i.CustomWelcomeMessage))
  169. }
  170. }
  171. // Execute file if given
  172. if err = i.LoadInitialFile(tid); err == nil {
  173. if interactive {
  174. // Drop into interactive shell
  175. if err == nil {
  176. isExitLine := func(s string) bool {
  177. return s == "exit" || s == "q" || s == "quit" || s == "bye" || s == "\x04"
  178. }
  179. // Add history functionality without file persistence
  180. clt, err = termutil.AddHistoryMixin(clt, "",
  181. func(s string) bool {
  182. return isExitLine(s)
  183. })
  184. if err == nil {
  185. if err = clt.StartTerm(); err == nil {
  186. var line string
  187. defer clt.StopTerm()
  188. fmt.Println("Type 'q' or 'quit' to exit the shell and '?' to get help")
  189. line, err = clt.NextLine()
  190. for err == nil && !isExitLine(line) {
  191. trimmedLine := strings.TrimSpace(line)
  192. i.HandleInput(clt, trimmedLine, tid)
  193. line, err = clt.NextLine()
  194. }
  195. }
  196. }
  197. }
  198. }
  199. }
  200. }
  201. }
  202. return err
  203. }
  204. /*
  205. HandleInput handles input to this interpreter. It parses a given input line
  206. and outputs on the given output terminal. Requires a thread ID of the executing
  207. thread - use the RuntimeProvider to generate a unique one.
  208. */
  209. func (i *CLIInterpreter) HandleInput(ot OutputTerminal, line string, tid uint64) {
  210. // Process the entered line
  211. if line == "?" {
  212. // Show help
  213. ot.WriteString(fmt.Sprintf("ECAL %v\n", config.ProductVersion))
  214. ot.WriteString(fmt.Sprint("\n"))
  215. ot.WriteString(fmt.Sprint("Console supports all normal ECAL statements and the following special commands:\n"))
  216. ot.WriteString(fmt.Sprint("\n"))
  217. ot.WriteString(fmt.Sprint(" @reload - Clear the interpreter and reload the initial file if it was given.\n"))
  218. ot.WriteString(fmt.Sprint(" @sym [glob] - List all available inbuild functions and available stdlib packages of ECAL.\n"))
  219. ot.WriteString(fmt.Sprint(" @std <package> [glob] - List all available constants and functions of a stdlib package.\n"))
  220. if i.CustomHelpString != "" {
  221. ot.WriteString(i.CustomHelpString)
  222. }
  223. ot.WriteString(fmt.Sprint("\n"))
  224. 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"))
  225. } else if strings.HasPrefix(line, "@reload") {
  226. // Reload happens in a separate thread as it may be suspended on start
  227. go i.LoadInitialFile(i.RuntimeProvider.NewThreadID())
  228. } else if strings.HasPrefix(line, "@sym") {
  229. i.displaySymbols(ot, strings.Split(line, " ")[1:])
  230. } else if strings.HasPrefix(line, "@std") {
  231. i.displayPackage(ot, strings.Split(line, " ")[1:])
  232. } else if i.CustomHandler != nil && i.CustomHandler.CanHandle(line) {
  233. i.CustomHandler.Handle(ot, line)
  234. } else {
  235. var ierr error
  236. var ast *parser.ASTNode
  237. var res interface{}
  238. if ast, ierr = parser.ParseWithRuntime("console input", line, i.RuntimeProvider); ierr == nil {
  239. if ierr = ast.Runtime.Validate(); ierr == nil {
  240. if res, ierr = ast.Runtime.Eval(i.GlobalVS, make(map[string]interface{}), tid); ierr == nil && res != nil {
  241. ot.WriteString(fmt.Sprintln(stringutil.ConvertToString(res)))
  242. }
  243. }
  244. }
  245. if ierr != nil {
  246. ot.WriteString(fmt.Sprintln(ierr.Error()))
  247. }
  248. }
  249. }
  250. /*
  251. displaySymbols lists all available inbuild functions and available stdlib packages of ECAL.
  252. */
  253. func (i *CLIInterpreter) displaySymbols(ot OutputTerminal, args []string) {
  254. tabData := []string{"Inbuild function", "Description"}
  255. for name, f := range interpreter.InbuildFuncMap {
  256. ds, _ := f.DocString()
  257. if len(args) > 0 && !matchesFulltextSearch(ot, fmt.Sprintf("%v %v", name, ds), args[0]) {
  258. continue
  259. }
  260. tabData = fillTableRow(tabData, name, ds)
  261. }
  262. if len(tabData) > 2 {
  263. ot.WriteString(stringutil.PrintGraphicStringTable(tabData, 2, 1,
  264. stringutil.SingleDoubleLineTable))
  265. }
  266. packageNames, _, _ := stdlib.GetStdlibSymbols()
  267. tabData = []string{"Package name", "Description"}
  268. for _, p := range packageNames {
  269. ps, _ := stdlib.GetPkgDocString(p)
  270. if len(args) > 0 && !matchesFulltextSearch(ot, fmt.Sprintf("%v %v", p, ps), args[0]) {
  271. continue
  272. }
  273. tabData = fillTableRow(tabData, p, ps)
  274. }
  275. if len(tabData) > 2 {
  276. ot.WriteString(stringutil.PrintGraphicStringTable(tabData, 2, 1,
  277. stringutil.SingleDoubleLineTable))
  278. }
  279. }
  280. /*
  281. displayPackage list all available constants and functions of a stdlib package.
  282. */
  283. func (i *CLIInterpreter) displayPackage(ot OutputTerminal, args []string) {
  284. _, constSymbols, funcSymbols := stdlib.GetStdlibSymbols()
  285. tabData := []string{"Constant", "Value"}
  286. for _, s := range constSymbols {
  287. if len(args) > 0 && !strings.HasPrefix(s, args[0]) {
  288. continue
  289. }
  290. val, _ := stdlib.GetStdlibConst(s)
  291. tabData = fillTableRow(tabData, s, fmt.Sprint(val))
  292. }
  293. if len(tabData) > 2 {
  294. ot.WriteString(stringutil.PrintGraphicStringTable(tabData, 2, 1,
  295. stringutil.SingleDoubleLineTable))
  296. }
  297. tabData = []string{"Function", "Description"}
  298. for _, f := range funcSymbols {
  299. if len(args) > 0 && !strings.HasPrefix(f, args[0]) {
  300. continue
  301. }
  302. fObj, _ := stdlib.GetStdlibFunc(f)
  303. fDoc, _ := fObj.DocString()
  304. fDoc = strings.Replace(fDoc, "\n", " ", -1)
  305. fDoc = strings.Replace(fDoc, "\t", " ", -1)
  306. if len(args) > 1 && !matchesFulltextSearch(ot, fmt.Sprintf("%v %v", f, fDoc), args[1]) {
  307. continue
  308. }
  309. tabData = fillTableRow(tabData, f, fDoc)
  310. }
  311. if len(tabData) > 2 {
  312. ot.WriteString(stringutil.PrintGraphicStringTable(tabData, 2, 1,
  313. stringutil.SingleDoubleLineTable))
  314. }
  315. }