Ejemplo n.º 1
0
// ObjectParser 实现数组解析器
func ObjectParser() p.P {
	return func(st p.State) (interface{}, error) {
		left := p.Chr('{').Then(Skip)
		right := Skip.Then(p.Chr('}'))
		empty := p.Between(left, right, Skip)

		object, err := p.Between(left, right, p.Many(p.Choice(objectBodyParser, p.NChr('}'))))(st)
		if err != nil {
			_, e := empty(st)
			if e != nil {
				return nil, err
			}
			return Object{}, nil
		}

		switch o := object.(type) {
		case Object:
			return O(o), nil
		case map[string]interface{}:
			return object.(map[string]interface{}), nil
		default:
			return nil, fmt.Errorf("Object Parser Error: %v type is unexpected: %v", object, reflect.TypeOf(object))
		}

	}
}
Ejemplo n.º 2
0
// ListParser 实现数组解析器
func ListParser() p.P {
	return func(st p.State) (interface{}, error) {
		left := p.Chr('[').Then(Skip)
		right := Skip.Then(p.Chr(']'))
		empty := p.Between(left, right, Skip)

		list, err := p.Between(left, right, p.Many(p.Choice(p.NChr(']'), listBodyParser)))(st)
		fmt.Printf("list type :%v, value :%v, err: %v\n", reflect.TypeOf(list), list, err)
		if err != nil {
			_, e := empty(st)
			if e != nil {
				return nil, err
			}
			return List{}, nil
		}

		switch l := list.(type) {
		case List:
			return L(l), nil
		case []interface{}:
			return list.([]interface{}), nil
		default:
			return nil, fmt.Errorf("List Parser Error: %v type is unexpected: %v", list, reflect.TypeOf(list))
		}
	}
}
Ejemplo n.º 3
0
		return '\n'
	case '\'':
		return '\''
	case '\\':
		return '\\'
	case 't':
		return '\t'
	default:
		panic(st.Trap("Unknown escape sequence \\%c", r))
	}
})

// RuneParser 实现 rune 的解析
var RuneParser = p.Do(func(state p.State) interface{} {
	p.Chr('\'').Exec(state)
	c := p.Choice(p.Try(EscapeCharr), p.NChr('\'')).Exec(state)
	p.Chr('\'').Exec(state)
	return Rune(c.(rune))
})

// StringParser 实现字符串解析
var StringParser = p.Between(p.Chr('"'), p.Chr('"'),
	p.Many(p.Choice(p.Try(EscapeChars), p.NChr('"')))).Bind(p.ReturnString)

func bodyParser(st p.State) (interface{}, error) {
	value, err := p.SepBy(ValueParser(), Skip)(st)
	return value, err
}

func bodyParserExt(env Env) p.P {
	return p.Many(ValueParserExt(env).Over(Skip))