interpret.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. "os"
  16. "strings"
  17. "devt.de/krotik/common/fileutil"
  18. "devt.de/krotik/common/termutil"
  19. "devt.de/krotik/ecal/config"
  20. "devt.de/krotik/ecal/interpreter"
  21. "devt.de/krotik/ecal/parser"
  22. "devt.de/krotik/ecal/scope"
  23. "devt.de/krotik/ecal/util"
  24. )
  25. /*
  26. Interpret starts the ECAL code interpreter from a CLI application which
  27. calls the interpret function as a sub executable. Starts an interactive console
  28. if the interactive flag is set.
  29. */
  30. func Interpret(interactive bool) error {
  31. var err error
  32. wd, _ := os.Getwd()
  33. idir := flag.String("dir", wd, "Root directory for ECAL interpreter")
  34. ilogFile := flag.String("logfile", "", "Log to a file")
  35. ilogLevel := flag.String("loglevel", "Info", "Logging level (Debug, Info, Error)")
  36. showHelp := flag.Bool("help", false, "Show this help message")
  37. flag.Usage = func() {
  38. fmt.Println()
  39. if !interactive {
  40. fmt.Println(fmt.Sprintf("Usage of %s run [options] <file>", os.Args[0]))
  41. } else {
  42. fmt.Println(fmt.Sprintf("Usage of %s [options]", os.Args[0]))
  43. }
  44. fmt.Println()
  45. flag.PrintDefaults()
  46. fmt.Println()
  47. }
  48. if len(os.Args) > 2 {
  49. flag.CommandLine.Parse(os.Args[2:])
  50. if *showHelp {
  51. flag.Usage()
  52. return nil
  53. }
  54. }
  55. var clt termutil.ConsoleLineTerminal
  56. var logger util.Logger
  57. clt, err = termutil.NewConsoleLineTerminal(os.Stdout)
  58. // Create the logger
  59. if err == nil {
  60. // Check if we should log to a file
  61. if ilogFile != nil && *ilogFile != "" {
  62. var logWriter io.Writer
  63. logFileRollover := fileutil.SizeBasedRolloverCondition(1000000) // Each file can be up to a megabyte
  64. logWriter, err = fileutil.NewMultiFileBuffer(*ilogFile, fileutil.ConsecutiveNumberIterator(10), logFileRollover)
  65. logger = util.NewBufferLogger(logWriter)
  66. } else {
  67. // Log to the console by default
  68. logger = util.NewStdOutLogger()
  69. }
  70. // Set the log level
  71. if err == nil {
  72. if ilogLevel != nil && *ilogLevel != "" {
  73. logger, err = util.NewLogLevelLogger(logger, *ilogLevel)
  74. }
  75. }
  76. }
  77. // Get the import locator
  78. importLocator := &util.FileImportLocator{Root: *idir}
  79. if err == nil {
  80. name := "ECAL console"
  81. // Create interpreter
  82. erp := interpreter.NewECALRuntimeProvider(name, importLocator, logger)
  83. // Create global variable scope
  84. vs := scope.NewScope(scope.GlobalScope)
  85. // TODO Execute file
  86. if interactive {
  87. // Preload stdlib packages and functions
  88. // TODO stdlibPackages, stdlibConst, stdlibFuncs := stdlib.GetStdlibSymbols()
  89. // Drop into interactive shell
  90. if err == nil {
  91. isExitLine := func(s string) bool {
  92. return s == "exit" || s == "q" || s == "quit" || s == "bye" || s == "\x04"
  93. }
  94. // Add history functionality without file persistence
  95. clt, err = termutil.AddHistoryMixin(clt, "",
  96. func(s string) bool {
  97. return isExitLine(s)
  98. })
  99. if err == nil {
  100. if err = clt.StartTerm(); err == nil {
  101. var line string
  102. defer clt.StopTerm()
  103. fmt.Println(fmt.Sprintf("ECAL %v", config.ProductVersion))
  104. fmt.Println("Type 'q' or 'quit' to exit the shell and '?' to get help")
  105. line, err = clt.NextLine()
  106. for err == nil && !isExitLine(line) {
  107. trimmedLine := strings.TrimSpace(line)
  108. // Process the entered line
  109. if line == "?" {
  110. // Show help
  111. clt.WriteString(fmt.Sprintf("ECAL %v\n", config.ProductVersion))
  112. clt.WriteString(fmt.Sprintf("\n"))
  113. clt.WriteString(fmt.Sprintf("Console supports all normal ECAL statements and the following special commands:\n"))
  114. clt.WriteString(fmt.Sprintf("\n"))
  115. clt.WriteString(fmt.Sprintf(" @syms - List all available inbuild functions and available stdlib packages of ECAL.\n"))
  116. clt.WriteString(fmt.Sprintf(" @stdl - List all available constants and functions of a stdlib package.\n"))
  117. clt.WriteString(fmt.Sprintf(" @lk - Do a full text search through all docstrings.\n"))
  118. clt.WriteString(fmt.Sprintf("\n"))
  119. } else if strings.HasPrefix(trimmedLine, "@syms") {
  120. args := strings.Split(trimmedLine, " ")[1:]
  121. // TODO Implement
  122. clt.WriteString(fmt.Sprint("syms:", args))
  123. } else if line == "!reset" {
  124. } else {
  125. var ierr error
  126. var ast *parser.ASTNode
  127. var res interface{}
  128. if ast, ierr = parser.ParseWithRuntime("console input", line, erp); ierr == nil {
  129. if ierr = ast.Runtime.Validate(); ierr == nil {
  130. if res, ierr = ast.Runtime.Eval(vs, make(map[string]interface{})); ierr == nil && res != nil {
  131. clt.WriteString(fmt.Sprintln(res))
  132. }
  133. }
  134. }
  135. if ierr != nil {
  136. clt.WriteString(fmt.Sprintln(ierr.Error()))
  137. }
  138. }
  139. line, err = clt.NextLine()
  140. }
  141. }
  142. }
  143. }
  144. }
  145. }
  146. return err
  147. }