Skip to main content

xur_bytecode/
items.rs

1//! Finding the syntax behind definitions.
2
3use std::collections::HashMap;
4
5use xur_ast::visit::{self, Visitor};
6use xur_ast::{
7    Attribute, ConstItem, FieldDef, Fn, Generics, Item, ItemKind, LitKind, MetaItemKind, NodeId,
8    Variant, VariantData,
9};
10use xur_resolve::{DefId, ModuleIdx, Program, Resolutions};
11
12/// What lowering needs to know about a definition.
13#[derive(Debug, Clone, Copy)]
14pub enum ItemRef {
15    Fn {
16        item: &'static Fn,
17        attrs: &'static [Attribute],
18        module: ModuleIdx,
19        impl_generics: Option<&'static Generics>,
20    },
21    Const {
22        item: &'static ConstItem,
23        module: ModuleIdx,
24    },
25    /// A struct or enum variant: the shape of its constructor, and the
26    /// attributes written on it.
27    Ctor {
28        data: &'static VariantData,
29        attrs: &'static [Attribute],
30        /// For `#[repr(inttype)]` enum variants, the integer discriminant.
31        repr_value: Option<i64>,
32    },
33    /// An enum definition: its attributes (e.g. `#[try(unwrap = Ok)]`).
34    Enum {
35        attrs: &'static [Attribute],
36    },
37}
38
39/// Every function, constant and constructor of the loaded modules, by
40/// definition. Updated as modules are imported.
41#[derive(Debug, Default)]
42pub struct ItemIndex {
43    items: HashMap<DefId, ItemRef>,
44    /// How many of the program's modules have been indexed.
45    indexed: usize,
46}
47
48impl ItemIndex {
49    pub fn new(program: &Program) -> Self {
50        let mut index = Self::default();
51        index.update(program);
52        index
53    }
54
55    /// Indexes the modules loaded since the last update.
56    pub fn update(&mut self, program: &Program) {
57        let modules = &program.krate.modules;
58        for (i, module) in modules.iter().enumerate().skip(self.indexed) {
59            let mut indexer = Indexer {
60                resolutions: program.resolutions(),
61                module: ModuleIdx(i),
62                items: &mut self.items,
63                current_impl: None,
64                current_repr: None,
65            };
66            indexer.visit_module(module.ast);
67        }
68        self.indexed = modules.len();
69    }
70
71    pub fn get(&self, def: DefId) -> Option<ItemRef> {
72        self.items.get(&def).copied()
73    }
74
75    /// The fields of the struct or variant `def`, named or positional, in
76    /// declaration order, or `None` if `def` has no fields.
77    pub fn fields(&self, def: DefId) -> Option<&'static [FieldDef]> {
78        match self.get(def)? {
79            ItemRef::Ctor {
80                data: VariantData::Struct(fields) | VariantData::Tuple(fields),
81                ..
82            } => Some(fields),
83            _ => None,
84        }
85    }
86
87    /// The named fields of the struct or variant `def`, in declaration
88    /// order, or `None` if it has no named fields.
89    pub fn named_fields(&self, def: DefId) -> Option<&'static [FieldDef]> {
90        match self.get(def)? {
91            ItemRef::Ctor {
92                data: VariantData::Struct(fields),
93                ..
94            } => Some(fields),
95            ItemRef::Ctor {
96                data: VariantData::Unit,
97                ..
98            } => Some(&[]),
99            _ => None,
100        }
101    }
102
103    /// The attributes on the struct or variant `def`.
104    pub fn attrs(&self, def: DefId) -> Option<&'static [Attribute]> {
105        match self.get(def)? {
106            ItemRef::Ctor { attrs, .. } => Some(attrs),
107            _ => None,
108        }
109    }
110
111    /// The repr discriminant of a `#[repr(inttype)]` variant, if any.
112    pub fn repr_value(&self, def: DefId) -> Option<i64> {
113        match self.get(def)? {
114            ItemRef::Ctor { repr_value, .. } => repr_value,
115            _ => None,
116        }
117    }
118
119    /// Every indexed definition.
120    pub fn iter(&self) -> impl Iterator<Item = (DefId, ItemRef)> + '_ {
121        self.items.iter().map(|(&def, &item)| (def, item))
122    }
123}
124
125struct Indexer<'a> {
126    resolutions: &'a Resolutions,
127    module: ModuleIdx,
128    items: &'a mut HashMap<DefId, ItemRef>,
129    current_impl: Option<&'static Generics>,
130    /// When inside a `#[repr(inttype)]` enum, the next auto-assigned
131    /// discriminant value.
132    current_repr: Option<i64>,
133}
134
135impl Indexer<'_> {
136    fn add(&mut self, node: NodeId, item: ItemRef) {
137        if let Some(&def) = self.resolutions.node_defs.get(&node) {
138            self.items.insert(def, item);
139        }
140    }
141}
142
143/// Modules' ASTs live for the rest of the process, so the index can keep
144/// references into them.
145impl Visitor<'static> for Indexer<'_> {
146    fn visit_item(&mut self, item: &'static Item) {
147        let module = self.module;
148        match &item.kind {
149            ItemKind::Fn(func) => {
150                let impl_generics = self.current_impl;
151                self.add(item.id, ItemRef::Fn { item: func, attrs: &item.attrs, module, impl_generics });
152            }
153            ItemKind::Const(konst) => self.add(
154                item.id,
155                ItemRef::Const {
156                    item: konst,
157                    module,
158                },
159            ),
160            ItemKind::Struct(_, _, data) => {
161                let attrs = &item.attrs;
162                self.add(item.id, ItemRef::Ctor { data, attrs, repr_value: None });
163            }
164            ItemKind::Enum(..) => {
165                self.add(item.id, ItemRef::Enum { attrs: &item.attrs });
166                self.current_repr = find_repr_attr(&item.attrs);
167                visit::walk_item(self, item);
168                self.current_repr = None;
169                return;
170            }
171            ItemKind::Impl(imp) => {
172                let saved = self.current_impl;
173                self.current_impl = if imp.generics.params.is_empty() {
174                    None
175                } else {
176                    Some(&imp.generics)
177                };
178                visit::walk_item(self, item);
179                self.current_impl = saved;
180                return;
181            }
182            ItemKind::Use(_) => {}
183        }
184        visit::walk_item(self, item);
185    }
186
187    fn visit_variant(&mut self, variant: &'static Variant) {
188        let (data, attrs) = (&variant.data, &variant.attrs);
189        let repr_value = if let Some(next) = &mut self.current_repr {
190            let value = if let Some(disc) = &variant.discriminant {
191                eval_discriminant(disc)
192            } else {
193                Some(*next)
194            };
195            if let Some(v) = value {
196                *next = v + 1;
197            }
198            value
199        } else {
200            None
201        };
202        self.add(variant.id, ItemRef::Ctor { data, attrs, repr_value });
203        visit::walk_variant(self, variant);
204    }
205}
206
207/// If `attrs` contains `#[repr(u8)]`, `#[repr(u16)]`, `#[repr(u32)]` or
208/// `#[repr(u64)]`, returns `Some(0)` as the initial discriminant.
209fn find_repr_attr(attrs: &[Attribute]) -> Option<i64> {
210    for attr in attrs {
211        let segments = &attr.meta.path.segments;
212        if segments.len() != 1 || segments[0].ident.name.as_str() != "repr" {
213            continue;
214        }
215        if let MetaItemKind::List(items) = &attr.meta.kind {
216            for item in items {
217                if let xur_ast::MetaItemInner::MetaItem(meta) = item {
218                    let name = meta.path.segments.last().map(|s| s.ident.name.as_str());
219                    if matches!(name, Some("u8" | "u16" | "u32" | "u64" | "i8" | "i16" | "i32" | "i64")) {
220                        return Some(0);
221                    }
222                }
223            }
224        }
225    }
226    None
227}
228
229/// Evaluates a discriminant expression to an integer. Only integer literals
230/// are supported.
231fn eval_discriminant(expr: &xur_ast::Expr) -> Option<i64> {
232    match &expr.kind {
233        xur_ast::ExprKind::Lit(lit) => match lit.kind {
234            LitKind::Int(i) => i64::try_from(i).ok(),
235            _ => None,
236        },
237        xur_ast::ExprKind::Unary(xur_ast::UnOp::Neg, inner) => {
238            eval_discriminant(inner).map(|v| -v)
239        }
240        _ => None,
241    }
242}