interpret.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. Interpret starts the ECAL code interpreter from a CLI application which
  30. calls the interpret function as a sub executable. Starts an interactive console
  31. if the interactive flag is set.
  32. */
  33. func Interpret(interactive bool) error {
  34. var err error
  35. wd, _ := os.Getwd()
  36. idir := flag.String("dir", wd, "Root directory for ECAL interpreter")
  37. ilogFile := flag.String("logfile", "", "Log to a file")
  38. ilogLevel := flag.String("loglevel", "Info", "Logging level (Debug, Info, Error)")
  39. showHelp := flag.Bool("help", false, "Show this help message")
  40. flag.Usage = func() {
  41. fmt.Println()
  42. if !interactive {
  43. fmt.Println(fmt.Sprintf("Usage of %s run [options] <file>", os.Args[0]))
  44. } else {
  45. fmt.Println(fmt.Sprintf("Usage of %s [options]", os.Args[0]))
  46. }
  47. fmt.Println()
  48. flag.PrintDefaults()
  49. fmt.Println()
  50. }
  51. if len(os.Args) > 2 {
  52. flag.CommandLine.Parse(os.Args[2:])
  53. if *showHelp {
  54. flag.Usage()
  55. return nil
  56. }
  57. }
  58. var clt termutil.ConsoleLineTerminal
  59. var logger util.Logger
  60. clt, err = termutil.NewConsoleLineTerminal(os.Stdout)
  61. fmt.Println(fmt.Sprintf("ECAL %v", config.ProductVersion))
  62. // Create the logger
  63. if err == nil {
  64. // Check if we should log to a file
  65. if ilogFile != nil && *ilogFile != "" {
  66. var logWriter io.Writer
  67. logFileRollover := fileutil.SizeBasedRolloverCondition(1000000) // Each file can be up to a megabyte
  68. logWriter, err = fileutil.NewMultiFileBuffer(*ilogFile, fileutil.ConsecutiveNumberIterator(10), logFileRollover)
  69. logger = util.NewBufferLogger(logWriter)
  70. } else {
  71. // Log to the console by default
  72. logger = util.NewStdOutLogger()
  73. }
  74. // Set the log level
  75. if err == nil {
  76. if ilogLevel != nil && *ilogLevel != "" {
  77. if logger, err = util.NewLogLevelLogger(logger, *ilogLevel); err == nil {
  78. fmt.Print(fmt.Sprintf("Log level: %v - ", logger.(*util.LogLevelLogger).Level()))
  79. }
  80. }
  81. }
  82. }
  83. if err == nil {
  84. // Get the import locator
  85. fmt.Println(fmt.Sprintf("Root directory: %v", *idir))
  86. importLocator := &util.FileImportLocator{Root: *idir}
  87. name := "console"
  88. // Create interpreter
  89. erp := interpreter.NewECALRuntimeProvider(name, importLocator, logger)
  90. // Create global variable scope
  91. vs := scope.NewScope(scope.GlobalScope)
  92. // Execute file if given
  93. if cargs := flag.Args(); len(cargs) > 0 {
  94. var ast *parser.ASTNode
  95. var initFile []byte
  96. initFileName := flag.Arg(0)
  97. initFile, err = ioutil.ReadFile(initFileName)
  98. if ast, err = parser.ParseWithRuntime(initFileName, string(initFile), erp); err == nil {
  99. if err = ast.Runtime.Validate(); err == nil {
  100. _, err = ast.Runtime.Eval(vs, make(map[string]interface{}))
  101. }
  102. }
  103. }
  104. if err == nil {
  105. if interactive {
  106. // Drop into interactive shell
  107. if err == nil {
  108. isExitLine := func(s string) bool {
  109. return s == "exit" || s == "q" || s == "quit" || s == "bye" || s == "\x04"
  110. }
  111. // Add history functionality without file persistence
  112. clt, err = termutil.AddHistoryMixin(clt, "",
  113. func(s string) bool {
  114. return isExitLine(s)
  115. })
  116. if err == nil {
  117. if err = clt.StartTerm(); err == nil {
  118. var line string
  119. defer clt.StopTerm()
  120. fmt.Println("Type 'q' or 'quit' to exit the shell and '?' to get help")
  121. line, err = clt.NextLine()
  122. for err == nil && !isExitLine(line) {
  123. trimmedLine := strings.TrimSpace(line)
  124. // Process the entered line
  125. if line == "?" {
  126. // Show help
  127. clt.WriteString(fmt.Sprintf("ECAL %v\n", config.ProductVersion))
  128. clt.WriteString(fmt.Sprintf("\n"))
  129. clt.WriteString(fmt.Sprintf("Console supports all normal ECAL statements and the following special commands:\n"))
  130. clt.WriteString(fmt.Sprintf("\n"))
  131. clt.WriteString(fmt.Sprintf(" @sym [glob] - List all available inbuild functions and available stdlib packages of ECAL.\n"))
  132. clt.WriteString(fmt.Sprintf(" @std <package> [glob] - List all available constants and functions of a stdlib package.\n"))
  133. clt.WriteString(fmt.Sprintf("\n"))
  134. clt.WriteString(fmt.Sprintf("Add an argument after a list command to do a full text search. The search string should be in glob format.\n"))
  135. } else if strings.HasPrefix(trimmedLine, "@sym") {
  136. displaySymbols(clt, strings.Split(trimmedLine, " ")[1:])
  137. } else if strings.HasPrefix(trimmedLine, "@std") {
  138. displayPackage(clt, strings.Split(trimmedLine, " ")[1:])
  139. } else {
  140. var ierr error
  141. var ast *parser.ASTNode
  142. var res interface{}
  143. if ast, ierr = parser.ParseWithRuntime("console input", line, erp); ierr == nil {
  144. if ierr = ast.Runtime.Validate(); ierr == nil {
  145. if res, ierr = ast.Runtime.Eval(vs, make(map[string]interface{})); ierr == nil && res != nil {
  146. clt.WriteString(fmt.Sprintln(res))
  147. }
  148. }
  149. }
  150. if ierr != nil {
  151. clt.WriteString(fmt.Sprintln(ierr.Error()))
  152. }
  153. }
  154. line, err = clt.NextLine()
  155. }
  156. }
  157. }
  158. }
  159. }
  160. }
  161. }
  162. return err
  163. }
  164. /*
  165. displaySymbols lists all available inbuild functions and available stdlib packages of ECAL.
  166. */
  167. func displaySymbols(clt termutil.ConsoleLineTerminal, args []string) {
  168. tabData := []string{"Inbuild function", "Description"}
  169. for name, f := range interpreter.InbuildFuncMap {
  170. ds, _ := f.DocString()
  171. if len(args) > 0 && !matchesFulltextSearch(clt, fmt.Sprintf("%v %v", name, ds), args[0]) {
  172. continue
  173. }
  174. tabData = fillTableRow(tabData, name, ds)
  175. }
  176. if len(tabData) > 2 {
  177. clt.WriteString(stringutil.PrintGraphicStringTable(tabData, 2, 1,
  178. stringutil.SingleDoubleLineTable))
  179. }
  180. packageNames, _, _ := stdlib.GetStdlibSymbols()
  181. tabData = []string{"Package name", "Description"}
  182. for _, p := range packageNames {
  183. ps, _ := stdlib.GetPkgDocString(p)
  184. if len(args) > 0 && !matchesFulltextSearch(clt, fmt.Sprintf("%v %v", p, ps), args[0]) {
  185. continue
  186. }
  187. tabData = fillTableRow(tabData, p, ps)
  188. }
  189. if len(tabData) > 2 {
  190. clt.WriteString(stringutil.PrintGraphicStringTable(tabData, 2, 1,
  191. stringutil.SingleDoubleLineTable))
  192. }
  193. }
  194. /*
  195. displayPackage list all available constants and functions of a stdlib package.
  196. */
  197. func displayPackage(clt termutil.ConsoleLineTerminal, args []string) {
  198. _, constSymbols, funcSymbols := stdlib.GetStdlibSymbols()
  199. tabData := []string{"Constant", "Value"}
  200. for _, s := range constSymbols {
  201. if len(args) > 0 && !strings.HasPrefix(s, args[0]) {
  202. continue
  203. }
  204. val, _ := stdlib.GetStdlibConst(s)
  205. tabData = fillTableRow(tabData, s, fmt.Sprint(val))
  206. }
  207. if len(tabData) > 2 {
  208. clt.WriteString(stringutil.PrintGraphicStringTable(tabData, 2, 1,
  209. stringutil.SingleDoubleLineTable))
  210. }
  211. tabData = []string{"Function", "Description"}
  212. for _, f := range funcSymbols {
  213. if len(args) > 0 && !strings.HasPrefix(f, args[0]) {
  214. continue
  215. }
  216. fObj, _ := stdlib.GetStdlibFunc(f)
  217. fDoc, _ := fObj.DocString()
  218. fDoc = strings.Replace(fDoc, "\n", " ", -1)
  219. fDoc = strings.Replace(fDoc, "\t", " ", -1)
  220. if len(args) > 1 && !matchesFulltextSearch(clt, fmt.Sprintf("%v %v", f, fDoc), args[1]) {
  221. continue
  222. }
  223. tabData = fillTableRow(tabData, f, fDoc)
  224. }
  225. if len(tabData) > 2 {
  226. clt.WriteString(stringutil.PrintGraphicStringTable(tabData, 2, 1,
  227. stringutil.SingleDoubleLineTable))
  228. }
  229. }