Skip to content

Prepare semantic tokens to include syntax highlighting - #3615

Closed
magic-akari wants to merge 4 commits into
pyrefly-org:mainfrom
magic-akari:feat/semantic-tokens-with-syntax-highlighting
Closed

magic-akari wants to merge 4 commits into
pyrefly-org:mainfrom
magic-akari:feat/semantic-tokens-with-syntax-highlighting

Conversation

@magic-akari

Copy link
Copy Markdown
Contributor

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-jsonschema
  • cargo test

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.
@meta-cla

meta-cla Bot commented May 30, 2026

Copy link
Copy Markdown

Hi @magic-akari!

Thank you for your pull request and welcome to our community.

Action Required

In 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.

Process

In 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 CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at cla@meta.com. Thanks!

@magic-akari
magic-akari marked this pull request as ready for review May 30, 2026 20:19
@meta-cla meta-cla Bot added the cla signed label May 30, 2026
@meta-cla

meta-cla Bot commented May 30, 2026

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

@github-actions github-actions Bot added size/xl and removed size/xl labels May 31, 2026
@yangdanny97
yangdanny97 requested a review from kinto0 June 1, 2026 15:10
@github-actions

This comment has been minimized.

@kinto0 kinto0 self-assigned this Jun 1, 2026
@kinto0

kinto0 commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

this looks great. let me do some memory testing

Comment on lines +1293 to +1295
// 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'm happy removing the gate as long as we have full support. do you think we're at that point after this?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can leave it for now and do it later. adding a todo comment here

@meta-codesync

meta-codesync Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

@kinto0 has imported this pull request. If you are a Meta employee, you can view this in D107114382.

Comment thread pyrefly/lib/lsp/wasm/semantic_tokens.rs Outdated
if include_syntax_tokens {
let tokens = self
.get_syntax_tokens(handle)
.expect("syntax tokens must be cached with the AST");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,                                                                                                                                                                                                     
  }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as a follow-up we probably should eventually update callsites

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

@kinto0 kinto0 Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@kinto0 kinto0 Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread pyrefly/lib/state/module.rs Outdated
"evict_ast called before answers computed"
);
self.state.steps.ast.store(None);
self.state.steps.syntax_tokens.store(None);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@github-actions github-actions Bot added size/xl and removed size/xl labels Jun 1, 2026
@github-actions github-actions Bot added size/xl and removed size/xl labels Jun 1, 2026
@github-actions

github-actions Bot commented Jun 1, 2026

Copy link
Copy Markdown

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

Comment on lines -78 to +114
pub ast: Option<Arc<ModModule>>,
pub parsed: Option<Arc<ParsedModule>>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll fix this up on import, no need to resubmit for it

Comment on lines +1293 to +1295
// 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can leave it for now and do it later. adding a todo comment here

@kinto0

kinto0 commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

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 yangdanny97 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review automatically exported from Phabricator review in Meta.

@meta-codesync

meta-codesync Bot commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

@kinto0 merged this pull request in 1074154.

meta-codesync Bot pushed a commit that referenced this pull request Nov 7, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants