Skip to content

Make Lexer::current_range and Lexer::current_flags public? #28415

Closed

Description

@pawamoy

Question

Hello 🙂

I'm exploring ways to improve the performance of Griffe, a static analysis tool written in Python. Its current bottleneck is compile(), used to build ASTs from source code.

I'm using Ruff's parser, and more specifically its lexer, to prune the body of functions in source code before passing it to compile: I don't ever visit these bodies so I can simply "hide" them when building the AST. That gives a speedup of about 3x for building ASTs on libraries like mypy or Pydantic (that of course depends on the input files).

The thing is, I currently have to vendor ruff_python_parser to make Lexer::current_range and Lexer::current_flags public, in order to be able to replace function bodies with blank lines.

The crux of it:

fn prune(source: &str) -> Option<String> {
    let mut collector = BodyCollector::new(source);
    let mut lexer = lexer::lex(source, Mode::Module);

    loop {
        let kind = lexer.next_token();
        if kind == TokenKind::Unknown {
            return None;
        }

        let range = lexer.current_range();
        collector.consume(Token {
            kind,
            start: range.start().to_usize(),
            end: range.end().to_usize(),
            flags: lexer.current_flags(),
        });

        if kind.is_eof() {
            break;
        }
    }

    let edits = collector.finish();
    if edits.is_empty() {
        None
    } else {
        Some(apply_edits(source, edits))
    }
}

Would you consider making these two symbols public? If not, I'm happy to keep vendoring it, it won't need frequent updates 🙂

Alternatively, do you have any recommendations on how to achieve what I'm doing without relying on these two symbols? Or, maybe do you have general advice on how to make Python's compile() faster ☺️?

Version

No response

Activity

  1. added
    question
    on Sep 8, 2026
  2. MichaReiser commented on Sep 8, 2026

    @MichaReiser
    Member

    Thanks for the kind words and the nice words.

    How do you detect a function body? Do you match based on seeing the first indent after a def keyword?

    In general, our lexer is not intended to be consumed directly. Unlike a lexer described in a classical compiler book, our lexer depends on a feedback loop with the parser to distinguish whether a contextual keywords is a keyword or a name in the current context (relevant for handling match and case). I don't think this matters to you but we may use this mechanism for other language features in the future if necessary. Because of that, I mainly consider our lexer as internal. The only reason lex is public is because it is required for benchmarking 😅

    Having said all this. I don't mind it terribly to make these methods public. Although I'm not sure why you'd need current_flags and I also can't guarantee that these methods will remain public or remain existing in the future.

    If you want to build on slightly more stable API, I'd suggest you to parse the AST, and take the range from the body's first and last statement. Unfortunately, this is likely to be a good deal slower than just lexing because Ruff has to allocate an AST. But I'm not sure if the difference is notable for your use case (it's still pretty fast) and it's likely also more resilient than guessing function bodies from the token stream.

    The other alternative is that you simply copy the entire lexer module. It isn't that much code.

  3. pawamoy commented on Sep 8, 2026

    @pawamoy
    Author

    Thanks!

    How do you detect a function body? Do you match based on seeing the first indent after a def keyword?

    The pruner uses Ruff’s lexer tokens:

    1. A Def token starts a function header.
    2. It finds the header’s terminating : only after the parameter list has closed, accounting for multiline signatures, nested delimiters, and lambda colons in return annotations.
    3. After ::
      • A logical newline followed by Indent starts an indented body.
      • Any other meaningful token starts a same-line body, such as def f(): return 1.
    4. An indented body ends when Ruff emits a Dedent returning below that body’s recorded indentation depth. An inline body ends at the logical Newline.

    If there's a multiline string (triple quoted string) in the middle of the function body, that still works because the string is parsed as a single String token.

    If you want to build on slightly more stable API, I'd suggest you to parse the AST, and take the range from the body's first and last statement.

    Oh, right, that's exactly what I was doing before that, but it felt wasteful to lex+parse in Rust, then tokenize+parse again in Python through compile(). It felt wasteful but it was already a performance improvement. I simply wanted to try and push it even further to maximize the performance gains (to compensate the added but well hidden complexity).

    For reference, the code is here: https://github.com/pawamoy/prune-source/. I used LLM assistance 🙂

  4. pawamoy commented on Sep 8, 2026

    @pawamoy
    Author

    Oh and the pruner uses the flags only to distinguish between "real docstring" and b"not a docstring" (Python doesn't consider byte strings as docstrings). Arguably this is an edge-case and we probably do not need it, but everything can be found in the wild so better be safe.

  5. pawamoy commented on Sep 8, 2026

    @pawamoy
    Author

    Having said all this. I don't mind it terribly to make these methods public. [...] I also can't guarantee that these methods will remain public or remain existing in the future.

    That'd be perfectly fine to me, I don't mind if API stability isn't guaranteed. It will already be super helpful because that means I don't have to vendor the code (keeping it up to date, while patching the two symbols everytime I update, etc.). But again, no worries if you don't think it's worth it, it's totally manageable on my end.

  6. MichaReiser commented on Sep 9, 2026

    @MichaReiser
    Member

    I see. I'm okay making these methods pub (but maybe with doc_hidden).

    I had codex analyze your pruner to see if it depends on any behavior that's driven by the parser and it found two minor bugs.


    A constructor body can be removed. Python normalizes the valid method name 𝒊nit to init. Ruff’s parser performs that normalization (line 442), but the linked pruner compares the raw source spelling. For class C: def 𝒊nit(self): ..., it would prune the constructor body, potentially removing self attributes from the AST Griffe examines. I confirmed with Python’s ast.parse that the method’s name is init. This is a parser-only normalization step, rather than lexer feedback.

    A method body can be retained unnecessarily. In class C: def match(__init__): ..., the lexer emits Match for the method name; the parser accepts it as an identifier (line 518). The pruner only recognizes Name as a definition name, so it mistakes the parameter __init__ for the method name and keeps the body. That loses the intended speedup, but does not itself remove AST information. case has the same issue.

  7. pawamoy commented on Sep 9, 2026

    @pawamoy
    Author

    Thanks a lot! I was able to fix both issues 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    question

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions