myd 0.1.1

An implementation of the rust module system
Documentation
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! Exposes a function to parse a crate into a [`ModuleInformation`]

mod compat_pkg;
use compat_pkg::ManualPackage;
mod conditional;
mod rustlib;

use std::collections::HashSet;
use std::path::{Path as StdPath, PathBuf};
use std::string::FromUtf8Error;
use std::{fs, io};

use cargo_metadata::{CargoOpt, MetadataCommand, Package};
use ego_tree::{NodeId, Tree};
use proc_macro2::Span;
use syn::punctuated::Punctuated;
use syn::{Attribute, Ident, Meta, PathSegment, Token};

use crate::platforms::SystemInfo;
use crate::{Features, Items, Module, ModuleInformation};
use rustlib::{add_sysroot_crate, SYSROOT_CRATES};

use self::conditional::{CfgAttrGroup, CfgEval, CfgPredicate};

/// An error that arises from parsing
#[derive(thiserror::Error, Debug)]
pub enum Error {
    /// Failed to fetch the cargo-metadata for the package
    #[error("error fetching cargo metadata: {0}")]
    CargoMetadata(#[from] cargo_metadata::Error),
    /// Failed to parse source code
    #[error("error parsing source code: {0}")]
    Syn(#[from] syn::Error),
    /// Failed to open a file
    #[error("io error: {0}")]
    Io(#[from] io::Error),
    /// Failed to find a package referenced somewhere
    #[error("unknown package: {0}")]
    UnknownPackage(String),
    /// Utf8
    #[error("failed to convert to utf8: {0}")]
    Utf8(#[from] FromUtf8Error),
    /// Failed to get the sysroot
    #[error(
        "can't load the standard library from sysroot. \n\n\
        try installing the rust-src the same way you installed rustc"
    )]
    Sysroot,
    /// A sysroot crate which is not a default sysroot crate
    /// is atempted to be used.
    #[error(
        "invalid sysroot crate: {0}.\n\n\
        sysroot crates should be one of: \n\
            `alloc`, `backtrace`, `core`, `panic_abort`, \
            `panic_unwind`, `proc_macro`, `profiler_builtins`, \
            `std`, `std_detect`, `test`, `unwind`"
    )]
    InvalidSysrootCrate(String),
}

/// A result wrapper for failed parsing
pub type Result<T> = ::std::result::Result<T, Error>;

/// Parses a rust project and all of its dependencies into a tree.
///
/// The root will have an identifier of `_` at call site.
pub fn parse<P: AsRef<StdPath> + Into<PathBuf>>(
    path: P,
    cargo_opt: CargoOpt,
    platform: &SystemInfo,
) -> Result<ModuleInformation> {
    // Generate cargo metadata
    let metadata = MetadataCommand::new()
        .manifest_path(path)
        .features(cargo_opt.clone())
        .exec()?;

    let mut tree = Tree::new(Module::new_s("_", None));

    let mut features = Features::new();

    // Reslove the features for the root
    if let Some(root) = metadata.root_package() {
        let entry = features.entry(root.name.clone()).or_default();
        match cargo_opt {
            CargoOpt::AllFeatures => {
                for feature in root.features.keys() {
                    entry.insert(feature.clone());
                }
            }
            CargoOpt::NoDefaultFeatures => (),
            CargoOpt::SomeFeatures(ref features) => {
                for feature in features {
                    entry.insert(feature.clone());
                }
            }
        }
        resolve_dependency_features(&mut Vec::new(), &mut features, root, &metadata.packages)?;
    }

    for pkg in SYSROOT_CRATES.keys() {
        features.insert((*pkg).to_owned(), Default::default());
    }

    let mut std = false;
    for package in metadata.packages {
        resolve_package(&features, platform, &mut tree, package.into(), &mut std)?;
    }

    // Add core if !#[no_std]
    if !std {
        add_sysroot_crate(&mut tree, &features, platform, "core")?;
    }

    Ok(tree.into())
}

/// Adds a package to the tree
pub(crate) fn resolve_package<'a, 'b: 'a>(
    features: &Features,
    platform: &SystemInfo,
    tree: &mut Tree<Module>,
    package: ManualPackage,
    std: &mut bool,
) -> Result<()> {
    // Add this package to the index.
    let mut root = tree.root_mut();
    let ident = package.name.replace('-', "_");
    let pkg_root = root.append(Module::new_s(&ident, package.edition.clone()));

    // Pass the syn of the tree
    let path = get_lib_path(&package);
    let path = match path {
        Some(path) => path,
        None => return Ok(()),
    };
    let file = fs::read_to_string(path)?;
    let file = syn::parse_file(&file)?;

    let pkg_root_id = pkg_root.id();
    resolve_module(
        features,
        platform,
        tree,
        &package,
        pkg_root_id,
        file.items,
        &new_path(&ident),
        path.parent().unwrap(),
        path,
    )?;

    // Check if its a #![no_std] crate.
    //
    // This is so we can add the std if otherwise
    if !*std {
        // Check the normal attributes
        let no_std_path = new_path("no_std");
        let mut no_std = file.attrs.iter().any(|x| x.path() == &no_std_path);

        // Check feature attributes
        if !no_std {
            if let Some(features) = features.get(&*package.name) {
                let attrs = get_attrs_cfg_attr(&file.attrs, features, platform)?;
                no_std = attrs.iter().any(|x| x.path() == &no_std_path);
            }
        }

        // Add the sysroot crate if not no_std
        if !no_std {
            add_sysroot_crate(tree, features, platform, "std")?;
            *std = true;
        }
    }

    Ok(())
}

/// Adds a module to the tree
#[allow(clippy::too_many_arguments)]
fn resolve_module<'a, 'b: 'a>(
    features: &Features,
    platform: &SystemInfo,
    tree: &mut Tree<Module>,
    package: &ManualPackage,
    position: NodeId,
    items: Items,
    syn_path: &syn::Path,
    // The path of the parent module
    mod_path: &StdPath,
    file_path: &StdPath,
) -> Result<()> {
    for item in items {
        match item {
            syn::Item::Mod(item) => {
                // Check this module should be included.
                let our_features = &features[&*package.name];
                let cfg = get_attr_cfg(&item.attrs, our_features, platform)?;
                if !cfg {
                    continue;
                }

                // Get the 'syn' path of the new module
                let mut syn_path = syn_path.clone();
                syn_path.segments.push(PathSegment {
                    ident: item.ident.clone(),
                    arguments: Default::default(),
                });

                // Check if it has a path attrbibute.
                let attrs = eval_cfg_attrs(item.attrs, our_features, platform)?;
                let path_attr = get_path_attr(&attrs);

                // Gets the relative path of this's parent
                let mut parent_rel: PathBuf = syn_path
                    .segments
                    .iter()
                    .skip(1)
                    .map(|x| x.ident.to_string())
                    .collect();
                parent_rel.pop();
                let same_path = mod_path.join(item.ident.to_string() + ".rs");
                let new_fs_path = mod_path.join(item.ident.to_string());

                let (fs_path, file_path) = match path_attr {
                    Some(attr) => {
                        let parent_path = file_path.parent().unwrap();
                        let new_fs_path = parent_path.join(&attr).parent().unwrap().to_owned();
                        let file_path = parent_path.join(&attr);
                        (new_fs_path, file_path)
                    }
                    None => {
                        // Find either parent/us.rs or parent/us/mod.rs
                        if same_path.exists() {
                            (new_fs_path, same_path)
                        } else {
                            (
                                new_fs_path,
                                mod_path.join(item.ident.to_string()).join("mod.rs"),
                            )
                        }
                    }
                };

                let items = match item.content {
                    None => {
                        let file = fs::read_to_string(&file_path)?;
                        syn::parse_file(&file)?.items
                    }
                    Some((_, items)) => items,
                };

                // Get a node to represent the new module
                let mut position = tree.get_mut(position).unwrap();
                let position = position.append(Module {
                    ident: item.ident,
                    vis: item.vis,
                    attrs,
                    items: Items::new(),
                    edition: None,
                });

                // Recurse
                let position = position.id();
                resolve_module(
                    features, platform, tree, package, position, items, &syn_path, &fs_path,
                    &file_path,
                )?;
            }
            syn::Item::ExternCrate(expr) => {
                if let Some(crat) = SYSROOT_CRATES.keys().find(|x| expr.ident == *x) {
                    add_sysroot_crate(tree, features, platform, crat)?;
                }
            }
            item => {
                let mut position = tree.get_mut(position).unwrap();
                position.value().items.push(item.clone())
            }
        }
    }

    Ok(())
}

/// Checks to see if this has a `#[path = "..."]` attribute
///
/// If it does it will return the file system path to that object,
/// elsewise it will return None
fn get_path_attr(attrs: &[Attribute]) -> Option<PathBuf> {
    for attr in attrs {
        if attr.path() == &new_path("path") {
            // Try and get a LitStr from the meta
            match &attr.meta {
                syn::Meta::Path(_) => (),
                syn::Meta::List(_) => (),
                syn::Meta::NameValue(x) => {
                    if let syn::Expr::Lit(x) = &x.value {
                        if let syn::Lit::Str(x) = &x.lit {
                            return Some(PathBuf::from(x.value()));
                        }
                    }
                }
            }
        }
    }

    None
}

/// Determines whether an item should be included
/// based of its attributes, namely `cfg`
fn get_attr_cfg(
    attrs: &[Attribute],
    features: &HashSet<String>,
    platform: &SystemInfo,
) -> Result<bool> {
    for attr in attrs {
        if attr.path() == &new_path("cfg") {
            match &attr.meta {
                syn::Meta::Path(_) => (),
                syn::Meta::List(x) => {
                    let predicate: CfgPredicate = syn::parse2(x.tokens.clone())?;
                    return Ok(predicate.eval(features, platform));
                }
                syn::Meta::NameValue(_) => (),
            }
        }
    }

    Ok(true)
}

/// Gets a cfg_attr attribute and aims to evaluate it. This preforms
/// no checks to see if it actually is a cfg_attr
fn eval_cfg_attr(
    attr: &Attribute,
    features: &HashSet<String>,
    platform: &SystemInfo,
) -> Result<Option<Punctuated<Meta, Token![,]>>> {
    // Try and parse the macro
    match &attr.meta {
        syn::Meta::List(x) => {
            let inner = syn::parse2(x.tokens.clone())?;

            // If we can parse it then we return the
            // attrbiutes it has
            let inner: CfgAttrGroup = inner;
            let eval = inner.cfg.eval(features, platform);
            if eval {
                Ok(Some(inner.attrs))
            } else {
                Ok(None)
            }
        }
        _ => Err(syn::Error::new(attr.pound_token.span, "cfg_attr has invalid type!").into()),
    }
}

/// Get all the `cfg_attr`s internals if they are present
///
/// That is, given the `cfg_attr`:
///
/// `#[cfg_attr(windows, a = b)]`
///
/// This would return `a = b`
fn get_attrs_cfg_attr(
    attrs: &[Attribute],
    features: &HashSet<String>,
    platform: &SystemInfo,
) -> Result<Vec<Meta>> {
    let mut vec = Vec::new();

    // Loop through each attribute, and
    // evaluates & adds the cfg_attrs
    for attr in attrs {
        // Disregard anything which isn't a cfg_attr macro
        if attr.path() == &new_path("cfg_attr") {
            let eval = eval_cfg_attr(attr, features, platform)?;
            if let Some(eval) = eval {
                vec.extend(eval.into_iter())
            }
        }
    }

    Ok(vec)
}

/// Evaluates all the `cfg_attr` into plain and simple attributes
fn eval_cfg_attrs(
    attrs: Vec<Attribute>,
    features: &HashSet<String>,
    platform: &SystemInfo,
) -> Result<Vec<Attribute>> {
    let mut vec = Vec::new();

    // Loop through each attribute, and
    // evaluates & adds the cfg_attrs
    for attr in attrs {
        if attr.path() == &new_path("cfg_attr") {
            let eval = eval_cfg_attr(&attr, features, platform)?;
            if let Some(eval) = eval {
                for inner_attr in eval {
                    vec.push(syn::Attribute {
                        pound_token: attr.pound_token,
                        style: attr.style,
                        bracket_token: attr.bracket_token,
                        meta: inner_attr,
                    });
                }
            }
        } else {
            vec.push(attr)
        }
    }

    Ok(vec)
}

/// Gets the file system path to the main library of th package
fn get_lib_path<'a, 'b: 'a>(package: &'a ManualPackage) -> Option<&'a StdPath> {
    for target in package.targets.iter() {
        let mut kinds = target.kind.iter();
        if kinds.any(|x| x == "lib") {
            return Some(&target.src_path);
        }
    }

    None
}

/// Creates a path wioth one identifier, `s`
fn new_path(s: &str) -> syn::Path {
    syn::Path {
        leading_colon: None,
        segments: {
            let mut p = Punctuated::new();
            p.push(syn::PathSegment {
                ident: Ident::new(s, Span::call_site()),
                arguments: Default::default(),
            });
            p
        },
    }
}

/// Resolves all the features enabled on different dependencies
fn resolve_dependency_features<'a>(
    stack: &mut Vec<&'a str>,
    features: &mut Features,
    package: &'a Package,
    packages: &'a [Package],
) -> Result<()> {
    for dependency in &package.dependencies {
        let dep_package = match get_pkg(packages, &dependency.name) {
            Ok(o) => o,
            Err(_) => continue,
        };

        // Check if this dependency is enabled, either because it is non-optional
        // or because a feature of ours enables it.
        let mut enabled = !dependency.optional;
        if let Some(features) = features.get(&package.name) {
            for enabled_feature in features {
                enabled |= package.features[enabled_feature].contains(&dependency.name);
            }
        }

        // If this is not enabled then there is no worry.
        if !enabled {
            continue;
        }

        let entry = features.entry(dependency.name.clone()).or_default();

        // Now if we use the default features add them
        if dependency.uses_default_features {
            if let Some(def) = dep_package.features.get("default") {
                for def in def {
                    entry.insert(def.clone());
                }
            }
        }

        // Add all the non-default features which we enable
        for feature in &dependency.features {
            entry.insert(feature.clone());
        }

        // Recurse
        // Prevents loops such as quote -> proc-macro2 -> unicode-ident -> quote
        if !stack.contains(&package.name.as_str()) {
            stack.push(&package.name);
            resolve_dependency_features(stack, features, dep_package, packages)?;
            stack.pop();
        }
    }

    Ok(())
}

/// Gets a package by its name from the list
fn get_pkg<'a>(packages: &'a [Package], this: &str) -> Result<&'a Package> {
    packages
        .iter()
        .find(|x| x.name == this)
        .ok_or_else(|| Error::UnknownPackage(this.to_owned()))
}