/
main.rs
258 lines (236 loc) · 6.86 KB
/
main.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
use std::fs;
use std::io::Read;
use std::process;
use anyhow::{Context, Result};
use atty::Stream;
use clap::Parser;
use colored::Colorize;
use rayon::prelude::*;
use tracing::info_span;
use tracing_subscriber::fmt::format::FmtSpan;
mod cli;
mod config;
mod filter;
mod interactive;
mod lint;
mod parse;
const EXIT_SUCCESS: i32 = 0;
const EXIT_FAIL_LINT: i32 = 1;
const EXIT_OTHER: i32 = 2;
fn read_datalog_file(datalog_file: &str) -> Result<String> {
let span = info_span!("read_datalog_file");
let _enter = span.enter();
fs::read_to_string(datalog_file)
.with_context(|| format!("Failed to read Datalog file {}", datalog_file))
}
fn parse_datalog(datalog_code: &str) -> Result<tree_sitter::Tree> {
let span = info_span!("parse_datalog");
let _enter = span.enter();
parse::tree(datalog_code)
}
fn read_config(path: &str) -> Result<config::Config> {
let span = info_span!("read_config");
let _enter = span.enter();
let config_text =
fs::read_to_string(path).with_context(|| format!("Failed to read config file {}", path))?;
Ok(serde_yaml::from_str(&config_text)?)
}
fn merge_configs(configs: &Vec<String>, no_default_rules: bool) -> Result<config::Config> {
let mut all_configs = if no_default_rules {
Vec::new()
} else {
vec![config::default()]
};
all_configs.reserve(configs.len());
for config_path in configs {
all_configs.push(read_config(config_path)?);
}
Ok(config::Config::merge(all_configs))
}
struct DatalogSrc(String);
fn lint_src(
language: tree_sitter::Language,
datalog_file: &str,
datalog_source: DatalogSrc,
rules: &Vec<config::Rule>,
format: &cli::Format,
interactive: &interactive::Interactive,
no_fail: bool,
) -> Result<bool> {
let DatalogSrc(src) = datalog_source;
let tree = parse_datalog(&src)?;
let mut fail = false;
let diagnostics: Vec<Result<Vec<_>>> = rules
.par_iter()
.map(|r| lint::query(language, datalog_file, &src, &tree, r))
.collect();
for diags in diagnostics {
for diag in diags? {
if !no_fail {
fail = true;
}
diag.display(format, interactive);
}
}
Ok(fail)
}
// TODO(lb): Check for duplicated rule IDs
// TODO(lb): Warn on lack of examples
// TODO(lb): Warn on empty short description
// TODO(lb): Warn on empty long description
fn check_config(config: &config::Config) {
let mut err = false;
for rule in &config.rules {
if rule.queries.is_empty() {
err = true;
eprintln!("Error: No queries for rule {}", rule.name);
}
}
if err {
process::exit(EXIT_OTHER);
}
}
fn lint(
configs: &Vec<String>,
no_default_rules: bool,
datalog_files: &Vec<String>,
format: &cli::Format,
filt: &filter::RuleFilter,
interactive: &interactive::Interactive,
no_fail: bool,
) -> Result<i32> {
let config = merge_configs(configs, no_default_rules)?;
check_config(&config);
let rules = filter::filter(config.rules, filt);
if rules.is_empty() {
eprintln!("No rules specified! Returning immediately without parsing.");
return Ok(EXIT_OTHER);
}
let language = tree_sitter_souffle::language();
// TODO(lb): parallelize this loop?
let mut exit = EXIT_SUCCESS;
if datalog_files.is_empty()
&& lint_src(
language,
"<stdin>",
DatalogSrc(stdin_string()?),
&rules,
format,
interactive,
no_fail,
)
.context("Failed to lint stdin")?
{
exit = EXIT_FAIL_LINT;
}
for datalog_file in datalog_files {
if lint_src(
language,
datalog_file,
DatalogSrc(read_datalog_file(datalog_file)?),
&rules,
format,
interactive,
no_fail,
)
.with_context(|| format!("Failed to lint file {}", datalog_file))?
{
exit = EXIT_FAIL_LINT;
}
}
Ok(exit)
}
fn info_rule(rule: &config::Rule) {
println!();
println!("{}: {}", rule.name.bold(), rule.short);
if let Some(l) = &rule.long {
println!("\n{}", l);
}
for ex in &rule.examples {
println!("Example:");
let before_lines: Vec<_> = ex.before.lines().collect();
let after_lines: Vec<_> = ex.after.lines().collect();
if before_lines.len() > 1 || after_lines.len() > 1 {
println!("\n Before:\n");
for line in before_lines {
println!(" {}", line);
}
println!("\n After:\n");
for line in after_lines {
println!(" {}", line);
}
} else {
print!(" Before: {}", ex.before);
print!(" After: {}", ex.after);
}
}
}
fn info(configs: &Vec<String>, rule_name: &Option<String>) -> Result<i32> {
let config = merge_configs(configs, false)?;
for rule in config.rules {
match rule_name {
Some(name) => {
if &rule.name == name {
info_rule(&rule);
}
}
None => info_rule(&rule),
}
}
Ok(EXIT_SUCCESS)
}
fn print_as_sexp(datalog_source: &str) -> Result<()> {
let tree = parse_datalog(datalog_source)?;
println!("{}", tree.root_node().to_sexp());
Ok(())
}
fn stdin_string() -> Result<String> {
let mut stdin_str: String = String::new();
std::io::stdin().read_to_string(&mut stdin_str)?;
Ok(stdin_str)
}
fn sexp(datalog_files: &Vec<String>) -> Result<i32> {
if datalog_files.is_empty() {
print_as_sexp(&stdin_string()?)?;
}
for datalog_file in datalog_files {
print_as_sexp(&read_datalog_file(datalog_file)?)?;
}
Ok(EXIT_SUCCESS)
}
fn main() -> Result<()> {
let mut args = cli::Args::parse();
args.interactive = args.interactive && atty::is(Stream::Stdout);
if args.trace {
// TODO(lb): Make this less verbose, drop time
tracing_subscriber::fmt::fmt()
.with_span_events(FmtSpan::ENTER | FmtSpan::CLOSE)
.with_target(false)
.with_level(false)
.init();
}
let span = info_span!("main");
let _enter = span.enter();
process::exit(match args.command {
cli::Cmd::Lint {
config,
datalog_files,
format,
only,
ignore,
slow,
no_default_rules,
no_fail,
} => lint(
&config,
no_default_rules,
&datalog_files,
&format,
&filter::RuleFilter { only, ignore, slow },
&From::from(args.interactive),
no_fail,
)?,
cli::Cmd::Info { config, rule } => info(&config, &rule)?,
cli::Cmd::Sexp { datalog_files } => sexp(&datalog_files)?,
})
}