Skip to content

Commit

Permalink
fix pre-defined variables to be available in initial modules (close #231
Browse files Browse the repository at this point in the history
)
  • Loading branch information
itchyny committed Jan 1, 2024
1 parent b9ac943 commit 111b6ef
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
14 changes: 7 additions & 7 deletions compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,13 @@ func Compile(q *Query, options ...CompilerOption) (*Code, error) {
setscope := c.lazy(func() *code {
return &code{op: opscope, v: [3]int{scope.id, scope.variablecnt, 0}}
})
for _, name := range c.variables {
if !newLexer(name).validVarName() {
return nil, &variableNameError{name}
}
c.appendCodeInfo(name)
c.append(&code{op: opstore, v: c.pushVariable(name)})
}
if c.moduleLoader != nil {
if moduleLoader, ok := c.moduleLoader.(interface {
LoadInitModules() ([]*Query, error)
Expand Down Expand Up @@ -113,13 +120,6 @@ func Compile(q *Query, options ...CompilerOption) (*Code, error) {
}

func (c *compiler) compile(q *Query) error {
for _, name := range c.variables {
if !newLexer(name).validVarName() {
return &variableNameError{name}
}
c.appendCodeInfo(name)
c.append(&code{op: opstore, v: c.pushVariable(name)})
}
for _, i := range q.Imports {
if err := c.compileImport(i); err != nil {
return err
Expand Down
5 changes: 3 additions & 2 deletions option_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ type moduleLoaderInitModules struct{}

func (*moduleLoaderInitModules) LoadInitModules() ([]*gojq.Query, error) {
query, err := gojq.Parse(`
def f: 42;
def f: $x;
def g: f * f;
`)
if err != nil {
Expand All @@ -162,12 +162,13 @@ func TestWithModuleLoader_LoadInitModules(t *testing.T) {
}
code, err := gojq.Compile(
query,
gojq.WithVariables([]string{"$x"}),
gojq.WithModuleLoader(&moduleLoaderInitModules{}),
)
if err != nil {
t.Fatal(err)
}
iter := code.Run(nil)
iter := code.Run(nil, 42)
for {
got, ok := iter.Next()
if !ok {
Expand Down

0 comments on commit 111b6ef

Please sign in to comment.