MiSawa / xq

Pure rust implementation of jq
MIT License
333 stars 18 forks source link

Optional object indexing suffix differences #66

Closed itchyny closed 2 years ago

itchyny commented 2 years ago

Using optional object indexing as term suffix seems to have different semantics.

❯ jq -n '[1,{x:2},3,{x:4}] | [.[].x?]'
[
  2,
  4
]

❯ xq -n '[1,{x:2},3,{x:4}] | [.[].x?]'
[]

❯ xq --version
xq 0.2.3-a7d4cfbf962f3570b326dd97ecf288365d396ed4

Interestingly, adding | will fix the behavior.

❯ xq -n '[1,{x:2},3,{x:4}] | [.[]|.x?]'
[
  2,
  4
]
MiSawa commented 2 years ago

Hmmm seems to be parsed as expected, so it's either a compiler's issue or a VM's issue.

itchyny commented 2 years ago

Note that the optional operator applies only to the last (index, slice and iterator) suffix. Here's

❯ jq -n '0 | .x.y?'
jq: error (at <unknown>): Cannot index number with string "x"

❯ xq -n '0 | .x.y?'

Here, .x.y? is semantically equivalent to .x | try .y, not try .x.y. Likewise, 0 | .[].x? is 0 | .[] | try .x, not 0 | try .[].x.

But while I was investigating the gojq implementation again, I noticed that gojq also has a bug. The query 0 | .x[]? should emit indexing error because it is equivalent to 0 | .x | try .[], not 0 | try .x[]. xq has this issue too.