Skip to content

fix: emit null from last/1 on an empty generator (#349) - #350

Closed
daichunghy wants to merge 2 commits into
itchyny:mainfrom
daichunghy:fix/349-last-empty-generator
Closed

daichunghy wants to merge 2 commits into
itchyny:mainfrom
daichunghy:fix/349-last-empty-generator

Conversation

@daichunghy

Copy link
Copy Markdown
Contributor

Problem

When a generator yields no values, last/1 produces no output, whereas jq returns null:

Cause

In compileLast (compiler.go), the compiled _last uses a $x flag to track whether any value was seen. If the generator is exhausted without yielding anything, $x stays true and the code backtracks without producing output. jq defines last(g) as reduce g as $item (null; $item), so an empty generator reduces to the initial value null.

Fix

Push null and return instead of backtracking when no value was seen. Non-empty generators are unaffected and still return the last value as before.

Tests

  • Added CLI cases in cli/test.yaml: last(empty) to null, [last(empty)] to [null], last(range(0)) to null.
  • Updated the existing first/1, last/1, nth/2 functions on empty case to expect [null] instead of [].
  • All four new/updated cases fail on unmodified main and pass with the fix. I verified the expected outputs against jq 1.7.
  • Full suite: go test ./... passes (2 packages, 0 failures), matching the baseline on unmodified main. gofmt and go vet are clean.

Limits

  • Left first/1 unchanged intentionally, since first(empty) producing no output matches jq.
  • The fix is limited to the empty-generator path of _last; last/0 (array index) uses a separate code path and is unchanged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

last/1 on an empty generator produces no output; jq produces null

2 participants