package raku import ( "errors" "fmt" "io/ioutil" "os" "github.com/yhirose/go-peg" ) type Parser struct { *peg.Parser } type Result struct { * peg.Ast } func parserCheck(err error) { if perr, ok := err.(*peg.Error); ok { for _, d := range perr.Details { fmt.Println(d) } os.Exit(1) } } var defaultParser *Parser /** Loads a PEG parser from the given file name. */ func LoadParser(filename string) (*Parser, error) { result := &Parser{} data, err := ioutil.ReadFile(filename) if err == nil { result.Parser, err = peg.NewParser(string(data)) if err == nil { result.EnableAst() } return result, err } else { return nil, err } } func InitDefaultParser(peg_filename string) error { var err error defaultParser, err = LoadParser(peg_filename) return err } func wrapResult(wrapme peg.Any) *Result { result := &Result{}; ast, ok := wrapme.(*peg.Ast) if ok { result.Ast = ast return result } return nil } func (parser Parser) Parse(source string) (*Result, error) { ast, err := parser.ParseAndGetValue(source, nil) return wrapResult(ast), err } func (parser Parser) ParseFile(filename string) (*Result, error) { source, err := ioutil.ReadFile(filename) if err == nil { return parser.Parse(string(source)) } else { return nil, err } } func parse(source string) (*Result, error) { if defaultParser == nil { return nil, errors.New("Default parser not initialized!") } return defaultParser.Parse(source) } func parseFile(filename string) (*Result, error) { if defaultParser == nil { return nil, errors.New("Default parser not initialized!") } return defaultParser.ParseFile(filename) }