Runnig tests somehow

This commit is contained in:
Aleksey Kladov 2018-08-24 13:41:25 +03:00
parent 89e56c364f
commit 6cade3f6d8
10 changed files with 149 additions and 32 deletions

View file

@ -10,6 +10,9 @@
"request": "launch", "request": "launch",
"runtimeExecutable": "${execPath}", "runtimeExecutable": "${execPath}",
"args": ["--extensionDevelopmentPath='./'"], "args": ["--extensionDevelopmentPath='./'"],
"env": {
"RUST_LOG": "m=trace"
},
"stopOnEntry": false, "stopOnEntry": false,
"sourceMaps": true, "sourceMaps": true,
"outFiles": [ "./out/src/**/*.js" ], "outFiles": [ "./out/src/**/*.js" ],

View file

@ -21,7 +21,7 @@
"showOutput": "silent", "showOutput": "silent",
// we run the custom script "compile" as defined in package.json // we run the custom script "compile" as defined in package.json
"args": ["run", "compile", "--loglevel", "silent"], "args": ["run", "compile",],
// The tsc compiler is started in watching mode // The tsc compiler is started in watching mode
"isBackground": true, "isBackground": true,

View file

@ -28,6 +28,28 @@
"onLanguage:rust" "onLanguage:rust"
], ],
"contributes": { "contributes": {
"taskDefinitions": [
{
"type": "cargo",
"required": [
"command"
],
"properties": {
"label": {
"type": "string"
},
"command": {
"type": "string"
},
"args": {
"type": "array"
},
"env": {
"type": "object"
}
}
}
],
"commands": [ "commands": [
{ {
"command": "libsyntax-rust.syntaxTree", "command": "libsyntax-rust.syntaxTree",
@ -48,6 +70,10 @@
{ {
"command": "libsyntax-rust.joinLines", "command": "libsyntax-rust.joinLines",
"title": "Rust Join Lines" "title": "Rust Join Lines"
},
{
"command": "libsyntax-rust.run",
"title": "Rust Run"
} }
], ],
"keybindings": [ "keybindings": [

View file

@ -81,6 +81,11 @@ export function activate(context: vscode.ExtensionContext) {
let e = await vscode.window.showTextDocument(doc) let e = await vscode.window.showTextDocument(doc)
e.revealRange(range, vscode.TextEditorRevealType.InCenter) e.revealRange(range, vscode.TextEditorRevealType.InCenter)
}) })
console.log("ping")
registerCommand('libsyntax-rust.run', async (cmd: ProcessSpec) => {
let task = createTask(cmd)
await vscode.tasks.executeTask(task)
})
dispose(vscode.workspace.registerTextDocumentContentProvider( dispose(vscode.workspace.registerTextDocumentContentProvider(
'libsyntax-rust', 'libsyntax-rust',
@ -265,3 +270,40 @@ interface Decoration {
range: lc.Range, range: lc.Range,
tag: string, tag: string,
} }
interface ProcessSpec {
bin: string;
args: string[];
env: { [key: string]: string };
}
interface CargoTaskDefinition extends vscode.TaskDefinition {
type: 'cargo';
label: string;
command: string;
args: Array<string>;
env?: { [key: string]: string };
}
function createTask(spec: ProcessSpec): vscode.Task {
const TASK_SOURCE = 'Rust';
let definition: CargoTaskDefinition = {
type: 'cargo',
label: 'cargo',
command: spec.bin,
args: spec.args,
env: spec.env
}
let execCmd = `${definition.command} ${definition.args.join(' ')}`;
let execOption: vscode.ShellExecutionOptions = {
cwd: '.',
env: definition.env,
};
let exec = new vscode.ShellExecution(execCmd, execOption);
let f = vscode.workspace.workspaceFolders[0]
let t = new vscode.Task(definition, f, definition.label, TASK_SOURCE, exec, ['$rustc']);
return t;
}

View file

@ -7,6 +7,5 @@
"sourceMap": true, "sourceMap": true,
"rootDir": "." "rootDir": "."
}, },
"include": [ "src" ], "include": [ "src/*.ts" ],
"exclude": [ "node_modules" ]
} }

View file

@ -5,6 +5,7 @@ use libsyntax2::{
walk::preorder, walk::preorder,
find_covering_node, find_covering_node,
}, },
text_utils::intersect,
SyntaxKind::*, SyntaxKind::*,
}; };
@ -53,16 +54,6 @@ pub fn join_lines(file: &ast::ParsedFile, range: TextRange) -> ActionResult {
} }
} }
fn intersect(r1: TextRange, r2: TextRange) -> Option<TextRange> {
let start = r1.start().max(r2.start());
let end = r1.end().min(r2.end());
if start <= end {
Some(TextRange::from_to(start, end))
} else {
None
}
}
fn remove_newline( fn remove_newline(
edit: &mut EditBuilder, edit: &mut EditBuilder,
node: SyntaxNodeRef, node: SyntaxNodeRef,

View file

@ -1,7 +1,10 @@
pub mod walk; pub mod walk;
pub mod visit; pub mod visit;
use {SyntaxNodeRef, TextUnit, TextRange}; use {
SyntaxNodeRef, TextUnit, TextRange,
text_utils::{contains_offset_nonstrict, is_subrange},
};
pub fn find_leaf_at_offset(node: SyntaxNodeRef, offset: TextUnit) -> LeafAtOffset { pub fn find_leaf_at_offset(node: SyntaxNodeRef, offset: TextUnit) -> LeafAtOffset {
let range = node.range(); let range = node.range();
@ -116,14 +119,6 @@ fn common_ancestor<'a>(n1: SyntaxNodeRef<'a>, n2: SyntaxNodeRef<'a>) -> SyntaxNo
panic!("Can't find common ancestor of {:?} and {:?}", n1, n2) panic!("Can't find common ancestor of {:?} and {:?}", n1, n2)
} }
fn contains_offset_nonstrict(range: TextRange, offset: TextUnit) -> bool {
range.start() <= offset && offset <= range.end()
}
fn is_subrange(range: TextRange, subrange: TextRange) -> bool {
range.start() <= subrange.start() && subrange.end() <= range.end()
}
fn generate<T>(seed: Option<T>, step: impl Fn(&T) -> Option<T>) -> impl Iterator<Item=T> { fn generate<T>(seed: Option<T>, step: impl Fn(&T) -> Option<T>) -> impl Iterator<Item=T> {
::itertools::unfold(seed, move |slot| { ::itertools::unfold(seed, move |slot| {
slot.take().map(|curr| { slot.take().map(|curr| {

View file

@ -39,6 +39,7 @@ mod syntax_kinds;
mod yellow; mod yellow;
/// Utilities for simple uses of the parser. /// Utilities for simple uses of the parser.
pub mod utils; pub mod utils;
pub mod text_utils;
pub use { pub use {
text_unit::{TextRange, TextUnit}, text_unit::{TextRange, TextUnit},

View file

@ -0,0 +1,19 @@
use {TextRange, TextUnit};
pub fn contains_offset_nonstrict(range: TextRange, offset: TextUnit) -> bool {
range.start() <= offset && offset <= range.end()
}
pub fn is_subrange(range: TextRange, subrange: TextRange) -> bool {
range.start() <= subrange.start() && subrange.end() <= range.end()
}
pub fn intersect(r1: TextRange, r2: TextRange) -> Option<TextRange> {
let start = r1.start().max(r2.start());
let end = r1.end().min(r2.end());
if start <= end {
Some(TextRange::from_to(start, end))
} else {
None
}
}

View file

@ -5,10 +5,13 @@ use languageserver_types::{
Command, TextDocumentIdentifier, WorkspaceEdit, Command, TextDocumentIdentifier, WorkspaceEdit,
SymbolInformation, Position, Location, TextEdit, SymbolInformation, Position, Location, TextEdit,
}; };
use serde_json::{to_value, from_value};
use libanalysis::{Query}; use libanalysis::{Query};
use libeditor; use libeditor;
use libsyntax2::TextUnit; use libsyntax2::{
use serde_json::{to_value, from_value}; TextUnit,
text_utils::contains_offset_nonstrict,
};
use ::{ use ::{
req::{self, Decoration}, Result, req::{self, Decoration}, Result,
@ -117,7 +120,7 @@ pub fn handle_code_action(
let file = world.analysis().file_syntax(file_id)?; let file = world.analysis().file_syntax(file_id)?;
let line_index = world.analysis().file_line_index(file_id)?; let line_index = world.analysis().file_line_index(file_id)?;
let offset = params.range.conv_with(&line_index).start(); let offset = params.range.conv_with(&line_index).start();
let mut ret = Vec::new(); let mut res = Vec::new();
let actions = &[ let actions = &[
(ActionId::FlipComma, libeditor::flip_comma(&file, offset).is_some()), (ActionId::FlipComma, libeditor::flip_comma(&file, offset).is_some()),
@ -128,10 +131,52 @@ pub fn handle_code_action(
for (id, edit) in actions { for (id, edit) in actions {
if *edit { if *edit {
let cmd = apply_code_action_cmd(*id, params.text_document.clone(), offset); let cmd = apply_code_action_cmd(*id, params.text_document.clone(), offset);
ret.push(cmd); res.push(cmd);
} }
} }
return Ok(Some(ret)); for runnable in libeditor::runnables(&file) {
if !contains_offset_nonstrict(runnable.range, offset) {
continue;
}
#[derive(Serialize)]
struct ProcessSpec {
bin: String,
args: Vec<String>,
env: HashMap<String, String>,
}
let spec = ProcessSpec {
bin: "cargo".to_string(),
args: match runnable.kind {
libeditor::RunnableKind::Test { name } => {
vec![
"test".to_string(),
"--".to_string(),
name,
"--nocapture".to_string(),
]
}
libeditor::RunnableKind::Bin => vec!["run".to_string()]
},
env: {
let mut m = HashMap::new();
m.insert(
"RUST_BACKTRACE".to_string(),
"short".to_string(),
);
m
}
};
let cmd = Command {
title: "Run ...".to_string(),
command: "libsyntax-rust.run".to_string(),
arguments: Some(vec![to_value(spec).unwrap()]),
};
res.push(cmd);
}
return Ok(Some(res));
} }
pub fn handle_workspace_symbol( pub fn handle_workspace_symbol(
@ -257,11 +302,7 @@ struct ActionRequest {
} }
fn apply_code_action_cmd(id: ActionId, doc: TextDocumentIdentifier, offset: TextUnit) -> Command { fn apply_code_action_cmd(id: ActionId, doc: TextDocumentIdentifier, offset: TextUnit) -> Command {
let action_request = ActionRequest { let action_request = ActionRequest { id, text_document: doc, offset };
id,
text_document: doc,
offset,
};
Command { Command {
title: id.title().to_string(), title: id.title().to_string(),
command: "apply_code_action".to_string(), command: "apply_code_action".to_string(),