Skip to content

Commit

Permalink
fix(cli/repl): interpret object literals as expressions (#7591)
Browse files Browse the repository at this point in the history
  • Loading branch information
caspervonb authored Sep 21, 2020
1 parent 5c2e499 commit 9caeff3
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
15 changes: 14 additions & 1 deletion cli/rt/40_repl.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,21 @@
// Evaluate code.
// Returns true if code is consumed (no error/irrecoverable error).
// Returns false if error is recoverable
function evaluate(code) {
function evaluate(code, preprocess = true) {
const rawCode = code;
if (preprocess) {
// It is a bit unexpected that { "foo": "bar" } is interpreted as a block
// statement rather than an object literal so we interpret it as an expression statement
// to match the behavior found in a typical prompt including browser developer tools.
if (code.trimLeft().startsWith("{") && !code.trimRight().endsWith(";")) {
code = `(${code})`;
}
}

// each evalContext is a separate function body, and we want strict mode to
// work, so we should ensure that the code starts with "use strict"
const [result, errInfo] = core.evalContext(`"use strict";\n\n${code}`);

if (!errInfo) {
// when a function is eval'ed with just "use strict" sometimes the result
// is "use strict" which should be discarded
Expand All @@ -65,6 +76,8 @@
if (!isCloseCalled()) {
replLog("%o", lastEvalResult);
}
} else if (errInfo.isCompileError && code.length != rawCode.length) {
return evaluate(rawCode, false);
} else if (errInfo.isCompileError && isRecoverableError(errInfo.thrown)) {
// Recoverable compiler error
return false; // don't consume code.
Expand Down
26 changes: 26 additions & 0 deletions cli/tests/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1058,6 +1058,32 @@ fn repl_test_console_log() {
assert!(err.is_empty());
}

#[test]
fn repl_test_object_literal() {
let (out, err) = util::run_and_collect_output(
true,
"repl",
Some(vec!["{}", "{ foo: 'bar' }"]),
Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]),
false,
);
assert!(out.ends_with("{}\n{ foo: \"bar\" }\n"));
assert!(err.is_empty());
}

#[test]
fn repl_test_block_expression() {
let (out, err) = util::run_and_collect_output(
true,
"repl",
Some(vec!["{};", "{\"\"}"]),
Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]),
false,
);
assert!(out.ends_with("undefined\n\"\"\n"));
assert!(err.is_empty());
}

#[test]
fn repl_cwd() {
let (_out, err) = util::run_and_collect_output(
Expand Down

0 comments on commit 9caeff3

Please sign in to comment.