-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathmain.rs
More file actions
367 lines (349 loc) · 12.4 KB
/
main.rs
File metadata and controls
367 lines (349 loc) · 12.4 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
use crate::diagnostics::{ExtractionStep, emit_extraction_diagnostics};
use crate::rust_analyzer::path_to_file_id;
use crate::translate::{ResolvePaths, SourceKind};
use crate::trap::TrapId;
use anyhow::Context;
use archive::Archiver;
use ra_ap_base_db::SourceDatabase;
use ra_ap_hir::Semantics;
use ra_ap_ide_db::RootDatabase;
use ra_ap_ide_db::line_index::{LineCol, LineIndex};
use ra_ap_load_cargo::LoadCargoConfig;
use ra_ap_paths::{AbsPathBuf, Utf8PathBuf};
use ra_ap_project_model::{CargoConfig, ProjectManifest};
use ra_ap_vfs::Vfs;
use rust_analyzer::{ParseResult, RustAnalyzer};
use std::collections::HashSet;
use std::hash::RandomState;
use std::time::Instant;
use std::{
collections::HashMap,
path::{Path, PathBuf},
};
use std::{env, fs};
use tracing::{error, info, warn};
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
mod archive;
mod config;
mod crate_graph;
mod diagnostics;
pub mod generated;
mod qltest;
mod rust_analyzer;
mod translate;
pub mod trap;
struct Extractor<'a> {
archiver: &'a Archiver,
traps: &'a trap::TrapFileProvider,
steps: Vec<ExtractionStep>,
}
impl<'a> Extractor<'a> {
pub fn new(archiver: &'a Archiver, traps: &'a trap::TrapFileProvider) -> Self {
Self {
archiver,
traps,
steps: Vec::new(),
}
}
fn extract(
&mut self,
rust_analyzer: &RustAnalyzer,
file: &Path,
resolve_paths: ResolvePaths,
source_kind: SourceKind,
) {
self.archiver.archive(file);
let before_parse = Instant::now();
let ParseResult {
ast,
text,
errors,
semantics_info,
} = rust_analyzer.parse(file);
self.steps
.push(ExtractionStep::parse(before_parse, source_kind, file));
let before_extract = Instant::now();
let line_index = LineIndex::new(text.as_ref());
let display_path = file.to_string_lossy();
let mut trap = self.traps.create("source", file);
let label = trap.emit_file(file);
let mut translator = translate::Translator::new(
trap,
display_path.as_ref(),
label,
line_index,
semantics_info.as_ref().ok(),
resolve_paths,
source_kind,
);
for err in errors {
translator.emit_parse_error(&ast, &err);
}
let no_location = (LineCol { line: 0, col: 0 }, LineCol { line: 0, col: 0 });
if let Err(reason) = semantics_info {
if !reason.is_empty() {
let message = format!("semantic analyzer unavailable ({reason})");
let full_message = format!(
"{message}: macro expansion, call graph, and type inference will be skipped."
);
translator.emit_diagnostic(
trap::DiagnosticSeverity::Warning,
"semantics".to_owned(),
message,
full_message,
no_location,
);
}
}
translator.emit_source_file(&ast);
translator.emit_truncated_diagnostics_message();
translator.trap.commit().unwrap_or_else(|err| {
error!(
"Failed to write trap file for: {}: {}",
display_path,
err.to_string()
)
});
self.steps
.push(ExtractionStep::extract(before_extract, source_kind, file));
}
pub fn extract_with_semantics(
&mut self,
file: &Path,
semantics: &Semantics<'_, RootDatabase>,
vfs: &Vfs,
resolve_paths: ResolvePaths,
source_kind: SourceKind,
) {
self.extract(
&RustAnalyzer::new(vfs, semantics),
file,
resolve_paths,
source_kind,
);
}
pub fn extract_without_semantics(
&mut self,
file: &Path,
source_kind: SourceKind,
reason: &str,
) {
self.extract(
&RustAnalyzer::WithoutSemantics { reason },
file,
ResolvePaths::No,
source_kind,
);
}
pub fn load_manifest(
&mut self,
project: &ProjectManifest,
config: &CargoConfig,
load_config: &LoadCargoConfig,
) -> Option<(RootDatabase, Vfs)> {
let before = Instant::now();
let ret = RustAnalyzer::load_workspace(project, config, load_config);
self.steps
.push(ExtractionStep::load_manifest(before, project));
ret
}
pub fn load_source(
&mut self,
file: &Path,
semantics: &Semantics<'_, RootDatabase>,
vfs: &Vfs,
) -> Result<(), String> {
let before = Instant::now();
let Some(id) = path_to_file_id(file, vfs) else {
return Err("not included in files loaded from manifest".to_string());
};
match semantics.file_to_module_def(id) {
None => return Err("not included as a module".to_string()),
Some(module)
if module
.as_source_file_id(semantics.db)
.is_none_or(|mod_file_id| mod_file_id.file_id(semantics.db) != id) =>
{
return Err(
"not loaded as its own module, probably included by `!include`".to_string(),
);
}
_ => {}
};
self.steps.push(ExtractionStep::load_source(before, file));
Ok(())
}
pub fn emit_extraction_diagnostics(
self,
start: Instant,
cfg: &config::Config,
) -> anyhow::Result<()> {
emit_extraction_diagnostics(start, cfg, &self.steps)?;
let mut trap = self.traps.create("diagnostics", "extraction");
for step in self.steps {
let file = step.file.as_ref().map(|f| trap.emit_file(f));
let duration_ms = usize::try_from(step.ms).unwrap_or_else(|_e| {
warn!("extraction step duration overflowed ({step:?})");
i32::MAX as usize
});
trap.emit(generated::ExtractorStep {
id: TrapId::Star,
action: format!("{:?}", step.action),
file,
duration_ms,
});
}
trap.commit()?;
Ok(())
}
pub fn find_manifests(&mut self, files: &[PathBuf]) -> anyhow::Result<Vec<ProjectManifest>> {
let before = Instant::now();
let ret = rust_analyzer::find_project_manifests(files);
self.steps.push(ExtractionStep::find_manifests(before));
ret
}
}
fn cwd() -> anyhow::Result<AbsPathBuf> {
let path = std::env::current_dir().context("current directory")?;
let utf8_path = Utf8PathBuf::from_path_buf(path)
.map_err(|p| anyhow::anyhow!("{} is not a valid UTF-8 path", p.display()))?;
let abs_path = AbsPathBuf::try_from(utf8_path)
.map_err(|p| anyhow::anyhow!("{} is not absolute", p.as_str()))?;
Ok(abs_path)
}
fn main() -> anyhow::Result<()> {
let mut cfg = config::Config::extract().context("failed to load configuration")?;
if cfg.qltest {
qltest::prepare(&mut cfg)?;
}
let start = Instant::now();
let (flame_layer, _flush_guard) = if let Some(path) = &cfg.logging_flamegraph {
tracing_flame::FlameLayer::with_file(path)
.ok()
.map(|(a, b)| (Some(a), Some(b)))
.unwrap_or((None, None))
} else {
(None, None)
};
tracing_subscriber::registry()
.with(codeql_extractor::extractor::default_subscriber_with_level(
"single_arch",
&cfg.logging_verbosity,
))
.with(flame_layer)
.init();
info!("{cfg:#?}\n");
let traps = trap::TrapFileProvider::new(&cfg).context("failed to set up trap files")?;
let archiver = archive::Archiver {
root: cfg.source_archive_dir.clone(),
};
let mut extractor = Extractor::new(&archiver, &traps);
let files: Vec<PathBuf> = cfg
.inputs
.iter()
.map(|file| {
let file = std::path::absolute(file).unwrap_or(file.to_path_buf());
// On Windows, rust analyzer expects non-`//?/` prefixed paths (see [1]), which is what
// `std::fs::canonicalize` returns. So we use `dunce::canonicalize` instead.
// [1]: https://github.com/rust-lang/rust-analyzer/issues/18894#issuecomment-2580014730
dunce::canonicalize(&file).unwrap_or(file)
})
.collect();
let manifests = extractor.find_manifests(&files)?;
let mut map: HashMap<&Path, (&ProjectManifest, Vec<&Path>)> = manifests
.iter()
.map(|x| (x.manifest_path().parent().as_ref(), (x, Vec::new())))
.collect();
'outer: for file in &files {
for ancestor in file.as_path().ancestors() {
if let Some((_, files)) = map.get_mut(ancestor) {
files.push(file);
continue 'outer;
}
}
extractor.extract_without_semantics(file, SourceKind::Source, "no manifest found");
}
let cwd = cwd()?;
let (cargo_config, load_cargo_config) = cfg.to_cargo_config(&cwd);
let resolve_paths = if cfg.skip_path_resolution {
ResolvePaths::No
} else {
ResolvePaths::Yes
};
let (library_mode, library_resolve_paths) = if cfg.extract_dependencies_as_source {
(SourceKind::Source, resolve_paths)
} else {
(SourceKind::Library, ResolvePaths::No)
};
let (source_mode, source_resolve_paths) = if cfg.force_library_mode {
(library_mode, library_resolve_paths)
} else {
(SourceKind::Source, resolve_paths)
};
let mut processed_files: HashSet<PathBuf, RandomState> =
HashSet::from_iter(files.iter().cloned());
for (manifest, files) in map.values().filter(|(_, files)| !files.is_empty()) {
if let Some((ref db, ref vfs)) =
extractor.load_manifest(manifest, &cargo_config, &load_cargo_config)
{
let before_crate_graph = Instant::now();
crate_graph::extract_crate_graph(extractor.traps, db, vfs);
extractor
.steps
.push(ExtractionStep::crate_graph(before_crate_graph));
let semantics = Semantics::new(db);
for file in files {
match extractor.load_source(file, &semantics, vfs) {
Ok(()) => extractor.extract_with_semantics(
file,
&semantics,
vfs,
source_resolve_paths,
source_mode,
),
Err(reason) => extractor.extract_without_semantics(file, source_mode, &reason),
};
}
for (file_id, file) in vfs.iter() {
if let Some(file) = file.as_path().map(<_ as AsRef<Path>>::as_ref) {
if file.extension().is_some_and(|ext| ext == "rs")
&& processed_files.insert(file.to_owned())
&& db
.source_root(db.file_source_root(file_id).source_root_id(db))
.source_root(db)
.is_library
{
extractor.extract_with_semantics(
file,
&semantics,
vfs,
library_resolve_paths,
library_mode,
);
extractor.archiver.archive(file);
}
}
}
} else {
for file in files {
extractor.extract_without_semantics(
file,
SourceKind::Source,
"unable to load manifest",
);
}
}
}
let builtins_dir = env::var("CODEQL_EXTRACTOR_RUST_ROOT")
.map(|path| Path::new(&path).join("tools").join("builtins"))?;
let builtins = fs::read_dir(builtins_dir).context("failed to read builtins directory")?;
for entry in builtins {
let entry = entry.context("failed to read builtins directory")?;
let path = entry.path();
if path.extension().is_some_and(|ext| ext == "rs") {
extractor.extract_without_semantics(&path, SourceKind::Library, "");
}
}
extractor.emit_extraction_diagnostics(start, &cfg)
}