parse_files.odin 1.7 KB

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