diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index bd05dd23..41326456 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -4132,7 +4132,13 @@ containing `target.path` when the configuration binds it to `target.directory` (an adapter such as Delve that builds a package; a path without a directory is `debug.target.invalid` with `field: "target.path"`); or from `target.executable` (an absolute path the host found) when the configuration -binds it to `target.executable`. Refusals use the `rejected` shape with +binds it to `target.executable`. Each `adapterArguments` path is filled the +same way, from `target.path`, the directory containing it (`target.directory`) +or `target.workingDirectory`, after `env`, so `env.` adds a variable +to the bound environment and leaves one the target sets; a target without the +fact is +`debug.target.invalid` with `field: "target.path"` or +`"target.workingDirectory"`. Refusals use the `rejected` shape with `debug.provider.stale`, `debug.request.unsupported`, `debug.runtime.stale`, or `debug.target.invalid`. diff --git a/rust/crates/core/src/tests/declarative_plugins.rs b/rust/crates/core/src/tests/declarative_plugins.rs index a5e3fae0..3a153314 100644 --- a/rust/crates/core/src/tests/declarative_plugins.rs +++ b/rust/crates/core/src/tests/declarative_plugins.rs @@ -2173,6 +2173,137 @@ fn debug_start_arguments_bind_program_to_the_directory_of_the_target() { ); } +#[test] +fn debug_start_arguments_fill_adapter_arguments_from_path_facts() { + let (root, path, directory) = if cfg!(windows) { + (r"C:\work", r"C:\work\cmd\app\main.go", r"C:\work\cmd\app") + } else { + ("/work", "/work/cmd/app/main.go", "/work/cmd/app") + }; + // Delve's shape: it builds in `dlvCwd`, not in its own working directory, + // and runs the program there when `cwd` is left out. + let mut manifest = fixture("debug-adapter.plugin.json"); + manifest["debugAdapters"][0]["configurations"]["launch"]["targetBindings"] = json!({ + "program": "target.directory", + "adapterArguments": { + "dlvCwd": "target.directory", + "file": "target.path", + "root": "target.workingDirectory", + }, + }); + let start = |target: Value| { + lithe_plugin_manifest::debug_start_arguments_command(json!({ + "manifest": manifest, + "adapterID": "example", + "request": "launch", + "facts": { + "registration": { "generation": 3, "currentGeneration": 3 }, + "target": target, + }, + })) + .expect("payload is well formed") + }; + let launch = start(json!({ "kind": "file", "path": path, "workingDirectory": root })); + assert_eq!(launch["status"], "ok", "{launch}"); + assert_eq!( + launch["arguments"], + json!({ + "stopOnEntry": false, + "program": directory, + "dlvCwd": directory, + "file": path, + "root": root, + }) + ); + + // A fact an adapter argument reads must be there, or the start is refused + // before the adapter builds in the wrong place. + let refused = start(json!({ "kind": "file", "path": path })); + assert_eq!( + refused["error"]["code"], "debug.target.invalid", + "{refused}" + ); + assert_eq!( + refused["error"]["field"], "target.workingDirectory", + "{refused}" + ); +} + +#[test] +fn debug_start_arguments_add_an_adapter_argument_to_the_environment() { + let (root, path, directory) = if cfg!(windows) { + (r"C:\work", r"C:\work\cmd\app\main.go", r"C:\work\cmd\app") + } else { + ("/work", "/work/cmd/app/main.go", "/work/cmd/app") + }; + // Delve's shape: `go build` runs in `dlvCwd` and reads the directory from + // `PWD`, which Delve leaves at the host's root, so both name the package. + let start = |arguments: Value, bindings: Value, target: Value| { + let mut manifest = fixture("debug-adapter.plugin.json"); + manifest["debugAdapters"][0]["configurations"]["launch"]["arguments"] = arguments; + manifest["debugAdapters"][0]["configurations"]["launch"]["targetBindings"] = bindings; + let outcome = lithe_plugin_manifest::debug_start_arguments_command(json!({ + "manifest": manifest, + "adapterID": "example", + "request": "launch", + "facts": { + "registration": { "generation": 3, "currentGeneration": 3 }, + "target": target, + }, + })) + .expect("payload is well formed"); + assert_eq!(outcome["status"], "ok", "{outcome}"); + outcome["arguments"].clone() + }; + let target = json!({ "kind": "file", "path": path, "workingDirectory": root }); + let into_pwd = json!({ "dlvCwd": "target.directory", "env.PWD": "target.directory" }); + + // The variable joins the ones the configuration sets itself. + let defaults = start( + json!({ "program": ".", "env": { "GO111MODULE": "auto" } }), + json!({ "adapterArguments": into_pwd }), + target.clone(), + ); + assert_eq!( + defaults, + json!({ + "program": ".", + "dlvCwd": directory, + "env": { "GO111MODULE": "auto", "PWD": directory }, + }) + ); + + // It joins the target's environment too, and a variable the target sets + // itself stays as the target set it. + let mut bound = target.clone(); + bound["environment"] = json!({ "PWD": "/elsewhere", "TOKEN": "1" }); + let bound = start( + json!({}), + json!({ "env": "target.environment", "adapterArguments": into_pwd }), + bound, + ); + assert_eq!(bound["env"], json!({ "PWD": "/elsewhere", "TOKEN": "1" })); + + // With no environment anywhere, the argument starts one. + let created = start(json!({}), json!({ "adapterArguments": into_pwd }), target); + assert_eq!(created["env"], json!({ "PWD": directory })); +} + +#[test] +fn debug_adapter_arguments_survive_manifest_normalization() { + let mut manifest = fixture("debug-adapter.plugin.json"); + manifest["debugAdapters"][0]["configurations"]["launch"]["targetBindings"] + ["adapterArguments"] = json!({ "dlvCwd": "target.directory" }); + let outcome = validate(manifest); + assert_eq!(outcome["status"], "ok", "{outcome}"); + // Hosts read the normalized declaration, so the binding must survive it. + assert_eq!( + outcome["plugin"]["debugAdapters"][0]["configurations"]["launch"]["targetBindings"] + ["adapterArguments"], + json!({ "dlvCwd": "target.directory" }) + ); +} + #[test] fn debug_executable_plan_lists_the_configured_path_and_ordered_candidates() { let plan = debug_executable_plan( diff --git a/rust/crates/debug/src/adapters.rs b/rust/crates/debug/src/adapters.rs index 8f80c725..5e385513 100644 --- a/rust/crates/debug/src/adapters.rs +++ b/rust/crates/debug/src/adapters.rs @@ -23,7 +23,7 @@ use lithe_plugin_model::settings::DeclaredSettings; use lithe_plugin_model::{invalid, is_safe_relative_path, PluginRejection, Validation}; use serde::{Deserialize, Deserializer, Serialize}; use serde_json::{json, Map, Value}; -use std::collections::{BTreeSet, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::net::IpAddr; mod announcement; @@ -93,6 +93,23 @@ const TARGET_EXECUTABLE: &str = "target.executable"; /// target's path, for adapters that debug a package rather than one file. const TARGET_DIRECTORY: &str = "target.directory"; +/// Facts an `adapterArguments` binding may read: the target's own path, the +/// directory containing it, and the working directory. Each means the same to +/// every adapter, whatever the adapter calls the argument. +const ADAPTER_ARGUMENT_FACTS: &[&str] = + &["target.path", TARGET_DIRECTORY, "target.workingDirectory"]; + +/// Most adapter-specific arguments one configuration may bind. +const MAX_ADAPTER_ARGUMENTS: usize = 8; + +/// Arguments that have a typed binding of their own, so `adapterArguments` +/// may not start at them. +const FIXED_BINDINGS: &[&str] = &["program", "processId", "cwd", "args", ENVIRONMENT_BINDING]; + +/// The fixed binding that holds an object of environment variables, the only +/// one an `adapterArguments` path may reach into, to add one variable. +const ENVIRONMENT_BINDING: &str = "env"; + /// The target kind of a remote `host:port` the debuggee listens on. const TARGET_CONNECTION: &str = "connection"; diff --git a/rust/crates/debug/src/adapters/declaration.rs b/rust/crates/debug/src/adapters/declaration.rs index 6c1aa2f2..78eeface 100644 --- a/rust/crates/debug/src/adapters/declaration.rs +++ b/rust/crates/debug/src/adapters/declaration.rs @@ -133,8 +133,9 @@ pub struct DebugExecutable { pub(crate) candidates: Vec, } -/// Typed projections from the target into known DAP fields. Each field has -/// exactly one legal source, so a binding is a fact, not an expression. +/// Typed projections from the target into DAP arguments. Each fixed field has +/// a closed set of legal sources, and `adapterArguments` reads from another +/// closed set, so a binding is a fact, not an expression. #[derive(Debug, Clone, Default, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct DebugTargetBindings { @@ -157,6 +158,15 @@ pub struct DebugTargetBindings { /// Where a remote `host:port` goes. Attach only. #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) connection: Option, + /// Argument paths only this adapter defines, each filled from a path fact + /// of the target: `target.path`, `target.directory` or + /// `target.workingDirectory`. A path is dotted like a connection + /// destination, and inside `env` it names one variable. Delve, for + /// example, builds the program in `dlvCwd` rather than in its own working + /// directory, which a host sets to the workspace root, and the build reads + /// the directory from `env.PWD` when the path passes a symbolic link. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) adapter_arguments: Option>, } /// Where each fact of a remote target lands in the adapter's attach diff --git a/rust/crates/debug/src/adapters/plan.rs b/rust/crates/debug/src/adapters/plan.rs index a0e9b329..8742b9f4 100644 --- a/rust/crates/debug/src/adapters/plan.rs +++ b/rust/crates/debug/src/adapters/plan.rs @@ -155,6 +155,18 @@ pub fn plan( { return Err(missing("target.workingDirectory", "working directory")); } + for fact in bindings.adapter_arguments.iter().flat_map(BTreeMap::values) { + if path_fact(target, fact).is_some() { + continue; + } + return Err(match fact.as_str() { + "target.workingDirectory" => missing("target.workingDirectory", "working directory"), + TARGET_DIRECTORY if target.path.as_deref().is_some_and(|path| !path.is_empty()) => { + missing("target.path", "path inside a directory") + } + _ => missing("target.path", "path"), + }); + } if let Some(connection) = &bindings.connection { connection_endpoint(target)?; if let Some(shape) = &connection.path_mappings { diff --git a/rust/crates/debug/src/adapters/start.rs b/rust/crates/debug/src/adapters/start.rs index 7e1c55da..1aab0b36 100644 --- a/rust/crates/debug/src/adapters/start.rs +++ b/rust/crates/debug/src/adapters/start.rs @@ -179,6 +179,13 @@ fn bound_arguments( &bindings.env, target.environment.as_ref().map(|env| json!(env)), ); + // After `env`, so a path inside it adds a variable to the bound + // environment instead of replacing it. + for (path, fact) in bindings.adapter_arguments.iter().flatten() { + if let Some(value) = path_fact(target, fact) { + fill_argument(&mut arguments, path, Value::from(value))?; + } + } let connection = match &bindings.connection { Some(binding) => Some(bind_connection(binding, target, &mut arguments)?), None => None, @@ -198,6 +205,18 @@ pub(crate) fn target_directory(path: &str) -> Option<&str> { .filter(|directory| !directory.is_empty()) } +/// The value of a path fact an `adapterArguments` binding reads, or `None` +/// when the target does not carry it. +pub(crate) fn path_fact<'a>(target: &'a TargetFacts, fact: &str) -> Option<&'a str> { + let present = |value: &'a Option| value.as_deref().filter(|value| !value.is_empty()); + match fact { + "target.path" => present(&target.path), + TARGET_DIRECTORY => present(&target.path).and_then(target_directory), + "target.workingDirectory" => present(&target.working_directory), + _ => None, + } +} + /// Writes the target's endpoint, and its path mappings when the adapter takes /// them, to the destinations the binding names. fn bind_connection( @@ -285,34 +304,53 @@ fn bind_connection( /// `DebugConnectionBinding::validate`), so an occupied path is a bug in the /// declaration that slipped past it and is refused rather than overwritten. fn set_argument(arguments: &mut Map, path: &str, value: Value) -> Validation<()> { - let occupied = || { - PluginRejection::at( - "debug.arguments.invalid", - path, - "The adapter's arguments already hold something at this path.", - ) - }; - let mut current = arguments; - let mut names = path.split('.').peekable(); - while let Some(name) = names.next() { - if names.peek().is_none() { - return match current.entry(name.to_string()) { - serde_json::map::Entry::Vacant(slot) => { - slot.insert(value); - Ok(()) - } - serde_json::map::Entry::Occupied(_) => Err(occupied()), - }; + let (parent, name) = argument_parent(arguments, path)?; + match parent.entry(name) { + serde_json::map::Entry::Vacant(slot) => { + slot.insert(value); + Ok(()) } + serde_json::map::Entry::Occupied(_) => Err(occupied_argument(path)), + } +} + +/// Fills the argument at a dotted path unless something is already there, +/// creating the objects on the way, the way every target binding fills only +/// what the defaults and earlier bindings leave out. +fn fill_argument(arguments: &mut Map, path: &str, value: Value) -> Validation<()> { + let (parent, name) = argument_parent(arguments, path)?; + parent.entry(name).or_insert(value); + Ok(()) +} + +/// The object that holds the last name of a dotted path, with that name, +/// creating the objects on the way. Validation keeps every value on the way an +/// object, so one that is not is refused rather than replaced. +fn argument_parent<'a, 'p>( + arguments: &'a mut Map, + path: &'p str, +) -> Validation<(&'a mut Map, &'p str)> { + let (parents, name) = path.rsplit_once('.').unwrap_or(("", path)); + let mut current = arguments; + for parent in parents.split('.').filter(|parent| !parent.is_empty()) { let next = current - .entry(name.to_string()) + .entry(parent.to_string()) .or_insert_with(|| Value::Object(Map::new())); let Value::Object(next) = next else { - return Err(occupied()); + return Err(occupied_argument(path)); }; current = next; } - Ok(()) + Ok((current, name)) +} + +/// The rejection of a path whose way or end the arguments already hold. +fn occupied_argument(path: &str) -> PluginRejection { + PluginRejection::at( + "debug.arguments.invalid", + path, + "The adapter's arguments already hold something at this path.", + ) } /// The endpoint a connection target names, checked. diff --git a/rust/crates/debug/src/adapters/validate_configuration.rs b/rust/crates/debug/src/adapters/validate_configuration.rs index 55fe4310..c4f082bf 100644 --- a/rust/crates/debug/src/adapters/validate_configuration.rs +++ b/rust/crates/debug/src/adapters/validate_configuration.rs @@ -59,6 +59,7 @@ impl DebugConfiguration { && bindings.args.is_none() && bindings.env.is_none() && bindings.connection.is_none() + && bindings.adapter_arguments.is_none() { return Err(invalid( &binding_field, @@ -86,6 +87,13 @@ impl DebugConfiguration { )); } } + if let Some(named) = &bindings.adapter_arguments { + validate_adapter_arguments( + &format!("{binding_field}.adapterArguments"), + named, + self.arguments.as_ref(), + )?; + } // `processId` names a running process and `connection` a remote // endpoint, which only attach has. if ((bindings.process_id.is_some() || bindings.connection.is_some()) @@ -104,6 +112,13 @@ impl DebugConfiguration { ] .into_iter() .filter_map(|(name, declared)| declared.then_some(name)) + .chain( + bindings + .adapter_arguments + .iter() + .flatten() + .map(|(name, _)| name.as_str()), + ) .collect(); connection.validate( &format!("{binding_field}.connection"), @@ -115,6 +130,89 @@ impl DebugConfiguration { } } +/// Checks the adapter-specific arguments a configuration binds: each is an +/// argument path that nothing else sets, read from a path fact. +fn validate_adapter_arguments( + field: &str, + named: &BTreeMap, + defaults: Option<&Map>, +) -> Validation<()> { + if named.is_empty() || named.len() > MAX_ADAPTER_ARGUMENTS { + return Err(invalid( + field, + format!("adapterArguments binds 1-{MAX_ADAPTER_ARGUMENTS} arguments."), + )); + } + for (index, (path, source)) in named.iter().enumerate() { + if !is_argument_path(path) { + return Err(invalid( + field, + format!( + "An argument path is up to {MAX_ARGUMENT_PATH_DEPTH} names joined by dots, each a letter or underscore followed by letters, digits, underscores, or hyphens." + ), + )); + } + let entry = format!("{field}.{path}"); + let (first, inside) = match path.split_once('.') { + Some((first, inside)) => (first, Some(inside)), + None => (path.as_str(), None), + }; + // The environment binding leaves `env` an object of variables, so a + // path may add one variable to it. Every other fixed binding holds a + // value that a path can neither replace nor reach into. + match inside { + Some(inside) if first == ENVIRONMENT_BINDING => { + if inside.contains('.') { + return Err(invalid( + entry, + "Inside env, an adapter argument names one variable.", + )); + } + } + _ if FIXED_BINDINGS.contains(&first) => { + return Err(invalid(entry, format!("{first} has a binding of its own."))); + } + _ => {} + } + if crate::backend_start::is_host_key(first) { + return Err(invalid( + entry, + "The argument belongs to the host and cannot be set by a plugin.", + )); + } + if !ADAPTER_ARGUMENT_FACTS.contains(&source.as_str()) { + return Err(invalid( + entry, + format!( + "An adapter argument can only be bound to {}.", + ADAPTER_ARGUMENT_FACTS.join(" or ") + ), + )); + } + // Two paths would fill one value twice, or one inside the other. + if let Some(other) = named + .keys() + .take(index) + .find(|other| paths_overlap(path, other)) + { + return Err(invalid( + entry, + format!("The argument path overlaps {other}."), + )); + } + // A binding only fills an argument the defaults leave out, so a + // default at the path would make the binding dead, and a default + // that is not an object on the way would leave it nowhere to go. + if defaults.is_some_and(|defaults| default_occupies(defaults, path)) { + return Err(invalid( + entry, + "The argument path is already set by the configuration's own arguments.", + )); + } + } + Ok(()) +} + impl DebugExecutable { fn validate( &self, diff --git a/rust/crates/debug/src/backend_start.rs b/rust/crates/debug/src/backend_start.rs index 86c718c7..5105cc21 100644 --- a/rust/crates/debug/src/backend_start.rs +++ b/rust/crates/debug/src/backend_start.rs @@ -109,13 +109,17 @@ fn decode(manifest: &impl DebugManifest, params: Value) -> Validation { })) } +/// Whether a DAP argument belongs to the host (see `reject_host_keys`). A +/// plugin sets one neither through its backend's configuration nor through a +/// target binding. +pub(crate) fn is_host_key(key: &str) -> bool { + key == NO_DEBUG_KEY || key.starts_with(HOST_KEY_PREFIX) +} + /// Refuses a configuration that sets a key the host owns: `noDebug`, which the /// session mode decides, or a `__` key, which carries the host's bookkeeping. pub(crate) fn reject_host_keys(configuration: &Map) -> Validation<()> { - match configuration - .keys() - .find(|key| key.as_str() == NO_DEBUG_KEY || key.starts_with(HOST_KEY_PREFIX)) - { + match configuration.keys().find(|key| is_host_key(key)) { Some(key) => Err(invalid( &format!("configuration.{key}"), "The key belongs to the host and cannot be set by a plugin.", diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 56069903..b56dc442 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -2351,6 +2351,7 @@ adapter serves `attach`), and one `onDebug:` activation event per adapter. | `selectors[]` | Optional automatic matching by `targetKinds` and `languageIDs`; absent means explicit selection only. | | `configurationTypes` | Imported `launch.json` `type` values the adapter answers to. | | `configurations.launch/attach` | Default DAP `arguments`, a packaged `parametersSchema`, and `targetBindings` (`program` ← `target.path`, or ← `target.directory`, the directory containing `target.path`, for an adapter that debugs a package such as Delve, `processId` ← `target.processID`, `cwd` ← `target.workingDirectory`, and for `attach` only `connection` ← `target.host`, `target.port`, `target.pathMappings`; also bounded `args` ← `target.arguments` and `env` ← `target.environment`; see [Remote attach](#remote-attach)). A configuration for an undeclared request is refused. | +| `targetBindings.adapterArguments` | Up to 8 DAP arguments only this adapter defines, as `{"": ""}` with the fact `target.path`, `target.directory` or `target.workingDirectory`. A path is dotted like a `connection` destination: up to 4 names, each a letter or `_` followed by up to 63 letters, digits, `_` or `-`, and objects on the way are created. For example Delve builds the program in `dlvCwd`, not in its own working directory, which the host sets to the workspace root, and `go build` reads the directory from `PWD`, which Delve leaves at that root; so a Go plugin binds `{"dlvCwd": "target.directory", "env.PWD": "target.directory"}`. Inside `env` a path names one variable and adds it to the environment the configuration or the `env` binding gives; elsewhere a path may not start at `program`, `processId`, `cwd`, `args` or `env`, which have their own bindings, or at `noDebug` or a `__` name, which belong to the host. Two paths may not overlap, nor a path and a `connection` destination, and a path may not land on or under a value the configuration's own `arguments` set, which the binding could never fill. Like every binding it fills the argument only when nothing holds it, so a variable the target's environment sets stays, and a target without the fact is refused with `debug.target.invalid`. | | `configurations.launch.executable` | For a target that is a source file the adapter cannot debug directly (C, C++, Swift): `setting` names a `file` setting of the plugin, `candidates[]` (up to 8) are the paths a host looks for when the user chose nothing. Each candidate starts with `${workspaceFolder}/` or `${fileDirectory}/`, may use `${fileBasenameNoExtension}`, and has no `..`. Declare it together with `targetBindings.program: "target.executable"` and neither without the other; a launch fills `program` with the path the host settled on. The user's setting always wins: a chosen path that is not a runnable file is an error, not a reason to try the candidates. The host shows the path it found in that setting, and the setting's `description` is where the plugin teaches how to produce the program. | | `capabilities.disabled` | Standard DAP `supports*` names or `exceptionBreakpointFilters` the host treats as absent. | | `features` | Adapter-specific DAP extensions the adapter implements; see [Adapter features and defaults](#adapter-features-and-defaults). | diff --git a/shared/plugins/contract/v1/fixtures/debug-adapters/debug-adapter-rejections.json b/shared/plugins/contract/v1/fixtures/debug-adapters/debug-adapter-rejections.json index 680f5426..ac9b2cfb 100644 --- a/shared/plugins/contract/v1/fixtures/debug-adapters/debug-adapter-rejections.json +++ b/shared/plugins/contract/v1/fixtures/debug-adapters/debug-adapter-rejections.json @@ -207,6 +207,102 @@ "edits": [{"op": "set", "path": "/block/debugAdapters/0/configurations", "value": {"launch": {"targetBindings": {"program": "target.directory"}}}}, {"op": "set", "path": "/context/target/path", "value": "main.go"}], "expected": {"code": "debug.target.invalid", "field": "target.path"} }, + { + "id": "adapter-arguments-empty", + "layer": "coreManifest", + "edits": [{"op": "set", "path": "/block/debugAdapters/0/configurations", "value": {"launch": {"targetBindings": {"adapterArguments": {}}}}}], + "expected": {"code": "plugin.manifest.invalid", "field": "debugAdapters[0].configurations.launch.targetBindings.adapterArguments"} + }, + { + "id": "adapter-arguments-too-many", + "layer": "coreManifest", + "edits": [{"op": "set", "path": "/block/debugAdapters/0/configurations", "value": {"launch": {"targetBindings": {"adapterArguments": {"a0": "target.path", "a1": "target.path", "a2": "target.path", "a3": "target.path", "a4": "target.path", "a5": "target.path", "a6": "target.path", "a7": "target.path", "a8": "target.path"}}}}}], + "expected": {"code": "plugin.manifest.invalid", "field": "debugAdapters[0].configurations.launch.targetBindings.adapterArguments"} + }, + { + "id": "adapter-argument-path-too-deep", + "layer": "coreManifest", + "edits": [{"op": "set", "path": "/block/debugAdapters/0/configurations", "value": {"launch": {"targetBindings": {"adapterArguments": {"a.b.c.d.e": "target.directory"}}}}}], + "expected": {"code": "plugin.manifest.invalid", "field": "debugAdapters[0].configurations.launch.targetBindings.adapterArguments"} + }, + { + "id": "adapter-argument-with-a-binding-of-its-own", + "layer": "coreManifest", + "edits": [{"op": "set", "path": "/block/debugAdapters/0/configurations", "value": {"launch": {"targetBindings": {"adapterArguments": {"cwd": "target.directory"}}}}}], + "expected": {"code": "plugin.manifest.invalid", "field": "debugAdapters[0].configurations.launch.targetBindings.adapterArguments.cwd"} + }, + { + "id": "adapter-argument-replaces-the-environment", + "layer": "coreManifest", + "edits": [{"op": "set", "path": "/block/debugAdapters/0/configurations", "value": {"launch": {"targetBindings": {"adapterArguments": {"env": "target.directory"}}}}}], + "expected": {"code": "plugin.manifest.invalid", "field": "debugAdapters[0].configurations.launch.targetBindings.adapterArguments.env"} + }, + { + "id": "adapter-argument-inside-a-fixed-binding", + "layer": "coreManifest", + "edits": [{"op": "set", "path": "/block/debugAdapters/0/configurations", "value": {"launch": {"targetBindings": {"adapterArguments": {"program.dir": "target.directory"}}}}}], + "expected": {"code": "plugin.manifest.invalid", "field": "debugAdapters[0].configurations.launch.targetBindings.adapterArguments.program.dir"} + }, + { + "id": "adapter-argument-two-levels-inside-the-environment", + "layer": "coreManifest", + "edits": [{"op": "set", "path": "/block/debugAdapters/0/configurations", "value": {"launch": {"targetBindings": {"adapterArguments": {"env.PWD.dir": "target.directory"}}}}}], + "expected": {"code": "plugin.manifest.invalid", "field": "debugAdapters[0].configurations.launch.targetBindings.adapterArguments.env.PWD.dir"} + }, + { + "id": "adapter-arguments-overlap-each-other", + "layer": "coreManifest", + "edits": [{"op": "set", "path": "/block/debugAdapters/0/configurations", "value": {"launch": {"targetBindings": {"adapterArguments": {"dlv": "target.path", "dlv.cwd": "target.directory"}}}}}], + "expected": {"code": "plugin.manifest.invalid", "field": "debugAdapters[0].configurations.launch.targetBindings.adapterArguments.dlv.cwd"} + }, + { + "id": "adapter-argument-under-a-default-that-is-no-object", + "layer": "coreManifest", + "edits": [{"op": "set", "path": "/block/debugAdapters/0/configurations", "value": {"launch": {"targetBindings": {"adapterArguments": {"env.PWD": "target.directory"}}, "arguments": {"env": "PWD"}}}}], + "expected": {"code": "plugin.manifest.invalid", "field": "debugAdapters[0].configurations.launch.targetBindings.adapterArguments.env.PWD"} + }, + { + "id": "adapter-argument-no-debug", + "layer": "coreManifest", + "edits": [{"op": "set", "path": "/block/debugAdapters/0/configurations", "value": {"launch": {"targetBindings": {"adapterArguments": {"noDebug": "target.path"}}}}}], + "expected": {"code": "plugin.manifest.invalid", "field": "debugAdapters[0].configurations.launch.targetBindings.adapterArguments.noDebug"} + }, + { + "id": "adapter-argument-host-prefix", + "layer": "coreManifest", + "edits": [{"op": "set", "path": "/block/debugAdapters/0/configurations", "value": {"launch": {"targetBindings": {"adapterArguments": {"__sessionId": "target.path"}}}}}], + "expected": {"code": "plugin.manifest.invalid", "field": "debugAdapters[0].configurations.launch.targetBindings.adapterArguments.__sessionId"} + }, + { + "id": "adapter-argument-from-a-non-path-fact", + "layer": "coreManifest", + "edits": [{"op": "set", "path": "/block/debugAdapters/0/configurations", "value": {"launch": {"targetBindings": {"adapterArguments": {"dlvCwd": "target.processID"}}}}}], + "expected": {"code": "plugin.manifest.invalid", "field": "debugAdapters[0].configurations.launch.targetBindings.adapterArguments.dlvCwd"} + }, + { + "id": "adapter-argument-set-by-the-defaults", + "layer": "coreManifest", + "edits": [{"op": "set", "path": "/block/debugAdapters/0/configurations", "value": {"launch": {"targetBindings": {"adapterArguments": {"dlvCwd": "target.directory"}}, "arguments": {"dlvCwd": "/work"}}}}], + "expected": {"code": "plugin.manifest.invalid", "field": "debugAdapters[0].configurations.launch.targetBindings.adapterArguments.dlvCwd"} + }, + { + "id": "adapter-argument-overlaps-the-connection", + "layer": "coreManifest", + "edits": [{"op": "set", "path": "/block/debugAdapters/0/requests", "value": ["attach"]}, {"op": "set", "path": "/context/manifestMetadata/permissions", "value": ["debug.attach", "debug.launch"]}, {"op": "set", "path": "/block/debugAdapters/0/configurations", "value": {"attach": {"targetBindings": {"adapterArguments": {"connect": "target.workingDirectory"}, "connection": {"host": "connect.host", "port": "connect.port"}}}}}], + "expected": {"code": "plugin.manifest.invalid", "field": "debugAdapters[0].configurations.attach.targetBindings.connection.host"} + }, + { + "id": "adapter-argument-without-its-path", + "layer": "corePlan", + "edits": [{"op": "set", "path": "/block/debugAdapters/0/configurations", "value": {"launch": {"targetBindings": {"adapterArguments": {"dlvCwd": "target.directory"}}}}}, {"op": "set", "path": "/context/target/path", "value": "main.go"}], + "expected": {"code": "debug.target.invalid", "field": "target.path"} + }, + { + "id": "adapter-argument-without-a-working-directory", + "layer": "corePlan", + "edits": [{"op": "set", "path": "/block/debugAdapters/0/configurations", "value": {"launch": {"targetBindings": {"adapterArguments": {"root": "target.workingDirectory"}}}}}], + "expected": {"code": "debug.target.invalid", "field": "target.workingDirectory"} + }, { "id": "executable-without-binding", "layer": "coreManifest", diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 69c61c79..40e68447 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -685,7 +685,7 @@ "$ref": "#/$defs/debugPackagePath" }, "targetBindings": { - "description": "Typed projections into known DAP fields. They only fill missing arguments; explicit values retain their existing precedence.", + "description": "Typed projections into DAP arguments. They only fill missing arguments; explicit values retain their existing precedence.", "type": "object", "additionalProperties": false, "minProperties": 1, @@ -705,6 +705,17 @@ "connection": { "description": "Attach only. Where the remote target's host and port go. Unlike the other bindings, each value is the destination argument path, because adapters name and nest these differently.", "$ref": "#/$defs/debugConnectionBinding" + }, + "adapterArguments": { + "description": "DAP arguments only this adapter defines, each filled from a path fact of the target when the request's `arguments` leave it out, for example Delve's `dlvCwd`, where it builds the program. A key is an argument path like a `connection` destination; `env.` adds one variable to the environment, such as `env.PWD`, which Go reads as the build directory. A path may not start at `program`, `processId`, `cwd`, `args` or `env` itself (they have their own bindings), at `noDebug` or a `__` name (the host's), overlap another path or a `connection` destination, or land on or under a value the configuration's own `arguments` set.", + "type": "object", + "minProperties": 1, + "maxProperties": 8, + "propertyNames": { "$ref": "#/$defs/debugArgumentPath" }, + "additionalProperties": { + "description": "`target.path` is the target's own path, `target.directory` the directory containing it, `target.workingDirectory` the working directory.", + "enum": ["target.path", "target.directory", "target.workingDirectory"] + } } } }, diff --git a/shared/plugins/guides/debug-adapter-plugin.md b/shared/plugins/guides/debug-adapter-plugin.md index 1ae73753..e64574db 100644 --- a/shared/plugins/guides/debug-adapter-plugin.md +++ b/shared/plugins/guides/debug-adapter-plugin.md @@ -72,6 +72,7 @@ - `selectors` 决定 Lithe 在哪些目标上自动选这个适配器:`targetKinds` 是目标种类,`languageIDs` 是语言。不写 `selectors` 表示只能被用户显式选择。 - `languages[]` 声明适配器服务的语言。如果这个语言已经由别的插件提供(例如 Rust),你的声明只会给它增加“可以调试”的能力,并并入你声明的文件扩展名;语言名、语言标识和语言服务器不变,装上调试器也不会重启正在运行的语言服务器。 - `targetBindings` 把调试目标的事实填进适配器的启动参数:`program` ← 目标路径(`target.path`),或目标所在目录(`target.directory`,Delve 这类按包构建再调试的适配器用它),`cwd` ← 工作目录,`processId` ← 进程 ID。只填 `arguments` 里没写的字段,不会覆盖你显式写出的默认值。目标缺少绑定要读的事实时,Lithe 会拒绝这次启动并说明缺什么。 +- 适配器自己定义的参数用 `targetBindings.adapterArguments`,键是参数路径,写法和 `connection` 的目标一样用点分隔,值是 `target.path`、`target.directory` 或 `target.workingDirectory`。例如 Delve 在 `dlvCwd` 里编译程序,而不是在它自己的工作目录(宿主设为工作区根目录)里编译;`go build` 又从 `PWD` 读当前目录,Delve 切换目录后不会改它。所以 Go 插件写 `"adapterArguments": { "dlvCwd": "target.directory", "env.PWD": "target.directory" }`,工作区根目录没有 `go.mod`、一个工作区里放了好几个模块、路径经过符号链接时,都在包所在的目录里编译。`env.<变量名>` 只往环境里加一个变量,`arguments` 的 `env` 和 `env` 绑定给的变量都保留,目标环境自己设了同名变量时以目标的为准。最多 8 个参数;路径不能从 `program`、`processId`、`cwd`、`args`、`env` 本身开始(它们有自己的绑定),不能从 `noDebug` 或 `__` 开头的名字开始(归宿主所有),路径之间、路径和 `connection` 的目标之间不能重叠,也不能落在 `arguments` 已经写了的值上或它的下面。 - `configurationTypes` 声明适配器对应的 `launch.json` `type`,用于导入用户已有的 VS Code 风格配置。 ### 3. 怎么启动适配器 @@ -269,6 +270,7 @@ Key points: - `selectors` decide on which targets Lithe picks this adapter automatically: `targetKinds` are target kinds and `languageIDs` are languages. Without `selectors`, the adapter can only be chosen explicitly by the user. - `languages[]` declares the languages the adapter serves. If another plugin already provides the language (for example Rust), your declaration only adds the ability to debug it and merges in the file extensions you declare; the language name, language ID, and language server stay the same, and installing the debugger does not restart a running language server. - `targetBindings` fills facts about the debug target into the adapter's launch arguments: `program` ← the target path (`target.path`) or the directory containing it (`target.directory`, for an adapter such as Delve that builds and debugs a package), `cwd` ← the working directory, `processId` ← the process ID. Only fields missing from `arguments` are filled; defaults you wrote explicitly are never overwritten. When the target lacks a fact a binding reads, Lithe refuses the launch and says what is missing. +- Arguments the adapter defines itself go in `targetBindings.adapterArguments`: each key is an argument path, dotted like a `connection` destination, and each value is `target.path`, `target.directory` or `target.workingDirectory`. Delve, for example, builds the program in `dlvCwd`, not in its own working directory (which the host sets to the workspace root), and `go build` reads the current directory from `PWD`, which Delve leaves unchanged when it switches. So a Go plugin writes `"adapterArguments": { "dlvCwd": "target.directory", "env.PWD": "target.directory" }`, and the build runs in the package's directory when the workspace root has no `go.mod`, when one workspace holds several modules, and when the path passes a symbolic link. `env.` adds one variable: those from the `env` in `arguments` and from the `env` binding stay, and a variable the target's environment sets itself keeps the target's value. Up to 8 arguments; a path may not start at `program`, `processId`, `cwd`, `args` or `env` itself (they have their own bindings) or at `noDebug` or a `__` name (they belong to the host), may not overlap another path or a `connection` destination, and may not land on or under a value already in `arguments`. - `configurationTypes` declares the `launch.json` `type` values the adapter matches, used to import the user's existing VS Code-style configurations. ### 3. Launching the adapter diff --git a/shared/plugins/reference/domains/debug-adapters.md b/shared/plugins/reference/domains/debug-adapters.md index 8a5421fe..796d394d 100644 --- a/shared/plugins/reference/domains/debug-adapters.md +++ b/shared/plugins/reference/domains/debug-adapters.md @@ -55,6 +55,7 @@ | 声明 | 说明 | | --- | --- | | `configurations.launch`、`configurations.attach` | 默认 DAP `arguments`、包内的 `parametersSchema` 和 `targetBindings`:`program` ← `target.path`(或 ← `target.directory`,即 `target.path` 所在目录,供 Delve 这类按包调试的适配器使用)、`processId` ← `target.processID`、`cwd` ← `target.workingDirectory`,以及有界的 `args` ← `target.arguments`、`env` ← `target.environment`;只有 `attach` 能绑定 `connection`。为未声明的请求写配置会被拒绝 | +| `targetBindings.adapterArguments` | 最多 8 个只有这个适配器才有的 DAP 参数,写成 `{"<参数路径>": "<事实>"}`,事实是 `target.path`、`target.directory` 或 `target.workingDirectory`。路径和 `connection` 的目标一样用点分隔,最多 4 段,每段以字母或 `_` 开头,其余是字母、数字、`_` 或 `-`,最长 64 个字符,途经的对象会自动创建。例如 Delve 在 `dlvCwd` 里编译程序、`go build` 从 `PWD` 读当前目录,Go 插件绑定 `{"dlvCwd": "target.directory", "env.PWD": "target.directory"}`。`env.<变量名>` 只往环境里加一个变量;其他路径不能从 `program`、`processId`、`cwd`、`args`、`env` 本身开始(有自己的绑定),不能从 `noDebug` 或 `__` 开头的名字开始(归宿主所有)。路径之间、路径和 `connection` 的目标之间不能重叠,也不能落在 `arguments` 已经写了的值上或它的下面。只在没有值时填入,目标环境自己设的同名变量保留;目标缺少要读的事实时以 `debug.target.invalid` 拒绝 | | `configurations.launch.executable` | 目标是适配器不能直接调试的源文件(C、C++、Swift)时:`setting` 指向插件的 `file` 设置,最多 8 个 `candidates[]`(以 `${workspaceFolder}/` 或 `${fileDirectory}/` 开头,不含 `..`)是用户没选时宿主查找的路径。必须与 `targetBindings.program: "target.executable"` 一起声明。用户在设置里选的路径永远优先,不是可运行文件就报错,不会改试候选 | | `capabilities.disabled` | 宿主视为不存在的标准 DAP `supports*` 名称或 `exceptionBreakpointFilters` | | `console.commandPrefix` | 1–8 个字符、不含空格的文本(lldb-dap 用反引号),适配器控制台把它读作“后面是调试器命令”;宿主只在请求补全时把它放在输入行前面,并把适配器的回答移回来,用户看不到 | @@ -193,6 +194,7 @@ Names (`request`, `event`, fields, `argument`) are a letter followed by up to 63 | Declaration | Notes | | --- | --- | | `configurations.launch`, `configurations.attach` | Default DAP `arguments`, a packaged `parametersSchema`, and `targetBindings`: `program` ← `target.path` (or ← `target.directory`, the directory containing `target.path`, for an adapter that debugs a package such as Delve), `processId` ← `target.processID`, `cwd` ← `target.workingDirectory`, plus bounded `args` ← `target.arguments` and `env` ← `target.environment`; only `attach` may bind `connection`. A configuration for an undeclared request is refused | +| `targetBindings.adapterArguments` | Up to 8 DAP arguments only this adapter defines, as `{"": ""}` with the fact `target.path`, `target.directory` or `target.workingDirectory`. A path is dotted like a `connection` destination, up to 4 names, each a letter or `_` followed by up to 63 letters, digits, `_` or `-`, and objects on the way are created. Delve, for example, builds the program in `dlvCwd` and `go build` reads the current directory from `PWD`, so a Go plugin binds `{"dlvCwd": "target.directory", "env.PWD": "target.directory"}`. `env.` adds one variable to the environment; any other path may not start at `program`, `processId`, `cwd`, `args` or `env` itself (they have their own bindings) or at `noDebug` or a `__` name (they belong to the host). Two paths may not overlap, nor a path and a `connection` destination, and a path may not land on or under a value already in `arguments`. It is filled only when nothing holds it, so a variable the target's environment sets stays; a target without the fact is refused with `debug.target.invalid` | | `configurations.launch.executable` | For a target that is a source file the adapter cannot debug directly (C, C++, Swift): `setting` names a `file` setting of the plugin, and up to 8 `candidates[]` (starting with `${workspaceFolder}/` or `${fileDirectory}/`, no `..`) are the paths the host looks for when the user chose nothing. Declare it together with `targetBindings.program: "target.executable"`. The path the user chose in the setting always wins: if it is not a runnable file that is an error, and the candidates are not tried instead | | `capabilities.disabled` | Standard DAP `supports*` names or `exceptionBreakpointFilters` the host treats as absent | | `console.commandPrefix` | Text of 1–8 characters without spaces (a backtick for lldb-dap) that the adapter's console reads as "what follows is a debugger command"; the host puts it before the typed line only when asking for completions and moves the adapter's answer back, so the user never sees it | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 04971b4f..4abf621f 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -134,6 +134,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | | --- | --- | --- | --- | --- | +| [#55](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/55) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-30 | `debugAdapters` 0 内的补充 | `targetBindings` 新增 `adapterArguments`:最多 8 个只有这个适配器才有的 DAP 参数,`{"<参数路径>": "<事实>"}`,路径和 `connection` 的目标一样用点分隔、最多 4 段,事实只能是 `target.path`、`target.directory` 或 `target.workingDirectory`,和其他绑定一样只在没有值时填入。`env.<变量名>` 往环境里加一个变量,`arguments` 和 `env` 绑定给的变量都保留。例如 Delve 在 `dlvCwd` 里编译程序,不在宿主给它的工作目录(工作区根目录)里编译,`go build` 又从 `PWD` 读当前目录;Go 插件绑定 `dlvCwd` 和 `env.PWD` ← `target.directory` 后,工作区根目录没有 `go.mod`、一个工作区放了多个模块、路径经过符号链接时都能调试。路径不能从 `program`、`processId`、`cwd`、`args`、`env` 本身、`noDebug`、`__` 开头的名字开始,路径之间、路径和 `connection` 的目标之间不能重叠,也不能落在 `arguments` 已有的值上或它的下面,违反时以 `plugin.manifest.invalid`(字段 `targetBindings.adapterArguments[.<参数路径>]`)拒绝;目标缺少事实时以 `debug.target.invalid`(字段 `target.path` 或 `target.workingDirectory`)拒绝。只是可选字段,不需要新能力版本。 | | [#53](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/53) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-23 | **`commandInstallers` 0** | 新能力 `commandInstallers` 和权限 `commands.install`:清单顶层 `commandInstallers[]` 声明怎样用插件已依赖的工具(`requiresTools`)安装 `systemCommand` 启动缺的裸命令,例如用 `go install` 装 `dlv`。每个安装声明 `commands`、`tool`、`minimumVersion?`、字面量 `arguments`、`mayUseNetwork`、`timeoutSeconds?`(1–3600,默认 600)和至少一个目标:`managed` 装进宿主为插件管理的目录,参数或环境变量必须用唯一的模板变量 `${installDirectory}`,`commandDirectory` 指命令所在的子目录;`toolDefault` 装到工具默认位置,`directory` 最多 4 个探针,按顺序运行同一工具,从输出读目录(`pathList`、`append`)。新增宿主命令 `plugins.commandInstallers.requirements`、`plan`、`defaultDirectory` 和错误码 `plugin.commandInstaller.unknown`、`targetUndeclared`、`directoryInvalid`、`probeOutputsInvalid`(Core),以及宿主报告的 `plugin.command.missing`、`plugin.commandInstaller.failed`、`timedOut`、`commandsMissing`。安装声明进入安装审查(`kind: "commandInstaller"`)。宿主只在用户确认命令行、网络和目标后安装,每次安装用 `diagnostics.recordPluginOperation` 记一条 `commandInstaller/install`(命令执行生命周期,安装后命令仍缺记 `decode`)。 | | [#52](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/52) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-23 | `toolDefinitions` 0 内的补充 | 工具定义的版本探针 `version.arguments` 第一个参数可以是子命令(如 Go 的 `go version` 写 `["version"]`),之后的参数仍然只能是选项,第一个之后出现裸词以 `plugin.manifest.invalid`(字段 `version.arguments`)拒绝;清单 schema 改用 `prefixItems` 并补上 `uniqueItems`。不需要新能力版本。 | | [#47](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/47) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-30 | `debugAdapters` 0 内的补充 | `targetBindings.program` 新增来源 `target.directory`:`target.path` 所在的目录,供 Delve 这类按包构建再调试的适配器使用;路径没有所在目录时以 `debug.target.invalid`(字段 `target.path`)拒绝。新增宿主命令 `debug.adapters.readAnnouncement`,宿主把 `tcpAnnounced` 适配器的输出逐行交给它,第一行含 `prefix` 的输出是公告,前缀之后是 `port`(连 `127.0.0.1`)或带回环主机的 `host:port`,返回 `none`、`announced` 或 `invalid`(`malformed`、`notLoopback`);契约写明宿主怎样读公告、10 秒内没有公告就启动失败。清单格式只多了一个枚举值,不需要新能力版本。 |