Skip to content

Commit

Permalink
Added possibility to use string literals as object poperties
Browse files Browse the repository at this point in the history
  • Loading branch information
ziflex committed Oct 22, 2018
1 parent c706f01 commit 685c587
Show file tree
Hide file tree
Showing 5 changed files with 388 additions and 304 deletions.
37 changes: 37 additions & 0 deletions pkg/compiler/compiler_member_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package compiler_test

import (
"context"
"fmt"
"github.com/MontFerret/ferret/pkg/compiler"
. "github.com/smartystreets/goconvey/convey"
"testing"
Expand Down Expand Up @@ -64,6 +65,42 @@ func TestMember(t *testing.T) {
So(string(out), ShouldEqual, `"wsx"`)
})

Convey("Object by literal with property defined as a string", func() {
c := compiler.New()

prog, err := c.Compile(`
LET obj = { "foo": "bar", "qaz": "wsx"}
RETURN obj["qaz"]
`)

So(err, ShouldBeNil)

out, err := prog.Run(context.Background())

So(err, ShouldBeNil)

So(string(out), ShouldEqual, `"wsx"`)
})

Convey("Object by literal with property defined as a multi line string", func() {
c := compiler.New()

prog, err := c.Compile(fmt.Sprintf(`
LET obj = { "foo": "bar", %s: "wsx"}
RETURN obj["qaz"]
`, "`qaz`"))

So(err, ShouldBeNil)

out, err := prog.Run(context.Background())

So(err, ShouldBeNil)

So(string(out), ShouldEqual, `"wsx"`)
})

Convey("Object by variable", func() {
c := compiler.New()

Expand Down
21 changes: 20 additions & 1 deletion pkg/compiler/visitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -560,7 +560,26 @@ func (v *visitor) doVisitObjectLiteral(ctx *fql.ObjectLiteralContext, scope *sco
}

func (v *visitor) doVisitPropertyNameContext(ctx *fql.PropertyNameContext, _ *scope) (core.Expression, error) {
return literals.NewStringLiteral(ctx.Identifier().GetText()), nil
var name string

identifier := ctx.Identifier()

if identifier != nil {
name = identifier.GetText()
} else {
stringLiteral := ctx.StringLiteral()

if stringLiteral != nil {
runes := []rune(stringLiteral.GetText())
name = string(runes[1 : len(runes)-1])
}
}

if name == "" {
return nil, core.Error(core.ErrNotFound, "property name")
}

return literals.NewStringLiteral(name), nil
}

func (v *visitor) doVisitComputedPropertyNameContext(ctx *fql.ComputedPropertyNameContext, scope *scope) (core.Expression, error) {
Expand Down
1 change: 1 addition & 0 deletions pkg/parser/antlr/FqlParser.g4
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ computedPropertyName

propertyName
: Identifier
| stringLiteral
;

expressionSequence
Expand Down
2 changes: 1 addition & 1 deletion pkg/parser/fql/FqlParser.interp

Large diffs are not rendered by default.

Loading

0 comments on commit 685c587

Please sign in to comment.