got comments within object and array literals working out

This commit is contained in:
Jeremy Ashkenas
2009-12-22 11:50:43 -05:00
parent 65809d08f6
commit ec58d6fda2
6 changed files with 47 additions and 4 deletions

View File

@@ -118,6 +118,7 @@ rule
# Assignment within an object literal. # Assignment within an object literal.
AssignObj: AssignObj:
IDENTIFIER ":" Expression { result = AssignNode.new(val[0], val[2], :object) } IDENTIFIER ":" Expression { result = AssignNode.new(val[0], val[2], :object) }
| Comment { result = val[0] }
; ;
# A return statement. # A return statement.

View File

@@ -32,7 +32,7 @@ module CoffeeScript
# Token cleaning regexes. # Token cleaning regexes.
JS_CLEANER = /(\A`|`\Z)/ JS_CLEANER = /(\A`|`\Z)/
MULTILINER = /\n/ MULTILINER = /\n/
COMMENT_CLEANER = /^\s*#/ COMMENT_CLEANER = /(^\s*#|\n\s*$)/
# Tokens that always constitute the start of an expression. # Tokens that always constitute the start of an expression.
EXP_START = ['{', '(', '['] EXP_START = ['{', '(', '[']

View File

@@ -423,7 +423,10 @@ module CoffeeScript
o = super(o) o = super(o)
indent = o[:indent] indent = o[:indent]
o[:indent] += TAB o[:indent] += TAB
props = @properties.map {|p| o[:indent] + p.compile(o) }.join(",\n") props = @properties.map { |prop|
joiner = prop == @properties.last ? '' : prop.is_a?(CommentNode) ? "\n" : ",\n"
o[:indent] + prop.compile(o) + joiner
}.join('')
write("{\n#{props}\n#{indent}}") write("{\n#{props}\n#{indent}}")
end end
end end
@@ -438,8 +441,12 @@ module CoffeeScript
def compile(o={}) def compile(o={})
o = super(o) o = super(o)
objects = @objects.map {|obj| obj.compile(o) }.join(', ') objects = @objects.map { |obj|
write("[#{objects}]") joiner = obj.is_a?(CommentNode) ? "\n#{o[:indent] + TAB}" : obj == @objects.last ? '' : ', '
obj.compile(o.merge(:indent => o[:indent] + TAB)) + joiner
}.join('')
ending = objects.include?("\n") ? "\n#{o[:indent]}]" : ']'
write("[#{objects}#{ending}")
end end
end end

15
test/fixtures/inner_comments.cs vendored Normal file
View File

@@ -0,0 +1,15 @@
object: {
a: 1
# Comments between the elements.
b: 2
# Like this.
c: 3
}
array: [
1
# Comments between the elements.
2
# Like this.
3
]

15
test/fixtures/inner_comments.js vendored Normal file
View File

@@ -0,0 +1,15 @@
(function(){
var object = {
a: 1,
// Comments between the elements.
b: 2,
// Like this.
c: 3
};
var array = [1,
// Comments between the elements.
2,
// Like this.
3
];
})();

View File

@@ -57,6 +57,11 @@ class ParserTest < Test::Unit::TestCase
assert nodes[1].is_a? CommentNode assert nodes[1].is_a? CommentNode
end end
def test_parsing_inner_comments
nodes = @par.parse(File.read('test/fixtures/inner_comments.cs'))
assert nodes.compile == File.read('test/fixtures/inner_comments.js')
end
def test_parsing def test_parsing
nodes = @par.parse(File.read('test/fixtures/each.cs')) nodes = @par.parse(File.read('test/fixtures/each.cs'))
assign = nodes.expressions[1] assign = nodes.expressions[1]