Skip to content

Add a power operator #2026

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
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
2 changes: 2 additions & 0 deletions src/grammar.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -560,6 +561,7 @@ operators = [
['nonassoc', '++', '--']
['left', '?']
['right', 'UNARY']
['right', '**']
['left', 'MATH']
['left', '+', '-']
['left', 'SHIFT']
Expand Down
1 change: 1 addition & 0 deletions src/lexer.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -599,6 +599,7 @@ OPERATOR = /// ^ (
| ([&|<>])\2=? # logic / shift
| \?\. # soak access
| \.{2,3} # range or splat
| \*\* # power
) ///

WHITESPACE = /^[^\n\S]+/
Expand Down
6 changes: 6 additions & 0 deletions src/nodes.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -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})"
Expand Down Expand Up @@ -1441,6 +1442,11 @@ exports.Op = class Op extends Base
parts.push @first.compile o, LEVEL_OP
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
Expand Down
9 changes: 9 additions & 0 deletions test/operators.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -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 2, 2 ** 1 ** 3