"""PEP 508 Marker parsing and evaluation. Derived from pypa/packaging: packaging/markers.py, packaging/_parser.py and packaging/_tokenizer.py (Apache 2.0 / BSD). Baseline: pypa/packaging 26.3 (plus #1438 set-of-extras evaluation) """ load("//pypackaging/private/specifiers:specifiers.bzl", "specifier_contains", "specifier_matches_parsed", "try_parse_specifier") load("//pypackaging/private/utils:utils.bzl", "utils") load("//pypackaging/private/version:version.bzl", "strip_whitespace", "try_parse_version") visibility(["//", "//pypackaging/..."]) # --------------------------------------------------------------------------- # Tokenizer primitives (shared with requirements.bzl) # --------------------------------------------------------------------------- _WS = " \t" # Characters matched by Python's `\w` in the ASCII range. Any non-ASCII # character is treated as a word character, which approximates `\w` for the # letters and digits that can legitimately appear next to a token. _ASCII_WORD_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_" # Pre-allocated variable nodes. _VAR_NODES = { name: struct(type = "variable", value = name) for name in ( "dependency_groups", "extra", "extras", "implementation_name", "implementation_version", "os_name", "platform_machine", "platform_python_implementation", "platform_release", "platform_system", "platform_version", "python_full_version", "python_version", "sys_platform", ) } # The spellings of the variables, keyed by the first character. A match must # end at a word boundary, so a name cannot shadow a longer one and the # candidates are ordered by how common they are in the wild. _VARS_BY_CHAR = { "d": (("dependency_groups", _VAR_NODES["dependency_groups"]),), "e": ( ("extra", _VAR_NODES["extra"]), ("extras", _VAR_NODES["extras"]), ), "i": ( ("implementation_name", _VAR_NODES["implementation_name"]), ("implementation_version", _VAR_NODES["implementation_version"]), ), "o": ( ("os_name", _VAR_NODES["os_name"]), ("os.name", _VAR_NODES["os_name"]), ), "p": ( ("python_version", _VAR_NODES["python_version"]), ("python_full_version", _VAR_NODES["python_full_version"]), ("platform_machine", _VAR_NODES["platform_machine"]), ("platform_system", _VAR_NODES["platform_system"]), ("platform_python_implementation", _VAR_NODES["platform_python_implementation"]), ("platform_release", _VAR_NODES["platform_release"]), ("platform_version", _VAR_NODES["platform_version"]), ("platform.machine", _VAR_NODES["platform_machine"]), ("platform.version", _VAR_NODES["platform_version"]), ("platform.python_implementation", _VAR_NODES["platform_python_implementation"]), ("python_implementation", _VAR_NODES["platform_python_implementation"]), ), "s": ( ("sys_platform", _VAR_NODES["sys_platform"]), ("sys.platform", _VAR_NODES["sys_platform"]), ), } _TWO_CHAR_OPS = {"==": "==", "~=": "~=", "!=": "!=", "<=": "<=", ">=": ">="} _ONE_CHAR_OPS = {"<": "<", ">": ">"} def is_word_char(c): """Returns True if `c` counts as a regex word character (`\\w`). Any non-ASCII character is treated as a word character. Internal helper shared with requirements.bzl; not part of the public API. Args: c: A single character. Returns: True for ASCII letters, digits, "_" and any non-ASCII character. """ return c in _ASCII_WORD_CHARS or c >= "\200" def _is_boundary(src, n, pos): """Returns True if `pos` is a regex `\\b` word boundary in `src`.""" before = pos > 0 and is_word_char(src[pos - 1]) after = pos < n and is_word_char(src[pos]) return before != after def _match_word(src, n, pos, word): """Matches `\\bword\\b` at `pos`.""" return ( src.startswith(word, pos) and _is_boundary(src, n, pos) and _is_boundary(src, n, pos + len(word)) ) def skip_ws(src, pos, n = None): """Returns the position after any spaces or tabs starting at `pos`. Internal helper shared with requirements.bzl; not part of the public API. Args: src: The source string. pos: The start position. n: Optional precomputed `len(src)`. Returns: The position of the first non-whitespace character at or after `pos`. """ if n == None: n = len(src) if pos >= n: return pos c = src[pos] if c != " " and c != "\t": return pos pos += 1 if pos >= n: return pos c = src[pos] if c != " " and c != "\t": return pos for _ in range(n - pos): c = src[pos] if c == " " or c == "\t": pos += 1 else: break return pos def at_end(src, pos, n = None): """Returns True if the upstream END token (regex `\\Z`) matches at `pos`. Internal helper shared with requirements.bzl; not part of the public API. Args: src: The source string. pos: The position to check. n: Optional precomputed `len(src)`. Returns: True if at the end of the input. """ if n == None: n = len(src) return pos == n def syntax_error(ctx, message, span_start, span_end = None): """Fails with an upstream-style `ParserSyntaxError` message. Internal helper shared with requirements.bzl; not part of the public API. Args: ctx: A struct with `src` (the full source text) and `label` (the error prefix, e.g. "Invalid marker"). message: The error message. span_start: Start of the highlighted span. span_end: End of the highlighted span (the caret position); defaults to `span_start`. """ if span_end == None: span_end = span_start # Python counts code points; Bazel strings hold UTF-8 bytes. span_start = _code_point_len(ctx.src[:span_start]) span_end = _code_point_len(ctx.src[:span_end]) caret = " " * span_start + "~" * (span_end - span_start) + "^" fail("{}: {}\n {}\n {}".format(ctx.label, message, ctx.src, caret)) def _code_point_len(s): """Returns the number of code points in the UTF-8 string `s`.""" n = len(s) # buildifier: disable=string-iteration for c in s.elems(): if c >= "\200" and c < "\300": n -= 1 return n # --------------------------------------------------------------------------- # Python string literal decoding (upstream uses `ast.literal_eval`) # --------------------------------------------------------------------------- # One single-character string per byte value, used to build UTF-8 output. _BYTES = ( "\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" + "\040\041\042\043\044\045\046\047\050\051\052\053\054\055\056\057\060\061\062\063\064\065\066\067\070\071\072\073\074\075\076\077" + "\100\101\102\103\104\105\106\107\110\111\112\113\114\115\116\117\120\121\122\123\124\125\126\127\130\131\132\133\134\135\136\137" + "\140\141\142\143\144\145\146\147\150\151\152\153\154\155\156\157\160\161\162\163\164\165\166\167\170\171\172\173\174\175\176\177" + "\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237" + "\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277" + "\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337" + "\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377" ) _SIMPLE_ESCAPES = { "\n": "", "\"": "\"", "'": "'", "\\": "\\", "a": "\007", "b": "\010", "f": "\014", "n": "\n", "r": "\r", "t": "\t", "v": "\013", } _OCT_DIGITS = "01234567" _HEX_DIGITS = "0123456789abcdefABCDEF" _HEX_ESCAPE_LEN = {"U": 8, "u": 4, "x": 2} def _utf8(cp): if cp < 0x80: return _BYTES[cp] if cp < 0x800: return _BYTES[0xC0 | (cp >> 6)] + _BYTES[0x80 | (cp & 0x3F)] if cp < 0x10000: return ( _BYTES[0xE0 | (cp >> 12)] + _BYTES[0x80 | ((cp >> 6) & 0x3F)] + _BYTES[0x80 | (cp & 0x3F)] ) return ( _BYTES[0xF0 | (cp >> 18)] + _BYTES[0x80 | ((cp >> 12) & 0x3F)] + _BYTES[0x80 | ((cp >> 6) & 0x3F)] + _BYTES[0x80 | (cp & 0x3F)] ) def _decode_python_str(ctx, start, end): """Decodes the quoted string `src[start:end + 1]` like `ast.literal_eval`.""" body = ctx.src[start + 1:end] if "\\" not in body and "\n" not in body and "\r" not in body and "\000" not in body: return body out = [] n = len(body) i = 0 for _ in range(n): if i >= n: break c = body[i] if c == "\n" or c == "\r" or c == "\000": syntax_error(ctx, "Invalid string literal (unescaped newline or NUL character)", start, end + 1) if c != "\\": out.append(c) i += 1 continue if i + 1 >= n: syntax_error(ctx, "Invalid string literal (the closing quote is escaped)", start, end + 1) d = body[i + 1] if d in _SIMPLE_ESCAPES: out.append(_SIMPLE_ESCAPES[d]) i += 2 elif d == "\r": # Line continuation (\r or \r\n). i += 2 if i < n and body[i] == "\n": i += 1 elif d in _OCT_DIGITS: j = i + 1 for _ in range(3): if j < n and body[j] in _OCT_DIGITS: j += 1 else: break out.append(_utf8(int(body[i + 1:j], 8))) i = j elif d in _HEX_ESCAPE_LEN: count = _HEX_ESCAPE_LEN[d] digits = body[i + 2:i + 2 + count] if len(digits) != count or digits.lstrip(_HEX_DIGITS): syntax_error(ctx, "Invalid string literal (truncated \\{} escape)".format(d), start, end + 1) cp = int(digits, 16) if cp > 0x10FFFF: syntax_error(ctx, "Invalid string literal (illegal Unicode character)", start, end + 1) out.append(_utf8(cp)) i += 2 + count elif d == "N": syntax_error(ctx, "Invalid string literal (\\N{...} escapes are not supported)", start, end + 1) elif d == "\000": syntax_error(ctx, "Invalid string literal (NUL character)", start, end + 1) else: # Unknown escapes are kept verbatim, like Python. out.append("\\") i += 1 return "".join(out) # --------------------------------------------------------------------------- # Marker parser # --------------------------------------------------------------------------- def _string(value): return struct(type = "string", value = value) def _parse_marker_var(ctx, src, n, pos): """marker_var = VARIABLE | QUOTED_STRING""" if pos < n: c = src[pos] if c == "'" or c == "\"": end = src.find(c, pos + 1) if end != -1: return _string(_decode_python_str(ctx, pos, end)), end + 1 else: candidates = _VARS_BY_CHAR.get(c) if candidates != None and (pos == 0 or not is_word_char(src[pos - 1])): for raw, node in candidates: if src.startswith(raw, pos): end = pos + len(raw) if end == n or not is_word_char(src[end]): return node, end syntax_error(ctx, "Expected a marker variable or quoted string", pos) return None, pos # Unreachable def _parse_marker_op(ctx, src, n, pos): """marker_op = IN | NOT IN | OP""" if pos < n: c = src[pos] if c == "=" or c == "!" or c == "<" or c == ">" or c == "~": if c == "=" and src.startswith("===", pos): return "===", pos + 3 op = _TWO_CHAR_OPS.get(src[pos:pos + 2]) if op != None: return op, pos + 2 op = _ONE_CHAR_OPS.get(c) if op != None: return op, pos + 1 elif c == "i": if _match_word(src, n, pos, "in"): return "in", pos + 2 elif c == "n": if _match_word(src, n, pos, "not"): pos += 3 if pos >= n or src[pos] not in _WS: syntax_error(ctx, "Expected whitespace after 'not'", pos) pos = skip_ws(src, pos, n) if not _match_word(src, n, pos, "in"): syntax_error(ctx, "Expected 'in' after 'not'", pos) return "not in", pos + 2 syntax_error(ctx, "Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in", pos) return None, pos # Unreachable def _parse_marker_item(ctx, src, n, pos): """marker_item = WS? marker_var WS? marker_op WS? marker_var WS?""" lhs, pos = _parse_marker_var(ctx, src, n, pos) pos = skip_ws(src, pos, n) op, pos = _parse_marker_op(ctx, src, n, pos) pos = skip_ws(src, pos, n) rhs, pos = _parse_marker_var(ctx, src, n, pos) pos = skip_ws(src, pos, n) # PEP 685 / PEP 735: normalize values compared against `extra`, `extras`, # and `dependency_groups` at every nesting level (matching packaging 26.3). if lhs.type == "variable" and lhs.value == "extra": rhs = _string(utils.canonicalize_name(rhs.value)) elif rhs.type == "variable" and rhs.value == "extra": lhs = _string(utils.canonicalize_name(lhs.value)) elif rhs.type == "variable" and rhs.value in _MARKERS_ALLOWING_SET and lhs.type == "string": lhs = _string(utils.canonicalize_name(lhs.value)) return (lhs, op, rhs), pos def parse_marker_expression(ctx, pos): """Parses `marker = marker_atom (BOOLOP marker_atom)*` starting at `pos`. Iterative (no recursion), so arbitrarily deep nesting is supported. Internal helper shared with requirements.bzl; not part of the public API. Args: ctx: A struct with `src` and `label` (see `syntax_error`). pos: The start position. Returns: A tuple of (marker tree, position after the marker and any trailing whitespace). """ src = ctx.src n = len(src) stack = [] # (open paren position, parent expression) current = [] # Every iteration consumes at least one character ("(" or a marker item). for _ in range(n + 1): # marker_atom: WS? "(" WS? marker WS? ")" WS? | WS? marker_item WS? pos = skip_ws(src, pos, n) if pos < n and src[pos] == "(": stack.append((pos, current)) current = [] pos += 1 continue item, pos = _parse_marker_item(ctx, src, n, pos) current.append(item) # After an atom: look for a BOOLOP, else close a parenthesis. expect_atom = False for _ in range(len(stack) + 1): if pos < n: c = src[pos] if c == "a" and _match_word(src, n, pos, "and"): current.append("and") pos += 3 expect_atom = True break if c == "o" and _match_word(src, n, pos, "or"): current.append("or") pos += 2 expect_atom = True break if c == ")" and stack: _open_pos, parent = stack.pop() parent.append(current) current = parent pos = skip_ws(src, pos + 1, n) continue if not stack: return current, pos syntax_error( ctx, "Expected matching RIGHT_PARENTHESIS for LEFT_PARENTHESIS, after marker expression", stack[-1][0], pos, ) if not expect_atom: fail("internal error: marker parser did not terminate") fail("internal error: marker parser did not terminate") def parse_marker(marker_str): """Parses a PEP 508 marker string into an AST-like structure. The grammar, error conditions and value processing follow `packaging.markers.Marker` (packaging 26.3): quoted strings are decoded like Python string literals (`\\N{...}` escapes are not supported), dotted variable names are mapped to their underscore form, `python_implementation` is an alias for `platform_python_implementation`, and values compared against `extra`, `extras` and `dependency_groups` are normalized (PEP 685 / PEP 735) at every nesting level. Unlike upstream, an empty or whitespace-only string is accepted and returns `[]`, which `evaluate` treats as always true. Invalid input fails with an upstream-style message that shows the marker and a caret at the error position. Args: marker_str: The marker string to parse. Returns: A list representing the parsed marker tree. Each comparison is a tuple `(lhs, op, rhs)` where `lhs`/`rhs` are `struct(type, value)` with `type` either "variable" or "string" and `op` a string such as "==", "in" or "not in"; boolean operators are the strings "and"/"or"; and parenthesized groups are nested lists. """ if not strip_whitespace(marker_str): return [] ctx = struct(src = marker_str, label = "Invalid marker") tree, pos = parse_marker_expression(ctx, 0) if not at_end(marker_str, pos): syntax_error(ctx, "Expected end of marker expression", pos) return tree # --------------------------------------------------------------------------- # Serialization (upstream `str(Marker)`) # --------------------------------------------------------------------------- def _format_node(node): if node.type == "string": if "\"" not in node.value: return "\"" + node.value + "\"" if "'" not in node.value: return "'" + node.value + "'" fail("Cannot serialize marker value containing both quote characters: {}".format(repr(node.value))) return node.value def _format_item(item): lhs, op, rhs = item return "{} {} {}".format(_format_node(lhs), op, _format_node(rhs)) def _unwrap_singleton(node): for _ in range(1 << 30): if type(node) == "list" and len(node) == 1 and type(node[0]) in ("list", "tuple"): node = node[0] else: break return node def marker_to_string(markers): """Serializes a parsed marker tree like upstream `str(Marker)`. Variables and `extra`/`extras`/`dependency_groups` values are emitted in their normalized form, string values are double-quoted (or single-quoted when the value contains `"`), and redundant outer parentheses around a group are dropped. Fails if a string value contains both `"` and `'`. Args: markers: A parsed marker tree (from `parse`). Returns: The normalized marker string ("" for an empty tree). """ node = _unwrap_singleton(markers) if type(node) == "tuple": return _format_item(node) if type(node) != "list": return node if not node: return "" out = [] work = [] for i in range(len(node) - 1, -1, -1): work.append(node[i]) if i: work.append(" ") for _ in range(1 << 30): if not work: break entry = work.pop() if type(entry) == "string": out.append(entry) continue if type(entry) == "tuple": out.append(_format_item(entry)) continue entry = _unwrap_singleton(entry) if type(entry) == "tuple": out.append(_format_item(entry)) elif type(entry) == "list": work.append(")") for i in range(len(entry) - 1, -1, -1): work.append(entry[i]) if i: work.append(" ") work.append("(") else: out.append(entry) return "".join(out) # --------------------------------------------------------------------------- # Evaluation # --------------------------------------------------------------------------- _MARKERS_REQUIRING_VERSION = { "implementation_version": True, "platform_release": True, "python_full_version": True, "python_version": True, } _MARKERS_ALLOWING_SET = { "dependency_groups": True, "extras": True, } _COLLECTION_TYPES = ("list", "tuple", "set", "dict") def _resolve_extra(environment, cache): if "extra" in cache: return cache["extra"] extra = environment.get("extra") if extra == None or extra == "": val = "" elif type(extra) == "string": val = utils.canonicalize_name(extra) elif type(extra) in ("list", "tuple", "set"): # Like upstream packaging (#1438), an empty collection of extras # evaluates like the empty string (no extra selected). if not extra: val = "" else: out = {} for e in extra: if type(e) != "string": fail("Marker environment value for 'extra' must be a string or a list/tuple/set of strings, got an element of type {}".format(type(e))) out[utils.canonicalize_name(e)] = True val = out else: fail("Marker environment value for 'extra' must be a string or a list/tuple/set of strings, got {}".format(type(extra))) cache["extra"] = val return val def _canonicalize_collection(value, key, item): out = [] for v in value: if type(v) != "string": fail("Marker environment value for '{}' must contain only strings, got {} (in marker `{}`)".format( key, type(v), _format_item(item), )) out.append(utils.canonicalize_name(v)) return out def _eval_item(item, environment, cache, ver_cache): lhs, op, rhs = item # The environment value is a string almost always, so the code below gets # its type only once. lhs_is_var = lhs.type == "variable" key = lhs.value if lhs_is_var else rhs.value if key == "extra": env_val = _resolve_extra(environment, cache) else: env_val = environment.get(key) if env_val == None: fail("Undefined environment variable '{}' in marker `{}`".format(key, _format_item(item))) env_type = type(env_val) if env_type == "string": if lhs_is_var: lhs_val = env_val rhs_val = rhs.value else: lhs_val = lhs.value rhs_val = env_val elif key == "extra" and env_type == "dict": # Upstream packaging (#1438): `extra` may be a set/list/tuple of # active extras (converted to a dict set by `_resolve_extra`). value = rhs.value if lhs_is_var else lhs.value if op == "==": return value in env_val if op == "!=": return value not in env_val fail("Operator '{}' is not supported when 'extra' is a collection of extras (in marker `{}`); only == and != are".format( op, _format_item(item), )) elif lhs_is_var: fail("Cannot evaluate marker `{}`: the left-hand side must be a string, but '{}' is a {}".format( _format_item(item), key, env_type, )) elif env_type not in _COLLECTION_TYPES: fail("Marker environment value for '{}' must be a string or a collection of strings, got {} (in marker `{}`)".format( key, env_type, _format_item(item), )) else: lhs_val = lhs.value rhs_val = env_val if key in _MARKERS_ALLOWING_SET: lhs_val = utils.canonicalize_name(lhs_val) if env_type == "string": rhs_val = utils.canonicalize_name(rhs_val) else: rhs_val = _canonicalize_collection(rhs_val, key, item) elif env_type == "string" and key in _MARKERS_REQUIRING_VERSION: if key == "python_full_version" and env_val.endswith("+"): env_val += "local" if lhs_is_var: lhs_val = env_val else: rhs_val = env_val # Upstream `_eval_op`: version comparison when `op + rhs` is a valid # specifier; otherwise fall through to the string operator table. if op != "in" and op != "not in": # The same comparison is often repeated in a marker and the same # version is compared in all of them, so both are parsed once. # Safe to share `cache` with `"extra"`: `op` always starts with an # operator symbol (`=`, `!`, `<`, `>`, `~`), never `"e"`. spec_str = op + rhs_val if spec_str in cache: spec = cache[spec_str] else: spec = try_parse_specifier(spec_str) cache[spec_str] = spec if spec != None: # Like upstream `spec.contains(lhs, prereleases=True)`: an # invalid version is False (only `===` compares it as a # string). if spec.operator == "===": return specifier_contains(spec, lhs_val) if lhs_val in ver_cache: pv = ver_cache[lhs_val] else: pv = try_parse_version(lhs_val) ver_cache[lhs_val] = pv if pv == None: return False return specifier_matches_parsed(spec, pv) if op == "==": return lhs_val == rhs_val if op == "!=": return lhs_val != rhs_val if op == "in": return lhs_val in rhs_val if op == "not in": return lhs_val not in rhs_val if op == "<" or op == ">": return False if op == "<=" or op == ">=": return lhs_val == rhs_val fail("Undefined comparison: operator '{}' is not defined for {} and {} (in marker `{}`)".format( op, repr(lhs_val), repr(rhs_val), _format_item(item), )) def evaluate_markers(markers, environment): """Evaluates a parsed marker expression against an environment. Semantics follow `packaging.markers.Marker.evaluate` (packaging 26.3, plus set-of-extras evaluation from pypa/packaging#1438): - `python_version`, `python_full_version`, `implementation_version` and `platform_release` are compared as PEP 440 versions when `op + value` is a valid specifier (pre-releases always match). If it is not a valid specifier, the comparison falls back to the string table below; if the version being tested is not a valid version, the comparison is False, except for `===`, which compares the strings case-insensitively. A `python_full_version` ending in "+" gets "local" appended first. - All other comparisons use upstream's string table: `==`, `!=`, `in` and `not in` as usual, `<` and `>` are always False, `<=` and `>=` mean equality, and `~=` and `===` fail ("Undefined comparison"). - `extra`, `extras` and `dependency_groups` values are normalized (PEP 685 / PEP 735) on both sides. There is no default environment: every variable the marker references must be present, except `extra`, which defaults to "" (None and empty collections are also treated as ""). Callers must supply `extras` / `dependency_groups` (as lists/sets of strings) when markers use them. `environment["extra"]` may also be a list, tuple, or set of strings representing all active extras (matching pypa/packaging#1438). Each element is normalized. `extra == X` and `X == extra` are True iff X is in the set; `!=` is True iff it is not. An empty collection behaves like `""` (no extra selected). Any operator other than `==` and `!=` on a non-empty collection fails. Args: markers: The parsed marker tree (list), as returned by `parse`. An empty list evaluates to True. environment: A dict mapping marker variable names (underscore form) to values. Returns: True if the markers evaluate to true, False otherwise. """ if not markers: return True cache = {} ver_cache = {} # Fast path for flat markers (no parenthesized sub-expressions). # Evaluates eagerly like upstream packaging (any invalid comparison or # undefined variable fails even in an otherwise-decided branch). or_val = False group_val = True nested_idx = -1 for i in range(len(markers)): marker = markers[i] if type(marker) == "tuple": if not _eval_item(marker, environment, cache, ver_cache): group_val = False elif marker == "or": if group_val: or_val = True group_val = True elif marker == "and": pass elif type(marker) == "list": nested_idx = i break else: fail("Unexpected marker: {}".format(marker)) if nested_idx == -1: return or_val or group_val # Fall back to explicit stack starting from the first nested list. # Mutable stack frames: [markers_list, index, length, or_val, group_val]. stack = [ [markers, nested_idx + 1, len(markers), or_val, group_val], [markers[nested_idx], 0, len(markers[nested_idx]), False, True], ] # Each step advances an index or pops a level, so this always terminates. for _ in range(1 << 30): frame = stack[-1] i = frame[1] if i >= frame[2]: result = frame[3] or frame[4] stack.pop() if not stack: return result if not result: stack[-1][4] = False continue marker = frame[0][i] frame[1] = i + 1 if type(marker) == "tuple": if not _eval_item(marker, environment, cache, ver_cache): frame[4] = False elif type(marker) == "list": stack.append([marker, 0, len(marker), False, True]) elif marker == "or": if frame[4]: frame[3] = True frame[4] = True elif marker == "and": pass else: fail("Unexpected marker: {}".format(marker)) fail("internal error: marker evaluation did not terminate") def _join_groups(groups): """Builds a marker tree from the `or`-ed groups of the `and`-ed atoms.""" out = [] for group in groups: if out: out.append("or") for i, atom in enumerate(group): if i: out.append("and") out.append(atom) return out def _close_group(frame): """Adds the `and`-ed atoms that were seen since the last `or` to the frame.""" group = frame[5] if frame[6]: # An atom is false, so the whole group is. pass elif not group: # All of the atoms are true, so the whole expression is. frame[3] = True elif len(group) == 1 and type(group[0]) == "tuple" and len(group[0]) == 1: # Only a parenthesized expression is left, so it does not need the # parentheses. frame[4].extend(group[0][0]) else: frame[4].append([ _join_groups(atom[0]) if type(atom) == "tuple" and len(atom) == 1 else atom for atom in group ]) frame[5] = [] frame[6] = False def evaluate_markers_partial(markers, environment): """Evaluates the part of a parsed marker expression that an environment defines. This is for the cases where only a part of the environment is known, e.g. the `extra` is known when a wheel is extracted, but the platform is only known later. The comparisons of the variables that are in `environment` are evaluated like `evaluate` does it and the result is simplified: - `True` if the marker is true for every value of the other variables. - `False` if the marker is false for every value of the other variables. - Otherwise a marker tree with the comparisons that could not be evaluated. Evaluating it with the other variables gives the same result as evaluating `markers` with all of them. Use `to_string` to serialize it. Only the comparisons that are decided by `environment` are removed, i.e. the comparisons that are left are not simplified any further, e.g. the result of `os_name == "posix" or os_name != "posix"` is not `True` if `os_name` is not in `environment`. Unlike `evaluate`, there is no default for `extra`: it is left in the result if it is not in `environment`. Like `evaluate`, all of the comparisons of the known variables are evaluated, so an invalid one fails even if it could not change the result. Args: markers: The parsed marker tree (list), as returned by `parse`. An empty list evaluates to True. environment: A dict mapping the names of the known marker variables (underscore form) to the values, see `evaluate`. Returns: `True`, `False` or the marker tree (see `parse`) of what is left to evaluate. """ if not markers: return True cache = {} ver_cache = {} # Mutable stack frames: [markers, index, length, is true, the groups that # are left, the atoms of the current group that are left, is the current # group false]. An atom that is left is either an item (a tuple of 3) or # the groups of a parenthesized expression (wrapped in a tuple of 1). stack = [[markers, 0, len(markers), False, [], [], False]] result = None # Each step advances an index or pops a level, so this always terminates. for _ in range(1 << 30): frame = stack[-1] i = frame[1] if i >= frame[2]: _close_group(frame) if frame[3]: result = True elif frame[4]: result = frame[4] else: result = False stack.pop() if not stack: break frame = stack[-1] if result == False: frame[6] = True elif result == True: pass elif len(result) == 1: # There is no `or`, so the parentheses are not needed. frame[5].extend(result[0]) else: frame[5].append((result,)) continue marker = frame[0][i] frame[1] = i + 1 if type(marker) == "tuple": lhs, _, rhs = marker if (lhs.value if lhs.type == "variable" else rhs.value) not in environment: frame[5].append(marker) elif not _eval_item(marker, environment, cache, ver_cache): frame[6] = True elif type(marker) == "list": stack.append([marker, 0, len(marker), False, [], [], False]) elif marker == "or": _close_group(frame) elif marker == "and": pass else: fail("Unexpected marker: {}".format(marker)) if type(result) == "list": return _join_groups(result) return result markers = struct( parse = parse_marker, evaluate = evaluate_markers, evaluate_partial = evaluate_markers_partial, to_string = marker_to_string, )