Skip to content
Open
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
280 changes: 240 additions & 40 deletions Cargo.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ authors = ["Posit Software, PBC"]

[workspace.dependencies]
biome_line_index = { git = "https://github.com/biomejs/biome", rev = "c13fc60726883781e4530a4437724273b560c8e0" }
biome_rowan = { git = "https://github.com/biomejs/biome", rev = "c13fc60726883781e4530a4437724273b560c8e0" }
aether_lsp_utils = { git = "https://github.com/posit-dev/air", rev = "f959e32eee91" }
aether_parser = { git = "https://github.com/posit-dev/air", package = "air_r_parser", rev = "f959e32eee91" }
aether_syntax = { git = "https://github.com/posit-dev/air", package = "air_r_syntax", rev = "f959e32eee91" }
Expand Down
1 change: 1 addition & 0 deletions crates/amalthea/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ serde_with = "3.0.0"
serde_repr = "0.1.17"
tracing = "0.1.40"
assert_matches = "1.5.0"
url = "2.5.7"

[dev-dependencies]
env_logger = "0.10.0"
42 changes: 40 additions & 2 deletions crates/amalthea/src/fixtures/dummy_frontend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ use crate::session::Session;
use crate::socket::socket::Socket;
use crate::wire::execute_input::ExecuteInput;
use crate::wire::execute_request::ExecuteRequest;
use crate::wire::execute_request::ExecuteRequestPositron;
use crate::wire::execute_request::JupyterPositronLocation;
use crate::wire::handshake_reply::HandshakeReply;
use crate::wire::input_reply::InputReply;
use crate::wire::jupyter_message::JupyterMessage;
Expand Down Expand Up @@ -48,6 +50,7 @@ pub struct DummyFrontend {

pub struct ExecuteRequestOptions {
pub allow_stdin: bool,
pub positron: Option<ExecuteRequestPositron>,
}

impl DummyConnection {
Expand Down Expand Up @@ -233,6 +236,7 @@ impl DummyFrontend {
user_expressions: serde_json::Value::Null,
allow_stdin: options.allow_stdin,
stop_on_error: false,
positron: options.positron,
})
}

Expand Down Expand Up @@ -264,7 +268,38 @@ impl DummyFrontend {
where
F: FnOnce(String),
{
self.send_execute_request(code, ExecuteRequestOptions::default());
self.execute_request_with_options(code, result_check, Default::default())
}

#[track_caller]
pub fn execute_request_with_location<F>(
&self,
code: &str,
result_check: F,
code_location: JupyterPositronLocation,
) -> u32
where
F: FnOnce(String),
{
self.execute_request_with_options(code, result_check, ExecuteRequestOptions {
positron: Some(ExecuteRequestPositron {
code_location: Some(code_location),
}),
..Default::default()
})
}

#[track_caller]
pub fn execute_request_with_options<F>(
&self,
code: &str,
result_check: F,
options: ExecuteRequestOptions,
) -> u32
where
F: FnOnce(String),
{
self.send_execute_request(code, options);
self.recv_iopub_busy();

let input = self.recv_iopub_execute_input();
Expand Down Expand Up @@ -663,6 +698,9 @@ impl DummyFrontend {

impl Default for ExecuteRequestOptions {
fn default() -> Self {
Self { allow_stdin: false }
Self {
allow_stdin: false,
positron: None,
}
}
}
115 changes: 115 additions & 0 deletions crates/amalthea/src/wire/execute_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
*
*/

use anyhow::Context;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;
use url::Url;

use crate::wire::jupyter_message::MessageType;

Expand All @@ -33,6 +35,119 @@ pub struct ExecuteRequest {
/// Whether the kernel should discard the execution queue if evaluating the
/// code results in an error
pub stop_on_error: bool,

/// Posit extension
pub positron: Option<ExecuteRequestPositron>,
}

#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ExecuteRequestPositron {
pub code_location: Option<JupyterPositronLocation>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct JupyterPositronLocation {
pub uri: String,
pub range: JupyterPositronRange,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct JupyterPositronRange {
pub start: JupyterPositronPosition,
pub end: JupyterPositronPosition,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct JupyterPositronPosition {
pub line: u32,
/// Column offset in UTF-8 bytes
pub character: u32,
}

/// Code location with `character` in UTF-8 offset
#[derive(Debug, Clone)]
pub struct CodeLocation {
pub uri: Url,
pub start: Position,
pub end: Position,
}

/// `character` in UTF-8 offset
#[derive(Debug, Clone)]
pub struct Position {
pub line: u32,
pub character: u32,
}

impl ExecuteRequest {
pub fn code_location(&self) -> anyhow::Result<Option<CodeLocation>> {
let Some(positron) = &self.positron else {
return Ok(None);
};
let Some(location) = &positron.code_location else {
return Ok(None);
};

let uri = Url::parse(&location.uri).context("Failed to parse URI from code location")?;
let range = &location.range;

// Validate that range is not inverted
if range.end.line < range.start.line ||
(range.end.line == range.start.line && range.end.character < range.start.character)
{
return Err(anyhow::anyhow!(
"Invalid range: end ({}, {}) is before start ({}, {})",
range.end.line,
range.end.character,
range.start.line,
range.start.character
));
}

// Validate that the span dimensions match the code extents
let span_lines = (range.end.line - range.start.line) as usize;
let code_newlines = self.code.matches('\n').count();

if code_newlines != span_lines {
return Err(anyhow::anyhow!(
"Line count mismatch: location spans {span_lines} lines, but code has {code_newlines} newlines"
));
}

// Validate last line byte length
let last_line = if self.code.ends_with('\n') {
""
} else {
self.code.lines().last().unwrap_or("")
};
let last_line = last_line.strip_suffix('\r').unwrap_or(last_line);

let expected_bytes = if span_lines == 0 {
range.end.character - range.start.character
} else {
range.end.character
};

if last_line.len() as u32 != expected_bytes {
return Err(anyhow::anyhow!(
"Expected last line to have {expected_bytes} bytes, got {}",
last_line.len()
));
}

Ok(Some(CodeLocation {
uri,
start: Position {
line: range.start.line,
character: range.start.character,
},
end: Position {
line: range.end.line,
character: range.end.character,
},
}))
}
}

impl MessageType for ExecuteRequest {
Expand Down
1 change: 1 addition & 0 deletions crates/ark/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ anyhow = "1.0.80"
async-trait = "0.1.66"
base64 = "0.21.0"
biome_line_index.workspace = true
biome_rowan.workspace = true
bus = "2.3.0"
cfg-if = "1.0.0"
crossbeam = { version = "0.8.2", features = ["crossbeam-channel"] }
Expand Down
142 changes: 142 additions & 0 deletions crates/ark/src/console_annotate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
//
// console_annotate.rs
//
// Copyright (C) 2025 Posit Software, PBC. All rights reserved.
//

use amalthea::wire::execute_request::CodeLocation;
use biome_rowan::AstNode;

pub(crate) fn annotate_input(code: &str, location: CodeLocation) -> String {
let node = aether_parser::parse(code, Default::default()).tree();
let Some(first_token) = node.syntax().first_token() else {
return code.into();
};

let line_directive = format!(
"#line {line} \"{uri}\"",
line = location.start.line + 1,
uri = location.uri
);

// Leading whitespace to ensure that R starts parsing expressions from
// the expected `character` offset.
let leading_padding = " ".repeat(location.start.character as usize);

// Collect existing leading trivia as (kind, text) tuples
let existing_trivia: Vec<_> = first_token
.leading_trivia()
.pieces()
.map(|piece| (piece.kind(), piece.text().to_string()))
.collect();

// Create new trivia with line directive prepended
let new_trivia: Vec<_> = vec![
(
biome_rowan::TriviaPieceKind::SingleLineComment,
line_directive.to_string(),
),
(biome_rowan::TriviaPieceKind::Newline, "\n".to_string()),
(
biome_rowan::TriviaPieceKind::Whitespace,
leading_padding.to_string(),
),
]
.into_iter()
.chain(existing_trivia.into_iter())
.collect();

let new_first_token =
first_token.with_leading_trivia(new_trivia.iter().map(|(k, t)| (*k, t.as_str())));

let Some(new_node) = node
.syntax()
.clone()
.replace_child(first_token.into(), new_first_token.into())
else {
return code.into();
};

new_node.to_string()
}

#[cfg(test)]
mod tests {
use amalthea::wire::execute_request::CodeLocation;
use amalthea::wire::execute_request::Position;
use url::Url;

use super::*;

fn make_location(line: u32, character: u32) -> CodeLocation {
CodeLocation {
uri: Url::parse("file:///test.R").unwrap(),
start: Position { line, character },
end: Position { line, character },
}
}

#[test]
fn test_annotate_input_basic() {
let code = "x <- 1\ny <- 2";
let location = make_location(0, 0);
let result = annotate_input(code, location);
insta::assert_snapshot!(result);
}

#[test]
fn test_annotate_input_shifted_line() {
let code = "x <- 1\ny <- 2";
let location = make_location(10, 0);
let result = annotate_input(code, location);
insta::assert_snapshot!(result);
}

#[test]
fn test_annotate_input_shifted_character() {
let code = "x <- 1\ny <- 2";
let location = make_location(0, 5);
let result = annotate_input(code, location);
insta::assert_snapshot!(result);
}

#[test]
fn test_annotate_input_shifted_line_and_character() {
let code = "x <- 1\ny <- 2";
let location = make_location(10, 5);
let result = annotate_input(code, location);
insta::assert_snapshot!(result);
}

#[test]
fn test_annotate_input_with_existing_whitespace() {
let code = " x <- 1\n y <- 2";
let location = make_location(0, 0);
let result = annotate_input(code, location);
insta::assert_snapshot!(result);
}

#[test]
fn test_annotate_input_with_existing_whitespace_shifted() {
let code = " x <- 1\n y <- 2";
let location = make_location(0, 2);
let result = annotate_input(code, location);
insta::assert_snapshot!(result);
}

#[test]
fn test_annotate_input_with_existing_comment() {
let code = "# comment\nx <- 1";
let location = make_location(0, 0);
let result = annotate_input(code, location);
insta::assert_snapshot!(result);
}

#[test]
fn test_annotate_input_empty_code() {
let code = "";
let location = make_location(0, 0);
let result = annotate_input(code, location);
insta::assert_snapshot!(result);
}
}
File renamed without changes.
2 changes: 1 addition & 1 deletion crates/ark/src/dap/dap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ use harp::object::RObject;
use stdext::result::ResultExt;
use stdext::spawn;

use crate::console_debug::FrameInfo;
use crate::dap::dap_server;
use crate::repl_debug::FrameInfo;
use crate::request::RRequest;
use crate::thread::RThreadSafe;

Expand Down
4 changes: 2 additions & 2 deletions crates/ark/src/dap/dap_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@ use stdext::spawn;

use super::dap::Dap;
use super::dap::DapBackendEvent;
use crate::console_debug::FrameInfo;
use crate::console_debug::FrameSource;
use crate::dap::dap::DapStoppedEvent;
use crate::dap::dap_variables::object_variables;
use crate::dap::dap_variables::RVariable;
use crate::r_task;
use crate::repl_debug::FrameInfo;
use crate::repl_debug::FrameSource;
use crate::request::debug_request_command;
use crate::request::DebugRequest;
use crate::request::RRequest;
Expand Down
Loading
Loading