/
types.rs
96 lines (81 loc) · 2.49 KB
/
types.rs
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
use std::borrow::Cow;
use rustc_hash::FxHashMap;
use crate::ast;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TrailingComma {
Present,
Absent,
}
impl Default for TrailingComma {
fn default() -> Self {
TrailingComma::Absent
}
}
#[derive(Debug, Hash, Ord, PartialOrd, Eq, PartialEq, Clone)]
pub struct ImportFromData<'a> {
pub module: Option<&'a str>,
pub level: Option<&'a usize>,
}
#[derive(Debug, Hash, Ord, PartialOrd, Eq, PartialEq)]
pub struct AliasData<'a> {
pub name: &'a str,
pub asname: Option<&'a str>,
}
#[derive(Debug, Default, Clone)]
pub struct CommentSet<'a> {
pub atop: Vec<Cow<'a, str>>,
pub inline: Vec<Cow<'a, str>>,
}
pub trait Importable {
fn module_name(&self) -> String;
fn module_base(&self) -> String;
}
impl Importable for AliasData<'_> {
fn module_name(&self) -> String {
self.name.to_string()
}
fn module_base(&self) -> String {
self.module_name().split('.').next().unwrap().to_string()
}
}
impl Importable for ImportFromData<'_> {
fn module_name(&self) -> String {
ast::helpers::format_import_from(self.level, self.module)
}
fn module_base(&self) -> String {
self.module_name().split('.').next().unwrap().to_string()
}
}
#[derive(Debug, Default)]
pub struct ImportBlock<'a> {
// Set of (name, asname), used to track regular imports.
// Ex) `import module`
pub import: FxHashMap<AliasData<'a>, CommentSet<'a>>,
// Map from (module, level) to `AliasData`, used to track 'from' imports.
// Ex) `from module import member`
pub import_from: FxHashMap<
ImportFromData<'a>,
(
CommentSet<'a>,
FxHashMap<AliasData<'a>, CommentSet<'a>>,
TrailingComma,
),
>,
// Set of (module, level, name, asname), used to track re-exported 'from' imports.
// Ex) `from module import member as member`
pub import_from_as: FxHashMap<(ImportFromData<'a>, AliasData<'a>), CommentSet<'a>>,
// Map from (module, level) to `AliasData`, used to track star imports.
// Ex) `from module import *`
pub import_from_star: FxHashMap<ImportFromData<'a>, CommentSet<'a>>,
}
type AliasDataWithComments<'a> = (AliasData<'a>, CommentSet<'a>);
#[derive(Debug, Default)]
pub struct OrderedImportBlock<'a> {
pub import: Vec<AliasDataWithComments<'a>>,
pub import_from: Vec<(
ImportFromData<'a>,
CommentSet<'a>,
TrailingComma,
Vec<AliasDataWithComments<'a>>,
)>,
}