MCPcopy Create free account
hub / github.com/astral-sh/ruff / node_range

Method node_range

crates/ruff_python_parser/src/parser/mod.rs:284–341  ·  view source on GitHub ↗
(&self, start: TextSize)

Source from the content-addressed store, hash-verified

282 }
283
284 fn node_range(&self, start: TextSize) -> TextRange {
285 // It's possible during error recovery that the parsing didn't consume any tokens. In that
286 // case, `last_token_end` still points to the end of the previous token but `start` is the
287 // start of the current token. Calling `TextRange::new(start, self.last_token_end)` would
288 // panic in that case because `start > end`. This path "detects" this case and creates an
289 // empty range instead.
290 //
291 // The reason it's `<=` instead of just `==` is because there could be whitespaces between
292 // the two tokens. For example:
293 //
294 // ```python
295 // # last token end
296 // # | current token (newline) start
297 // # v v
298 // def foo \n
299 // # ^
300 // # assume there's trailing whitespace here
301 // ```
302 //
303 // Or, there could tokens that are considered "trivia" and thus aren't emitted by the token
304 // source. These are comments and non-logical newlines. For example:
305 //
306 // ```python
307 // # last token end
308 // # v
309 // def foo # comment\n
310 // # ^ current token (newline) start
311 // ```
312 //
313 // In either of the above cases, there's a "gap" between the end of the last token and start
314 // of the current token.
315 if self.prev_token_end <= start {
316 // We need to create an empty range at the last token end instead of the start because
317 // otherwise this node range will fall outside the range of it's parent node. Taking
318 // the above example:
319 //
320 // ```python
321 // if True:
322 // # function start
323 // # | function end
324 // # v v
325 // def foo # comment
326 // # ^ current token start
327 // ```
328 //
329 // Here, the current token start is the start of parameter range but the function ends
330 // at `foo`. Even if there's a function body, the range of parameters would still be
331 // before the comment.
332
333 // test_err node_range_with_gaps
334 // def foo # comment
335 // def bar(): ...
336 // def baz
337 TextRange::empty(self.prev_token_end)
338 } else {
339 TextRange::new(start, self.prev_token_end)
340 }
341 }

Calls 1

emptyFunction · 0.50

Tested by

no test coverage detected