main.go 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package main
  2. import "os"
  3. import "fmt"
  4. import "io"
  5. import "io/ioutil"
  6. import "./parser/syntax"
  7. import "./parser/scanner"
  8. import "./parser"
  9. import "./transpiler"
  10. func check (err error) {
  11. if (err != nil) {
  12. panic(err)
  13. }
  14. }
  15. func parser_debug (file io.Reader, name string, root string) {
  16. var code_bytes, err = ioutil.ReadAll(file)
  17. check(err)
  18. var code_string = string(code_bytes)
  19. var code = []rune(code_string)
  20. var tokens, info, semi = scanner.Scan(code)
  21. fmt.Println("Tokens:")
  22. for i, token := range tokens {
  23. fmt.Printf(
  24. "(%v) at [%v, %v] %v: %v\n",
  25. i, info[token.Pos].Row, info[token.Pos].Col,
  26. syntax.Id2Name[token.Id],
  27. string(token.Content),
  28. )
  29. }
  30. var RootId, exists = syntax.Name2Id[root]
  31. if !exists {
  32. panic("invalid root syntax unit " + root)
  33. }
  34. var nodes, err_ptr, err_desc = parser.BuildBareTree(RootId, tokens)
  35. fmt.Println("------------------------------------------------------")
  36. fmt.Println("AST Nodes:")
  37. parser.PrintBareTree(nodes)
  38. var tree = parser.Tree {
  39. Code: code, Tokens: tokens, Info: info, Semi: semi,
  40. Nodes: nodes, File: name,
  41. }
  42. fmt.Println("------------------------------------------------------")
  43. fmt.Println("AST:")
  44. parser.PrintTree(tree)
  45. if err_ptr != -1 {
  46. parser.Error(&tree, err_ptr, err_desc)
  47. }
  48. }
  49. func PrintHelpInfo () {
  50. fmt.Printf (
  51. "Usage:\n\t" +
  52. "%v eval [--debug]\n\t" +
  53. "%v module FILE [--debug]\n",
  54. os.Args[0], os.Args[0],
  55. )
  56. }
  57. func main () {
  58. syntax.Init()
  59. transpiler.Init()
  60. if len(os.Args) > 1 {
  61. var mode = os.Args[1]
  62. if mode == "eval" {
  63. var only_debug = len(os.Args) > 2 && os.Args[2] == "--debug"
  64. if only_debug {
  65. parser_debug(os.Stdin, "<eval>", "eval")
  66. } else {
  67. fmt.Print(transpiler.TranspileFile(os.Stdin, "<eval>", "eval"))
  68. }
  69. } else if mode == "module" {
  70. if len(os.Args) <= 2 {
  71. PrintHelpInfo()
  72. }
  73. var path = os.Args[2]
  74. var file, err = os.Open(path)
  75. if err != nil {
  76. panic(fmt.Sprintf("error: %v: %v", path, err))
  77. }
  78. var only_debug = len(os.Args) > 3 && os.Args[3] == "--debug"
  79. if only_debug {
  80. parser_debug(file, path, "module")
  81. } else {
  82. fmt.Print(transpiler.TranspileFile(file, path, "module"))
  83. }
  84. file.Close()
  85. } else {
  86. PrintHelpInfo()
  87. }
  88. } else {
  89. PrintHelpInfo()
  90. }
  91. }