use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::LazyLock;
use tree_sitter::{Language, Node, Parser, Query, QueryCursor, StreamingIterator, Tree};
pub use crate::scheme::SERIALIZATION;
pub struct LangSpec {
pub id: &'static str,
pub extensions: &'static [&'static str],
pub skip_kind: fn(&str) -> bool,
pub span_kind: fn(&str) -> bool,
set_language: fn(&mut Parser) -> bool,
scoping: Scoping,
pub mdx: bool,
template: bool,
}
#[derive(Clone, Copy)]
enum Scoping {
Free,
Query(&'static LazyLock<Query>),
Rust,
Python,
}
macro_rules! lang {
(
$id:ident,
id: $name:literal,
exts: [$($ext:literal),+ $(,)?],
skip: [$($skip:literal),* $(,)?],
span: [$($span:literal),+ $(,)?],
scoping: $scoping:expr,
language: $lang:expr
$(, mdx: $mdx:literal)?
$(, template: $template:literal)?
) => {
pub static $id: LangSpec = LangSpec {
id: $name,
extensions: &[$($ext),+],
skip_kind: |k| [$($skip),*].contains(&k),
span_kind: |k| matches!(k, $($span)|+),
set_language: |parser| parser.set_language(&$lang.into()).is_ok(),
scoping: $scoping,
mdx: false $(|| $mdx)?,
template: false $(|| $template)?,
};
};
}
lang! {
RUST,
id: "rust",
exts: ["rs"],
skip: [
"line_comment",
"block_comment",
"attribute_item",
"inner_attribute_item"
],
span: [
"function_item",
"impl_item",
"const_item",
"static_item",
"mod_item",
"enum_item",
"struct_item",
"trait_item",
"macro_definition",
"closure_expression",
"block",
"field_initializer",
"match_arm"
],
scoping: Scoping::Rust,
language: tree_sitter_rust::LANGUAGE
}
lang! {
PYTHON,
id: "python",
exts: ["py"],
skip: ["comment"],
span: ["function_definition", "class_definition", "decorated_definition", "block"],
scoping: Scoping::Python,
language: tree_sitter_python::LANGUAGE
}
lang! {
JAVASCRIPT,
id: "javascript",
exts: ["js", "jsx", "mjs", "cjs"],
skip: [
"comment",
"html_comment"
],
span: [
"function_declaration",
"generator_function_declaration",
"class_declaration",
"method_definition",
"arrow_function",
"statement_block",
"export_statement",
"lexical_declaration"
],
scoping: Scoping::Query(&JS_LOCALS),
language: tree_sitter_javascript::LANGUAGE
}
lang! {
TYPESCRIPT,
id: "typescript",
exts: ["ts", "mts", "cts"],
skip: [
"comment",
"html_comment"
],
span: [
"function_declaration",
"generator_function_declaration",
"class_declaration",
"method_definition",
"arrow_function",
"statement_block",
"interface_declaration",
"type_alias_declaration",
"enum_declaration",
"export_statement",
"lexical_declaration"
],
scoping: Scoping::Query(&TS_LOCALS),
language: tree_sitter_typescript::LANGUAGE_TYPESCRIPT
}
lang! {
TSX,
id: "tsx",
exts: ["tsx"],
skip: [
"comment",
"html_comment"
],
span: [
"function_declaration",
"generator_function_declaration",
"class_declaration",
"method_definition",
"arrow_function",
"statement_block",
"interface_declaration",
"type_alias_declaration",
"enum_declaration",
"export_statement",
"lexical_declaration"
],
scoping: Scoping::Query(&TSX_LOCALS),
language: tree_sitter_typescript::LANGUAGE_TSX
}
lang! {
HTML,
id: "html",
exts: ["html", "htm"],
skip: ["comment"],
span: ["element", "script_element", "style_element"],
scoping: Scoping::Free,
language: tree_sitter_html::LANGUAGE
}
lang! {
CSS,
id: "css",
exts: ["css"],
skip: ["comment"],
span: ["rule_set", "media_statement", "stylesheet"],
scoping: Scoping::Free,
language: tree_sitter_css::LANGUAGE
}
lang! {
HCL,
id: "hcl",
exts: ["hcl", "tf", "tfvars"],
skip: ["comment"],
span: ["block", "attribute"],
scoping: Scoping::Free,
language: tree_sitter_hcl::LANGUAGE
}
lang! {
BASH,
id: "bash",
exts: ["sh", "bash"],
skip: ["comment"],
span: [
"function_definition",
"compound_statement",
"subshell",
"if_statement",
"do_group",
"case_item"
],
scoping: Scoping::Free,
language: tree_sitter_bash::LANGUAGE
}
lang! {
YAML,
id: "yaml",
exts: ["yaml", "yml"],
skip: ["comment"],
span: ["block_mapping_pair", "block_sequence_item"],
scoping: Scoping::Free,
language: tree_sitter_yaml::LANGUAGE
}
lang! {
CEDAR,
id: "cedar",
exts: ["cedar"],
skip: ["comment"],
span: ["policy", "condition"],
scoping: Scoping::Free,
language: arborium_cedar::language()
}
lang! {
DOCKERFILE,
id: "dockerfile",
exts: ["dockerfile", "containerfile"],
skip: ["comment"],
span: ["source_file"],
scoping: Scoping::Free,
language: tree_sitter_containerfile::LANGUAGE
}
lang! {
PRISMA,
id: "prisma",
exts: ["prisma"],
skip: ["comment", "developer_comment", "block_comment"],
span: [
"model_declaration",
"enum_declaration",
"view_declaration",
"type_declaration",
"datasource_declaration",
"generator_declaration"
],
scoping: Scoping::Free,
language: tree_sitter_prisma::LANGUAGE
}
lang! {
JSONC,
id: "jsonc",
exts: ["jsonc"],
skip: ["comment"],
span: ["object", "array"],
scoping: Scoping::Free,
language: tree_sitter_json::LANGUAGE
}
lang! {
HELM,
id: "yaml",
exts: ["yaml", "yml"],
skip: ["comment"],
span: ["block_mapping_pair", "block_sequence_item"],
scoping: Scoping::Free,
language: tree_sitter_yaml::LANGUAGE,
template: true
}
lang! {
MARKDOWN,
id: "markdown",
exts: ["md", "markdown", "mdx"],
skip: [],
span: ["section", "fenced_code_block", "document"],
scoping: Scoping::Free,
language: tree_sitter_md::LANGUAGE
}
lang! {
MDX,
id: "markdown",
exts: ["mdx"],
skip: [],
span: ["section", "fenced_code_block", "document"],
scoping: Scoping::Free,
language: tree_sitter_md::LANGUAGE,
mdx: true
}
pub static PINNED: &[&LangSpec] = &[
&RUST,
&PYTHON,
&JAVASCRIPT,
&TYPESCRIPT,
&TSX,
&HTML,
&CSS,
&HCL,
&BASH,
&YAML,
&CEDAR,
&DOCKERFILE,
&PRISMA,
&JSONC,
&MARKDOWN,
];
pub fn lang_for_extension(ext: &str) -> Option<&'static LangSpec> {
std::iter::once(&MDX)
.chain(PINNED.iter().copied())
.find(|lang| lang.extensions.contains(&ext))
}
pub fn lang_for_path(path: &Path) -> Option<&'static LangSpec> {
let name = path.file_name()?.to_str()?.to_ascii_lowercase();
if let Some(lang) = lang_for_name(&name) {
return Some(lang);
}
let ext = path.extension()?.to_str()?;
let lang = lang_for_extension(&ext.to_ascii_lowercase())?;
let template = lang.id == "yaml"
&& path
.parent()
.is_some_and(|dir| dir.components().any(|c| c.as_os_str() == "templates"));
Some(if template { &HELM } else { lang })
}
fn lang_for_name(name: &str) -> Option<&'static LangSpec> {
let docker = ["dockerfile", "containerfile"]
.iter()
.any(|base| name == *base || name.starts_with(&format!("{base}.")))
&& !name.ends_with(".dockerignore");
let config = |base: &str| {
name == format!("{base}.json")
|| (name.starts_with(&format!("{base}.")) && name.ends_with(".json"))
};
if docker {
Some(&DOCKERFILE)
} else if config("tsconfig") || config("jsconfig") || name == "deno.json" {
Some(&JSONC)
} else {
None
}
}
#[cfg(test)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SpanDigests {
pub complete: String,
pub shape: String,
}
#[derive(Clone, Copy)]
enum WalkMode {
Complete,
Shape,
Callee,
}
#[cfg(test)]
pub fn mint_span_digests(
lang: &LangSpec,
source: &str,
marker_line: usize,
punch_ranges: &[(usize, usize)],
) -> Option<SpanDigests> {
let tree = parse(lang, source)?;
let (start, end) = span_range(lang, source, &tree, marker_line)?;
if hiding_error_line(source, &tree, start, end).is_some() {
return None;
}
let complete = serialize_range(
lang,
source,
&tree,
(start, end),
(punch_ranges, true),
WalkMode::Complete,
&HashMap::new(),
);
let shape = pin_shape(lang, source, &tree, (start, end), punch_ranges, &|_| None);
Some(SpanDigests {
complete: encode_digest(&complete),
shape: encode_digest(&shape),
})
}
pub(crate) fn parse_source(lang: &LangSpec, source: &str) -> Option<Tree> {
parse(lang, source)
}
#[cfg(test)]
pub fn mint_span_digest(
lang: &LangSpec,
source: &str,
marker_line: usize,
punch_ranges: &[(usize, usize)],
) -> Option<String> {
mint_span_digests(lang, source, marker_line, punch_ranges).map(|d| d.complete)
}
pub fn marker_extents(
lang: &LangSpec,
source: &str,
tree: &Tree,
ends: &crate::marker::Ends,
unmarked: &[bool],
) -> std::collections::BTreeMap<usize, (usize, usize)> {
let mut out = std::collections::BTreeMap::new();
for (idx, line) in source.lines().enumerate() {
if unmarked[idx] || crate::marker::markers_in_line(line).is_empty() {
continue;
}
if let Some(&end_idx) = ends.pairs.get(&idx) {
out.insert(idx, explicit_span(source, idx, end_idx));
continue;
}
if let Some(span) = span_range(lang, source, tree, idx + 1) {
out.insert(idx, span);
}
}
out
}
pub fn literal_lines(lang: &LangSpec, source: &str, tree: &Tree) -> Vec<bool> {
let mut out = Vec::new();
let mut at = 0;
for line in source.split_inclusive('\n') {
let indent = line.len() - line.trim_start().len();
let opens = at + indent;
out.push(line.contains('§') && in_literal(lang, tree, opens));
at += line.len();
}
out
}
pub fn indented_code_lines(source: &str) -> Vec<usize> {
if !source.contains(" ") && !source.contains('\t') {
return Vec::new();
}
let Some(tree) = parse(&MARKDOWN, source) else {
return Vec::new();
};
let mut out = Vec::new();
let mut stack = vec![tree.root_node()];
while let Some(node) = stack.pop() {
if node.kind() == "indented_code_block" {
let (first, end) = (node.start_position(), node.end_position());
let last = if end.column == 0 && end.row > first.row {
end.row - 1
} else {
end.row
};
out.extend(first.row..=last);
continue;
}
stack.extend(node.named_children(&mut node.walk()));
}
out
}
pub fn literal_ranges(lang: &LangSpec, tree: &Tree) -> Vec<(usize, usize)> {
let mut out = Vec::new();
let mut stack = vec![tree.root_node()];
while let Some(node) = stack.pop() {
let kind = node.kind();
if (lang.skip_kind)(kind) && kind.contains("comment") {
continue;
}
if is_literal_kind(lang, kind) {
out.push((node.start_byte(), node.end_byte()));
continue;
}
stack.extend(node.children(&mut node.walk()));
}
out.sort();
out
}
fn is_literal_kind(lang: &LangSpec, kind: &str) -> bool {
let named = ["string", "heredoc", "template"]
.iter()
.any(|k| kind.contains(k));
match lang.id {
"yaml" => {
named
|| matches!(
kind,
"double_quote_scalar" | "single_quote_scalar" | "block_scalar"
)
}
"cedar" => kind == "string",
_ => named,
}
}
fn in_literal(lang: &LangSpec, tree: &Tree, at: usize) -> bool {
let Some(mut node) = tree.root_node().descendant_for_byte_range(at, at + 1) else {
return false;
};
loop {
let kind = node.kind();
if (lang.skip_kind)(kind) && kind.contains("comment") {
return false;
}
if is_literal_kind(lang, kind) {
return true;
}
match node.parent() {
Some(parent) => node = parent,
None => return false,
}
}
}
#[cfg(test)]
pub fn shape_in_span(
lang: &LangSpec,
source: &str,
tree: &Tree,
start: usize,
end: usize,
punch_ranges: &[(usize, usize)],
names: &dyn Fn(usize) -> Option<String>,
) -> String {
pin_shape(lang, source, tree, (start, end), punch_ranges, names)
}
pub fn pin_shape(
lang: &LangSpec,
source: &str,
tree: &Tree,
extent: (usize, usize),
punch_ranges: &[(usize, usize)],
names: &dyn Fn(usize) -> Option<String>,
) -> String {
shape_with(lang, source, tree, extent, punch_ranges, names, false)
}
pub fn callee_shape(
lang: &LangSpec,
source: &str,
tree: &Tree,
start: usize,
end: usize,
names: &dyn Fn(usize) -> Option<String>,
) -> String {
shape_with(lang, source, tree, (start, end), &[], names, true)
}
fn shape_with(
lang: &LangSpec,
source: &str,
tree: &Tree,
(start, end): (usize, usize),
punch_ranges: &[(usize, usize)],
names: &dyn Fn(usize) -> Option<String>,
callee: bool,
) -> String {
let mode = if lang.id == "bash" {
WalkMode::Complete
} else if callee {
WalkMode::Callee
} else {
WalkMode::Shape
};
let around = if callee {
callee_prefix(source, tree, (start, end))
} else {
prefix(lang, source, tree, (start, end))
};
let mut ranges: Vec<Range<'_>> = around
.before
.iter()
.chain(&around.after)
.map(|(s, e, punch)| (*s, *e, punch.as_slice()))
.collect();
ranges.push((start, end, punch_ranges));
let locals = match mode {
WalkMode::Complete => HashMap::new(),
WalkMode::Shape | WalkMode::Callee => {
let binders: Vec<Range<'_>> = around
.unit
.map(|(s, e)| (s, e, &[][..]))
.into_iter()
.collect();
let mut locals = local_numbers(lang, source, tree, &ranges, &binders);
let extent = Extent { ranges: &ranges };
visit(tree.root_node(), None, None, &extent, &mut |node, _, _| {
if node.child_count() == 0 && extent.holds(node) {
if let Some(name) = names(node.start_byte()) {
locals.insert(node.id(), name);
}
}
true
});
locals
}
};
let stretch = |(s, e, punch): &Stretch| {
serialize_range(lang, source, tree, (*s, *e), (punch, false), mode, &locals)
};
let mut out = String::new();
if lang.id == "yaml" {
for step in yaml_path(lang, source, tree, (start, end)) {
out.push_str(&step);
out.push('\n');
}
}
for part in &around.before {
out.push_str(&stretch(part));
out.push('\n');
}
let read = [&around.before, &around.after];
for attr in governing_attributes(lang, source, tree, start, end) {
let (a, b) = (attr.start_byte(), attr.end_byte());
if read
.iter()
.flat_map(|r| r.iter())
.any(|&(s, e, _)| s <= a && b <= e)
{
continue;
}
out.push_str(&serialize_range(
lang,
source,
tree,
(a, b),
(&[], false),
WalkMode::Complete,
&HashMap::new(),
));
out.push('\n');
}
out.push_str(&serialize_range(
lang,
source,
tree,
(start, end),
(punch_ranges, true),
mode,
&locals,
));
for part in &around.after {
out.push('\n');
out.push_str(&stretch(part));
}
if lang.id == "markdown" {
for resolved in reference_resolutions(source, tree, (start, end), punch_ranges) {
out.push('\n');
out.push_str(&resolved);
}
}
out
}
pub fn yaml_duplicate_keys(
lang: &LangSpec,
source: &str,
tree: &Tree,
extents: impl Iterator<Item = (usize, usize)>,
) -> Vec<(usize, usize, String)> {
let mapping = |n: &Node<'_>| matches!(n.kind(), "block_mapping" | "flow_mapping");
let mut mappings: Vec<Node<'_>> = Vec::new();
for (start, end) in extents {
let around = tree.root_node().descendant_for_byte_range(start, end);
mappings.extend(std::iter::successors(around, |n| n.parent()).filter(mapping));
let mut stack: Vec<Node<'_>> = around.into_iter().collect();
while let Some(node) = stack.pop() {
if (start..end).contains(&node.start_byte()) && mapping(&node) {
mappings.push(node);
}
let mut cursor = node.walk();
stack.extend(
node.named_children(&mut cursor)
.filter(|c| c.start_byte() < end && c.end_byte() > start),
);
}
}
mappings.sort_by_key(|n| (n.start_byte(), n.id()));
mappings.dedup_by_key(|n| n.id());
let mut out = Vec::new();
for map in mappings {
let mut seen: HashMap<String, usize> = HashMap::new();
let mut cursor = map.walk();
for key in map
.named_children(&mut cursor)
.filter_map(|pair| pair.child_by_field_name("key"))
{
let read = serialize_range(
lang,
source,
tree,
(key.start_byte(), key.end_byte()),
(&[], false),
WalkMode::Complete,
&HashMap::new(),
);
let line = key.start_position().row + 1;
if let Some(&first) = seen.get(&read) {
let text = key.utf8_text(source.as_bytes()).unwrap_or_default();
out.push((first, line, text.to_string()));
} else {
seen.insert(read, line);
}
}
}
out
}
fn is_scalar_entry(pair: Node<'_>) -> bool {
let Some(value) = pair.child_by_field_name("value") else {
return true;
};
let mut cursor = value.walk();
let scalar = value.named_children(&mut cursor).any(|n| {
matches!(
n.kind(),
"plain_scalar"
| "double_quote_scalar"
| "single_quote_scalar"
| "block_scalar"
| "alias"
)
});
scalar
}
fn yaml_path(
lang: &LangSpec,
source: &str,
tree: &Tree,
(start, end): (usize, usize),
) -> Vec<String> {
let read = |node: Node<'_>| {
serialize_range(
lang,
source,
tree,
(node.start_byte(), node.end_byte()),
(&[], false),
WalkMode::Complete,
&HashMap::new(),
)
};
yaml_above(tree, (start, end))
.into_iter()
.map(|step| match step {
Above::Key(key) => format!("key:{:?}", read(key)),
Above::Entries(entries) => {
let entries: Vec<String> = entries.into_iter().map(read).collect();
format!("entries:{entries:?}")
}
Above::Item { before, .. } => format!("item:{}", before.len()),
})
.collect()
}
enum Above<'a> {
Key(Node<'a>),
Entries(Vec<Node<'a>>),
Item {
sequence: Node<'a>,
item: Node<'a>,
before: Vec<Node<'a>>,
},
}
fn yaml_above(tree: &Tree, (start, end): (usize, usize)) -> Vec<Above<'_>> {
let mut out = Vec::new();
let mut node = tree.root_node().descendant_for_byte_range(start, end);
let mut below: Option<Node<'_>> = None;
while let Some(current) = node {
node = current.parent();
let inner = below.replace(current);
if (current.start_byte(), current.end_byte()) == (start, end) {
continue;
}
let members = |kinds: &[&str]| {
let mut cursor = current.walk();
current
.named_children(&mut cursor)
.filter(|n| kinds.contains(&n.kind()))
.collect::<Vec<_>>()
};
match current.kind() {
"block_mapping_pair" | "flow_pair" => {
if let Some(key) = current
.child_by_field_name("key")
.filter(|key| key.end_byte() <= start)
{
out.push(Above::Key(key));
}
}
"block_mapping" | "flow_mapping" => {
let entries = members(&["block_mapping_pair", "flow_pair"])
.into_iter()
.filter(|n| n.end_byte() <= start || n.start_byte() >= end)
.filter(|n| is_scalar_entry(*n))
.collect();
out.push(Above::Entries(entries));
}
"block_sequence" | "flow_sequence" => {
let kind = if current.kind() == "flow_sequence" {
"flow_node"
} else {
"block_sequence_item"
};
let Some(item) = inner
.filter(|n| n.kind() == kind)
.filter(|n| (n.start_byte(), n.end_byte()) != (start, end))
else {
continue;
};
let before = members(&[kind])
.into_iter()
.take_while(|n| n.end_byte() <= item.start_byte())
.collect();
out.push(Above::Item {
sequence: current,
item,
before,
});
}
_ => {}
}
}
out.reverse();
out
}
fn yaml_stretches(tree: &Tree, extent: (usize, usize)) -> Vec<Stretch> {
let whole = |n: Node<'_>| (n.start_byte(), n.end_byte(), Vec::new());
let mut out = Vec::new();
for step in yaml_above(tree, extent) {
match step {
Above::Key(key) => out.push(whole(key)),
Above::Entries(entries) => out.extend(entries.into_iter().map(whole)),
Above::Item {
sequence,
item,
before,
} => {
let body = |n: Node<'_>| match n.kind() {
"block_sequence_item" => (
n.child(0).map_or(n.start_byte(), |d| d.end_byte()),
n.end_byte(),
),
_ => (n.start_byte(), n.end_byte()),
};
let punch = before.into_iter().map(body).collect();
if sequence.start_byte() < item.start_byte() {
out.push((sequence.start_byte(), item.start_byte(), punch));
}
}
}
}
out
}
#[cfg(test)]
pub fn parse_error_line(tree: &Tree, start: usize, end: usize) -> Option<usize> {
fn find(node: Node<'_>, start: usize, end: usize) -> Option<usize> {
let (s, e) = (node.start_byte(), node.end_byte());
let touches = if s == e {
start <= s && s <= end
} else {
s < end && e > start
};
if !touches || !node.has_error() {
return None;
}
if node.is_error() || node.is_missing() {
return Some(node.start_position().row + 1);
}
let mut cursor = node.walk();
let children: Vec<_> = node.children(&mut cursor).collect();
children
.into_iter()
.find_map(|child| find(child, start, end))
}
find(tree.root_node(), start, end)
}
pub fn hiding_error_line(source: &str, tree: &Tree, start: usize, end: usize) -> Option<usize> {
let root = tree.root_node();
if !root.has_error() {
return None;
}
let line = |node: Node<'_>| node.start_position().row + 1;
if root.is_error() || root.is_missing() {
return Some(line(root));
}
let mut cursor = root.walk();
let items: Vec<Node<'_>> = root.children(&mut cursor).collect();
items.into_iter().find_map(|item| {
if item.is_error() || item.is_missing() {
return Some(line(item));
}
let overlaps = item.start_byte() < end && start < item.end_byte();
first_error(item, &|node| overlaps || swallows(source, item, node)).map(line)
})
}
pub fn swallowing_items(source: &str, tree: &Tree) -> Vec<(usize, usize, usize)> {
let root = tree.root_node();
if !root.has_error() {
return Vec::new();
}
let line = |node: Node<'_>| node.start_position().row + 1;
if root.is_error() || root.is_missing() {
return vec![(root.start_byte(), root.end_byte(), line(root))];
}
let mut cursor = root.walk();
let items: Vec<Node<'_>> = root.children(&mut cursor).collect();
items
.into_iter()
.filter_map(|item| {
let at = match item.is_error() || item.is_missing() {
true => item,
false => first_error(item, &|node| swallows(source, item, node))?,
};
Some((item.start_byte(), item.end_byte(), line(at)))
})
.collect()
}
fn first_error<'a>(node: Node<'a>, keep: &dyn Fn(Node<'a>) -> bool) -> Option<Node<'a>> {
if !node.has_error() {
return None;
}
if node.is_error() || node.is_missing() {
return keep(node).then_some(node);
}
let mut cursor = node.walk();
let children: Vec<Node<'a>> = node.children(&mut cursor).collect();
children
.into_iter()
.find_map(|child| first_error(child, keep))
}
fn swallows(source: &str, item: Node<'_>, node: Node<'_>) -> bool {
if node.is_missing() && node.end_byte() >= item.end_byte() {
return true;
}
let bytes = source.as_bytes();
let indent = |from: usize| {
bytes[from..]
.iter()
.take_while(|b| matches!(b, b' ' | b'\t'))
.count()
};
let (start, end) = (node.start_byte(), node.end_byte().min(bytes.len()));
let own = indent(
bytes[..start]
.iter()
.rposition(|b| *b == b'\n')
.map_or(0, |i| i + 1),
);
let top = item.start_position().column;
(start..end)
.filter(|&i| bytes[i] == b'\n')
.map(|i| i + 1)
.any(|from| {
let depth = indent(from);
from + depth < end
&& !matches!(bytes[from + depth], b'\n' | b'\r')
&& (depth < own || depth <= top)
&& !is_conflict_marker(&source[from..])
})
}
pub fn is_conflict_marker(text: &str) -> bool {
let line = text.split('\n').next().unwrap_or_default();
let line = line.strip_suffix('\r').unwrap_or(line);
let labelled = |marker: &str| {
line.strip_prefix(marker)
.is_some_and(|rest| rest.is_empty() || rest.starts_with(' '))
};
line == "=======" || ["<<<<<<<", "|||||||", ">>>>>>>"].into_iter().any(labelled)
}
pub fn span_is_empty(
lang: &LangSpec,
source: &str,
tree: &Tree,
(start, end): (usize, usize),
punch: &[(usize, usize)],
) -> bool {
fn holds(
lang: &LangSpec,
source: &str,
node: Node<'_>,
(start, end): (usize, usize),
punch: &[(usize, usize)],
) -> bool {
if node.end_byte() <= start
|| node.start_byte() >= end
|| (lang.skip_kind)(node.kind())
|| punched_out(node, punch)
{
return false;
}
let markdown = lang.id == "markdown";
if markdown && matches!(node.kind(), "atx_heading" | "setext_heading") {
return false;
}
if markdown && node.kind() == "html_block" {
let text = source[node.start_byte()..node.end_byte()].trim();
if text.starts_with("<!--") && text.ends_with("-->") {
return false;
}
}
if lang.mdx && is_mdx_comment(source, node) {
return false;
}
let leaf = node.named_child_count() == 0 && !(lang.span_kind)(node.kind());
let own = node.start_byte() >= start
&& node.end_byte() <= end
&& ((node.start_byte(), node.end_byte()) != (start, end) || leaf)
&& !(markdown && node.kind() == "section");
if own && node.is_named() {
return true;
}
let mut cursor = node.walk();
let found = node
.children(&mut cursor)
.any(|child| holds(lang, source, child, (start, end), punch));
found
}
!holds(lang, source, tree.root_node(), (start, end), punch)
}
pub fn only_called_names(
lang: &LangSpec,
source: &str,
tree: &Tree,
(start, end): (usize, usize),
punch: &[(usize, usize)],
) -> Option<Vec<String>> {
fn statements<'t>(
lang: &LangSpec,
node: Node<'t>,
(start, end): (usize, usize),
punch: &[(usize, usize)],
out: &mut Vec<Node<'t>>,
) {
let block = matches!(
node.kind(),
"block"
| "source_file"
| "declaration_list"
| "module"
| "statement_block"
| "program"
| "class_body"
| "switch_case"
| "switch_default"
);
let mut cursor = node.walk();
for child in node.named_children(&mut cursor) {
let (s, e) = (child.start_byte(), child.end_byte());
if e <= start || s >= end || (lang.skip_kind)(child.kind()) || punched_out(child, punch)
{
continue;
}
let holds_span = s <= start && e >= end && (s, e) != (start, end);
if block && !holds_span {
out.push(child);
} else {
statements(lang, child, (start, end), punch, out);
}
}
}
fn named<'t>(node: Node<'t>) -> Vec<Node<'t>> {
let mut cursor = node.walk();
node.named_children(&mut cursor)
.filter(|child| !child.kind().contains("comment"))
.collect()
}
fn call_of(node: Node<'_>) -> Option<Node<'_>> {
match node.kind() {
"call_expression" | "call" => Some(node),
"expression_statement"
| "return_statement"
| "return_expression"
| "try_expression"
| "await_expression"
| "await"
| "parenthesized_expression" => match named(node).as_slice() {
[only] => call_of(*only),
_ => None,
},
_ => None,
}
}
fn decides(node: Node<'_>) -> bool {
match node.kind() {
"identifier"
| "self"
| "this"
| "super"
| "field_identifier"
| "property_identifier"
| "private_property_identifier"
| "scoped_identifier"
| "shorthand_property_identifier"
| "nested_identifier" => false,
"call_expression"
| "call"
| "arguments"
| "argument_list"
| "field_expression"
| "member_expression"
| "attribute"
| "reference_expression"
| "spread_element"
| "list_splat"
| "dictionary_splat"
| "keyword_argument"
| "non_null_expression"
| "parenthesized_expression"
| "await_expression"
| "await"
| "try_expression" => named(node).into_iter().any(decides),
_ => true,
}
}
if !matches!(
lang.id,
"rust" | "python" | "javascript" | "typescript" | "tsx"
) {
return None;
}
let mut found = Vec::new();
statements(lang, tree.root_node(), (start, end), punch, &mut found);
if found.is_empty() {
return None;
}
found
.iter()
.map(|node| {
let call = call_of(*node).filter(|call| !decides(*call))?;
callee_name(call, source).map(str::to_string)
})
.collect()
}
fn callee_name<'s>(call: Node<'_>, source: &'s str) -> Option<&'s str> {
let mut callee = call.child_by_field_name("function")?;
loop {
let name = match callee.kind() {
"member_expression" => callee.child_by_field_name("property"),
"field_expression" => callee.child_by_field_name("field"),
"attribute" => callee.child_by_field_name("attribute"),
"scoped_identifier" => callee.child_by_field_name("name"),
"generic_function" => {
callee = callee.child_by_field_name("function")?;
continue;
}
_ => Some(callee),
}?;
return name.utf8_text(source.as_bytes()).ok();
}
}
pub fn span_bytes(
lang: &LangSpec,
path: &Path,
source: &str,
marker_line: usize,
) -> Option<(usize, usize)> {
let idx = marker_line.checked_sub(1)?;
let tree = parse(lang, source);
let unmarked = crate::span::unmarked_lines(path, source, tree.as_ref());
if let Some(&end_idx) = crate::marker::explicit_ends_in(&unmarked, source)
.pairs
.get(&idx)
{
return Some(explicit_span(source, idx, end_idx));
}
span_range(lang, source, &tree?, marker_line)
}
pub fn construct_below(
lang: &LangSpec,
source: &str,
tree: &Tree,
marker_line: usize,
) -> Option<(usize, Option<usize>)> {
let comment = node_on_line(lang, source, tree, marker_line)?;
let mut next = comment.next_named_sibling();
while let Some(n) = next.filter(|n| (lang.skip_kind)(n.kind())) {
next = n.next_named_sibling();
}
let mut node = next?;
if lang.id == "hcl" && node.kind() == "body" {
node = node.named_child(0)?;
}
let kind = node.kind();
let bound = match kind {
"export_statement" => node.child_by_field_name("declaration").unwrap_or(node),
_ => node,
};
let binds = binds_a_name(lang, bound);
if !((lang.span_kind)(kind)
|| is_function_kind(lang, kind)
|| is_header_kind(lang, kind)
|| binds)
{
return None;
}
let bodiless = binds && body_of(bound).is_none();
Some((
node.start_position().row + 1,
bodiless.then(|| node.end_position().row + 1),
))
}
fn binds_a_name(lang: &LangSpec, node: Node<'_>) -> bool {
let first = node.named_child(0).map(|c| c.kind()).unwrap_or("");
match (lang.id, node.kind()) {
("rust", kind) => matches!(kind, "const_item" | "static_item"),
("python", "expression_statement") => {
matches!(first, "assignment" | "augmented_assignment")
}
("python", kind) => kind == "type_alias_statement",
("javascript" | "typescript" | "tsx", "expression_statement") => {
matches!(
first,
"assignment_expression" | "augmented_assignment_expression"
)
}
("javascript" | "typescript" | "tsx", kind) => {
matches!(kind, "variable_declaration" | "lexical_declaration")
}
("bash", kind) => matches!(kind, "variable_assignment" | "declaration_command"),
("hcl", kind) => kind == "attribute",
_ => false,
}
}
fn span_range(
lang: &LangSpec,
source: &str,
tree: &Tree,
marker_line: usize,
) -> Option<(usize, usize)> {
let line = source.lines().nth(marker_line.checked_sub(1)?)?;
if let Some(entry) = macro_entry(lang, source, tree, marker_line) {
return entry;
}
if crate::marker::is_one(line) || spans_below(lang) {
return one_span(lang, source, tree, marker_line);
}
if matches!(lang.id, "tsx" | "javascript") && line.trim_start().starts_with("{/*") {
return one_span(lang, source, tree, marker_line);
}
if lang.id == "markdown" {
return markdown_section(source, tree, marker_line);
}
match span_node(lang, source, tree, marker_line) {
Some(span) => Some((span.start_byte(), span.end_byte())),
None => top_function(lang, source, tree, marker_line),
}
}
fn macro_entry(
lang: &LangSpec,
source: &str,
tree: &Tree,
marker_line: usize,
) -> Option<Option<(usize, usize)>> {
if lang.id != "rust" {
return None;
}
let comment = node_on_line(lang, source, tree, marker_line)?;
if !(lang.skip_kind)(comment.kind()) || comment.parent()?.kind() != "token_tree" {
return None;
}
let (mut first, mut last, mut arrow) = (None, None, false);
let mut next = comment.next_sibling();
while let Some(token) = next {
next = token.next_sibling();
if (lang.skip_kind)(token.kind()) {
continue;
}
if next.is_none() || matches!(token.kind(), "," | ";") {
break;
}
first.get_or_insert(token.start_byte());
last = Some(token.end_byte());
let group = token.kind() == "token_tree" && source[token.start_byte()..].starts_with('{');
if arrow && group {
break;
}
arrow = token.kind() == "=>";
}
Some(first.zip(last))
}
fn spans_below(lang: &LangSpec) -> bool {
matches!(lang.id, "yaml" | "dockerfile")
}
fn top_function(
lang: &LangSpec,
source: &str,
tree: &Tree,
marker_line: usize,
) -> Option<(usize, usize)> {
let (start, end) = one_span(lang, source, tree, marker_line)?;
let mut node = tree
.root_node()
.descendant_for_byte_range(end.saturating_sub(1), end.saturating_sub(1))?;
while let Some(parent) = node
.parent()
.filter(|p| p.end_byte() == end && p.start_byte() >= start)
{
node = parent;
}
let function = |n: Node<'_>| {
matches!(
n.kind(),
"function_item"
| "function_definition"
| "function_declaration"
| "generator_function_declaration"
)
};
let named = |n: Node<'_>, field: &str| n.child_by_field_name(field).is_some_and(function);
let holds = function(node)
|| (lang.id == "cedar" && node.kind() == "policy")
|| (node.kind() == "decorated_definition" && named(node, "definition"))
|| (node.kind() == "export_statement" && named(node, "declaration"));
holds.then_some((start, end))
}
fn holds_members(lang: &LangSpec, kind: &str) -> bool {
match lang.id {
"rust" => matches!(
kind,
"source_file"
| "block"
| "declaration_list"
| "field_declaration_list"
| "ordered_field_declaration_list"
| "enum_variant_list"
| "match_block"
| "arguments"
| "field_initializer_list"
| "array_expression"
),
"python" => matches!(
kind,
"module" | "block" | "argument_list" | "dictionary" | "list" | "set"
),
"javascript" | "typescript" | "tsx" => matches!(
kind,
"program"
| "statement_block"
| "class_body"
| "switch_body"
| "switch_case"
| "switch_default"
| "object"
| "arguments"
| "array"
| "object_type"
| "interface_body"
| "enum_body"
| "jsx_element"
),
"html" => matches!(kind, "document" | "element"),
"css" => matches!(kind, "stylesheet" | "block"),
"hcl" => matches!(kind, "body"),
"yaml" => matches!(
kind,
"block_mapping" | "block_sequence" | "flow_mapping" | "flow_sequence"
),
"cedar" => matches!(kind, "policy_set" | "condition"),
"dockerfile" => kind == "source_file",
"prisma" => matches!(kind, "program" | "statement_block" | "enum_block"),
"jsonc" => matches!(kind, "object" | "array"),
"bash" => matches!(
kind,
"program" | "compound_statement" | "do_group" | "case_statement"
),
"markdown" => matches!(kind, "document" | "section"),
_ => false,
}
}
fn one_span(
lang: &LangSpec,
source: &str,
tree: &Tree,
marker_line: usize,
) -> Option<(usize, usize)> {
let at = line_to_byte(source, marker_line)?;
let at = at + (source[at..].len() - source[at..].trim_start().len());
let mut comment = tree.root_node().descendant_for_byte_range(at, at + 1)?;
let is_comment = |n: Node<'_>| {
if lang.id == "markdown" {
(n.kind() == "html_block" && source[n.start_byte()..].trim_start().starts_with("<!--"))
|| (lang.mdx && is_mdx_comment(source, n))
} else {
(n.kind() != "attribute_item" && (lang.skip_kind)(n.kind())) || is_jsx_comment(lang, n)
}
};
while !is_comment(comment) {
comment = comment.parent()?;
}
if comment.start_position().row + 1 != marker_line {
return None;
}
if lang.id == "yaml" {
let member = yaml_member_below(tree, comment.end_byte())?;
return Some((member.start_byte(), yaml_member_end(source, member)));
}
let mut next = comment.next_named_sibling();
let mut first = None;
let blank_text = |n: Node<'_>| {
n.kind() == "jsx_text"
&& n.utf8_text(source.as_bytes())
.is_ok_and(|t| t.trim().is_empty())
};
while let Some(n) =
next.filter(|n| (lang.skip_kind)(n.kind()) || is_comment(*n) || blank_text(*n))
{
if n.kind() == "attribute_item" {
first.get_or_insert(n.start_byte());
}
next = n.next_named_sibling();
}
let mut node = next?;
let mut parent = comment.parent()?;
if matches!(
(lang.id, node.kind()),
("python", "block") | ("hcl", "body")
) && first.is_none()
{
parent = node;
node = node.named_child(0)?;
}
let ends_construct = match lang.id {
"markdown" => matches!(node.kind(), "section" | "atx_heading" | "setext_heading"),
"html" => node.kind() == "end_tag",
"tsx" | "javascript" if parent.kind() == "jsx_element" => !matches!(
node.kind(),
"jsx_element" | "jsx_self_closing_element" | "jsx_expression"
),
_ => false,
};
if ends_construct || !holds_members(lang, parent.kind()) {
return None;
}
Some((first.unwrap_or(node.start_byte()), node.end_byte()))
}
fn yaml_member_below(tree: &Tree, after: usize) -> Option<Node<'_>> {
let member = |n: Node<'_>| match n.kind() {
"block_mapping_pair" | "block_sequence_item" => true,
"flow_pair" => n.parent().is_some_and(|p| p.kind() == "flow_mapping"),
"flow_node" => n.parent().is_some_and(|p| p.kind() == "flow_sequence"),
_ => false,
};
let mut stack = vec![tree.root_node()];
while let Some(node) = stack.pop() {
if node.end_byte() <= after {
continue;
}
if node.start_byte() >= after && member(node) {
return Some(node);
}
let mut cursor = node.walk();
let children: Vec<Node<'_>> = node.named_children(&mut cursor).collect();
stack.extend(children.into_iter().rev());
}
None
}
fn yaml_member_end(source: &str, member: Node<'_>) -> usize {
let comment = |n: &Node<'_>| n.kind() == "comment" && source[n.start_byte()..].starts_with('#');
let mut end = member.start_byte();
let mut stack = vec![member];
while let Some(node) = stack.pop() {
if comment(&node) {
continue;
}
let mut cursor = node.walk();
let inner: Vec<Node<'_>> = node.children(&mut cursor).filter(|n| !comment(n)).collect();
let scalar = matches!(
node.kind(),
"plain_scalar" | "double_quote_scalar" | "single_quote_scalar" | "block_scalar"
);
if inner.is_empty() || scalar {
end = end.max(node.end_byte());
} else {
stack.extend(inner);
}
}
end
}
fn markdown_section(source: &str, tree: &Tree, marker_line: usize) -> Option<(usize, usize)> {
fn headings(node: Node<'_>, out: &mut Vec<(usize, usize)>) {
let mut cursor = node.walk();
for child in node.named_children(&mut cursor) {
match child.kind() {
"section" => headings(child, out),
"atx_heading" | "setext_heading" => {
let mut cursor = child.walk();
let level = child.named_children(&mut cursor).find_map(|m| {
let kind = m.kind();
kind.strip_prefix("atx_h")
.or_else(|| kind.strip_prefix("setext_h"))
.and_then(|rest| rest.chars().next()?.to_digit(10))
});
if let Some(level) = level {
out.push((child.start_byte(), level as usize));
}
}
_ => {}
}
}
}
let root = tree.root_node();
let at = line_to_byte(source, marker_line)?;
let mut all = Vec::new();
headings(root, &mut all);
let Some(owner) = all.iter().rposition(|&(start, _)| start <= at) else {
return Some((root.start_byte(), root.end_byte()));
};
let (start, level) = all[owner];
let end = all[owner + 1..]
.iter()
.find(|&&(_, next)| next <= level)
.map_or(root.end_byte(), |&(next, _)| next);
Some((start, end))
}
fn explicit_span(source: &str, idx: usize, end_idx: usize) -> (usize, usize) {
let start = line_to_byte(source, idx + 1).unwrap_or(source.len());
let end = line_to_byte(source, end_idx + 2).unwrap_or(source.len());
(start, end)
}
pub const MAX_DEPTH: usize = 10_000;
fn parse(lang: &LangSpec, source: &str) -> Option<Tree> {
let mut parser = Parser::new();
if !(lang.set_language)(&mut parser) {
return None;
}
let shadow = match lang.id {
"rust" => unraw(source),
"typescript" | "tsx" => untype_tags(source),
"yaml" if lang.template => untemplate(source),
"jsonc" => untrail(source),
_ => None,
};
let mut tree = parser.parse(shadow.as_deref().unwrap_or(source), None)?;
if lang.id == "bash" && tree.root_node().has_error() {
if let Some(shadow) = unbase(source, &tree) {
tree = parser.parse(&shadow, None)?;
}
}
(depth(&tree) <= MAX_DEPTH).then_some(tree)
}
fn unbase(source: &str, tree: &Tree) -> Option<String> {
let bytes = source.as_bytes();
let mut shadow: Option<String> = None;
let mut stack = vec![tree.root_node()];
while let Some(node) = stack.pop() {
if !node.has_error() {
continue;
}
let text = &source[node.start_byte()..node.end_byte()];
let base = text
.strip_suffix('#')
.is_some_and(|digits| !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()));
let at = node.end_byte();
let named = bytes
.get(at + 1)
.is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_');
if node.is_error() && base && bytes.get(at) == Some(&b'$') && named {
shadow
.get_or_insert_with(|| source.to_string())
.replace_range(at..at + 1, "0");
}
stack.extend(node.children(&mut node.walk()));
}
shadow
}
fn depth(tree: &Tree) -> usize {
let mut cursor = tree.walk();
let (mut at, mut deepest) = (0, 0);
loop {
deepest = deepest.max(at);
if cursor.goto_first_child() {
at += 1;
continue;
}
while !cursor.goto_next_sibling() {
if !cursor.goto_parent() {
return deepest;
}
at -= 1;
}
}
}
static RAW_BORROW: LazyLock<regex::Regex> =
LazyLock::new(|| regex::Regex::new(r"&\s*(raw)\b(\s*(?:const|mut)\b)?").expect("raw borrow"));
fn unraw(source: &str) -> Option<String> {
let mut shadow: Option<String> = None;
for caps in RAW_BORROW.captures_iter(source) {
if caps.get(2).is_some() {
continue;
}
let name = caps.get(1).expect("raw");
shadow
.get_or_insert_with(|| source.to_string())
.replace_range(name.range(), "rAw");
}
shadow
}
fn template_actions(source: &str) -> Vec<(usize, usize)> {
let bytes = source.as_bytes();
let mut out = Vec::new();
let mut at = 0;
'actions: while let Some(rel) = source[at..].find("{{") {
let start = at + rel;
let mut i = start + 2;
while i < bytes.len() {
match bytes[i] {
b'}' if bytes.get(i + 1) == Some(&b'}') => {
out.push((start, i + 2));
at = i + 2;
continue 'actions;
}
quote @ (b'"' | b'\'' | b'`') => {
i += 1;
while i < bytes.len() && bytes[i] != quote {
i += if bytes[i] == b'\\' && quote != b'`' {
2
} else {
1
};
}
}
b'/' if bytes.get(i + 1) == Some(&b'*') => {
let Some(close) = source[i + 2..].find("*/") else {
break 'actions;
};
i += close + 3;
}
_ => {}
}
i += 1;
}
break;
}
out
}
fn untemplate(source: &str) -> Option<String> {
let actions = template_actions(source);
if actions.is_empty() {
return None;
}
let in_action = |at: usize| {
let next = actions.partition_point(|&(_, end)| end <= at);
actions.get(next).is_some_and(|&(start, _)| start <= at)
};
let mut shadow = String::with_capacity(source.len());
for line in source.split_inclusive('\n') {
let at = shadow.len();
let text = line.trim_end_matches(['\n', '\r']);
let mut code = text
.char_indices()
.filter(|(_, c)| !c.is_whitespace())
.map(|(i, _)| at + i)
.peekable();
let first = code.peek().copied();
let alone = first.is_some() && code.all(in_action);
for (i, c) in text.char_indices() {
if alone && Some(at + i) == first {
shadow.push('#');
shadow.push_str(&" ".repeat(c.len_utf8() - 1));
} else if !alone && in_action(at + i) {
shadow.push_str(&"x".repeat(c.len_utf8()));
} else {
shadow.push(c);
}
}
shadow.push_str(&line[text.len()..]);
}
Some(shadow)
}
fn untrail(source: &str) -> Option<String> {
let bytes = source.as_bytes();
let mut trailing = Vec::new();
let mut comma = None;
let mut i = 0;
while i < bytes.len() {
let rest = &bytes[i..];
let skip = if rest.starts_with(b"//") {
rest.iter().position(|&b| b == b'\n').unwrap_or(rest.len())
} else if rest.starts_with(b"/*") {
rest[2..]
.windows(2)
.position(|w| w == b"*/")
.map_or(rest.len(), |end| end + 4)
} else if rest[0] == b'"' {
let mut end = 1;
while end < rest.len() && rest[end] != b'"' {
end += if rest[end] == b'\\' { 2 } else { 1 };
}
comma = None;
end + 1
} else {
match bytes[i] {
b',' => comma = Some(i),
b'}' | b']' => trailing.extend(comma.take()),
b if b.is_ascii_whitespace() => {}
_ => comma = None,
}
1
};
i += skip;
}
if trailing.is_empty() {
return None;
}
let mut shadow = source.to_string();
for at in trailing {
shadow.replace_range(at..at + 1, " ");
}
Some(shadow)
}
static TYPED_TAG: LazyLock<regex::Regex> = LazyLock::new(|| {
let braced = r#"\{(?:[^{}`]|\{[^{}`]*\})*\}"#;
let arg = format!(r#"(?:[^<>()`'"=;{{}}]|{braced})"#);
regex::Regex::new(&format!(
r"[\w$)\]](<{arg}*(?:<{arg}*(?:<{arg}*>{arg}*)*>{arg}*)*>)\s*`"
))
.expect("typed tag")
});
fn untype_tags(source: &str) -> Option<String> {
let mut shadow: Option<String> = None;
for caps in TYPED_TAG.captures_iter(source) {
let args = caps.get(1).expect("type arguments");
let blank: String = args
.as_str()
.chars()
.map(|c| match c {
'\n' | '\r' => c.to_string(),
_ => " ".repeat(c.len_utf8()),
})
.collect();
shadow
.get_or_insert_with(|| source.to_string())
.replace_range(args.range(), &blank);
}
shadow
}
fn typed_tag_args(lang: &LangSpec, source: &str, from: usize, to: usize) -> Option<(usize, usize)> {
if !matches!(lang.id, "typescript" | "tsx") || !source[from..to].contains('<') {
return None;
}
let before = source[..from]
.char_indices()
.next_back()
.map_or(0, |(at, _)| at);
let args = TYPED_TAG.captures_at(source, before)?.get(1)?;
(args.start() >= from && args.end() <= to).then(|| (args.start(), args.end()))
}
fn span_node<'a>(
lang: &LangSpec,
source: &str,
tree: &'a Tree,
marker_line: usize,
) -> Option<Node<'a>> {
let mut node = node_on_line(lang, source, tree, marker_line)?;
if let Some(block) = python_leading_block(lang, node) {
return Some(block);
}
loop {
if (lang.span_kind)(node.kind()) {
return Some(node);
}
node = node.parent()?;
}
}
fn python_leading_block<'a>(lang: &LangSpec, node: Node<'a>) -> Option<Node<'a>> {
if lang.id != "python" || node.kind() != "comment" {
return None;
}
let mut next = node.next_sibling();
while let Some(sibling) = next {
match sibling.kind() {
"comment" => next = sibling.next_sibling(),
"block" => return Some(sibling),
_ => return None,
}
}
None
}
fn node_on_line<'a>(
lang: &LangSpec,
source: &str,
tree: &'a Tree,
marker_line: usize,
) -> Option<Node<'a>> {
let start = line_to_byte(source, marker_line)?;
let end = line_to_byte(source, marker_line + 1)
.unwrap_or(source.len())
.max(start + 1);
let end = end.min(source.len());
let root = tree.root_node();
let mut node = root.descendant_for_byte_range(start, end)?;
loop {
if (lang.skip_kind)(node.kind()) {
break;
}
let mut cursor = node.walk();
let child = node
.children(&mut cursor)
.find(|c| c.start_position().row + 1 == marker_line);
match child {
Some(c) if c.id() != node.id() => node = c,
_ => break,
}
}
Some(node)
}
fn serialize_range(
lang: &LangSpec,
source: &str,
tree: &Tree,
(start, end): (usize, usize),
(punch, holes): (&[(usize, usize)], bool),
mode: WalkMode,
locals: &HashMap<usize, String>,
) -> String {
let mut parts = Vec::new();
let mut walk = Walk {
lang,
source,
start,
end,
punch,
mode,
locals,
keep_types: false,
literal: false,
holes: vec![!holes; punch.len()],
out: &mut parts,
};
walk_node(&mut walk, tree.root_node(), None);
drop_trailing_holes(&mut parts);
parts.join("\n")
}
fn drop_trailing_holes(parts: &mut Vec<String>) {
let closes = |part: &str| matches!(part, CLOSE | "}:}" | "):)" | "]:]" | "gap:");
let mut at = parts.len();
while at > 0 {
at -= 1;
if parts[at] == "hole" {
parts.remove(at);
} else if !closes(&parts[at]) {
break;
}
}
}
const TYPE_FIELDS: &[&str] = &[
"type",
"return_type",
"type_parameters",
"type_arguments",
"type_annotation",
];
const KEPT_TYPES: &[(&str, &str)] = &[
("generic_function", "type_arguments"),
("scoped_identifier", "path"),
("scoped_type_identifier", "path"),
("struct_expression", "name"),
("struct_pattern", "type"),
("tuple_struct_pattern", "type"),
("type_cast_expression", "type"),
("type_alias_statement", "left"),
("type_alias_statement", "right"),
];
fn keeps_type(parent: &str, field: &str) -> bool {
KEPT_TYPES.contains(&(parent, field))
}
fn erases_types(lang: &LangSpec) -> bool {
!matches!(lang.id, "rust" | "python")
}
struct Walk<'a> {
lang: &'a LangSpec,
source: &'a str,
start: usize,
end: usize,
punch: &'a [(usize, usize)],
mode: WalkMode,
locals: &'a HashMap<usize, String>,
keep_types: bool,
literal: bool,
holes: Vec<bool>,
out: &'a mut Vec<String>,
}
type Step<'a> = (Node<'a>, Option<&'a str>);
const CLOSE: &str = ".";
fn walk_node<'a>(walk: &mut Walk<'a>, node: Node<'a>, field: Option<&'a str>) {
if node.end_byte() <= walk.start || node.start_byte() >= walk.end {
return;
}
if let Some(at) = punch_holding(node, walk.punch) {
hole(walk, at);
return;
}
let kind = node.kind();
if node.is_missing() {
walk.out.push(format!("MISSING:{kind}"));
return;
}
if node.is_error() {
let text = node.utf8_text(walk.source.as_bytes()).unwrap_or("");
walk.out.push(format!("ERROR:{:?}", lf(text)));
return;
}
if walk.lang.template && kind == "comment" && !walk.source[node.start_byte()..].starts_with('#')
{
let text = node.utf8_text(walk.source.as_bytes()).unwrap_or("");
walk.out.push(format!("action:{:?}", lf(text)));
return;
}
if (walk.lang.skip_kind)(kind) && !is_kept_attribute(walk.source, node) {
return;
}
if walk.lang.mdx && is_mdx_comment(walk.source, node) {
return;
}
if is_jsx_comment(walk.lang, node) {
return;
}
if matches!(walk.mode, WalkMode::Callee) {
if kind == "visibility_modifier" {
return;
}
if kind == "export_statement" {
walk_children(walk, node);
return;
}
}
let shape = matches!(walk.mode, WalkMode::Shape | WalkMode::Callee);
let erase_types = shape && !walk.keep_types && erases_types(walk.lang);
if erase_types && is_type_wrapper(kind) {
walk_children(walk, node);
return;
}
if erase_types && matches!(kind, "as" | "satisfies") {
return;
}
if erase_types && (is_type_syntax(kind) || is_type_field(field)) {
return;
}
if shape && walk.lang.id == "rust" && matches!(kind, "lifetime" | "lifetime_parameter") {
return;
}
if shape && is_formatting(walk.lang, node) {
return;
}
if shape {
if let Some(inner) = transparent_child(walk.lang, node) {
walk_node(walk, inner, field);
return;
}
}
if walk.lang.id == "markdown" && kind == "section" {
walk_children(walk, node);
return;
}
if walk.lang.id == "markdown" {
if let Some((level, inline)) = heading_parts(node) {
walk.out.push(format!("heading:{level}"));
if let Some(inline) = inline {
walk_node(walk, inline, None);
}
walk.out.push(CLOSE.to_string());
return;
}
if let Some(form) = markdown_form(walk.source, node) {
walk.out.push(form);
return;
}
}
if walk.lang.id == "markdown" && matches!(kind, "inline" | "html_block") {
let text = &without_continuations(walk.source, node);
let text = &if walk.lang.mdx && kind == "inline" {
strip_mdx_comments(text)
} else {
text.to_string()
};
let heading = node.parent().is_some_and(|p| p.kind() == "atx_heading");
let read = if kind == "html_block" {
html_block_text(text)
} else if heading {
prose_text(without_closing_sequence(text))
} else {
prose_text(text)
};
if !read.is_empty() {
walk.out.push(format!("{kind}:{read}"));
}
return;
}
if let Some(value) = plain_string(walk.lang, walk.source, node)
.or_else(|| joined_string(walk.lang, walk.source, node))
{
walk.out.push(format!("string:{value:?}"));
return;
}
if walk.lang.id == "yaml" {
if let Some(value) = yaml_scalar(walk.source, node) {
walk.out.push(value);
return;
}
}
if walk.lang.id == "css" && kind == "color_value" {
let text = node.utf8_text(walk.source.as_bytes()).unwrap_or("");
walk.out
.push(format!("{kind}:{}", text.to_ascii_lowercase()));
return;
}
let was_literal = walk.literal;
if let Some(on) = literal_effect(walk.lang, walk.source, node) {
walk.literal = on;
}
if node.child_count() == 0 {
let leaf = leaf_token(walk, node);
walk.out.push(leaf);
} else {
walk.out.push(kind.to_string());
walk_children(walk, node);
walk.out.push(CLOSE.to_string());
}
walk.literal = was_literal;
}
fn leaf_token(walk: &Walk<'_>, node: Node<'_>) -> String {
let kind = node.kind();
let text = node.utf8_text(walk.source.as_bytes()).unwrap_or("");
if is_string_quote(walk.lang, node) {
return "quote".to_string();
}
if walk.literal {
return format!("{kind}:{:?}", lf(text));
}
if let Some(local) = walk.locals.get(&node.id()) {
return format!("{kind}:{local}");
}
let text = match (walk.lang.id, kind) {
("dockerfile", _) if !node.is_named() && kind.eq_ignore_ascii_case(text) => String::new(),
("python", "string_start") => {
let prefix = text.trim_end_matches(['\'', '"']).to_ascii_lowercase();
prefix.replace('u', "")
}
("python", "string_end") => String::new(),
(_, "jsx_text") => jsx_text(text),
_ if is_number_kind(walk.lang, kind) => decimal(walk.lang, &text.to_ascii_lowercase()),
_ => collapse(text),
};
if text.is_empty() {
kind.to_string()
} else {
format!("{kind}:{text}")
}
}
const SPACE: [char; 5] = [' ', '\t', '\n', '\r', '\x0c'];
fn collapse(text: &str) -> String {
text.split(SPACE)
.filter(|word| !word.is_empty())
.collect::<Vec<_>>()
.join(" ")
}
fn lf(text: &str) -> std::borrow::Cow<'_, str> {
if !text.contains("\r\n") {
return text.into();
}
text.replace("\r\n", "\n").into()
}
fn prose_text(text: &str) -> String {
let text = &with_titles_quoted(text);
let mut parts = Vec::new();
let mut prose = String::new();
for (code, part) in crate::hash::code_spans(text) {
if code {
prose.push('`');
prose.push_str(part);
prose.push('`');
continue;
}
for (raw, piece) in raw_html(&strip_html_comments(part)) {
if raw {
parts.push(collapse(&std::mem::take(&mut prose)));
parts.push(format!("{piece:?}"));
} else {
prose.push_str(&piece);
}
}
}
parts.push(collapse(&prose));
parts.retain(|part| !part.is_empty());
parts.join(" ")
}
static OPEN_TAG: LazyLock<regex::Regex> = LazyLock::new(|| {
regex::Regex::new(
r#"^<([A-Za-z][A-Za-z0-9-]*)(?:[ \t\r\n]+[A-Za-z_:][A-Za-z0-9_.:-]*(?:[ \t\r\n]*=[ \t\r\n]*(?:[^ \t\r\n"'=<>`]+|'[^']*'|"[^"]*"))?)*[ \t\r\n]*(/?)>"#,
)
.expect("open tag regex")
});
const KEEPS_TEXT: &[&str] = &[
"pre",
"textarea",
"listing",
"plaintext",
"xmp",
"script",
"style",
];
fn raw_html(text: &str) -> Vec<(bool, String)> {
let mut out = Vec::new();
let (mut prose, mut at) = (0, 0);
while let Some(rel) = text[at..].find('<') {
let open = at + rel;
at = open + 1;
if escaped(text, open) {
continue;
}
let Some(tag) = OPEN_TAG.captures(&text[open..]) else {
continue;
};
let end = open + tag[0].len();
out.push((false, text[prose..open].to_string()));
let mut inside = open;
let bytes = text.as_bytes();
let mut quote = None;
for i in open..end {
match (quote, bytes[i]) {
(None, q @ (b'"' | b'\'')) => {
out.push((false, text[inside..i].to_string()));
quote = Some((q, i + 1));
}
(Some((q, from)), b) if b == q => {
out.push((true, text[from..i].to_string()));
inside = i + 1;
quote = None;
}
_ => {}
}
}
out.push((false, text[inside..end].to_string()));
(prose, at) = (end, end);
let name = tag[1].to_ascii_lowercase();
if tag[2].is_empty() && KEEPS_TEXT.contains(&name.as_str()) {
let lower = text[end..].to_ascii_lowercase();
let close = lower
.match_indices(&format!("</{name}"))
.map(|(rel, _)| end + rel)
.find(|&c| {
let after = text[c + 2 + name.len()..].chars().next();
after.is_none_or(|ch| ch == '>' || SPACE.contains(&ch))
})
.unwrap_or(text.len());
out.push((true, text[end..close].to_string()));
(prose, at) = (close, close);
}
}
out.push((false, text[prose..].to_string()));
out.retain(|(raw, piece)| *raw || !piece.is_empty());
out
}
fn escaped(text: &str, at: usize) -> bool {
text[..at].bytes().rev().take_while(|&b| b == b'\\').count() % 2 == 1
}
fn inline_tree(text: &str) -> Tree {
let mut parser = Parser::new();
parser
.set_language(&tree_sitter_md::INLINE_LANGUAGE.into())
.expect("the inline markdown grammar matches the tree-sitter of the binary");
parser
.parse(text, None)
.expect("a parser with a language and no timeout returns a tree")
}
fn link_label(text: &str) -> String {
let inner = text.strip_prefix('[').unwrap_or(text);
let inner = inner.strip_suffix(']').unwrap_or(inner);
collapse(inner).to_lowercase()
}
fn reference_resolutions(
source: &str,
tree: &Tree,
(start, end): (usize, usize),
punch: &[(usize, usize)],
) -> Vec<String> {
let mut found = Vec::new();
let mut inlines = Vec::new();
let mut stack = vec![tree.root_node()];
while let Some(node) = stack.pop() {
if node.kind() == "inline" {
if node.start_byte() >= start && node.end_byte() <= end && !punched_out(node, punch) {
inlines.push(node);
}
continue;
}
if node.kind() == "link_reference_definition" {
let part = |kind: &str| {
let mut cursor = node.walk();
let found = node.named_children(&mut cursor).find(|c| c.kind() == kind);
found.and_then(|c| c.utf8_text(source.as_bytes()).ok())
};
if let Some(label) = part("link_label") {
let destination = part("link_destination").unwrap_or("");
let destination = destination
.strip_prefix('<')
.and_then(|d| d.strip_suffix('>'))
.unwrap_or(destination);
let title = part("link_title")
.and_then(|t| t.get(1..t.len().saturating_sub(1)))
.unwrap_or("");
found.push((
node.start_byte(),
link_label(label),
format!("{destination:?}:{:?}", collapse(title)),
));
}
continue;
}
if node.kind() == "paragraph" {
let text = node.utf8_text(source.as_bytes()).unwrap_or("");
if let Some((label, content)) = footnote_definition(text) {
let mut read = vec![prose_text(content)];
let mut next = node.next_named_sibling();
while let Some(block) = next.filter(|b| b.kind() == "indented_code_block") {
read.push(prose_text(block.utf8_text(source.as_bytes()).unwrap_or("")));
next = block.next_named_sibling();
}
found.push((
node.start_byte(),
link_label(label),
format!("footnote:{:?}", read.join(" ")),
));
}
}
stack.extend(node.named_children(&mut node.walk()));
}
found.sort();
let mut definitions: HashMap<String, String> = HashMap::new();
for (_, label, target) in found {
definitions.entry(label).or_insert(target);
}
inlines.sort_by_key(|n| n.start_byte());
let mut out = Vec::new();
for node in inlines {
let text = node.utf8_text(source.as_bytes()).unwrap_or("");
if !text.contains('[') {
continue;
}
let inline = inline_tree(text);
let mut labels = Vec::new();
let mut stack = vec![inline.root_node()];
while let Some(n) = stack.pop() {
stack.extend(n.named_children(&mut n.walk()));
let child = |kind: &str| {
let mut cursor = n.walk();
let first = n.named_children(&mut cursor).find(|c| c.kind() == kind);
first
};
let label = match n.kind() {
"full_reference_link" => child("link_label"),
"collapsed_reference_link" | "shortcut_link" => child("link_text"),
"image" if child("link_destination").is_none() => {
child("link_label").or_else(|| child("image_description"))
}
_ => None,
};
if let Some(label) = label {
labels.push((
n.start_byte(),
label.utf8_text(text.as_bytes()).unwrap_or(""),
));
}
}
labels.sort_by_key(|(at, _)| *at);
for (_, label) in labels {
let label = link_label(label);
let target = definitions.get(&label).map_or("none", String::as_str);
out.push(format!("ref:{label:?}:{target}"));
}
}
out
}
fn footnote_definition(text: &str) -> Option<(&str, &str)> {
let close = text.strip_prefix("[^")?.find(']')? + 2;
let label = &text[..=close];
let content = text[close + 1..].strip_prefix(':')?;
(close > 2 && !label[1..].contains('[')).then_some((label, content))
}
fn with_titles_quoted(text: &str) -> std::borrow::Cow<'_, str> {
if !text.contains("](") && !text.contains(['*', '_']) {
return text.into();
}
let tree = inline_tree(text);
let mut edits: Vec<(usize, usize, String)> = Vec::new();
let mut stack = vec![tree.root_node()];
while let Some(node) = stack.pop() {
let mut cursor = node.walk();
stack.extend(node.children(&mut cursor));
let parent = node.parent();
let in_link = parent.is_some_and(|p| matches!(p.kind(), "inline_link" | "image"));
let (start, end) = (node.start_byte(), node.end_byte());
match node.kind() {
"link_title" if in_link && !node.has_error() => {
let inner = &text[start + 1..end - 1];
if !text[start..end].starts_with('"') && !inner.contains('"') {
edits.push((start, end, format!("\"{inner}\"")));
}
}
"(" if in_link && !parent.is_some_and(|p| p.has_error()) => {
let next = node.next_sibling().map_or(end, |n| n.start_byte());
edits.push((end, next, String::new()));
}
")" if in_link && !parent.is_some_and(|p| p.has_error()) => {
let prev = node.prev_sibling().map_or(start, |n| n.end_byte());
edits.push((prev, start, String::new()));
}
"emphasis_delimiter" => {
let strong = parent.is_some_and(|p| p.kind() == "strong_emphasis");
let mark = if strong { '\u{3}' } else { '\u{2}' };
edits.push((start, end, mark.to_string()));
}
_ => {}
}
}
edits.retain(|(start, end, with)| start < end && text[*start..*end] != **with);
if edits.is_empty() {
return text.into();
}
edits.sort();
let mut out = String::with_capacity(text.len());
let mut at = 0;
for (start, end, with) in edits {
if start < at {
continue;
}
out.push_str(&text[at..start]);
out.push_str(&with);
at = end;
}
out.push_str(&text[at..]);
out.into()
}
fn html_block_text(text: &str) -> String {
let text = lf(text);
let Some(tree) = parse(&HTML, &text) else {
return format!("{text:?}");
};
let locals = HashMap::new();
let mut parts = Vec::new();
let mut walk = Walk {
lang: &HTML,
source: &text,
start: 0,
end: text.len(),
punch: &[],
mode: WalkMode::Complete,
locals: &locals,
keep_types: false,
literal: false,
holes: Vec::new(),
out: &mut parts,
};
walk_children(&mut walk, tree.root_node());
if parts.is_empty() {
return String::new();
}
format!("{:?}", parts.join("\n"))
}
fn is_jsx_comment(lang: &LangSpec, node: Node<'_>) -> bool {
let mut cursor = node.walk();
matches!(lang.id, "tsx" | "javascript")
&& node.kind() == "jsx_expression"
&& node.named_child_count() > 0
&& node
.named_children(&mut cursor)
.all(|n| (lang.skip_kind)(n.kind()))
}
fn is_mdx_comment(source: &str, node: Node<'_>) -> bool {
let text = &source[node.start_byte()..node.end_byte()];
node.kind() == "paragraph"
&& text.trim_start().starts_with("{/*")
&& strip_mdx_comments(text).trim().is_empty()
}
fn strip_mdx_comments(text: &str) -> String {
let masked = crate::parse::mask_inline_code(text);
let mut out = String::with_capacity(text.len());
let (mut kept, mut at) = (0, 0);
while let Some(rel) = masked[at..].find("{/*") {
let open = at + rel;
at = open + 1;
let Some(body) = masked[open + 3..].find("*/").map(|rel| open + 3 + rel + 2) else {
break;
};
let rest = &masked[body..];
let gap = rest.len() - rest.trim_start().len();
if !rest[gap..].starts_with('}') {
continue;
}
out.push_str(&text[kept..open]);
out.push(' ');
kept = body + gap + 1;
at = kept;
}
out.push_str(&text[kept..]);
out
}
fn strip_html_comments(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let (mut kept, mut at) = (0, 0);
while let Some(rel) = text[at..].find("<!--") {
let open = at + rel;
at = open + 1;
if escaped(text, open) {
continue;
}
let body = &text[open + 4..];
let close = if body.starts_with('>') {
Some(1)
} else if body.starts_with("->") {
Some(2)
} else {
body.find("-->").map(|rel| rel + 3)
};
let Some(close) = close else {
break;
};
out.push_str(&text[kept..open]);
out.push(' ');
kept = open + 4 + close;
at = kept;
}
out.push_str(&text[kept..]);
out
}
fn literal_effect(lang: &LangSpec, source: &str, node: Node<'_>) -> Option<bool> {
let kind = node.kind();
let opens = match lang.id {
"rust" => matches!(
kind,
"string_literal" | "raw_string_literal" | "char_literal"
),
"python" => matches!(kind, "string_content" | "format_specifier"),
"javascript" | "typescript" | "tsx" => {
matches!(kind, "string" | "template_string" | "regex")
}
"css" => kind == "string_value",
"html" => {
matches!(
kind,
"quoted_attribute_value" | "attribute_value" | "raw_text"
) || (kind == "element" && keeps_whitespace(source, node))
}
"hcl" => matches!(
kind,
"quoted_template" | "heredoc_template" | "template_literal"
),
"yaml" => matches!(
kind,
"double_quote_scalar" | "single_quote_scalar" | "block_scalar"
),
"cedar" | "prisma" | "jsonc" => kind == "string",
"dockerfile" => matches!(
kind,
"double_quoted_string"
| "single_quoted_string"
| "json_string"
| "shell_command"
| "heredoc_block"
),
"bash" => matches!(
kind,
"string"
| "raw_string"
| "ansi_c_string"
| "translated_string"
| "heredoc_redirect"
| "heredoc_body"
),
"markdown" => matches!(kind, "code_fence_content" | "indented_code_block"),
_ => false,
};
if opens {
return Some(true);
}
let code = match lang.id {
"python" if kind == "interpolation" => return Some(self_documenting(node)),
"python" => kind == "format_expression",
"javascript" | "typescript" | "tsx" => kind == "template_substitution",
"hcl" => matches!(kind, "template_interpolation" | "template_directive"),
"bash" => matches!(
kind,
"command_substitution" | "process_substitution" | "arithmetic_expansion"
),
"html" => matches!(kind, "start_tag" | "end_tag"),
_ => false,
};
code.then_some(false)
}
fn self_documenting(node: Node<'_>) -> bool {
let mut cursor = node.walk();
let found = node
.children(&mut cursor)
.any(|c| c.kind() == "=" && !c.is_named());
found
}
fn plain_string(lang: &LangSpec, source: &str, node: Node<'_>) -> Option<String> {
if node.kind() != "string" {
return None;
}
let mut cursor = node.walk();
let children: Vec<_> = node.children(&mut cursor).collect();
let (first, last) = (children.first()?, children.last()?);
let body = match lang.id {
"javascript" | "typescript" | "tsx" => {
if !matches!(first.kind(), "\"" | "'") || children.len() < 2 {
return None;
}
&source[first.end_byte()..last.start_byte()]
}
"python" => {
let prefix = first.utf8_text(source.as_bytes()).ok()?;
let raw = prefix.contains(['r', 'R']);
let interpolated = children.iter().any(|c| {
let mut cursor = c.walk();
let found = c.children(&mut cursor).any(|g| g.kind() == "interpolation");
c.kind() == "interpolation" || found
});
if raw || interpolated || first.kind() != "string_start" || last.kind() != "string_end"
{
return None;
}
let quotes = prefix.trim_start_matches(|c: char| c.is_ascii_alphabetic());
let prefix = prefix[..prefix.len() - quotes.len()].to_ascii_lowercase();
let body = &source[first.end_byte()..last.start_byte()];
return Some(format!(
"{}:{}",
prefix.replace('u', ""),
unescape_quotes(&lf(body))
));
}
_ => return None,
};
Some(unescape_quotes(&lf(body)))
}
fn joined_string(lang: &LangSpec, source: &str, node: Node<'_>) -> Option<String> {
if lang.id != "python" || node.kind() != "concatenated_string" {
return None;
}
let mut cursor = node.walk();
let mut prefix = None;
let mut joined = String::new();
for part in node.named_children(&mut cursor) {
if (lang.skip_kind)(part.kind()) {
continue;
}
let value = plain_string(lang, source, part)?;
let (head, body) = value.split_once(':')?;
if body.contains('\\') || prefix.get_or_insert(head.to_string()) != head {
return None;
}
joined.push_str(body);
}
Some(format!("{}:{joined}", prefix?))
}
fn unescape_quotes(body: &str) -> String {
let mut out = String::with_capacity(body.len());
let mut chars = body.chars();
while let Some(c) = chars.next() {
if c != '\\' {
out.push(c);
continue;
}
match chars.next() {
Some(q @ ('\'' | '"')) => out.push(q),
Some(other) => {
out.push('\\');
out.push(other);
}
None => out.push('\\'),
}
}
out
}
const YAML_1_1_WORDS: &[&str] = &["y", "yes", "n", "no", "true", "false", "on", "off", "null"];
fn yaml_scalar(source: &str, node: Node<'_>) -> Option<String> {
let text = lf(node.utf8_text(source.as_bytes()).ok()?);
let quoted = || {
text.get(1..text.len().checked_sub(1)?)
.filter(|body| !body.contains('\n'))
};
match node.kind() {
"plain_scalar" => {
let value = folded(&text);
let string = node
.named_child(0)
.is_some_and(|c| c.kind() == "string_scalar")
&& value.starts_with(|c: char| c.is_ascii_alphabetic())
&& !value.contains("{{")
&& !YAML_1_1_WORDS.contains(&value.to_ascii_lowercase().as_str());
let kind = if string { "string" } else { "plain" };
Some(format!("{kind}:{value:?}"))
}
"single_quote_scalar" => Some(format!("string:{:?}", quoted()?.replace("''", "'"))),
"double_quote_scalar" => {
let body = quoted().filter(|body| !body.contains('\\'))?;
Some(format!("string:{body:?}"))
}
"block_scalar" => block_scalar(source, node, &text),
_ => None,
}
}
fn folded(text: &str) -> String {
let mut out = String::new();
let mut breaks = 0;
for (i, line) in text
.split('\n')
.map(|l| l.trim_matches([' ', '\t']))
.enumerate()
{
if i > 0 && line.is_empty() {
breaks += 1;
continue;
}
if i > 0 {
out.push_str(if breaks == 0 { " " } else { "" });
out.push_str(&"\n".repeat(breaks));
}
breaks = 0;
out.push_str(line);
}
out
}
fn block_scalar(source: &str, node: Node<'_>, text: &str) -> Option<String> {
let header = node.child(0)?.utf8_text(source.as_bytes()).ok()?;
if header.bytes().any(|b| b.is_ascii_digit()) {
return None;
}
let (_, body) = text.split_once('\n')?;
let lines: Vec<&str> = body.split('\n').collect();
let indent = lines
.iter()
.find(|line| !line.trim().is_empty())
.map_or(0, |line| line.len() - line.trim_start_matches(' ').len());
let mut value = Vec::new();
for line in lines {
match line.get(indent..) {
Some(rest) if line[..indent].bytes().all(|b| b == b' ') => value.push(rest),
_ if line.trim().is_empty() => value.push(""),
_ => return None,
}
}
let kept = match header.contains('+') {
true => source[node.end_byte()..]
.chars()
.take_while(|c| c.is_whitespace())
.filter(|&c| c == '\n')
.count(),
false => 0,
};
Some(format!(
"block_scalar:{header}:{:?}:{kept}",
value.join("\n")
))
}
fn keeps_whitespace(source: &str, element: Node<'_>) -> bool {
let tag = element
.named_child(0)
.filter(|t| t.kind() == "start_tag")
.and_then(|t| t.named_child(0))
.and_then(|n| n.utf8_text(source.as_bytes()).ok())
.unwrap_or("");
["pre", "textarea", "listing", "plaintext", "xmp"]
.iter()
.any(|t| t.eq_ignore_ascii_case(tag))
}
fn is_string_quote(lang: &LangSpec, node: Node<'_>) -> bool {
let parent = || node.parent().map(|p| p.kind());
if lang.id == "markdown" {
return matches!(node.kind(), "\"" | "'" | "(" | ")") && parent() == Some("link_title");
}
let quote = matches!(node.kind(), "\"" | "'") && !node.is_named();
quote
&& match lang.id {
"javascript" | "typescript" | "tsx" => parent() == Some("string"),
"css" => parent() == Some("string_value"),
"html" => parent() == Some("quoted_attribute_value"),
_ => false,
}
}
fn markdown_form(source: &str, node: Node<'_>) -> Option<String> {
let kind = node.kind();
match kind {
"list_marker_star" | "list_marker_minus" | "list_marker_plus" => {
Some("list_marker_bullet".to_string())
}
"pipe_table_delimiter_cell" => {
let mut cursor = node.walk();
let kinds: Vec<_> = node.children(&mut cursor).map(|c| c.kind()).collect();
let left = kinds.contains(&"pipe_table_align_left");
let right = kinds.contains(&"pipe_table_align_right");
Some(format!("{kind}:{left}:{right}"))
}
"list_marker_dot" | "list_marker_parenthesis" => {
let item = node.parent().filter(|p| p.kind() == "list_item")?;
let first = item
.prev_named_sibling()
.is_none_or(|s| s.kind() != "list_item");
let text = node.utf8_text(source.as_bytes()).ok()?.trim();
let digits = text.trim_end_matches(['.', ')']);
if first {
let start: u64 = digits.parse().ok()?;
Some(format!("list_marker_ordered:{start}"))
} else {
Some("list_marker_ordered".to_string())
}
}
_ => None,
}
}
fn without_continuations(source: &str, node: Node<'_>) -> String {
let mut out = String::new();
let mut at = node.start_byte();
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() == "block_continuation" {
out.push_str(&source[at..child.start_byte()]);
out.push(' ');
at = child.end_byte();
}
}
out.push_str(&source[at..node.end_byte()]);
out
}
fn heading_parts(node: Node<'_>) -> Option<(u32, Option<Node<'_>>)> {
if !matches!(node.kind(), "atx_heading" | "setext_heading") {
return None;
}
let mut cursor = node.walk();
let parts: Vec<Node<'_>> = node.named_children(&mut cursor).collect();
let level = parts.iter().find_map(|m| {
let kind = m.kind();
kind.strip_prefix("atx_h")
.or_else(|| kind.strip_prefix("setext_h"))
.and_then(|rest| rest.chars().next()?.to_digit(10))
})?;
let inline = parts.iter().find_map(|p| match p.kind() {
"inline" => Some(*p),
"paragraph" => {
let mut cursor = p.walk();
let found = p.named_children(&mut cursor).find(|c| c.kind() == "inline");
found
}
_ => None,
});
Some((level, inline))
}
fn without_closing_sequence(text: &str) -> &str {
let trimmed = text.trim_end_matches([' ', '\t']);
let body = trimmed.trim_end_matches('#');
if body.len() == trimmed.len() {
return text;
}
if body.is_empty() {
return body;
}
match body.strip_suffix([' ', '\t']) {
Some(_) => body.trim_end_matches([' ', '\t']),
None => text,
}
}
fn decimal(lang: &LangSpec, text: &str) -> String {
if !matches!(lang.id, "javascript" | "typescript" | "tsx" | "python") {
return text.to_string();
}
let (mantissa, exponent) = match text.find('e') {
Some(at) => text.split_at(at),
None => (text, ""),
};
let Some((whole, fraction)) = mantissa.split_once('.') else {
return text.to_string();
};
if !whole
.bytes()
.chain(fraction.bytes())
.all(|b| b.is_ascii_digit())
{
return text.to_string();
}
let whole = if whole.is_empty() { "0" } else { whole };
let fraction = fraction.trim_end_matches('0');
let fraction = if fraction.is_empty() { "0" } else { fraction };
format!("{whole}.{fraction}{exponent}")
}
fn is_number_kind(lang: &LangSpec, kind: &str) -> bool {
match lang.id {
"rust" => matches!(kind, "integer_literal" | "float_literal"),
"python" => matches!(kind, "integer" | "float"),
"javascript" | "typescript" | "tsx" => kind == "number",
_ => false,
}
}
fn jsx_text(text: &str) -> String {
let lines: Vec<&str> = text
.split(['\n'])
.map(|l| l.strip_suffix('\r').unwrap_or(l))
.collect();
let last = lines.len() - 1;
let mut kept = Vec::new();
for (i, line) in lines.iter().enumerate() {
let mut line = line.replace('\t', " ");
if i > 0 {
line = line.trim_start_matches(' ').to_string();
}
if i < last {
line = line.trim_end_matches(' ').to_string();
}
if !line.is_empty() {
kept.push(line);
}
}
format!("{:?}", kept.join(" "))
}
fn is_formatting(lang: &LangSpec, node: Node<'_>) -> bool {
let kind = node.kind();
match lang.id {
"python" => {
kind == "line_continuation"
|| (matches!(kind, "(" | ")")
&& node.parent().is_some_and(|p| p.kind() == "with_clause"))
}
"rust" if kind == "," => node.parent().is_some_and(|p| p.kind() == "match_arm"),
"javascript" | "typescript" | "tsx" if !node.is_named() => {
let Some(parent) = node.parent() else {
return false;
};
match (kind, parent.kind()) {
(";", "empty_statement") => false,
(";", "class_body") => true,
(";", _) => next_token(lang, node).is_none(),
("!", "non_null_expression") => true,
("const", "as_expression") => true,
_ => false,
}
}
_ => false,
}
}
fn next_token<'a>(lang: &LangSpec, node: Node<'a>) -> Option<Node<'a>> {
let mut next = node.next_sibling();
while let Some(n) = next.filter(|n| (lang.skip_kind)(n.kind())) {
next = n.next_sibling();
}
next
}
fn transparent_child<'a>(lang: &LangSpec, node: Node<'a>) -> Option<Node<'a>> {
let named = || {
let mut cursor = node.walk();
node.named_children(&mut cursor)
.filter(|c| !(lang.skip_kind)(c.kind()))
.collect::<Vec<_>>()
};
let only = || match named().as_slice() {
[one] => Some(*one),
_ => None,
};
match (lang.id, node.kind()) {
("rust", "block")
if node
.parent()
.is_some_and(|p| p.kind() == "closure_expression") =>
{
tail_only(node)
}
("rust", "block") if node.parent().is_some_and(|p| p.kind() == "match_arm") => {
tail_only(node)
}
("rust", "parenthesized_expression") => {
let inner = only()?;
rust_redundant_parentheses(node).then_some(inner)
}
("python", "parenthesized_expression") => only(),
("javascript" | "typescript" | "tsx", "parenthesized_expression") => {
let inner = only()?;
redundant_parentheses(node, inner).then_some(inner)
}
("javascript" | "typescript" | "tsx", "statement_block") => one_statement_body(node),
("typescript" | "tsx", "non_null_expression") => only(),
("javascript" | "typescript" | "tsx", "formal_parameters")
if node.parent().is_some_and(|p| p.kind() == "arrow_function") =>
{
let param = only()?;
match param.kind() {
"identifier" => Some(param),
"required_parameter" => {
let mut cursor = param.walk();
let parts: Vec<_> = param.children(&mut cursor).collect();
match parts.as_slice() {
[name] | [name, _]
if name.kind() == "identifier"
&& parts.get(1).is_none_or(|t| t.kind() == "type_annotation") =>
{
Some(*name)
}
_ => None,
}
}
_ => None,
}
}
_ => None,
}
}
fn redundant_parentheses(parens: Node<'_>, inner: Node<'_>) -> bool {
if inner.kind().starts_with("jsx_") {
return true;
}
let Some(parent) = parens.parent() else {
return false;
};
if parent.kind() == "parenthesized_expression" {
return true;
}
let holds = |field: &str| {
parent
.child_by_field_name(field)
.is_some_and(|n| n.id() == parens.id())
};
let ends_chain = match parent.kind() {
"member_expression" | "subscript_expression" => holds("object"),
"call_expression" => holds("function"),
"new_expression" => holds("constructor"),
_ => false,
};
let opens_body =
parent.kind() == "arrow_function" && holds("body") && first_token(inner).kind() == "{";
if ends_chain
|| opens_body
|| parent.kind() == "expression_statement"
|| inner.kind() == "sequence_expression"
|| holds_in_operator(inner)
{
return false;
}
if parent.kind() != "binary_expression" || inner.kind() != "binary_expression" {
return matches!(
inner.kind(),
"identifier"
| "this"
| "super"
| "number"
| "string"
| "template_string"
| "regex"
| "true"
| "false"
| "null"
| "undefined"
| "array"
| "member_expression"
| "subscript_expression"
| "call_expression"
) || match parent.kind() {
"arguments"
| "array"
| "template_substitution"
| "spread_element"
| "return_statement" => true,
"variable_declarator" | "pair" => holds("value"),
"assignment_expression" | "augmented_assignment_expression" => holds("right"),
"ternary_expression" => holds("consequence") || holds("alternative"),
"subscript_expression" => holds("index"),
"arrow_function" => holds("body"),
_ => false,
};
}
let rank = |n: Node<'_>| {
let op = n.child_by_field_name("operator")?;
Some(match op.kind() {
"||" | "??" => 1,
"&&" => 2,
"|" => 3,
"^" => 4,
"&" => 5,
"==" | "!=" | "===" | "!==" => 6,
"<" | ">" | "<=" | ">=" | "instanceof" | "in" => 7,
"<<" | ">>" | ">>>" => 8,
"+" | "-" => 9,
"*" | "/" | "%" => 10,
"**" => 11,
_ => return None,
})
};
let (Some(inner_rank), Some(outer_rank)) = (rank(inner), rank(parent)) else {
return false;
};
let mixes_nullish = |n: Node<'_>| {
n.child_by_field_name("operator")
.is_some_and(|op| op.kind() == "??")
};
if mixes_nullish(inner) != mixes_nullish(parent) && (inner_rank <= 2 || outer_rank <= 2) {
return false;
}
let left = parent
.child_by_field_name("left")
.is_some_and(|l| l.id() == parens.id());
inner_rank > outer_rank || (inner_rank == outer_rank && left && outer_rank != 11)
}
fn holds_in_operator(node: Node<'_>) -> bool {
let mut stack = vec![node];
while let Some(n) = stack.pop() {
if n.kind() == "binary_expression"
&& n.child_by_field_name("operator")
.is_some_and(|op| op.kind() == "in")
{
return true;
}
let mut cursor = n.walk();
stack.extend(n.children(&mut cursor));
}
false
}
fn first_token(node: Node<'_>) -> Node<'_> {
let mut at = node;
while let Some(child) = at.child(0) {
at = child;
}
at
}
fn rust_redundant_parentheses(parens: Node<'_>) -> bool {
parens.parent().is_some_and(|p| {
matches!(
p.kind(),
"let_declaration"
| "return_expression"
| "break_expression"
| "arguments"
| "if_expression"
| "while_expression"
| "match_expression"
| "match_arm"
| "assignment_expression"
| "compound_assignment_expr"
| "array_expression"
| "field_initializer"
| "unary_expression"
| "reference_expression"
| "binary_expression"
| "parenthesized_expression"
| "closure_expression"
)
})
}
fn one_statement_body(block: Node<'_>) -> Option<Node<'_>> {
let parent = block.parent()?;
let body = match parent.kind() {
"if_statement" => parent
.child_by_field_name("consequence")
.is_some_and(|n| n.id() == block.id()),
"else_clause" | "do_statement" => true,
"for_statement" | "for_in_statement" | "while_statement" => parent
.child_by_field_name("body")
.is_some_and(|n| n.id() == block.id()),
_ => false,
};
if !body {
return None;
}
let mut cursor = block.walk();
let parts: Vec<_> = block
.children(&mut cursor)
.filter(|c| c.kind() != "comment")
.collect();
match parts.as_slice() {
[open, one, close]
if open.kind() == "{"
&& close.kind() == "}"
&& matches!(
one.kind(),
"expression_statement"
| "return_statement"
| "throw_statement"
| "break_statement"
| "continue_statement"
| "if_statement"
| "for_statement"
| "for_in_statement"
| "while_statement"
| "do_statement"
) =>
{
Some(*one)
}
_ => None,
}
}
fn tail_only(block: Node<'_>) -> Option<Node<'_>> {
let mut cursor = block.walk();
let parts: Vec<_> = block
.children(&mut cursor)
.filter(|c| !matches!(c.kind(), "line_comment" | "block_comment"))
.collect();
match parts.as_slice() {
[open, tail, close]
if open.kind() == "{"
&& close.kind() == "}"
&& tail.is_named()
&& !tail.kind().ends_with("_item")
&& !matches!(
tail.kind(),
"expression_statement"
| "let_declaration"
| "empty_statement"
| "label"
| "attribute_item"
| "inner_attribute_item"
) =>
{
Some(*tail)
}
[open, tail, close]
if open.kind() == "{"
&& close.kind() == "}"
&& tail.kind() == "expression_statement" =>
{
let mut cursor = tail.walk();
let inner: Vec<_> = tail
.children(&mut cursor)
.filter(|c| !matches!(c.kind(), "line_comment" | "block_comment"))
.collect();
let leaves = |n: &Node<'_>| {
matches!(
n.kind(),
"return_expression" | "break_expression" | "continue_expression"
)
};
let block_like = |n: &Node<'_>| {
matches!(
n.kind(),
"match_expression"
| "if_expression"
| "loop_expression"
| "while_expression"
| "for_expression"
| "block"
| "unsafe_block"
| "async_block"
| "const_block"
)
};
match inner.as_slice() {
[expr] if leaves(expr) || block_like(expr) => Some(*expr),
[expr, semi] if semi.kind() == ";" && leaves(expr) => Some(*expr),
_ => None,
}
}
_ => None,
}
}
fn walk_children<'a>(walk: &mut Walk<'a>, node: Node<'a>) {
let mut cursor = node.walk();
if !cursor.goto_first_child() {
return;
}
let mut children: Vec<Step<'a>> = Vec::new();
loop {
children.push((cursor.node(), cursor.field_name()));
if !cursor.goto_next_sibling() {
break;
}
}
let mut at = node.start_byte();
for (i, &(child, child_field)) in children.iter().enumerate() {
gap(walk, at, child.start_byte());
at = at.max(child.end_byte());
if is_trailing_separator(walk.lang, walk.source, node, &children[..i], &children[i..]) {
continue;
}
let kept = !walk.keep_types && child_field.is_some_and(|f| keeps_type(node.kind(), f));
walk.keep_types |= kept;
walk_node(walk, child, child_field);
if kept {
walk.keep_types = false;
}
}
gap(walk, at, node.end_byte());
}
fn gap(walk: &mut Walk<'_>, from: usize, to: usize) {
let (from, to) = (from.max(walk.start), to.min(walk.end));
if from >= to {
return;
}
let mut kept = String::new();
let mut at = from;
let mut punch: Vec<_> = walk
.punch
.iter()
.copied()
.filter(|(s, e)| *s < to && *e > from)
.collect();
let shape = matches!(walk.mode, WalkMode::Shape | WalkMode::Callee);
if shape && !walk.keep_types && erases_types(walk.lang) {
punch.extend(typed_tag_args(walk.lang, walk.source, from, to));
}
punch.sort();
for &(s, e) in &punch {
if s > at {
kept.push_str(&walk.source[at..s]);
}
at = at.max(e);
}
if at < to {
kept.push_str(&walk.source[at..to]);
}
if kept.ends_with('\r') && walk.source.as_bytes().get(to) == Some(&b'\n') {
kept.pop();
}
if walk.lang.id == "markdown" && to == walk.source.len() && kept.ends_with('\n') {
kept.pop();
if kept.ends_with('\r') {
kept.pop();
}
}
if kept.is_empty() {
return;
}
if walk.literal {
walk.out.push(format!("gap:{:?}", lf(&kept)));
return;
}
if walk.lang.id == "jsonc" {
return;
}
let joined = if walk.lang.id == "bash" {
kept.replace("\\\r\n", "").replace("\\\n", "")
} else {
kept.clone()
};
let collapsed = collapse(&joined);
if !collapsed.is_empty() {
walk.out.push(format!("gap:{collapsed}"));
} else if joined.is_empty() {
walk.out.push("gap:".to_string());
}
}
fn is_trailing_separator(
lang: &LangSpec,
source: &str,
parent: Node<'_>,
before: &[Step<'_>],
rest: &[Step<'_>],
) -> bool {
let node = rest[0].0;
if node.is_named() || node.kind() != "," {
return false;
}
let token = |n: &&Step<'_>| !(lang.skip_kind)(n.0.kind());
let after_element = before
.iter()
.rev()
.find(token)
.is_some_and(|(n, _)| n.is_named());
let next = rest[1..].iter().find(token);
let trailing = next.is_none_or(|(n, _)| matches!(n.kind(), ")" | "]" | "}" | ">"));
trailing
&& after_element
&& !is_one_tuple(source, parent)
&& !is_one_key(lang, parent)
&& !in_user_macro(source, parent)
}
fn in_user_macro(source: &str, node: Node<'_>) -> bool {
const STD: &[&str] = &[
"assert",
"assert_eq",
"assert_ne",
"concat",
"dbg",
"debug_assert",
"debug_assert_eq",
"debug_assert_ne",
"eprint",
"eprintln",
"format",
"format_args",
"matches",
"panic",
"print",
"println",
"todo",
"unimplemented",
"unreachable",
"vec",
"write",
"writeln",
];
if node.kind() != "token_tree" {
return false;
}
let mut at = node.parent();
while let Some(n) = at.filter(|n| n.kind() == "token_tree") {
at = n.parent();
}
let Some(name) = at
.filter(|n| n.kind() == "macro_invocation")
.and_then(|n| n.child_by_field_name("macro"))
else {
return false;
};
let path = name.utf8_text(source.as_bytes()).unwrap_or_default();
let (root, last) = match path.rsplit_once("::") {
Some((root, last)) => (Some(root.trim_start_matches("::")), last),
None => (None, path),
};
let std_root = root.is_none_or(|r| matches!(r, "std" | "core" | "alloc"));
!(std_root && STD.contains(&last))
}
fn is_one_key(lang: &LangSpec, parent: Node<'_>) -> bool {
if lang.id != "python" || parent.kind() != "subscript" {
return false;
}
let mut cursor = parent.walk();
let commas = parent
.children(&mut cursor)
.filter(|c| c.kind() == ",")
.count();
commas == 1
}
const RUST_KEYWORDS: &[&str] = &[
"as", "async", "await", "box", "break", "const", "continue", "crate", "do", "dyn", "else",
"enum", "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop", "macro", "match",
"mod", "move", "mut", "priv", "pub", "ref", "return", "self", "Self", "static", "struct",
"super", "trait", "true", "try", "type", "typeof", "union", "unsafe", "unsized", "use",
"virtual", "where", "while", "yield", "gen",
];
fn is_one_tuple(source: &str, tree: Node<'_>) -> bool {
if tree.kind() != "token_tree" || tree.parent().is_none_or(|p| p.kind() != "token_tree") {
return false;
}
let called = tree.prev_sibling().is_some_and(|p| {
p.kind() == "identifier"
&& !RUST_KEYWORDS.contains(&p.utf8_text(source.as_bytes()).unwrap_or_default())
});
if called {
return false;
}
let mut cursor = tree.walk();
let kinds: Vec<&str> = tree.children(&mut cursor).map(|c| c.kind()).collect();
kinds.first() == Some(&"(") && kinds.iter().filter(|&&k| k == ",").count() == 1
}
fn is_type_syntax(kind: &str) -> bool {
matches!(
kind,
"adding_type_annotation"
| "array_type"
| "conditional_type"
| "constrained_type"
| "constructor_type"
| "default_type"
| "existential_type"
| "extends_type_clause"
| "flow_maybe_type"
| "function_type"
| "generic_type"
| "index_type_query"
| "infer_type"
| "intersection_type"
| "literal_type"
| "lookup_type"
| "mapped_type_clause"
| "member_type"
| "nested_type_identifier"
| "object_type"
| "omitting_type_annotation"
| "opting_type_annotation"
| "optional_type"
| "parenthesized_type"
| "predefined_type"
| "primary_type"
| "readonly_type"
| "rest_type"
| "splat_type"
| "template_literal_type"
| "template_type"
| "this_type"
| "tuple_type"
| "type"
| "type_annotation"
| "type_arguments"
| "type_identifier"
| "type_parameter"
| "type_parameters"
| "type_predicate"
| "type_predicate_annotation"
| "type_query"
| "union_type"
)
}
fn is_type_wrapper(kind: &str) -> bool {
matches!(
kind,
"as_expression" | "satisfies_expression" | "type_assertion"
)
}
fn is_type_field(field: Option<&str>) -> bool {
field.is_some_and(|f| TYPE_FIELDS.contains(&f))
}
fn is_cfg_attribute(source: &str, node: Node<'_>) -> bool {
if !matches!(node.kind(), "attribute_item" | "inner_attribute_item") {
return false;
}
let path = node.named_child(0).and_then(|attr| attr.named_child(0));
path.and_then(|p| p.utf8_text(source.as_bytes()).ok())
.is_some_and(|name| matches!(name, "cfg" | "cfg_attr"))
}
fn is_function_kind(lang: &LangSpec, kind: &str) -> bool {
match lang.id {
"rust" => matches!(kind, "function_item" | "closure_expression"),
"python" => kind == "function_definition",
"javascript" | "typescript" | "tsx" => matches!(
kind,
"function_declaration"
| "generator_function_declaration"
| "function_expression"
| "function"
| "generator_function"
| "method_definition"
| "arrow_function"
),
"bash" => kind == "function_definition",
_ => false,
}
}
const INERT_RUST_ATTRIBUTES: &[&str] = &[
"doc",
"allow",
"warn",
"deny",
"forbid",
"expect",
"must_use",
"inline",
"cold",
"deprecated",
"test",
"rustfmt",
"clippy",
"diagnostic",
];
fn is_behavioural_rust_attribute(source: &str, node: Node<'_>) -> bool {
if !matches!(node.kind(), "attribute_item" | "inner_attribute_item")
|| is_cfg_attribute(source, node)
{
return false;
}
let path = node.named_child(0).and_then(|attr| attr.named_child(0));
let name = path
.and_then(|p| p.utf8_text(source.as_bytes()).ok())
.unwrap_or("");
let head = name.split("::").next().unwrap_or(name);
!INERT_RUST_ATTRIBUTES.contains(&head)
}
fn is_kept_attribute(source: &str, node: Node<'_>) -> bool {
is_cfg_attribute(source, node) || is_behavioural_rust_attribute(source, node)
}
fn is_header_kind(lang: &LangSpec, kind: &str) -> bool {
match lang.id {
"rust" => matches!(kind, "impl_item" | "trait_item"),
"python" => kind == "class_definition",
"javascript" | "typescript" | "tsx" => {
matches!(
kind,
"class_declaration" | "class" | "abstract_class_declaration"
)
}
"css" => matches!(
kind,
"rule_set" | "media_statement" | "supports_statement" | "at_rule"
),
_ => false,
}
}
fn body_of<'a>(node: Node<'a>) -> Option<Node<'a>> {
node.child_by_field_name("body").or_else(|| {
let mut cursor = node.walk();
let last = node.named_children(&mut cursor).last();
last.filter(|b| b.kind() == "block")
})
}
fn is_unit(lang: &LangSpec, node: Node<'_>) -> bool {
let member = || node.parent().is_some_and(|p| p.kind() == "class_body");
match (lang.id, node.kind()) {
("rust", kind) => kind == "function_item",
("python" | "bash", kind) => kind == "function_definition",
("javascript" | "typescript" | "tsx", kind) => match kind {
"function_declaration" | "generator_function_declaration" => true,
"method_definition" | "public_field_definition" | "field_definition" => member(),
_ => false,
},
_ => false,
}
}
fn is_loop_kind(lang: &LangSpec, kind: &str) -> bool {
match lang.id {
"rust" => matches!(
kind,
"for_expression" | "while_expression" | "loop_expression"
),
"python" => matches!(kind, "for_statement" | "while_statement"),
"javascript" | "typescript" | "tsx" => matches!(
kind,
"for_statement" | "for_in_statement" | "while_statement" | "do_statement"
),
"bash" => matches!(
kind,
"for_statement" | "c_style_for_statement" | "while_statement"
),
_ => false,
}
}
fn first_byte(source: &str, node: Node<'_>) -> usize {
if let Some(decorated) = node.parent().filter(|p| p.kind() == "decorated_definition") {
return decorated.start_byte();
}
let mut at = node.start_byte();
let mut sibling = node.prev_sibling();
while let Some(s) = sibling {
match s.kind() {
"decorator" => at = s.start_byte(),
"attribute_item" if is_kept_attribute(source, s) => at = s.start_byte(),
"attribute_item" | "line_comment" | "block_comment" | "comment" => {}
_ => break,
}
sibling = s.prev_sibling();
}
at
}
fn name_and_visibility(node: Node<'_>) -> Vec<(usize, usize)> {
let mut cursor = node.walk();
let visibility = node
.children(&mut cursor)
.filter(|c| matches!(c.kind(), "visibility_modifier" | "accessibility_modifier"));
node.child_by_field_name("name")
.into_iter()
.chain(visibility)
.map(|n| (n.start_byte(), n.end_byte()))
.collect()
}
#[derive(Default)]
struct Around {
before: Vec<Stretch>,
after: Vec<Stretch>,
unit: Option<(usize, usize)>,
}
fn prefix(lang: &LangSpec, source: &str, tree: &Tree, (start, end): (usize, usize)) -> Around {
if !matches!(
lang.id,
"rust" | "python" | "javascript" | "typescript" | "tsx" | "bash" | "css"
) {
return Around::default();
}
let (code_start, code_end) = code_extent(lang, tree, start, end);
let root = tree.root_node();
let chain: Vec<Node<'_>> =
std::iter::successors(root.descendant_for_byte_range(code_start, code_end), |n| {
n.parent()
})
.collect();
let top_level = |n: &&Node<'_>| n.parent().is_some_and(|p| p.id() == root.id());
let function = chain.iter().rposition(|n| is_unit(lang, *n));
let Some(at) = function.or_else(|| chain.iter().position(|n| top_level(&n))) else {
return Around::default();
};
let unit = chain[at];
let from = first_byte(source, unit);
let mut out = Around {
unit: Some((from, unit.end_byte())),
..Around::default()
};
if function.is_some() {
for header in chain[at + 1..]
.iter()
.rev()
.filter(|n| is_header_kind(lang, n.kind()))
{
let body = body_of(*header).map_or(header.end_byte(), |b| b.start_byte());
out.before.push((
first_byte(source, *header),
body,
name_and_visibility(*header),
));
}
}
if from < start {
let punch = if function.is_some() {
name_and_visibility(unit)
} else {
Vec::new()
};
out.before.push((from, start, punch));
}
let closure = chain[..at].iter().position(|n| {
is_function_kind(lang, n.kind()) || matches!(n.kind(), "async_block" | "gen_block")
});
let receiving = closure
.into_iter()
.flat_map(|c| &chain[c + 1..at])
.filter(|n| {
is_call_kind(n.kind())
|| matches!(n.kind(), "jsx_opening_element" | "jsx_self_closing_element")
});
let looping = chain[..=at].iter().filter(|n| is_loop_kind(lang, n.kind()));
let to = receiving.chain(looping).map(|n| n.end_byte()).max();
if let Some(to) = to.filter(|&to| to > end) {
out.after.push((end, to, Vec::new()));
}
out
}
pub fn prefix_stretches(
lang: &LangSpec,
source: &str,
tree: &Tree,
extent: (usize, usize),
) -> Vec<Stretch> {
let around = prefix(lang, source, tree, extent);
around.before.into_iter().chain(around.after).collect()
}
fn callee_prefix(source: &str, tree: &Tree, (start, end): (usize, usize)) -> Around {
let node = tree.root_node().descendant_for_byte_range(start, end);
let mut out = Around::default();
if let Some(node) = node.filter(|n| (n.start_byte(), n.end_byte()) == (start, end)) {
let from = first_byte(source, node);
if from < start {
out.before.push((from, start, Vec::new()));
}
}
out
}
fn code_leaves(lang: &LangSpec, tree: &Tree, start: usize, end: usize) -> Vec<(usize, usize)> {
let mut out = Vec::new();
let mut stack = vec![tree.root_node()];
while let Some(node) = stack.pop() {
let (s, e) = (node.start_byte(), node.end_byte());
let comment = (lang.skip_kind)(node.kind()) && node.kind().contains("comment");
if e <= start || s >= end || s == e || comment {
continue;
}
if node.child_count() == 0 {
if start <= s && e <= end {
out.push((s, e));
}
continue;
}
let mut cursor = node.walk();
let children: Vec<_> = node.children(&mut cursor).collect();
stack.extend(children.into_iter().rev());
}
out
}
fn code_extent(lang: &LangSpec, tree: &Tree, start: usize, end: usize) -> (usize, usize) {
let leaves = code_leaves(lang, tree, start, end);
match (leaves.first(), leaves.last()) {
(Some(&(s, _)), Some(&(_, e))) => (s, e),
_ => (start, end),
}
}
pub type Stretch = (usize, usize, Vec<(usize, usize)>);
#[derive(
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
)]
pub enum Read {
Prefix,
Attribute,
Above,
}
pub fn read_stretches(
lang: &LangSpec,
source: &str,
tree: &Tree,
start: usize,
end: usize,
) -> Vec<(Read, Stretch)> {
let around = prefix(lang, source, tree, (start, end));
let held = |a: usize, b: usize| {
around
.before
.iter()
.chain(&around.after)
.any(|&(s, e, _)| s <= a && b <= e)
};
let attributes: Vec<Stretch> = governing_attributes(lang, source, tree, start, end)
.into_iter()
.map(|attr| (attr.start_byte(), attr.end_byte(), Vec::new()))
.filter(|&(a, b, _)| !held(a, b))
.collect();
let mut out: Vec<(Read, Stretch)> = around
.before
.into_iter()
.chain(around.after)
.map(|stretch| (Read::Prefix, stretch))
.collect();
out.extend(attributes.into_iter().map(|attr| (Read::Attribute, attr)));
let above = above_stretches(lang, tree, (start, end));
out.extend(above.into_iter().map(|stretch| (Read::Above, stretch)));
out
}
pub fn above_stretches(lang: &LangSpec, tree: &Tree, extent: (usize, usize)) -> Vec<Stretch> {
match lang.id {
"yaml" => yaml_stretches(tree, extent),
_ => Vec::new(),
}
}
fn governing_attributes<'a>(
lang: &LangSpec,
source: &str,
tree: &'a Tree,
start: usize,
end: usize,
) -> Vec<Node<'a>> {
if lang.id != "rust" {
return Vec::new();
}
let mut out = Vec::new();
let mut node = tree.root_node().descendant_for_byte_range(start, end);
while let Some(current) = node {
let read_by_signature =
is_function_kind(lang, current.kind()) || is_header_kind(lang, current.kind());
let mut sibling = current.prev_sibling();
let mut before = Vec::new();
while let Some(s) = sibling {
match s.kind() {
"attribute_item" if is_cfg_attribute(source, s) => before.push(s),
"attribute_item"
if !read_by_signature && is_behavioural_rust_attribute(source, s) =>
{
before.push(s)
}
"attribute_item" | "line_comment" | "block_comment" => {}
_ => break,
}
sibling = s.prev_sibling();
}
let mut cursor = current.walk();
let inner: Vec<_> = current
.children(&mut cursor)
.filter(|c| c.kind() == "inner_attribute_item" && is_kept_attribute(source, *c))
.filter(|c| c.end_byte() <= start || c.start_byte() >= end)
.collect();
out.extend(inner.into_iter().rev());
out.extend(before);
node = current.parent();
}
out.reverse();
out
}
pub(crate) fn is_call_kind(kind: &str) -> bool {
matches!(
kind,
"call"
| "call_expression"
| "macro_invocation"
| "method_invocation"
| "new_expression"
| "command"
| "object_creation_expression"
| "explicit_constructor_invocation"
| "constructor_invocation"
)
}
const JS_LOCALS_EXTRA: &str = r#"
(catch_clause parameter: (identifier) @local.definition)
(arrow_function parameter: (identifier) @local.definition)
(rest_pattern (identifier) @local.definition)
(for_in_statement left: (identifier) @local.definition)
(shorthand_property_identifier_pattern) @local.definition
(shorthand_property_identifier) @local.reference
"#;
const JS_LOCALS_CLASSES: &str = r#"
(class_declaration name: (identifier) @local.definition)
"#;
static JS_LOCALS: LazyLock<Query> = LazyLock::new(|| {
locals_query(
tree_sitter_javascript::LANGUAGE.into(),
&[
tree_sitter_javascript::LOCALS_QUERY,
JS_LOCALS_CLASSES,
JS_LOCALS_EXTRA,
],
)
});
const TS_LOCALS_PARAMS: &str = r#"
(required_parameter pattern: (identifier) @local.definition)
(optional_parameter pattern: (identifier) @local.definition)
"#;
const TS_LOCALS_CLASSES: &str = r#"
(class_declaration name: (type_identifier) @local.definition)
(abstract_class_declaration name: (type_identifier) @local.definition)
"#;
static TS_LOCALS: LazyLock<Query> = LazyLock::new(|| {
locals_query(
tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
&[
tree_sitter_javascript::LOCALS_QUERY,
TS_LOCALS_PARAMS,
TS_LOCALS_CLASSES,
JS_LOCALS_EXTRA,
],
)
});
static TSX_LOCALS: LazyLock<Query> = LazyLock::new(|| {
locals_query(
tree_sitter_typescript::LANGUAGE_TSX.into(),
&[
tree_sitter_javascript::LOCALS_QUERY,
TS_LOCALS_PARAMS,
TS_LOCALS_CLASSES,
JS_LOCALS_EXTRA,
],
)
});
fn locals_query(language: Language, parts: &[&str]) -> Query {
Query::new(&language, &parts.concat()).expect("locals query compiles")
}
struct Site<'a> {
node: Node<'a>,
from: usize,
to: usize,
named: bool,
gaps: Vec<(usize, usize)>,
}
impl Site<'_> {
fn sees(&self, at: usize) -> bool {
self.from <= at && at < self.to && !self.gaps.iter().any(|&(s, e)| s <= at && at < e)
}
}
fn local_numbers(
lang: &LangSpec,
source: &str,
tree: &Tree,
ranges: &[Range<'_>],
binders: &[Range<'_>],
) -> HashMap<usize, String> {
let extent = Extent { ranges };
let unpunched: Vec<Range<'_>> = ranges.iter().map(|&(s, e, _)| (s, e, &[][..])).collect();
let whole = Extent { ranges: &unpunched };
let all: Vec<Range<'_>> = unpunched.iter().chain(binders).copied().collect();
let wide = Extent { ranges: &all };
let (sites, refs) = match lang.scoping {
Scoping::Free => return HashMap::new(),
Scoping::Query(query) => query_locals(lang, query, source, tree, &wide),
Scoping::Rust => rust_locals(source, tree, &wide),
Scoping::Python => python_locals(source, tree, &wide),
};
let text = |n: Node<'_>| n.utf8_text(source.as_bytes()).unwrap_or("");
let resolve = |sites: &[Site<'_>], node: Node<'_>| {
sites
.iter()
.filter(|s| text(s.node) == text(node) && s.sees(node.start_byte()))
.max_by_key(|s| (s.from, std::cmp::Reverse(s.to)))
.map(|s| s.node.id())
};
let sites: Vec<Site<'_>> = sites.into_iter().filter(|s| wide.holds(s.node)).collect();
let site_ids: HashSet<usize> = sites.iter().map(|s| s.node.id()).collect();
let read: HashSet<usize> = refs
.iter()
.filter(|n| extent.holds(**n) && !site_ids.contains(&n.id()))
.filter_map(|n| resolve(&sites, *n))
.collect();
let mut sites: Vec<Site<'_>> = sites
.into_iter()
.filter(|s| whole.holds(s.node) || read.contains(&s.node.id()))
.collect();
sites.sort_by_key(|s| s.node.start_byte());
let inner: HashSet<(&str, usize, usize)> = sites
.iter()
.filter(|s| whole.holds(s.node))
.map(|s| (text(s.node), s.from, s.to))
.collect();
let mut variables: HashMap<(&str, usize, usize), usize> = HashMap::new();
let mut number: HashMap<usize, Option<usize>> = HashMap::new();
let mut by_name: HashMap<&str, Vec<&Site<'_>>> = HashMap::new();
let mut out = HashMap::new();
for site in &sites {
let name = text(site.node);
let key = (name, site.from, site.to);
let n = inner.contains(&key).then(|| {
let next = variables.len() + 1;
*variables.entry(key).or_insert(next)
});
number.insert(site.node.id(), n);
by_name.entry(name).or_default().push(site);
let written = match n {
Some(n) if !site.named => label(site.node, name, n),
_ => name.to_string(),
};
out.insert(site.node.id(), written);
}
for node in refs {
if !extent.holds(node) || number.contains_key(&node.id()) {
continue;
}
let at = node.start_byte();
let site = by_name.get(text(node)).and_then(|sites| {
sites
.iter()
.filter(|s| s.sees(at))
.max_by_key(|s| (s.from, std::cmp::Reverse(s.to)))
});
if let Some(site) = site {
let written = match number[&site.node.id()] {
Some(n) if !site.named => label(node, text(node), n),
_ => text(node).to_string(),
};
out.insert(node.id(), written);
}
}
out
}
fn macro_string_names(source: &str, leaf: Node<'_>) -> Vec<String> {
let in_macro = leaf
.parent()
.filter(|p| matches!(p.kind(), "string_literal" | "raw_string_literal"))
.and_then(|literal| literal.parent())
.is_some_and(|group| group.kind() == "token_tree");
if leaf.kind() != "string_content" || !in_macro {
return Vec::new();
}
let text = leaf.utf8_text(source.as_bytes()).unwrap_or("");
format_captures(text)
.into_iter()
.map(|(s, e)| text[s..e].to_string())
.collect()
}
fn format_captures(text: &str) -> Vec<(usize, usize)> {
let bytes = text.as_bytes();
let ident_end = |from: usize| {
let mut i = from;
if bytes
.get(i)
.is_some_and(|b| b.is_ascii_alphabetic() || *b == b'_')
{
i += 1;
while bytes
.get(i)
.is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_')
{
i += 1;
}
}
i
};
let name = |s: usize, e: usize| e > s && &text[s..e] != "_";
let mut out = Vec::new();
let mut i = 0;
while i < bytes.len() {
if bytes[i] != b'{' {
i += 1;
continue;
}
if bytes.get(i + 1) == Some(&b'{') {
i += 2;
continue;
}
let Some(close) = text[i..].find('}').map(|c| i + c) else {
break;
};
let open = i + 1;
let end = ident_end(open);
if name(open, end) && matches!(bytes.get(end), Some(b'}' | b':')) {
out.push((open, end));
}
if let Some(colon) = text[open..close].find(':').map(|c| open + c) {
let mut j = colon + 1;
while j < close {
let e = ident_end(j);
if e == j {
j += 1;
continue;
}
if bytes.get(e) == Some(&b'$') && name(j, e) {
out.push((j, e));
}
j = e;
}
}
i = close + 1;
}
out
}
pub fn free_names(lang: &LangSpec, source: &str, tree: &Tree) -> Vec<(String, usize, usize)> {
if !matches!(
lang.id,
"rust" | "javascript" | "typescript" | "tsx" | "python"
) {
return Vec::new();
}
let root = tree.root_node();
let mut out = Vec::new();
let mut items = Vec::new();
let mut stack: Vec<Node<'_>> = root.named_children(&mut root.walk()).collect();
stack.reverse();
while let Some(item) = stack.pop() {
let mut namespace = item;
while matches!(
namespace.kind(),
"export_statement" | "expression_statement"
) {
match namespace.named_child(0) {
Some(inner) => namespace = inner,
None => break,
}
}
let body = (namespace.kind() == "internal_module")
.then(|| namespace.child_by_field_name("body"))
.flatten();
match body {
Some(body) => {
let mut inner: Vec<Node<'_>> = body.named_children(&mut body.walk()).collect();
inner.reverse();
stack.extend(inner);
}
None => items.push(item),
}
}
for item in items {
let ranges: &[Range<'_>] = &[(item.start_byte(), item.end_byte(), &[])];
let locals = local_numbers(lang, source, tree, ranges, &[]);
let extent = Extent { ranges };
visit(
item,
None,
Some(root),
&extent,
&mut |node, field, parent| {
let tag = parent.is_some_and(|p| {
matches!(
p.kind(),
"jsx_opening_element" | "jsx_closing_element" | "jsx_self_closing_element"
)
}) && node
.utf8_text(source.as_bytes())
.is_ok_and(|t| t.starts_with(|c: char| c.is_ascii_uppercase()));
let declared = !tag
&& field.is_some_and(|f| matches!(f, "name" | "macro" | "label" | "attribute"));
let read = matches!(node.kind(), "identifier" | "shorthand_property_identifier");
let matched = || lang.id == "rust" && refutable(node);
if read && !declared && (!locals.contains_key(&node.id()) || matched()) {
if let Ok(name) = node.utf8_text(source.as_bytes()) {
out.push((name.to_string(), node.start_byte(), node.end_byte()));
}
}
true
},
);
}
out
}
fn label(node: Node<'_>, text: &str, n: usize) -> String {
let shorthand = node.kind().starts_with("shorthand_")
|| node
.parent()
.is_some_and(|p| p.kind().starts_with("shorthand_"));
if shorthand {
format!("{text}=${n}")
} else {
format!("${n}")
}
}
type Range<'a> = (usize, usize, &'a [(usize, usize)]);
struct Extent<'a> {
ranges: &'a [Range<'a>],
}
impl Extent<'_> {
fn touches(&self, node: Node<'_>) -> bool {
self.ranges
.iter()
.any(|&(start, end, _)| node.end_byte() > start && node.start_byte() < end)
}
fn holds(&self, node: Node<'_>) -> bool {
self.ranges.iter().any(|&(start, end, punch)| {
node.start_byte() >= start && node.end_byte() <= end && !punched_out(node, punch)
})
}
fn bounds(&self) -> (usize, usize) {
let start = self.ranges.iter().map(|r| r.0).min().unwrap_or(0);
let end = self.ranges.iter().map(|r| r.1).max().unwrap_or(0);
(start, end)
}
}
fn visit<'a>(
node: Node<'a>,
field: Option<&'a str>,
parent: Option<Node<'a>>,
extent: &Extent<'_>,
f: &mut impl FnMut(Node<'a>, Option<&'a str>, Option<Node<'a>>) -> bool,
) {
if !extent.touches(node) || !f(node, field, parent) {
return;
}
let mut cursor = node.walk();
if !cursor.goto_first_child() {
return;
}
loop {
visit(cursor.node(), cursor.field_name(), Some(node), extent, f);
if !cursor.goto_next_sibling() {
break;
}
}
}
fn query_locals<'a>(
lang: &LangSpec,
query: &Query,
source: &str,
tree: &'a Tree,
extent: &Extent<'_>,
) -> (Vec<Site<'a>>, Vec<Node<'a>>) {
let names = query.capture_names();
let mut scopes = std::collections::HashSet::new();
let mut defs: Vec<Node<'a>> = Vec::new();
let mut refs = Vec::new();
let mut cursor = QueryCursor::new();
let (start, end) = extent.bounds();
cursor.set_byte_range(start..end);
let mut captures = cursor.captures(query, tree.root_node(), source.as_bytes());
while let Some((m, i)) = captures.next() {
let capture = m.captures()[*i];
match names[capture.index as usize] {
"local.scope" => {
scopes.insert(capture.node.id());
}
"local.definition"
if !defs.iter().any(|d| d.id() == capture.node.id()) && !in_type(capture.node) =>
{
let class = capture.node.parent().is_some_and(|p| {
matches!(p.kind(), "class_declaration" | "abstract_class_declaration")
});
let in_function = || {
let mut at = capture.node.parent();
while let Some(n) = at {
if is_function_kind(lang, n.kind()) {
return true;
}
at = n.parent();
}
false
};
if !class || in_function() {
defs.push(capture.node);
}
}
"local.reference" => refs.push(capture.node),
_ => {}
}
}
let root = tree.root_node();
let sites = defs
.into_iter()
.map(|node| {
let hoisted = node
.parent()
.filter(|p| p.kind() == "variable_declarator")
.and_then(|p| p.parent())
.is_some_and(|p| p.kind() == "variable_declaration");
let mut scope = node.parent();
while let Some(s) = scope.filter(|s| {
if hoisted {
!is_function_kind(lang, s.kind())
} else {
!scopes.contains(&s.id())
}
}) {
scope = s.parent();
}
let scope = scope.unwrap_or(root);
Site {
node,
from: scope.start_byte(),
to: scope.end_byte(),
named: false,
gaps: Vec::new(),
}
})
.collect();
(sites, refs)
}
fn in_type(node: Node<'_>) -> bool {
std::iter::successors(node.parent(), |n| n.parent()).any(|n| is_type_syntax(n.kind()))
}
fn ancestor<'a>(node: Node<'a>, kinds: &[&str]) -> Option<Node<'a>> {
let mut current = node.parent();
while let Some(n) = current {
if kinds.contains(&n.kind()) {
return Some(n);
}
current = n.parent();
}
None
}
fn rust_locals<'a>(
source: &str,
tree: &'a Tree,
extent: &Extent<'_>,
) -> (Vec<Site<'a>>, Vec<Node<'a>>) {
let mut sites = Vec::new();
let mut refs = Vec::new();
let mut captured = HashSet::new();
visit(
tree.root_node(),
None,
None,
extent,
&mut |node, field, parent| {
let field_of = |name: &str| node.child_by_field_name(name);
match node.kind() {
"attribute_item" | "inner_attribute_item" => return false,
"let_declaration" => {
if let (Some(pattern), Some(block)) = (field_of("pattern"), parent) {
rust_pattern(
source,
pattern,
node.end_byte(),
block.end_byte(),
&mut sites,
);
}
}
"parameter" => {
let owner = ancestor(node, &["function_item", "closure_expression"]);
if let (Some(pattern), Some(owner)) = (field_of("pattern"), owner) {
rust_pattern(
source,
pattern,
node.end_byte(),
owner.end_byte(),
&mut sites,
);
}
}
"closure_parameters" => {
let to = parent.map_or(node.end_byte(), |p| p.end_byte());
let mut cursor = node.walk();
for child in node.named_children(&mut cursor) {
if child.kind() != "parameter" {
rust_pattern(source, child, node.end_byte(), to, &mut sites);
}
}
}
"for_expression" => {
if let (Some(pattern), Some(body)) = (field_of("pattern"), field_of("body")) {
rust_pattern(
source,
pattern,
body.start_byte(),
body.end_byte(),
&mut sites,
);
}
}
"match_pattern" => {
let to = parent.map_or(node.end_byte(), |arm| arm.end_byte());
let mut cursor = node.walk();
let condition = field_of("condition").map(|c| c.id());
for child in node.named_children(&mut cursor) {
if Some(child.id()) != condition {
rust_pattern(source, child, child.end_byte(), to, &mut sites);
}
}
}
"let_condition" => {
let owner = ancestor(node, &["if_expression", "while_expression"]);
let body = owner.and_then(|o| {
o.child_by_field_name("consequence")
.or(o.child_by_field_name("body"))
});
if let (Some(pattern), Some(body)) = (field_of("pattern"), body) {
rust_pattern(
source,
pattern,
node.end_byte(),
body.end_byte(),
&mut sites,
);
}
}
"identifier" if is_rust_reference(field, parent) => refs.push(node),
"shorthand_field_identifier"
if parent.is_some_and(|p| p.kind() == "shorthand_field_initializer") =>
{
refs.push(node)
}
"string_content" => captured.extend(macro_string_names(source, node)),
_ => {}
}
true
},
);
for site in &mut sites {
let name = site.node.utf8_text(source.as_bytes()).unwrap_or("");
site.named |= captured.contains(name);
}
(sites, refs)
}
pub fn refutable(node: Node<'_>) -> bool {
let mut child = node;
while let Some(p) = child.parent() {
let at = |field: &str| {
p.child_by_field_name(field)
.is_some_and(|n| n.id() == child.id())
};
let pattern = at("pattern");
match p.kind() {
"match_pattern" => return !at("condition"),
"let_condition" => return pattern,
"let_declaration" => return pattern && p.child_by_field_name("alternative").is_some(),
"match_arm" | "block" | "parameter" | "closure_parameters" | "for_expression" => {
return false
}
_ => child = p,
}
}
false
}
fn is_rust_reference(field: Option<&str>, parent: Option<Node<'_>>) -> bool {
let in_path = parent.is_some_and(|p| {
matches!(
p.kind(),
"scoped_identifier"
| "scoped_type_identifier"
| "scoped_use_list"
| "use_as_clause"
| "use_list"
| "use_declaration"
)
});
!in_path && !field.is_some_and(|f| matches!(f, "macro" | "name" | "type" | "label"))
}
fn rust_pattern<'a>(
source: &str,
pattern: Node<'a>,
from: usize,
to: usize,
sites: &mut Vec<Site<'a>>,
) {
match pattern.kind() {
"identifier" | "shorthand_field_identifier" => {
let name = pattern.utf8_text(source.as_bytes()).unwrap_or("");
if name.starts_with(|c: char| c.is_lowercase() || c == '_') {
sites.push(Site {
node: pattern,
from,
to,
named: false,
gaps: Vec::new(),
});
}
}
"scoped_identifier" | "scoped_type_identifier" | "range_pattern" => {}
_ => {
let mut cursor = pattern.walk();
if !cursor.goto_first_child() {
return;
}
loop {
let binds = !matches!(cursor.field_name(), Some("type" | "name"));
if binds && cursor.node().is_named() {
rust_pattern(source, cursor.node(), from, to, sites);
}
if !cursor.goto_next_sibling() {
break;
}
}
}
}
}
const PY_COMPREHENSIONS: &[&str] = &[
"list_comprehension",
"set_comprehension",
"dictionary_comprehension",
"generator_expression",
];
const PY_SCOPES: &[&str] = &[
"function_definition",
"lambda",
"class_definition",
"list_comprehension",
"set_comprehension",
"dictionary_comprehension",
"generator_expression",
];
fn python_locals<'a>(
source: &str,
tree: &'a Tree,
extent: &Extent<'_>,
) -> (Vec<Site<'a>>, Vec<Node<'a>>) {
let root = tree.root_node();
let scope_of = |node: Node<'a>| ancestor(node, PY_SCOPES).unwrap_or(root);
let mut targets: Vec<Node<'a>> = Vec::new();
let mut walrus: Vec<Node<'a>> = Vec::new();
let mut refs = Vec::new();
let mut nonlocal = Vec::new();
let mut keyword = Vec::new();
visit(root, None, None, extent, &mut |node, field, parent| {
let field_of = |name: &str| node.child_by_field_name(name);
match node.kind() {
"parameters" | "lambda_parameters" => {
let mut cursor = node.walk();
let params: Vec<_> = node.named_children(&mut cursor).collect();
let slash = params
.iter()
.position(|p| p.kind() == "positional_separator");
for (at, param) in params.into_iter().enumerate() {
let splat = |n: Node<'_>| {
matches!(n.kind(), "list_splat_pattern" | "dictionary_splat_pattern")
};
let positional = slash.is_some_and(|slash| at < slash)
|| splat(param)
|| (param.kind() == "typed_parameter"
&& param.named_child(0).is_some_and(splat));
let name = match param.kind() {
"default_parameter" | "typed_default_parameter" => {
param.child_by_field_name("name")
}
"identifier" => Some(param),
_ => param.named_child(0),
};
let bound = name.into_iter().flat_map(|n| py_target(n));
if !positional {
keyword.extend(bound.clone().map(|n| n.id()));
}
targets.extend(bound);
}
}
"assignment" | "augmented_assignment" | "for_statement" | "for_in_clause" => {
targets.extend(field_of("left").into_iter().flat_map(|n| py_target(n)));
}
"as_pattern_target" => targets.extend(py_target(node)),
"named_expression" => walrus.extend(field_of("name")),
"global_statement" | "nonlocal_statement" => {
let mut cursor = node.walk();
for name in node.named_children(&mut cursor) {
nonlocal.push((scope_of(node).id(), name.utf8_text(source.as_bytes()).ok()));
}
return false;
}
"import_statement" | "import_from_statement" => return false,
"identifier" if is_python_reference(field, parent) => refs.push(node),
_ => {}
}
true
});
let walrus_scope = |node: Node<'a>| {
let mut scope = scope_of(node);
while PY_COMPREHENSIONS.contains(&scope.kind()) {
scope = scope_of(scope);
}
scope
};
let scoped = targets
.into_iter()
.map(|n| (n, scope_of(n)))
.chain(walrus.into_iter().map(|n| (n, walrus_scope(n))));
let sites = scoped
.filter(|(n, _)| n.kind() == "identifier")
.filter_map(|(node, scope)| {
let name = node.utf8_text(source.as_bytes()).ok();
if nonlocal.contains(&(scope.id(), name)) {
return None;
}
let class = scope.kind() == "class_definition";
let named = keyword.contains(&node.id()) || class;
Some(Site {
node,
from: scope.start_byte(),
to: scope.end_byte(),
named,
gaps: if class { class_gaps(scope) } else { Vec::new() },
})
})
.collect();
(sites, refs)
}
fn class_gaps(class: Node<'_>) -> Vec<(usize, usize)> {
let mut out = Vec::new();
let mut stack: Vec<Node<'_>> = class
.child_by_field_name("body")
.map(|b| b.named_children(&mut b.walk()).collect())
.unwrap_or_default();
while let Some(node) = stack.pop() {
match node.kind() {
"function_definition" | "lambda" | "class_definition" => {
if let Some(body) = node.child_by_field_name("body") {
out.push((body.start_byte(), body.end_byte()));
}
stack.extend(
node.named_children(&mut node.walk())
.filter(|c| Some(*c) != node.child_by_field_name("body")),
);
}
kind if PY_COMPREHENSIONS.contains(&kind) => {
let first = node
.named_children(&mut node.walk())
.find(|c| c.kind() == "for_in_clause")
.and_then(|c| c.child_by_field_name("right"));
match first {
Some(iter) => {
out.push((node.start_byte(), iter.start_byte()));
out.push((iter.end_byte(), node.end_byte()));
stack.push(iter);
}
None => out.push((node.start_byte(), node.end_byte())),
}
}
_ => stack.extend(node.named_children(&mut node.walk())),
}
}
out
}
fn py_target(node: Node<'_>) -> Vec<Node<'_>> {
match node.kind() {
"identifier" => vec![node],
"pattern_list"
| "tuple_pattern"
| "list_pattern"
| "tuple"
| "list"
| "parenthesized_expression"
| "list_splat_pattern"
| "list_splat"
| "dictionary_splat_pattern"
| "as_pattern_target" => {
let mut cursor = node.walk();
let children: Vec<_> = node.named_children(&mut cursor).collect();
children.into_iter().flat_map(py_target).collect()
}
_ => Vec::new(),
}
}
fn is_python_reference(field: Option<&str>, parent: Option<Node<'_>>) -> bool {
let Some(parent) = parent else {
return true;
};
!matches!(
(parent.kind(), field),
("attribute", Some("attribute"))
| ("keyword_argument", Some("name"))
| ("function_definition" | "class_definition", Some("name"))
| ("dotted_name" | "aliased_import", _)
)
}
fn hole(walk: &mut Walk<'_>, at: usize) {
if !std::mem::replace(&mut walk.holes[at], true) {
walk.out.push("hole".to_string());
}
}
fn punch_holding(node: Node<'_>, punch: &[(usize, usize)]) -> Option<usize> {
let (start, end) = (node.start_byte(), node.end_byte());
punch
.iter()
.position(|(ps, pe)| start >= *ps && end <= *pe && end > start)
}
fn punched_out(node: Node<'_>, punch: &[(usize, usize)]) -> bool {
let start = node.start_byte();
let end = node.end_byte();
punch
.iter()
.any(|(ps, pe)| start >= *ps && end <= *pe && end > start)
}
pub(crate) fn line_to_byte(source: &str, line: usize) -> Option<usize> {
if line == 0 {
return None;
}
let mut current = 1usize;
for (idx, ch) in source.char_indices() {
if current == line {
return Some(idx);
}
if ch == '\n' {
current += 1;
}
}
if current == line {
return Some(source.len());
}
None
}
pub(crate) fn encode_digest(serialized: &str) -> String {
use blake3::Hasher;
const ALPHABET: &[u8; 32] = b"0123456789abcdefghjkmnpqrstvwxyz";
let mut hasher = Hasher::new();
hasher.update(serialized.as_bytes());
let mut xof = hasher.finalize_xof();
let mut bits = [0u8; 4];
xof.fill(&mut bits);
let mut value = u32::from_be_bytes(bits) as u64;
let mut out = String::with_capacity(5);
for _ in 0..5 {
let idx = (value & 0x1f) as usize;
out.push(ALPHABET[idx] as char);
value >>= 5;
}
out
}
#[cfg(test)]
mod lang_contracts {
use super::*;
#[test]
fn a_conflict_marker_is_seven_signs_then_a_label_or_the_line_end() {
for line in [
"<<<<<<< HEAD",
"<<<<<<<",
"||||||| base",
"=======",
"=======\r",
">>>>>>> feat\nx",
] {
assert!(is_conflict_marker(line), "{line:?}");
}
for line in [
"========",
"<<<<<<<<",
" =======",
">>>>>>>x",
"a <<<<<<< b",
] {
assert!(!is_conflict_marker(line), "{line:?}");
}
}
fn assert_comment_invariant(lang: &LangSpec, clean: &str, commented: &str, marker_line: usize) {
let a = mint_span_digest(lang, clean, marker_line, &[]).expect("clean digest");
let b = mint_span_digest(lang, commented, marker_line, &[]).expect("commented digest");
assert_eq!(a, b, "{}: comments must not move digest", lang.id);
}
fn assert_whitespace_invariant(lang: &LangSpec, a: &str, b: &str, marker_line: usize) {
let da = mint_span_digest(lang, a, marker_line, &[]).expect("a digest");
let db = mint_span_digest(lang, b, marker_line, &[]).expect("b digest");
assert_eq!(da, db, "{}: whitespace must not move digest", lang.id);
}
mod rust {
use super::*;
#[test]
fn contract() {
let src = "fn foo() {\n return value;\n}\n";
let commented = "fn foo() {\n // line\n /* block */\n return value;\n}\n";
assert_comment_invariant(&RUST, src, commented, 1);
assert_whitespace_invariant(&RUST, src, commented, 1);
}
#[test]
fn pin_inside_block_is_that_block() {
let src = "impl Project {\n // pin\n pub fn inner() {\n // pin\n value();\n }\n}\n";
let outer = span_bytes(&RUST, Path::new("a.rs"), src, 2).expect("impl");
let inner = span_bytes(&RUST, Path::new("a.rs"), src, 4).expect("body");
assert_eq!(
&src[outer.0..outer.1],
"impl Project {\n // pin\n pub fn inner() {\n // pin\n value();\n }\n}"
);
assert_eq!(
&src[inner.0..inner.1],
"{\n // pin\n value();\n }"
);
}
#[test]
fn pin_outside_construct_has_no_span() {
let src = "// pin\nimpl Foo {}\n";
assert!(span_bytes(&RUST, Path::new("a.rs"), src, 1).is_none());
let src = "// pin\n#[inline]\nfn foo() {}\n";
let (start, end) = span_bytes(&RUST, Path::new("a.rs"), src, 1).expect("fn");
assert_eq!(&src[start..end], "#[inline]\nfn foo() {}");
}
#[test]
fn explicit_end_bounds_a_stretch() {
let src = "fn quote() {\n setup();\n // § abcdefgh1\n price();\n // § end abcdefgh1\n teardown();\n}\n";
let extent = span_bytes(&RUST, Path::new("a.rs"), src, 3).expect("explicit");
let text = &src[extent.0..extent.1];
assert!(text.contains("price();"));
assert!(!text.contains("setup();"));
assert!(!text.contains("teardown();"));
}
#[test]
fn explicit_end_opens_a_span_outside_any_construct() {
let src = "// § abcdefgh1\nconst A: u8 = 1;\nconst B: u8 = 2;\n// § end abcdefgh1\n";
assert!(span_bytes(&RUST, Path::new("a.rs"), src, 1).is_some());
}
#[test]
fn trailing_comma_is_formatting() {
let flat = "fn f() {\n // pin\n save(a, b);\n}\n";
let wrapped = "fn f() {\n // pin\n save(\n a,\n b,\n );\n}\n";
let one = mint_span_digest(&RUST, flat, 2, &[]).unwrap();
assert_eq!(one, mint_span_digest(&RUST, wrapped, 2, &[]).unwrap());
let call = "fn f() {\n // pin\n save(a, b);\n}\n";
let dropped = "fn f() {\n // pin\n save(a);\n}\n";
assert_ne!(
mint_span_digest(&RUST, call, 2, &[]).unwrap(),
mint_span_digest(&RUST, dropped, 2, &[]).unwrap()
);
}
#[test]
fn trailing_comma_in_a_macro_is_formatting() {
let flat =
"fn f() {\n // pin\n let v = vec![a, b];\n assert_eq!(x, (y, z));\n}\n";
let wrapped = "fn f() {\n // pin\n let v = vec![\n a,\n b,\n ];\n assert_eq!(x, (y, z,),);\n}\n";
assert_eq!(
mint_span_digest(&RUST, flat, 2, &[]).unwrap(),
mint_span_digest(&RUST, wrapped, 2, &[]).unwrap()
);
}
#[test]
fn trailing_comma_in_a_user_macro_is_a_token() {
let one = "fn f() {\n // pin\n m!(0);\n}\n";
let two = "fn f() {\n // pin\n m!(0,);\n}\n";
assert_ne!(
mint_span_digest(&RUST, one, 2, &[]).unwrap(),
mint_span_digest(&RUST, two, 2, &[]).unwrap()
);
}
#[test]
fn a_one_tuple_in_a_macro_is_not_a_trailing_separator() {
let tuple = "fn f() {\n // pin\n m!(x, (y,));\n}\n";
let paren = "fn f() {\n // pin\n m!(x, (y));\n}\n";
assert_ne!(
mint_span_digest(&RUST, tuple, 2, &[]).unwrap(),
mint_span_digest(&RUST, paren, 2, &[]).unwrap()
);
}
#[test]
fn grouping_block_is_the_close() {
let src = "fn quote() {\n setup();\n {\n // pin\n price();\n }\n teardown();\n}\n";
let extent = span_bytes(&RUST, Path::new("a.rs"), src, 4).expect("block");
assert_eq!(
&src[extent.0..extent.1],
"{\n // pin\n price();\n }"
);
}
}
mod python {
use super::*;
#[test]
fn contract() {
let src = "def foo():\n return value\n";
let commented = "def foo():\n # line\n return value\n";
assert_comment_invariant(&PYTHON, src, commented, 1);
assert_whitespace_invariant(&PYTHON, src, commented, 1);
}
}
mod javascript {
use super::*;
#[test]
fn contract() {
let src = "function foo() {\n return value;\n}\n";
let commented = "function foo() {\n // line\n /* block */\n return value;\n}\n";
assert_comment_invariant(&JAVASCRIPT, src, commented, 1);
}
}
mod typescript {
use super::*;
#[test]
fn contract() {
let src = "function foo(): number {\n return value;\n}\n";
let commented = "function foo(): number {\n // line\n return value;\n}\n";
assert_comment_invariant(&TYPESCRIPT, src, commented, 1);
}
}
mod tsx {
use super::*;
#[test]
fn contract() {
let src = "export function Foo() {\n return <span>ok</span>;\n}\n";
let commented = "export function Foo() {\n // line\n return <span>ok</span>;\n}\n";
assert_comment_invariant(&TSX, src, commented, 1);
}
}
mod html {
use super::*;
#[test]
fn contract() {
let src = "<div>\n value\n</div>\n";
let commented = "<div>\n <!-- line -->\n value\n</div>\n";
assert_comment_invariant(&HTML, src, commented, 1);
}
}
mod css {
use super::*;
#[test]
fn contract() {
let src = ".a {\n color: red;\n}\n";
let commented = ".a {\n /* line */\n color: red;\n}\n";
assert_comment_invariant(&CSS, src, commented, 1);
}
}
mod hcl {
use super::*;
#[test]
fn contract() {
let src = "resource \"a\" \"b\" {\n x = 1\n}\n";
let commented = "resource \"a\" \"b\" {\n # line\n x = 1\n}\n";
assert_comment_invariant(&HCL, src, commented, 1);
}
}
mod yaml {
use super::*;
#[test]
fn contract() {
let src = "# pin\na:\n b: 1\n";
let commented = "# pin\na:\n # line\n b: 1 # trailing\n";
assert_comment_invariant(&YAML, src, commented, 1);
assert_whitespace_invariant(&YAML, src, commented, 1);
}
}
mod cedar {
use super::*;
#[test]
fn contract() {
let src = "// pin\npermit (principal, action, resource)\nwhen { context.a };\n";
let commented = "// pin\npermit (principal, action, resource)\nwhen {\n // line\n context.a // trailing\n};\n";
assert_comment_invariant(&CEDAR, src, commented, 1);
assert_whitespace_invariant(&CEDAR, src, commented, 1);
}
}
mod bash {
use super::*;
#[test]
fn contract() {
let src = "#!/bin/sh\nfoo() {\n echo value\n}\n";
let commented = "#!/bin/bash\nfoo() {\n # line\n echo value\n}\n";
assert_comment_invariant(&BASH, src, commented, 2);
assert_whitespace_invariant(&BASH, src, commented, 2);
}
#[test]
fn pin_inside_body_is_the_body() {
let src = "foo() {\n # pin\n echo value\n}\n";
let extent = span_bytes(&BASH, Path::new("a.sh"), src, 2).expect("body");
assert_eq!(&src[extent.0..extent.1], "{\n # pin\n echo value\n}");
}
#[test]
fn pin_at_top_level_has_no_span() {
let src = "# pin\necho value\n";
assert!(span_bytes(&BASH, Path::new("a.sh"), src, 1).is_none());
}
}
mod markdown {
use super::*;
#[test]
fn contract() {
let src = "# Title\n\nhello\n";
let spaced = "# Title\n\nhello \n";
assert_whitespace_invariant(&MARKDOWN, src, spaced, 1);
}
}
#[test]
fn every_code_ext_is_pinned() {
for ext in crate::walk::CODE_EXTS {
assert!(
lang_for_extension(ext).is_some(),
"extension `{ext}` has no pinned Tree-sitter grammar"
);
}
}
}
#[cfg(test)]
#[path = "shape_cases/mod.rs"]
mod shape_cases;