2021-01-11 12:13:41 -05:00
|
|
|
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
|
2020-09-05 20:34:02 -04:00
|
|
|
|
2021-09-07 10:39:32 -04:00
|
|
|
use crate::ast::transpile;
|
2021-12-08 19:12:14 -05:00
|
|
|
use crate::ast::Diagnostics;
|
2021-06-21 15:13:25 -04:00
|
|
|
use crate::ast::ImportsNotUsedAsValues;
|
2020-10-13 10:23:02 -04:00
|
|
|
use crate::colors;
|
2021-09-24 11:10:42 -04:00
|
|
|
use crate::proc_state::ProcState;
|
2021-09-07 10:39:32 -04:00
|
|
|
use deno_ast::swc::parser::error::SyntaxError;
|
2021-11-25 14:05:12 -05:00
|
|
|
use deno_ast::swc::parser::token::Token;
|
|
|
|
use deno_ast::swc::parser::token::Word;
|
2020-09-14 12:48:57 -04:00
|
|
|
use deno_core::error::AnyError;
|
2021-05-26 11:47:33 -04:00
|
|
|
use deno_core::futures::FutureExt;
|
2021-07-06 23:48:01 -04:00
|
|
|
use deno_core::parking_lot::Mutex;
|
2020-10-01 19:14:55 -04:00
|
|
|
use deno_core::serde_json::json;
|
2020-10-06 07:50:48 -04:00
|
|
|
use deno_core::serde_json::Value;
|
2021-05-26 15:07:12 -04:00
|
|
|
use deno_core::LocalInspectorSession;
|
2020-12-13 13:45:53 -05:00
|
|
|
use deno_runtime::worker::MainWorker;
|
2020-10-19 15:25:21 -04:00
|
|
|
use rustyline::completion::Completer;
|
2020-10-01 19:14:55 -04:00
|
|
|
use rustyline::error::ReadlineError;
|
2020-10-13 10:23:02 -04:00
|
|
|
use rustyline::highlight::Highlighter;
|
2020-10-01 19:14:55 -04:00
|
|
|
use rustyline::validate::ValidationContext;
|
|
|
|
use rustyline::validate::ValidationResult;
|
|
|
|
use rustyline::validate::Validator;
|
2021-06-21 20:07:26 -04:00
|
|
|
use rustyline::CompletionType;
|
|
|
|
use rustyline::Config;
|
2020-10-19 15:25:21 -04:00
|
|
|
use rustyline::Context;
|
2020-05-07 12:01:27 -04:00
|
|
|
use rustyline::Editor;
|
2020-10-19 15:25:21 -04:00
|
|
|
use rustyline_derive::{Helper, Hinter};
|
2020-10-13 10:23:02 -04:00
|
|
|
use std::borrow::Cow;
|
2021-06-09 19:07:50 -04:00
|
|
|
use std::path::PathBuf;
|
2020-10-01 19:14:55 -04:00
|
|
|
use std::sync::Arc;
|
2021-11-25 14:05:12 -05:00
|
|
|
|
|
|
|
mod channel;
|
|
|
|
|
|
|
|
use channel::rustyline_channel;
|
|
|
|
use channel::RustylineSyncMessageHandler;
|
|
|
|
use channel::RustylineSyncMessageSender;
|
2018-11-05 12:55:59 -05:00
|
|
|
|
2020-10-19 15:25:21 -04:00
|
|
|
// Provides helpers to the editor like validation for multi-line edits, completion candidates for
|
|
|
|
// tab completion.
|
|
|
|
#[derive(Helper, Hinter)]
|
2021-06-09 19:07:50 -04:00
|
|
|
struct EditorHelper {
|
2020-10-19 15:25:21 -04:00
|
|
|
context_id: u64,
|
2021-11-25 14:05:12 -05:00
|
|
|
sync_sender: RustylineSyncMessageSender,
|
2018-11-05 12:55:59 -05:00
|
|
|
}
|
|
|
|
|
2021-06-09 19:07:50 -04:00
|
|
|
impl EditorHelper {
|
2021-07-08 12:58:18 -04:00
|
|
|
pub fn get_global_lexical_scope_names(&self) -> Vec<String> {
|
2021-06-15 09:31:36 -04:00
|
|
|
let evaluate_response = self
|
2021-11-25 14:05:12 -05:00
|
|
|
.sync_sender
|
2021-06-15 09:31:36 -04:00
|
|
|
.post_message(
|
|
|
|
"Runtime.globalLexicalScopeNames",
|
|
|
|
Some(json!({
|
|
|
|
"executionContextId": self.context_id,
|
|
|
|
})),
|
|
|
|
)
|
|
|
|
.unwrap();
|
2020-10-19 15:25:21 -04:00
|
|
|
|
2021-06-15 09:31:36 -04:00
|
|
|
evaluate_response
|
|
|
|
.get("names")
|
|
|
|
.unwrap()
|
|
|
|
.as_array()
|
|
|
|
.unwrap()
|
|
|
|
.iter()
|
|
|
|
.map(|n| n.as_str().unwrap().to_string())
|
|
|
|
.collect()
|
|
|
|
}
|
2020-10-19 15:25:21 -04:00
|
|
|
|
2021-07-08 12:58:18 -04:00
|
|
|
pub fn get_expression_property_names(&self, expr: &str) -> Vec<String> {
|
|
|
|
// try to get the properties from the expression
|
|
|
|
if let Some(properties) = self.get_object_expr_properties(expr) {
|
|
|
|
return properties;
|
|
|
|
}
|
|
|
|
|
|
|
|
// otherwise fall back to the prototype
|
|
|
|
let expr_type = self.get_expression_type(expr);
|
|
|
|
let object_expr = match expr_type.as_deref() {
|
|
|
|
// possibilities: https://chromedevtools.github.io/devtools-protocol/v8/Runtime/#type-RemoteObject
|
|
|
|
Some("object") => "Object.prototype",
|
|
|
|
Some("function") => "Function.prototype",
|
|
|
|
Some("string") => "String.prototype",
|
|
|
|
Some("boolean") => "Boolean.prototype",
|
|
|
|
Some("bigint") => "BigInt.prototype",
|
|
|
|
Some("number") => "Number.prototype",
|
|
|
|
_ => return Vec::new(), // undefined, symbol, and unhandled
|
|
|
|
};
|
|
|
|
|
|
|
|
self
|
|
|
|
.get_object_expr_properties(object_expr)
|
|
|
|
.unwrap_or_else(Vec::new)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_expression_type(&self, expr: &str) -> Option<String> {
|
|
|
|
self
|
|
|
|
.evaluate_expression(expr)?
|
|
|
|
.get("result")?
|
|
|
|
.get("type")?
|
|
|
|
.as_str()
|
|
|
|
.map(|s| s.to_string())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_object_expr_properties(
|
|
|
|
&self,
|
|
|
|
object_expr: &str,
|
|
|
|
) -> Option<Vec<String>> {
|
|
|
|
let evaluate_result = self.evaluate_expression(object_expr)?;
|
|
|
|
let object_id = evaluate_result.get("result")?.get("objectId")?;
|
|
|
|
|
|
|
|
let get_properties_response = self
|
2021-11-25 14:05:12 -05:00
|
|
|
.sync_sender
|
2021-07-08 12:58:18 -04:00
|
|
|
.post_message(
|
|
|
|
"Runtime.getProperties",
|
|
|
|
Some(json!({
|
|
|
|
"objectId": object_id,
|
|
|
|
})),
|
|
|
|
)
|
|
|
|
.ok()?;
|
|
|
|
|
|
|
|
Some(
|
|
|
|
get_properties_response
|
|
|
|
.get("result")?
|
|
|
|
.as_array()
|
|
|
|
.unwrap()
|
|
|
|
.iter()
|
|
|
|
.map(|r| r.get("name").unwrap().as_str().unwrap().to_string())
|
|
|
|
.collect(),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn evaluate_expression(&self, expr: &str) -> Option<Value> {
|
2020-10-19 15:25:21 -04:00
|
|
|
let evaluate_response = self
|
2021-11-25 14:05:12 -05:00
|
|
|
.sync_sender
|
2020-10-19 15:25:21 -04:00
|
|
|
.post_message(
|
|
|
|
"Runtime.evaluate",
|
|
|
|
Some(json!({
|
|
|
|
"contextId": self.context_id,
|
2021-06-15 09:31:36 -04:00
|
|
|
"expression": expr,
|
2020-10-19 15:25:21 -04:00
|
|
|
"throwOnSideEffect": true,
|
|
|
|
"timeout": 200,
|
|
|
|
})),
|
|
|
|
)
|
2021-07-08 12:58:18 -04:00
|
|
|
.ok()?;
|
2020-10-19 15:25:21 -04:00
|
|
|
|
|
|
|
if evaluate_response.get("exceptionDetails").is_some() {
|
2021-07-08 12:58:18 -04:00
|
|
|
None
|
|
|
|
} else {
|
|
|
|
Some(evaluate_response)
|
2020-10-19 15:25:21 -04:00
|
|
|
}
|
2021-07-08 12:58:18 -04:00
|
|
|
}
|
2021-06-15 09:31:36 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn is_word_boundary(c: char) -> bool {
|
|
|
|
if c == '.' {
|
|
|
|
false
|
|
|
|
} else {
|
|
|
|
char::is_ascii_whitespace(&c) || char::is_ascii_punctuation(&c)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_expr_from_line_at_pos(line: &str, cursor_pos: usize) -> &str {
|
|
|
|
let start = line[..cursor_pos]
|
|
|
|
.rfind(is_word_boundary)
|
|
|
|
.map_or_else(|| 0, |i| i);
|
|
|
|
let end = line[cursor_pos..]
|
|
|
|
.rfind(is_word_boundary)
|
|
|
|
.map_or_else(|| cursor_pos, |i| cursor_pos + i);
|
|
|
|
|
|
|
|
let word = &line[start..end];
|
|
|
|
let word = word.strip_prefix(is_word_boundary).unwrap_or(word);
|
|
|
|
let word = word.strip_suffix(is_word_boundary).unwrap_or(word);
|
|
|
|
|
|
|
|
word
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Completer for EditorHelper {
|
|
|
|
type Candidate = String;
|
|
|
|
|
|
|
|
fn complete(
|
|
|
|
&self,
|
|
|
|
line: &str,
|
|
|
|
pos: usize,
|
|
|
|
_ctx: &Context<'_>,
|
|
|
|
) -> Result<(usize, Vec<String>), ReadlineError> {
|
|
|
|
let expr = get_expr_from_line_at_pos(line, pos);
|
|
|
|
|
|
|
|
// check if the expression is in the form `obj.prop`
|
|
|
|
if let Some(index) = expr.rfind('.') {
|
|
|
|
let sub_expr = &expr[..index];
|
|
|
|
let prop_name = &expr[index + 1..];
|
|
|
|
let candidates = self
|
|
|
|
.get_expression_property_names(sub_expr)
|
|
|
|
.into_iter()
|
|
|
|
.filter(|n| !n.starts_with("Symbol(") && n.starts_with(prop_name))
|
|
|
|
.collect();
|
|
|
|
|
|
|
|
Ok((pos - prop_name.len(), candidates))
|
|
|
|
} else {
|
|
|
|
// combine results of declarations and globalThis properties
|
|
|
|
let mut candidates = self
|
|
|
|
.get_expression_property_names("globalThis")
|
|
|
|
.into_iter()
|
|
|
|
.chain(self.get_global_lexical_scope_names())
|
|
|
|
.filter(|n| n.starts_with(expr))
|
|
|
|
.collect::<Vec<_>>();
|
|
|
|
|
|
|
|
// sort and remove duplicates
|
|
|
|
candidates.sort();
|
|
|
|
candidates.dedup(); // make sure to sort first
|
|
|
|
|
|
|
|
Ok((pos - expr.len(), candidates))
|
|
|
|
}
|
2020-10-19 15:25:21 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-09 19:07:50 -04:00
|
|
|
impl Validator for EditorHelper {
|
2020-10-01 19:14:55 -04:00
|
|
|
fn validate(
|
|
|
|
&self,
|
|
|
|
ctx: &mut ValidationContext,
|
|
|
|
) -> Result<ValidationResult, ReadlineError> {
|
2020-11-27 14:14:54 -05:00
|
|
|
let mut stack: Vec<Token> = Vec::new();
|
|
|
|
let mut in_template = false;
|
|
|
|
|
2021-09-07 10:39:32 -04:00
|
|
|
for item in deno_ast::lex(ctx.input(), deno_ast::MediaType::TypeScript) {
|
|
|
|
if let deno_ast::TokenOrComment::Token(token) = item.inner {
|
2020-11-27 14:14:54 -05:00
|
|
|
match token {
|
|
|
|
Token::BackQuote => in_template = !in_template,
|
|
|
|
Token::LParen
|
|
|
|
| Token::LBracket
|
|
|
|
| Token::LBrace
|
|
|
|
| Token::DollarLBrace => stack.push(token),
|
|
|
|
Token::RParen | Token::RBracket | Token::RBrace => {
|
|
|
|
match (stack.pop(), token) {
|
|
|
|
(Some(Token::LParen), Token::RParen)
|
|
|
|
| (Some(Token::LBracket), Token::RBracket)
|
|
|
|
| (Some(Token::LBrace), Token::RBrace)
|
|
|
|
| (Some(Token::DollarLBrace), Token::RBrace) => {}
|
|
|
|
(Some(left), _) => {
|
|
|
|
return Ok(ValidationResult::Invalid(Some(format!(
|
|
|
|
"Mismatched pairs: {:?} is not properly closed",
|
|
|
|
left
|
|
|
|
))))
|
|
|
|
}
|
|
|
|
(None, _) => {
|
|
|
|
// While technically invalid when unpaired, it should be V8's task to output error instead.
|
|
|
|
// Thus marked as valid with no info.
|
|
|
|
return Ok(ValidationResult::Valid(None));
|
|
|
|
}
|
|
|
|
}
|
2020-10-19 10:54:50 -04:00
|
|
|
}
|
2021-07-19 08:38:13 -04:00
|
|
|
Token::Error(error) => {
|
|
|
|
match error.kind() {
|
|
|
|
// If there is unterminated template, it continues to read input.
|
|
|
|
SyntaxError::UnterminatedTpl => {}
|
|
|
|
_ => {
|
|
|
|
// If it failed parsing, it should be V8's task to output error instead.
|
|
|
|
// Thus marked as valid with no info.
|
|
|
|
return Ok(ValidationResult::Valid(None));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-11-27 14:14:54 -05:00
|
|
|
_ => {}
|
|
|
|
}
|
2020-10-19 10:54:50 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-27 14:14:54 -05:00
|
|
|
if !stack.is_empty() || in_template {
|
2020-10-19 10:54:50 -04:00
|
|
|
return Ok(ValidationResult::Incomplete);
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(ValidationResult::Valid(None))
|
2018-11-05 12:55:59 -05:00
|
|
|
}
|
2020-10-01 19:14:55 -04:00
|
|
|
}
|
2018-11-05 12:55:59 -05:00
|
|
|
|
2021-06-09 19:07:50 -04:00
|
|
|
impl Highlighter for EditorHelper {
|
2020-10-13 10:23:02 -04:00
|
|
|
fn highlight_hint<'h>(&self, hint: &'h str) -> Cow<'h, str> {
|
|
|
|
hint.into()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn highlight_candidate<'c>(
|
|
|
|
&self,
|
|
|
|
candidate: &'c str,
|
2021-08-14 04:19:30 -04:00
|
|
|
completion: rustyline::CompletionType,
|
2020-10-13 10:23:02 -04:00
|
|
|
) -> Cow<'c, str> {
|
2021-08-14 04:19:30 -04:00
|
|
|
if completion == CompletionType::List {
|
|
|
|
candidate.into()
|
|
|
|
} else {
|
|
|
|
self.highlight(candidate, 0)
|
|
|
|
}
|
2020-10-13 10:23:02 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn highlight_char(&self, line: &str, _: usize) -> bool {
|
|
|
|
!line.is_empty()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn highlight<'l>(&self, line: &'l str, _: usize) -> Cow<'l, str> {
|
2020-11-27 14:14:54 -05:00
|
|
|
let mut out_line = String::from(line);
|
|
|
|
|
2021-09-07 10:39:32 -04:00
|
|
|
for item in deno_ast::lex(line, deno_ast::MediaType::TypeScript) {
|
2020-11-27 14:14:54 -05:00
|
|
|
// Adding color adds more bytes to the string,
|
|
|
|
// so an offset is needed to stop spans falling out of sync.
|
|
|
|
let offset = out_line.len() - line.len();
|
2021-09-07 10:39:32 -04:00
|
|
|
let span = std::ops::Range {
|
|
|
|
start: item.span.lo.0 as usize,
|
|
|
|
end: item.span.hi.0 as usize,
|
|
|
|
};
|
2020-11-27 14:14:54 -05:00
|
|
|
|
|
|
|
out_line.replace_range(
|
|
|
|
span.start + offset..span.end + offset,
|
|
|
|
&match item.inner {
|
2021-09-07 10:39:32 -04:00
|
|
|
deno_ast::TokenOrComment::Token(token) => match token {
|
2020-11-27 14:14:54 -05:00
|
|
|
Token::Str { .. } | Token::Template { .. } | Token::BackQuote => {
|
|
|
|
colors::green(&line[span]).to_string()
|
|
|
|
}
|
|
|
|
Token::Regex(_, _) => colors::red(&line[span]).to_string(),
|
|
|
|
Token::Num(_) | Token::BigInt(_) => {
|
|
|
|
colors::yellow(&line[span]).to_string()
|
|
|
|
}
|
|
|
|
Token::Word(word) => match word {
|
|
|
|
Word::True | Word::False | Word::Null => {
|
|
|
|
colors::yellow(&line[span]).to_string()
|
|
|
|
}
|
|
|
|
Word::Keyword(_) => colors::cyan(&line[span]).to_string(),
|
|
|
|
Word::Ident(ident) => {
|
|
|
|
if ident == *"undefined" {
|
|
|
|
colors::gray(&line[span]).to_string()
|
|
|
|
} else if ident == *"Infinity" || ident == *"NaN" {
|
|
|
|
colors::yellow(&line[span]).to_string()
|
2020-12-01 14:52:03 -05:00
|
|
|
} else if ident == *"async" || ident == *"of" {
|
|
|
|
colors::cyan(&line[span]).to_string()
|
2020-11-27 14:14:54 -05:00
|
|
|
} else {
|
|
|
|
line[span].to_string()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
_ => line[span].to_string(),
|
|
|
|
},
|
2021-09-07 10:39:32 -04:00
|
|
|
deno_ast::TokenOrComment::Comment { .. } => {
|
2020-11-27 14:14:54 -05:00
|
|
|
colors::gray(&line[span]).to_string()
|
|
|
|
}
|
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
out_line.into()
|
2020-10-13 10:23:02 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-09 19:07:50 -04:00
|
|
|
#[derive(Clone)]
|
|
|
|
struct ReplEditor {
|
|
|
|
inner: Arc<Mutex<Editor<EditorHelper>>>,
|
|
|
|
history_file_path: PathBuf,
|
|
|
|
}
|
2020-10-06 07:50:48 -04:00
|
|
|
|
2021-06-09 19:07:50 -04:00
|
|
|
impl ReplEditor {
|
|
|
|
pub fn new(helper: EditorHelper, history_file_path: PathBuf) -> Self {
|
2021-06-21 20:07:26 -04:00
|
|
|
let editor_config = Config::builder()
|
|
|
|
.completion_type(CompletionType::List)
|
|
|
|
.build();
|
|
|
|
|
|
|
|
let mut editor = Editor::with_config(editor_config);
|
2021-06-09 19:07:50 -04:00
|
|
|
editor.set_helper(Some(helper));
|
|
|
|
editor.load_history(&history_file_path).unwrap_or(());
|
2020-10-19 15:25:21 -04:00
|
|
|
|
2021-06-09 19:07:50 -04:00
|
|
|
ReplEditor {
|
|
|
|
inner: Arc::new(Mutex::new(editor)),
|
|
|
|
history_file_path,
|
2020-10-19 15:25:21 -04:00
|
|
|
}
|
2021-06-09 19:07:50 -04:00
|
|
|
}
|
2020-10-19 15:25:21 -04:00
|
|
|
|
2021-06-09 19:07:50 -04:00
|
|
|
pub fn readline(&self) -> Result<String, ReadlineError> {
|
2021-07-06 23:48:01 -04:00
|
|
|
self.inner.lock().readline("> ")
|
2021-06-09 19:07:50 -04:00
|
|
|
}
|
2020-10-06 07:50:48 -04:00
|
|
|
|
2021-06-09 19:07:50 -04:00
|
|
|
pub fn add_history_entry(&self, entry: String) {
|
2021-07-06 23:48:01 -04:00
|
|
|
self.inner.lock().add_history_entry(entry);
|
2021-06-09 19:07:50 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn save_history(&self) -> Result<(), AnyError> {
|
|
|
|
std::fs::create_dir_all(self.history_file_path.parent().unwrap())?;
|
|
|
|
|
2021-07-06 23:48:01 -04:00
|
|
|
self.inner.lock().save_history(&self.history_file_path)?;
|
2021-06-09 19:07:50 -04:00
|
|
|
Ok(())
|
2020-10-06 07:50:48 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-14 08:34:05 -04:00
|
|
|
static PRELUDE: &str = r#"
|
|
|
|
Object.defineProperty(globalThis, "_", {
|
|
|
|
configurable: true,
|
|
|
|
get: () => Deno[Deno.internal].lastEvalResult,
|
|
|
|
set: (value) => {
|
|
|
|
Object.defineProperty(globalThis, "_", {
|
|
|
|
value: value,
|
|
|
|
writable: true,
|
|
|
|
enumerable: true,
|
|
|
|
configurable: true,
|
|
|
|
});
|
|
|
|
console.log("Last evaluation result is no longer saved to _.");
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
Object.defineProperty(globalThis, "_error", {
|
|
|
|
configurable: true,
|
|
|
|
get: () => Deno[Deno.internal].lastThrownError,
|
|
|
|
set: (value) => {
|
|
|
|
Object.defineProperty(globalThis, "_error", {
|
|
|
|
value: value,
|
|
|
|
writable: true,
|
|
|
|
enumerable: true,
|
|
|
|
configurable: true,
|
|
|
|
});
|
|
|
|
|
|
|
|
console.log("Last thrown error is no longer saved to _error.");
|
|
|
|
},
|
|
|
|
});
|
|
|
|
"#;
|
|
|
|
|
2021-08-06 17:30:28 -04:00
|
|
|
enum EvaluationOutput {
|
|
|
|
Value(String),
|
|
|
|
Error(String),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl std::fmt::Display for EvaluationOutput {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
match self {
|
|
|
|
EvaluationOutput::Value(value) => f.write_str(value),
|
|
|
|
EvaluationOutput::Error(value) => f.write_str(value),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-09 19:07:50 -04:00
|
|
|
struct ReplSession {
|
|
|
|
worker: MainWorker,
|
|
|
|
session: LocalInspectorSession,
|
|
|
|
pub context_id: u64,
|
|
|
|
}
|
2020-10-14 08:34:05 -04:00
|
|
|
|
2021-06-09 19:07:50 -04:00
|
|
|
impl ReplSession {
|
|
|
|
pub async fn initialize(mut worker: MainWorker) -> Result<Self, AnyError> {
|
|
|
|
let mut session = worker.create_inspector_session().await;
|
|
|
|
|
|
|
|
worker
|
|
|
|
.with_event_loop(
|
|
|
|
session.post_message("Runtime.enable", None).boxed_local(),
|
|
|
|
)
|
|
|
|
.await?;
|
|
|
|
|
|
|
|
// Enabling the runtime domain will always send trigger one executionContextCreated for each
|
|
|
|
// context the inspector knows about so we grab the execution context from that since
|
|
|
|
// our inspector does not support a default context (0 is an invalid context id).
|
|
|
|
let mut context_id: u64 = 0;
|
|
|
|
for notification in session.notifications() {
|
|
|
|
let method = notification.get("method").unwrap().as_str().unwrap();
|
|
|
|
let params = notification.get("params").unwrap();
|
|
|
|
|
|
|
|
if method == "Runtime.executionContextCreated" {
|
|
|
|
context_id = params
|
|
|
|
.get("context")
|
|
|
|
.unwrap()
|
|
|
|
.get("id")
|
|
|
|
.unwrap()
|
|
|
|
.as_u64()
|
|
|
|
.unwrap();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut repl_session = ReplSession {
|
|
|
|
worker,
|
|
|
|
session,
|
|
|
|
context_id,
|
|
|
|
};
|
|
|
|
|
|
|
|
// inject prelude
|
|
|
|
repl_session.evaluate_expression(PRELUDE).await?;
|
|
|
|
|
|
|
|
Ok(repl_session)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn is_closing(&mut self) -> Result<bool, AnyError> {
|
|
|
|
let closed = self
|
2021-09-30 11:25:58 -04:00
|
|
|
.evaluate_expression("(this.closed)")
|
2021-06-09 19:07:50 -04:00
|
|
|
.await?
|
|
|
|
.get("result")
|
|
|
|
.unwrap()
|
|
|
|
.get("value")
|
|
|
|
.unwrap()
|
|
|
|
.as_bool()
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
Ok(closed)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn post_message_with_event_loop(
|
|
|
|
&mut self,
|
|
|
|
method: &str,
|
|
|
|
params: Option<Value>,
|
|
|
|
) -> Result<Value, AnyError> {
|
|
|
|
self
|
|
|
|
.worker
|
|
|
|
.with_event_loop(self.session.post_message(method, params).boxed_local())
|
|
|
|
.await
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn run_event_loop(&mut self) -> Result<(), AnyError> {
|
2021-06-29 14:39:28 -04:00
|
|
|
self.worker.run_event_loop(true).await
|
2021-06-09 19:07:50 -04:00
|
|
|
}
|
|
|
|
|
2021-06-21 15:13:25 -04:00
|
|
|
pub async fn evaluate_line_and_get_output(
|
|
|
|
&mut self,
|
|
|
|
line: &str,
|
2021-08-06 17:30:28 -04:00
|
|
|
) -> Result<EvaluationOutput, AnyError> {
|
2021-12-08 19:12:14 -05:00
|
|
|
fn format_diagnostic(diagnostic: &deno_ast::Diagnostic) -> String {
|
|
|
|
format!(
|
|
|
|
"{}: {} at {}:{}",
|
|
|
|
colors::red("parse error"),
|
|
|
|
diagnostic.message(),
|
|
|
|
diagnostic.display_position.line_number,
|
|
|
|
diagnostic.display_position.column_number,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2021-06-21 15:13:25 -04:00
|
|
|
match self.evaluate_line_with_object_wrapping(line).await {
|
|
|
|
Ok(evaluate_response) => {
|
|
|
|
let evaluate_result = evaluate_response.get("result").unwrap();
|
|
|
|
let evaluate_exception_details =
|
|
|
|
evaluate_response.get("exceptionDetails");
|
|
|
|
|
|
|
|
if evaluate_exception_details.is_some() {
|
|
|
|
self.set_last_thrown_error(evaluate_result).await?;
|
|
|
|
} else {
|
|
|
|
self.set_last_eval_result(evaluate_result).await?;
|
|
|
|
}
|
|
|
|
|
|
|
|
let value = self.get_eval_value(evaluate_result).await?;
|
|
|
|
Ok(match evaluate_exception_details {
|
2021-08-06 17:30:28 -04:00
|
|
|
Some(_) => EvaluationOutput::Error(format!("Uncaught {}", value)),
|
|
|
|
None => EvaluationOutput::Value(value),
|
2021-06-21 15:13:25 -04:00
|
|
|
})
|
|
|
|
}
|
|
|
|
Err(err) => {
|
|
|
|
// handle a parsing diagnostic
|
2021-09-07 10:39:32 -04:00
|
|
|
match err.downcast_ref::<deno_ast::Diagnostic>() {
|
2021-12-08 19:12:14 -05:00
|
|
|
Some(diagnostic) => {
|
|
|
|
Ok(EvaluationOutput::Error(format_diagnostic(diagnostic)))
|
|
|
|
}
|
|
|
|
None => match err.downcast_ref::<Diagnostics>() {
|
|
|
|
Some(diagnostics) => Ok(EvaluationOutput::Error(
|
|
|
|
diagnostics
|
|
|
|
.0
|
|
|
|
.iter()
|
|
|
|
.map(format_diagnostic)
|
|
|
|
.collect::<Vec<_>>()
|
|
|
|
.join("\n\n"),
|
|
|
|
)),
|
|
|
|
None => Err(err),
|
|
|
|
},
|
2021-06-21 15:13:25 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn evaluate_line_with_object_wrapping(
|
|
|
|
&mut self,
|
|
|
|
line: &str,
|
|
|
|
) -> Result<Value, AnyError> {
|
2021-12-08 19:12:14 -05:00
|
|
|
// Expressions like { "foo": "bar" } are interpreted as block expressions at the
|
|
|
|
// statement level rather than an object literal so we interpret it as an expression statement
|
2021-06-09 19:07:50 -04:00
|
|
|
// to match the behavior found in a typical prompt including browser developer tools.
|
|
|
|
let wrapped_line = if line.trim_start().starts_with('{')
|
|
|
|
&& !line.trim_end().ends_with(';')
|
|
|
|
{
|
|
|
|
format!("({})", &line)
|
|
|
|
} else {
|
|
|
|
line.to_string()
|
|
|
|
};
|
|
|
|
|
2021-12-08 19:12:14 -05:00
|
|
|
let evaluate_response = self.evaluate_ts_expression(&wrapped_line).await;
|
2021-06-09 19:07:50 -04:00
|
|
|
|
|
|
|
// If that fails, we retry it without wrapping in parens letting the error bubble up to the
|
|
|
|
// user if it is still an error.
|
2021-12-08 19:12:14 -05:00
|
|
|
if wrapped_line != line
|
|
|
|
&& (evaluate_response.is_err()
|
|
|
|
|| evaluate_response
|
|
|
|
.as_ref()
|
|
|
|
.unwrap()
|
|
|
|
.get("exceptionDetails")
|
|
|
|
.is_some())
|
|
|
|
{
|
|
|
|
self.evaluate_ts_expression(line).await
|
|
|
|
} else {
|
|
|
|
evaluate_response
|
|
|
|
}
|
2021-06-09 19:07:50 -04:00
|
|
|
}
|
|
|
|
|
2021-06-21 15:13:25 -04:00
|
|
|
async fn set_last_thrown_error(
|
2021-06-09 19:07:50 -04:00
|
|
|
&mut self,
|
|
|
|
error: &Value,
|
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
self.post_message_with_event_loop(
|
|
|
|
"Runtime.callFunctionOn",
|
|
|
|
Some(json!({
|
|
|
|
"executionContextId": self.context_id,
|
|
|
|
"functionDeclaration": "function (object) { Deno[Deno.internal].lastThrownError = object; }",
|
|
|
|
"arguments": [
|
|
|
|
error,
|
|
|
|
],
|
|
|
|
})),
|
|
|
|
).await?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2021-06-21 15:13:25 -04:00
|
|
|
async fn set_last_eval_result(
|
2021-06-09 19:07:50 -04:00
|
|
|
&mut self,
|
|
|
|
evaluate_result: &Value,
|
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
self.post_message_with_event_loop(
|
|
|
|
"Runtime.callFunctionOn",
|
|
|
|
Some(json!({
|
|
|
|
"executionContextId": self.context_id,
|
|
|
|
"functionDeclaration": "function (object) { Deno[Deno.internal].lastEvalResult = object; }",
|
|
|
|
"arguments": [
|
|
|
|
evaluate_result,
|
|
|
|
],
|
|
|
|
})),
|
|
|
|
).await?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn get_eval_value(
|
|
|
|
&mut self,
|
|
|
|
evaluate_result: &Value,
|
|
|
|
) -> Result<String, AnyError> {
|
|
|
|
// TODO(caspervonb) we should investigate using previews here but to keep things
|
|
|
|
// consistent with the previous implementation we just get the preview result from
|
|
|
|
// Deno.inspectArgs.
|
|
|
|
let inspect_response = self.post_message_with_event_loop(
|
|
|
|
"Runtime.callFunctionOn",
|
|
|
|
Some(json!({
|
|
|
|
"executionContextId": self.context_id,
|
2021-07-06 17:33:06 -04:00
|
|
|
"functionDeclaration": r#"function (object) {
|
|
|
|
try {
|
|
|
|
return Deno[Deno.internal].inspectArgs(["%o", object], { colors: !Deno.noColor });
|
|
|
|
} catch (err) {
|
|
|
|
return Deno[Deno.internal].inspectArgs(["%o", err]);
|
|
|
|
}
|
|
|
|
}"#,
|
2021-06-09 19:07:50 -04:00
|
|
|
"arguments": [
|
|
|
|
evaluate_result,
|
|
|
|
],
|
|
|
|
})),
|
|
|
|
).await?;
|
|
|
|
|
|
|
|
let inspect_result = inspect_response.get("result").unwrap();
|
|
|
|
let value = inspect_result.get("value").unwrap().as_str().unwrap();
|
|
|
|
|
|
|
|
Ok(value.to_string())
|
|
|
|
}
|
|
|
|
|
2021-06-21 15:13:25 -04:00
|
|
|
async fn evaluate_ts_expression(
|
|
|
|
&mut self,
|
|
|
|
expression: &str,
|
|
|
|
) -> Result<Value, AnyError> {
|
2021-09-07 10:39:32 -04:00
|
|
|
let parsed_module = deno_ast::parse_module(deno_ast::ParseParams {
|
|
|
|
specifier: "repl.ts".to_string(),
|
|
|
|
source: deno_ast::SourceTextInfo::from_string(expression.to_string()),
|
|
|
|
media_type: deno_ast::MediaType::TypeScript,
|
|
|
|
capture_tokens: false,
|
|
|
|
maybe_syntax: None,
|
2021-10-12 09:58:04 -04:00
|
|
|
scope_analysis: false,
|
2021-09-07 10:39:32 -04:00
|
|
|
})?;
|
|
|
|
|
|
|
|
let transpiled_src = transpile(
|
|
|
|
&parsed_module,
|
|
|
|
&crate::ast::EmitOptions {
|
2021-06-21 15:13:25 -04:00
|
|
|
emit_metadata: false,
|
|
|
|
source_map: false,
|
|
|
|
inline_source_map: false,
|
2021-09-08 00:05:34 -04:00
|
|
|
inline_sources: false,
|
2021-06-21 15:13:25 -04:00
|
|
|
imports_not_used_as_values: ImportsNotUsedAsValues::Preserve,
|
|
|
|
// JSX is not supported in the REPL
|
|
|
|
transform_jsx: false,
|
2021-11-08 20:26:39 -05:00
|
|
|
jsx_automatic: false,
|
|
|
|
jsx_development: false,
|
2021-06-21 15:13:25 -04:00
|
|
|
jsx_factory: "React.createElement".into(),
|
|
|
|
jsx_fragment_factory: "React.Fragment".into(),
|
2021-11-08 20:26:39 -05:00
|
|
|
jsx_import_source: None,
|
2021-06-24 09:00:46 -04:00
|
|
|
repl_imports: true,
|
2021-09-07 10:39:32 -04:00
|
|
|
},
|
|
|
|
)?
|
|
|
|
.0;
|
2021-06-21 15:13:25 -04:00
|
|
|
|
|
|
|
self
|
|
|
|
.evaluate_expression(&format!(
|
|
|
|
"'use strict'; void 0;\n{}",
|
|
|
|
transpiled_src
|
|
|
|
))
|
|
|
|
.await
|
|
|
|
}
|
|
|
|
|
2021-06-09 19:07:50 -04:00
|
|
|
async fn evaluate_expression(
|
|
|
|
&mut self,
|
|
|
|
expression: &str,
|
|
|
|
) -> Result<Value, AnyError> {
|
|
|
|
self
|
|
|
|
.post_message_with_event_loop(
|
|
|
|
"Runtime.evaluate",
|
|
|
|
Some(json!({
|
|
|
|
"expression": expression,
|
|
|
|
"contextId": self.context_id,
|
|
|
|
"replMode": true,
|
|
|
|
})),
|
|
|
|
)
|
|
|
|
.await
|
|
|
|
}
|
2020-10-14 08:34:05 -04:00
|
|
|
}
|
|
|
|
|
2021-06-09 19:07:50 -04:00
|
|
|
async fn read_line_and_poll(
|
|
|
|
repl_session: &mut ReplSession,
|
2021-11-25 14:05:12 -05:00
|
|
|
message_handler: &mut RustylineSyncMessageHandler,
|
2021-06-09 19:07:50 -04:00
|
|
|
editor: ReplEditor,
|
|
|
|
) -> Result<String, ReadlineError> {
|
2021-06-29 14:39:28 -04:00
|
|
|
let mut line_fut = tokio::task::spawn_blocking(move || editor.readline());
|
2021-06-09 19:07:50 -04:00
|
|
|
let mut poll_worker = true;
|
|
|
|
|
|
|
|
loop {
|
|
|
|
tokio::select! {
|
2021-06-29 14:39:28 -04:00
|
|
|
result = &mut line_fut => {
|
2021-06-09 19:07:50 -04:00
|
|
|
return result.unwrap();
|
|
|
|
}
|
2021-11-25 14:05:12 -05:00
|
|
|
result = message_handler.recv() => {
|
2021-06-29 14:39:28 -04:00
|
|
|
if let Some((method, params)) = result {
|
|
|
|
let result = repl_session
|
|
|
|
.post_message_with_event_loop(&method, params)
|
|
|
|
.await;
|
2021-11-25 14:05:12 -05:00
|
|
|
message_handler.send(result).unwrap();
|
2021-06-29 14:39:28 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
poll_worker = true;
|
|
|
|
},
|
2021-06-09 19:07:50 -04:00
|
|
|
_ = repl_session.run_event_loop(), if poll_worker => {
|
|
|
|
poll_worker = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-10-18 10:19:47 -04:00
|
|
|
}
|
|
|
|
|
2020-10-01 19:14:55 -04:00
|
|
|
pub async fn run(
|
2021-09-24 11:10:42 -04:00
|
|
|
ps: &ProcState,
|
2021-06-09 19:07:50 -04:00
|
|
|
worker: MainWorker,
|
2021-08-06 17:30:28 -04:00
|
|
|
maybe_eval: Option<String>,
|
2021-12-11 09:56:45 -05:00
|
|
|
) -> Result<i32, AnyError> {
|
2021-06-09 19:07:50 -04:00
|
|
|
let mut repl_session = ReplSession::initialize(worker).await?;
|
2021-11-25 14:05:12 -05:00
|
|
|
let mut rustyline_channel = rustyline_channel();
|
2020-10-19 15:25:21 -04:00
|
|
|
|
2021-06-09 19:07:50 -04:00
|
|
|
let helper = EditorHelper {
|
|
|
|
context_id: repl_session.context_id,
|
2021-11-25 14:05:12 -05:00
|
|
|
sync_sender: rustyline_channel.0,
|
2020-10-01 19:14:55 -04:00
|
|
|
};
|
|
|
|
|
2021-09-24 11:10:42 -04:00
|
|
|
let history_file_path = ps.dir.root.join("deno_history.txt");
|
2021-06-09 19:07:50 -04:00
|
|
|
let editor = ReplEditor::new(helper, history_file_path);
|
2020-10-01 19:14:55 -04:00
|
|
|
|
2021-08-06 17:30:28 -04:00
|
|
|
if let Some(eval) = maybe_eval {
|
|
|
|
let output = repl_session.evaluate_line_and_get_output(&eval).await?;
|
|
|
|
// only output errors
|
|
|
|
if let EvaluationOutput::Error(error_text) = output {
|
|
|
|
println!("error in --eval flag. {}", error_text);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-25 05:30:14 -05:00
|
|
|
println!("Deno {}", crate::version::deno());
|
2020-10-01 19:14:55 -04:00
|
|
|
println!("exit using ctrl+d or close()");
|
|
|
|
|
2020-12-01 08:13:30 -05:00
|
|
|
loop {
|
2020-10-19 15:25:21 -04:00
|
|
|
let line = read_line_and_poll(
|
2021-06-09 19:07:50 -04:00
|
|
|
&mut repl_session,
|
2021-11-25 14:05:12 -05:00
|
|
|
&mut rustyline_channel.1,
|
2020-10-19 15:25:21 -04:00
|
|
|
editor.clone(),
|
|
|
|
)
|
|
|
|
.await;
|
2020-10-01 19:14:55 -04:00
|
|
|
match line {
|
|
|
|
Ok(line) => {
|
2021-06-21 15:13:25 -04:00
|
|
|
let output = repl_session.evaluate_line_and_get_output(&line).await?;
|
2020-10-01 19:14:55 -04:00
|
|
|
|
2020-12-01 08:13:30 -05:00
|
|
|
// We check for close and break here instead of making it a loop condition to get
|
|
|
|
// consistent behavior in when the user evaluates a call to close().
|
2021-06-09 19:07:50 -04:00
|
|
|
if repl_session.is_closing().await? {
|
2020-12-01 08:13:30 -05:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
2020-10-19 07:41:25 -04:00
|
|
|
println!("{}", output);
|
2020-10-01 19:14:55 -04:00
|
|
|
|
2021-06-09 19:07:50 -04:00
|
|
|
editor.add_history_entry(line);
|
2020-10-01 19:14:55 -04:00
|
|
|
}
|
|
|
|
Err(ReadlineError::Interrupted) => {
|
2020-10-19 08:06:21 -04:00
|
|
|
println!("exit using ctrl+d or close()");
|
|
|
|
continue;
|
2020-10-01 19:14:55 -04:00
|
|
|
}
|
|
|
|
Err(ReadlineError::Eof) => {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
Err(err) => {
|
|
|
|
println!("Error: {:?}", err);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
2018-11-05 12:55:59 -05:00
|
|
|
}
|
|
|
|
|
2021-06-09 19:07:50 -04:00
|
|
|
editor.save_history()?;
|
2020-10-01 19:14:55 -04:00
|
|
|
|
2021-12-11 09:56:45 -05:00
|
|
|
Ok(repl_session.worker.get_exit_code())
|
2018-11-05 12:55:59 -05:00
|
|
|
}
|