diff --git a/changelog.d/12591-for-with-builtin-rebind-guard.md b/changelog.d/12591-for-with-builtin-rebind-guard.md new file mode 100644 index 00000000000..5800c4d6989 --- /dev/null +++ b/changelog.d/12591-for-with-builtin-rebind-guard.md @@ -0,0 +1,2 @@ + +- A Python `isinstance` guard is read as unknown, and keeps fail-open credit, when the file rebinds a builtin through the builtins module as a `for` target, a `with ... as` target or a comprehension target (`for b.isinstance in items:`, `with ctx() as b.isinstance:`); a plain `for x in items:` or `with ctx() as x:` and a read of the attribute in the iterable still leave the guard readable (#12591). diff --git a/crates/ripr/src/analysis/language/python/arm_activation.rs b/crates/ripr/src/analysis/language/python/arm_activation.rs index b41a1ef91f6..4cf85ec5717 100644 --- a/crates/ripr/src/analysis/language/python/arm_activation.rs +++ b/crates/ripr/src/analysis/language/python/arm_activation.rs @@ -414,6 +414,7 @@ fn patches_builtin(lines: &[&str], index: usize, name: &str, modules: &[String]) return false; } let compact = compact_statement(lines, index); + let spaced = spaced_statement(lines, index); modules.iter().any(|module| { [ format!("{module}.{name}"), @@ -422,13 +423,14 @@ fn patches_builtin(lines: &[&str], index: usize, name: &str, modules: &[String]) ] .iter() .any(|target| { - compact.match_indices(target.as_str()).any(|(start, _)| { - let boundary = compact[..start] - .chars() - .next_back() - .is_none_or(|ch| !(ch.is_alphanumeric() || ch == '_' || ch == '.')); - boundary && rebinds_target(&compact, target) - }) + binds_in_header(&spaced, target) + || compact.match_indices(target.as_str()).any(|(start, _)| { + let boundary = compact[..start] + .chars() + .next_back() + .is_none_or(|ch| !(ch.is_alphanumeric() || ch == '_' || ch == '.')); + boundary && rebinds_target(&compact, target) + }) }) }) } @@ -466,6 +468,121 @@ fn compact_statement(lines: &[&str], index: usize) -> String { .collect() } +/// Text of the statement containing `lines[index]` with comments removed and +/// line breaks and `\` continuations turned into single spaces (#12591). +fn spaced_statement(lines: &[&str], index: usize) -> String { + statement_line_range(lines, index) + .map(|line_index| { + let code = strip_comment(lines[line_index].trim()); + code.strip_suffix('\\').unwrap_or(code).to_string() + }) + .collect::>() + .join(" ") +} + +/// `text` with the inside of every string literal replaced by `_`, so a +/// keyword or delimiter inside a string is never read. The result has the +/// same length as `text`. +fn mask_strings(text: &str) -> Vec { + let (mut quote, mut escaped) = (0u8, false); + let mut masked = Vec::with_capacity(text.len()); + for byte in text.bytes() { + if quote != 0 { + if escaped { + escaped = false; + masked.push(b'_'); + } else if byte == b'\\' { + escaped = true; + masked.push(b'_'); + } else if byte == quote { + quote = 0; + masked.push(byte); + } else { + masked.push(b'_'); + } + } else { + if byte == b'"' || byte == b'\'' { + quote = byte; + } + masked.push(byte); + } + } + masked +} + +fn is_word_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || byte == b'_' +} + +/// Whether `word` stands alone at `at` (not part of a longer name or an attribute). +fn word_at(bytes: &[u8], at: usize, word: &str) -> bool { + let word = word.as_bytes(); + bytes.get(at..at + word.len()) == Some(word) + && at + .checked_sub(1) + .and_then(|before| bytes.get(before)) + .is_none_or(|&byte| !is_word_byte(byte) && byte != b'.') + && bytes + .get(at + word.len()) + .is_none_or(|&byte| !is_word_byte(byte)) +} + +/// End of the target that starts at `from`: the first index at bracket depth +/// zero where `stop` holds, or where an enclosing bracket closes. +fn target_end(bytes: &[u8], from: usize, stop: impl Fn(&[u8], usize) -> bool) -> usize { + let mut depth = 0usize; + for (index, &byte) in bytes.iter().enumerate().skip(from) { + if depth == 0 && stop(bytes, index) { + return index; + } + match byte { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => match depth.checked_sub(1) { + Some(next) => depth = next, + None => return index, + }, + _ => {} + } + } + bytes.len() +} + +/// Whether a `for` target (a loop header or comprehension clause) or a +/// `with ... as` target in `statement` stores into `target` (#12591), so +/// `for b.isinstance in items:`, `with ctx() as b.isinstance:` and +/// `[0 for b.isinstance in items]` read as a rebinding. A plain +/// `for x in items:` or `with ctx() as x:`, and a use of the attribute in the +/// iterable or context expression, bind nothing. Strings are never read. +fn binds_in_header(statement: &str, target: &str) -> bool { + let masked = mask_strings(statement); + let stores = |from: usize, end: usize| { + statement.get(from..end).is_some_and(|slice| { + let compact: String = slice.chars().filter(|ch| !ch.is_whitespace()).collect(); + is_store_slot(&compact, target) + }) + }; + let is_with = (0..masked.len()).any(|at| word_at(&masked, at, "with")); + (0..masked.len()).any(|at| { + if word_at(&masked, at, "for") { + let from = at + "for".len(); + stores( + from, + target_end(&masked, from, |bytes, index| word_at(bytes, index, "in")), + ) + } else if is_with && word_at(&masked, at, "as") { + let from = at + "as".len(); + stores( + from, + target_end(&masked, from, |bytes, index| { + matches!(bytes.get(index), Some(b',' | b':')) + }), + ) + } else { + false + } + }) +} + /// Whether the line rebinds `target` (`builtins.name`, `builtins["name"]`; /// whitespace already removed) as an assignment store (#12222): a plain, /// chained or annotated `target = f`, or a slot in a tuple, list or diff --git a/crates/ripr/src/analysis/language/python/guard_atoms_tests.rs b/crates/ripr/src/analysis/language/python/guard_atoms_tests.rs index 3ee3766cd5f..69aa8d56ad8 100644 --- a/crates/ripr/src/analysis/language/python/guard_atoms_tests.rs +++ b/crates/ripr/src/analysis/language/python/guard_atoms_tests.rs @@ -384,6 +384,21 @@ fn other_ways_to_reach_the_builtins_module_are_not_read_as_the_builtin() -> Resu "import builtins as b\n[other,\n b.isinstance] = [None, checker]\n\n\n", "import builtins as b\nb.isinstance = \\\n checker\n\n\n", "import builtins as b\n(\n b.isinstance,\n other,\n) = (checker, None)\n\n\n", + // #12591: `for`, `with ... as` and comprehension targets store too. + "import builtins as b\nfor b.isinstance in items:\n pass\n\n\n", + "import builtins as b\nfor other, b.isinstance in pairs:\n pass\n\n\n", + "import builtins as b\nfor (other, b.isinstance) in pairs:\n pass\n\n\n", + "import builtins as b\nasync for b.isinstance in items:\n pass\n\n\n", + "import builtins as b\nwith ctx() as b.isinstance:\n pass\n\n\n", + "import builtins as b\nwith open(path) as handle, ctx() as b.isinstance:\n pass\n\n\n", + "import builtins as b\nwith (ctx() as b.isinstance, other() as handle):\n pass\n\n\n", + "import builtins as b\nwith ctx() as (other, b.isinstance):\n pass\n\n\n", + "import builtins as b\nchecks = [0 for b.isinstance in items]\n\n\n", + "import builtins as b\nchecks = {k: 0 for k, b.isinstance in pairs}\n\n\n", + "import builtins as b\nchecks = list(1 for other in rows for b.isinstance in other)\n\n\n", + "import builtins as b\nfor b . isinstance in items:\n pass\n\n\n", + "import builtins as b\nfor b['isinstance'] in items:\n pass\n\n\n", + "import builtins as b\nchecks = [0 for other in rows\n for b.isinstance in other]\n\n\n", ]; for patch in patches { let owner = format!("{patch}{arm}"); @@ -416,6 +431,17 @@ fn other_ways_to_reach_the_builtins_module_are_not_read_as_the_builtin() -> Resu // #12593 controls: multiline reads and continued expressions bind nothing. "import builtins as b\nchecks = (b.isinstance,\n b.len)\n\n\n", "import builtins as b\nsame = b.isinstance == \\\n checker\n\n\n", + // #12591 controls: plain targets, and the attribute only read in the + // iterable, context expression, a string or a comprehension condition. + "import builtins as b\nfor item in items:\n pass\n\n\n", + "import builtins as b\nwith ctx() as handle:\n pass\n\n\n", + "import builtins as b\nfor item in [b.isinstance, b.len]:\n pass\n\n\n", + "import builtins as b\nwith b.isinstance as handle:\n pass\n\n\n", + "import builtins as b\nwith open(b.isinstance) as handle, ctx() as other:\n pass\n\n\n", + "import builtins as b\nchecks = [b.isinstance for item in items]\n\n\n", + "import builtins as b\nchecks = [item for item in items if item is b.isinstance]\n\n\n", + "import builtins as b\nlabel = \"for b.isinstance in items\"\n\n\n", + "import builtins as b\nimport os as handle\nuse(b.isinstance)\n\n\n", ] { let owner = format!("{harmless}{arm}"); assert_eq!( diff --git a/docs/specs/RIPR-SPEC-0260-python-guarded-arm-activation.md b/docs/specs/RIPR-SPEC-0260-python-guarded-arm-activation.md index e0d2d4cccf1..fb6b46d098e 100644 --- a/docs/specs/RIPR-SPEC-0260-python-guarded-arm-activation.md +++ b/docs/specs/RIPR-SPEC-0260-python-guarded-arm-activation.md @@ -104,9 +104,13 @@ an `and` chain (split outside quotes and brackets) may be: builtins module or an alias (`builtins.isinstance = f`, an annotated `b.isinstance: object = f`, a tuple, list or chained target `b.isinstance, other = f, g`, a tuple/list/parenthesized target split across - physical lines or continued with `\`, `setattr`, `vars(builtins)[..]`); a bare - annotation, a use inside a call or subscript key, a comparison and a - right-hand-side read are not rebindings (#12183, #12206, #12222, #12593); + physical lines or continued with `\`, a `for` or comprehension target + (`for b.isinstance in items`, `[0 for b.isinstance in items]`), a + `with ... as b.isinstance` target, `setattr`, `vars(builtins)[..]`); a bare + annotation, a use inside a call or subscript key, a comparison, a + right-hand-side, iterable or context-expression read and a plain + `for x in items` / `with ctx() as x` are not rebindings (#12183, #12206, + #12222, #12593, #12591); - a `for TARGET in NAME:` header, read as `len(NAME) > 0` over a literal display or string, so a loop body never runs for `total([])`.