From 3853a3ba12687a93118d70601f2543919005dbb9 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Thu, 9 Jul 2026 14:51:15 -0400 Subject: [PATCH 1/4] feat(requirement): PEP 508 dependency specifier (#18636) Port pypa/packaging's _parse_requirement: name [extras] (versionspec | "@" url) [";" marker], driving the shared internal/pep508 tokenizer end-to-end in one pass rather than splitting the string on ";" (which would mishandle a URL requirement whose URL itself contains ";"). - internal/pep508: add requirement-only token kinds (Identifier, LBracket, RBracket, Comma, Semicolon, AT, Specifier, URL) and ParseRequirement, which parses the marker clause mid-stream via the existing ParseMarker - no substring re-parse, no second lexer. - marker: add FromExpr, the seam that lets requirement/ wrap an already-parsed pep508.Expr into a Marker without re-lexing. - requirement: public Requirement/Parse/String, delegating the specifier to version.NewSpecifiers, extras to extras.Normalize, and distinguishing malformed-syntax/bad-version/bad-marker error categories under the ErrInvalidRequirement sentinel. --- internal/pep508/doc.go | 4 +- internal/pep508/requirement.go | 236 ++++++++++++++++++++++ internal/pep508/requirement_test.go | 302 ++++++++++++++++++++++++++++ internal/pep508/tokenizer.go | 99 +++++++-- marker/marker.go | 14 ++ requirement/doc.go | 13 +- requirement/requirement.go | 127 ++++++++++++ requirement/requirement_test.go | 228 +++++++++++++++++++++ 8 files changed, 1005 insertions(+), 18 deletions(-) create mode 100644 internal/pep508/requirement.go create mode 100644 internal/pep508/requirement_test.go create mode 100644 requirement/requirement.go create mode 100644 requirement/requirement_test.go diff --git a/internal/pep508/doc.go b/internal/pep508/doc.go index 6f8fe09..cea01d4 100644 --- a/internal/pep508/doc.go +++ b/internal/pep508/doc.go @@ -1,8 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 OR MIT // Package pep508 implements the shared, position-tracking tokenizer used to -// parse PEP 508 environment markers (package marker/) and, eventually, PEP -// 508 dependency-specifier requirement strings (package requirement/). +// parse PEP 508 environment markers (package marker/) and PEP 508 +// dependency-specifier requirement strings (package requirement/). // // It is a Go port of pypa/packaging's _tokenizer.py: a Tokenizer holds the // source string and a byte offset, and exposes a parser-driven API (check, diff --git a/internal/pep508/requirement.go b/internal/pep508/requirement.go new file mode 100644 index 0000000..66b0955 --- /dev/null +++ b/internal/pep508/requirement.go @@ -0,0 +1,236 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package pep508 + +import "strings" + +// RawRequirement is the raw, structurally-parsed result of a PEP 508 +// requirement string, before the public requirement/ package applies name +// canonicalization (none - the caller's concern), extras normalization +// (extras.Normalize), version-specifier delegation (version.NewSpecifiers), +// and marker wrapping (marker.FromExpr). +// +// Fields are populated exactly as parsed: Name is not canonicalized, Extras +// are not normalized, Specifier is the raw (un-parenthesized) specifier +// text handed verbatim to version.NewSpecifiers, and Marker is the +// pep508.Expr returned by ParseMarker (nil if there was no "; marker" +// clause at all - as opposed to a Marker.ast of nil, which package marker's +// zero value also represents "no clause"). +type RawRequirement struct { + Name string + Extras []string + Specifier string + URL string + Marker Expr +} + +// MarkerClauseError wraps an error that occurred while parsing a +// requirement's "; marker" clause (via ParseMarker), distinguishing it from +// a *SyntaxError raised anywhere else in the requirement grammar (name, +// extras, versionspec, url). Both are *SyntaxError under the hood - this +// wrapper is what lets a caller (package requirement's Parse) tell "bad +// marker" apart from "malformed requirement syntax" via errors.As, without +// requiring a second, unrelated error type from the marker grammar itself. +type MarkerClauseError struct { + Err error +} + +func (e *MarkerClauseError) Error() string { return e.Err.Error() } +func (e *MarkerClauseError) Unwrap() error { return e.Err } + +// ParseRequirement parses s (via t) as a complete PEP 508 dependency +// specifier and verifies nothing but end-of-input follows, mirroring +// packaging's _parse_requirement (_parser.py) and its wrapper parse_requirement. +// +// Grammar (PEP 508's formal grammar, as packaging implements it): +// +// specification = wsp* ( url_req | name_req ) wsp* +// name_req = name wsp* extras? wsp* versionspec? wsp* quoted_marker? +// url_req = name wsp* extras? wsp* urlspec wsp+ quoted_marker? +// name = identifier +// extras = '[' wsp* extras_list? wsp* ']' +// extras_list = identifier (wsp* ',' wsp* identifier)* +// versionspec = ( '(' version_many ')' ) | version_many +// version_many = version_one (wsp* ',' version_one)* +// urlspec = '@' wsp* +// quoted_marker = ';' wsp* marker +// +// This drives the SHARED tokenizer end-to-end in one pass - name, then +// optional extras, then optional (versionspec | "@" url), then, if a ";" +// follows, the marker clause via ParseMarker from the tokenizer's current +// position - rather than pre-splitting the string on ";" (which would +// mishandle a URL requirement whose URL itself contains ";") or re-lexing a +// marker substring with a second tokenizer. +func ParseRequirement(t *Tokenizer) (RawRequirement, error) { + t.consume(WS) + nameTok, err := t.expect(Identifier, "package name") + if err != nil { + return RawRequirement{}, err + } + req := RawRequirement{Name: nameTok.Text} + t.consume(WS) + + extras, err := parseExtras(t) + if err != nil { + return RawRequirement{}, err + } + req.Extras = extras + t.consume(WS) + + if err := parseRequirementDetails(t, &req); err != nil { + return RawRequirement{}, err + } + t.consume(WS) + + if _, err := t.expect(End, "end of requirement string"); err != nil { + return RawRequirement{}, err + } + return req, nil +} + +// parseExtras parses packaging's "extras" production. A missing "[" is not +// an error - extras are entirely optional - and an empty "[]" is valid +// (returning a nil/empty slice, not an error). +func parseExtras(t *Tokenizer) ([]string, error) { + if !t.check(LBracket) { + return nil, nil + } + t.read() + t.consume(WS) + + var names []string + if t.check(Identifier) { + names = append(names, t.read().Text) + t.consume(WS) + for t.check(Comma) { + t.read() + t.consume(WS) + idTok, err := t.expect(Identifier, "extra name after ','") + if err != nil { + return nil, err + } + names = append(names, idTok.Text) + t.consume(WS) + } + } + + if _, err := t.expect(RBracket, "']'"); err != nil { + return nil, err + } + return names, nil +} + +// parseRequirementDetails parses packaging's "requirement_details": +// optionally either a version specifier or an "@ url" clause, followed by +// an optional "; marker" clause, and stores the results into req. +// +// The "@ url" branch enforces PEP 508's url_req asymmetry: mandatory +// whitespace (or end-of-input) must follow the URL before anything else can +// be parsed - including a following marker clause. Without that whitespace, +// there is no way to tell "the URL ends here" from "the URL continues", so +// (correctly, per PEP 508) everything up to the next whitespace or +// end-of-input is simply part of the URL, semicolons included. +func parseRequirementDetails(t *Tokenizer, req *RawRequirement) error { + if t.check(AT) { + t.read() + t.consume(WS) + urlTok, err := t.expect(URL, "URL after '@'") + if err != nil { + return err + } + req.URL = urlTok.Text + + if t.peek(End) { + return nil + } + if _, err := t.expect(WS, "whitespace after URL"); err != nil { + return err + } + if t.peek(End) { + return nil + } + return parseMarkerClause(t, req) + } + + spec, err := parseVersionSpec(t) + if err != nil { + return err + } + req.Specifier = spec + t.consume(WS) + return parseMarkerClause(t, req) +} + +// parseVersionSpec parses packaging's "versionspec": an optionally +// parenthesized, comma-separated run of version-specifier clauses. It +// returns the raw specifier text (parens stripped, clauses rejoined with +// ","), or "" if no version specifier is present at all - which is legal, +// since versionspec is entirely optional in name_req. +func parseVersionSpec(t *Tokenizer) (string, error) { + t.consume(WS) + parenthesized := t.check(LParen) + if parenthesized { + t.read() + t.consume(WS) + } + + var clauses []string + if t.check(Specifier) { + clauses = append(clauses, normalizeSpecifierClause(t.read().Text)) + t.consume(WS) + for t.check(Comma) { + t.read() + t.consume(WS) + specTok, err := t.expect(Specifier, "version specifier after ','") + if err != nil { + return "", err + } + clauses = append(clauses, normalizeSpecifierClause(specTok.Text)) + t.consume(WS) + } + } else if parenthesized { + return "", t.NewSyntaxError("Expected version specifier inside parentheses") + } + + if parenthesized { + if _, err := t.expect(RParen, "')'"); err != nil { + return "", err + } + } + + return strings.Join(clauses, ","), nil +} + +// normalizeSpecifierClause strips whitespace from a single tokenized +// Specifier clause's text (the Specifier rule permissively allows "\s*" +// between the operator and the version, e.g. ">= 1.0"), producing a +// canonical, whitespace-free clause for joining into the raw specifier +// string handed to version.NewSpecifiers - which is agnostic to whether +// the input had that whitespace, but round-tripping a canonical form is +// cleaner than preserving arbitrary user spacing verbatim. +func normalizeSpecifierClause(s string) string { + return strings.Join(strings.Fields(s), "") +} + +// parseMarkerClause parses packaging's "quoted_marker" (';' wsp* marker) if +// a ';' is present at the current position; it is a no-op otherwise, since +// the marker clause is always optional. The marker itself is parsed by +// ParseMarker directly from t's current (mid-stream) position - the same +// shared tokenizer, no substring, no second lexer - and any error it +// returns is wrapped in *MarkerClauseError so the caller can distinguish a +// bad marker from a bad requirement syntax error elsewhere. +func parseMarkerClause(t *Tokenizer, req *RawRequirement) error { + if !t.check(Semicolon) { + return nil + } + t.read() + t.consume(WS) + + expr, err := ParseMarker(t) + if err != nil { + return &MarkerClauseError{Err: err} + } + req.Marker = expr + t.consume(WS) + return nil +} diff --git a/internal/pep508/requirement_test.go b/internal/pep508/requirement_test.go new file mode 100644 index 0000000..dd8c380 --- /dev/null +++ b/internal/pep508/requirement_test.go @@ -0,0 +1,302 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package pep508 + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// parseRequirementString is a small test helper mirroring parseFullMarkerString +// in marker_test.go: parse s as a complete requirement and fail the test +// immediately on error. +func parseRequirementString(t *testing.T, s string) RawRequirement { + t.Helper() + tok := NewTokenizer(s) + req, err := ParseRequirement(tok) + require.NoError(t, err, "source %q", s) + return req +} + +// --- plain name --- + +func TestParseRequirement_PlainName(t *testing.T) { + req := parseRequirementString(t, "foo") + assert.Equal(t, "foo", req.Name) + assert.Empty(t, req.Extras) + assert.Empty(t, req.Specifier) + assert.Empty(t, req.URL) + assert.Nil(t, req.Marker) +} + +func TestParseRequirement_NameWithDigitsDotsHyphensUnderscores(t *testing.T) { + req := parseRequirementString(t, "foo_bar-2.0") + assert.Equal(t, "foo_bar-2.0", req.Name) +} + +func TestParseRequirement_LeadingTrailingWhitespace(t *testing.T) { + req := parseRequirementString(t, " foo ") + assert.Equal(t, "foo", req.Name) +} + +// --- extras --- + +func TestParseRequirement_SingleExtra(t *testing.T) { + req := parseRequirementString(t, "foo[bar]") + assert.Equal(t, []string{"bar"}, req.Extras) +} + +func TestParseRequirement_MultipleExtras(t *testing.T) { + req := parseRequirementString(t, "foo[bar,baz]") + assert.Equal(t, []string{"bar", "baz"}, req.Extras) +} + +func TestParseRequirement_ExtrasWithWhitespace(t *testing.T) { + req := parseRequirementString(t, "foo[ bar , baz ]") + assert.Equal(t, []string{"bar", "baz"}, req.Extras) +} + +func TestParseRequirement_EmptyExtras(t *testing.T) { + req := parseRequirementString(t, "foo[]") + assert.Empty(t, req.Extras) +} + +func TestParseRequirement_ExtrasTrailingCommaIsSyntaxError(t *testing.T) { + tok := NewTokenizer("foo[bar,]") + _, err := ParseRequirement(tok) + require.Error(t, err) + var synErr *SyntaxError + require.ErrorAs(t, err, &synErr) +} + +func TestParseRequirement_UnclosedExtrasIsSyntaxError(t *testing.T) { + tok := NewTokenizer("foo[bar") + _, err := ParseRequirement(tok) + require.Error(t, err) + var synErr *SyntaxError + require.ErrorAs(t, err, &synErr) +} + +// --- versionspec --- + +func TestParseRequirement_BareVersionSpec(t *testing.T) { + req := parseRequirementString(t, "foo>=1.0") + assert.Equal(t, ">=1.0", req.Specifier) +} + +func TestParseRequirement_ParenthesizedVersionSpec(t *testing.T) { + req := parseRequirementString(t, "foo(>=1.0)") + assert.Equal(t, ">=1.0", req.Specifier) +} + +func TestParseRequirement_MultipleVersionSpecClauses(t *testing.T) { + req := parseRequirementString(t, "foo>=1.0,<2.0") + assert.Equal(t, ">=1.0,<2.0", req.Specifier) +} + +func TestParseRequirement_ParenthesizedMultipleVersionSpecClauses(t *testing.T) { + req := parseRequirementString(t, "foo(>=1.0,<2.0)") + assert.Equal(t, ">=1.0,<2.0", req.Specifier) +} + +func TestParseRequirement_VersionSpecWithWhitespace(t *testing.T) { + req := parseRequirementString(t, "foo >= 1.0") + assert.Equal(t, ">=1.0", req.Specifier) +} + +// --- grammar asymmetry: name form allows no wsp before ";" --- + +func TestParseRequirement_NoSpaceBeforeMarker_NameForm(t *testing.T) { + req := parseRequirementString(t, `foo>=1.0;python_version>="3.8"`) + assert.Equal(t, ">=1.0", req.Specifier) + require.NotNil(t, req.Marker) + cmp, ok := req.Marker.(*CompareExpr) + require.True(t, ok) + assert.Equal(t, EnvVar{Name: "python_version"}, cmp.Lhs) +} + +func TestParseRequirement_NoSpaceBeforeMarker_BareNameForm(t *testing.T) { + // No extras, no versionspec at all - still legal with zero whitespace + // before ";" per name_req's "wsp*". + req := parseRequirementString(t, `foo;python_version>="3.8"`) + assert.Empty(t, req.Specifier) + require.NotNil(t, req.Marker) +} + +// --- @ url form --- + +func TestParseRequirement_URL(t *testing.T) { + req := parseRequirementString(t, "foo @ https://example.com/foo-1.0.whl") + assert.Equal(t, "https://example.com/foo-1.0.whl", req.URL) + assert.Empty(t, req.Specifier) + assert.Nil(t, req.Marker) +} + +func TestParseRequirement_URLNoSpaceAroundAt(t *testing.T) { + req := parseRequirementString(t, "foo@https://example.com/foo-1.0.whl") + assert.Equal(t, "https://example.com/foo-1.0.whl", req.URL) +} + +func TestParseRequirement_URLWithMarker(t *testing.T) { + req := parseRequirementString(t, `foo @ https://example.com/foo-1.0.whl ; python_version > "3"`) + assert.Equal(t, "https://example.com/foo-1.0.whl", req.URL) + require.NotNil(t, req.Marker) + cmp, ok := req.Marker.(*CompareExpr) + require.True(t, ok) + assert.Equal(t, EnvVar{Name: "python_version"}, cmp.Lhs) + assert.Equal(t, Literal{Value: "3"}, cmp.Rhs) +} + +// --- URL containing ";" (the key robustness case) --- + +func TestParseRequirement_URLContainingSemicolon_WithMarker(t *testing.T) { + // The URL itself contains a literal ";" (e.g. a query string). Because + // the URL token is greedy non-whitespace, the whole "https://x/y;z.whl" + // is consumed as ONE token - naive splitting on the first ";" in the + // source would wrongly cut the URL in half. + req := parseRequirementString(t, `foo @ https://x/y;z.whl ; python_version > "3"`) + assert.Equal(t, "https://x/y;z.whl", req.URL) + require.NotNil(t, req.Marker) + cmp, ok := req.Marker.(*CompareExpr) + require.True(t, ok) + assert.Equal(t, EnvVar{Name: "python_version"}, cmp.Lhs) + assert.Equal(t, Literal{Value: "3"}, cmp.Rhs) +} + +func TestParseRequirement_URLContainingSemicolon_NoMarker(t *testing.T) { + req := parseRequirementString(t, `foo @ https://x/y;z.whl`) + assert.Equal(t, "https://x/y;z.whl", req.URL) + assert.Nil(t, req.Marker) +} + +// --- grammar asymmetry: url form requires wsp+ before ";" marker --- + +func TestParseRequirement_URLForm_NoSpaceBeforeMarker_SwallowsIntoURL(t *testing.T) { + // Without the mandatory whitespace, url_req has no way to tell "URL + // ends here, marker begins" - so the whole remainder, semicolon + // included, is just part of the (greedy, non-whitespace) URL token. + // This is not an error: it is PEP 508's documented behavior. + req := parseRequirementString(t, `foo@https://x/y;python_version>"3"`) + assert.Equal(t, `https://x/y;python_version>"3"`, req.URL) + assert.Nil(t, req.Marker) +} + +func TestParseRequirement_URLForm_SpaceBeforeMarker_Splits(t *testing.T) { + req := parseRequirementString(t, `foo@https://x/y ;python_version>"3"`) + assert.Equal(t, "https://x/y", req.URL) + require.NotNil(t, req.Marker) +} + +// --- combinations --- + +func TestParseRequirement_ExtrasAndVersionSpecAndMarker(t *testing.T) { + req := parseRequirementString(t, `foo[bar,baz]>=1.0,<2.0; python_version >= "3.8"`) + assert.Equal(t, "foo", req.Name) + assert.Equal(t, []string{"bar", "baz"}, req.Extras) + assert.Equal(t, ">=1.0,<2.0", req.Specifier) + require.NotNil(t, req.Marker) +} + +// --- malformed inputs are syntax errors --- + +func TestParseRequirement_Empty_IsSyntaxError(t *testing.T) { + tok := NewTokenizer("") + _, err := ParseRequirement(tok) + require.Error(t, err) +} + +func TestParseRequirement_MissingURLAfterAt_IsSyntaxError(t *testing.T) { + tok := NewTokenizer("foo @ ") + _, err := ParseRequirement(tok) + require.Error(t, err) + var synErr *SyntaxError + require.ErrorAs(t, err, &synErr) +} + +func TestParseRequirement_TrailingGarbage_IsSyntaxError(t *testing.T) { + tok := NewTokenizer("foo bar") + _, err := ParseRequirement(tok) + require.Error(t, err) +} + +func TestParseRequirement_MarkerSyntaxError_Propagates(t *testing.T) { + tok := NewTokenizer(`foo; and`) + _, err := ParseRequirement(tok) + require.Error(t, err) + var synErr *SyntaxError + require.ErrorAs(t, err, &synErr) +} + +func TestParseRequirement_UnknownMarkerVariable_IsSyntaxError(t *testing.T) { + tok := NewTokenizer(`foo; not_a_real_variable == "1"`) + _, err := ParseRequirement(tok) + require.Error(t, err) +} + +// --- ParseRequirement does not leave a dangling token cached on success --- + +func TestParseRequirement_ConsumesEnd(t *testing.T) { + tok := NewTokenizer("foo") + _, err := ParseRequirement(tok) + require.NoError(t, err) + // A subsequent check must not panic on "already have pending token" - + // proving ParseRequirement itself consumed (not merely peeked) END. + assert.NotPanics(t, func() { tok.check(End) }) +} + +// --- IDENTIFIER \b boundary caveat (tokenizer.go's tokenRules doc) --- +// +// tokenizer.go documents that a LEADING \b in a rule matched via \A against +// source[pos:] always succeeds at the slice start, regardless of the real +// character preceding pos in the unsliced source - so a rule reached right +// after a word-character token (with no true boundary) could wrongly +// report a match. Identifier has a leading \b, so this must be checked. +// +// In the requirement grammar as implemented here, every position where +// Identifier is checked is reached only after: start-of-input, "[", ",", +// whitespace, or (transitively) another delimiter - never directly after a +// word-character-ending token with nothing between. This directly exercises +// that: a name (word-char-ending) immediately followed, with zero +// separator, by a non-Identifier token (LBracket, OP-shaped Specifier, +// Semicolon, AT) - i.e. exactly "a word-char token immediately followed by +// another token with no separator" - and confirms each parses as the +// grammar intends, never as a spuriously split/merged Identifier. +func TestIdentifier_NeverCheckedAfterWordCharWithNoBoundary(t *testing.T) { + cases := []struct { + name string + source string + }{ + {"name immediately followed by extras", "foo[bar]"}, + {"name immediately followed by versionspec", "foo>=1.0"}, + {"name immediately followed by url-spec", "foo@https://x"}, + {"name immediately followed by marker", "foo;python_version>=\"3.8\""}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + tok := NewTokenizer(c.source) + require.True(t, tok.check(Identifier), "source %q", c.source) + nameTok := tok.read() + // The Identifier match must stop exactly at "foo" - the first + // character outside Identifier's char class - and must not + // spuriously consume (or refuse to consume) based on what + // immediately follows. + assert.Equal(t, "foo", nameTok.Text, "source %q", c.source) + }) + } +} + +// A second, lower-level demonstration: Identifier's own greedy char class +// (which includes digits, ".", "_", "-") means two runs of allowed +// characters with nothing but allowed characters between them are simply +// ONE token, by construction - there is no way to "immediately follow" an +// Identifier match with another Identifier check at a false boundary, since +// the first check would have already consumed everything up to the true +// next delimiter. +func TestIdentifier_GreedyMatchConsumesWholeRunNoFalseSplit(t *testing.T) { + tok := NewTokenizer("foo123_bar-baz.qux") + require.True(t, tok.check(Identifier)) + got := tok.read() + assert.Equal(t, "foo123_bar-baz.qux", got.Text) +} diff --git a/internal/pep508/tokenizer.go b/internal/pep508/tokenizer.go index bca8f21..84a1eb0 100644 --- a/internal/pep508/tokenizer.go +++ b/internal/pep508/tokenizer.go @@ -10,11 +10,13 @@ import ( // Kind identifies a lexical token kind recognized by the Tokenizer. // -// This is the marker-grammar subset of pypa/packaging's DEFAULT_RULES keys -// (_tokenizer.py): WS, LPAREN, RPAREN, OP, BOOLOP, IN, NOT, VARIABLE, -// QUOTED_STRING, END. Requirement-only kinds (IDENTIFIER, LBRACKET, -// RBRACKET, SPECIFIER, AT, URL) are added alongside the requirement parser -// that needs them. +// This is pypa/packaging's DEFAULT_RULES keys (_tokenizer.py): the +// marker-grammar subset (WS, LPAREN, RPAREN, OP, BOOLOP, IN, NOT, VARIABLE, +// QUOTED_STRING, END), plus the requirement-only kinds needed by the +// requirement parser (IDENTIFIER, LBRACKET, RBRACKET, COMMA, SEMICOLON, AT, +// SPECIFIER, URL). The requirement-only kinds coexist with the marker kinds +// without any ordering conflict, since matching is parser-driven (a given +// Kind is only ever attempted where the calling grammar expects it). type Kind int const ( @@ -44,6 +46,38 @@ const ( QuotedString // End matches only at the end of the source (zero-width). End + + // --- requirement-only kinds below: used by the requirement parser + // (internal/pep508/requirement.go), never by the marker parser. --- + + // Identifier matches a PEP 508 "identifier" production: a package name + // or extra name. Per packaging's IDENTIFIER rule, the ground truth for + // this grammar (PEP 508's prose and formal grammar disagree). + Identifier + // LBracket matches a literal "[", opening an extras list. + LBracket + // RBracket matches a literal "]", closing an extras list. + RBracket + // Comma matches a literal ",", separating extras or specifier clauses. + Comma + // Semicolon matches a literal ";", introducing a "; marker" clause. + Semicolon + // AT matches a literal "@", introducing a "@ url" clause. + AT + // Specifier matches one version-specifier clause: a PEP 440 + // comparison operator followed by a version-shaped token. The raw + // text is handed to version.NewSpecifiers for authoritative parsing + // and validation; the tokenizer's own version-shape match need only + // be permissive enough to bound the clause (up to the next + // whitespace, comma, semicolon, or closing paren). + Specifier + // URL matches a greedy run of non-whitespace characters following + // "@". It intentionally has no upper bound other than whitespace (not + // even ";"), since a URL requirement's URL can itself contain a + // semicolon (e.g. a direct-reference wheel URL with a query string); + // PEP 508 relies on mandatory whitespace, not "no semicolons in a + // URL", to separate a URL from a following marker clause. + URL ) // String renders a Kind by its packaging DEFAULT_RULES name, primarily for @@ -70,6 +104,22 @@ func (k Kind) String() string { return "QUOTED_STRING" case End: return "END" + case Identifier: + return "IDENTIFIER" + case LBracket: + return "LBRACKET" + case RBracket: + return "RBRACKET" + case Comma: + return "COMMA" + case Semicolon: + return "SEMICOLON" + case AT: + return "AT" + case Specifier: + return "SPECIFIER" + case URL: + return "URL" default: return fmt.Sprintf("Kind(%d)", int(k)) } @@ -104,15 +154,19 @@ func (t Token) Unquoted() string { // it starts at position 0 of the (position-sliced) source - see check. // // Rules are matched with \A against source[pos:], so a leading \b in a rule -// (BoolOp, IN, NOT, Variable) sees the start of that slice as a word -// boundary, regardless of what precedes source[pos] in the full source. -// This is safe today because every reachable pos follows either +// (BoolOp, IN, NOT, Variable, Identifier) sees the start of that slice as a +// word boundary, regardless of what precedes source[pos] in the full +// source. This is safe because every reachable pos follows either // start-of-input or a token ending in a non-word character (WS, LParen, -// OP, QuotedString, ...), so the synthetic boundary at the slice start -// always agrees with the true boundary in the unsliced source. A future -// rule added without a trailing word-boundary of its own (e.g. an -// IDENTIFIER kind for the requirement parser) could be reached right -// after a word-character token and would need this assumption checked. +// OP, QuotedString, LBracket, RBracket, Comma, Semicolon, AT, ...), so the +// synthetic boundary at the slice start always agrees with the true +// boundary in the unsliced source. Identifier (added for the requirement +// parser) was checked against this invariant when it was introduced: every +// grammar position that checks Identifier is reached only after such a +// delimiter, start-of-input, or whitespace - never directly after another +// word-character token with no separator - see +// TestIdentifier_NeverCheckedAfterWordCharWithNoBoundary in +// requirement_test.go. var tokenRules = map[Kind]*regexp.Regexp{ WS: regexp.MustCompile(`\A\s+`), LParen: regexp.MustCompile(`\A\(`), @@ -136,6 +190,25 @@ var tokenRules = map[Kind]*regexp.Regexp{ `)\b`), QuotedString: regexp.MustCompile(`\A(?:'[^']*'|"[^"]*")`), End: regexp.MustCompile(`\A$`), + + // --- requirement-only rules below (see the requirement-only Kind + // constants for what each matches and why). --- + + Identifier: regexp.MustCompile(`\A\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b`), + LBracket: regexp.MustCompile(`\A\[`), + RBracket: regexp.MustCompile(`\A\]`), + Comma: regexp.MustCompile(`\A,`), + Semicolon: regexp.MustCompile(`\A;`), + AT: regexp.MustCompile(`\A@`), + // Specifier: an OP (reusing the same longest-first alternation as the + // OP rule) followed by optional whitespace and a version-shaped run + // of characters, bounded by whitespace/comma/semicolon/closing-paren + // rather than a precise PEP 440 grammar - version.NewSpecifiers is + // the authoritative parser for the accumulated raw text. + Specifier: regexp.MustCompile(`\A(?:===|==|~=|!=|<=|>=|<|>)\s*[^\s,;)]+`), + // URL: greedy non-whitespace, per packaging - deliberately not + // bounded by ";" (see the URL Kind doc comment). + URL: regexp.MustCompile(`\A[^ \t]+`), } // Tokenizer performs context-sensitive lexing over a PEP 508 source string. diff --git a/marker/marker.go b/marker/marker.go index 06fe5ac..23804bb 100644 --- a/marker/marker.go +++ b/marker/marker.go @@ -36,6 +36,20 @@ func Parse(s string) (Marker, error) { return Marker{ast: ast}, nil } +// FromExpr wraps an already-parsed internal marker expression into a +// Marker. It is the seam the requirement/ parser uses to build the Marker +// for a requirement's "; marker" clause without re-lexing: requirement/ +// drives the shared internal/pep508 tokenizer end-to-end itself (parsing +// the marker clause mid-stream via pep508.ParseMarker), so it already has a +// pep508.Expr in hand and has no need - and, since Marker.ast is +// unexported, no ability - to go through Parse's string-based entry point. +// +// A nil expr yields the zero-value "always true" Marker, matching what +// Parse returns for the absence of a "; marker" clause. +func FromExpr(e pep508.Expr) Marker { + return Marker{ast: e} +} + // IsEmpty reports whether m is the zero-value "always true" marker - i.e. // there is no marker clause to evaluate at all, as opposed to a parsed // marker expression that merely evaluates to true in some environment. diff --git a/requirement/doc.go b/requirement/doc.go index e467d2a..2c9714d 100644 --- a/requirement/doc.go +++ b/requirement/doc.go @@ -1,7 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 OR MIT -// Package requirement parses PEP 508 dependency-specifier strings (name, -// extras, version specifier, and environment marker). +// Package requirement parses PEP 508 dependency-specifier strings: a +// package name, optional bracketed extras, an optional version specifier +// or direct-reference URL, and an optional environment marker clause, e.g. +// `foo[extra]>=1.0,<2.0 ; python_version >= "3.8"`. // -// TODO(#18636): implement the PEP 508 requirement grammar. +// Parse drives the shared internal/pep508 tokenizer end-to-end in one pass +// (name, extras, versionspec-or-url, then the marker clause from the +// tokenizer's current position via internal/pep508's ParseMarker), then +// delegates the version specifier to version.NewSpecifiers, normalizes +// extras via extras.Normalize, and wraps the parsed marker expression via +// marker.FromExpr. package requirement diff --git a/requirement/requirement.go b/requirement/requirement.go new file mode 100644 index 0000000..c5e6b2f --- /dev/null +++ b/requirement/requirement.go @@ -0,0 +1,127 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package requirement + +import ( + "errors" + "fmt" + "strings" + + "github.com/posit-dev/go-python-packaging/extras" + "github.com/posit-dev/go-python-packaging/internal/pep508" + "github.com/posit-dev/go-python-packaging/marker" + "github.com/posit-dev/go-python-packaging/version" +) + +// ErrInvalidRequirement is the sentinel wrapped by every error Parse +// returns, regardless of which stage of parsing failed: malformed +// requirement syntax, an invalid version specifier, and an invalid marker +// expression are all distinct underlying causes, but all satisfy +// errors.Is(err, ErrInvalidRequirement). The specific cause remains +// distinguishable in the error chain: +// +// - malformed syntax (bad name/extras/versionspec/url grammar): the chain +// contains a *pep508.SyntaxError, but NOT a *pep508.MarkerClauseError. +// - invalid marker expression: the chain contains a +// *pep508.MarkerClauseError (itself wrapping a *pep508.SyntaxError from +// the marker grammar specifically). +// - invalid version specifier: the chain contains neither of the above - +// the error instead comes from version.NewSpecifiers. +var ErrInvalidRequirement = errors.New("invalid PEP 508 requirement") + +// Requirement is a parsed PEP 508 dependency-specifier requirement: +// +// name [extras] (versionspec | "@" url) [";" marker] +type Requirement struct { + // Name is the requirement's package name exactly as parsed - not + // canonicalized. Name canonicalization is a naming concern left to + // the caller (consistent with package wheelname's Name field). + Name string + // Extras are the requirement's bracketed extras, each normalized via + // extras.Normalize. Nil if there was no "[...]" clause or it was + // empty ("[]"). + Extras []string + // Specifiers is the requirement's version specifier, parsed via + // version.NewSpecifiers. It is the zero value if the requirement is + // a URL requirement, or has no version specifier at all. + Specifiers version.Specifiers + // URL is the requirement's direct-reference URL ("@ url" form). Empty + // unless that form was used. + URL string + // Marker is the requirement's "; marker" clause. It is the zero + // value (always-true) if there was no such clause. + Marker marker.Marker +} + +// Parse parses s as a PEP 508 dependency-specifier requirement string: +// +// name [extras] (versionspec | "@" url) [";" marker] +// +// Parsing drives the shared internal/pep508 tokenizer end-to-end in one +// pass (see pep508.ParseRequirement): the marker clause, if present, is +// parsed from the tokenizer's position immediately after the name/extras/ +// versionspec-or-url, not by splitting the string on ";" - which would +// mishandle a URL requirement whose URL itself contains a ";". +func Parse(s string) (Requirement, error) { + t := pep508.NewTokenizer(s) + raw, err := pep508.ParseRequirement(t) + if err != nil { + var markerErr *pep508.MarkerClauseError + if errors.As(err, &markerErr) { + return Requirement{}, fmt.Errorf("%w: invalid marker expression: %w", ErrInvalidRequirement, err) + } + return Requirement{}, fmt.Errorf("%w: %w", ErrInvalidRequirement, err) + } + + req := Requirement{ + Name: raw.Name, + URL: raw.URL, + } + + if len(raw.Extras) > 0 { + req.Extras = make([]string, len(raw.Extras)) + for i, e := range raw.Extras { + req.Extras[i] = extras.Normalize(e) + } + } + + if raw.Specifier != "" { + specs, err := version.NewSpecifiers(raw.Specifier) + if err != nil { + return Requirement{}, fmt.Errorf("%w: invalid version specifier %q: %w", ErrInvalidRequirement, raw.Specifier, err) + } + req.Specifiers = specs + } + + req.Marker = marker.FromExpr(raw.Marker) + + return req, nil +} + +// String renders r in canonical PEP 508 requirement syntax; +// Parse(r.String()) yields an equivalent Requirement. +func (r Requirement) String() string { + var b strings.Builder + b.WriteString(r.Name) + + if len(r.Extras) > 0 { + b.WriteString("[") + b.WriteString(strings.Join(r.Extras, ",")) + b.WriteString("]") + } + + switch { + case r.URL != "": + b.WriteString(" @ ") + b.WriteString(r.URL) + case r.Specifiers.String() != "": + b.WriteString(r.Specifiers.String()) + } + + if !r.Marker.IsEmpty() { + b.WriteString(" ; ") + b.WriteString(r.Marker.String()) + } + + return b.String() +} diff --git a/requirement/requirement_test.go b/requirement/requirement_test.go new file mode 100644 index 0000000..08496af --- /dev/null +++ b/requirement/requirement_test.go @@ -0,0 +1,228 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package requirement + +import ( + "errors" + "testing" + + "github.com/posit-dev/go-python-packaging/internal/pep508" + "github.com/posit-dev/go-python-packaging/version" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// --- plain name --- + +func TestParse_PlainName(t *testing.T) { + r, err := Parse("foo") + require.NoError(t, err) + assert.Equal(t, "foo", r.Name) + assert.Empty(t, r.Extras) + assert.Empty(t, r.URL) + assert.True(t, r.Marker.IsEmpty()) + assert.Empty(t, r.Specifiers.String()) +} + +// --- extras --- + +func TestParse_Extras_Multiple(t *testing.T) { + r, err := Parse("foo[bar,baz]") + require.NoError(t, err) + assert.Equal(t, []string{"bar", "baz"}, r.Extras) +} + +func TestParse_Extras_Empty(t *testing.T) { + r, err := Parse("foo[]") + require.NoError(t, err) + assert.Empty(t, r.Extras) +} + +func TestParse_Extras_WhitespaceInside(t *testing.T) { + r, err := Parse("foo[ bar , baz ]") + require.NoError(t, err) + assert.Equal(t, []string{"bar", "baz"}, r.Extras) +} + +func TestParse_Extras_Normalized(t *testing.T) { + r, err := Parse("foo[Foo_Bar]") + require.NoError(t, err) + assert.Equal(t, []string{"foo-bar"}, r.Extras) +} + +// --- version specifier --- + +func TestParse_VersionSpec_Bare(t *testing.T) { + r, err := Parse("foo>=1.0") + require.NoError(t, err) + want, err := version.NewSpecifiers(">=1.0") + require.NoError(t, err) + assert.Equal(t, want.String(), r.Specifiers.String()) +} + +func TestParse_VersionSpec_Parenthesized(t *testing.T) { + r, err := Parse("foo(>=1.0)") + require.NoError(t, err) + want, err := version.NewSpecifiers(">=1.0") + require.NoError(t, err) + assert.Equal(t, want.String(), r.Specifiers.String()) +} + +func TestParse_VersionSpec_MultipleClauses(t *testing.T) { + r, err := Parse("foo>=1.0,<2.0") + require.NoError(t, err) + v, err := (versionParse("1.5")) + require.NoError(t, err) + assert.True(t, r.Specifiers.Check(v)) + v2, err := versionParse("2.5") + require.NoError(t, err) + assert.False(t, r.Specifiers.Check(v2)) +} + +// versionParse is a tiny local helper wrapping version.Parse, to avoid +// importing it under a name that collides with this file's other uses of +// "version" as a package alias. +func versionParse(s string) (version.Version, error) { + return version.Parse(s) +} + +// --- grammar asymmetry: no space required before ";" after a name/versionspec --- + +func TestParse_NoSpaceBeforeMarker(t *testing.T) { + r, err := Parse(`foo>=1.0;python_version>="3.8"`) + require.NoError(t, err) + assert.False(t, r.Marker.IsEmpty()) + assert.Equal(t, `python_version >= "3.8"`, r.Marker.String()) +} + +// --- @ url form --- + +func TestParse_URL(t *testing.T) { + r, err := Parse("foo @ https://example.com/foo-1.0.whl") + require.NoError(t, err) + assert.Equal(t, "https://example.com/foo-1.0.whl", r.URL) + assert.Empty(t, r.Specifiers.String()) + assert.True(t, r.Marker.IsEmpty()) +} + +func TestParse_URL_WithMarker(t *testing.T) { + r, err := Parse(`foo @ https://example.com/foo-1.0.whl ; python_version > "3"`) + require.NoError(t, err) + assert.Equal(t, "https://example.com/foo-1.0.whl", r.URL) + assert.False(t, r.Marker.IsEmpty()) +} + +// --- URL containing ";" (key robustness case) --- + +func TestParse_URLContainingSemicolon(t *testing.T) { + r, err := Parse(`foo @ https://x/y;z.whl ; python_version > "3"`) + require.NoError(t, err) + assert.Equal(t, "https://x/y;z.whl", r.URL) + require.False(t, r.Marker.IsEmpty()) + assert.Equal(t, `python_version > "3"`, r.Marker.String()) +} + +// --- grammar asymmetry: URL form needs wsp+ (or end) before a marker --- + +func TestParse_URLForm_NoSpaceBeforeMarker_SwallowsIntoURL(t *testing.T) { + r, err := Parse(`foo@https://x/y;python_version>"3"`) + require.NoError(t, err) + assert.Equal(t, `https://x/y;python_version>"3"`, r.URL) + assert.True(t, r.Marker.IsEmpty()) +} + +// --- distinct error categories --- + +func TestParse_MalformedSyntax_IsErrInvalidRequirement(t *testing.T) { + _, err := Parse("foo[bar") + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirement)) + + var syntaxErr *pep508.SyntaxError + assert.True(t, errors.As(err, &syntaxErr), "expected a *pep508.SyntaxError in the chain") + var markerErr *pep508.MarkerClauseError + assert.False(t, errors.As(err, &markerErr), "malformed (non-marker) syntax must NOT be a MarkerClauseError") +} + +func TestParse_InvalidVersionSpecifier_IsErrInvalidRequirement(t *testing.T) { + _, err := Parse("foo~=1") + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirement)) + + var syntaxErr *pep508.SyntaxError + assert.False(t, errors.As(err, &syntaxErr), "a bad-version error must not be a pep508.SyntaxError") + var markerErr *pep508.MarkerClauseError + assert.False(t, errors.As(err, &markerErr)) +} + +func TestParse_InvalidMarker_IsErrInvalidRequirement(t *testing.T) { + _, err := Parse(`foo; not_a_real_variable == "1"`) + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirement)) + + var markerErr *pep508.MarkerClauseError + require.True(t, errors.As(err, &markerErr), "expected a *pep508.MarkerClauseError in the chain") + var syntaxErr *pep508.SyntaxError + assert.True(t, errors.As(err, &syntaxErr), "the marker error should still wrap a *pep508.SyntaxError") +} + +func TestParse_ThreeErrorCategoriesAreDistinguishable(t *testing.T) { + _, malformedErr := Parse("foo[bar") + _, versionErr := Parse("foo~=1") + _, markerErr := Parse(`foo; not_a_real_variable == "1"`) + + var mce *pep508.MarkerClauseError + assert.False(t, errors.As(malformedErr, &mce)) + assert.False(t, errors.As(versionErr, &mce)) + assert.True(t, errors.As(markerErr, &mce)) + + var se *pep508.SyntaxError + assert.True(t, errors.As(malformedErr, &se)) + assert.False(t, errors.As(versionErr, &se)) + assert.True(t, errors.As(markerErr, &se)) +} + +// --- round trip: Parse(r.String()) is stable --- + +func TestParse_RoundTrip(t *testing.T) { + sources := []string{ + "foo", + "foo[bar]", + "foo[bar,baz]", + "foo>=1.0", + "foo>=1.0,<2.0", + `foo>=1.0 ; python_version >= "3.8"`, + "foo @ https://example.com/foo-1.0.whl", + `foo @ https://example.com/foo-1.0.whl ; python_version > "3"`, + `foo @ https://x/y;z.whl ; python_version > "3"`, + "foo[Foo_Bar]>=1.0", + } + + for _, src := range sources { + t.Run(src, func(t *testing.T) { + r1, err := Parse(src) + require.NoError(t, err, "parsing %q", src) + s1 := r1.String() + + r2, err := Parse(s1) + require.NoError(t, err, "re-parsing serialized form %q", s1) + s2 := r2.String() + + assert.Equal(t, s1, s2, "serialization must be stable across a re-parse") + assert.Equal(t, r1.Name, r2.Name) + assert.Equal(t, r1.Extras, r2.Extras) + assert.Equal(t, r1.URL, r2.URL) + assert.Equal(t, r1.Specifiers.String(), r2.Specifiers.String()) + assert.Equal(t, r1.Marker.String(), r2.Marker.String()) + }) + } +} + +// --- Marker zero value is always-true --- + +func TestParse_NoMarker_IsAlwaysTrueZeroValue(t *testing.T) { + r, err := Parse("foo") + require.NoError(t, err) + assert.True(t, r.Marker.IsEmpty()) + assert.Equal(t, "", r.Marker.String()) +} From df92dffc956e2406382b62f0e693fed4967b5f41 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Thu, 9 Jul 2026 15:00:37 -0400 Subject: [PATCH 2/4] docs(requirement): attribution + package docs (#18636) Polish requirement/doc.go to describe the implemented Parse/Requirement API and ErrInvalidRequirement, add the missing NOTICE attribution for the requirement/ package's dependency-specifier grammar (pypa/packaging _parse_requirement + requirements.py, Apache-2.0; Astral uv's uv-pep508 crate, dual Apache-2.0/MIT), and mark the requirement/ row implemented in README.md. --- NOTICE | 7 +++++++ README.md | 2 +- requirement/doc.go | 15 +++++++++++---- 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/NOTICE b/NOTICE index fca75cb..3d64019 100644 --- a/NOTICE +++ b/NOTICE @@ -49,6 +49,13 @@ recursive-descent grammar of pypa/packaging marker productions (`_parse_marker` and friends) and `process_env_var`, licensed under the Apache License, Version 2.0. +The requirement/ package adapts the dependency-specifier grammar of +pypa/packaging (https://github.com/pypa/packaging), specifically +packaging/_parser.py's `_parse_requirement` and packaging/requirements.py's +`Requirement`, licensed under the Apache License, Version 2.0; and Astral +uv's (https://github.com/astral-sh/uv) `uv-pep508` crate, dual-licensed +under the Apache License, Version 2.0, or the MIT license. + The marker/ package's Environment platform mapping (os_name, sys_platform, platform_system, platform_release, platform_version) adapts the linux/macos/windows cases of Astral uv's platform-tag logic diff --git a/README.md b/README.md index b0f0733..d795ee0 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ Part of [RFD 0001 — Native Go PyPI Dependency Resolution](https://github.com/r | Package | Scope | |---|---| | [`version/`](https://github.com/rstudio/go-pep440-version) | PEP 440 versions and specifiers | -| `requirement/` | PEP 508 dependency specifiers | +| `requirement/` | PEP 508 dependency specifiers (implemented) | | `marker/` | PEP 508 environment markers (implemented) | | `extras/` | PEP 685 extra-name normalization (implemented) | | `reqtxt/` | pip `requirements.txt` format | diff --git a/requirement/doc.go b/requirement/doc.go index 2c9714d..430f0d3 100644 --- a/requirement/doc.go +++ b/requirement/doc.go @@ -7,8 +7,15 @@ // // Parse drives the shared internal/pep508 tokenizer end-to-end in one pass // (name, extras, versionspec-or-url, then the marker clause from the -// tokenizer's current position via internal/pep508's ParseMarker), then -// delegates the version specifier to version.NewSpecifiers, normalizes -// extras via extras.Normalize, and wraps the parsed marker expression via -// marker.FromExpr. +// tokenizer's current position via internal/pep508's ParseRequirement), +// then delegates the version specifier to version.NewSpecifiers, +// normalizes extras via extras.Normalize, and wraps the parsed marker +// expression via marker.FromExpr. Every parse failure - malformed syntax, +// an invalid version specifier, or an invalid marker expression - is +// wrapped in ErrInvalidRequirement, with the specific cause still +// distinguishable via errors.As/errors.Is. +// +// Requirement's fields (Name, Extras, Specifiers, URL, Marker) hold the +// parsed result, and Requirement.String renders it back to canonical PEP +// 508 syntax such that Parse(r.String()) yields an equivalent Requirement. package requirement From 2a55530dcf657f4486be622c6a25ef45ce806b8a Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Thu, 9 Jul 2026 15:08:13 -0400 Subject: [PATCH 3/4] chore(requirement): address whole-branch review minors (#18636) - Remove the misleading versionParse test helper (no alias collision exists); call sites now use version.Parse directly. - Add a comment on the URL tokenizer rule noting the deliberate space+tab divergence from upstream packaging's space-only rule. - Add a test asserting foo() (empty parenthesized specifier) is rejected as ErrInvalidRequirement. --- internal/pep508/tokenizer.go | 5 ++++- requirement/requirement_test.go | 17 ++++++++--------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/internal/pep508/tokenizer.go b/internal/pep508/tokenizer.go index 84a1eb0..387854f 100644 --- a/internal/pep508/tokenizer.go +++ b/internal/pep508/tokenizer.go @@ -207,7 +207,10 @@ var tokenRules = map[Kind]*regexp.Regexp{ // the authoritative parser for the accumulated raw text. Specifier: regexp.MustCompile(`\A(?:===|==|~=|!=|<=|>=|<|>)\s*[^\s,;)]+`), // URL: greedy non-whitespace, per packaging - deliberately not - // bounded by ";" (see the URL Kind doc comment). + // bounded by ";" (see the URL Kind doc comment). Upstream packaging's + // rule excludes only space ([^ ]+); this port also excludes tab, + // consistent with the WS rule above - a deliberate space+tab + // divergence from upstream, harmless for single-line Requires-Dist. URL: regexp.MustCompile(`\A[^ \t]+`), } diff --git a/requirement/requirement_test.go b/requirement/requirement_test.go index 08496af..c2aa474 100644 --- a/requirement/requirement_test.go +++ b/requirement/requirement_test.go @@ -68,24 +68,23 @@ func TestParse_VersionSpec_Parenthesized(t *testing.T) { assert.Equal(t, want.String(), r.Specifiers.String()) } +func TestParse_VersionSpec_EmptyParens_IsError(t *testing.T) { + _, err := Parse("foo()") + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirement)) +} + func TestParse_VersionSpec_MultipleClauses(t *testing.T) { r, err := Parse("foo>=1.0,<2.0") require.NoError(t, err) - v, err := (versionParse("1.5")) + v, err := version.Parse("1.5") require.NoError(t, err) assert.True(t, r.Specifiers.Check(v)) - v2, err := versionParse("2.5") + v2, err := version.Parse("2.5") require.NoError(t, err) assert.False(t, r.Specifiers.Check(v2)) } -// versionParse is a tiny local helper wrapping version.Parse, to avoid -// importing it under a name that collides with this file's other uses of -// "version" as a package alias. -func versionParse(s string) (version.Version, error) { - return version.Parse(s) -} - // --- grammar asymmetry: no space required before ";" after a name/versionspec --- func TestParse_NoSpaceBeforeMarker(t *testing.T) { From f7422c7efd500f9552724eb699aa325973d0410c Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Thu, 9 Jul 2026 15:11:25 -0400 Subject: [PATCH 4/4] fix(requirement): URL token terminates at all whitespace, not just space/tab (#18636) The URL rule (\A[^ \t]+) treated newline/CR as URL characters, so a defensively-multiline value like "name @ https://x/y\n; python_version > \"3\"" would absorb the marker clause into the URL token and lose it. Change the rule to \A\S+, the exact complement of the WS rule, so any whitespace terminates the URL - safe since a valid URL never contains whitespace. Add a regression test covering a newline between the URL and the marker clause; the existing URL-with-";" behavior is unaffected since ";" is not whitespace. --- internal/pep508/requirement_test.go | 16 ++++++++++++++++ internal/pep508/tokenizer.go | 16 ++++++++++------ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/internal/pep508/requirement_test.go b/internal/pep508/requirement_test.go index dd8c380..801f194 100644 --- a/internal/pep508/requirement_test.go +++ b/internal/pep508/requirement_test.go @@ -171,6 +171,22 @@ func TestParseRequirement_URLContainingSemicolon_NoMarker(t *testing.T) { assert.Nil(t, req.Marker) } +// --- URL terminates at any whitespace, not just space/tab --- + +func TestParseRequirement_URLThenNewlineThenMarker_Splits(t *testing.T) { + // A defensively-multiline value: the "@ url" clause ends in a newline + // rather than a space before "; marker". The URL rule must treat the + // newline as a terminator (it is the exact complement of the WS rule, + // \s+) so the marker clause is not absorbed into the URL token. + req := parseRequirementString(t, "foo @ https://x/y\n; python_version > \"3\"") + assert.Equal(t, "https://x/y", req.URL) + require.NotNil(t, req.Marker) + cmp, ok := req.Marker.(*CompareExpr) + require.True(t, ok) + assert.Equal(t, EnvVar{Name: "python_version"}, cmp.Lhs) + assert.Equal(t, Literal{Value: "3"}, cmp.Rhs) +} + // --- grammar asymmetry: url form requires wsp+ before ";" marker --- func TestParseRequirement_URLForm_NoSpaceBeforeMarker_SwallowsIntoURL(t *testing.T) { diff --git a/internal/pep508/tokenizer.go b/internal/pep508/tokenizer.go index 387854f..64c329a 100644 --- a/internal/pep508/tokenizer.go +++ b/internal/pep508/tokenizer.go @@ -206,12 +206,16 @@ var tokenRules = map[Kind]*regexp.Regexp{ // rather than a precise PEP 440 grammar - version.NewSpecifiers is // the authoritative parser for the accumulated raw text. Specifier: regexp.MustCompile(`\A(?:===|==|~=|!=|<=|>=|<|>)\s*[^\s,;)]+`), - // URL: greedy non-whitespace, per packaging - deliberately not - // bounded by ";" (see the URL Kind doc comment). Upstream packaging's - // rule excludes only space ([^ ]+); this port also excludes tab, - // consistent with the WS rule above - a deliberate space+tab - // divergence from upstream, harmless for single-line Requires-Dist. - URL: regexp.MustCompile(`\A[^ \t]+`), + // URL: a greedy run of non-whitespace characters - the exact + // complement of the WS rule above (\s+) - deliberately not bounded by + // ";" (see the URL Kind doc comment). Upstream packaging's rule + // excludes only space ([^ ]+); this port is stricter, treating all + // whitespace (including tab and newlines) as a terminator. That's + // safe because a valid URL never contains whitespace, and it avoids + // a stray newline (e.g. in a defensively-multiline Requires-Dist + // value) being absorbed into the URL along with a following "; marker" + // clause. + URL: regexp.MustCompile(`\A\S+`), } // Tokenizer performs context-sensitive lexing over a PEP 508 source string.