Skip to main content

ridx_format/reader/
macro_access.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//! Zero-copy `O(log N)` reader accessors for declarative macro definitions (`MacroDefEntry`).
12
13use super::IndexReader;
14use crate::format::{MacroDefEntry, MacroDelim, MacroEdition, MACRO_FLAG_BUILTIN, MACRO_FLAG_EXPORTED, MACRO_FLAG_LOCAL_INNER, MACRO_FLAG_MACRO_RULES};
15
16/// Decoded zero-copy view of a `MacroDefEntry` row and its interned token body.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub struct MacroDefView<'a> {
19    pub def_index: u32,
20    pub body: &'a str,
21    pub flags: u8,
22    pub delim: MacroDelim,
23    pub edition: MacroEdition,
24}
25
26impl<'a> MacroDefView<'a> {
27    #[inline]
28    pub const fn is_macro_rules(&self) -> bool {
29        (self.flags & MACRO_FLAG_MACRO_RULES) != 0
30    }
31
32    #[inline]
33    pub const fn is_exported(&self) -> bool {
34        (self.flags & MACRO_FLAG_EXPORTED) != 0
35    }
36
37    #[inline]
38    pub const fn has_local_inner_macros(&self) -> bool {
39        (self.flags & MACRO_FLAG_LOCAL_INNER) != 0
40    }
41
42    #[inline]
43    pub const fn is_builtin(&self) -> bool {
44        (self.flags & MACRO_FLAG_BUILTIN) != 0
45    }
46}
47
48impl<B: AsRef<[u8]>> IndexReader<B> {
49    /// Raw slice of `MacroDefEntry` rows sorted by `def_index`.
50    #[inline]
51    pub fn macro_defs(&self) -> &[MacroDefEntry] {
52        self.typed_slice(self.header.macro_defs_offset, self.header.macro_defs_count)
53    }
54
55    #[inline]
56    fn decode_macro_def(&self, raw: &MacroDefEntry) -> MacroDefView<'_> {
57        let e = raw.from_le();
58        MacroDefView { def_index: e.def_index, body: self.get_str(e.body_offset), flags: e.flags, delim: e.delim_kind(), edition: e.edition_kind() }
59    }
60
61    /// Iterates over all decoded `MacroDefView` entries in `def_index` order.
62    pub fn macro_defs_iter(&self) -> impl ExactSizeIterator<Item = MacroDefView<'_>> + '_ {
63        self.macro_defs().iter().map(|raw| self.decode_macro_def(raw))
64    }
65
66    /// `O(log N)` lookup for the declarative macro definition owned by `def_index`.
67    pub fn macro_def_for_def(&self, def_index: u32) -> Option<MacroDefView<'_>> {
68        let entries = self.macro_defs();
69        let idx = entries.binary_search_by_key(&def_index, |raw| raw.def_index()).ok()?;
70        Some(self.decode_macro_def(&entries[idx]))
71    }
72}