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