-
-
Notifications
You must be signed in to change notification settings - Fork 11.6k
fix(swift): parse an if let binding whose await operand is not a call #3542
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
L4XB
wants to merge
2
commits into
Graphify-Labs:v8
Choose a base branch
from
L4XB:fix/3540-swift-await-optional-binding
base: v8
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+242
−0
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,6 +4,7 @@ | |
| import hashlib | ||
| import importlib | ||
| import json | ||
| import re | ||
| from graphify.extractors.base import _LANGUAGE_BUILTIN_GLOBALS, _file_stem, _make_id, _read_text | ||
| from graphify.ids import normalize_id | ||
| from graphify.extractors.models import LanguageConfig | ||
|
|
@@ -3141,6 +3142,79 @@ def _ruby_extra_walk(node, source: bytes, file_nid: str, stem: str, str_path: st | |
| del ruby_namespace[-len(const_segments):] | ||
| return True | ||
|
|
||
| # tree-sitter-swift (0.7.3, the only published release) accepts `await` in an | ||
| # `if let` binding ONLY when the operand is a direct call. `if let r = await | ||
| # pending`, `if let r = await box.rings` and `if let r = try await mint()` are | ||
| # all valid Swift 6 and all parse as ERROR, which costs the rest of the file: | ||
| # a 412-line source came out with 59 of its ~87 symbols (#3540). `guard let` | ||
| # with the same operand parses, so the gap is in the if/while binding rule. | ||
| # | ||
| # Blanking `await` with SPACES rather than deleting it is the whole trick: the | ||
| # repaired source is byte-for-byte the same length, so every offset, line and | ||
| # column downstream still points where it did. `await` names no symbol, so a | ||
| # graph built from the repaired bytes is the graph of the original file. | ||
| _SWIFT_AWAIT_BINDING = re.compile( | ||
| rb"(\b(?:if|while)\s+(?:let|var)\s+[A-Za-z_]\w*\s*=\s*)((?:try\s+)?await\s+)" | ||
| ) | ||
|
|
||
|
|
||
| def _swift_line_comment_start(line: bytes) -> int: | ||
| """Offset of the `//` that opens a line comment, or `len(line)` if none. | ||
|
|
||
| Quote-aware, because "is there a `//` earlier on the line" is not the same | ||
| question: `let base = "https://x"; if let y = await f(base)` has one inside | ||
| a string literal, and reading it as a comment marker skipped the repair on | ||
| a line that needed it (Graphify review on #3542). A URL in Swift source is | ||
| ordinary, so this was not a corner. | ||
|
|
||
| What it does NOT model: raw strings (`#"..."#`), multi-line `\"\"\"` | ||
| literals, and interpolation. Getting one of those wrong costs nothing in | ||
| either direction. Reading a comment as code rewrites an `await` inside a | ||
| comment, which is equal-length and only reaches a file that already failed | ||
| to parse; reading code as a comment is the behaviour this replaces. | ||
| """ | ||
| inside_string = False | ||
| index = 0 | ||
| while index < len(line): | ||
| character = line[index : index + 1] | ||
| if inside_string: | ||
| if character == b"\\": | ||
| index += 2 | ||
| continue | ||
| if character == b'"': | ||
| inside_string = False | ||
| elif character == b'"': | ||
| inside_string = True | ||
| elif character == b"/" and line[index + 1 : index + 2] == b"/": | ||
| return index | ||
| index += 1 | ||
| return len(line) | ||
|
|
||
|
|
||
| def _swift_blank_await_bindings(source: bytes) -> bytes: | ||
| """`if let x = await y` -> `if let x = y`, same byte length. | ||
|
|
||
| Skips a match that sits behind the `//` that opens a line comment, so a | ||
| commented-out binding keeps its text: comments are not parsed into symbols, | ||
| but some of them are read as documentation and rewriting one would be a | ||
| change nobody asked for. A block comment or a string literal holding this | ||
| exact shape is still rewritten — harmless at equal length, and this only | ||
| runs on a file that already failed to parse. | ||
| """ | ||
|
|
||
| def replace(match: "re.Match[bytes]") -> bytes: | ||
| line_start = source.rfind(b"\n", 0, match.start()) + 1 | ||
| line_end = source.find(b"\n", match.start()) | ||
| if line_end == -1: | ||
| line_end = len(source) | ||
| comment_start = _swift_line_comment_start(source[line_start:line_end]) | ||
| if line_start + comment_start < match.start(): | ||
| return match.group(0) | ||
| return match.group(1) + b" " * len(match.group(2)) | ||
|
|
||
| return _SWIFT_AWAIT_BINDING.sub(replace, source) | ||
|
|
||
|
|
||
| def _extract_generic( | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
fans out to 27 callees (efferent coupling); 18 callers depend on it (afferent coupling). Grounded coupling-delta finding (deterministic), not an LLM guess. |
||
| path: Path, config: LanguageConfig, *, source_override: bytes | None = None | ||
| ) -> dict: | ||
|
|
@@ -3184,6 +3258,19 @@ def _extract_generic( | |
| source = source + b"\n" | ||
| tree = parser.parse(source) | ||
| root = tree.root_node | ||
| # Error-gated, so a file that already parses is never rewritten, and | ||
| # the repair is kept only when it actually buys something: no error at | ||
| # all, or a first error that moved further down the file (a source can | ||
| # carry this grammar gap AND a real mistake). | ||
| if root.has_error and config.ts_module == "tree_sitter_swift": | ||
| repaired = _swift_blank_await_bindings(source) | ||
| if repaired != source: | ||
| retry_root = parser.parse(repaired).root_node | ||
| if not retry_root.has_error or ( | ||
| (_first_parse_error_line(retry_root) or 0) | ||
| > (_first_parse_error_line(root) or 0) | ||
| ): | ||
| source, root = repaired, retry_root | ||
| except Exception as e: | ||
| return {"nodes": [], "edges": [], "error": str(e)} | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,154 @@ | ||
| """Regression tests for #3540. | ||
|
|
||
| tree-sitter-swift (0.7.3, the only published release) accepts `await` in an | ||
| `if let` binding ONLY when the operand is a direct call. Valid Swift 6 such as | ||
| `if let r = await pending`, `if let r = await box.rings` and | ||
| `if let r = try await mint()` all parse as ERROR, so the file is reported as | ||
| "partially extracted" and every rule downstream walks a damaged subtree. | ||
| `guard let` with the same operand parses, which places the gap in the | ||
| if/while binding rule rather than in `await` itself. | ||
|
|
||
| The repair blanks the `await` with SPACES instead of deleting it, so the | ||
| repaired source is byte-for-byte the same length and every offset, line and | ||
| column downstream still points where it did. | ||
| """ | ||
| from __future__ import annotations | ||
|
|
||
| import tempfile | ||
| import unittest | ||
| from pathlib import Path | ||
|
|
||
| from graphify.extract import extract_swift | ||
|
|
||
| from graphify.extractors.engine import _swift_blank_await_bindings | ||
|
|
||
| PREAMBLE = """import Foundation | ||
|
|
||
| struct Rings { let move: Double = 0 } | ||
|
|
||
| func fetchRings() async -> Rings? { nil } | ||
| """ | ||
|
|
||
| # A declaration after the binding, so "the file still parsed past it" is | ||
| # something the assertions can see rather than something they assume. | ||
| SENTINEL = "\nstruct SentinelType { let marker = 1 }\n" | ||
|
|
||
|
|
||
| class TestSwiftAwaitOptionalBinding(unittest.TestCase): | ||
| def _extract(self, body: str) -> dict: | ||
| with tempfile.TemporaryDirectory() as d: | ||
| p = Path(d) / "Await.swift" | ||
| p.write_text(PREAMBLE + body + SENTINEL, encoding="utf-8") | ||
| return extract_swift(p) | ||
|
|
||
| def test_every_await_binding_shape_parses(self): | ||
| """The four shapes the report measured, plus `while` and `var`.""" | ||
| bodies = { | ||
| "await a bare identifier": ( | ||
| "func load() async {\n" | ||
| " async let pending = fetchRings()\n" | ||
| " if let r = await pending { print(r.move) }\n" | ||
| "}\n" | ||
| ), | ||
| "await a member": ( | ||
| "func load(box: Box) async {\n" | ||
| " if let r = await box.rings { print(r.move) }\n" | ||
| "}\n" | ||
| ), | ||
| "try await a call": ( | ||
| "func load() async throws {\n" | ||
| " if let r = try await fetchRings() { print(r.move) }\n" | ||
| "}\n" | ||
| ), | ||
| "if var": ( | ||
| "func load() async {\n" | ||
| " async let pending = fetchRings()\n" | ||
| " if var r = await pending { print(r.move) }\n" | ||
| "}\n" | ||
| ), | ||
| "while let": ( | ||
| "func load() async {\n" | ||
| " async let pending = fetchRings()\n" | ||
| " while let r = await pending { print(r.move) }\n" | ||
| "}\n" | ||
| ), | ||
| } | ||
| for name, body in bodies.items(): | ||
| with self.subTest(name): | ||
| result = self._extract(body) | ||
| # `parse_errors`, plural — the key the extractor actually | ||
| # sets. The singular spelling is never present, so asserting | ||
| # on it passes for a file that failed to parse. | ||
| self.assertEqual(result.get("parse_errors"), None, name) | ||
| # Arrival: the file really was walked, so the absence above is | ||
| # a clean parse and not an empty result. | ||
| self.assertIn("SentinelType", [n["label"] for n in result["nodes"]]) | ||
|
|
||
| def test_a_direct_call_operand_was_never_broken(self): | ||
| """Accept control. `await` + a direct call always parsed, so a rule | ||
| that "fixed" it would be repairing nothing and could only add risk.""" | ||
| result = self._extract( | ||
| "func load() async {\n" | ||
| " if let r = await fetchRings() { print(r.move) }\n" | ||
| "}\n" | ||
| ) | ||
| self.assertEqual(result.get("parse_errors"), None) | ||
| self.assertIn("SentinelType", [n["label"] for n in result["nodes"]]) | ||
|
|
||
| def test_the_repair_preserves_every_byte_offset(self): | ||
| """The property the whole approach rests on: same length, so every | ||
| node's start/end byte still addresses the text it did.""" | ||
| for source in ( | ||
| b"if let r = await pending {", | ||
| b"if let r = try await mint() {", | ||
| b"while var r = await box.rings {", | ||
| b"if let r = await fetchRings() {", | ||
| b"guard let r = await pending else {", | ||
| ): | ||
| with self.subTest(source.decode()): | ||
| self.assertEqual(len(_swift_blank_await_bindings(source)), len(source)) | ||
|
|
||
| def test_a_url_in_a_string_is_not_a_comment_marker(self): | ||
| """The Graphify review's finding, reproduced first. | ||
|
|
||
| `"https://..."` puts a `//` on the line before the binding, and reading | ||
| "is there a `//` earlier" as "is this commented out" skipped the repair | ||
| on a line that needed it — so the file stayed unparseable, which is the | ||
| defect this whole function exists to clear. A URL in Swift source is | ||
| ordinary, so this was not a corner. | ||
| """ | ||
| for source in ( | ||
| b'let base = "https://api.example.com"; if let x = await f(base) {', | ||
| b'let u = "a//b"; while var r = await box.rings {', | ||
| b'let s = "said \\"hi//\\""; if let r = await p {', | ||
| ): | ||
| with self.subTest(source.decode()): | ||
| repaired = _swift_blank_await_bindings(source) | ||
| self.assertNotEqual(repaired, source) | ||
| self.assertEqual(len(repaired), len(source)) | ||
| self.assertNotIn(b"await", repaired) | ||
|
|
||
| def test_a_real_line_comment_is_still_left_alone(self): | ||
| """The control for it, in both positions a comment can open: the whole | ||
| line, and after code on the same line. Losing this would rewrite a | ||
| commented-out binding that somebody is reading as documentation.""" | ||
| for untouched in ( | ||
| b"// if let r = await pending\n", | ||
| b" // guard let r = await pending else {\n", | ||
| b'let base = "x" // if let r = await pending\n', | ||
| ): | ||
| with self.subTest(untouched.decode()): | ||
| self.assertEqual(_swift_blank_await_bindings(untouched), untouched) | ||
|
|
||
| def test_the_repair_leaves_everything_else_alone(self): | ||
| """It rewrites the binding operand and nothing else — not a `guard`, | ||
| which the grammar already accepts, and not an `await` in a statement | ||
| position.""" | ||
| for untouched in ( | ||
| b"guard let r = await pending else { return }", | ||
| b"let r = await pending", | ||
| b"await doThing()", | ||
| b"// if let r = await pending\n", | ||
| ): | ||
| with self.subTest(untouched.decode()): | ||
| self.assertEqual(_swift_blank_await_bindings(untouched), untouched) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
_extract_generic()fans out to 27 callees (efferent coupling); 18 callers depend on it (afferent coupling).
Grounded coupling-delta finding (deterministic), not an LLM guess.