Repository navigation
Prepare semantic tokens to include syntax highlighting - #3615
magic-akari wants to merge 4 commits into
Conversation
Pyrefly's semantic pipeline currently models only identifier-level tokens. Future support for a full semantic stream therefore requires a syntax-token source covering keywords, comments, strings, numbers, and operators. This change introduces a lightweight syntax path derived from Ruff's parse results and configures the LSP encoder to split multiline ranges into line-local tokens. To ensure the new path remains unadvertised, this server capability is gated to clients that already augment syntax tokens. This enables proper representation of triple-quoted strings and preserves current semantic-overlay behavior during the gated rollout.
|
Hi @magic-akari! Thank you for your pull request and welcome to our community. Action RequiredIn order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you. ProcessIn order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA. Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with If you have received this in error or have any questions, please contact us at cla@meta.com. Thanks! |
|
Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks! |
This comment has been minimized.
This comment has been minimized.
|
this looks great. let me do some memory testing |
| // We now have an implementation path for a full semantic token stream that fills in | ||
| // syntax tokens, but we do not advertise that capability to non-augmenting clients yet. | ||
| // Keep the provider gate here until that full-stream behavior is ready to expose. |
There was a problem hiding this comment.
this comment is relative to the PR, not the future of the file. i.e. it speaks to this change explicity
let's just remove it?
There was a problem hiding this comment.
That's a good point.
I added the syntax tokens so that semantic tokens are available whether they are augmented or not.
However, I didn't loosen the gate because I feel that decision should be left to the pyrefly team.
That's why I felt the need to add a comment here.
Should we just change the gate now and remove the comment entirely?
There was a problem hiding this comment.
i'm happy removing the gate as long as we have full support. do you think we're at that point after this?
There was a problem hiding this comment.
we can leave it for now and do it later. adding a todo comment here
|
@kinto0 has imported this pull request. If you are a Meta employee, you can view this in D107114382. |
| if include_syntax_tokens { | ||
| let tokens = self | ||
| .get_syntax_tokens(handle) | ||
| .expect("syntax tokens must be cached with the AST"); |
There was a problem hiding this comment.
risky: we have to clear ast + syntax tokens together. can we bind their storage together?
we can probably make a new ParsedModule and impl Deref for it to avoid updating callsites:
impl Deref for ParsedModule {
type Target = ModModule;
fn deref(&self) -> &ModModule {
&self.module
}
}
#[derive(Debug, Clone)]
pub struct ParsedModule {
module: ModModule,
tokens: Tokens,
}
There was a problem hiding this comment.
as a follow-up we probably should eventually update callsites
There was a problem hiding this comment.
sorry for the back/forth: even better, what if we just re-lexed on-demand in the AST when include_syntax_tokens is true?
we wouldn't have to worry about storing extra on the AST since we wouldn't store anything there.
There was a problem hiding this comment.
That was actually the approach in my initial commit, 7057f8c. I moved away from it because it would re-parse the module when include_syntax_tokens is true, and I was worried about the performance impact of doing that repeatedly.
My preference is still to cache the tokens from the original parse, as in the current direction, since that avoids the extra parse and keeps the tokens tied to the same parser invocation as the AST.
That said, if you’d prefer the simpler on-demand re-lex/re-parse approach to avoid storing extra data, I can revert back toward the original implementation. Which direction would you prefer?
There was a problem hiding this comment.
it depends how long it takes to lex and how much storage the cache uses. let me find the biggest file I can and benchmark it
There was a problem hiding this comment.
benchmarks were pretty good for both: 5ms to parse (we can't just lex, we have to parse) and 800kb extra storage on a very very big file.
it looks like we evict the ast for any non-open files (by virtue of require::exports) and we keep the ast for open files.
since parsing is O(semantic token requests) and ast is O(open files), I think your approach here by caching it in the ast is the best solution
| "evict_ast called before answers computed" | ||
| ); | ||
| self.state.steps.ast.store(None); | ||
| self.state.steps.syntax_tokens.store(None); |
There was a problem hiding this comment.
if we want to keep the separation between AST/syntax_tokens, maybe we add a comment here saying this ordering is required to avoid a crash
|
According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅ |
| pub ast: Option<Arc<ModModule>>, | ||
| pub parsed: Option<Arc<ParsedModule>>, |
There was a problem hiding this comment.
one final nit: I don't think we need to rename the ast step to parsed. If we want to, we can do that in another PR
There was a problem hiding this comment.
I'll fix this up on import, no need to resubmit for it
| // We now have an implementation path for a full semantic token stream that fills in | ||
| // syntax tokens, but we do not advertise that capability to non-augmenting clients yet. | ||
| // Keep the provider gate here until that full-stream behavior is ready to expose. |
There was a problem hiding this comment.
we can leave it for now and do it later. adding a todo comment here
|
I'm also adding a follow-up optimization to avoid computing these tokens at all when we don't require::everything. this makes it so we never request it for CLI or dependencies, limiting peak memory |
yangdanny97
left a comment
There was a problem hiding this comment.
Review automatically exported from Phabricator review in Meta.
Summary: Part of #4740: hover, go-to-definition, references and rename inside quoted annotations. Semantic highlighting is not covered here (see #3615). _The rest of this description was drafted with an AI assistant (Claude Code)._ The binder already parses forward-reference strings such as `x: "list[Foo]"` and binds the names inside them at their real source ranges. The LSP, however, located the cursor in the original AST, where the annotation is a single string literal. As a result: - hover showed only a bare `type[Foo]`, without the name or docstring - go-to-definition returned nothing, and in `list["Foo"]` it jumped to `list.__getitem__` - references and rename skipped every occurrence inside a string The PR has two commits: 1. Tests that show the current behavior, with `// BUG:` comments. 2. The fix, which updates those expectations. Approach (all in `pyrefly/lib/state/lsp.rs`): - `forward_ref_at` parses the string under the cursor. It uses the parse only if a name in it has a `Key::BoundName`. Only strings the binder parsed as types have such keys, so ordinary strings, `Literal["..."]` values and malformed annotations stay strings. - `identifier_at` and `find_definition` resolve against that parsed expression. This fixes hover, definition, declaration and type definition, including `TYPE_CHECKING` imports and qualified names like `"lib.Helper"`. - The local variable reference scan also descends into strings that mention the name. This fixes references, rename and document highlight. References to imported names already included string occurrences through the solver's index. - Only strings whose contents map exactly onto the source (`AnnotationKind::Simple`) are handled. Strings with escapes or implicit concatenation are skipped, because positions inside them can't be mapped exactly. - [ ] I am a human, and I fully understand the code I am submitting. Pull Request resolved: #5243 Test Plan: New tests: - `definition::goto_def_inside_quoted_annotation`: simple, `TYPE_CHECKING` import, nested subscript, `list["Model"]`, and both parts of `"lib.Helper"` - `definition::goto_def_ignores_strings_that_are_not_type_expressions`: `x = "Model"`, `Literal["Model"]` and a malformed `"list[Model"` resolve to nothing, before and after the fix - `hover::hover_inside_quoted_annotation`: after the fix, hover inside quotes is identical to the unquoted hover - `local_find_refs::references_inside_quoted_annotations` - `rename::test_rename_from_inside_quoted_annotation` Commands run: - `python3 test.py --no-test --no-tensor-shapes --no-conformance --no-jsonschema --no-extension` - `cargo test -p pyrefly --lib` - `cargo test -p pyrefly --test pyrefly_laziness_tests` - `cargo clippy --release` Type-checker behavior is unchanged, so conformance output is unaffected. Reviewed By: rchen152 Differential Revision: D130119984 fbshipit-source-id: ab3fe01ea9b64b4fa81a8540b883a41db35d7447
Summary
Pyrefly's semantic pipeline currently models only identifier-level tokens. Future support for a full semantic stream therefore requires a syntax-token source covering keywords, comments, strings, numbers, and operators.
This change introduces a lightweight syntax path derived from Ruff's parse results and configures the LSP encoder to split multiline ranges into line-local tokens. To ensure the new path remains unadvertised, this server capability is gated to clients that already augment syntax tokens.
This enables proper representation of triple-quoted strings and preserves current semantic-overlay behavior during the gated rollout.
Test Plan
python3 test.py --no-test --no-conformance --no-jsonschemacargo test