From 94e7cb5b9564b5155b05c0a33009da88d9bb9f17 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Thu, 9 Jul 2026 12:52:15 -0400 Subject: [PATCH 1/8] feat(pep508): shared PEP 508 tokenizer (#18637) --- NOTICE | 5 + internal/pep508/doc.go | 14 ++ internal/pep508/tokenizer.go | 267 ++++++++++++++++++++++++++ internal/pep508/tokenizer_test.go | 302 ++++++++++++++++++++++++++++++ 4 files changed, 588 insertions(+) create mode 100644 internal/pep508/doc.go create mode 100644 internal/pep508/tokenizer.go create mode 100644 internal/pep508/tokenizer_test.go diff --git a/NOTICE b/NOTICE index 198c4ab..cd3c39a 100644 --- a/NOTICE +++ b/NOTICE @@ -37,3 +37,8 @@ The extras/ package adapts PEP 685/503 name-canonicalization from pypa/packaging (https://github.com/pypa/packaging), specifically packaging/utils.py's `canonicalize_name`, licensed under the Apache License, Version 2.0. + +The internal/pep508 package's tokenizer adapts the lexer design of +pypa/packaging (https://github.com/pypa/packaging), specifically +packaging/_tokenizer.py's `Tokenizer`, `Token`, `ParserSyntaxError`, and +`DEFAULT_RULES`, licensed under the Apache License, Version 2.0. diff --git a/internal/pep508/doc.go b/internal/pep508/doc.go new file mode 100644 index 0000000..6f8fe09 --- /dev/null +++ b/internal/pep508/doc.go @@ -0,0 +1,14 @@ +// 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/). +// +// 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, +// expect, read, consume) rather than pre-scanning the whole input into a +// token slice. Callers ask for a specific token kind at the current +// position, which is what lets requirement-only kinds (added in a later +// package) coexist with marker kinds without any global "first rule wins" +// ordering to maintain. +package pep508 diff --git a/internal/pep508/tokenizer.go b/internal/pep508/tokenizer.go new file mode 100644 index 0000000..de31019 --- /dev/null +++ b/internal/pep508/tokenizer.go @@ -0,0 +1,267 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +package pep508 + +import ( + "fmt" + "regexp" + "strings" +) + +// 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. +type Kind int + +const ( + // WS matches one or more whitespace characters. + WS Kind = iota + // LParen matches a literal "(". + LParen + // RParen matches a literal ")". + RParen + // OP matches a PEP 440 comparison operator. Alternatives are ordered + // longest-first so e.g. "===" is not truncated to "==". + OP + // BoolOp matches the marker boolean keywords "and"/"or". + BoolOp + // IN matches the marker keyword "in". + IN + // NOT matches the marker keyword "not". + NOT + // Variable matches a PEP 508 environment-marker variable name, + // including the deprecated "python_implementation" alias for + // "platform_python_implementation". Folding the alias to its + // canonical name is the marker parser's job, not the tokenizer's. + Variable + // QuotedString matches a single- or double-quoted string literal. + // PEP 508 quoted strings have no escape syntax; a double-quoted + // string may embed unescaped single quotes and vice versa. + QuotedString + // End matches only at the end of the source (zero-width). + End +) + +// String renders a Kind by its packaging DEFAULT_RULES name, primarily for +// panic/error messages. +func (k Kind) String() string { + switch k { + case WS: + return "WS" + case LParen: + return "LPAREN" + case RParen: + return "RPAREN" + case OP: + return "OP" + case BoolOp: + return "BOOLOP" + case IN: + return "IN" + case NOT: + return "NOT" + case Variable: + return "VARIABLE" + case QuotedString: + return "QUOTED_STRING" + case End: + return "END" + default: + return fmt.Sprintf("Kind(%d)", int(k)) + } +} + +// Token is a single lexed token: its Kind, the exact matched source text, +// and the byte offset in the source where it begins. +// +// For QuotedString, Text retains the surrounding quote characters (matching +// packaging's Token.text, which is later sliced [1:-1] by the parser); use +// Unquoted for the string literal's value. +type Token struct { + Kind Kind + Text string + Pos int +} + +// Unquoted returns a QuotedString token's value with its surrounding quote +// characters stripped. No escape processing is performed, since PEP 508 +// quoted strings support none; this mirrors packaging's _parser.py, which +// takes token.text[1:-1] directly. +func (t Token) Unquoted() string { + if len(t.Text) < 2 { + return t.Text + } + return t.Text[1 : len(t.Text)-1] +} + +// tokenRules mirrors pypa/packaging's _tokenizer.py DEFAULT_RULES, restricted +// to the kinds needed by the marker grammar. Each pattern is compiled once, +// at package init, and wrapped in \A so a match is only ever accepted when +// 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 +// 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. +var tokenRules = map[Kind]*regexp.Regexp{ + WS: regexp.MustCompile(`\A\s+`), + LParen: regexp.MustCompile(`\A\(`), + RParen: regexp.MustCompile(`\A\)`), + OP: regexp.MustCompile(`\A(?:===|==|~=|!=|<=|>=|<|>)`), + BoolOp: regexp.MustCompile(`\A\b(?:and|or)\b`), + IN: regexp.MustCompile(`\A\bin\b`), + NOT: regexp.MustCompile(`\A\bnot\b`), + // Longest-alternative-first: python_full_version before python_version, + // and the platform_python_implementation forms before the bare + // python_implementation alias, so a longer name is never truncated to + // a shorter one that happens to prefix it. + Variable: regexp.MustCompile(`\A\b(?:` + + `python_full_version|python_version|` + + `os[._]name|sys[._]platform|` + + `platform_(?:release|system)|` + + `platform[._](?:version|machine|python_implementation)|` + + `python_implementation|` + + `implementation_(?:name|version)|` + + `extra` + + `)\b`), + QuotedString: regexp.MustCompile(`\A(?:'[^']*'|"[^"]*")`), + End: regexp.MustCompile(`\A$`), +} + +// Tokenizer performs context-sensitive lexing over a PEP 508 source string. +// It holds a single-token lookahead: callers ask whether the current +// position matches a given Kind (check), then read it, mirroring +// packaging's Tokenizer class. There is no whole-input pre-scan, since the +// set of valid token kinds at a given position is determined by the caller +// (the marker or requirement parser), not by a single global grammar. +type Tokenizer struct { + source string + pos int + next *Token +} + +// NewTokenizer returns a Tokenizer positioned at the start of source. +func NewTokenizer(source string) *Tokenizer { + return &Tokenizer{source: source} +} + +// check reports whether the rule for kind matches at the current position. +// On a successful non-peeking check, the matched token is cached and must +// be consumed via read before another check is made (panics otherwise, +// mirroring packaging's assert). +func (t *Tokenizer) check(kind Kind) bool { + return t.checkOrPeek(kind, false) +} + +// peek is like check, but never caches the match: the position is +// unaffected and the same (or a different) kind may be checked again +// immediately after. +func (t *Tokenizer) peek(kind Kind) bool { + return t.checkOrPeek(kind, true) +} + +func (t *Tokenizer) checkOrPeek(kind Kind, peek bool) bool { + if t.next != nil { + panic(fmt.Sprintf("pep508: cannot check %s, already have pending token %s %q", kind, t.next.Kind, t.next.Text)) + } + re, ok := tokenRules[kind] + if !ok { + panic(fmt.Sprintf("pep508: unknown token kind %s", kind)) + } + + // re is anchored with \A, so a non-nil match always starts at index 0 + // of source[pos:] - i.e., exactly at the current position. + loc := re.FindStringIndex(t.source[t.pos:]) + if loc == nil { + return false + } + if !peek { + t.next = &Token{Kind: kind, Text: t.source[t.pos : t.pos+loc[1]], Pos: t.pos} + } + return true +} + +// expect requires that kind matches at the current position, reading and +// returning the token if so. Otherwise, it returns a *SyntaxError whose +// message is "Expected " + expected, positioned at the current (unmoved) +// position. +func (t *Tokenizer) expect(kind Kind, expected string) (Token, error) { + if !t.check(kind) { + return Token{}, t.NewSyntaxError("Expected " + expected) + } + return t.read(), nil +} + +// read consumes and returns the token cached by the most recent successful +// (non-peeking) check, advancing the position past it. It panics if no +// token is pending, mirroring packaging's assert next_token is not None. +func (t *Tokenizer) read() Token { + if t.next == nil { + panic("pep508: read called with no pending token; check must succeed first") + } + tok := *t.next + t.pos += len(tok.Text) + t.next = nil + return tok +} + +// consume reads past kind if it matches at the current position, discarding +// the token; it is a no-op (returning false) otherwise. It is used to skip +// optional tokens such as WS. +func (t *Tokenizer) consume(kind Kind) bool { + if t.check(kind) { + t.read() + return true + } + return false +} + +// SyntaxError reports that the source could not be tokenized/parsed +// correctly at a given span. It mirrors packaging's ParserSyntaxError, +// including its message/source/marker-line rendering (a run of spaces, +// then tildes spanning [Start,End), then a caret), so error output points +// at the offending span the same way packaging's does. +type SyntaxError struct { + Msg string + Source string + Start int + End int +} + +func (e *SyntaxError) Error() string { + width := e.End - e.Start + if width < 0 { + width = 0 + } + marker := strings.Repeat(" ", max(e.Start, 0)) + strings.Repeat("~", width) + "^" + return e.Msg + "\n" + e.Source + "\n" + marker +} + +// NewSyntaxError builds a *SyntaxError for message at the tokenizer's +// current position (a zero-width span), mirroring a bare call to +// packaging's Tokenizer.raise_syntax_error(message). +// +// Exported (rather than kept alongside the unexported check/expect/read/ +// consume methods) so the marker and requirement parsers - which live in +// this package but are handed a *Tokenizer constructed by their public +// wrapper packages - have a stable, documented way to raise it. +func (t *Tokenizer) NewSyntaxError(message string) *SyntaxError { + return t.NewSyntaxErrorAt(message, t.pos, t.pos) +} + +// NewSyntaxErrorAt is like NewSyntaxError but with an explicit [start, end) +// span, mirroring packaging's Tokenizer.raise_syntax_error(message, +// span_start=..., span_end=...) - used e.g. to point at the opening "(" of +// an unclosed parenthesized expression rather than at the current position. +func (t *Tokenizer) NewSyntaxErrorAt(message string, start, end int) *SyntaxError { + return &SyntaxError{Msg: message, Source: t.source, Start: start, End: end} +} diff --git a/internal/pep508/tokenizer_test.go b/internal/pep508/tokenizer_test.go new file mode 100644 index 0000000..b4049fb --- /dev/null +++ b/internal/pep508/tokenizer_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" +) + +// --- OP: longest-match ordering --- + +func TestCheck_OP_LongestMatch(t *testing.T) { + cases := []struct { + source string + want string + }{ + {"===1.0", "==="}, + {"==1.0", "=="}, + {"~=1.0", "~="}, + {"!=1.0", "!="}, + {"<=1.0", "<="}, + {">=1.0", ">="}, + {"<1.0", "<"}, + {">1.0", ">"}, + } + for _, c := range cases { + tok := NewTokenizer(c.source) + ok := tok.check(OP) + require.True(t, ok, "source %q", c.source) + got := tok.read() + assert.Equal(t, OP, got.Kind) + assert.Equal(t, c.want, got.Text, "source %q", c.source) + assert.Equal(t, 0, got.Pos) + } +} + +func TestCheck_OP_NoMatch(t *testing.T) { + tok := NewTokenizer("banana") + assert.False(t, tok.check(OP)) +} + +// --- QUOTED_STRING --- + +func TestCheck_QuotedString_SingleQuoted(t *testing.T) { + tok := NewTokenizer(`'posix'`) + require.True(t, tok.check(QuotedString)) + got := tok.read() + assert.Equal(t, QuotedString, got.Kind) + assert.Equal(t, `'posix'`, got.Text) + assert.Equal(t, "posix", got.Unquoted()) +} + +func TestCheck_QuotedString_DoubleQuoted(t *testing.T) { + tok := NewTokenizer(`"posix"`) + require.True(t, tok.check(QuotedString)) + got := tok.read() + assert.Equal(t, `"posix"`, got.Text) + assert.Equal(t, "posix", got.Unquoted()) +} + +func TestCheck_QuotedString_EmbeddedOtherQuoteChar(t *testing.T) { + // A double-quoted string may embed single-quote characters, and + // vice versa, without any escaping. + tok := NewTokenizer(`"it's fine"`) + require.True(t, tok.check(QuotedString)) + got := tok.read() + assert.Equal(t, `"it's fine"`, got.Text) + assert.Equal(t, "it's fine", got.Unquoted()) + + tok2 := NewTokenizer(`'she said "hi"'`) + require.True(t, tok2.check(QuotedString)) + got2 := tok2.read() + assert.Equal(t, `'she said "hi"'`, got2.Text) + assert.Equal(t, `she said "hi"`, got2.Unquoted()) +} + +func TestCheck_QuotedString_Unterminated(t *testing.T) { + tok := NewTokenizer(`'posix`) + assert.False(t, tok.check(QuotedString)) +} + +// --- WS handling --- + +func TestConsume_WS_SkipsWhitespace(t *testing.T) { + tok := NewTokenizer(" and") + assert.True(t, tok.consume(WS)) + require.True(t, tok.check(BoolOp)) + got := tok.read() + assert.Equal(t, "and", got.Text) + assert.Equal(t, 3, got.Pos) +} + +func TestConsume_WS_NoOpWhenAbsent(t *testing.T) { + tok := NewTokenizer("and") + assert.False(t, tok.consume(WS)) + assert.True(t, tok.check(BoolOp)) +} + +// --- VARIABLE recognition --- + +func TestCheck_Variable_PythonImplementationAlias(t *testing.T) { + tok := NewTokenizer("python_implementation") + require.True(t, tok.check(Variable)) + got := tok.read() + assert.Equal(t, "python_implementation", got.Text) + assert.Equal(t, End, kindOfEnd(tok)) // sanity: nothing left but END +} + +func TestCheck_Variable_LongestNameFirst(t *testing.T) { + // python_full_version must tokenize whole, not split into + // "python_version"-shaped junk (it doesn't share that prefix, but + // the rule ordering must still be longest-alternative-first per + // the tokenizer's construction). + tok := NewTokenizer("python_full_version") + require.True(t, tok.check(Variable)) + got := tok.read() + assert.Equal(t, "python_full_version", got.Text) + + tok2 := NewTokenizer("python_version") + require.True(t, tok2.check(Variable)) + got2 := tok2.read() + assert.Equal(t, "python_version", got2.Text) +} + +func TestCheck_Variable_PlatformPythonImplementation(t *testing.T) { + tok := NewTokenizer("platform_python_implementation") + require.True(t, tok.check(Variable)) + got := tok.read() + assert.Equal(t, "platform_python_implementation", got.Text) +} + +func TestCheck_Variable_AllRecognizedNames(t *testing.T) { + names := []string{ + "os_name", "os.name", + "sys_platform", "sys.platform", + "platform_release", + "platform_system", + "platform_version", "platform.version", + "platform_machine", "platform.machine", + "implementation_name", + "implementation_version", + "extra", + } + for _, name := range names { + tok := NewTokenizer(name) + require.True(t, tok.check(Variable), "name %q", name) + got := tok.read() + assert.Equal(t, name, got.Text, "name %q", name) + } +} + +func TestCheck_Variable_RejectsUnknownName(t *testing.T) { + tok := NewTokenizer("not_a_real_variable") + assert.False(t, tok.check(Variable)) +} + +// --- BOOLOP / IN / NOT word-boundary --- + +func TestCheck_In_WordBoundary_RejectsInformation(t *testing.T) { + // "information" must not tokenize as IN ("in") followed by leftover + // "formation": the IN rule's trailing \b must reject the match + // entirely because 'n' is directly followed by a word character. + tok := NewTokenizer("information") + assert.False(t, tok.check(IN)) + // Nor is it a recognized VARIABLE. + assert.False(t, tok.check(Variable)) +} + +func TestCheck_In_MatchesStandalone(t *testing.T) { + tok := NewTokenizer("in 'foo'") + require.True(t, tok.check(IN)) + got := tok.read() + assert.Equal(t, "in", got.Text) +} + +func TestCheck_Not_WordBoundary_RejectsNotice(t *testing.T) { + tok := NewTokenizer("notice") + assert.False(t, tok.check(NOT)) +} + +func TestCheck_Not_MatchesStandalone(t *testing.T) { + tok := NewTokenizer("not in") + require.True(t, tok.check(NOT)) + got := tok.read() + assert.Equal(t, "not", got.Text) +} + +func TestCheck_BoolOp_WordBoundary(t *testing.T) { + // "android" must not be mistaken for "and" + "roid". + tok := NewTokenizer("android") + assert.False(t, tok.check(BoolOp)) + + tok2 := NewTokenizer("and or") + require.True(t, tok2.check(BoolOp)) + got := tok2.read() + assert.Equal(t, "and", got.Text) + tok2.consume(WS) + require.True(t, tok2.check(BoolOp)) + got2 := tok2.read() + assert.Equal(t, "or", got2.Text) +} + +// --- LPAREN / RPAREN / END --- + +func TestCheck_ParensAndEnd(t *testing.T) { + tok := NewTokenizer("()") + require.True(t, tok.check(LParen)) + assert.Equal(t, "(", tok.read().Text) + require.True(t, tok.check(RParen)) + assert.Equal(t, ")", tok.read().Text) + require.True(t, tok.check(End)) +} + +func TestCheck_End_FalseWhenSourceRemains(t *testing.T) { + tok := NewTokenizer("x") + assert.False(t, tok.check(End)) +} + +// --- expect() --- + +func TestExpect_ReadsMatchingToken(t *testing.T) { + tok := NewTokenizer("and") + got, err := tok.expect(BoolOp, "boolean operator") + require.NoError(t, err) + assert.Equal(t, "and", got.Text) +} + +func TestExpect_SyntaxErrorOnMismatch(t *testing.T) { + tok := NewTokenizer("banana") + _, err := tok.expect(BoolOp, "boolean operator") + require.Error(t, err) + var synErr *SyntaxError + require.ErrorAs(t, err, &synErr) + assert.Equal(t, "Expected boolean operator", synErr.Msg) + assert.Equal(t, "banana", synErr.Source) + assert.Equal(t, 0, synErr.Start) + assert.Equal(t, 0, synErr.End) +} + +// --- syntax error position/rendering --- + +func TestSyntaxError_PositionAfterConsumedTokens(t *testing.T) { + tok := NewTokenizer("and banana") + require.True(t, tok.check(BoolOp)) + tok.read() + tok.consume(WS) + _, err := tok.expect(NOT, "'not'") + require.Error(t, err) + var synErr *SyntaxError + require.ErrorAs(t, err, &synErr) + assert.Equal(t, 4, synErr.Start, "position should be after 'and '") + assert.Equal(t, 4, synErr.End) +} + +func TestSyntaxError_ErrorStringHasCaretAtPosition(t *testing.T) { + tok := NewTokenizer("banana") + _, err := tok.expect(BoolOp, "boolean operator") + require.Error(t, err) + want := "Expected boolean operator\nbanana\n^" + assert.Equal(t, want, err.Error()) +} + +func TestSyntaxError_SpanRendersTildes(t *testing.T) { + e := &SyntaxError{Msg: "Expected end of input", Source: "and banana", Start: 4, End: 10} + assert.Equal(t, "Expected end of input\nand banana\n ~~~~~~^", e.Error()) +} + +// --- read()/check() invariant panics --- + +func TestRead_PanicsWithoutPriorCheck(t *testing.T) { + tok := NewTokenizer("and") + assert.Panics(t, func() { tok.read() }) +} + +func TestCheck_PanicsIfTokenAlreadyPending(t *testing.T) { + tok := NewTokenizer("and") + require.True(t, tok.check(BoolOp)) + assert.Panics(t, func() { tok.check(BoolOp) }) +} + +// --- peek() lookahead without consuming --- + +func TestPeek_DoesNotCacheToken(t *testing.T) { + tok := NewTokenizer("and") + require.True(t, tok.peek(BoolOp)) + // A subsequent check (not peek) must still succeed - peek did not + // leave a pending token behind that would trip the "already have a + // pending token" invariant. + require.True(t, tok.check(BoolOp)) + got := tok.read() + assert.Equal(t, "and", got.Text) +} + +// kindOfEnd is a tiny test helper asserting the tokenizer is positioned +// at End after consuming the prior token. +func kindOfEnd(t *Tokenizer) Kind { + if !t.check(End) { + panic("expected End") + } + return End +} From 2a007b37649ed0a2e8aef69c6346e319a10daf09 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Thu, 9 Jul 2026 13:11:04 -0400 Subject: [PATCH 2/8] feat(marker): PEP 508 marker AST + parser (#18637) Port pypa/packaging's _parser.py marker grammar (_parse_marker, _parse_marker_atom/_item/_var/_op) as a recursive-descent parser over the shared pep508 tokenizer, producing a typed, exported AST (BoolExpr/CompareExpr/EnvVar/Literal) that a later evaluator can walk directly instead of re-deriving and/or precedence at evaluation time. Also adds the public marker.Marker wrapper (Parse/IsEmpty/String), whose zero value is the always-true "no marker clause" marker. --- internal/pep508/marker.go | 366 +++++++++++++++++++++++++++++++++ internal/pep508/marker_test.go | 223 ++++++++++++++++++++ marker/doc.go | 13 +- marker/marker.go | 53 +++++ marker/marker_test.go | 91 ++++++++ 5 files changed, 744 insertions(+), 2 deletions(-) create mode 100644 internal/pep508/marker.go create mode 100644 internal/pep508/marker_test.go create mode 100644 marker/marker.go create mode 100644 marker/marker_test.go diff --git a/internal/pep508/marker.go b/internal/pep508/marker.go new file mode 100644 index 0000000..1e10c4d --- /dev/null +++ b/internal/pep508/marker.go @@ -0,0 +1,366 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package pep508 + +import ( + "fmt" + "strings" + + "github.com/posit-dev/go-python-packaging/extras" +) + +// LogicalOp identifies the boolean keyword ("and" or "or") joining a +// BoolExpr's operands. (Named LogicalOp, not BoolOp, to avoid colliding with +// the tokenizer's BoolOp Kind constant.) +type LogicalOp string + +const ( + And LogicalOp = "and" + Or LogicalOp = "or" +) + +// Expr is a node in a parsed PEP 508 marker expression tree: either a +// *BoolExpr (an "and"/"or" of two or more sub-expressions) or a *CompareExpr +// (a single comparison). A parenthesized sub-expression in the source is +// captured structurally - "(...)" parses to the Expr it contains, with no +// distinct node type of its own - so String does not necessarily preserve +// redundant source parentheses, only the grouping they express. +// +// Exported (even though this package is "internal/pep508") so the evaluator +// in the public marker/ package (a later task) can type-switch over the +// tree; parsing has to happen here regardless, since building the tree +// requires the tokenizer's unexported check/expect/read/consume methods. +type Expr interface { + fmt.Stringer + markerExpr() +} + +// BoolExpr is a boolean "and"/"or" combination of two or more operands. +// "and" binds tighter than "or": parsing "a or b and c" yields +// BoolExpr{Or, [a, BoolExpr{And, [b, c]}]}, never the reverse grouping. +type BoolExpr struct { + Op LogicalOp + Operands []Expr +} + +func (*BoolExpr) markerExpr() {} + +// String renders e, parenthesizing an operand only where necessary to +// preserve precedence on a re-parse (see formatBoolOperand). +func (e *BoolExpr) String() string { + parts := make([]string, len(e.Operands)) + for i, operand := range e.Operands { + parts[i] = formatBoolOperand(e.Op, operand) + } + return strings.Join(parts, " "+string(e.Op)+" ") +} + +// formatBoolOperand renders operand as a component of a BoolExpr whose +// operator is parentOp. Parentheses are added only when omitting them would +// change the parsed meaning: an "or" nested inside an "and" must be +// parenthesized, since "and" binds tighter and a flat print would let it +// silently re-associate. Every other nesting - "and" inside "or" (the normal +// result of precedence grouping), or same-operator nesting produced by +// redundant source parentheses - prints flat, since both operators are +// associative and the grouping is unaffected either way. +func formatBoolOperand(parentOp LogicalOp, operand Expr) string { + if nested, ok := operand.(*BoolExpr); ok && parentOp == And && nested.Op == Or { + return "(" + nested.String() + ")" + } + return operand.String() +} + +// CompareOp is a marker comparison operator: one of the PEP 440 comparison +// operators (<=, <, !=, ==, >=, >, ~=, ===) or the marker-only "in"/"not in". +type CompareOp string + +// CompareExpr is a single marker comparison "lhs op rhs", e.g. +// `python_version >= "3.8"` or `extra == "foo"`. +type CompareExpr struct { + Lhs Operand + Op CompareOp + Rhs Operand +} + +func (*CompareExpr) markerExpr() {} + +func (e *CompareExpr) String() string { + return e.Lhs.String() + " " + string(e.Op) + " " + e.Rhs.String() +} + +// Operand is one side of a CompareExpr: either an EnvVar (an environment +// marker variable reference) or a Literal (a quoted string). Distinct +// concrete types per side let the evaluator (package marker) type-switch to +// tell "variable" from "literal" without inspecting a discriminant field. +type Operand interface { + fmt.Stringer + markerOperand() +} + +// EnvVar is an environment-marker variable reference, e.g. python_version. +// (Named EnvVar, not Variable, to avoid colliding with the tokenizer's +// Variable Kind constant.) Deprecated/legacy spellings - the dotted aliases +// and the bare "python_implementation" alias - are folded to their +// canonical snake_case name by the parser (see foldEnvVarAlias), so Name is +// always canonical. +type EnvVar struct { + Name string +} + +func (EnvVar) markerOperand() {} + +func (v EnvVar) String() string { return v.Name } + +// Literal is a quoted string operand. Where one side of a comparison is the +// "extra" EnvVar, the parser normalizes the other side's Literal.Value via +// extras.Normalize once, here (see normalizeExtraLiteral), so Evaluate (the +// hot path, a later task) never has to re-normalize. +type Literal struct { + Value string +} + +func (Literal) markerOperand() {} + +func (l Literal) String() string { return quoteLiteral(l.Value) } + +// quoteLiteral renders a literal's value back into PEP 508 quoted-string +// syntax. PEP 508 quoted strings have no escape syntax, so a value +// containing a double quote is rendered single-quoted instead; a value +// containing both quote characters cannot be round-tripped (packaging has +// the same limitation, for the same reason). +func quoteLiteral(v string) string { + if strings.Contains(v, `"`) { + return "'" + v + "'" + } + return `"` + v + `"` +} + +// envVarAliases maps every deprecated/legacy Variable-token spelling the +// tokenizer recognizes to its canonical PEP 508 name, mirroring packaging's +// process_env_var (_parser.py). Canonical spellings are absent from the map +// and fold to themselves. +var envVarAliases = map[string]string{ + "python_implementation": "platform_python_implementation", + "os.name": "os_name", + "sys.platform": "sys_platform", + "platform.version": "platform_version", + "platform.machine": "platform_machine", + "platform.python_implementation": "platform_python_implementation", +} + +func foldEnvVarAlias(name string) string { + if canon, ok := envVarAliases[name]; ok { + return canon + } + return name +} + +// ParseMarker parses a PEP 508 marker expression from t's current position +// and returns as soon as the marker grammar is exhausted. It does not +// consume or verify End: the caller decides what, if anything, must follow. +// +// This mirrors packaging's _parse_marker (_parser.py), which is reused - +// without an END check - both by parse_marker's END-checking wrapper and by +// _parse_requirement, which keeps parsing requirement grammar after the +// marker clause. Here, ParseFullMarker plays the role of parse_marker's +// wrapper (used by package marker's Parse); the requirement parser (a later +// package, in this same internal/pep508 package) calls ParseMarker +// directly, since more requirement grammar follows the marker clause there. +func ParseMarker(t *Tokenizer) (Expr, error) { + atoms, ops, err := parseMarkerSequence(t) + if err != nil { + return nil, err + } + return groupByPrecedence(atoms, ops), nil +} + +// ParseFullMarker parses a complete marker expression from t and verifies +// nothing but end-of-input follows, mirroring packaging's parse_marker +// (_parser.py), which wraps _parse_marker with a +// tokenizer.expect("END", ...) check. +func ParseFullMarker(t *Tokenizer) (Expr, error) { + expr, err := ParseMarker(t) + if err != nil { + return nil, err + } + if _, err := t.expect(End, "end of marker expression"); err != nil { + return nil, err + } + return expr, nil +} + +// parseMarkerSequence parses packaging's _parse_marker: one marker atom, +// then zero or more (LogicalOp, atom) pairs. It returns the flat list of +// atoms and the operator between each consecutive pair, deferring +// and/or-precedence grouping to groupByPrecedence. +func parseMarkerSequence(t *Tokenizer) ([]Expr, []LogicalOp, error) { + first, err := parseMarkerAtom(t) + if err != nil { + return nil, nil, err + } + atoms := []Expr{first} + var ops []LogicalOp + for t.check(BoolOp) { + op := LogicalOp(t.read().Text) + atom, err := parseMarkerAtom(t) + if err != nil { + return nil, nil, err + } + ops = append(ops, op) + atoms = append(atoms, atom) + } + return atoms, ops, nil +} + +// groupByPrecedence assembles the flat (atom, op, atom, ...) sequence +// produced by parseMarkerSequence into a tree where "and" binds tighter than +// "or": consecutive atoms joined by "and" are grouped into a single BoolExpr, +// and those groups are then combined - if there is more than one - into a +// top-level "or" BoolExpr. +// +// This mirrors the grouping packaging's _evaluate_markers performs over its +// flat MarkerList at evaluation time (grouping "and"-joined runs and +// splitting into a new group at each "or"), except performed once here, at +// parse time, so the returned tree already reflects precedence and a later +// evaluator can walk it directly with no grouping logic of its own. +func groupByPrecedence(atoms []Expr, ops []LogicalOp) Expr { + var orGroups [][]Expr + current := []Expr{atoms[0]} + for i, op := range ops { + if op == Or { + orGroups = append(orGroups, current) + current = []Expr{atoms[i+1]} + } else { + current = append(current, atoms[i+1]) + } + } + orGroups = append(orGroups, current) + + orOperands := make([]Expr, len(orGroups)) + for i, group := range orGroups { + if len(group) == 1 { + orOperands[i] = group[0] + } else { + orOperands[i] = &BoolExpr{Op: And, Operands: group} + } + } + if len(orOperands) == 1 { + return orOperands[0] + } + return &BoolExpr{Op: Or, Operands: orOperands} +} + +// parseMarkerAtom parses packaging's _parse_marker_atom: an optional +// parenthesized sub-expression, or a single marker item (comparison), with +// optional surrounding whitespace. +func parseMarkerAtom(t *Tokenizer) (Expr, error) { + t.consume(WS) + var atom Expr + if t.check(LParen) { + t.read() + t.consume(WS) + inner, err := ParseMarker(t) + if err != nil { + return nil, err + } + t.consume(WS) + if _, err := t.expect(RParen, "')'"); err != nil { + return nil, err + } + atom = inner + } else { + item, err := parseMarkerItem(t) + if err != nil { + return nil, err + } + atom = item + } + t.consume(WS) + return atom, nil +} + +// parseMarkerItem parses packaging's _parse_marker_item: marker_var OP +// marker_var. It also applies the once-at-parse-time "extra" literal +// normalization (see normalizeExtraLiteral), since both operands are +// available here. +func parseMarkerItem(t *Tokenizer) (*CompareExpr, error) { + t.consume(WS) + lhs, err := parseMarkerVar(t) + if err != nil { + return nil, err + } + t.consume(WS) + op, err := parseMarkerOp(t) + if err != nil { + return nil, err + } + t.consume(WS) + rhs, err := parseMarkerVar(t) + if err != nil { + return nil, err + } + t.consume(WS) + lhs, rhs = normalizeExtraLiteral(lhs, rhs) + return &CompareExpr{Lhs: lhs, Op: op, Rhs: rhs}, nil +} + +// parseMarkerVar parses packaging's _parse_marker_var: either an EnvVar +// (folding deprecated aliases to their canonical name) or a Literal (a +// quoted string's unquoted value). +func parseMarkerVar(t *Tokenizer) (Operand, error) { + if t.check(Variable) { + name := t.read().Text + return EnvVar{Name: foldEnvVarAlias(name)}, nil + } + if t.check(QuotedString) { + return Literal{Value: t.read().Unquoted()}, nil + } + return nil, t.NewSyntaxError("Expected a marker variable or quoted string") +} + +// parseMarkerOp parses packaging's _parse_marker_op: a PEP 440 comparison +// OP, or "in"/"not in". +func parseMarkerOp(t *Tokenizer) (CompareOp, error) { + if t.check(IN) { + t.read() + return "in", nil + } + if t.check(NOT) { + t.read() + if _, err := t.expect(WS, "whitespace after 'not'"); err != nil { + return "", err + } + if _, err := t.expect(IN, "'in' after 'not'"); err != nil { + return "", err + } + return "not in", nil + } + if t.check(OP) { + return CompareOp(t.read().Text), nil + } + return "", t.NewSyntaxError("Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in") +} + +// normalizeExtraLiteral normalizes the Literal side of a comparison against +// the "extra" EnvVar via extras.Normalize, once, at parse time - handling +// both operand orders ("extra == 'X'" and "'X' == extra") - so evaluation +// (package marker's Evaluate, a later task) never has to re-normalize on its +// hot path. +func normalizeExtraLiteral(lhs, rhs Operand) (Operand, Operand) { + if isExtraVar(lhs) { + if lit, ok := rhs.(Literal); ok { + rhs = Literal{Value: extras.Normalize(lit.Value)} + } + } + if isExtraVar(rhs) { + if lit, ok := lhs.(Literal); ok { + lhs = Literal{Value: extras.Normalize(lit.Value)} + } + } + return lhs, rhs +} + +func isExtraVar(o Operand) bool { + v, ok := o.(EnvVar) + return ok && v.Name == "extra" +} diff --git a/internal/pep508/marker_test.go b/internal/pep508/marker_test.go new file mode 100644 index 0000000..65f805a --- /dev/null +++ b/internal/pep508/marker_test.go @@ -0,0 +1,223 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +package pep508 + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// parseFullMarkerString is a small test helper: parse s as a complete marker +// (mirroring what package marker's Parse does) and fail the test immediately +// on error, since most AST-shape assertions below don't want to repeat the +// success-path boilerplate. +func parseFullMarkerString(t *testing.T, s string) Expr { + t.Helper() + tok := NewTokenizer(s) + expr, err := ParseFullMarker(tok) + require.NoError(t, err) + return expr +} + +// --- basic comparison --- + +func TestParseMarker_SimpleComparison(t *testing.T) { + expr := parseFullMarkerString(t, `python_version >= "3.8"`) + cmp, ok := expr.(*CompareExpr) + require.True(t, ok, "expected *CompareExpr, got %T", expr) + assert.Equal(t, EnvVar{Name: "python_version"}, cmp.Lhs) + assert.Equal(t, CompareOp(">="), cmp.Op) + assert.Equal(t, Literal{Value: "3.8"}, cmp.Rhs) +} + +func TestParseMarker_QuotedStringLiteralOnLhs(t *testing.T) { + expr := parseFullMarkerString(t, `"3.8" <= python_version`) + cmp, ok := expr.(*CompareExpr) + require.True(t, ok) + assert.Equal(t, Literal{Value: "3.8"}, cmp.Lhs) + assert.Equal(t, EnvVar{Name: "python_version"}, cmp.Rhs) +} + +func TestParseMarker_InOperator(t *testing.T) { + expr := parseFullMarkerString(t, `python_version in "2.7 3.5"`) + cmp, ok := expr.(*CompareExpr) + require.True(t, ok) + assert.Equal(t, CompareOp("in"), cmp.Op) +} + +func TestParseMarker_NotInOperator(t *testing.T) { + expr := parseFullMarkerString(t, `python_version not in "2.7 3.5"`) + cmp, ok := expr.(*CompareExpr) + require.True(t, ok) + assert.Equal(t, CompareOp("not in"), cmp.Op) +} + +// --- and/or precedence --- + +func TestParseMarker_AndBindsTighterThanOr(t *testing.T) { + // "a or b and c" must group as Or{a, And{b, c}}, not And{Or{a,b}, c}. + expr := parseFullMarkerString(t, `os_name == "posix" or sys_platform == "linux" and extra == "foo"`) + or, ok := expr.(*BoolExpr) + require.True(t, ok, "expected top-level *BoolExpr, got %T", expr) + require.Equal(t, Or, or.Op) + require.Len(t, or.Operands, 2) + + a, ok := or.Operands[0].(*CompareExpr) + require.True(t, ok, "operand 0 should be a bare comparison, got %T", or.Operands[0]) + assert.Equal(t, EnvVar{Name: "os_name"}, a.Lhs) + + and, ok := or.Operands[1].(*BoolExpr) + require.True(t, ok, "operand 1 should be a nested And, got %T", or.Operands[1]) + assert.Equal(t, And, and.Op) + require.Len(t, and.Operands, 2) +} + +func TestParseMarker_AndBindsTighterThanOr_OtherOrder(t *testing.T) { + // "a and b or c" must group as Or{And{a,b}, c}. + expr := parseFullMarkerString(t, `os_name == "posix" and sys_platform == "linux" or extra == "foo"`) + or, ok := expr.(*BoolExpr) + require.True(t, ok) + require.Equal(t, Or, or.Op) + require.Len(t, or.Operands, 2) + + and, ok := or.Operands[0].(*BoolExpr) + require.True(t, ok, "operand 0 should be a nested And, got %T", or.Operands[0]) + assert.Equal(t, And, and.Op) + + c, ok := or.Operands[1].(*CompareExpr) + require.True(t, ok, "operand 1 should be a bare comparison, got %T", or.Operands[1]) + assert.Equal(t, EnvVar{Name: "extra"}, c.Lhs) +} + +func TestParseMarker_ParenthesesOverridePrecedence(t *testing.T) { + // "(a or b) and c" must group as And{Or{a,b}, c} - the parens force an + // Or to nest inside an And, which precedence alone would never produce. + expr := parseFullMarkerString(t, `(os_name == "posix" or sys_platform == "linux") and extra == "foo"`) + and, ok := expr.(*BoolExpr) + require.True(t, ok, "expected top-level *BoolExpr, got %T", expr) + require.Equal(t, And, and.Op) + require.Len(t, and.Operands, 2) + + or, ok := and.Operands[0].(*BoolExpr) + require.True(t, ok, "operand 0 should be a nested Or, got %T", and.Operands[0]) + assert.Equal(t, Or, or.Op) +} + +func TestParseMarker_ChainedAndIsOneGroup(t *testing.T) { + expr := parseFullMarkerString(t, `os_name == "posix" and sys_platform == "linux" and extra == "foo"`) + and, ok := expr.(*BoolExpr) + require.True(t, ok) + assert.Equal(t, And, and.Op) + assert.Len(t, and.Operands, 3) +} + +// --- no comparison chaining --- + +func TestParseMarker_NoComparisonChaining_IsSyntaxError(t *testing.T) { + tok := NewTokenizer(`python_version < "3" < "4"`) + _, err := ParseFullMarker(tok) + require.Error(t, err) + var synErr *SyntaxError + require.ErrorAs(t, err, &synErr) +} + +func TestParseMarker_DanglingBoolOp_IsSyntaxError(t *testing.T) { + tok := NewTokenizer(`python_version >= "3.8" or`) + _, err := ParseFullMarker(tok) + require.Error(t, err) +} + +// --- unknown variable --- + +func TestParseMarker_UnknownVariable_IsSyntaxError(t *testing.T) { + tok := NewTokenizer(`foo == "1"`) + _, err := ParseFullMarker(tok) + require.Error(t, err) + var synErr *SyntaxError + require.ErrorAs(t, err, &synErr) +} + +// --- alias folding --- + +func TestParseMarker_AliasFolding(t *testing.T) { + cases := []struct { + source string + want string + }{ + {"python_implementation", "platform_python_implementation"}, + {"platform_python_implementation", "platform_python_implementation"}, + {"os.name", "os_name"}, + {"os_name", "os_name"}, + {"sys.platform", "sys_platform"}, + {"sys_platform", "sys_platform"}, + {"platform.version", "platform_version"}, + {"platform_version", "platform_version"}, + {"platform.machine", "platform_machine"}, + {"platform_machine", "platform_machine"}, + {"platform.python_implementation", "platform_python_implementation"}, + } + for _, c := range cases { + expr := parseFullMarkerString(t, c.source+` == "x"`) + cmp, ok := expr.(*CompareExpr) + require.True(t, ok, "source %q", c.source) + assert.Equal(t, EnvVar{Name: c.want}, cmp.Lhs, "source %q", c.source) + } +} + +// --- extra literal normalization --- + +func TestParseMarker_ExtraNormalization_VariableOnLhs(t *testing.T) { + expr := parseFullMarkerString(t, `extra == "Foo_Bar"`) + cmp, ok := expr.(*CompareExpr) + require.True(t, ok) + assert.Equal(t, Literal{Value: "foo-bar"}, cmp.Rhs) +} + +func TestParseMarker_ExtraNormalization_VariableOnRhs(t *testing.T) { + expr := parseFullMarkerString(t, `"Foo_Bar" == extra`) + cmp, ok := expr.(*CompareExpr) + require.True(t, ok) + assert.Equal(t, Literal{Value: "foo-bar"}, cmp.Lhs) +} + +func TestParseMarker_ExtraNormalization_NotAppliedToNonExtraComparisons(t *testing.T) { + expr := parseFullMarkerString(t, `os_name == "Foo_Bar"`) + cmp, ok := expr.(*CompareExpr) + require.True(t, ok) + assert.Equal(t, Literal{Value: "Foo_Bar"}, cmp.Rhs) +} + +// --- ParseMarker does not consume/verify END --- + +func TestParseMarker_DoesNotCheckEnd(t *testing.T) { + tok := NewTokenizer(`python_version >= "3.8" garbage`) + expr, err := ParseMarker(tok) + require.NoError(t, err, "ParseMarker must not itself verify END") + _, ok := expr.(*CompareExpr) + assert.True(t, ok) + // Confirm trailing input was left unconsumed for the caller to notice. + assert.False(t, tok.check(End)) +} + +// --- String() rendering --- + +func TestBoolExpr_String_ParenthesizesOrInsideAnd(t *testing.T) { + expr := parseFullMarkerString(t, `(os_name == "posix" or sys_platform == "linux") and extra == "foo"`) + assert.Equal(t, `(os_name == "posix" or sys_platform == "linux") and extra == "foo"`, expr.String()) +} + +func TestBoolExpr_String_NoParensNeededForAndInsideOr(t *testing.T) { + expr := parseFullMarkerString(t, `os_name == "posix" or sys_platform == "linux" and extra == "foo"`) + assert.Equal(t, `os_name == "posix" or sys_platform == "linux" and extra == "foo"`, expr.String()) +} + +func TestCompareExpr_String(t *testing.T) { + expr := parseFullMarkerString(t, `python_version >= "3.8"`) + assert.Equal(t, `python_version >= "3.8"`, expr.String()) +} + +func TestLiteral_String_UsesSingleQuoteWhenValueContainsDoubleQuote(t *testing.T) { + lit := Literal{Value: `has "quote"`} + assert.Equal(t, `'has "quote"'`, lit.String()) +} diff --git a/marker/doc.go b/marker/doc.go index 296347c..9fc846c 100644 --- a/marker/doc.go +++ b/marker/doc.go @@ -1,6 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 OR MIT -// Package marker represents and evaluates PEP 508 environment markers. +// Package marker represents PEP 508 environment markers - the optional +// `; ` suffix of a requirement string, e.g. +// `extra == "foo" and python_version >= "3.8"`. // -// TODO(#18637): implement the marker AST and evaluator. +// Marker is an opaque wrapper around the raw AST parsed by +// internal/pep508 (a Go port of pypa/packaging's _parser.py marker +// productions): Parse builds one from marker text, and its zero value +// represents "no marker clause" (always true), so callers never need to +// nil-check before working with a Marker. +// +// TODO(#18637): implement Evaluate and the environment it evaluates +// against. package marker diff --git a/marker/marker.go b/marker/marker.go new file mode 100644 index 0000000..06fe5ac --- /dev/null +++ b/marker/marker.go @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package marker + +import "github.com/posit-dev/go-python-packaging/internal/pep508" + +// Marker represents a parsed PEP 508 environment marker expression - the +// part of a requirement string following ";", e.g. +// `extra == "foo" and python_version >= "3.8"`. +// +// The zero value represents the absence of a marker clause (e.g. a +// requirement with no ";" section at all) and always evaluates as true, so +// callers never need to nil-check or special-case "no marker" before using +// a Marker. +type Marker struct { + // ast is the parsed expression tree, or nil for the zero-value + // "always true" marker. Left unexported: only this package and the + // evaluator that will live alongside it (a later task) need to walk + // it directly. + ast pep508.Expr +} + +// Parse parses s - the marker text with no leading ";" - as a complete PEP +// 508 marker expression. +// +// An empty or whitespace-only s is a syntax error, matching packaging's +// behavior for Marker(""): a marker expression always requires at least one +// comparison. To represent "no marker clause", use the zero-value Marker +// rather than calling Parse. +func Parse(s string) (Marker, error) { + t := pep508.NewTokenizer(s) + ast, err := pep508.ParseFullMarker(t) + if err != nil { + return Marker{}, err + } + return Marker{ast: ast}, nil +} + +// 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. +func (m Marker) IsEmpty() bool { + return m.ast == nil +} + +// String renders m in canonical PEP 508 marker syntax; Parse(m.String()) +// yields an equivalent marker. The zero-value marker renders as "". +func (m Marker) String() string { + if m.ast == nil { + return "" + } + return m.ast.String() +} diff --git a/marker/marker_test.go b/marker/marker_test.go new file mode 100644 index 0000000..0de7872 --- /dev/null +++ b/marker/marker_test.go @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package marker + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestParse_Simple(t *testing.T) { + m, err := Parse(`python_version >= "3.8"`) + require.NoError(t, err) + assert.False(t, m.IsEmpty()) + assert.Equal(t, `python_version >= "3.8"`, m.String()) +} + +func TestParse_Empty_IsSyntaxError(t *testing.T) { + _, err := Parse("") + assert.Error(t, err) +} + +func TestParse_WhitespaceOnly_IsSyntaxError(t *testing.T) { + _, err := Parse(" ") + assert.Error(t, err) +} + +func TestParse_TrailingGarbage_IsSyntaxError(t *testing.T) { + _, err := Parse(`python_version >= "3.8" or`) + assert.Error(t, err) +} + +func TestParse_NoComparisonChaining_IsSyntaxError(t *testing.T) { + _, err := Parse(`python_version < "3" < "4"`) + assert.Error(t, err) +} + +func TestParse_UnknownVariable_IsSyntaxError(t *testing.T) { + _, err := Parse(`unknown_var == "1"`) + assert.Error(t, err) +} + +func TestMarker_ZeroValue_IsAlwaysTrue(t *testing.T) { + var m Marker + assert.True(t, m.IsEmpty()) + assert.Equal(t, "", m.String()) +} + +func TestParse_PythonImplementationAlias_FoldsToCanonicalName(t *testing.T) { + m, err := Parse(`python_implementation == "CPython"`) + require.NoError(t, err) + assert.Equal(t, `platform_python_implementation == "CPython"`, m.String()) +} + +func TestParse_ExtraNormalization(t *testing.T) { + m, err := Parse(`extra == "Foo_Bar"`) + require.NoError(t, err) + assert.Equal(t, `extra == "foo-bar"`, m.String()) +} + +// --- round trip: Parse(m.String()) is stable --- + +func TestParse_RoundTrip(t *testing.T) { + markers := []string{ + `python_version >= "3.8"`, + `os_name == "posix" and sys_platform == "linux"`, + `os_name == "posix" or sys_platform == "linux"`, + `os_name == "posix" or sys_platform == "linux" and extra == "foo"`, + `os_name == "posix" and sys_platform == "linux" or extra == "foo"`, + `(os_name == "posix" or sys_platform == "linux") and extra == "foo"`, + `python_version in "2.7 3.5"`, + `python_version not in "2.7 3.5"`, + `extra == "Foo_Bar"`, + `python_implementation == "CPython"`, + } + + for _, src := range markers { + t.Run(src, func(t *testing.T) { + m1, err := Parse(src) + require.NoError(t, err) + s1 := m1.String() + + m2, err := Parse(s1) + require.NoError(t, err, "re-parsing serialized form %q", s1) + s2 := m2.String() + + assert.Equal(t, s1, s2, "serialization must be stable across a re-parse") + }) + } +} From 3446b2378684a2b859443381869520f2bc63f360 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Thu, 9 Jul 2026 13:22:17 -0400 Subject: [PATCH 3/8] feat(marker): Environment + EnvironmentFromTarget (#18637) Add the concrete-target marker environment (11 PEP 508 variables) and EnvironmentFromTarget, which fills platform fields from a tags.Target (linux/macos/windows, per uv's TargetTriple) and interpreter-identity fields from a caller-supplied InterpreterIdentity. Repairs a bare trailing "+" in python_full_version per packaging's _pep440_python_full_version so a later version.Parse does not fail. --- NOTICE | 7 ++ marker/environment.go | 159 +++++++++++++++++++++++++++++++++++++ marker/environment_test.go | 145 +++++++++++++++++++++++++++++++++ 3 files changed, 311 insertions(+) create mode 100644 marker/environment.go create mode 100644 marker/environment_test.go diff --git a/NOTICE b/NOTICE index cd3c39a..c48cf21 100644 --- a/NOTICE +++ b/NOTICE @@ -42,3 +42,10 @@ The internal/pep508 package's tokenizer adapts the lexer design of pypa/packaging (https://github.com/pypa/packaging), specifically packaging/_tokenizer.py's `Tokenizer`, `Token`, `ParserSyntaxError`, and `DEFAULT_RULES`, licensed under the Apache License, Version 2.0. + +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 +(https://github.com/astral-sh/uv), specifically the uv-configuration crate's +`TargetTriple`, dual-licensed under the Apache License, Version 2.0, or the +MIT license. diff --git a/marker/environment.go b/marker/environment.go new file mode 100644 index 0000000..654b329 --- /dev/null +++ b/marker/environment.go @@ -0,0 +1,159 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package marker + +import ( + "errors" + "fmt" + "strings" + + "github.com/posit-dev/go-python-packaging/tags" +) + +// ErrUnsupportedTarget is returned by EnvironmentFromTarget when the given +// tags.Target names an OS this package does not know how to map to PEP 508 +// marker variables. +var ErrUnsupportedTarget = errors.New("unsupported target for marker environment") + +// Environment holds the 11 PEP 508 marker variables for one concrete +// target. Field names correspond to PEP 508 variable names via snake_case +// (e.g. OsName -> os_name); the Evaluate method (a later task) maps between +// them. +type Environment struct { + OsName string // "posix", "nt" + SysPlatform string // "linux", "darwin", "win32" + PlatformMachine string // "x86_64", "aarch64", "arm64", "AMD64" (win), ... + PlatformPythonImplementation string // "CPython", "PyPy" + PlatformRelease string // "" when target-derived + PlatformSystem string // "Linux", "Darwin", "Windows" + PlatformVersion string // "" when target-derived + PythonVersion string // "3.11" (major.minor) + PythonFullVersion string // "3.11.4" + ImplementationName string // "cpython", "pypy" + ImplementationVersion string // "3.11.4" +} + +// InterpreterIdentity carries the marker fields a tags.Target cannot derive: +// the concrete interpreter identity and its full version. +// tags.Target.Implementation is only "cp"|"py" - a wheel-compatibility +// class, not a runtime interpreter identity - so the caller (which knows +// the real target interpreter) supplies these explicitly. +type InterpreterIdentity struct { + ImplementationName string // "cpython", "pypy" + PlatformPythonImplementation string // "CPython", "PyPy" + PythonFullVersion string // "3.11.4" (trailing-'+' repaired; see below) + ImplementationVersion string // "3.11.4" +} + +// EnvironmentFromTarget builds an Environment for t, filling the platform +// fields (OsName, SysPlatform, PlatformSystem, PlatformMachine, +// PlatformRelease, PlatformVersion) from t and the interpreter-identity +// fields from id. +// +// The platform mapping follows Astral uv's uv-configuration TargetTriple +// (os_name/sys_platform/platform_system/platform_release/platform_version): +// linux -> posix/linux/Linux; macos -> posix/darwin/Darwin; windows -> +// nt/win32/Windows; PlatformRelease and PlatformVersion are "" in all three +// cases, since they are target-derived rather than observed from a live +// process. An unsupported t.OS returns ErrUnsupportedTarget. +// +// PlatformMachine forwards t.Arch verbatim for linux/macos, where +// tags.Target's arch strings ("x86_64", "aarch64", "arm64", ...) already +// match real platform.machine() output. Windows is special-cased instead of +// blindly upper-cased: tags.Target's windows arches are "amd64"/"arm64"/ +// "x86", and real Windows platform.machine() values (sourced from the +// PROCESSOR_ARCHITECTURE environment variable) are "AMD64"/"ARM64"/"x86" - +// note "x86" is NOT upper-cased. This deliberately diverges from uv's own +// TargetTriple::platform_machine(), which reports "x86_64" (not "AMD64") +// for its windows/x86_64 triples; we favor fidelity to real-world PEP 508 +// markers actually written against platform_machine == 'AMD64' (as seen in +// uv's own MarkerEnvironment test fixtures) over matching uv's Rust-target- +// style naming. +// +// PythonFullVersion is repaired per packaging's +// _pep440_python_full_version/_repair_python_full_version: a bare trailing +// "+" (as reported by some patched/dirty CPython builds) is not a valid PEP +// 440 local version, so it becomes "+local" (e.g. "3.11.0+" -> +// "3.11.0+local") before being stored, so a later version.Parse of it does +// not fail. PythonVersion is then derived as the major.minor prefix of the +// repaired PythonFullVersion (e.g. "3.11.4" -> "3.11"); if that cannot be +// derived, EnvironmentFromTarget returns an error. +func EnvironmentFromTarget(t tags.Target, id InterpreterIdentity) (Environment, error) { + var env Environment + + switch t.OS { + case "linux": + env.OsName = "posix" + env.SysPlatform = "linux" + env.PlatformSystem = "Linux" + env.PlatformMachine = t.Arch + case "macos": + env.OsName = "posix" + env.SysPlatform = "darwin" + env.PlatformSystem = "Darwin" + env.PlatformMachine = t.Arch + case "windows": + env.OsName = "nt" + env.SysPlatform = "win32" + env.PlatformSystem = "Windows" + env.PlatformMachine = windowsPlatformMachine(t.Arch) + default: + return Environment{}, fmt.Errorf("%w: unsupported OS %q", ErrUnsupportedTarget, t.OS) + } + env.PlatformRelease = "" + env.PlatformVersion = "" + + env.PlatformPythonImplementation = id.PlatformPythonImplementation + env.ImplementationName = id.ImplementationName + env.ImplementationVersion = id.ImplementationVersion + env.PythonFullVersion = repairPythonFullVersion(id.PythonFullVersion) + + pythonVersion, err := majorMinor(env.PythonFullVersion) + if err != nil { + return Environment{}, err + } + env.PythonVersion = pythonVersion + + return env, nil +} + +// windowsPlatformMachine maps a tags.Target windows arch ("amd64", "arm64", +// "x86") to the value real Windows Python reports for platform.machine() +// ("AMD64", "ARM64", "x86" - note "x86" stays lower-case). Any other value +// is upper-cased as a best-effort fallback; tags.Target validates windows +// arches to this exact set (see tags.Target.Compile), so this path is not +// expected to be exercised. +func windowsPlatformMachine(arch string) string { + switch arch { + case "amd64": + return "AMD64" + case "arm64": + return "ARM64" + case "x86": + return "x86" + default: + return strings.ToUpper(arch) + } +} + +// repairPythonFullVersion applies packaging's +// _pep440_python_full_version repair: a python_full_version ending in a +// bare "+" is not a valid PEP 440 version (a local version segment requires +// content after "+"), so "local" is appended. +func repairPythonFullVersion(full string) string { + if strings.HasSuffix(full, "+") { + return full + "local" + } + return full +} + +// majorMinor extracts the "major.minor" prefix of a python_full_version +// string such as "3.11.4" -> "3.11". It returns an error if full does not +// have at least two dot-separated, non-empty components. +func majorMinor(full string) (string, error) { + parts := strings.SplitN(full, ".", 3) + if len(parts) < 2 || parts[0] == "" || parts[1] == "" { + return "", fmt.Errorf("marker: cannot derive python_version from python_full_version %q", full) + } + return parts[0] + "." + parts[1], nil +} diff --git a/marker/environment_test.go b/marker/environment_test.go new file mode 100644 index 0000000..78082d4 --- /dev/null +++ b/marker/environment_test.go @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package marker + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/posit-dev/go-python-packaging/tags" +) + +func testIdentity() InterpreterIdentity { + return InterpreterIdentity{ + ImplementationName: "cpython", + PlatformPythonImplementation: "CPython", + PythonFullVersion: "3.11.4", + ImplementationVersion: "3.11.4", + } +} + +func TestEnvironmentFromTarget_Linux(t *testing.T) { + target := tags.Target{OS: "linux", Arch: "x86_64"} + env, err := EnvironmentFromTarget(target, testIdentity()) + require.NoError(t, err) + + assert.Equal(t, "posix", env.OsName) + assert.Equal(t, "linux", env.SysPlatform) + assert.Equal(t, "Linux", env.PlatformSystem) + assert.Equal(t, "x86_64", env.PlatformMachine) + assert.Equal(t, "", env.PlatformRelease) + assert.Equal(t, "", env.PlatformVersion) +} + +func TestEnvironmentFromTarget_Linux_ArchAarch64Verbatim(t *testing.T) { + target := tags.Target{OS: "linux", Arch: "aarch64"} + env, err := EnvironmentFromTarget(target, testIdentity()) + require.NoError(t, err) + + assert.Equal(t, "aarch64", env.PlatformMachine) +} + +func TestEnvironmentFromTarget_Macos(t *testing.T) { + target := tags.Target{OS: "macos", Arch: "arm64"} + env, err := EnvironmentFromTarget(target, testIdentity()) + require.NoError(t, err) + + assert.Equal(t, "posix", env.OsName) + assert.Equal(t, "darwin", env.SysPlatform) + assert.Equal(t, "Darwin", env.PlatformSystem) + assert.Equal(t, "arm64", env.PlatformMachine) + assert.Equal(t, "", env.PlatformRelease) + assert.Equal(t, "", env.PlatformVersion) +} + +func TestEnvironmentFromTarget_Macos_ArchX86_64Verbatim(t *testing.T) { + target := tags.Target{OS: "macos", Arch: "x86_64"} + env, err := EnvironmentFromTarget(target, testIdentity()) + require.NoError(t, err) + + assert.Equal(t, "x86_64", env.PlatformMachine) +} + +func TestEnvironmentFromTarget_Windows(t *testing.T) { + target := tags.Target{OS: "windows", Arch: "amd64"} + env, err := EnvironmentFromTarget(target, testIdentity()) + require.NoError(t, err) + + assert.Equal(t, "nt", env.OsName) + assert.Equal(t, "win32", env.SysPlatform) + assert.Equal(t, "Windows", env.PlatformSystem) + assert.Equal(t, "AMD64", env.PlatformMachine) + assert.Equal(t, "", env.PlatformRelease) + assert.Equal(t, "", env.PlatformVersion) +} + +func TestEnvironmentFromTarget_Windows_PlatformMachineUppercased(t *testing.T) { + for _, tc := range []struct { + arch string + want string + }{ + {"amd64", "AMD64"}, + {"arm64", "ARM64"}, + {"x86", "x86"}, + } { + target := tags.Target{OS: "windows", Arch: tc.arch} + env, err := EnvironmentFromTarget(target, testIdentity()) + require.NoError(t, err) + assert.Equal(t, tc.want, env.PlatformMachine, "arch %q", tc.arch) + } +} + +func TestEnvironmentFromTarget_UnsupportedOS_Errors(t *testing.T) { + target := tags.Target{OS: "solaris", Arch: "x86_64"} + _, err := EnvironmentFromTarget(target, testIdentity()) + require.Error(t, err) + assert.ErrorIs(t, err, ErrUnsupportedTarget) +} + +func TestEnvironmentFromTarget_PythonVersionDerived(t *testing.T) { + target := tags.Target{OS: "linux", Arch: "x86_64"} + id := testIdentity() + id.PythonFullVersion = "3.11.4" + env, err := EnvironmentFromTarget(target, id) + require.NoError(t, err) + + assert.Equal(t, "3.11.4", env.PythonFullVersion) + assert.Equal(t, "3.11", env.PythonVersion) +} + +func TestEnvironmentFromTarget_TrailingPlusRepaired(t *testing.T) { + target := tags.Target{OS: "linux", Arch: "x86_64"} + id := testIdentity() + id.PythonFullVersion = "3.11.0+" + env, err := EnvironmentFromTarget(target, id) + require.NoError(t, err) + + assert.Equal(t, "3.11.0+local", env.PythonFullVersion) + assert.Equal(t, "3.11", env.PythonVersion) +} + +func TestEnvironmentFromTarget_MalformedPythonFullVersion_Errors(t *testing.T) { + target := tags.Target{OS: "linux", Arch: "x86_64"} + id := testIdentity() + id.PythonFullVersion = "3" + _, err := EnvironmentFromTarget(target, id) + require.Error(t, err) +} + +func TestEnvironmentFromTarget_InterpreterFieldsCopied(t *testing.T) { + target := tags.Target{OS: "linux", Arch: "x86_64"} + id := InterpreterIdentity{ + ImplementationName: "pypy", + PlatformPythonImplementation: "PyPy", + PythonFullVersion: "3.10.13", + ImplementationVersion: "7.3.16", + } + env, err := EnvironmentFromTarget(target, id) + require.NoError(t, err) + + assert.Equal(t, "pypy", env.ImplementationName) + assert.Equal(t, "PyPy", env.PlatformPythonImplementation) + assert.Equal(t, "7.3.16", env.ImplementationVersion) +} From cb9c96ec3dde96117d78755dd7d0fa010ab53d0f Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Thu, 9 Jul 2026 13:32:51 -0400 Subject: [PATCH 4/8] feat(marker): marker evaluation (#18637) Implement Marker.Evaluate with the unified per-comparison dispatch ported from packaging's _eval_op: extra set-membership, an attempted PEP 440 version comparison on the four version-typed variables (python_version, python_full_version, implementation_version, platform_release) that falls back to a generic string-operator table on any parse failure, and and/or tree evaluation. --- marker/evaluate.go | 234 +++++++++++++++++++++++++++++++++ marker/evaluate_test.go | 279 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 513 insertions(+) create mode 100644 marker/evaluate.go create mode 100644 marker/evaluate_test.go diff --git a/marker/evaluate.go b/marker/evaluate.go new file mode 100644 index 0000000..63f1830 --- /dev/null +++ b/marker/evaluate.go @@ -0,0 +1,234 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package marker + +import ( + "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/version" +) + +// versionTypedVars is the set of marker variables packaging attempts a PEP +// 440 version comparison against before falling back to string semantics +// (packaging's MARKERS_REQUIRING_VERSION). Note platform_version is NOT a +// member - only these four are - and this set differs from uv's (uv omits +// platform_release); we follow packaging, our correctness anchor. +var versionTypedVars = map[string]struct{}{ + "python_version": {}, + "python_full_version": {}, + "implementation_version": {}, + "platform_release": {}, +} + +// Evaluate reports whether the marker is satisfied in env, with the given +// set of active extras bound to the `extra` variable. Pass nil extras for a +// metadata-context evaluation with no active extras. +func (m Marker) Evaluate(env Environment, extraList []string) bool { + if m.ast == nil { + return true + } + active := normalizeExtraSet(extraList) + return evalExpr(m.ast, env, active) +} + +// normalizeExtraSet normalizes each active extra name (extras.Normalize) at +// evaluation time and returns it as a membership set. The literal side of an +// `extra` comparison is already normalized once at parse time (see +// internal/pep508's normalizeExtraLiteral); only the caller-supplied active +// list needs normalizing here, on Evaluate's hot path. +func normalizeExtraSet(extraList []string) map[string]struct{} { + set := make(map[string]struct{}, len(extraList)) + for _, e := range extraList { + set[extras.Normalize(e)] = struct{}{} + } + return set +} + +// evalExpr walks the marker AST: a *pep508.BoolExpr short-circuits its +// "and"/"or" operands, a *pep508.CompareExpr evaluates a single comparison. +func evalExpr(e pep508.Expr, env Environment, active map[string]struct{}) bool { + switch n := e.(type) { + case *pep508.BoolExpr: + return evalBool(n, env, active) + case *pep508.CompareExpr: + return evalCompare(n, env, active) + default: + // Unreachable: pep508.Expr has exactly these two implementations. + return false + } +} + +func evalBool(n *pep508.BoolExpr, env Environment, active map[string]struct{}) bool { + switch n.Op { + case pep508.And: + for _, operand := range n.Operands { + if !evalExpr(operand, env, active) { + return false + } + } + return true + case pep508.Or: + for _, operand := range n.Operands { + if evalExpr(operand, env, active) { + return true + } + } + return false + default: + return false + } +} + +// evalCompare implements the unified per-comparison dispatch ported from +// packaging's _eval_op: `extra` comparisons are set-membership (rule 3); +// otherwise a version comparison is attempted whenever either operand names +// one of the four version-typed variables (rule 1), falling back on any +// failure - or immediately, for any other variable - to a single generic +// string-operator table (rule 2). +func evalCompare(n *pep508.CompareExpr, env Environment, active map[string]struct{}) bool { + if isExtraVar(n.Lhs) { + return evalExtra(n.Op, n.Rhs, env, active) + } + if isExtraVar(n.Rhs) { + return evalExtra(n.Op, n.Lhs, env, active) + } + + lhsVal := resolveOperand(n.Lhs, env) + rhsVal := resolveOperand(n.Rhs, env) + + if isVersionTypedOperand(n.Lhs) || isVersionTypedOperand(n.Rhs) { + if result, ok := tryVersionCompare(n.Op, lhsVal, rhsVal); ok { + return result + } + } + return evalStringOp(n.Op, lhsVal, rhsVal) +} + +// evalExtra evaluates a comparison where one side is the `extra` variable +// and other is the opposite operand (the value side, whichever operand +// order the marker was written in). Only == and != are meaningful for +// set-membership against the active-extras set; any other operator is +// inapplicable and evaluates false. +func evalExtra(op pep508.CompareOp, other pep508.Operand, env Environment, active map[string]struct{}) bool { + lit := resolveOperand(other, env) + _, present := active[lit] + switch op { + case "==": + return present + case "!=": + return !present + default: + return false + } +} + +// isVersionTypedOperand reports whether operand is an EnvVar naming one of +// the four version-typed marker variables. +func isVersionTypedOperand(operand pep508.Operand) bool { + v, ok := operand.(pep508.EnvVar) + if !ok { + return false + } + _, isVersionTyped := versionTypedVars[v.Name] + return isVersionTyped +} + +func isExtraVar(operand pep508.Operand) bool { + v, ok := operand.(pep508.EnvVar) + return ok && v.Name == "extra" +} + +// resolveOperand resolves an operand (in source position, lhs or rhs) to its +// string value: a Literal's Value verbatim, or an EnvVar's value looked up +// in env. +func resolveOperand(operand pep508.Operand, env Environment) string { + switch v := operand.(type) { + case pep508.Literal: + return v.Value + case pep508.EnvVar: + return envVarValue(v.Name, env) + default: + return "" + } +} + +// envVarValue maps a canonical PEP 508 marker variable name to its value in +// env. `extra` is handled separately (evalExtra) and never reaches here; +// every other name is guaranteed valid by Parse (unknown variables are a +// parse-time syntax error), so the default case is unreachable in practice. +func envVarValue(name string, env Environment) string { + switch name { + case "os_name": + return env.OsName + case "sys_platform": + return env.SysPlatform + case "platform_machine": + return env.PlatformMachine + case "platform_python_implementation": + return env.PlatformPythonImplementation + case "platform_release": + return env.PlatformRelease + case "platform_system": + return env.PlatformSystem + case "platform_version": + return env.PlatformVersion + case "python_version": + return env.PythonVersion + case "python_full_version": + return env.PythonFullVersion + case "implementation_name": + return env.ImplementationName + case "implementation_version": + return env.ImplementationVersion + default: + return "" + } +} + +// tryVersionCompare attempts a PEP 440 version comparison of lhsVal op +// rhsVal: it builds a specifier from op+rhsVal and checks it against +// version.Parse(lhsVal). ok is false whenever either step fails to parse +// (e.g. op is "in"/"not in", or either side is not a valid PEP 440 version, +// including ""), signaling the caller to fall back to string semantics; the +// version.Parse/NewSpecifiers failure path never panics. +func tryVersionCompare(op pep508.CompareOp, lhsVal, rhsVal string) (result bool, ok bool) { + spec, err := version.NewSpecifiers(string(op) + rhsVal) + if err != nil { + return false, false + } + pv, err := version.Parse(lhsVal) + if err != nil { + return false, false + } + return spec.Check(pv), true +} + +// evalStringOp is the single generic operator table used whenever a version +// comparison was not attempted (neither operand names a version-typed +// variable) or was attempted and failed to parse. `~=` and `===` have no +// meaningful string semantics - packaging raises UndefinedComparison here; +// since Evaluate's signature is a fixed bool with no error channel, this is +// a deliberate, documented divergence: they evaluate false rather than +// erroring. See the task report for this judgment call. +func evalStringOp(op pep508.CompareOp, lhsVal, rhsVal string) bool { + switch op { + case "==": + return lhsVal == rhsVal + case "!=": + return lhsVal != rhsVal + case "in": + return strings.Contains(rhsVal, lhsVal) + case "not in": + return !strings.Contains(rhsVal, lhsVal) + case "<", ">": + return false + case "<=", ">=": + return lhsVal == rhsVal + case "~=", "===": + return false + default: + return false + } +} diff --git a/marker/evaluate_test.go b/marker/evaluate_test.go new file mode 100644 index 0000000..0f5e24d --- /dev/null +++ b/marker/evaluate_test.go @@ -0,0 +1,279 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package marker + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// baseEnv is a representative environment used across the truth table: +// CPython 3.8.5 on 64-bit Linux, mirroring a common packaging test fixture. +func baseEnv() Environment { + return Environment{ + OsName: "posix", + SysPlatform: "linux", + PlatformMachine: "x86_64", + PlatformPythonImplementation: "CPython", + PlatformRelease: "5.4.0-42-generic", + PlatformSystem: "Linux", + PlatformVersion: "#1 SMP", + PythonVersion: "3.8", + PythonFullVersion: "3.8.5", + ImplementationName: "cpython", + ImplementationVersion: "3.8.5", + } +} + +func evalStr(t *testing.T, expr string, env Environment, extras []string) bool { + t.Helper() + m, err := Parse(expr) + require.NoError(t, err, "parsing %q", expr) + return m.Evaluate(env, extras) +} + +func TestEvaluate_ZeroValueMarker_AlwaysTrue(t *testing.T) { + var m Marker + assert.True(t, m.Evaluate(baseEnv(), nil)) + assert.True(t, m.Evaluate(Environment{}, []string{"anything"})) +} + +// --- version-key comparisons delegating to version/ --- + +func TestEvaluate_VersionKeyComparisons(t *testing.T) { + tests := []struct { + name string + expr string + want bool + }{ + {"python_version >= true", `python_version >= "3.8"`, true}, + {"python_version >= false (higher required)", `python_version >= "3.9"`, false}, + {"python_version > false (equal)", `python_version > "3.8"`, false}, + {"python_version < true", `python_version < "3.9"`, true}, + {"python_full_version == true", `python_full_version == "3.8.5"`, true}, + {"python_full_version == false", `python_full_version == "3.8.6"`, false}, + {"reversed operand order, true", `"3.8" <= python_version`, true}, + {"reversed operand order, false", `"3.9" <= python_version`, false}, + {"implementation_version ==", `implementation_version == "3.8.5"`, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, evalStr(t, tt.expr, baseEnv(), nil)) + }) + } +} + +// --- the `python_version in "2.6 2.7 3.2"` substring idiom --- + +func TestEvaluate_VersionKey_InSubstringIdiom(t *testing.T) { + tests := []struct { + name string + expr string + want bool + }{ + {"in, present", `python_version in "2.6 2.7 3.2 3.8"`, true}, + {"in, absent", `python_version in "2.6 2.7 3.2"`, false}, + {"not in, present", `python_version not in "2.6 2.7 3.2 3.8"`, false}, + {"not in, absent", `python_version not in "2.6 2.7 3.2"`, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, evalStr(t, tt.expr, baseEnv(), nil)) + }) + } +} + +// --- string-op quirks on a non-version key --- + +func TestEvaluate_StringOpQuirks_NonVersionKey(t *testing.T) { + tests := []struct { + name string + expr string + want bool + }{ + {"< always false", `sys_platform < "zzzz"`, false}, + {"< always false (reverse would be true lexicographically)", `sys_platform < "aaaa"`, false}, + {"> always false", `sys_platform > "aaaa"`, false}, + {"> always false (equal case too)", `sys_platform > "linux"`, false}, + {"<= treated as ==, true", `sys_platform <= "linux"`, true}, + {"<= treated as ==, false", `sys_platform <= "darwin"`, false}, + {">= treated as ==, true", `sys_platform >= "linux"`, true}, + {">= treated as ==, false", `sys_platform >= "darwin"`, false}, + {"== true", `sys_platform == "linux"`, true}, + {"== false", `sys_platform == "darwin"`, false}, + {"!= true", `sys_platform != "darwin"`, true}, + {"!= false", `sys_platform != "linux"`, false}, + {"in substring true", `sys_platform in "the linux platform"`, true}, + {"in substring false", `sys_platform in "the darwin platform"`, false}, + {"not in substring true", `sys_platform not in "the darwin platform"`, true}, + {"not in substring false", `sys_platform not in "the linux platform"`, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, evalStr(t, tt.expr, baseEnv(), nil)) + }) + } +} + +// `~=`/`===` on a non-version string field: no bool-returning entry in +// the fallback string-operator table (packaging raises here; our fixed bool +// signature can't propagate an error, so we return false - a deliberate, +// documented divergence). See evaluate.go and the task report. +func TestEvaluate_TildeEqualAndArbitraryEqual_NonVersionKey_ReturnsFalse(t *testing.T) { + assert.False(t, evalStr(t, `sys_platform ~= "linux"`, baseEnv(), nil)) + assert.False(t, evalStr(t, `sys_platform === "linux"`, baseEnv(), nil)) +} + +// On a version-typed key, ~= and === are valid PEP 440 specifier operators +// and are handled by the version-comparison attempt (rule 1), not the +// string fallback table - so they behave normally there, not as "false". +func TestEvaluate_TildeEqualAndArbitraryEqual_VersionKey_DelegatesToVersion(t *testing.T) { + assert.True(t, evalStr(t, `python_version ~= "3.8"`, baseEnv(), nil)) + assert.False(t, evalStr(t, `python_version ~= "3.9"`, baseEnv(), nil)) + assert.True(t, evalStr(t, `python_full_version === "3.8.5"`, baseEnv(), nil)) + assert.False(t, evalStr(t, `python_full_version === "3.8.6"`, baseEnv(), nil)) +} + +// --- platform_release: version-typed with string fallback --- + +func TestEvaluate_PlatformRelease_VersionTypedWithStringFallback(t *testing.T) { + // A version-looking platform_release compares as a version. + env := baseEnv() + env.PlatformRelease = "5.4.0" + assert.True(t, evalStr(t, `platform_release >= "5.0.0"`, env, nil)) + assert.False(t, evalStr(t, `platform_release >= "6.0.0"`, env, nil)) + + // An empty platform_release (target-derived env) falls through to + // string ops rather than panicking: version.Parse("") errors. + env.PlatformRelease = "" + assert.NotPanics(t, func() { + evalStr(t, `platform_release == ""`, env, nil) + }) + assert.True(t, evalStr(t, `platform_release == ""`, env, nil)) + assert.False(t, evalStr(t, `platform_release == "5.4.0"`, env, nil)) + // >= falls back to string-equality semantics per rule 2 when the + // version attempt fails (empty string is never a valid PEP 440 version). + assert.False(t, evalStr(t, `platform_release >= "5.0.0"`, env, nil)) +} + +// --- extra set-membership --- + +func TestEvaluate_Extra_SetMembership(t *testing.T) { + tests := []struct { + name string + expr string + active []string + want bool + }{ + {"== present", `extra == "foo"`, []string{"foo"}, true}, + {"== absent", `extra == "foo"`, []string{"bar"}, false}, + {"== no active extras", `extra == "foo"`, nil, false}, + {"!= present (false)", `extra != "foo"`, []string{"foo"}, false}, + {"!= absent (true)", `extra != "foo"`, []string{"bar"}, true}, + {"reversed operand order", `"foo" == extra`, []string{"foo"}, true}, + // normalization: literal already normalized at parse time + // ("Foo_Bar" -> "foo-bar"); active extras normalized at eval time. + {"normalization, literal side", `extra == "Foo_Bar"`, []string{"foo-bar"}, true}, + {"normalization, active side", `extra == "foo-bar"`, []string{"Foo_Bar"}, true}, + {"normalization, both sides", `extra == "Foo.Bar"`, []string{"foo_bar"}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, evalStr(t, tt.expr, baseEnv(), tt.active)) + }) + } +} + +// The documented set-membership divergence from packaging: packaging's +// singular `extra` makes `extra == "a" and extra == "b"` unsatisfiable, +// but our active-extras-as-a-set model makes it true when both are active. +func TestEvaluate_Extra_ANDCombinedDistinctExtras_Divergence(t *testing.T) { + expr := `extra == "a" and extra == "b"` + assert.True(t, evalStr(t, expr, baseEnv(), []string{"a", "b"})) + assert.False(t, evalStr(t, expr, baseEnv(), []string{"a"})) + assert.False(t, evalStr(t, expr, baseEnv(), nil)) +} + +// --- empty-string LHS on a version key: no panic --- + +func TestEvaluate_EmptyStringLHS_OnVersionKey_NoPanic(t *testing.T) { + env := baseEnv() + env.PlatformRelease = "" + assert.NotPanics(t, func() { + evalStr(t, `platform_release != "5.4.0"`, env, nil) + }) + assert.True(t, evalStr(t, `platform_release != "5.4.0"`, env, nil)) +} + +// --- and/or tree evaluation and nesting --- + +func TestEvaluate_BoolTree(t *testing.T) { + tests := []struct { + name string + expr string + want bool + }{ + {"and, both true", `os_name == "posix" and sys_platform == "linux"`, true}, + {"and, one false", `os_name == "posix" and sys_platform == "darwin"`, false}, + {"or, one true", `os_name == "nt" or sys_platform == "linux"`, true}, + {"or, both false", `os_name == "nt" or sys_platform == "darwin"`, false}, + { + "and binds tighter than or, right group true", + `os_name == "nt" or sys_platform == "linux" and platform_system == "Linux"`, + true, + }, + { + "and binds tighter than or, right group false", + `os_name == "nt" or sys_platform == "linux" and platform_system == "Darwin"`, + false, + }, + { + "parens override precedence, true", + `(os_name == "nt" or sys_platform == "linux") and platform_system == "Linux"`, + true, + }, + { + "parens override precedence, false", + `(os_name == "nt" or sys_platform == "darwin") and platform_system == "Linux"`, + false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, evalStr(t, tt.expr, baseEnv(), nil)) + }) + } +} + +// --- env field mapping coverage (all 11 variables) --- + +func TestEvaluate_AllEnvVarsResolve(t *testing.T) { + env := baseEnv() + tests := []string{ + `os_name == "posix"`, + `sys_platform == "linux"`, + `platform_machine == "x86_64"`, + `platform_python_implementation == "CPython"`, + `platform_release == "5.4.0-42-generic"`, + `platform_system == "Linux"`, + `platform_version == "#1 SMP"`, + `python_version == "3.8"`, + `python_full_version == "3.8.5"`, + `implementation_name == "cpython"`, + `implementation_version == "3.8.5"`, + } + for _, expr := range tests { + t.Run(expr, func(t *testing.T) { + assert.True(t, evalStr(t, expr, env, nil)) + }) + } +} + +// python_implementation is a legacy alias for +// platform_python_implementation, folded at parse time - Evaluate never +// sees the alias name at all, but this pins the end-to-end behavior. +func TestEvaluate_PythonImplementationAlias(t *testing.T) { + assert.True(t, evalStr(t, `python_implementation == "CPython"`, baseEnv(), nil)) +} From 71c9cb810f1cd9f4744c75c117cef3e9101dfe66 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Thu, 9 Jul 2026 13:40:23 -0400 Subject: [PATCH 5/8] docs(marker): attribution + package docs (#18637) Polish marker/doc.go to describe the implemented API (Parse, Marker, Environment/InterpreterIdentity, EnvironmentFromTarget, Evaluate) and drop the stale TODO. Add the missing NOTICE attributions for pypa/packaging's marker grammar (packaging/_parser.py) and evaluation logic (packaging/markers.py's _eval_op), and mark marker/ implemented in the README package table. --- NOTICE | 11 +++++++++++ README.md | 2 +- marker/doc.go | 10 ++++++++-- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/NOTICE b/NOTICE index c48cf21..fca75cb 100644 --- a/NOTICE +++ b/NOTICE @@ -43,9 +43,20 @@ pypa/packaging (https://github.com/pypa/packaging), specifically packaging/_tokenizer.py's `Tokenizer`, `Token`, `ParserSyntaxError`, and `DEFAULT_RULES`, licensed under the Apache License, Version 2.0. +The internal/pep508 package's marker-expression parser adapts the +recursive-descent grammar of pypa/packaging +(https://github.com/pypa/packaging), specifically packaging/_parser.py's +marker productions (`_parse_marker` and friends) and `process_env_var`, +licensed under the Apache License, Version 2.0. + 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 (https://github.com/astral-sh/uv), specifically the uv-configuration crate's `TargetTriple`, dual-licensed under the Apache License, Version 2.0, or the MIT license. + +The marker/ package's Evaluate adapts the marker-evaluation logic of +pypa/packaging (https://github.com/pypa/packaging), specifically +packaging/markers.py's `_eval_op` and its operator/specifier dispatch, +licensed under the Apache License, Version 2.0. diff --git a/README.md b/README.md index f260e79..b0f0733 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Part of [RFD 0001 — Native Go PyPI Dependency Resolution](https://github.com/r |---|---| | [`version/`](https://github.com/rstudio/go-pep440-version) | PEP 440 versions and specifiers | | `requirement/` | PEP 508 dependency specifiers | -| `marker/` | PEP 508 environment markers | +| `marker/` | PEP 508 environment markers (implemented) | | `extras/` | PEP 685 extra-name normalization (implemented) | | `reqtxt/` | pip `requirements.txt` format | | [`distribution/`](https://github.com/rstudio/python-distribution-parser) | METADATA / wheel parsing | diff --git a/marker/doc.go b/marker/doc.go index 9fc846c..613beb7 100644 --- a/marker/doc.go +++ b/marker/doc.go @@ -10,6 +10,12 @@ // represents "no marker clause" (always true), so callers never need to // nil-check before working with a Marker. // -// TODO(#18637): implement Evaluate and the environment it evaluates -// against. +// Environment holds the 11 PEP 508 marker variables for one concrete +// target; EnvironmentFromTarget builds one from a tags.Target plus the +// InterpreterIdentity fields a Target alone cannot supply (the concrete +// interpreter's implementation name and version). Marker's Evaluate method +// then checks a parsed marker against a single concrete Environment and set +// of active extras, following packaging's _eval_op dispatch: version +// comparison for the four version-typed variables, set membership for +// `extra`, and a generic string-operator fallback otherwise. package marker From 090fe90def127ce936410408833f3bc25f858fd8 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Thu, 9 Jul 2026 14:25:54 -0400 Subject: [PATCH 6/8] chore(marker): address whole-branch review minors (#18637) --- internal/pep508/marker_test.go | 1 + internal/pep508/tokenizer.go | 1 + internal/pep508/tokenizer_test.go | 1 + marker/environment.go | 7 +++---- marker/evaluate_test.go | 5 +++++ 5 files changed, 11 insertions(+), 4 deletions(-) diff --git a/internal/pep508/marker_test.go b/internal/pep508/marker_test.go index 65f805a..18b0fa9 100644 --- a/internal/pep508/marker_test.go +++ b/internal/pep508/marker_test.go @@ -1,4 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 OR MIT + package pep508 import ( diff --git a/internal/pep508/tokenizer.go b/internal/pep508/tokenizer.go index de31019..bca8f21 100644 --- a/internal/pep508/tokenizer.go +++ b/internal/pep508/tokenizer.go @@ -1,4 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 OR MIT + package pep508 import ( diff --git a/internal/pep508/tokenizer_test.go b/internal/pep508/tokenizer_test.go index b4049fb..98190f8 100644 --- a/internal/pep508/tokenizer_test.go +++ b/internal/pep508/tokenizer_test.go @@ -1,4 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 OR MIT + package pep508 import ( diff --git a/marker/environment.go b/marker/environment.go index 654b329..99755ff 100644 --- a/marker/environment.go +++ b/marker/environment.go @@ -119,10 +119,9 @@ func EnvironmentFromTarget(t tags.Target, id InterpreterIdentity) (Environment, // windowsPlatformMachine maps a tags.Target windows arch ("amd64", "arm64", // "x86") to the value real Windows Python reports for platform.machine() -// ("AMD64", "ARM64", "x86" - note "x86" stays lower-case). Any other value -// is upper-cased as a best-effort fallback; tags.Target validates windows -// arches to this exact set (see tags.Target.Compile), so this path is not -// expected to be exercised. +// ("AMD64", "ARM64", "x86" - note "x86" stays lower-case). EnvironmentFromTarget +// expects callers to supply a validated Target, so the default case (a plain +// upper-case fallback) only matters for an out-of-band arch value. func windowsPlatformMachine(arch string) string { switch arch { case "amd64": diff --git a/marker/evaluate_test.go b/marker/evaluate_test.go index 0f5e24d..f9f03f2 100644 --- a/marker/evaluate_test.go +++ b/marker/evaluate_test.go @@ -178,6 +178,11 @@ func TestEvaluate_Extra_SetMembership(t *testing.T) { {"normalization, literal side", `extra == "Foo_Bar"`, []string{"foo-bar"}, true}, {"normalization, active side", `extra == "foo-bar"`, []string{"Foo_Bar"}, true}, {"normalization, both sides", `extra == "Foo.Bar"`, []string{"foo_bar"}, true}, + // Only == and != are meaningful for extra set-membership; any other + // operator is inapplicable and evaluates false, even when the extra + // named on the value side is active. + {"< present (inapplicable op)", `extra < "foo"`, []string{"foo"}, false}, + {"in present (inapplicable op)", `extra in "foo"`, []string{"foo"}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { From 3c5a903caa31dfb9f37b6c73d152b857260a60f9 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Thu, 9 Jul 2026 14:30:42 -0400 Subject: [PATCH 7/8] fix(marker): derive python_version from release prefix, not raw split (#18637) majorMinor previously derived python_version from python_full_version via a naive strings.SplitN(full, ".", 3), which breaks when the version has only two release segments followed by a local/pre/post/dev suffix. The common trigger is repairPythonFullVersion turning a bare trailing "+" into "+local" (e.g. "3.11+" -> "3.11+local"): majorMinor then returned "3.11+local" instead of "3.11", making python_version == "3.11" marker checks fail and selecting the wrong dependencies. majorMinor now validates full via version.Parse, then derives major.minor from the leading digit/"." run only (the PEP 440 release segment), discarding any local/pre/post/dev suffix before splitting on ".". --- marker/environment.go | 29 ++++++++++++++++++--- marker/environment_test.go | 53 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 3 deletions(-) diff --git a/marker/environment.go b/marker/environment.go index 99755ff..5451a8e 100644 --- a/marker/environment.go +++ b/marker/environment.go @@ -8,6 +8,7 @@ import ( "strings" "github.com/posit-dev/go-python-packaging/tags" + "github.com/posit-dev/go-python-packaging/version" ) // ErrUnsupportedTarget is returned by EnvironmentFromTarget when the given @@ -147,10 +148,32 @@ func repairPythonFullVersion(full string) string { } // majorMinor extracts the "major.minor" prefix of a python_full_version -// string such as "3.11.4" -> "3.11". It returns an error if full does not -// have at least two dot-separated, non-empty components. +// string such as "3.11.4" -> "3.11". The derivation is based only on the +// leading numeric release segment of full - any pre/post/dev/local suffix +// (e.g. the "+local" appended by repairPythonFullVersion for a bare +// trailing "+", or "rc1", ".post1", ".dev0") is discarded rather than +// naively split on ".", so "3.11+local" correctly yields "3.11" instead of +// the bogus "3.11+local". full is first validated as a real PEP 440 version +// via version.Parse; an error is returned for malformed input (e.g. "" or +// "abc") or if the release segment has fewer than two dot-separated, +// non-empty numeric components (e.g. "3" alone). func majorMinor(full string) (string, error) { - parts := strings.SplitN(full, ".", 3) + if _, err := version.Parse(full); err != nil { + return "", fmt.Errorf("marker: cannot derive python_version from python_full_version %q: %w", full, err) + } + + // Cut full at the first rune that is not part of the release segment + // (i.e. not a digit or "."), discarding any epoch marker ("!") and any + // pre/post/dev/local suffix. + end := strings.IndexFunc(full, func(r rune) bool { + return (r < '0' || r > '9') && r != '.' + }) + release := full + if end >= 0 { + release = full[:end] + } + + parts := strings.SplitN(release, ".", 3) if len(parts) < 2 || parts[0] == "" || parts[1] == "" { return "", fmt.Errorf("marker: cannot derive python_version from python_full_version %q", full) } diff --git a/marker/environment_test.go b/marker/environment_test.go index 78082d4..6e04b79 100644 --- a/marker/environment_test.go +++ b/marker/environment_test.go @@ -128,6 +128,59 @@ func TestEnvironmentFromTarget_MalformedPythonFullVersion_Errors(t *testing.T) { require.Error(t, err) } +// TestEnvironmentFromTarget_BareTrailingPlus_PythonVersionDerived is the +// RoboRev regression case: repairPythonFullVersion turns a bare trailing "+" +// into "+local" (e.g. "3.11+" -> "3.11+local"), and majorMinor must still +// derive "3.11" from that repaired value rather than returning the raw +// "3.11+local" (as a naive strings.SplitN(full, ".", 3) based derivation +// would). +func TestEnvironmentFromTarget_BareTrailingPlus_PythonVersionDerived(t *testing.T) { + target := tags.Target{OS: "linux", Arch: "x86_64"} + id := testIdentity() + id.PythonFullVersion = "3.11+" + env, err := EnvironmentFromTarget(target, id) + require.NoError(t, err) + + assert.Equal(t, "3.11+local", env.PythonFullVersion) + assert.Equal(t, "3.11", env.PythonVersion) +} + +func TestEnvironmentFromTarget_PythonVersion_DiscardsLocalSuffix(t *testing.T) { + target := tags.Target{OS: "linux", Arch: "x86_64"} + id := testIdentity() + id.PythonFullVersion = "3.11.0+local" + env, err := EnvironmentFromTarget(target, id) + require.NoError(t, err) + + assert.Equal(t, "3.11", env.PythonVersion) +} + +func TestEnvironmentFromTarget_PythonVersion_DiscardsPreReleaseSuffix(t *testing.T) { + target := tags.Target{OS: "linux", Arch: "x86_64"} + id := testIdentity() + id.PythonFullVersion = "3.11.0rc1" + env, err := EnvironmentFromTarget(target, id) + require.NoError(t, err) + + assert.Equal(t, "3.11", env.PythonVersion) +} + +func TestEnvironmentFromTarget_EmptyPythonFullVersion_Errors(t *testing.T) { + target := tags.Target{OS: "linux", Arch: "x86_64"} + id := testIdentity() + id.PythonFullVersion = "" + _, err := EnvironmentFromTarget(target, id) + require.Error(t, err) +} + +func TestEnvironmentFromTarget_NonNumericPythonFullVersion_Errors(t *testing.T) { + target := tags.Target{OS: "linux", Arch: "x86_64"} + id := testIdentity() + id.PythonFullVersion = "abc" + _, err := EnvironmentFromTarget(target, id) + require.Error(t, err) +} + func TestEnvironmentFromTarget_InterpreterFieldsCopied(t *testing.T) { target := tags.Target{OS: "linux", Arch: "x86_64"} id := InterpreterIdentity{ From 9228852972da74d824a838a835ad2dd2903e901e Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Thu, 9 Jul 2026 14:33:22 -0400 Subject: [PATCH 8/8] fix(marker): discard epoch/v prefix in python_version derivation (#18637) --- marker/environment.go | 17 +++++++++++------ marker/environment_test.go | 13 +++++++++++++ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/marker/environment.go b/marker/environment.go index 5451a8e..e1e9d8c 100644 --- a/marker/environment.go +++ b/marker/environment.go @@ -162,15 +162,20 @@ func majorMinor(full string) (string, error) { return "", fmt.Errorf("marker: cannot derive python_version from python_full_version %q: %w", full, err) } - // Cut full at the first rune that is not part of the release segment - // (i.e. not a digit or "."), discarding any epoch marker ("!") and any - // pre/post/dev/local suffix. - end := strings.IndexFunc(full, func(r rune) bool { + // Drop a leading "v"/"V" and any epoch prefix ("!"), both of which + // PEP 440 permits before the release segment, then cut at the first rune + // that is not part of the release segment (not a digit or "."), which + // discards any pre/post/dev/local suffix. + rest := strings.TrimLeft(full, "vV") + if bang := strings.IndexByte(rest, '!'); bang >= 0 { + rest = rest[bang+1:] + } + end := strings.IndexFunc(rest, func(r rune) bool { return (r < '0' || r > '9') && r != '.' }) - release := full + release := rest if end >= 0 { - release = full[:end] + release = rest[:end] } parts := strings.SplitN(release, ".", 3) diff --git a/marker/environment_test.go b/marker/environment_test.go index 6e04b79..222ee01 100644 --- a/marker/environment_test.go +++ b/marker/environment_test.go @@ -165,6 +165,19 @@ func TestEnvironmentFromTarget_PythonVersion_DiscardsPreReleaseSuffix(t *testing assert.Equal(t, "3.11", env.PythonVersion) } +// An epoch prefix ("!") is valid PEP 440 (though it never appears in a real +// interpreter's python_full_version); majorMinor discards it rather than +// erroring on the version it just validated. +func TestEnvironmentFromTarget_PythonVersion_DiscardsEpoch(t *testing.T) { + target := tags.Target{OS: "linux", Arch: "x86_64"} + id := testIdentity() + id.PythonFullVersion = "1!3.11.4" + env, err := EnvironmentFromTarget(target, id) + require.NoError(t, err) + + assert.Equal(t, "3.11", env.PythonVersion) +} + func TestEnvironmentFromTarget_EmptyPythonFullVersion_Errors(t *testing.T) { target := tags.Target{OS: "linux", Arch: "x86_64"} id := testIdentity()