Return None instead of crashing on invalid An+B input#72
Merged
Conversation
parse_nth is documented to return None for invalid input, but several
truncated nth-child fragments crashed instead:
- '+' (and '+/**/') raised StopIteration: after a leading '+', next(tokens)
read the following token without guarding against an exhausted iterator.
- 'n+', 'n +', '-n-', '2n +' raised AttributeError: parse_signless_b
dereferenced token.type when _next_significant returned None.
Guard both reads so they fall through to the function's implicit return None.
Whitespace after a leading '+' stays invalid ('+ n' -> None, '+n' -> (1, 0)),
matching the An+B spec test data.
Member
|
Thank you! |
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.
Steps
tinycss2.nth.parse_nthis documented to returnNonefor invalid input, but several short, plausible truncatedAn+Bfragments crash instead:Two unguarded token reads:
parse_nth(after a leading+):next(tokens)reads the next token without guarding against an exhausted iterator. The rawnextis intentional — whitespace after+must stay invalid, so it can't be skipped — but exhaustion wasn't handled.parse_signless_b:_next_significant(tokens)can returnNone, thentoken.typedereferences it.Fix
Use
next(tokens, None)and addtoken is not Noneguards so both paths fall through to the function's implicitreturn None, matching the documented contract.Whitespace-sensitivity is preserved:
+n→(1, 0)(valid),+ n→None(invalid), confirmed against the officialAn+B.jsontest data.Added regression tests in
tests/test_tinycss2.py; the full suite passes (16975).Notes
Found by fuzzing the public API. This pull request was prepared with the assistance of AI, under my direction and review.