parse_files.odin 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package odin_parser
  2. import "core:odin/tokenizer"
  3. import "core:odin/ast"
  4. import "core:path/filepath"
  5. import "core:fmt"
  6. import "core:os"
  7. import "core:slice"
  8. import "core:strings"
  9. collect_package :: proc(path: string) -> (pkg: ^ast.Package, success: bool) {
  10. NO_POS :: tokenizer.Pos{}
  11. pkg_path, pkg_path_ok := filepath.abs(path)
  12. if !pkg_path_ok {
  13. return
  14. }
  15. path_pattern := fmt.tprintf("%s/*.odin", pkg_path)
  16. matches, err := filepath.glob(path_pattern)
  17. defer delete(matches)
  18. if err != nil {
  19. return
  20. }
  21. pkg = ast.new(ast.Package, NO_POS, NO_POS)
  22. pkg.fullpath = pkg_path
  23. for match in matches {
  24. src: []byte
  25. fullpath, ok := filepath.abs(match)
  26. if !ok {
  27. return
  28. }
  29. src, ok = os.read_entire_file(fullpath)
  30. if !ok {
  31. delete(fullpath)
  32. return
  33. }
  34. if strings.trim_space(string(src)) == "" {
  35. delete(fullpath)
  36. delete(src)
  37. continue
  38. }
  39. file := ast.new(ast.File, NO_POS, NO_POS)
  40. file.pkg = pkg
  41. file.src = string(src)
  42. file.fullpath = fullpath
  43. pkg.files[fullpath] = file
  44. }
  45. success = true
  46. return
  47. }
  48. parse_package :: proc(pkg: ^ast.Package, p: ^Parser = nil) -> bool {
  49. p := p
  50. if p == nil {
  51. p = &Parser{}
  52. p^ = default_parser()
  53. }
  54. ok := true
  55. files := make([]^ast.File, len(pkg.files), context.temp_allocator)
  56. i := 0
  57. for _, file in pkg.files {
  58. files[i] = file
  59. i += 1
  60. }
  61. slice.sort(files)
  62. for file in files {
  63. if !parse_file(p, file) {
  64. ok = false
  65. }
  66. if pkg.name == "" {
  67. pkg.name = file.pkg_decl.name
  68. } else if pkg.name != file.pkg_decl.name {
  69. error(p, file.pkg_decl.pos, "different package name, expected '%s', got '%s'", pkg.name, file.pkg_decl.name)
  70. }
  71. }
  72. return ok
  73. }
  74. parse_package_from_path :: proc(path: string, p: ^Parser = nil) -> (pkg: ^ast.Package, ok: bool) {
  75. pkg, ok = collect_package(path)
  76. if !ok {
  77. return
  78. }
  79. ok = parse_package(pkg, p)
  80. return
  81. }