123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- 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)
- }
|