0
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-02-08 07:16:56 -05:00
denoland-deno/cli/tools/lint/plugins.rs

492 lines
14 KiB
Rust
Raw Permalink Normal View History

2024-12-01 03:21:16 +01:00
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
2024-12-02 01:38:54 +01:00
use deno_ast::ModuleSpecifier;
use deno_ast::ParsedSource;
2024-12-02 18:29:30 +01:00
use deno_ast::SourceRange;
use deno_ast::SourceTextInfo;
2024-12-03 03:11:26 +01:00
use deno_ast::SourceTextProvider;
2024-12-01 03:21:16 +01:00
use deno_core::error::custom_error;
use deno_core::error::AnyError;
use deno_core::futures::FutureExt;
use deno_core::op2;
2024-12-04 02:37:04 +01:00
use deno_core::resolve_url_or_path;
2024-12-01 03:21:16 +01:00
use deno_core::v8;
use deno_core::OpState;
use deno_core::PollEventLoopOptions;
2024-12-02 02:27:30 +01:00
use deno_lint::diagnostic::LintDiagnostic;
use deno_lint::diagnostic::LintDiagnosticDetails;
2024-12-02 18:29:30 +01:00
use deno_lint::diagnostic::LintDiagnosticRange;
2024-12-04 02:37:04 +01:00
use deno_runtime::deno_permissions::Permissions;
use deno_runtime::deno_permissions::PermissionsContainer;
2024-12-02 01:57:49 +01:00
use deno_runtime::tokio_util;
2024-12-04 02:37:04 +01:00
use deno_runtime::worker::MainWorker;
use deno_runtime::WorkerExecutionMode;
2024-12-12 10:53:12 +01:00
use std::path::Path;
use std::path::PathBuf;
2024-12-02 01:38:54 +01:00
use std::sync::Arc;
use tokio::sync::mpsc::channel;
use tokio::sync::mpsc::Receiver;
use tokio::sync::mpsc::Sender;
2024-12-01 03:21:16 +01:00
2024-12-04 02:59:39 +01:00
use crate::args::DenoSubcommand;
2024-12-04 02:37:04 +01:00
use crate::args::Flags;
2024-12-04 02:59:39 +01:00
use crate::args::LintFlags;
2024-12-04 02:37:04 +01:00
use crate::factory::CliFactory;
2024-12-12 22:16:49 +01:00
use crate::tools::lint::swc::serialize_ast_bin;
2024-12-04 02:37:04 +01:00
2024-12-02 01:57:49 +01:00
#[derive(Debug)]
2024-12-02 01:38:54 +01:00
pub enum PluginRunnerRequest {
LoadPlugins(Vec<ModuleSpecifier>),
2024-12-05 11:21:34 +01:00
Run(Vec<u8>, PathBuf, SourceTextInfo),
2024-12-02 01:38:54 +01:00
}
pub enum PluginRunnerResponse {
LoadPlugin(Result<(), AnyError>),
2024-12-02 02:27:30 +01:00
Run(Result<Vec<LintDiagnostic>, AnyError>),
}
impl std::fmt::Debug for PluginRunnerResponse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::LoadPlugin(_arg0) => f.debug_tuple("LoadPlugin").finish(),
Self::Run(_arg0) => f.debug_tuple("Run").finish(),
}
}
2024-12-02 01:38:54 +01:00
}
2024-12-02 01:57:49 +01:00
#[derive(Debug)]
2024-12-02 01:38:54 +01:00
pub struct PluginRunnerProxy {
tx: Sender<PluginRunnerRequest>,
rx: Arc<tokio::sync::Mutex<Receiver<PluginRunnerResponse>>>,
2024-12-03 13:56:47 +01:00
#[allow(unused)]
2024-12-02 01:38:54 +01:00
join_handle: std::thread::JoinHandle<Result<(), AnyError>>,
}
pub struct PluginRunner {
2024-12-04 02:37:04 +01:00
worker: MainWorker,
2024-12-04 04:30:32 +01:00
install_plugin_fn: v8::Global<v8::Function>,
run_plugins_for_file_fn: v8::Global<v8::Function>,
2024-12-02 01:38:54 +01:00
tx: Sender<PluginRunnerResponse>,
rx: Receiver<PluginRunnerRequest>,
}
impl PluginRunner {
2024-12-04 02:37:04 +01:00
fn create() -> Result<PluginRunnerProxy, AnyError> {
2024-12-02 01:38:54 +01:00
let (tx_req, rx_req) = channel(10);
let (tx_res, rx_res) = channel(10);
2024-12-10 04:33:33 +01:00
log::debug!("spawning thread");
2024-12-02 01:38:54 +01:00
let join_handle = std::thread::spawn(move || {
2024-12-10 04:33:33 +01:00
log::debug!("PluginRunner thread spawned");
2024-12-04 04:30:32 +01:00
let start = std::time::Instant::now();
2024-12-04 02:37:04 +01:00
let fut = async move {
2024-12-12 10:53:12 +01:00
let flags = Flags {
subcommand: DenoSubcommand::Lint(LintFlags::default()),
..Default::default()
};
2024-12-04 02:59:39 +01:00
let flags = Arc::new(flags);
2024-12-04 02:37:04 +01:00
let factory = CliFactory::from_flags(flags);
let cli_options = factory.cli_options()?;
let main_module =
resolve_url_or_path("./$deno$lint.mts", cli_options.initial_cwd())
.unwrap();
// TODO(bartlomieju): should we run with all permissions?
let permissions = PermissionsContainer::new(
factory.permission_desc_parser()?.clone(),
2024-12-17 23:44:06 +01:00
// FIXME
Permissions::allow_all(),
2024-12-04 02:37:04 +01:00
);
// let npm_resolver = factory.npm_resolver().await?.clone();
// let resolver = factory.resolver().await?.clone();
let worker_factory = factory.create_cli_main_worker_factory().await?;
let worker = worker_factory
.create_custom_worker(
// TODO(bartlomieju): add "lint" execution mode
WorkerExecutionMode::Run,
main_module.clone(),
permissions,
vec![deno_lint_ext::init_ops()],
Default::default(),
)
.await?;
2024-12-02 02:27:30 +01:00
2024-12-04 02:37:04 +01:00
let mut worker = worker.into_main_worker();
let runtime = &mut worker.js_runtime;
2024-12-02 01:38:54 +01:00
2024-12-10 04:33:33 +01:00
log::debug!("before loaded");
2024-12-04 02:37:04 +01:00
2024-12-16 16:17:02 +01:00
match runtime.lazy_load_es_module_with_code(
"ext:cli/lint/selector.js",
deno_core::ascii_str_include!(concat!(
"../../js/40_lint_selector.js"
)),
) {
Ok(_) => {}
Err(err) => {
eprintln!("after load error {:#?}", err);
return Err(err);
}
}
2024-12-04 02:37:04 +01:00
let obj_result = runtime.lazy_load_es_module_with_code(
"ext:cli/lint.js",
2024-12-04 02:59:39 +01:00
deno_core::ascii_str_include!(concat!("../../js/40_lint.js")),
2024-12-04 02:37:04 +01:00
);
let obj = match obj_result {
Ok(obj) => obj,
Err(err) => {
eprintln!("after load error {:#?}", err);
return Err(err);
}
};
2024-12-10 04:33:33 +01:00
log::debug!("After plugin loaded, capturing exports");
2024-12-04 04:32:38 +01:00
let (install_plugin_fn, run_plugins_for_file_fn) = {
2024-12-04 02:37:04 +01:00
let scope = &mut runtime.handle_scope();
let module_exports: v8::Local<v8::Object> =
2024-12-04 02:37:04 +01:00
v8::Local::new(scope, obj).try_into().unwrap();
// TODO(bartlomieju): use v8::OneByteConst and `v8_static_strings!` macro from `deno_core`.
2024-12-04 04:30:32 +01:00
let install_plugin_fn_name =
v8::String::new(scope, "installPlugin").unwrap();
let install_plugin_fn_val = module_exports
.get(scope, install_plugin_fn_name.into())
.unwrap();
2024-12-04 04:30:32 +01:00
let install_plugin_fn: v8::Local<v8::Function> =
install_plugin_fn_val.try_into().unwrap();
// TODO(bartlomieju): use v8::OneByteConst and `v8_static_strings!` macro from `deno_core`.
let run_plugins_for_file_fn_name =
2024-12-04 04:30:32 +01:00
v8::String::new(scope, "runPluginsForFile").unwrap();
let run_plugins_for_file_fn_val = module_exports
.get(scope, run_plugins_for_file_fn_name.into())
.unwrap();
let run_plugins_for_file_fn: v8::Local<v8::Function> =
run_plugins_for_file_fn_val.try_into().unwrap();
(
2024-12-04 04:30:32 +01:00
v8::Global::new(scope, install_plugin_fn),
v8::Global::new(scope, run_plugins_for_file_fn),
)
2024-12-04 02:37:04 +01:00
};
let runner = Self {
worker,
2024-12-04 04:30:32 +01:00
install_plugin_fn,
run_plugins_for_file_fn,
2024-12-04 02:37:04 +01:00
tx: tx_res,
rx: rx_req,
};
// TODO(bartlomieju): send "host ready" message to the proxy
2024-12-10 04:33:33 +01:00
log::debug!("running host loop");
2024-12-04 02:37:04 +01:00
runner.run_loop().await?;
2024-12-10 04:33:33 +01:00
log::debug!(
2024-12-04 04:30:32 +01:00
"PluginRunner thread finished, took {:?}",
std::time::Instant::now() - start
);
2024-12-04 02:37:04 +01:00
Ok(())
}
.boxed_local();
tokio_util::create_and_run_current_thread(fut)
2024-12-02 01:38:54 +01:00
});
2024-12-10 04:33:33 +01:00
log::debug!("is thread finished {}", join_handle.is_finished());
2024-12-02 01:38:54 +01:00
let proxy = PluginRunnerProxy {
tx: tx_req,
rx: Arc::new(tokio::sync::Mutex::new(rx_res)),
join_handle,
};
Ok(proxy)
}
2024-12-04 02:37:04 +01:00
async fn run_loop(mut self) -> Result<(), AnyError> {
log::info!("waiting for message");
while let Some(req) = self.rx.recv().await {
log::info!("received message");
match req {
PluginRunnerRequest::LoadPlugins(specifiers) => {
let r = self.load_plugins(specifiers).await;
let _ = self.tx.send(PluginRunnerResponse::LoadPlugin(r)).await;
}
PluginRunnerRequest::Run(
serialized_ast,
specifier,
source_text_info,
) => {
let start = std::time::Instant::now();
let r = match self
2024-12-05 11:21:34 +01:00
.run_plugins(&specifier, serialized_ast, source_text_info)
2024-12-04 02:37:04 +01:00
.await
{
Ok(()) => Ok(self.take_diagnostics()),
Err(err) => Err(err),
};
log::info!(
"Running rules took {:?}",
std::time::Instant::now() - start
);
let _ = self.tx.send(PluginRunnerResponse::Run(r)).await;
2024-12-02 01:57:49 +01:00
}
}
}
2024-12-04 02:37:04 +01:00
log::info!("breaking loop");
Ok(())
2024-12-02 01:38:54 +01:00
}
2024-12-02 02:27:30 +01:00
fn take_diagnostics(&mut self) -> Vec<LintDiagnostic> {
2024-12-04 02:37:04 +01:00
let op_state = self.worker.js_runtime.op_state();
2024-12-02 02:27:30 +01:00
let mut state = op_state.borrow_mut();
2024-12-03 13:56:47 +01:00
let container = state.borrow_mut::<LintPluginContainer>();
2024-12-02 02:27:30 +01:00
std::mem::take(&mut container.diagnostics)
}
2024-12-04 04:30:32 +01:00
async fn run_plugins(
2024-12-02 01:38:54 +01:00
&mut self,
2024-12-12 10:53:12 +01:00
specifier: &Path,
2024-12-05 11:21:34 +01:00
serialized_ast: Vec<u8>,
2024-12-02 18:29:30 +01:00
source_text_info: SourceTextInfo,
2024-12-02 01:38:54 +01:00
) -> Result<(), AnyError> {
2024-12-02 18:29:30 +01:00
{
2024-12-04 02:37:04 +01:00
let state = self.worker.js_runtime.op_state();
2024-12-02 18:29:30 +01:00
let mut state = state.borrow_mut();
let container = state.borrow_mut::<LintPluginContainer>();
container.source_text_info = Some(source_text_info);
}
2024-12-04 00:31:58 +01:00
2024-12-05 11:21:34 +01:00
let (file_name_v8, ast_uint8arr_v8) = {
2024-12-04 02:37:04 +01:00
let scope = &mut self.worker.js_runtime.handle_scope();
2024-12-04 00:31:58 +01:00
let file_name_v8: v8::Local<v8::Value> =
v8::String::new(scope, &specifier.display().to_string())
.unwrap()
.into();
2024-12-04 16:21:17 +01:00
2024-12-05 11:21:34 +01:00
let store = v8::ArrayBuffer::new_backing_store_from_vec(serialized_ast);
2024-12-04 16:21:17 +01:00
let ast_buf =
v8::ArrayBuffer::with_backing_store(scope, &store.make_shared());
let ast_bin_v8: v8::Local<v8::Value> =
v8::Uint8Array::new(scope, ast_buf, 0, ast_buf.byte_length())
.unwrap()
.into();
2024-12-04 00:31:58 +01:00
(
v8::Global::new(scope, file_name_v8),
2024-12-04 16:21:17 +01:00
v8::Global::new(scope, ast_bin_v8),
2024-12-04 00:31:58 +01:00
)
};
2024-12-04 04:30:32 +01:00
let call = self.worker.js_runtime.call_with_args(
&self.run_plugins_for_file_fn,
2024-12-05 11:21:34 +01:00
&[file_name_v8, ast_uint8arr_v8],
2024-12-04 04:30:32 +01:00
);
let result = self
.worker
.js_runtime
.with_event_loop_promise(call, PollEventLoopOptions::default())
.await;
match result {
Ok(_r) => {
log::info!("plugins finished")
}
Err(error) => {
log::info!("error running plugins {}", error);
2024-12-01 04:53:47 +01:00
}
}
2024-12-02 01:38:54 +01:00
Ok(())
}
2024-12-01 04:53:47 +01:00
2024-12-02 01:38:54 +01:00
async fn load_plugins(
&mut self,
plugin_specifiers: Vec<ModuleSpecifier>,
) -> Result<(), AnyError> {
let mut load_futures = Vec::with_capacity(plugin_specifiers.len());
for specifier in plugin_specifiers {
2024-12-04 02:37:04 +01:00
let mod_id = self
.worker
.js_runtime
.load_side_es_module(&specifier)
.await?;
let mod_future =
self.worker.js_runtime.mod_evaluate(mod_id).boxed_local();
2024-12-02 17:00:49 +01:00
load_futures.push((mod_future, mod_id));
2024-12-02 01:38:54 +01:00
}
self
2024-12-04 02:37:04 +01:00
.worker
.js_runtime
2024-12-02 01:38:54 +01:00
.run_event_loop(PollEventLoopOptions::default())
.await?;
2024-12-02 17:00:49 +01:00
for (fut, mod_id) in load_futures {
2024-12-03 13:56:47 +01:00
fut.await?;
2024-12-04 02:37:04 +01:00
let module = self.worker.js_runtime.get_module_namespace(mod_id).unwrap();
let scope = &mut self.worker.js_runtime.handle_scope();
2024-12-02 17:00:49 +01:00
let module_local = v8::Local::new(scope, module);
let default_export_str = v8::String::new(scope, "default").unwrap();
let default_export =
module_local.get(scope, default_export_str.into()).unwrap();
2024-12-04 04:30:32 +01:00
// TODO(bartlomieju): put `install_plugin_fn` behind na `Rc``
let install_plugins_local =
v8::Local::new(scope, self.install_plugin_fn.clone());
let undefined = v8::undefined(scope);
let args = &[default_export];
log::info!("Installing plugin...");
// TODO(bartlomieju): do it in a try/catch scope
install_plugins_local.call(scope, undefined.into(), args);
log::info!("Plugin installed");
2024-12-02 01:38:54 +01:00
}
Ok(())
}
}
impl PluginRunnerProxy {
pub async fn load_plugins(
&self,
plugin_specifiers: Vec<ModuleSpecifier>,
) -> Result<(), AnyError> {
self
.tx
.send(PluginRunnerRequest::LoadPlugins(plugin_specifiers))
.await?;
let mut rx = self.rx.lock().await;
2024-12-10 04:33:33 +01:00
log::debug!("receiving load plugins");
2024-12-02 17:00:49 +01:00
if let Some(val) = rx.recv().await {
let PluginRunnerResponse::LoadPlugin(result) = val else {
unreachable!()
};
2024-12-04 02:37:04 +01:00
log::info!("load plugins response {:#?}", result);
2024-12-02 01:38:54 +01:00
return Ok(());
2024-12-01 03:40:59 +01:00
}
2024-12-02 01:38:54 +01:00
Err(custom_error("AlreadyClosed", "Plugin host has closed"))
2024-12-01 03:40:59 +01:00
}
2024-12-02 01:38:54 +01:00
pub async fn run_rules(
&self,
2024-12-12 10:53:12 +01:00
specifier: &Path,
2024-12-05 11:21:34 +01:00
serialized_ast: Vec<u8>,
2024-12-02 18:29:30 +01:00
source_text_info: SourceTextInfo,
2024-12-02 02:27:30 +01:00
) -> Result<Vec<LintDiagnostic>, AnyError> {
2024-12-02 01:38:54 +01:00
self
.tx
.send(PluginRunnerRequest::Run(
2024-12-05 11:21:34 +01:00
serialized_ast,
specifier.to_path_buf(),
source_text_info,
))
2024-12-02 01:38:54 +01:00
.await?;
let mut rx = self.rx.lock().await;
2024-12-04 02:37:04 +01:00
log::info!("receiving diagnostics");
2024-12-02 02:27:30 +01:00
if let Some(PluginRunnerResponse::Run(diagnostics_result)) = rx.recv().await
{
return diagnostics_result;
2024-12-02 01:38:54 +01:00
}
Err(custom_error("AlreadyClosed", "Plugin host has closed"))
}
}
pub async fn create_runner_and_load_plugins(
plugin_specifiers: Vec<ModuleSpecifier>,
) -> Result<PluginRunnerProxy, AnyError> {
2024-12-04 02:37:04 +01:00
let runner_proxy = PluginRunner::create()?;
2024-12-02 01:38:54 +01:00
runner_proxy.load_plugins(plugin_specifiers).await?;
Ok(runner_proxy)
}
pub async fn run_rules_for_ast(
runner_proxy: &mut PluginRunnerProxy,
2024-12-12 10:53:12 +01:00
specifier: &Path,
2024-12-05 11:21:34 +01:00
serialized_ast: Vec<u8>,
2024-12-02 18:29:30 +01:00
source_text_info: SourceTextInfo,
2024-12-02 02:27:30 +01:00
) -> Result<Vec<LintDiagnostic>, AnyError> {
2024-12-02 18:29:30 +01:00
let d = runner_proxy
.run_rules(specifier, serialized_ast, source_text_info)
2024-12-02 18:29:30 +01:00
.await?;
2024-12-02 02:27:30 +01:00
Ok(d)
2024-12-01 03:21:16 +01:00
}
2024-12-05 11:21:34 +01:00
pub fn serialize_ast(parsed_source: ParsedSource) -> Result<Vec<u8>, AnyError> {
2024-12-03 02:51:29 +01:00
let start = std::time::Instant::now();
2024-12-05 11:21:34 +01:00
let r = serialize_ast_bin(&parsed_source);
2024-12-04 02:37:04 +01:00
log::info!(
2024-12-05 11:21:34 +01:00
"serialize custom ast took {:?}",
2024-12-03 02:51:29 +01:00
std::time::Instant::now() - start
);
2024-12-05 11:21:34 +01:00
Ok(r)
2024-12-03 02:51:29 +01:00
}
2024-12-01 03:21:16 +01:00
#[derive(Default)]
struct LintPluginContainer {
2024-12-02 02:27:30 +01:00
diagnostics: Vec<LintDiagnostic>,
2024-12-02 18:29:30 +01:00
source_text_info: Option<SourceTextInfo>,
2024-12-01 03:21:16 +01:00
}
impl LintPluginContainer {
2024-12-02 18:29:30 +01:00
fn report(
&mut self,
id: String,
specifier: String,
message: String,
2024-12-03 03:11:26 +01:00
start: usize,
end: usize,
2024-12-02 18:29:30 +01:00
) {
let source_text_info = self.source_text_info.as_ref().unwrap();
2024-12-03 03:11:26 +01:00
let start_pos = source_text_info.start_pos();
let source_range = SourceRange::new(start_pos + start, start_pos + end);
2024-12-02 18:29:30 +01:00
let range = LintDiagnosticRange {
range: source_range,
description: None,
text_info: source_text_info.clone(),
};
2024-12-02 02:27:30 +01:00
let lint_diagnostic = LintDiagnostic {
// TODO: fix
specifier: ModuleSpecifier::parse(&format!("file:///{}", specifier))
.unwrap(),
2024-12-02 18:29:30 +01:00
range: Some(range),
2024-12-02 02:27:30 +01:00
details: LintDiagnosticDetails {
message,
code: id,
hint: None,
fixes: vec![],
custom_docs_url: None,
info: vec![],
},
};
self.diagnostics.push(lint_diagnostic);
}
2024-12-01 03:21:16 +01:00
}
deno_core::extension!(
deno_lint_ext,
2024-12-04 04:30:32 +01:00
ops = [op_lint_report, op_lint_get_source],
2024-12-01 03:21:16 +01:00
state = |state| {
state.put(LintPluginContainer::default());
},
);
2024-12-02 02:27:30 +01:00
#[op2(fast)]
fn op_lint_report(
state: &mut OpState,
#[string] id: String,
#[string] specifier: String,
#[string] message: String,
2024-12-03 03:11:26 +01:00
#[smi] start: usize,
#[smi] end: usize,
2024-12-02 02:27:30 +01:00
) {
2024-12-02 17:00:49 +01:00
let container = state.borrow_mut::<LintPluginContainer>();
2024-12-03 03:11:26 +01:00
container.report(id, specifier, message, start, end);
2024-12-02 02:27:30 +01:00
}
2024-12-03 13:45:31 +01:00
#[op2]
#[string]
fn op_lint_get_source(state: &mut OpState) -> String {
let container = state.borrow_mut::<LintPluginContainer>();
container
.source_text_info
.as_ref()
.unwrap()
.text_str()
.to_string()
}