-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathmod.rs
465 lines (411 loc) · 15 KB
/
mod.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
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
//! Provides the [StyleChecker] visitor to verify the coding style of
//! this library.
//!
//! This is split out so that the implementation itself can be tested
//! separately, see test/check_style.rs for how it's used and
//! test/style_tests.rs for the implementation tests.
//!
//! ## Guidelines
//!
//! The current style is:
//!
//! * Specific module layout:
//! 1. use directives
//! 2. typedefs
//! 3. structs
//! 4. constants
//! 5. f! { ... } functions
//! 6. extern functions
//! 7. modules + pub use
//! * No manual deriving Copy/Clone
//! * Only one f! per module
//! * Multiple s! macros are allowed as long as there isn't a duplicate cfg,
//! whether as a standalone attribute (#[cfg]) or in a cfg_if!
//! * s! macros should not just have a positive cfg since they should
//! just go into the relevant file but combined cfgs with all(...) and
//! any(...) are allowed
use std::collections::HashMap;
use std::fs;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use annotate_snippets::{Level, Renderer, Snippet};
use proc_macro2::Span;
use syn::parse::{Parse, ParseStream};
use syn::spanned::Spanned;
use syn::visit::{self, Visit};
use syn::Token;
pub type Error = Box<dyn std::error::Error>;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Default)]
pub struct StyleChecker {
/// The state the style checker is in, used to enforce the module layout.
state: State,
/// Span of the first item encountered in this state to use in help
/// diagnostic text.
state_span: Option<Span>,
seen_s_macro_cfgs: HashMap<String, Span>,
/// Span of the first f! macro seen, used to enforce only one f! macro
/// per module.
first_f_macro: Option<Span>,
/// The errors that the style checker has seen.
errors: Vec<FileError>,
/// Path of the currently active file.
path: PathBuf,
/// Whether the style checker is currently in an `impl` block.
in_impl: bool,
}
#[derive(Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum State {
#[default]
Start,
Imports,
Typedefs,
Structs,
Constants,
FunctionDefinitions,
Functions,
Modules,
}
/// Similar to [syn::ExprIf] except with [syn::Attribute]
/// as the condition instead of [syn::Expr].
struct ExprCfgIf {
_attr: syn::Attribute,
then_branch: Vec<syn::Item>,
else_branch: Option<Box<ExprCfgElse>>,
}
enum ExprCfgElse {
Block(Vec<syn::Item>),
If(ExprCfgIf),
}
impl StyleChecker {
pub fn new() -> Self {
Self::default()
}
/// Reads and parses the file at the given path and checks
/// for any style violations.
pub fn check_file(&mut self, path: &Path) -> Result<()> {
let contents = fs::read_to_string(path)?;
self.path = PathBuf::from(path);
self.check_string(contents)
}
pub fn check_string(&mut self, contents: String) -> Result<()> {
let file = syn::parse_file(&contents)?;
self.visit_file(&file);
Ok(())
}
/// Resets the state of the [StyleChecker].
pub fn reset_state(&mut self) {
*self = Self {
errors: std::mem::take(&mut self.errors),
..Self::default()
};
}
/// Collect all errors into a single error, reporting them if any.
pub fn finalize(self) -> Result<()> {
if self.errors.is_empty() {
return Ok(());
}
let renderer = Renderer::styled();
for error in self.errors {
let source = fs::read_to_string(&error.path)?;
let mut snippet = Snippet::source(&source)
.origin(error.path.to_str().expect("path to be UTF-8"))
.fold(true)
.annotation(Level::Error.span(error.span.byte_range()).label(&error.msg));
if let Some((help_span, help_msg)) = &error.help {
if let Some(help_span) = help_span {
snippet = snippet
.annotation(Level::Help.span(help_span.byte_range()).label(help_msg));
}
}
let mut msg = Level::Error.title(&error.title).snippet(snippet);
if let Some((help_span, help_msg)) = &error.help {
if help_span.is_none() {
msg = msg.footer(Level::Help.title(help_msg))
}
}
eprintln!("{}", renderer.render(msg));
}
Err("some tests failed".into())
}
fn set_state(&mut self, new_state: State, span: Span) {
if self.state > new_state && !self.in_impl {
self.error(
"incorrect module layout".to_string(),
span,
format!(
"{} found after {} when it belongs before",
new_state.desc(),
self.state.desc()
),
(
Some(
self.state_span
.expect("state_span should be set since we are on a second state"),
),
format!(
"move the {} to before this {}",
new_state.desc(),
self.state.desc()
),
),
);
}
if self.state != new_state {
self.state = new_state;
self.state_span = Some(span);
}
}
/// Visit the items inside the [ExprCfgIf], restoring the state after
/// each branch.
fn visit_expr_cfg_if(&mut self, expr_cfg_if: &ExprCfgIf) {
let initial_state = self.state;
for item in &expr_cfg_if.then_branch {
self.visit_item(item);
}
self.state = initial_state;
if let Some(else_branch) = &expr_cfg_if.else_branch {
match else_branch.deref() {
ExprCfgElse::Block(items) => {
for item in items {
self.visit_item(item);
}
}
ExprCfgElse::If(expr_cfg_if) => self.visit_expr_cfg_if(&expr_cfg_if),
}
}
self.state = initial_state;
}
fn push_error(&mut self, title: String, span: Span, msg: String, help: Option<Help>) {
self.errors.push(FileError {
path: self.path.clone(),
title,
span,
msg,
help,
});
}
fn error(&mut self, title: String, span: Span, msg: String, help: Help) {
self.push_error(title, span, msg, Some(help));
}
}
impl<'ast> Visit<'ast> for StyleChecker {
fn visit_meta_list(&mut self, meta_list: &'ast syn::MetaList) {
let span = meta_list.span();
let meta_str = meta_list.tokens.to_string();
if meta_list.path.is_ident("derive")
&& (meta_str.contains("Copy") || meta_str.contains("Clone"))
{
self.error(
"impl Copy and Clone manually".to_string(),
span,
"found manual implementation of Copy and/or Clone".to_string(),
(None, "use one of the s! macros instead".to_string()),
);
}
visit::visit_meta_list(self, meta_list);
}
fn visit_item_use(&mut self, item_use: &'ast syn::ItemUse) {
let span = item_use.span();
let new_state = if matches!(item_use.vis, syn::Visibility::Public(_)) {
State::Modules
} else {
State::Imports
};
self.set_state(new_state, span);
visit::visit_item_use(self, item_use);
}
fn visit_item_const(&mut self, item_const: &'ast syn::ItemConst) {
let span = item_const.span();
self.set_state(State::Constants, span);
visit::visit_item_const(self, item_const);
}
fn visit_item_impl(&mut self, item_impl: &'ast syn::ItemImpl) {
self.in_impl = true;
visit::visit_item_impl(self, item_impl);
self.in_impl = false;
}
fn visit_item_struct(&mut self, item_struct: &'ast syn::ItemStruct) {
let span = item_struct.span();
self.set_state(State::Structs, span);
visit::visit_item_struct(self, item_struct);
}
fn visit_item_type(&mut self, item_type: &'ast syn::ItemType) {
let span = item_type.span();
self.set_state(State::Typedefs, span);
visit::visit_item_type(self, item_type);
}
fn visit_item_macro(&mut self, item_macro: &'ast syn::ItemMacro) {
if item_macro.mac.path.is_ident("s") {
if item_macro.attrs.is_empty() {
let span = item_macro.span();
match self.seen_s_macro_cfgs.get("") {
Some(seen_span) => {
self.error(
"duplicate s! macro".to_string(),
span,
format!("other s! macro"),
(Some(*seen_span), "combine the two".to_string()),
);
}
None => {
self.seen_s_macro_cfgs.insert(String::new(), span);
}
}
} else {
for attr in &item_macro.attrs {
if let Ok(meta_list) = attr.meta.require_list() {
if meta_list.path.is_ident("cfg") {
let span = meta_list.span();
let meta_str = meta_list.tokens.to_string();
match self.seen_s_macro_cfgs.get(&meta_str) {
Some(seen_span) => {
self.error(
"duplicate #[cfg] for s! macro".to_string(),
span,
"duplicated #[cfg]".to_string(),
(Some(*seen_span), "combine the two".to_string()),
);
}
None => {
self.seen_s_macro_cfgs.insert(meta_str.clone(), span);
}
}
if !meta_str.starts_with("not")
&& !meta_str.starts_with("any")
&& !meta_str.starts_with("all")
{
self.error(
"positive #[cfg] for s! macro".to_string(),
span,
String::new(),
(None, "move it to the relevant file".to_string()),
);
}
}
}
}
}
}
visit::visit_item_macro(self, item_macro);
}
fn visit_macro(&mut self, mac: &'ast syn::Macro) {
let span = mac.span();
if mac.path.is_ident("cfg_if") {
let expr_cfg_if: ExprCfgIf = mac
.parse_body()
.expect("cfg_if! should be parsed since it compiled");
self.visit_expr_cfg_if(&expr_cfg_if);
} else {
let new_state = if mac.path.is_ident("s") {
// multiple macros are allowed if they have proper #[cfg(...)]
// attributes, see Self::visit_item_macro
State::Structs
} else if mac.path.is_ident("s_no_extra_traits") {
// multiple macros of this type are allowed
State::Structs
} else if mac.path.is_ident("s_paren") {
// multiple macros of this type are allowed
State::Structs
} else if mac.path.is_ident("f") {
match self.first_f_macro {
Some(f_macro_span) => {
self.error(
"multiple f! macros in one module".to_string(),
span,
"other f! macro".to_string(),
(
Some(f_macro_span),
"combine it with this f! macro".to_string(),
),
);
}
None => {
self.first_f_macro = Some(span);
}
}
State::FunctionDefinitions
} else {
self.state
};
self.set_state(new_state, span);
}
visit::visit_macro(self, mac);
}
fn visit_item_foreign_mod(&mut self, item_foreign_mod: &'ast syn::ItemForeignMod) {
let span = item_foreign_mod.span();
self.set_state(State::Functions, span);
visit::visit_item_foreign_mod(self, item_foreign_mod);
}
fn visit_item_mod(&mut self, item_mod: &'ast syn::ItemMod) {
let span = item_mod.span();
self.set_state(State::Modules, span);
visit::visit_item_mod(self, item_mod);
}
}
impl Parse for ExprCfgIf {
fn parse(input: ParseStream) -> syn::Result<Self> {
input.parse::<Token![if]>()?;
let attr = input
.call(syn::Attribute::parse_outer)?
.into_iter()
.next()
.expect("an attribute should be present since it compiled");
let content;
syn::braced!(content in input);
let then_branch: Vec<syn::Item> = {
let mut items = Vec::new();
while !content.is_empty() {
let mut value = content.parse()?;
if let syn::Item::Macro(item_macro) = &mut value {
item_macro.attrs.push(attr.clone());
}
items.push(value);
}
items
};
let mut else_branch = None;
if input.peek(Token![else]) {
input.parse::<Token![else]>()?;
if input.peek(Token![if]) {
else_branch = Some(Box::new(ExprCfgElse::If(input.parse()?)));
} else {
let content;
syn::braced!(content in input);
let mut items = Vec::new();
while !content.is_empty() {
items.push(content.parse()?);
}
else_branch = Some(Box::new(ExprCfgElse::Block(items)));
}
}
Ok(Self {
_attr: attr,
then_branch,
else_branch,
})
}
}
impl State {
fn desc(&self) -> &str {
match *self {
State::Start => "start",
State::Imports => "import",
State::Typedefs => "typedef",
State::Structs => "struct",
State::Constants => "constant",
State::FunctionDefinitions => "function definition",
State::Functions => "extern function",
State::Modules => "module",
}
}
}
#[derive(Debug)]
struct FileError {
path: PathBuf,
span: Span,
title: String,
msg: String,
help: Option<Help>,
}
type Help = (Option<Span>, String);