Repository navigation
fix: emit null from last/1 on an empty generator (#349) - #350
Closed
daichunghy wants to merge 2 commits into
Closed
daichunghy wants to merge 2 commits into
daichunghy wants to merge 2 commits into
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
When a generator yields no values,
last/1produces no output, whereas jq returnsnull:gojq -n 'last(empty)'prints nothing;jq -n 'last(empty)'printsnullgojq -n '[last(empty)]'prints[]; jq prints[null]echo '[]' | gojq -c 'last(.[])'prints nothing; jq printsnulllast(range(0))behaves the same wayFixes
last/1on an empty generator produces no output; jq producesnull#349.Cause
In
compileLast(compiler.go), the compiled_lastuses a$xflag to track whether any value was seen. If the generator is exhausted without yielding anything,$xstays true and the code backtracks without producing output. jq defineslast(g)asreduce g as $item (null; $item), so an empty generator reduces to the initial valuenull.Fix
Push
nulland return instead of backtracking when no value was seen. Non-empty generators are unaffected and still return the last value as before.Tests
cli/test.yaml:last(empty)tonull,[last(empty)]to[null],last(range(0))tonull.first/1, last/1, nth/2 functions on emptycase to expect[null]instead of[].go test ./...passes (2 packages, 0 failures), matching the baseline on unmodified main.gofmtandgo vetare clean.Limits
first/1unchanged intentionally, sincefirst(empty)producing no output matches jq._last;last/0(array index) uses a separate code path and is unchanged.