~sircmpwn/go-bare

b9b6a4eeac71cc72cbadbd059430dc3e15400e50 — Drew DeVault a month ago f16cd33
parse: implement optional types
3 files changed, 39 insertions(+), 7 deletions(-)

M schema/ast.go
M schema/parser.go
M schema/parser_test.go
M schema/ast.go => schema/ast.go +12 -0
@@ 78,3 78,15 @@ type PrimitiveType struct {
func (pt *PrimitiveType) Kind() TypeKind {
	return pt.kind
}

type OptionalType struct {
	subtype Type
}

func (ot *OptionalType) Kind() TypeKind {
	return Optional
}

func (ot *OptionalType) Subtype() Type {
	return ot.subtype
}

M schema/parser.go => schema/parser.go +7 -2
@@ 111,12 111,17 @@ func parseType(scanner *Scanner) (Type, error) {
		return &PrimitiveType{Bool}, nil
	case TSTRING:
		return &PrimitiveType{String}, nil
	case TOPTIONAL:
		st, err := parseType(scanner)
		if err != nil {
			return nil, err
		}
		return &OptionalType{subtype: st}, nil
	case TDATA:
	case TMAP:
	case TOPTIONAL:
	case TNAME:
		return nil, errors.New("TODO: " + name)
	}

	return nil, errors.New("TODO")
	return nil, &ErrUnexpectedToken{tok, "type"}
}

M schema/parser_test.go => schema/parser_test.go +20 -5
@@ 42,14 42,29 @@ func ParsePrimitives(t *testing.T) {
		type MyBool bool
		type MyString string
	`))
	assert.NoError(t, err, "Expected Parse to return without error")
	assert.NoError(t, err)
	assert.Len(t, types, len(reference))

	for i, ty := range types {
		ref := reference[i]
		assert.IsType(t, ty, new(*UserDefinedType), "Expected primitive type")
		assert.IsType(t, ty, new(*UserDefinedType))

		udt, _ := ty.(*UserDefinedType)
		assert.Equal(t, udt.Name(), ref.name, "Incorrect type name")
		assert.Equal(t, udt.Type().Kind(), ref.kind, "Incorrect type kind")
		udt := ty.(*UserDefinedType)
		assert.Equal(t, ref.name, udt.Name())
		assert.Equal(t, ref.kind, udt.Type().Kind())
	}
}

func ParseOptional(t *testing.T) {
	types, err := Parse(strings.NewReader("type MyOptional optional<u32>"))
	assert.NoError(t, err)
	assert.Len(t, types, 1)

	assert.IsType(t, new(*UserDefinedType), types[0])
	udt := types[0].(*UserDefinedType)
	assert.Equal(t, "", udt.Name())

	assert.IsType(t, new(*OptionalType), udt.Type())
	ot := udt.Type().(*OptionalType)
	assert.Equal(t, ot.Subtype().Kind(), U8)
}