mirror of
https://github.com/jashkenas/coffeescript.git
synced 2026-02-18 03:21:20 -05:00
completely reorganized for a gem and the 'coffee-script' command
This commit is contained in:
99
lib/coffee_script/command_line.rb
Normal file
99
lib/coffee_script/command_line.rb
Normal file
@@ -0,0 +1,99 @@
|
||||
require 'optparse'
|
||||
require 'fileutils'
|
||||
require 'open3'
|
||||
require File.expand_path(File.dirname(__FILE__) + '/../coffee-script')
|
||||
|
||||
module CoffeeScript
|
||||
|
||||
class CommandLine
|
||||
|
||||
BANNER = <<-EOS
|
||||
coffee-script compiles CoffeeScript files into JavaScript.
|
||||
|
||||
Usage:
|
||||
coffee-script path/to/script.cs
|
||||
EOS
|
||||
|
||||
def initialize
|
||||
parse_options
|
||||
check_sources
|
||||
compile_javascript
|
||||
end
|
||||
|
||||
def usage
|
||||
puts "\n#{@option_parser}\n"
|
||||
exit
|
||||
end
|
||||
|
||||
|
||||
private
|
||||
|
||||
def compile_javascript
|
||||
@sources.each do |source|
|
||||
contents = CoffeeScript.compile(File.open(source))
|
||||
next puts(contents) if @options[:print]
|
||||
next lint(contents) if @options[:lint]
|
||||
File.open(path_for(source), 'w+') {|f| f.write(contents) }
|
||||
end
|
||||
end
|
||||
|
||||
def check_sources
|
||||
usage if @sources.empty?
|
||||
missing = @sources.detect {|s| !File.exists?(s) }
|
||||
if missing
|
||||
STDERR.puts("File not found: '#{missing}'")
|
||||
exit(1)
|
||||
end
|
||||
end
|
||||
|
||||
# Pipe compiled JS through JSLint.
|
||||
def lint(js)
|
||||
stdin, stdout, stderr = Open3.popen3('jsl -nologo -stdin')
|
||||
stdin.write(js)
|
||||
stdin.close
|
||||
print stdout.read
|
||||
stdout.close and stderr.close
|
||||
end
|
||||
|
||||
# Write out JavaScript alongside CoffeeScript unless an output directory
|
||||
# is specified.
|
||||
def path_for(source)
|
||||
filename = File.basename(source, File.extname(source)) + '.js'
|
||||
dir = @options[:output] || File.dirname(source)
|
||||
File.join(dir, filename)
|
||||
end
|
||||
|
||||
def parse_options
|
||||
@options = {}
|
||||
@option_parser = OptionParser.new do |opts|
|
||||
opts.on('-o', '--output [DIR]', 'set the directory for compiled javascript') do |d|
|
||||
@options[:output] = d
|
||||
FileUtils.mkdir_p(d) unless File.exists?(d)
|
||||
end
|
||||
opts.on('-p', '--print', 'print the compiled javascript to stdout') do |d|
|
||||
@options[:print] = true
|
||||
end
|
||||
opts.on('-l', '--lint', 'pipe the compiled javascript through JSLint') do |l|
|
||||
@options[:lint] = true
|
||||
end
|
||||
opts.on_tail('-v', '--version', 'display coffee-script version') do
|
||||
puts "coffee-script version #{CoffeeScript::VERSION}"
|
||||
exit
|
||||
end
|
||||
opts.on_tail('-h', '--help', 'display this help message') do
|
||||
usage
|
||||
end
|
||||
end
|
||||
@option_parser.banner = BANNER
|
||||
begin
|
||||
@option_parser.parse!(ARGV)
|
||||
rescue OptionParser::InvalidOption => e
|
||||
puts e.message
|
||||
exit(1)
|
||||
end
|
||||
@sources = ARGV
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
294
lib/coffee_script/grammar.y
Normal file
294
lib/coffee_script/grammar.y
Normal file
@@ -0,0 +1,294 @@
|
||||
class Parser
|
||||
|
||||
# Declare tokens produced by the lexer
|
||||
token IF ELSE THEN UNLESS
|
||||
token NUMBER STRING REGEX
|
||||
token TRUE FALSE NULL
|
||||
token IDENTIFIER PROPERTY_ACCESS
|
||||
token CODE PARAM NEW RETURN
|
||||
token TRY CATCH FINALLY THROW
|
||||
token BREAK CONTINUE
|
||||
token FOR IN WHILE
|
||||
token SWITCH CASE DEFAULT
|
||||
token NEWLINE
|
||||
token JS
|
||||
|
||||
# Declare order of operations.
|
||||
prechigh
|
||||
nonassoc UMINUS NOT '!'
|
||||
left '*' '/' '%'
|
||||
left '+' '-'
|
||||
left '<=' '<' '>' '>='
|
||||
right '==' '!=' IS AINT
|
||||
left '&&' '||' AND OR
|
||||
left ':'
|
||||
right '-=' '+=' '/=' '*=' '||=' '&&='
|
||||
nonassoc IF
|
||||
left UNLESS
|
||||
right RETURN THROW FOR WHILE
|
||||
nonassoc "."
|
||||
preclow
|
||||
|
||||
# We expect 2 shift/reduce errors for optional syntax.
|
||||
# There used to be 252 -- greatly improved.
|
||||
expect 2
|
||||
|
||||
rule
|
||||
|
||||
# All parsing will end in this rule, being the trunk of the AST.
|
||||
Root:
|
||||
/* nothing */ { result = Nodes.new([]) }
|
||||
| Terminator { result = Nodes.new([]) }
|
||||
| Expressions { result = val[0] }
|
||||
;
|
||||
|
||||
# Any list of expressions or method body, seperated by line breaks or semis.
|
||||
Expressions:
|
||||
Expression { result = Nodes.new(val) }
|
||||
| Expressions Terminator Expression { result = val[0] << val[2] }
|
||||
| Expressions Terminator { result = val[0] }
|
||||
| Terminator Expressions { result = val[1] }
|
||||
;
|
||||
|
||||
# All types of expressions in our language
|
||||
Expression:
|
||||
Literal
|
||||
| Value
|
||||
| Call
|
||||
| Assign
|
||||
| Code
|
||||
| Operation
|
||||
| If
|
||||
| Try
|
||||
| Throw
|
||||
| Return
|
||||
| While
|
||||
| For
|
||||
| Switch
|
||||
;
|
||||
|
||||
# All tokens that can terminate an expression
|
||||
Terminator:
|
||||
"\n"
|
||||
| ";"
|
||||
;
|
||||
|
||||
# All tokens that can serve to begin the second block
|
||||
Then:
|
||||
THEN
|
||||
| Terminator
|
||||
;
|
||||
|
||||
# All hard-coded values
|
||||
Literal:
|
||||
NUMBER { result = LiteralNode.new(val[0]) }
|
||||
| STRING { result = LiteralNode.new(val[0]) }
|
||||
| JS { result = LiteralNode.new(val[0]) }
|
||||
| REGEX { result = LiteralNode.new(val[0]) }
|
||||
| TRUE { result = LiteralNode.new(true) }
|
||||
| FALSE { result = LiteralNode.new(false) }
|
||||
| NULL { result = LiteralNode.new(nil) }
|
||||
| BREAK { result = LiteralNode.new(val[0]) }
|
||||
| CONTINUE { result = LiteralNode.new(val[0]) }
|
||||
;
|
||||
|
||||
# Assign to a variable
|
||||
Assign:
|
||||
Value ":" Expression { result = AssignNode.new(val[0], val[2]) }
|
||||
;
|
||||
|
||||
# Assignment within an object literal.
|
||||
AssignObj:
|
||||
IDENTIFIER ":" Expression { result = AssignNode.new(val[0], val[2], :object) }
|
||||
;
|
||||
|
||||
# A Return statement.
|
||||
Return:
|
||||
RETURN Expression { result = ReturnNode.new(val[1]) }
|
||||
;
|
||||
|
||||
# Arithmetic and logical operators
|
||||
# For Ruby's Operator precedence, see:
|
||||
# https://www.cs.auckland.ac.nz/references/ruby/ProgrammingRuby/language.html
|
||||
Operation:
|
||||
'!' Expression { result = OpNode.new(val[0], val[1]) }
|
||||
| '-' Expression = UMINUS { result = OpNode.new(val[0], val[1]) }
|
||||
| NOT Expression { result = OpNode.new(val[0], val[1]) }
|
||||
|
||||
|
||||
| Expression '*' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '/' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '%' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
|
||||
| Expression '+' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '-' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
|
||||
| Expression '<=' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '<' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '>' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '>=' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
|
||||
| Expression '==' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '!=' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression IS Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression AINT Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
|
||||
| Expression '&&' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '||' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression AND Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression OR Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
|
||||
| Expression '-=' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '+=' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '/=' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '*=' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '||=' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
| Expression '&&=' Expression { result = OpNode.new(val[1], val[0], val[2]) }
|
||||
;
|
||||
|
||||
|
||||
# Method definition
|
||||
Code:
|
||||
ParamList "=>" Expressions "." { result = CodeNode.new(val[0], val[2]) }
|
||||
| "=>" Expressions "." { result = CodeNode.new([], val[1]) }
|
||||
;
|
||||
|
||||
ParamList:
|
||||
PARAM { result = val }
|
||||
| ParamList "," PARAM { result = val[0] << val[2] }
|
||||
;
|
||||
|
||||
Value:
|
||||
IDENTIFIER { result = ValueNode.new(val) }
|
||||
| Array { result = ValueNode.new(val) }
|
||||
| Object { result = ValueNode.new(val) }
|
||||
| Parenthetical { result = ValueNode.new(val) }
|
||||
| Value Accessor { result = val[0] << val[1] }
|
||||
| Invocation Accessor { result = ValueNode.new(val[0], [val[1]]) }
|
||||
;
|
||||
|
||||
Accessor:
|
||||
PROPERTY_ACCESS IDENTIFIER { result = AccessorNode.new(val[1]) }
|
||||
| Index { result = val[0] }
|
||||
| Slice { result = val[0] }
|
||||
;
|
||||
|
||||
Index:
|
||||
"[" Expression "]" { result = IndexNode.new(val[1]) }
|
||||
;
|
||||
|
||||
Slice:
|
||||
"[" Expression "," Expression "]" { result = SliceNode.new(val[1], val[3]) }
|
||||
;
|
||||
|
||||
Object:
|
||||
"{" AssignList "}" { result = ObjectNode.new(val[1]) }
|
||||
;
|
||||
|
||||
AssignList:
|
||||
/* nothing */ { result = []}
|
||||
| AssignObj { result = val }
|
||||
| AssignList "," AssignObj { result = val[0] << val[2] }
|
||||
| AssignList Terminator AssignObj { result = val[0] << val[2] }
|
||||
;
|
||||
|
||||
# A method call.
|
||||
Call:
|
||||
Invocation { result = val[0] }
|
||||
| NEW Invocation { result = val[1].new_instance }
|
||||
;
|
||||
|
||||
Invocation:
|
||||
Value "(" ArgList ")" { result = CallNode.new(val[0], val[2]) }
|
||||
;
|
||||
|
||||
# An Array.
|
||||
Array:
|
||||
"[" ArgList "]" { result = ArrayNode.new(val[1]) }
|
||||
;
|
||||
|
||||
# A list of arguments to a method call.
|
||||
ArgList:
|
||||
/* nothing */ { result = [] }
|
||||
| Expression { result = val }
|
||||
| ArgList "," Expression { result = val[0] << val[2] }
|
||||
| ArgList Terminator Expression { result = val[0] << val[2] }
|
||||
;
|
||||
|
||||
If:
|
||||
IF Expression
|
||||
Then Expressions "." { result = IfNode.new(val[1], val[3]) }
|
||||
| IF Expression
|
||||
Then Expressions
|
||||
ELSE Expressions "." { result = IfNode.new(val[1], val[3], val[5]) }
|
||||
| Expression IF Expression { result = IfNode.new(val[2], Nodes.new([val[0]])) }
|
||||
| Expression UNLESS Expression { result = IfNode.new(val[2], Nodes.new([val[0]]), nil, :invert) }
|
||||
;
|
||||
|
||||
Try:
|
||||
TRY Expressions CATCH IDENTIFIER
|
||||
Expressions "." { result = TryNode.new(val[1], val[3], val[4]) }
|
||||
| TRY Expressions FINALLY
|
||||
Expressions "." { result = TryNode.new(val[1], nil, nil, val[3]) }
|
||||
| TRY Expressions CATCH IDENTIFIER
|
||||
Expressions
|
||||
FINALLY Expressions "." { result = TryNode.new(val[1], val[3], val[4], val[6]) }
|
||||
;
|
||||
|
||||
Throw:
|
||||
THROW Expression { result = ThrowNode.new(val[1]) }
|
||||
;
|
||||
|
||||
Parenthetical:
|
||||
"(" Expressions ")" { result = ParentheticalNode.new(val[1]) }
|
||||
;
|
||||
|
||||
While:
|
||||
WHILE Expression Then
|
||||
Expressions "." { result = WhileNode.new(val[1], val[3]) }
|
||||
;
|
||||
|
||||
For:
|
||||
Expression FOR IDENTIFIER
|
||||
IN Expression "." { result = ForNode.new(val[0], val[4], val[2]) }
|
||||
| Expression FOR
|
||||
IDENTIFIER "," IDENTIFIER
|
||||
IN Expression "." { result = ForNode.new(val[0], val[6], val[2], val[4]) }
|
||||
| Expression FOR IDENTIFIER
|
||||
IN Expression
|
||||
IF Expression "." { result = ForNode.new(IfNode.new(val[6], Nodes.new([val[0]])), val[4], val[2]) }
|
||||
| Expression FOR
|
||||
IDENTIFIER "," IDENTIFIER
|
||||
IN Expression
|
||||
IF Expression "." { result = ForNode.new(IfNode.new(val[8], Nodes.new([val[0]])), val[6], val[2], val[4]) }
|
||||
;
|
||||
|
||||
Switch:
|
||||
SWITCH Expression Then
|
||||
Cases "." { result = val[3].rewrite_condition(val[1]) }
|
||||
| SWITCH Expression Then
|
||||
Cases DEFAULT Expressions "." { result = val[3].rewrite_condition(val[1]).add_default(val[5]) }
|
||||
;
|
||||
|
||||
Cases:
|
||||
Case { result = val[0] }
|
||||
| Cases Case { result = val[0] << val[1] }
|
||||
;
|
||||
|
||||
Case:
|
||||
CASE Expression Then Expressions { result = IfNode.new(val[1], val[3]) }
|
||||
;
|
||||
|
||||
end
|
||||
|
||||
---- inner
|
||||
def parse(code, show_tokens=false)
|
||||
# @yydebug = true
|
||||
@tokens = Lexer.new.tokenize(code)
|
||||
puts @tokens.inspect if show_tokens
|
||||
do_parse
|
||||
end
|
||||
|
||||
def next_token
|
||||
@tokens.shift
|
||||
end
|
||||
140
lib/coffee_script/lexer.rb
Normal file
140
lib/coffee_script/lexer.rb
Normal file
@@ -0,0 +1,140 @@
|
||||
class Lexer
|
||||
|
||||
KEYWORDS = ["if", "else", "then", "unless",
|
||||
"true", "false", "null",
|
||||
"and", "or", "is", "aint", "not",
|
||||
"new", "return",
|
||||
"try", "catch", "finally", "throw",
|
||||
"break", "continue",
|
||||
"for", "in", "while",
|
||||
"switch", "case", "default"]
|
||||
|
||||
IDENTIFIER = /\A([a-zA-Z$_]\w*)/
|
||||
NUMBER = /\A([0-9]+(\.[0-9]+)?)/
|
||||
STRING = /\A("(.*?)"|'(.*?)')/
|
||||
JS = /\A(`(.*?)`)/
|
||||
OPERATOR = /\A([+\*&|\/\-%=<>]+)/
|
||||
WHITESPACE = /\A([ \t\r]+)/
|
||||
NEWLINE = /\A([\r\n]+)/
|
||||
COMMENT = /\A(#[^\r\n]*)/
|
||||
CODE = /\A(=>)/
|
||||
REGEX = /\A(\/(.*?)\/[imgy]{0,4})/
|
||||
|
||||
JS_CLEANER = /(\A`|`\Z)/
|
||||
|
||||
EXP_START = ['{', '(', '[']
|
||||
EXP_END = ['}', ')', ']']
|
||||
|
||||
# This is how to implement a very simple scanner.
|
||||
# Scan one caracter at the time until you find something to parse.
|
||||
def tokenize(code)
|
||||
@code = code.chomp # Cleanup code by remove extra line breaks
|
||||
@i = 0 # Current character position we're parsing
|
||||
@tokens = [] # Collection of all parsed tokens in the form [:TOKEN_TYPE, value]
|
||||
while @i < @code.length
|
||||
@chunk = @code[@i..-1]
|
||||
extract_next_token
|
||||
end
|
||||
@tokens
|
||||
end
|
||||
|
||||
def extract_next_token
|
||||
return if identifier_token
|
||||
return if number_token
|
||||
return if string_token
|
||||
return if js_token
|
||||
return if regex_token
|
||||
return if remove_comment
|
||||
return if whitespace_token
|
||||
return literal_token
|
||||
end
|
||||
|
||||
# Matching if, print, method names, etc.
|
||||
def identifier_token
|
||||
return false unless identifier = @chunk[IDENTIFIER, 1]
|
||||
# Keywords are special identifiers tagged with their own name, 'if' will result
|
||||
# in an [:IF, "if"] token
|
||||
tag = KEYWORDS.include?(identifier) ? identifier.upcase.to_sym : :IDENTIFIER
|
||||
if tag == :IDENTIFIER && @tokens[-1] && @tokens[-1][1] == '.'
|
||||
@tokens[-1] = [:PROPERTY_ACCESS, '.']
|
||||
end
|
||||
@tokens << [tag, identifier]
|
||||
@i += identifier.length
|
||||
end
|
||||
|
||||
def number_token
|
||||
return false unless number = @chunk[NUMBER, 1]
|
||||
float = number.include?('.')
|
||||
@tokens << [:NUMBER, float ? number.to_f : number.to_i]
|
||||
@i += number.length
|
||||
end
|
||||
|
||||
def string_token
|
||||
return false unless string = @chunk[STRING, 1]
|
||||
@tokens << [:STRING, string]
|
||||
@i += string.length
|
||||
end
|
||||
|
||||
def js_token
|
||||
return false unless script = @chunk[JS, 1]
|
||||
@tokens << [:JS, script.gsub(JS_CLEANER, '')]
|
||||
@i += script.length
|
||||
end
|
||||
|
||||
def regex_token
|
||||
return false unless regex = @chunk[REGEX, 1]
|
||||
@tokens << [:REGEX, regex]
|
||||
@i += regex.length
|
||||
end
|
||||
|
||||
def remove_comment
|
||||
return false unless comment = @chunk[COMMENT, 1]
|
||||
@i += comment.length
|
||||
end
|
||||
|
||||
# Ignore whitespace
|
||||
def whitespace_token
|
||||
return false unless whitespace = @chunk[WHITESPACE, 1]
|
||||
@i += whitespace.length
|
||||
end
|
||||
|
||||
# We treat all other single characters as a token. Eg.: ( ) , . !
|
||||
# Multi-character operators are also literal tokens, so that Racc can assign
|
||||
# the proper order of operations. Multiple newlines get merged.
|
||||
def literal_token
|
||||
value = @chunk[NEWLINE, 1]
|
||||
if value
|
||||
@tokens << ["\n", "\n"] unless @tokens.last && @tokens.last[0] == "\n"
|
||||
return @i += value.length
|
||||
end
|
||||
value = @chunk[OPERATOR, 1]
|
||||
tag_parameters if value && value.match(CODE)
|
||||
value ||= @chunk[0,1]
|
||||
skip_following_newlines if EXP_START.include?(value)
|
||||
remove_leading_newlines if EXP_END.include?(value)
|
||||
@tokens << [value, value]
|
||||
@i += value.length
|
||||
end
|
||||
|
||||
# The main source of ambiguity in our grammar was Parameter lists (as opposed
|
||||
# to argument lists in method calls). Tag parameter identifiers to avoid this.
|
||||
def tag_parameters
|
||||
index = 0
|
||||
loop do
|
||||
tok = @tokens[index -= 1]
|
||||
next if tok[0] == ','
|
||||
return if tok[0] != :IDENTIFIER
|
||||
tok[0] = :PARAM
|
||||
end
|
||||
end
|
||||
|
||||
def skip_following_newlines
|
||||
newlines = @code[(@i+1)..-1][NEWLINE, 1]
|
||||
@i += newlines.length if newlines
|
||||
end
|
||||
|
||||
def remove_leading_newlines
|
||||
@tokens.pop if @tokens.last[1] == "\n"
|
||||
end
|
||||
|
||||
end
|
||||
455
lib/coffee_script/nodes.rb
Normal file
455
lib/coffee_script/nodes.rb
Normal file
@@ -0,0 +1,455 @@
|
||||
class Scope
|
||||
|
||||
attr_reader :parent, :temp_variable
|
||||
|
||||
def initialize(parent=nil)
|
||||
@parent = parent
|
||||
@variables = {}
|
||||
@temp_variable = @parent ? @parent.temp_variable : 'a'
|
||||
end
|
||||
|
||||
# Look up a variable in lexical scope, or declare it if not found.
|
||||
def find(name, remote=false)
|
||||
found = check(name, remote)
|
||||
return found if found || remote
|
||||
@variables[name] = true
|
||||
found
|
||||
end
|
||||
|
||||
# Just check for the pre-definition of a variable.
|
||||
def check(name, remote=false)
|
||||
return true if @variables[name]
|
||||
@parent && @parent.find(name, true)
|
||||
end
|
||||
|
||||
# Find an available, short variable name.
|
||||
def free_variable
|
||||
@temp_variable.succ! while check(@temp_variable)
|
||||
@variables[@temp_variable] = true
|
||||
@temp_variable.dup
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
class Node
|
||||
# Tabs are two spaces for pretty-printing.
|
||||
TAB = ' '
|
||||
|
||||
def flatten; self; end
|
||||
def line_ending; ';'; end
|
||||
def statement?; false; end
|
||||
def custom_return?; false; end
|
||||
def custom_assign?; false; end
|
||||
|
||||
def compile(indent='', scope=nil, opts={}); end
|
||||
end
|
||||
|
||||
# Collection of nodes each one representing an expression.
|
||||
class Nodes < Node
|
||||
attr_reader :nodes
|
||||
|
||||
def self.wrap(node)
|
||||
node.is_a?(Nodes) ? node : Nodes.new([node])
|
||||
end
|
||||
|
||||
def initialize(nodes)
|
||||
@nodes = nodes
|
||||
end
|
||||
|
||||
def <<(node)
|
||||
@nodes << node
|
||||
self
|
||||
end
|
||||
|
||||
def flatten
|
||||
@nodes.length == 1 ? @nodes.first : self
|
||||
end
|
||||
|
||||
def begin_compile
|
||||
"(function(){\n#{compile(TAB, Scope.new)}\n})();"
|
||||
end
|
||||
|
||||
# Fancy to handle pushing down returns recursively to the final lines of
|
||||
# inner statements (to make expressions out of them).
|
||||
def compile(indent='', scope=nil, opts={})
|
||||
return begin_compile unless scope
|
||||
@nodes.map { |n|
|
||||
if opts[:return] && n == @nodes.last
|
||||
if n.statement? || n.custom_return?
|
||||
"#{indent}#{n.compile(indent, scope, opts)}#{n.line_ending}"
|
||||
else
|
||||
"#{indent}return #{n.compile(indent, scope, opts)}#{n.line_ending}"
|
||||
end
|
||||
else
|
||||
"#{indent}#{n.compile(indent, scope)}#{n.line_ending}"
|
||||
end
|
||||
}.join("\n")
|
||||
end
|
||||
end
|
||||
|
||||
# Literals are static values that have a Ruby representation, eg.: a string, a number,
|
||||
# true, false, nil, etc.
|
||||
class LiteralNode < Node
|
||||
def initialize(value)
|
||||
@value = value
|
||||
end
|
||||
|
||||
def compile(indent, scope, opts={})
|
||||
@value.to_s
|
||||
end
|
||||
end
|
||||
|
||||
class ReturnNode < Node
|
||||
def initialize(expression)
|
||||
@expression = expression
|
||||
end
|
||||
|
||||
def custom_return?
|
||||
true
|
||||
end
|
||||
|
||||
def compile(indent, scope, opts={})
|
||||
compiled = @expression.compile(indent, scope)
|
||||
@expression.statement? ? "#{compiled}\n#{indent}return null" : "return #{compiled}"
|
||||
end
|
||||
end
|
||||
|
||||
# Node of a method call or local variable access, can take any of these forms:
|
||||
#
|
||||
# method # this form can also be a local variable
|
||||
# method(argument1, argument2)
|
||||
# receiver.method
|
||||
# receiver.method(argument1, argument2)
|
||||
#
|
||||
class CallNode < Node
|
||||
def initialize(variable, arguments=[])
|
||||
@variable, @arguments = variable, arguments
|
||||
end
|
||||
|
||||
def new_instance
|
||||
@new = true
|
||||
self
|
||||
end
|
||||
|
||||
def compile(indent, scope, opts={})
|
||||
args = @arguments.map{|a| a.compile(indent, scope, :no_paren => true) }.join(', ')
|
||||
prefix = @new ? "new " : ''
|
||||
"#{prefix}#{@variable.compile(indent, scope)}(#{args})"
|
||||
end
|
||||
end
|
||||
|
||||
class ValueNode < Node
|
||||
def initialize(name, properties=[])
|
||||
@name, @properties = name, properties
|
||||
end
|
||||
|
||||
def <<(other)
|
||||
@properties << other
|
||||
self
|
||||
end
|
||||
|
||||
def properties?
|
||||
return !@properties.empty?
|
||||
end
|
||||
|
||||
def compile(indent, scope, opts={})
|
||||
[@name, @properties].flatten.map { |v|
|
||||
v.respond_to?(:compile) ? v.compile(indent, scope) : v.to_s
|
||||
}.join('')
|
||||
end
|
||||
end
|
||||
|
||||
class AccessorNode
|
||||
def initialize(name)
|
||||
@name = name
|
||||
end
|
||||
|
||||
def compile(indent, scope, opts={})
|
||||
".#{@name}"
|
||||
end
|
||||
end
|
||||
|
||||
class IndexNode
|
||||
def initialize(index)
|
||||
@index = index
|
||||
end
|
||||
|
||||
def compile(indent, scope, opts={})
|
||||
"[#{@index.compile(indent, scope)}]"
|
||||
end
|
||||
end
|
||||
|
||||
class SliceNode
|
||||
def initialize(from, to)
|
||||
@from, @to = from, to
|
||||
end
|
||||
|
||||
def compile(indent, scope, opts={})
|
||||
".slice(#{@from.compile(indent, scope, opts)}, #{@to.compile(indent, scope, opts)} + 1)"
|
||||
end
|
||||
end
|
||||
|
||||
# Setting the value of a local variable.
|
||||
class AssignNode < Node
|
||||
def initialize(variable, value, context=nil)
|
||||
@variable, @value, @context = variable, value, context
|
||||
end
|
||||
|
||||
def custom_return?
|
||||
true
|
||||
end
|
||||
|
||||
def compile(indent, scope, opts={})
|
||||
value = @value.compile(indent + TAB, scope)
|
||||
return "#{@variable}: #{value}" if @context == :object
|
||||
name = @variable.compile(indent, scope)
|
||||
return "#{name} = #{value}" if @variable.properties?
|
||||
defined = scope.find(name)
|
||||
postfix = !defined && opts[:return] ? ";\n#{indent}return #{name}" : ''
|
||||
def_part = defined ? "" : "var #{name};\n#{indent}"
|
||||
return def_part + @value.compile(indent, scope, opts.merge(:assign => name)) if @value.custom_assign?
|
||||
def_part = defined ? name : "var #{name}"
|
||||
"#{def_part} = #{@value.compile(indent, scope)}#{postfix}"
|
||||
end
|
||||
end
|
||||
|
||||
# Simple Arithmetic and logical operations
|
||||
class OpNode < Node
|
||||
CONVERSIONS = {
|
||||
"==" => "===",
|
||||
"!=" => "!==",
|
||||
'and' => '&&',
|
||||
'or' => '||',
|
||||
'is' => '===',
|
||||
"aint" => "!==",
|
||||
'not' => '!',
|
||||
}
|
||||
CONDITIONALS = ['||=', '&&=']
|
||||
|
||||
def initialize(operator, first, second=nil)
|
||||
@first, @second = first, second
|
||||
@operator = CONVERSIONS[operator] || operator
|
||||
end
|
||||
|
||||
def unary?
|
||||
@second.nil?
|
||||
end
|
||||
|
||||
def compile(indent, scope, opts={})
|
||||
return compile_conditional(indent, scope) if CONDITIONALS.include?(@operator)
|
||||
return compile_unary(indent, scope) if unary?
|
||||
"#{@first.compile(indent, scope)} #{@operator} #{@second.compile(indent, scope)}"
|
||||
end
|
||||
|
||||
def compile_conditional(indent, scope)
|
||||
first, second = @first.compile(indent, scope), @second.compile(indent, scope)
|
||||
sym = @operator[0..1]
|
||||
"#{first} = #{first} #{sym} #{second}"
|
||||
end
|
||||
|
||||
def compile_unary(indent, scope)
|
||||
"#{@operator}#{@first.compile(indent, scope)}"
|
||||
end
|
||||
end
|
||||
|
||||
# Method definition.
|
||||
class CodeNode < Node
|
||||
def initialize(params, body)
|
||||
@params = params
|
||||
@body = body
|
||||
end
|
||||
|
||||
def compile(indent, scope, opts={})
|
||||
code = @body.compile(indent + TAB, Scope.new(scope), {:return => true})
|
||||
"function(#{@params.join(', ')}) {\n#{code}\n#{indent}}"
|
||||
end
|
||||
end
|
||||
|
||||
class ObjectNode < Node
|
||||
def initialize(properties = [])
|
||||
@properties = properties
|
||||
end
|
||||
|
||||
def compile(indent, scope, opts={})
|
||||
props = @properties.map {|p| indent + TAB + p.compile(indent, scope) }.join(",\n")
|
||||
"{\n#{props}\n#{indent}}"
|
||||
end
|
||||
end
|
||||
|
||||
class ArrayNode < Node
|
||||
def initialize(objects=[])
|
||||
@objects = objects
|
||||
end
|
||||
|
||||
def compile(indent, scope, opts={})
|
||||
objects = @objects.map {|o| o.compile(indent, scope) }.join(', ')
|
||||
"[#{objects}]"
|
||||
end
|
||||
end
|
||||
|
||||
# "if-else" control structure. Look at this node if you want to implement other control
|
||||
# structures like while, for, loop, etc.
|
||||
class IfNode < Node
|
||||
FORCE_STATEMENT = [Nodes, ReturnNode, AssignNode, IfNode]
|
||||
|
||||
def initialize(condition, body, else_body=nil, tag=nil)
|
||||
@condition = condition
|
||||
@body = body && body.flatten
|
||||
@else_body = else_body && else_body.flatten
|
||||
@condition = OpNode.new("!", @condition) if tag == :invert
|
||||
end
|
||||
|
||||
def <<(else_body)
|
||||
eb = else_body.flatten
|
||||
@else_body ? @else_body << eb : @else_body = eb
|
||||
self
|
||||
end
|
||||
|
||||
# Rewrite a chain of IfNodes with their switch condition for equality.
|
||||
def rewrite_condition(expression)
|
||||
@condition = OpNode.new("is", expression, @condition)
|
||||
@else_body.rewrite_condition(expression) if chain?
|
||||
self
|
||||
end
|
||||
|
||||
# Rewrite a chain of IfNodes to add a default case as the final else.
|
||||
def add_default(expressions)
|
||||
chain? ? @else_body.add_default(expressions) : @else_body = expressions
|
||||
self
|
||||
end
|
||||
|
||||
def chain?
|
||||
@chain ||= @else_body && @else_body.is_a?(IfNode)
|
||||
end
|
||||
|
||||
def statement?
|
||||
@is_statement ||= (FORCE_STATEMENT.include?(@body.class) || FORCE_STATEMENT.include?(@else_body.class))
|
||||
end
|
||||
|
||||
def line_ending
|
||||
statement? ? '' : ';'
|
||||
end
|
||||
|
||||
def compile(indent, scope, opts={})
|
||||
statement? ? compile_statement(indent, scope, opts) : compile_ternary(indent, scope)
|
||||
end
|
||||
|
||||
def compile_statement(indent, scope, opts)
|
||||
if_part = "if (#{@condition.compile(indent, scope, :no_paren => true)}) {\n#{Nodes.wrap(@body).compile(indent + TAB, scope, opts)}\n#{indent}}"
|
||||
else_part = @else_body ? " else {\n#{Nodes.wrap(@else_body).compile(indent + TAB, scope, opts)}\n#{indent}}" : ''
|
||||
if_part + else_part
|
||||
end
|
||||
|
||||
def compile_ternary(indent, scope)
|
||||
if_part = "#{@condition.compile(indent, scope)} ? #{@body.compile(indent, scope)}"
|
||||
else_part = @else_body ? "#{@else_body.compile(indent, scope)}" : 'null'
|
||||
"#{if_part} : #{else_part}"
|
||||
end
|
||||
end
|
||||
|
||||
class WhileNode < Node
|
||||
def initialize(condition, body)
|
||||
@condition, @body = condition, body
|
||||
end
|
||||
|
||||
def line_ending
|
||||
''
|
||||
end
|
||||
|
||||
def statement?
|
||||
true
|
||||
end
|
||||
|
||||
def compile(indent, scope, opts={})
|
||||
"while (#{@condition.compile(indent, scope, :no_paren => true)}) {\n#{@body.compile(indent + TAB, scope)}\n#{indent}}"
|
||||
end
|
||||
end
|
||||
|
||||
class ForNode < Node
|
||||
|
||||
def initialize(body, source, name, index=nil)
|
||||
@body, @source, @name, @index = body, source, name, index
|
||||
end
|
||||
|
||||
def line_ending
|
||||
''
|
||||
end
|
||||
|
||||
def custom_return?
|
||||
true
|
||||
end
|
||||
|
||||
def custom_assign?
|
||||
true
|
||||
end
|
||||
|
||||
def compile(indent, scope, opts={})
|
||||
svar = scope.free_variable
|
||||
ivar = scope.free_variable
|
||||
lvar = scope.free_variable
|
||||
name_part = scope.find(@name) ? @name : "var #{@name}"
|
||||
index_name = @index ? (scope.find(@index) ? @index : "var #{@index}") : nil
|
||||
source_part = "var #{svar} = #{@source.compile(indent, scope)};"
|
||||
for_part = "var #{ivar}=0, #{lvar}=#{svar}.length; #{ivar}<#{lvar}; #{ivar}++"
|
||||
var_part = "\n#{indent + TAB}#{name_part} = #{svar}[#{ivar}];\n"
|
||||
index_part = @index ? "#{indent + TAB}#{index_name} = #{ivar};\n" : ''
|
||||
|
||||
set_result = ''
|
||||
save_result = ''
|
||||
return_result = ''
|
||||
if opts[:return] || opts[:assign]
|
||||
rvar = scope.free_variable
|
||||
set_result = "var #{rvar} = [];\n#{indent}"
|
||||
save_result = "#{rvar}[#{ivar}] = "
|
||||
return_result = rvar
|
||||
return_result = "#{opts[:assign]} = #{return_result}" if opts[:assign]
|
||||
return_result = "return #{return_result}" if opts[:return]
|
||||
return_result = "\n#{indent}#{return_result}"
|
||||
end
|
||||
|
||||
body = @body.compile(indent + TAB, scope)
|
||||
"#{source_part}\n#{indent}#{set_result}for (#{for_part}) {#{var_part}#{index_part}#{indent + TAB}#{save_result}#{body};\n#{indent}}#{return_result}"
|
||||
end
|
||||
end
|
||||
|
||||
class TryNode < Node
|
||||
def initialize(try, error, recovery, finally=nil)
|
||||
@try, @error, @recovery, @finally = try, error, recovery, finally
|
||||
end
|
||||
|
||||
def line_ending
|
||||
''
|
||||
end
|
||||
|
||||
def statement?
|
||||
true
|
||||
end
|
||||
|
||||
def compile(indent, scope, opts={})
|
||||
catch_part = @recovery && " catch (#{@error}) {\n#{@recovery.compile(indent + TAB, scope, opts)}\n#{indent}}"
|
||||
finally_part = @finally && " finally {\n#{@finally.compile(indent + TAB, scope, opts)}\n#{indent}}"
|
||||
"try {\n#{@try.compile(indent + TAB, scope, opts)}\n#{indent}}#{catch_part}#{finally_part}"
|
||||
end
|
||||
end
|
||||
|
||||
class ThrowNode < Node
|
||||
def initialize(expression)
|
||||
@expression = expression
|
||||
end
|
||||
|
||||
def compile(indent, scope, opts={})
|
||||
"throw #{@expression.compile(indent, scope)}"
|
||||
end
|
||||
end
|
||||
|
||||
class ParentheticalNode < Node
|
||||
def initialize(expressions)
|
||||
@expressions = expressions
|
||||
end
|
||||
|
||||
def compile(indent, scope, opts={})
|
||||
compiled = @expressions.flatten.compile(indent, scope)
|
||||
compiled = compiled[0...-1] if compiled[-1..-1] == ';'
|
||||
opts[:no_paren] ? compiled : "(#{compiled})"
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user