use crate::lang_helpers::case_arms::pattern_is_bare_underscore;
use crate::role_table;
use crate::roles::control_flow::else_if_parent_clause_gate;
use crate::{Ancestors, Node, Rust};
else_if_parent_clause_gate!(Rust, ElseClause);
fn is_decision_arm<'a>(node: &Node<'a>, _ancestors: Ancestors<'a, '_>) -> bool {
!node
.child_by_field_name("pattern")
.is_some_and(|pat| pattern_is_bare_underscore(&pat, Rust::UNDERSCORE as u16))
}
fn has_alternative(node: &Node<'_>) -> bool {
node.child_by_field_name("alternative").is_some()
}
fn not_in_type_syntax<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool {
!ancestors.parent(node).is_some_and(|parent| {
matches!(
parent.kind_id().into(),
Rust::ImplItem | Rust::HigherRankedTraitBound | Rust::ForLifetimes | Rust::AbstractType
)
})
}
fn has_guard(node: &Node<'_>) -> bool {
node.child_by_field_name("condition").is_some()
}
const DOC_MARKERS: [u16; 4] = [
Rust::OuterDocCommentMarker as u16,
Rust::OuterDocCommentMarker2 as u16,
Rust::InnerDocCommentMarker as u16,
Rust::InnerDocCommentMarker2 as u16,
];
fn has_doc_marker_child(node: &Node<'_>) -> bool {
node.child_count() > 2 && node.wraps_any(&DOC_MARKERS)
}
role_table! {
lang: Rust;
Call { owns [CallExpression] }
StringLit { owns [StringLiteral, RawStringLiteral] }
Comparison {
owns [BinaryExpression(holds_payer)]
pays [
EQEQ, BANGEQ, LTEQ, GTEQ,
LT under BinaryExpression, GT under BinaryExpression,
]
project "operator"
}
ShortCircuit {
owns [
BinaryExpression(holds_payer),
LetChain, LetChain2,
]
pays [AMPAMP, PIPEPIPE]
project "operator"
}
EagerLogical {
owns []
excludes [
AMP "a boolean `&` is the integral `&`'s kind, which the grammar does not tell apart",
PIPE "a boolean `|` is the integral `|`'s kind, which the grammar does not tell apart",
CARET "a boolean `^` is the integral `^`'s kind, which the grammar does not tell apart",
]
}
Ternary { absent "Rust has no ternary operator; `if` is an expression" }
NullSafe { absent "Rust has no optional navigation or null coalescing; `?` is an exit" }
CaseArm { owns [MatchArm(gated_by is_decision_arm), MatchArm2(gated_by is_decision_arm)] }
Guard {
owns [MatchPattern(gated_by has_guard no_chain)]
pays [If under MatchPattern]
}
Branch {
owns [IfExpression, LetDeclaration(pays_itself gated_by has_alternative no_chain)]
pays [If]
}
Switch { owns [MatchExpression] }
Loop {
owns [ForExpression, WhileExpression, LoopExpression]
pays [For gated_by not_in_type_syntax, While, Loop]
}
Catch { absent "Rust has no exception handling; `?` is an exit and `match` on a `Result` a switch" }
ElseIf { owns [IfExpression(gated_by continues_else_clause)] pays [] }
Exit { owns [ReturnExpression, TryExpression] }
Modifier {
owns [Pub, MutableSpecifier, Const, Static, Unsafe, Async, Extern, Move, Dyn]
}
DeclKeyword { owns [Fn, Let, Enum, Struct, Union, Trait, Impl, Use, Mod, Type, Where] }
Primitive {
owns [
PrimitiveType, PrimitiveType2, PrimitiveType3, PrimitiveType4, PrimitiveType5,
PrimitiveType6, PrimitiveType7, PrimitiveType8, PrimitiveType9, PrimitiveType10,
PrimitiveType11, PrimitiveType12, PrimitiveType13, PrimitiveType14, PrimitiveType15,
PrimitiveType16, PrimitiveType17,
]
}
FuncOpener { owns [FunctionItem(callable opens Function), ClosureExpression(opens Function)] }
Closure { owns [ClosureExpression] }
Container { owns [SourceFile(opens Unit), ImplItem(opens Impl), TraitItem(opens Trait)] }
Member { owns [FieldDeclaration, ConstItem, StaticItem, AssociatedType] }
Comment { owns [LineComment, BlockComment] }
DocComment {
owns [
LineComment(gated_by has_doc_marker_child no_chain),
BlockComment(gated_by has_doc_marker_child no_chain),
]
}
Docstring { absent "Rust documents with `///` comments, not string literals" }
DocTarget {
owns [
ModItem,
StructItem,
UnionItem,
EnumItem,
EnumVariant,
FieldDeclaration,
ConstItem,
StaticItem,
TypeItem,
FunctionItem,
FunctionSignatureItem,
ImplItem,
TraitItem,
AssociatedType,
UseDeclaration,
ExternCrateDeclaration,
MacroDefinition,
]
}
DocRunOpener { absent "rustdoc attaches every doc comment to an item; none documents by its own content" }
DocRunDirective { absent "rustdoc reads no directive comment" }
DocBodyResidual { absent "only the callables and closures hold a doc comment in a body; the trait default" }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::RustCode;
use crate::test_support::for_each_node_with_chain;
#[cfg(feature = "rust")]
#[test]
fn guard_owns_a_pattern_only_where_it_carries_a_condition() {
let source = b"fn f(x: i32) -> i32 { match x { a if a > 0 => 1, b => b, _ => 0 } }\n";
let (mut patterns, mut owned, mut paid) = (0, Vec::new(), Vec::new());
for_each_node_with_chain::<RustCode>(source, |node, chain| {
let ancestors = Ancestors::known(chain);
let text = || node.utf8_text(source).expect("fixture is UTF-8").to_owned();
if node.kind_id() == Rust::MatchPattern as u16 {
patterns += 1;
}
if guard::owns(node, source, ancestors) {
owned.push(text());
}
if guard::pays_at_leaf(node, source, ancestors) {
paid.push(text());
}
});
assert_eq!(patterns, 3);
assert_eq!(owned, ["a if a > 0"]);
assert_eq!(paid, ["if"]);
}
#[cfg(feature = "rust")]
#[test]
fn doc_markers_reach_the_gate_as_the_base_ids() {
let source = b"/// a\n//! b\n/** c */\n/*! d */\n/*!*/\nfn f() {}\n";
let mut markers = Vec::new();
for_each_node_with_chain::<RustCode>(source, |node, chain| {
if matches!(
node.kind(),
"outer_doc_comment_marker" | "inner_doc_comment_marker"
) {
let comment = Ancestors::known(chain)
.parent(node)
.map(|parent| parent.kind());
markers.push((comment, node.kind_id()));
}
});
let (outer, inner) = (
Rust::OuterDocCommentMarker as u16,
Rust::InnerDocCommentMarker as u16,
);
assert_eq!(
markers,
[
(Some("line_comment"), outer),
(Some("line_comment"), inner),
(Some("block_comment"), outer),
(Some("block_comment"), inner),
(Some("block_comment"), inner),
]
);
}
#[cfg(feature = "rust")]
#[test]
fn doc_comment_gate_scans_a_doc_comment_and_no_plain_one() {
use crate::node::child_scan_cursors;
let source = b"// a\n//// b\n/* c */\n/**/\n/***/\n/// d\n//! e\n/** f */\n/*! g */\n/*!*/\nfn f() {}\n";
let mut asked = Vec::new();
for_each_node_with_chain::<RustCode>(source, |node, chain| {
let ancestors = Ancestors::known(chain);
if !comment::owns(node, source, ancestors) {
return;
}
let before = child_scan_cursors::observed();
let doc = doc_comment::owns(node, source, ancestors);
let scans = child_scan_cursors::observed() - before;
let text = node.utf8_text(source).expect("fixture is UTF-8");
asked.push((text.trim_end().to_owned(), doc, scans));
});
let expected = [
("// a", false, 0),
("//// b", false, 0),
("/* c */", false, 0),
("/**/", false, 0),
("/***/", false, 0),
("/// d", true, 1),
("//! e", true, 1),
("/** f */", true, 1),
("/*! g */", true, 1),
("/*!*/", true, 1),
];
assert_eq!(
asked,
expected.map(|(text, doc, scans)| (text.to_owned(), doc, scans))
);
}
}