Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.<variable>` 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`.

Expand Down
131 changes: 131 additions & 0 deletions rust/crates/core/src/tests/declarative_plugins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
19 changes: 18 additions & 1 deletion rust/crates/debug/src/adapters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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";

Expand Down
14 changes: 12 additions & 2 deletions rust/crates/debug/src/adapters/declaration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,9 @@ pub struct DebugExecutable {
pub(crate) candidates: Vec<String>,
}

/// 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 {
Expand All @@ -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<DebugConnectionBinding>,
/// 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<BTreeMap<String, String>>,
}

/// Where each fact of a remote target lands in the adapter's attach
Expand Down
12 changes: 12 additions & 0 deletions rust/crates/debug/src/adapters/plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
80 changes: 59 additions & 21 deletions rust/crates/debug/src/adapters/start.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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<String>| 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(
Expand Down Expand Up @@ -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<String, Value>, 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<String, Value>, 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<String, Value>,
path: &'p str,
) -> Validation<(&'a mut Map<String, Value>, &'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.
Expand Down
Loading
Loading