Skip to main content

ridx_syntax/
sema_fn.rs

1/*
2 * rust-intelligence — Ultra-fast, zero-memory code intelligence for Rust
3 * Copyright (c) 2026 Alexander Panasenko
4 *
5 * Contact: alex@prod.codes
6 * Author: https://prod.codes/about/
7 * Project: https://github.com/alex09x/rust-intelligence
8 * SPDX-License-Identifier: MIT OR Apache-2.0
9 */
10
11//! Syntax-only function-body semantics over [`SyntaxTree`]: parameter descriptors, scope-aware
12//! parameter use analysis (with shadowing and macro `TokenTree` separation), own `return` / `?`
13//! extraction, and tail expression lookup.
14
15use std::ops::Range;
16
17use crate::sema_macro::collect_own_cf;
18pub use crate::sema_pat::ParamBindings;
19use crate::sema_pat::{collect_pat_bindings, pat_binds_bytes};
20use crate::sema_scope::find_param_uses;
21use crate::syntax_kind::SyntaxKind as K;
22use crate::token::TokenKind as T;
23use crate::tree::{NodeId, SyntaxTree};
24
25/// Receiver form of a `self` parameter (`SelfParam`).
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub enum SelfKind<'s> {
28    /// `self`
29    Value,
30    /// `mut self`
31    MutValue,
32    /// `&self` or `&'a self`
33    Ref { lifetime: Option<&'s str> },
34    /// `&mut self` or `&'a mut self`
35    MutRef { lifetime: Option<&'s str> },
36    /// Explicit receiver type: `self: T` or `mut self: T` (e.g. `self: Box<Self>`).
37    Typed { mutability: bool, ty: &'s str },
38}
39
40impl<'s> SelfKind<'s> {
41    pub const fn is_ref(self) -> bool {
42        matches!(self, Self::Ref { .. } | Self::MutRef { .. })
43    }
44
45    pub const fn is_mut(self) -> bool {
46        matches!(self, Self::MutValue | Self::MutRef { .. } | Self::Typed { mutability: true, .. })
47    }
48
49    pub const fn lifetime(self) -> Option<&'s str> {
50        match self {
51            Self::Ref { lifetime } | Self::MutRef { lifetime } => lifetime,
52            _ => None,
53        }
54    }
55}
56
57/// Extracted syntax descriptor of one parameter (`SelfParam` or `Param`) in a `Fn` item.
58#[derive(Clone, Debug, PartialEq, Eq)]
59pub struct ParamInfo<'s> {
60    pub node: NodeId,
61    pub self_kind: Option<SelfKind<'s>>,
62    pub pat: Option<NodeId>,
63    pub pat_text: Option<&'s str>,
64    pub bindings: ParamBindings<'s>,
65    pub ty: Option<NodeId>,
66    pub ty_text: Option<&'s str>,
67}
68
69/// Uses of a function parameter inside the function body, split into confident AST references and
70/// uncertain macro `TokenTree` occurrences.
71#[derive(Clone, Debug, Default, PartialEq, Eq)]
72pub struct ParamUses {
73    pub uses: Vec<Range<usize>>,
74    pub macro_uses: Vec<Range<usize>>,
75}
76
77impl ParamUses {
78    #[inline]
79    pub fn is_unused(&self) -> bool {
80        self.uses.is_empty() && self.macro_uses.is_empty()
81    }
82
83    #[inline]
84    pub fn clear(&mut self) {
85        self.uses.clear();
86        self.macro_uses.clear();
87    }
88}
89
90/// Strips a leading `r#` raw-identifier prefix so `r#foo` and `foo` compare equal.
91#[inline]
92pub fn norm_ident(raw: &str) -> &str {
93    raw.strip_prefix("r#").unwrap_or(raw)
94}
95
96/// Returns the body `BlockExpr` of a `Fn` node, or `None` for declarations without a body (`fn f();`).
97#[inline]
98pub fn fn_body(tree: &SyntaxTree<'_>, fn_id: NodeId) -> Option<NodeId> {
99    if tree.kind(fn_id) != K::Fn {
100        return None;
101    }
102    // Body `BlockExpr` is always the last child of `Fn` when present.
103    let last = tree.children(fn_id).last()?;
104    (tree.kind(last) == K::BlockExpr).then_some(last)
105}
106
107/// Extracts all parameters (`SelfParam` followed by `Param`s) of `fn_id` into `out` (cleared first).
108pub fn params_into<'s>(tree: &SyntaxTree<'s>, fn_id: NodeId, out: &mut Vec<ParamInfo<'s>>) {
109    out.clear();
110    if tree.kind(fn_id) != K::Fn {
111        return;
112    }
113    let Some(param_list) = tree.child(fn_id, K::ParamList) else { return };
114    let count = tree.children(param_list).filter(|&c| matches!(tree.kind(c), K::SelfParam | K::Param)).count();
115    if count == 0 {
116        return;
117    }
118    out.reserve(count);
119    for ch in tree.children(param_list) {
120        match tree.kind(ch) {
121            K::SelfParam => out.push(extract_self_param(tree, ch)),
122            K::Param => out.push(extract_value_param(tree, ch)),
123            _ => {}
124        }
125    }
126}
127
128/// Extracts all parameters (`SelfParam` followed by `Param`s) of `fn_id` in declaration order.
129pub fn params<'s>(tree: &SyntaxTree<'s>, fn_id: NodeId) -> Vec<ParamInfo<'s>> {
130    let mut out = Vec::new();
131    params_into(tree, fn_id, &mut out);
132    out
133}
134
135/// Extracts the normalized bound identifier names introduced by `pat_id` in source order (deduplicated).
136pub fn pat_bindings<'s>(tree: &SyntaxTree<'s>, pat_id: NodeId) -> Vec<&'s str> {
137    let mut b = ParamBindings::empty();
138    collect_pat_bindings(tree, pat_id, &mut b);
139    b.as_slice().to_vec()
140}
141
142/// Finds uses of parameter `name` within `fn_id`'s body into reusable `out` (cleared first).
143pub fn param_uses_into(tree: &SyntaxTree<'_>, fn_id: NodeId, name: &str, out: &mut ParamUses) {
144    out.clear();
145    let target = norm_ident(name);
146    if target.is_empty() || target == "_" {
147        return;
148    }
149    let Some(body) = fn_body(tree, fn_id) else { return };
150    if !fn_declares_param(tree, fn_id, target) {
151        return;
152    }
153    find_param_uses(tree, body, target, out);
154}
155
156/// Finds uses of parameter `name` (normalized; `"self"` for receiver) within `fn_id`'s body.
157pub fn param_uses(tree: &SyntaxTree<'_>, fn_id: NodeId, name: &str) -> ParamUses {
158    let mut out = ParamUses::default();
159    param_uses_into(tree, fn_id, name, &mut out);
160    out
161}
162
163/// Finds the uses of `name` (normalized), bound by the `let` statement `let_stmt`, in the rest of its block: up to a
164/// statement that binds the name again, through blocks, closures and macro arguments, as `param_uses` does.
165pub fn let_uses(tree: &SyntaxTree<'_>, let_stmt: NodeId, name: &str) -> ParamUses {
166    let mut out = ParamUses::default();
167    crate::sema_scope::find_let_uses(tree, let_stmt, name, &mut out);
168    out
169}
170
171/// Collects `ReturnExpr` nodes belonging to `fn_id` into `out` (cleared first).
172pub fn own_returns_into(tree: &SyntaxTree<'_>, fn_id: NodeId, out: &mut Vec<NodeId>) {
173    out.clear();
174    if let Some(body) = fn_body(tree, fn_id) {
175        collect_own_cf(tree, body, false, K::ReturnExpr, out);
176    }
177}
178
179/// Returns all `ReturnExpr` nodes belonging to `fn_id` itself.
180pub fn own_returns(tree: &SyntaxTree<'_>, fn_id: NodeId) -> Vec<NodeId> {
181    let mut out = Vec::new();
182    own_returns_into(tree, fn_id, &mut out);
183    out
184}
185
186/// Collects `TryExpr` (`?`) nodes belonging to `fn_id` into `out` (cleared first).
187pub fn own_try_ops_into(tree: &SyntaxTree<'_>, fn_id: NodeId, out: &mut Vec<NodeId>) {
188    out.clear();
189    if let Some(body) = fn_body(tree, fn_id) {
190        collect_own_cf(tree, body, true, K::TryExpr, out);
191    }
192}
193
194/// Returns all `TryExpr` (`?`) nodes belonging to `fn_id` itself.
195pub fn own_try_ops(tree: &SyntaxTree<'_>, fn_id: NodeId) -> Vec<NodeId> {
196    let mut out = Vec::new();
197    own_try_ops_into(tree, fn_id, &mut out);
198    out
199}
200
201/// Returns the tail expression of `fn_id`'s body `BlockExpr`, if present.
202#[inline]
203pub fn tail_expr(tree: &SyntaxTree<'_>, fn_id: NodeId) -> Option<NodeId> {
204    let body = fn_body(tree, fn_id)?;
205    let last = tree.children(body).last()?;
206    let k = tree.kind(last);
207    (k.is_expr() || k == K::MacroCall).then_some(last)
208}
209
210fn fn_declares_param(tree: &SyntaxTree<'_>, fn_id: NodeId, target: &str) -> bool {
211    let Some(pl) = tree.child(fn_id, K::ParamList) else { return false };
212    if target == "self" {
213        return tree.children(pl).next().is_some_and(|c| tree.kind(c) == K::SelfParam);
214    }
215    let tb = target.as_bytes();
216    let src = tree.src.as_bytes();
217    for ch in tree.children(pl) {
218        if tree.kind(ch) == K::Param {
219            if let Some(pat) = tree.children(ch).find(|&c| tree.kind(c).is_pat()) {
220                if pat_binds_bytes(&tree.nodes, &tree.tokens, src, pat, tb) {
221                    return true;
222                }
223            }
224        }
225    }
226    false
227}
228
229fn extract_self_param<'s>(tree: &SyntaxTree<'s>, id: NodeId) -> ParamInfo<'s> {
230    let mut has_amp = false;
231    let mut has_mut = false;
232    for tok in tree.tokens_of(id) {
233        match tok.kind {
234            T::Amp => has_amp = true,
235            T::Mut => has_mut = true,
236            T::SelfKw => break,
237            _ => {}
238        }
239    }
240    let lifetime = tree.child(id, K::Lifetime).map(|lt| tree.text(lt));
241    let ty = tree.children(id).find(|&c| tree.kind(c).is_type() || tree.kind(c) == K::MacroCall);
242    let ty_text = ty.map(|t| tree.text(t));
243    let self_kind = if let Some(t_str) = ty_text {
244        SelfKind::Typed { mutability: has_mut, ty: t_str }
245    } else if has_amp {
246        if has_mut {
247            SelfKind::MutRef { lifetime }
248        } else {
249            SelfKind::Ref { lifetime }
250        }
251    } else if has_mut {
252        SelfKind::MutValue
253    } else {
254        SelfKind::Value
255    };
256    ParamInfo { node: id, self_kind: Some(self_kind), pat: None, pat_text: None, bindings: ParamBindings::single("self"), ty, ty_text }
257}
258
259fn extract_value_param<'s>(tree: &SyntaxTree<'s>, id: NodeId) -> ParamInfo<'s> {
260    let mut pat = None;
261    let mut ty = None;
262    for ch in tree.children(id) {
263        let ck = tree.kind(ch);
264        if pat.is_none() && ck.is_pat() {
265            pat = Some(ch);
266        } else if ck.is_type() || ck == K::MacroCall {
267            ty = Some(ch);
268        }
269    }
270    let mut bindings = ParamBindings::empty();
271    if let Some(p) = pat {
272        collect_pat_bindings(tree, p, &mut bindings);
273    }
274    ParamInfo { node: id, self_kind: None, pat, pat_text: pat.map(|p| tree.text(p)), bindings, ty, ty_text: ty.map(|t| tree.text(t)) }
275}