peg.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package raku
  2. import (
  3. "errors"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "github.com/yhirose/go-peg"
  8. )
  9. type Parser struct {
  10. *peg.Parser
  11. }
  12. type Result struct {
  13. * peg.Ast
  14. }
  15. func parserCheck(err error) {
  16. if perr, ok := err.(*peg.Error); ok {
  17. for _, d := range perr.Details {
  18. fmt.Println(d)
  19. }
  20. os.Exit(1)
  21. }
  22. }
  23. var defaultParser *Parser
  24. /** Loads a PEG parser from the given file name. */
  25. func LoadParser(filename string) (*Parser, error) {
  26. result := &Parser{}
  27. data, err := ioutil.ReadFile(filename)
  28. if err == nil {
  29. result.Parser, err = peg.NewParser(string(data))
  30. if err == nil {
  31. result.EnableAst()
  32. }
  33. return result, err
  34. } else {
  35. return nil, err
  36. }
  37. }
  38. func InitDefaultParser(peg_filename string) error {
  39. var err error
  40. defaultParser, err = LoadParser(peg_filename)
  41. return err
  42. }
  43. func wrapResult(wrapme peg.Any) *Result {
  44. result := &Result{};
  45. ast, ok := wrapme.(*peg.Ast)
  46. if ok {
  47. result.Ast = ast
  48. return result
  49. }
  50. return nil
  51. }
  52. func (parser Parser) Parse(source string) (*Result, error) {
  53. ast, err := parser.ParseAndGetValue(source, nil)
  54. return wrapResult(ast), err
  55. }
  56. func (parser Parser) ParseFile(filename string) (*Result, error) {
  57. source, err := ioutil.ReadFile(filename)
  58. if err == nil {
  59. return parser.Parse(string(source))
  60. } else {
  61. return nil, err
  62. }
  63. }
  64. func parse(source string) (*Result, error) {
  65. if defaultParser == nil {
  66. return nil, errors.New("Default parser not initialized!")
  67. }
  68. return defaultParser.Parse(source)
  69. }
  70. func parseFile(filename string) (*Result, error) {
  71. if defaultParser == nil {
  72. return nil, errors.New("Default parser not initialized!")
  73. }
  74. return defaultParser.ParseFile(filename)
  75. }