1
0
Fork 0
mirror of https://github.com/jashkenas/coffeescript.git synced 2022-11-09 12:23:24 -05:00

power operator + tests

This commit is contained in:
charliesome 2012-01-11 17:14:23 +11:00
parent 806df9bc1e
commit a4249fd573
4 changed files with 18 additions and 0 deletions

View file

@ -526,6 +526,7 @@ grammar =
o 'Expression - Expression', -> new Op '-' , $1, $3
o 'Expression MATH Expression', -> new Op $2, $1, $3
o 'Expression ** Expression', -> new Op $2, $1, $3
o 'Expression SHIFT Expression', -> new Op $2, $1, $3
o 'Expression COMPARE Expression', -> new Op $2, $1, $3
o 'Expression LOGIC Expression', -> new Op $2, $1, $3
@ -560,6 +561,7 @@ operators = [
['nonassoc', '++', '--']
['left', '?']
['right', 'UNARY']
['right', '**']
['left', 'MATH']
['left', '+', '-']
['left', 'SHIFT']

View file

@ -599,6 +599,7 @@ OPERATOR = /// ^ (
| ([&|<>])\2=? # logic / shift
| \?\. # soak access
| \.{2,3} # range or splat
| \*\* # power
) ///
WHITESPACE = /^[^\n\S]+/

View file

@ -1406,6 +1406,7 @@ exports.Op = class Op extends Base
return @compileUnary o if @isUnary()
return @compileChain o if isChain
return @compileExistence o if @operator is '?'
return @compilePower o if @operator is '**'
code = @first.compile(o, LEVEL_OP) + ' ' + @operator + ' ' +
@second.compile(o, LEVEL_OP)
if o.level <= LEVEL_OP then code else "(#{code})"
@ -1442,6 +1443,11 @@ exports.Op = class Op extends Base
parts.reverse() if @flip
parts.join ''
compilePower: (o) ->
left = @first.compile o, LEVEL_OP
right = @second.compile o, LEVEL_OP
"Math.pow(#{left}, #{right})"
toString: (idt) ->
super idt, @constructor.name + ' ' + @operator

View file

@ -269,3 +269,12 @@ test "Regression with implicit calls against an indented assignment", ->
1
eq a, 1
test "power operator", ->
eq 27, 3 ** 3
test "power operator has higher precedence than other maths operators", ->
eq 55, 1 + 3 ** 3 * 2
test "power operator is right associative", ->
eq 1, 1 ** 2 ** 3