| 1 | /* |
| 2 | * Copyright 2011 The Closure Compiler Authors. |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package com.google.javascript.jscomp; |
| 18 | |
| 19 | import com.google.javascript.rhino.Node; |
| 20 | |
| 21 | /** |
| 22 | * Reorder constant expression hoping for a better compression. |
| 23 | * ex. x === 0 -> 0 === x |
| 24 | * After reordering, expressions like 0 === x and 0 === y may have higher |
| 25 | * compression together than their original counterparts. |
| 26 | * |
| 27 | */ |
| 28 | class ReorderConstantExpression extends AbstractPeepholeOptimization { |
| 29 | |
| 30 | // TODO(user): Rename this pass to PeepholeReorderConstantExpression |
| 31 | // to follow our naming convention. |
| 32 | @Override |
| 33 | Node optimizeSubtree(Node subtree) { |
| 34 | // if the operator is symmetric |
| 35 | if (NodeUtil.isSymmetricOperation(subtree) |
| 36 | || NodeUtil.isRelationalOperation(subtree)) { |
| 37 | // right value is immutable and left is not |
| 38 | if (NodeUtil.isImmutableValue(subtree.getLastChild()) |
| 39 | && !NodeUtil.isImmutableValue(subtree.getFirstChild())) { |
| 40 | |
| 41 | // if relational, get the inverse operator. |
| 42 | if (NodeUtil.isRelationalOperation(subtree)){ |
| 43 | int inverseOperator = NodeUtil.getInverseOperator(subtree.getType()); |
| 44 | subtree.setType(inverseOperator); |
| 45 | } |
| 46 | |
| 47 | // swap them |
| 48 | Node firstNode = subtree.getFirstChild().detachFromParent(); |
| 49 | Node lastNode = subtree.getLastChild().detachFromParent(); |
| 50 | |
| 51 | subtree.addChildrenToFront(lastNode); |
| 52 | subtree.addChildrenToBack(firstNode); |
| 53 | reportCodeChange(); |
| 54 | } |
| 55 | } |
| 56 | return subtree; |
| 57 | } |
| 58 | } |