Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
172 lines
6.2 KiB
Python
172 lines
6.2 KiB
Python
"""Top-level items of a Rust file: where each starts and ends, what it is, and what must change when it moves."""
|
|
from dataclasses import dataclass
|
|
|
|
from .lexer import tokenize
|
|
|
|
OPEN, CLOSE = "{([", "})]"
|
|
BRACE_ITEMS = {"fn", "impl", "trait", "mod", "struct", "enum", "union", "macro_rules", "extern"}
|
|
SEMI_ITEMS = {"use", "const", "static", "type", "crate"}
|
|
|
|
|
|
@dataclass
|
|
class Item:
|
|
start: int # first character carried by the item: the comments and blanks before it
|
|
head: int # first character of the item proper (after attributes and doc comments)
|
|
end: int # one past the last character
|
|
kind: str # fn impl or other
|
|
name: str
|
|
attrs: str # text of the outer attributes
|
|
inherent: bool = False
|
|
|
|
|
|
def significant(tokens):
|
|
return [t for t in tokens if t.kind not in ("ws", "comment")]
|
|
|
|
|
|
def _skip_bracket(sig, k):
|
|
"""Index after the balanced `[ ... ]` group whose `[` is at sig[k]."""
|
|
depth = 0
|
|
while k < len(sig):
|
|
depth += (sig[k].text == "[") - (sig[k].text == "]")
|
|
k += 1
|
|
if depth == 0:
|
|
break
|
|
return k
|
|
|
|
|
|
def _skip_attrs(sig, k):
|
|
"""Index of the first token after the outer attributes starting at k."""
|
|
while k + 1 < len(sig) and sig[k].text == "#" and sig[k + 1].text == "[":
|
|
k = _skip_bracket(sig, k + 1)
|
|
return k
|
|
|
|
|
|
def _skip_visibility(sig, k):
|
|
if sig[k].text != "pub":
|
|
return k
|
|
k += 1
|
|
if sig[k].text == "(":
|
|
while sig[k].text != ")":
|
|
k += 1
|
|
k += 1
|
|
return k
|
|
|
|
|
|
def _keyword(sig, k):
|
|
"""The keyword naming the item whose first token (after attributes and visibility) is sig[k], and its index."""
|
|
while sig[k].text in ("unsafe", "async", "default", "const", "extern"):
|
|
word, nxt = sig[k].text, sig[k + 1]
|
|
if word == "const" and nxt.text not in ("fn", "unsafe", "async", "extern"):
|
|
break
|
|
if word == "extern":
|
|
skip = 2 if nxt.kind == "string" else 1
|
|
if sig[k + skip].text not in ("fn", "unsafe"):
|
|
break
|
|
k += skip
|
|
continue
|
|
k += 1
|
|
return sig[k].text, k
|
|
|
|
|
|
def _ends_with_brace(sig, k, bang_brace):
|
|
"""Index of the last token when the `}` at sig[k] closes a braced item (a macro call may be followed by `;`)."""
|
|
return k + 1 if bang_brace and k + 1 < len(sig) and sig[k + 1].text == ";" else k
|
|
|
|
|
|
def _item_end(sig, k, keyword):
|
|
"""Index in `sig` of the last token of the item whose keyword is at sig[k]."""
|
|
depth, semi_only = 0, keyword in SEMI_ITEMS
|
|
bang_brace = keyword not in BRACE_ITEMS | SEMI_ITEMS and sig[k + 1].text == "!"
|
|
while k < len(sig):
|
|
text = sig[k].text
|
|
depth += (text in OPEN) - (text in CLOSE)
|
|
if depth == 0 and (text == ";" or text == "}" and not semi_only):
|
|
return k if text == ";" else _ends_with_brace(sig, k, bang_brace)
|
|
k += 1
|
|
return len(sig) - 1
|
|
|
|
|
|
def _impl_name(sig, k):
|
|
"""`Foo` for `impl Foo`, `Trait_for_Foo` for `impl<T> path::Trait for path::Foo<T>`: the last identifier of each path."""
|
|
j, depth, before, after, seen_for = k + 1, 0, None, None, False
|
|
while j < len(sig) and sig[j].text not in ("{", "where"):
|
|
depth += (sig[j].text == "<") - (sig[j].text == ">")
|
|
if depth == 0 and sig[j].text == "for":
|
|
seen_for = True
|
|
elif depth == 0 and sig[j].kind == "ident":
|
|
before, after = (before, sig[j].text) if seen_for else (sig[j].text, after)
|
|
j += 1
|
|
if seen_for:
|
|
return f"{before}_for_{after}" if before and after else before or after or "impl"
|
|
return before or "impl"
|
|
|
|
|
|
def _name_of(sig, k, keyword):
|
|
if keyword == "impl":
|
|
return _impl_name(sig, k)
|
|
return sig[k + 1].text if k + 1 < len(sig) and sig[k + 1].kind == "ident" else keyword
|
|
|
|
|
|
def _is_inherent(sig, k, end):
|
|
"""An `impl` is inherent when no `for` appears before its opening brace."""
|
|
for j in range(k, end):
|
|
if sig[j].text == "{":
|
|
return True
|
|
if sig[j].text == "for":
|
|
return False
|
|
return True
|
|
|
|
|
|
def preamble_end(text, tokens):
|
|
"""End of the file header: `//!` docs, `#![...]` inner attributes and the blanks between them."""
|
|
sig = significant(tokens)
|
|
end, k = 0, 0
|
|
for t in tokens:
|
|
if t.kind == "comment" and t.text.startswith(("//!", "/*!")) or t.kind == "ws":
|
|
end = t.end
|
|
elif t.kind != "comment" or t.text.startswith("//"):
|
|
break
|
|
while k + 2 < len(sig) and sig[k].text == "#" and sig[k + 1].text == "!":
|
|
k = _skip_bracket(sig, k + 2)
|
|
end = max(end, sig[k - 1].end)
|
|
return end, k
|
|
|
|
|
|
def parse_items(text):
|
|
"""Top-level items of `text` in order; the text between items is carried by the item that follows it."""
|
|
tokens = tokenize(text)
|
|
sig = significant(tokens)
|
|
previous_end, k = preamble_end(text, tokens)
|
|
items = []
|
|
while k < len(sig):
|
|
attrs_end = _skip_attrs(sig, k)
|
|
if attrs_end >= len(sig):
|
|
break
|
|
keyword, at = _keyword(sig, _skip_visibility(sig, attrs_end))
|
|
last = _item_end(sig, at, keyword)
|
|
kind = keyword if keyword in ("fn", "impl") else "other"
|
|
items.append(Item(previous_end, sig[attrs_end].start, sig[last].end, kind, _name_of(sig, at, keyword),
|
|
text[sig[k].start:sig[attrs_end].start], kind == "impl" and _is_inherent(sig, at, last)))
|
|
previous_end, k = sig[last].end, last + 1
|
|
return items
|
|
|
|
|
|
def cfg_attributes(attrs):
|
|
"""The `#[cfg(...)]` attributes among the outer attributes text, each as written."""
|
|
sig = significant(tokenize(attrs))
|
|
found, k = [], 0
|
|
while k + 1 < len(sig):
|
|
end = _skip_bracket(sig, k + 1) if sig[k].text == "#" and sig[k + 1].text == "[" else k + 1
|
|
if sig[k].text == "#" and k + 2 < len(sig) and sig[k + 2].text == "cfg":
|
|
found.append(attrs[sig[k].start:sig[end - 1].end])
|
|
k = max(end, k + 1)
|
|
return found
|
|
|
|
|
|
def visibility_text(chunk):
|
|
"""The visibility of the item that `chunk` holds, as written: '', 'pub', 'pub(crate)', 'pub(in a::b)' ..."""
|
|
sig = significant(tokenize(chunk))
|
|
first = _skip_attrs(sig, 0)
|
|
after = _skip_visibility(sig, first)
|
|
return chunk[sig[first].start:sig[after].start].strip() if after > first else ""
|