1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! Utilities for working with rust modules
use cargo_metadata::Edition;
use ego_tree::{NodeId, NodeRef};
use proc_macro2::Span;
use syn::{punctuated::Punctuated, Attribute, Ident, Item, PathSegment, Token};
use crate::{
syn_helpers::{ident_crate, ident_self, ident_super, item_ident, item_vis},
Import, ImportStrength, ItemId, Items, ModuleInformation, ModuleOrItem, ResolveError,
};
/// A rust module
#[derive(Debug, Clone)]
pub struct Module {
/// All the non-module items inside of the module
///
/// To access module items see [`NodeRef::children`]
pub items: Items,
/// The name of the module
pub ident: Ident,
/// The visibility of the module, relative
/// to its parent
pub vis: syn::Visibility,
/// Any attributes on the module, ie `#[deny(missing_docs)]`
pub attrs: Vec<Attribute>,
/// The edition of rust for this module, or None to
/// indicate that it should be inherited
pub edition: Option<Edition>,
}
/// The resolved version of an import
#[derive(Debug, Clone)]
struct Resolved {
/// The item imported
pub iom: ModuleOrItem,
/// How strong it is
pub strength: ImportStrength,
}
impl Module {
/// Creates a new module from the given string name.
pub fn new_s(s: &str, edition: Option<Edition>) -> Self {
Self {
ident: Ident::new(s, Span::call_site()),
vis: syn::Visibility::Public(Token!(pub)(Span::call_site())),
attrs: Vec::new(),
items: Vec::new(),
edition,
}
}
/// Returns the edition of this, or the inherited edition
pub fn edition(this: NodeRef<Self>) -> Option<Edition> {
for ancestor in this.ancestors() {
if let Some(edition) = &ancestor.value().edition {
return Some(edition.clone());
}
}
None
}
/// Gets the crate of a Module
///
/// Should always return a `Some` if it is
/// not the root and was generated by [`crate::parse::parse`]
pub fn get_crate(this: NodeRef<Self>) -> Option<NodeRef<Self>> {
let root = this.tree().root();
if this.parent() == Some(root) {
Some(this)
} else {
this.ancestors()
.find(|&ancestor| ancestor.parent() == Some(root))
}
}
/// Gets the path to this.
///
/// For example `::std::collections`
pub fn absolute_path(this: NodeRef<Self>) -> syn::Path {
syn::Path {
leading_colon: Some(Token!(::)(Span::call_site())),
segments: {
let mut p = Punctuated::new();
// Add each ancestor of this to the path
for ancestor in this.ancestors() {
if ancestor != this.tree().root() {
p.insert(
0,
PathSegment {
ident: ancestor.value().ident.clone(),
arguments: Default::default(),
},
);
}
}
// Add this
p.push(PathSegment {
ident: this.value().ident.clone(),
arguments: Default::default(),
});
p
},
}
}
/// Gets an item or module from its identifier
///
/// This will follow imports
pub fn get_item(
this: NodeRef<Self>,
mi: &ModuleInformation,
ident: &Ident,
) -> Result<Option<ModuleOrItem>, ResolveError> {
// Our prime candidate
let mut found: Option<Resolved> = None;
// Check if any modules match the specifier
for node in this.children() {
if &node.value().ident == ident {
set_found_strong(&mut found, node.id())?;
}
}
// Check to see if any items match the specifier
for (i, item) in this.value().items.iter().enumerate() {
// Check if:
//
// a) This is the item that is referenced
// b) This is a use statement which may
// reference the item which we want
if item_ident(item) == Some(ident) {
// Set this as a found candidate
set_found_strong(
&mut found,
ItemId {
node: this.id(),
item_id: i,
},
)?;
} else if let Item::Use(expr) = item {
// TODO: Make this more accurate by
// TODO: taking into account visibility
// Create a vector to store all the possible paths
// that we resolve from this.
let mut imports = Vec::new();
let mut current_path = Self::absolute_path(this);
Self::get_use(this.id(), mi, &expr.tree, &mut imports, &mut current_path)?;
// Resolve the correct import
for import in imports {
let import_ident = import.ident();
if import_ident == ident {
set_found(&mut found, Self::resolve_import(this, mi, import)?)?;
}
}
}
}
// Attempt to use one of the default preludes (std or core)
if found.is_none() {
if let Some(ref edition) = this.value().edition {
// Find 'std' if available, otherwise use 'core'
let main_crate = match mi.get_crate("std") {
Some(std) => Some(std),
None => mi.get_crate("core"),
};
if let Some(main_crate) = main_crate {
// Try and get the 'prelude' module
let span = Span::call_site();
let ident_prelude = Ident::new("prelude", span);
let prelude = Module::get_item(main_crate, mi, &ident_prelude)?;
if let Some(ModuleOrItem::Module(prelude)) = prelude {
// Try and get the relevant prelude to our edition
let ident_relevant_prelude = Ident::new(&format!("rust_{}", edition), span);
let prelude = mi.tree.get(prelude).unwrap();
let relevant_prelude =
Module::get_item(prelude, mi, &ident_relevant_prelude)?;
if let Some(ModuleOrItem::Module(relevant_prelude)) = relevant_prelude {
// Set the found iom
let relevant_prelude = mi.tree.get(relevant_prelude).unwrap();
let moi = Module::get_item(relevant_prelude, mi, ident)?;
if let Some(iom) = moi {
found = Some(Resolved {
iom,
strength: ImportStrength::Weak,
});
}
}
}
}
}
}
Ok(found.map(|x| x.iom))
}
/// Resolves an [`Import`] into a [`Resolved`]
fn resolve_import(
this: NodeRef<Self>,
mi: &ModuleInformation,
import: Import,
) -> Result<Resolved, ResolveError> {
Ok(Resolved {
strength: import.strength,
iom: mi.path(this.id(), &import.item)?,
})
}
/// Adds all the imports in a use statement to the vec `imports`
fn get_use(
this_id: NodeId,
mi: &ModuleInformation,
expr: &syn::UseTree,
imports: &mut Vec<Import>,
current_path: &mut syn::Path,
) -> Result<(), ResolveError> {
match expr {
syn::UseTree::Path(expr) => {
// Check if this is:
//
// a) super - this goes up one
// b) crate - this goes up to the toplevel
// c) something else - this affects the path
//
// We don't do self here because it makes no
// sense do self unless the last element (`Name`)
// and in a group
if expr.ident == ident_super() {
current_path
.segments
.pop()
.ok_or(ResolveError::TooManySupers)?;
} else if expr.ident == ident_crate() {
while current_path.segments.len() > 1 {
current_path.segments.pop();
}
} else {
// Append this path segment to the current path
current_path.segments.push(PathSegment {
ident: expr.ident.clone(),
arguments: Default::default(),
});
}
// Recurse down (I know recursion isn't preferable,
// but I think it makes the most sense for this
// code as we are dealing with a tree.)
Self::get_use(this_id, mi, &expr.tree, imports, current_path)
}
syn::UseTree::Name(expr) => {
if expr.ident == ident_self() {
} else if expr.ident == ident_super() {
current_path
.segments
.pop()
.ok_or(ResolveError::TooManySupers)?;
} else {
// Append this path segment to the current path
current_path.segments.push(PathSegment {
ident: expr.ident.clone(),
arguments: Default::default(),
});
}
// And append said path to the list of paths
imports.push(Import::new(
current_path.clone(),
ImportStrength::Strong,
None,
));
// Pop, so we go down one level
current_path.segments.pop();
Ok(())
}
syn::UseTree::Rename(expr) => {
// Append this path segment to the "current path"
current_path.segments.push(PathSegment {
ident: expr.ident.clone(),
arguments: Default::default(),
});
// And append said path to the list of paths,
// with the rename accounted for
imports.push(Import::new(
current_path.clone(),
ImportStrength::Strong,
Some(expr.rename.clone()),
));
// Pop, so we go down one level
current_path.segments.pop();
Ok(())
}
syn::UseTree::Glob(_) => {
// Now we need to find on the global
// module tree the place refered to by this path
//
// This could in theory recurse into this function
// again so this whole thing will get a bit to recursive
// quite quickly if crates expose others' APIs
let node = mi.path(this_id, current_path)?;
match node {
ModuleOrItem::Module(module) => {
let module = mi.tree.get(module).unwrap();
for item in &module.value().items {
// If this is an item with a name (an item we care about)
if let Some(ident) = item_ident(item) {
// Check we have the visibility to access
// this item.
let item_vis_applicable =
is_item_vis_acceptable(mi, this_id, module.id(), item);
if item_vis_applicable {
// Append this path segment to the "current path"
current_path.segments.push(PathSegment {
ident: ident.clone(),
arguments: Default::default(),
});
// Add this item
imports.push(Import::new(
current_path.clone(),
ImportStrength::Weak,
None,
));
// Pop, so we go down one level
current_path.segments.pop();
}
}
}
Ok(())
}
ModuleOrItem::Item(_) => Err(ResolveError::PrematureItem),
}
}
syn::UseTree::Group(expr) => {
// Loop through each element of the group,
// and recurse on said element.
for expr in &expr.items {
Self::get_use(this_id, mi, expr, imports, current_path)?;
}
Ok(())
}
}
}
}
/// Determines whether we can see an item from where we are in the tree.
fn is_item_vis_acceptable(
mi: &ModuleInformation,
reference_point: NodeId,
item_module: NodeId,
item: &Item,
) -> bool {
let vis = match item_vis(item) {
Some(vis) => vis,
None => return false,
};
let reference_point = match mi.tree.get(reference_point) {
Some(x) => x,
None => return false,
};
let item_module = match mi.tree.get(item_module) {
Some(x) => x,
None => return false,
};
match vis {
syn::Visibility::Public(_) => true,
syn::Visibility::Restricted(_) => todo!(),
syn::Visibility::Inherited => item_module.descendants().any(|x| x == reference_point),
}
}
/// Aims to strongly resolve an import
///
/// See [`set_found`]
fn set_found_strong<I: Into<ModuleOrItem>>(
found: &mut Option<Resolved>,
import: I,
) -> Result<(), ResolveError> {
set_found(
found,
Resolved {
iom: import.into(),
strength: ImportStrength::Strong,
},
)
}
/// Set the `found` variable to `resolve` if applicable
///
/// It will not be set if:
///
/// - They have matching strengths (err)
/// - `found` is stronger than `resolve` (fine but nothing happens)
fn set_found(found: &mut Option<Resolved>, resolve: Resolved) -> Result<(), ResolveError> {
// Checks to see if a found exists,
// if it doesn't we can always set it.
match found {
Some(found) => {
// Checks if:
//
// a) They have matching strengths
// b) `found` is weaker than `resolve`
// c) `found` is stronger than `resolve`
if found.strength == resolve.strength {
Err(ResolveError::Conflicting)
} else if found.strength == ImportStrength::Weak {
*found = resolve;
Ok(())
} else {
Ok(())
}
}
None => {
*found = Some(resolve);
Ok(())
}
}
}