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
// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2024 Datadog, Inc.
use crate::ArchitectureLintRule;
use crate::declare_variable_severity_lint;
use crate::helpers::lint_helpers::span_lint_and_help;
use cargo_pup_lint_config::{ConfiguredLint, StructMatch, StructRule};
use regex::Regex;
use rustc_hir::{Item, ItemKind, def_id::DefId};
use rustc_lint::{LateContext, LateLintPass, LintStore};
use rustc_session::impl_lint_pass;
use rustc_span::BytePos;
pub struct StructLint {
name: String,
matches: StructMatch,
struct_rules: Vec<StructRule>,
}
impl StructLint {
#[allow(clippy::new_ret_no_self)]
pub fn new(config: &ConfiguredLint) -> Box<dyn ArchitectureLintRule + Send> {
if let ConfiguredLint::Struct(s) = config {
Box::new(Self {
name: s.name.clone(),
matches: s.matches.clone(),
struct_rules: s.rules.to_vec(),
})
} else {
panic!("Expected a Struct lint configuration")
}
}
// Helper method to check if a struct in a given crate should be linted
fn matches_struct(&self, crate_name: &str, struct_name: &str) -> bool {
self.evaluate_struct_match(&self.matches, crate_name, struct_name)
}
// Evaluates the complex matcher structure to determine if a struct matches
fn evaluate_struct_match(
&self,
matcher: &StructMatch,
crate_name: &str,
struct_name: &str,
) -> bool {
match matcher {
StructMatch::Name(pattern) => {
// Try to match both the crate name and the struct name
// If it's a crate name starting with "test_", prefer that match
if pattern.starts_with("test_") {
// This is likely a crate name pattern
self.string_matches_pattern(crate_name, pattern)
} else {
// This is likely a struct name pattern
self.string_matches_pattern(struct_name, pattern)
}
}
StructMatch::HasAttribute(_) => {
// Attribute matching not yet implemented
false
}
StructMatch::ImplementsTrait(_) => {
// Implementation will be handled in check_item
// Always return true here and do the filtering there
true
}
StructMatch::AndMatches(left, right) => {
self.evaluate_struct_match(left, crate_name, struct_name)
&& self.evaluate_struct_match(right, crate_name, struct_name)
}
StructMatch::OrMatches(left, right) => {
self.evaluate_struct_match(left, crate_name, struct_name)
|| self.evaluate_struct_match(right, crate_name, struct_name)
}
StructMatch::NotMatch(inner) => {
!self.evaluate_struct_match(inner, crate_name, struct_name)
}
}
}
// Helper to determine if a string matches a pattern (exact match or regex)
fn string_matches_pattern(&self, string: &str, pattern: &str) -> bool {
match Regex::new(pattern) {
Ok(regex) => regex.is_match(string),
Err(_) => string == pattern,
}
}
fn describe_pattern(&self, pattern: &str) -> &'static str {
if pattern.contains(|c: char| {
c == '*' || c == '.' || c == '+' || c == '[' || c == '(' || c == '|'
}) {
"pattern"
} else {
"name"
}
}
// Check if this struct has any trait implementations that match our patterns
fn has_matching_trait_impl(&self, ctx: &LateContext<'_>, def_id: DefId) -> bool {
use crate::helpers::queries;
// Extract trait pattern if one exists in the matcher
fn needs_trait_check(matcher: &StructMatch) -> Option<String> {
match matcher {
StructMatch::ImplementsTrait(pattern) => Some(pattern.clone()),
StructMatch::AndMatches(left, right) => {
needs_trait_check(left).or_else(|| needs_trait_check(right))
}
StructMatch::OrMatches(left, right) => {
needs_trait_check(left).or_else(|| needs_trait_check(right))
}
StructMatch::NotMatch(inner) => needs_trait_check(inner),
_ => None,
}
}
// Check if we have any trait matchers
if let Some(trait_pattern) = needs_trait_check(&self.matches) {
// Create a regex from the trait pattern
let trait_regex = match Regex::new(&trait_pattern) {
Ok(regex) => regex,
Err(_) => return false, // If regex is invalid, consider no match
};
// Get the type for the struct
let ty = ctx.tcx.type_of(def_id).skip_binder();
// Get parameter environment for the struct
let param_env = ctx.param_env;
// For each trait in all crates, check if:
// 1. The trait name matches our pattern
// 2. The struct implements the trait
for trait_def_id in ctx.tcx.all_traits_including_private() {
// Get the full canonical trait name
let full_trait_name =
queries::get_full_canonical_trait_name_from_def_id(&ctx.tcx, trait_def_id);
// Check if the trait name matches our pattern
if trait_regex.is_match(&full_trait_name) {
// If the trait name matches, check if our type implements this trait
if queries::implements_trait(ctx.tcx, param_env, ty, trait_def_id) {
return true;
}
}
}
// If we get here, no matching trait implementations were found
return false;
}
// If no trait patterns found, no trait constraints to enforce
true
}
}
declare_variable_severity_lint!(
pub,
STRUCT_LINT_MUST_BE_NAMED,
STRUCT_LINT_MUST_BE_NAMED_DENY,
STRUCT_LINT_MUST_BE_NAMED_WARN,
"Struct naming and attribute rules"
);
declare_variable_severity_lint!(
pub,
STRUCT_LINT_MUST_NOT_BE_NAMED,
STRUCT_LINT_MUST_NOT_BE_NAMED_DENY,
STRUCT_LINT_MUST_NOT_BE_NAMED_WARN,
"Struct naming and attribute rules"
);
declare_variable_severity_lint!(
pub,
STRUCT_LINT_MUST_BE_PRIVATE,
STRUCT_LINT_MUST_BE_PRIVATE_DENY,
STRUCT_LINT_MUST_BE_PRIVATE_WARN,
"Struct must have private visibility"
);
declare_variable_severity_lint!(
pub,
STRUCT_LINT_MUST_BE_PUBLIC,
STRUCT_LINT_MUST_BE_PUBLIC_DENY,
STRUCT_LINT_MUST_BE_PUBLIC_WARN,
"Struct must have public visibility"
);
declare_variable_severity_lint!(
pub,
STRUCT_LINT_MUST_BE_PUB_CRATE,
STRUCT_LINT_MUST_BE_PUB_CRATE_DENY,
STRUCT_LINT_MUST_BE_PUB_CRATE_WARN,
"Struct must have pub(crate) visibility"
);
impl_lint_pass!(StructLint => [
STRUCT_LINT_MUST_BE_NAMED_DENY,
STRUCT_LINT_MUST_BE_NAMED_WARN,
STRUCT_LINT_MUST_NOT_BE_NAMED_DENY,
STRUCT_LINT_MUST_NOT_BE_NAMED_WARN,
STRUCT_LINT_MUST_BE_PRIVATE_DENY,
STRUCT_LINT_MUST_BE_PRIVATE_WARN,
STRUCT_LINT_MUST_BE_PUBLIC_DENY,
STRUCT_LINT_MUST_BE_PUBLIC_WARN,
STRUCT_LINT_MUST_BE_PUB_CRATE_DENY,
STRUCT_LINT_MUST_BE_PUB_CRATE_WARN
]);
impl ArchitectureLintRule for StructLint {
fn name(&self) -> String {
self.name.clone()
}
fn applies_to_module(&self, _namespace: &str) -> bool {
false
}
fn applies_to_trait(&self, _trait_path: &str) -> bool {
false
}
fn register_late_pass(&self, lint_store: &mut LintStore) {
let name = self.name.clone();
let matches = self.matches.clone();
let struct_rules = self.struct_rules.clone();
lint_store.register_late_pass(move |_| {
Box::new(StructLint {
name: name.clone(),
matches: matches.clone(),
struct_rules: struct_rules.clone(),
})
});
}
}
impl<'tcx> LateLintPass<'tcx> for StructLint {
fn check_item(&mut self, ctx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) {
// We only care about struct items
if let ItemKind::Struct(..) = item.kind {
let item_name = ctx
.tcx
.item_name(item.owner_id.def_id.to_def_id())
.to_string();
let crate_name = ctx
.tcx
.crate_name(rustc_hir::def_id::LOCAL_CRATE)
.to_string();
// Check if this struct matches our patterns
if !self.matches_struct(&crate_name, &item_name) {
return;
}
// Check trait implementations if needed
let def_id = item.owner_id.def_id.to_def_id();
if !self.has_matching_trait_impl(ctx, def_id) {
return;
}
// Create a span that only covers the struct definition line
// This includes "pub struct Name {" but not the struct fields or closing brace
let definition_span = {
let span = item.span;
// Check if the struct is public by checking if ident_span is different from vis_span
let is_pub = !item.vis_span.is_empty();
let prefix_len = if is_pub { 11 } else { 7 }; // "pub struct " or "struct "
// Create a span from start to just after the struct name and opening brace
let end_pos = span.lo() + BytePos((prefix_len + item_name.len() + 2) as u32); // +2 for " {"
span.with_hi(end_pos)
};
// Get visibility of the struct
let struct_visibility = ctx.tcx.visibility(def_id);
let is_public = struct_visibility == rustc_middle::ty::Visibility::Public;
// Check if there's a visibility keyword (pub, pub(crate), pub(super), etc.)
let has_visibility_keyword = !item.vis_span.is_empty();
// Check if visibility is pub(crate):
// - Must have a visibility keyword (not inherited/private)
// - Must be restricted to the crate root
let is_pub_crate = match struct_visibility {
rustc_middle::ty::Visibility::Restricted(restricted_to) => {
has_visibility_keyword && restricted_to.is_crate_root()
}
_ => false,
};
// Truly private means no visibility keyword at all (inherited visibility)
let is_private = !has_visibility_keyword;
// Apply rules
for rule in &self.struct_rules {
match rule {
StructRule::MustBeNamed(pattern, severity) => {
if !self.string_matches_pattern(&item_name, pattern) {
let pattern_type = self.describe_pattern(pattern);
let message = format!(
"Struct must match {pattern_type} '{pattern}', found '{item_name}'"
);
let help = if pattern_type == "pattern" {
format!("Rename this struct to match the pattern '{pattern}'")
} else {
format!("Rename this struct to '{pattern}'")
};
span_lint_and_help(
ctx,
STRUCT_LINT_MUST_BE_NAMED::get_by_severity(*severity),
self.name().as_str(),
definition_span,
message,
None,
help,
);
}
}
StructRule::MustNotBeNamed(pattern, severity) => {
if self.string_matches_pattern(&item_name, pattern) {
let pattern_type = self.describe_pattern(pattern);
let message =
format!("Struct must not match {pattern_type} '{pattern}'");
let help = if pattern_type == "pattern" {
"Choose a name that doesn't match this pattern"
} else {
"Choose a different name for this struct"
};
span_lint_and_help(
ctx,
STRUCT_LINT_MUST_NOT_BE_NAMED::get_by_severity(*severity),
self.name().as_str(),
definition_span,
message,
None,
help,
);
}
}
StructRule::MustBePrivate(severity) => {
if !is_private {
let visibility_desc = if is_public {
"pub"
} else if is_pub_crate {
"pub(crate)"
} else {
"restricted" // pub(super) or pub(in path)
};
span_lint_and_help(
ctx,
STRUCT_LINT_MUST_BE_PRIVATE::get_by_severity(*severity),
self.name().as_str(),
definition_span,
format!(
"Struct '{item_name}' has {visibility_desc} visibility, but must be private"
),
None,
"Remove the visibility modifier",
);
}
}
StructRule::MustBePublic(severity) => {
if !is_public {
let visibility_desc = if is_pub_crate {
"pub(crate)"
} else {
"private"
};
span_lint_and_help(
ctx,
STRUCT_LINT_MUST_BE_PUBLIC::get_by_severity(*severity),
self.name().as_str(),
definition_span,
format!(
"Struct '{item_name}' has {visibility_desc} visibility, but must be pub"
),
None,
"Change the visibility to 'pub'",
);
}
}
StructRule::MustBePubCrate(severity) => {
if !is_pub_crate {
let visibility_desc = if is_public { "pub" } else { "private" };
span_lint_and_help(
ctx,
STRUCT_LINT_MUST_BE_PUB_CRATE::get_by_severity(*severity),
self.name().as_str(),
definition_span,
format!(
"Struct '{item_name}' has {visibility_desc} visibility, but must be pub(crate)"
),
None,
"Change the visibility to 'pub(crate)'",
);
}
}
_ => {} // Ignore other rule types for now
}
}
}
}
}