Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

First prototype of evaluation #1672

Merged
merged 2 commits into from
Oct 12, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
23 changes: 23 additions & 0 deletions lsp/nls/src/actions.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use lsp_server::{RequestId, Response, ResponseError};
use lsp_types::{CodeActionOrCommand, CodeActionParams};

use crate::{cache::CacheExt, server::Server};

pub fn handle_code_action(
params: CodeActionParams,
req: RequestId,
server: &mut Server,
) -> Result<(), ResponseError> {
let mut actions = Vec::new();

if server.cache.file_id(&params.text_document.uri)?.is_some() {
actions.push(CodeActionOrCommand::Command(lsp_types::Command {
title: "evaluate term".to_owned(),
command: "eval".to_owned(),
arguments: Some(vec![serde_json::to_value(&params.text_document).unwrap()]),
}));
}

server.reply(Response::new_ok(req, Some(actions)));
Ok(())
}
17 changes: 11 additions & 6 deletions lsp/nls/src/cache.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use codespan::{ByteIndex, FileId};
use lsp_types::TextDocumentPositionParams;
use lsp_types::{TextDocumentPositionParams, Url};
use nickel_lang_core::term::{RichTerm, Term, Traverse};
use nickel_lang_core::{
cache::{Cache, CacheError, CacheOp, EntryState, SourcePath, TermEntry},
Expand All @@ -21,6 +21,8 @@ pub trait CacheExt {

fn position(&self, lsp_pos: &TextDocumentPositionParams)
-> Result<RawPos, crate::error::Error>;

fn file_id(&self, uri: &Url) -> Result<Option<FileId>, crate::error::Error>;
}

impl CacheExt for Cache {
Expand Down Expand Up @@ -106,18 +108,21 @@ impl CacheExt for Cache {
}
}

fn file_id(&self, uri: &Url) -> Result<Option<FileId>, crate::error::Error> {
let path = uri
.to_file_path()
.map_err(|_| crate::error::Error::FileNotFound(uri.clone()))?;
Ok(self.id_of(&SourcePath::Path(path)))
}

fn position(
&self,
lsp_pos: &TextDocumentPositionParams,
) -> Result<RawPos, crate::error::Error> {
let uri = &lsp_pos.text_document.uri;
let path = uri
.to_file_path()
.map_err(|_| crate::error::Error::FileNotFound(uri.clone()))?;
let file_id = self
.id_of(&SourcePath::Path(path))
.file_id(uri)?
.ok_or_else(|| crate::error::Error::FileNotFound(uri.clone()))?;

let pos = lsp_pos.position;
let idx =
codespan_lsp::position_to_byte_index(self.files(), file_id, &pos).map_err(|_| {
Expand Down
39 changes: 39 additions & 0 deletions lsp/nls/src/command.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use lsp_server::{RequestId, Response, ResponseError};
use lsp_types::{ExecuteCommandParams, TextDocumentIdentifier, Url};
use nickel_lang_core::{
error::IntoDiagnostics,
eval::{cache::CacheImpl, VirtualMachine},
};

use crate::{cache::CacheExt, error::Error, server::Server};

pub fn handle_command(
params: ExecuteCommandParams,
req: RequestId,
server: &mut Server,
) -> Result<(), ResponseError> {
match params.command.as_str() {
"eval" => {
server.reply(Response::new_ok(req, None::<()>));

let doc: TextDocumentIdentifier =
serde_json::from_value(params.arguments[0].clone()).unwrap();
eval(server, &doc.uri)?;
Ok(())
}
_ => Err(Error::CommandNotFound(params.command).into()),
}
}

fn eval(server: &mut Server, uri: &Url) -> Result<(), Error> {
if let Some(file_id) = server.cache.file_id(uri)? {
// TODO: avoid cloning the cache. Maybe we can have a VM with a &mut ImportResolver?
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, this would be annoying because we'd have to add a lifetime parameter to VirtualMachine. I wonder if you can't just implement ImportResolver for &'a mut R when R: ImportResolver, thus passing a mutable reference instead? Or just wrap it as a dedicated type ImportResolverRef<'a, R: ImportResolver>(&'a mut ImportResolver) and implement the trait. After all VirtualMachine is generic over the resolver.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, that's a good point. I'll give it a quick try, and if it works I'll add it to this PR

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Implementing ImportResolver for &'a mut R worked nicely, but it didn't solve the issue because prepare_eval is only defined when the import resolver parameter is ImportCache. I'll just leave the TODO for now...

let mut vm = VirtualMachine::<_, CacheImpl>::new(server.cache.clone(), std::io::stderr());
let rt = vm.prepare_eval(file_id)?;
if let Err(e) = vm.eval_full(rt) {
let diags = e.into_diagnostics(server.cache.files_mut(), None);
server.issue_diagnostics(file_id, diags);
}
}
Ok(())
}
16 changes: 16 additions & 0 deletions lsp/nls/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,22 @@ pub enum Error {
#[error("Method not supported")]
MethodNotFound,

#[error("Command not supported: {0}")]
CommandNotFound(String),

#[error("formatting failed for file {file}: {details}")]
FormattingFailed { details: String, file: Url },

// Mostly we convert nickel errors into nice diagnostics, but there are a few
// places where we just don't expect them to happen, and then they go here.
#[error("unhandled nickel error: {0}")]
Nickel(String),
}

impl From<nickel_lang_core::error::Error> for Error {
fn from(e: nickel_lang_core::error::Error) -> Self {
Error::Nickel(format!("{:?}", e))
}
}

impl From<Error> for ResponseError {
Expand All @@ -30,8 +44,10 @@ impl From<Error> for ResponseError {
Error::InvalidPosition { .. } => ErrorCode::InvalidParams,
Error::SchemeNotSupported(_) => ErrorCode::InvalidParams,
Error::InvalidPath(_) => ErrorCode::InvalidParams,
Error::CommandNotFound(_) => ErrorCode::InvalidParams,
Error::MethodNotFound => ErrorCode::MethodNotFound,
Error::FormattingFailed { .. } => ErrorCode::InternalError,
Error::Nickel(_) => ErrorCode::InternalError,
};
ResponseError {
code: code as i32,
Expand Down
2 changes: 2 additions & 0 deletions lsp/nls/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ use anyhow::Result;
use log::debug;
use lsp_server::Connection;

mod actions;
mod analysis;
mod cache;
mod command;
mod diagnostic;
mod error;
mod field_walker;
Expand Down
30 changes: 25 additions & 5 deletions lsp/nls/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@ use lsp_types::{
notification::Notification as _,
notification::{DidChangeTextDocument, DidOpenTextDocument},
request::{Request as RequestTrait, *},
CompletionOptions, CompletionParams, DidChangeTextDocumentParams, DidOpenTextDocumentParams,
DocumentFormattingParams, DocumentSymbolParams, GotoDefinitionParams, HoverOptions,
HoverParams, HoverProviderCapability, OneOf, PublishDiagnosticsParams, ReferenceParams,
ServerCapabilities, TextDocumentSyncCapability, TextDocumentSyncKind, TextDocumentSyncOptions,
Url, WorkDoneProgressOptions,
CodeActionParams, CompletionOptions, CompletionParams, DidChangeTextDocumentParams,
DidOpenTextDocumentParams, DocumentFormattingParams, DocumentSymbolParams,
ExecuteCommandParams, GotoDefinitionParams, HoverOptions, HoverParams, HoverProviderCapability,
OneOf, PublishDiagnosticsParams, ReferenceParams, ServerCapabilities,
TextDocumentSyncCapability, TextDocumentSyncKind, TextDocumentSyncOptions, Url,
WorkDoneProgressOptions,
};

use nickel_lang_core::{
Expand All @@ -27,8 +28,10 @@ use nickel_lang_core::{
use nickel_lang_core::{stdlib, typecheck::Context};

use crate::{
actions,
analysis::{Analysis, AnalysisRegistry},
cache::CacheExt,
command,
diagnostic::DiagnosticCompat,
field_walker::DefWithPath,
requests::{completion, formatting, goto, hover, symbols},
Expand Down Expand Up @@ -72,6 +75,11 @@ impl Server {
}),
document_symbol_provider: Some(OneOf::Left(true)),
document_formatting_provider: Some(OneOf::Left(true)),
code_action_provider: Some(lsp_types::CodeActionProviderCapability::Simple(true)),
execute_command_provider: Some(lsp_types::ExecuteCommandOptions {
commands: vec!["eval".to_owned()],
..Default::default()
}),
..ServerCapabilities::default()
}
}
Expand Down Expand Up @@ -250,6 +258,18 @@ impl Server {
formatting::handle_format_document(params, req.id.clone(), self)
}

CodeActionRequest::METHOD => {
debug!("code action");
let params: CodeActionParams = serde_json::from_value(req.params).unwrap();
actions::handle_code_action(params, req.id.clone(), self)
}

ExecuteCommand::METHOD => {
debug!("command");
let params: ExecuteCommandParams = serde_json::from_value(req.params).unwrap();
command::handle_command(params, req.id.clone(), self)
}

_ => Ok(()),
};

Expand Down
2 changes: 0 additions & 2 deletions lsp/nls/test2.ncl

This file was deleted.