interpret.go 4.5 KB

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