Skip to content
Merged
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
30 changes: 24 additions & 6 deletions lib/coffeescript/repl.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 22 additions & 10 deletions src/repl.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ nodeREPL = require 'repl'
CoffeeScript = require './'
{merge, updateSyntaxError} = require './helpers'

sawSIGINT = no

replDefaults =
prompt: 'coffee> ',
historyFile: do ->
Expand All @@ -22,23 +24,31 @@ replDefaults =
input = input.replace /^\s*try\s*{([\s\S]*)}\s*catch.*$/m, '$1'

# Require AST nodes to do some AST manipulation.
{Block, Assign, Value, Literal} = require './nodes'
{Block, Assign, Value, Literal, Call, Code} = require './nodes'

try
# Tokenize the clean input.
tokens = CoffeeScript.tokens input
# Collect referenced variable names just like in `CoffeeScript.compile`.
referencedVars = (
token[1] for token in tokens when token[0] is 'IDENTIFIER'
)
referencedVars = (token[1] for token in tokens when token[0] is 'IDENTIFIER')
# Generate the AST of the tokens.
ast = CoffeeScript.nodes tokens
# Add assignment to `_` variable to force the input to be an expression.
ast = new Block [
new Assign (new Value new Literal '__'), ast, '='
]
js = ast.compile {bare: yes, locals: Object.keys(context), referencedVars}
cb null, runInContext js, context, filename
# Add assignment to `__` variable to force the input to be an expression.
ast = new Block [new Assign (new Value new Literal '__'), ast, '=']
# Wrap the expression in a closure to support top-level `await`
ast = new Code [], ast
isAsync = ast.isAsync
# Invoke the wrapping closure
ast = new Block [new Call ast]
js = ast.compile {bare: yes, locals: Object.keys(context), referencedVars, sharedScope: yes}
result = runInContext js, context, filename
# Await an async result, if necessary
if isAsync
result = await result
cb null, result unless sawSIGINT
sawSIGINT = false
else
cb null, result
catch err
# AST's `compile` does not add source code information to syntax errors.
updateSyntaxError err, input
Expand Down Expand Up @@ -131,6 +141,8 @@ addHistory = (repl, filename, maxSize) ->
fs.writeSync fd, "#{code}\n"
lastLine = code

# XXX: The SIGINT event from REPLServer is undocumented, so this is a bit fragile
repl.on 'SIGINT', -> sawSIGINT = yes
repl.on 'exit', -> fs.closeSync fd

# Add a command to show the history stack
Expand Down