-
Notifications
You must be signed in to change notification settings - Fork 178
Expand file tree
/
Copy pathunused_data_var.rs
More file actions
367 lines (307 loc) · 10.6 KB
/
unused_data_var.rs
File metadata and controls
367 lines (307 loc) · 10.6 KB
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
//! Lint to find unused global (`declare-data-var`) variables
//!
//! A diagnostic is generated if:
//! - The variable is never referenced
//! - The variable is never modified (suggest using constant instead)
use std::collections::HashMap;
use clarity::vm::analysis::analysis_db::AnalysisDatabase;
use clarity::vm::analysis::types::ContractAnalysis;
use clarity::vm::diagnostic::{Diagnostic, Level};
use clarity::vm::representations::Span;
use clarity::vm::{ClarityVersion, SymbolicExpression};
use clarity_types::ClarityName;
use crate::analysis::annotation::{get_index_of_span, Annotation, AnnotationKind, WarningKind};
use crate::analysis::ast_visitor::{traverse, ASTVisitor};
use crate::analysis::cache::AnalysisCache;
use crate::analysis::linter::Lint;
use crate::analysis::util::is_explicitly_unused;
use crate::analysis::{self, AnalysisPass, AnalysisResult, LintName};
struct UnusedDataVarSettings {
// TODO
}
impl UnusedDataVarSettings {
fn new() -> Self {
Self {}
}
}
/// Data associated with a `define-data-var` variable
struct DataVarData<'a> {
expr: &'a SymbolicExpression,
/// Has this variable been written to?
pub written_to: bool,
/// Has this variable been read from?
pub read_from: bool,
}
impl<'a> DataVarData<'a> {
fn new(expr: &'a SymbolicExpression) -> Self {
Self {
expr,
written_to: false,
read_from: false,
}
}
}
pub struct UnusedDataVar<'a> {
clarity_version: ClarityVersion,
_settings: UnusedDataVarSettings,
annotations: &'a Vec<Annotation>,
active_annotation: Option<usize>,
level: Level,
data_vars: HashMap<&'a ClarityName, DataVarData<'a>>,
}
impl<'a> UnusedDataVar<'a> {
fn new(
clarity_version: ClarityVersion,
annotations: &'a Vec<Annotation>,
level: Level,
settings: UnusedDataVarSettings,
) -> UnusedDataVar<'a> {
Self {
clarity_version,
_settings: settings,
level,
annotations,
active_annotation: None,
data_vars: HashMap::new(),
}
}
fn run(mut self, contract_analysis: &'a ContractAnalysis) -> AnalysisResult {
// Traverse the entire AST
traverse(&mut self, &contract_analysis.expressions);
// Process hashmap of unused constants and generate diagnostics
let diagnostics = self.generate_diagnostics();
Ok(diagnostics)
}
// Check for annotations that should be attached to the given span
fn set_active_annotation(&mut self, span: &Span) {
self.active_annotation = get_index_of_span(self.annotations, span);
}
// Check if the expression is annotated with `allow(<lint_name>)`
fn allow(&self) -> bool {
self.active_annotation
.map(|idx| Self::match_allow_annotation(&self.annotations[idx]))
.unwrap_or(false)
}
/// Make diagnostic message and suggestion for variable which is never written to
fn make_diagnostic_strings_unset(name: &ClarityName) -> (String, Option<String>) {
(
format!("data variable `{name}` never modified"),
Some("Declare using `declare-constant`".to_string()),
)
}
/// Make diagnostic message and suggestion for variable which is never read from
fn make_diagnostic_strings_unread(name: &ClarityName) -> (String, Option<String>) {
(
format!("data variable `{name}` never read"),
Some("Remove this expression".to_string()),
)
}
/// Make diagnostic message and suggestion for variable which is never used
fn make_diagnostic_strings_unused(name: &ClarityName) -> (String, Option<String>) {
(
format!("data variable `{name}` never used"),
Some("Remove this expression".to_string()),
)
}
fn make_diagnostic(
&self,
expr: &'a SymbolicExpression,
message: String,
suggestion: Option<String>,
) -> Diagnostic {
Diagnostic {
level: self.level.clone(),
message,
spans: vec![expr.span.clone()],
suggestion,
}
}
fn generate_diagnostics(&mut self) -> Vec<Diagnostic> {
let mut diagnostics = vec![];
for (name, data) in &self.data_vars {
if is_explicitly_unused(name) {
continue;
}
let (message, suggestion) = match (data.read_from, data.written_to) {
(true, true) => continue,
(true, false) => Self::make_diagnostic_strings_unset(name),
(false, true) => Self::make_diagnostic_strings_unread(name),
(false, false) => Self::make_diagnostic_strings_unused(name),
};
let diagnostic = self.make_diagnostic(data.expr, message, suggestion);
diagnostics.push(diagnostic);
}
// Order the sets by the span of the error (the first diagnostic)
diagnostics.sort_by(|a, b| a.spans[0].cmp(&b.spans[0]));
diagnostics
}
}
impl<'a> ASTVisitor<'a> for UnusedDataVar<'a> {
fn get_clarity_version(&self) -> &ClarityVersion {
&self.clarity_version
}
fn visit_define_data_var(
&mut self,
expr: &'a SymbolicExpression,
name: &'a ClarityName,
_data_type: &'a SymbolicExpression,
_initial: &'a SymbolicExpression,
) -> bool {
self.set_active_annotation(&expr.span);
if !self.allow() {
self.data_vars.insert(name, DataVarData::new(expr));
}
true
}
fn visit_var_set(
&mut self,
_expr: &'a SymbolicExpression,
name: &'a ClarityName,
_value: &'a SymbolicExpression,
) -> bool {
_ = self
.data_vars
.get_mut(name)
.map(|data| data.written_to = true);
true
}
fn visit_var_get(&mut self, _expr: &'a SymbolicExpression, name: &'a ClarityName) -> bool {
_ = self
.data_vars
.get_mut(name)
.map(|data| data.read_from = true);
true
}
}
impl AnalysisPass for UnusedDataVar<'_> {
fn run_pass(
_analysis_db: &mut AnalysisDatabase,
analysis_cache: &mut AnalysisCache,
level: Level,
_settings: &analysis::Settings,
) -> AnalysisResult {
let settings = UnusedDataVarSettings::new();
let lint = UnusedDataVar::new(
analysis_cache.contract_analysis.clarity_version,
analysis_cache.annotations,
level,
settings,
);
lint.run(analysis_cache.contract_analysis)
}
}
impl Lint for UnusedDataVar<'_> {
fn get_name() -> LintName {
LintName::UnusedDataVar
}
fn match_allow_annotation(annotation: &Annotation) -> bool {
match &annotation.kind {
AnnotationKind::Allow(warning_kinds) => {
warning_kinds.contains(&WarningKind::UnusedDataVar)
}
_ => false,
}
}
}
#[cfg(test)]
mod tests {
use clarity::vm::ExecutionResult;
use clarity_types::diagnostic::Level;
use indoc::indoc;
use super::UnusedDataVar;
use crate::analysis::linter::Lint;
use crate::repl::session::Session;
use crate::repl::SessionSettings;
fn run_snippet(snippet: String) -> (Vec<String>, ExecutionResult) {
let mut settings = SessionSettings::default();
settings
.repl_settings
.analysis
.enable_lint(UnusedDataVar::get_name(), Level::Warning);
Session::new_without_boot_contracts(settings)
.formatted_interpretation(snippet, Some("checker".to_string()), false, None)
.expect("Invalid code snippet")
}
#[test]
fn used() {
#[rustfmt::skip]
let snippet = indoc!("
(define-data-var counter uint u0)
(define-public (increment)
(ok (var-set counter (+ (var-get counter) u1))))
").to_string();
let (_, result) = run_snippet(snippet);
assert_eq!(result.diagnostics.len(), 0);
}
#[test]
fn not_set() {
#[rustfmt::skip]
let snippet = indoc!("
(define-data-var counter uint u0)
(define-public (read-counter)
(ok (var-get counter)))
").to_string();
let (output, result) = run_snippet(snippet);
let var_name = "counter";
let (expected_message, _) = UnusedDataVar::make_diagnostic_strings_unset(&var_name.into());
assert_eq!(result.diagnostics.len(), 1);
assert!(output[0].contains("warning:"));
assert!(output[0].contains(var_name));
assert!(output[0].contains(&expected_message));
}
#[test]
fn not_read() {
#[rustfmt::skip]
let snippet = indoc!("
(define-data-var counter uint u0)
(define-public (set (val uint))
(ok (var-set counter val)))
").to_string();
let (output, result) = run_snippet(snippet);
let var_name = "counter";
let (expected_message, _) = UnusedDataVar::make_diagnostic_strings_unread(&var_name.into());
assert_eq!(result.diagnostics.len(), 1);
assert!(output[0].contains("warning:"));
assert!(output[0].contains(var_name));
assert!(output[0].contains(&expected_message));
}
#[test]
fn not_used() {
#[rustfmt::skip]
let snippet = indoc!("
(define-data-var counter uint u0)
(define-public (read-counter)
(ok u5))
").to_string();
let (output, result) = run_snippet(snippet);
let var_name = "counter";
let (expected_message, _) = UnusedDataVar::make_diagnostic_strings_unused(&var_name.into());
assert_eq!(result.diagnostics.len(), 1);
assert!(output[0].contains("warning:"));
assert!(output[0].contains(var_name));
assert!(output[0].contains(&expected_message));
}
#[test]
fn allow_with_annotation() {
#[rustfmt::skip]
let snippet = indoc!("
;; #[allow(unused_data_var)]
(define-data-var counter uint u0)
(define-public (read-counter)
(ok u5))
").to_string();
let (_, result) = run_snippet(snippet);
assert_eq!(result.diagnostics.len(), 0);
}
#[test]
fn allow_with_naming_convention() {
#[rustfmt::skip]
let snippet = indoc!("
(define-data-var counter_ uint u0)
(define-public (read-counter)
(ok u5))
").to_string();
let (_, result) = run_snippet(snippet);
assert_eq!(result.diagnostics.len(), 0);
}
}