1 /*
   2  * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package jdk.nashorn.internal.ir;
  27 
  28 import java.io.Serializable;
  29 import java.util.ArrayList;
  30 import java.util.List;
  31 import jdk.nashorn.internal.ir.visitor.NodeVisitor;
  32 import jdk.nashorn.internal.parser.Token;
  33 import jdk.nashorn.internal.parser.TokenType;
  34 
  35 /**
  36  * Nodes are used to compose Abstract Syntax Trees.
  37  */
  38 public abstract class Node implements Cloneable, Serializable {
  39     private static final long serialVersionUID = 1L;
  40 
  41     /** Constant used for synthetic AST nodes that have no line number. */
  42     public static final int NO_LINE_NUMBER = -1;
  43 
  44     /** Constant used for synthetic AST nodes that have no token. */
  45     public static final long NO_TOKEN = 0L;
  46 
  47     /** Constant used for synthetic AST nodes that have no finish. */
  48     public static final int NO_FINISH = 0;
  49 
  50     /** Start of source range. */
  51     protected final int start;
  52 
  53     /** End of source range. */
  54     protected final int finish;
  55 
  56     /** Token descriptor. */
  57     private final long token;
  58 
  59     /**
  60      * Constructor
  61      *
  62      * @param token  token
  63      * @param finish finish
  64      */
  65     public Node(final long token, final int finish) {
  66         this.token  = token;
  67         this.start  = Token.descPosition(token);
  68         this.finish = finish;
  69     }
  70 
  71     /**
  72      * Constructor
  73      *
  74      * @param token   token
  75      * @param start   start
  76      * @param finish  finish
  77      */
  78     protected Node(final long token, final int start, final int finish) {
  79         this.start = start;
  80         this.finish = finish;
  81         this.token = token;
  82     }
  83 
  84     /**
  85      * Copy constructor
  86      *
  87      * @param node source node
  88      */
  89     protected Node(final Node node) {
  90         this.token  = node.token;
  91         this.start  = node.start;
  92         this.finish = node.finish;
  93     }
  94 
  95     /**
  96      * Copy constructor that overrides finish
  97      *
  98      * @param node source node
  99      * @param finish Last character
 100      */
 101     protected Node(final Node node, final int finish) {
 102         this.token = node.token;
 103         this.start = node.start;
 104         this.finish = finish;
 105     }
 106 
 107     /**
 108      * Is this a loop node?
 109      *
 110      * @return true if atom
 111      */
 112     public boolean isLoop() {
 113         return false;
 114     }
 115 
 116     /**
 117      * Is this an assignment node - for example a var node with an init
 118      * or a binary node that writes to a destination
 119      *
 120      * @return true if assignment
 121      */
 122     public boolean isAssignment() {
 123         return false;
 124     }
 125 
 126     /**
 127      * For reference copies - ensure that labels in the copy node are unique
 128      * using an appropriate copy constructor
 129      * @param lc lexical context
 130      * @return new node or same of no labels
 131      */
 132     public Node ensureUniqueLabels(final LexicalContext lc) {
 133         return this;
 134     }
 135 
 136     /**
 137      * Provides a means to navigate the IR.
 138      * @param visitor Node visitor.
 139      * @return node the node or its replacement after visitation, null if no further visitations are required
 140      */
 141     public abstract Node accept(NodeVisitor<? extends LexicalContext> visitor);
 142 
 143     @Override
 144     public String toString() {
 145         final StringBuilder sb = new StringBuilder();
 146         toString(sb);
 147         return sb.toString();
 148     }
 149 
 150     /**
 151      * String conversion helper. Fills a {@link StringBuilder} with the
 152      * string version of this node
 153      *
 154      * @param sb a StringBuilder
 155      */
 156     public void toString(final StringBuilder sb) {
 157         toString(sb, true);
 158     }
 159 
 160     /**
 161      * Print logic that decides whether to show the optimistic type
 162      * or not - for example it should not be printed after just parse,
 163      * when it hasn't been computed, or has been set to a trivially provable
 164      * value
 165      * @param sb   string builder
 166      * @param printType print type?
 167      */
 168     public abstract void toString(final StringBuilder sb, final boolean printType);
 169 
 170     /**
 171      * Get the finish position for this node in the source string
 172      * @return finish
 173      */
 174     public int getFinish() {
 175         return finish;
 176     }
 177 
 178     /**
 179      * Get start position for node
 180      * @return start position
 181      */
 182     public int getStart() {
 183         return start;
 184     }
 185 
 186     /**
 187      * Integer to sort nodes in source order. This order is
 188      * used by parser API to sort statements in correct order.
 189      * By default, this is the start position of this node.
 190      *
 191      * @return int code to sort this node.
 192      */
 193     public int getSourceOrder() {
 194         return getStart();
 195     }
 196 
 197     @Override
 198     protected Object clone() {
 199         try {
 200             return super.clone();
 201         } catch (final CloneNotSupportedException e) {
 202             throw new AssertionError(e);
 203         }
 204     }
 205 
 206     @Override
 207     public final boolean equals(final Object other) {
 208         return this == other;
 209     }
 210 
 211     @Override
 212     public final int hashCode() {
 213         // NOTE: we aren't delegating to Object.hashCode as it still requires trip to the VM for initializing,
 214         // it touches the object header and/or stores the identity hashcode somewhere, etc. There's several
 215         // places in the compiler pipeline that store nodes in maps, so this can get hot.
 216         return Long.hashCode(token);
 217     }
 218 
 219     /**
 220      * Return token position from a token descriptor.
 221      *
 222      * @return Start position of the token in the source.
 223      */
 224     public int position() {
 225         return Token.descPosition(token);
 226     }
 227 
 228     /**
 229      * Return token length from a token descriptor.
 230      *
 231      * @return Length of the token.
 232      */
 233     public int length() {
 234         return Token.descLength(token);
 235     }
 236 
 237     /**
 238      * Returns this node's token's type. If you want to check for the node having a specific token type,
 239      * consider using {@link #isTokenType(TokenType)} instead.
 240      *
 241      * @return type of token.
 242      */
 243     public TokenType tokenType() {
 244         return Token.descType(token);
 245     }
 246 
 247     /**
 248      * Tests if this node has the specific token type.
 249      *
 250      * @param type a token type to check this node's token type against
 251      * @return true if token types match.
 252      */
 253     public boolean isTokenType(final TokenType type) {
 254         return tokenType() == type;
 255     }
 256 
 257     /**
 258      * Get the token for this node. If you want to retrieve the token's type, consider using
 259      * {@link #tokenType()} or {@link #isTokenType(TokenType)} instead.
 260      * @return the token
 261      */
 262     public long getToken() {
 263         return token;
 264     }
 265 
 266     //on change, we have to replace the entire list, that's we can't simple do ListIterator.set
 267     static <T extends Node> List<T> accept(final NodeVisitor<? extends LexicalContext> visitor, final List<T> list) {
 268         final int size = list.size();
 269         if (size == 0) {
 270             return list;
 271         }
 272 
 273          List<T> newList = null;
 274 
 275         for (int i = 0; i < size; i++) {
 276             final T node = list.get(i);
 277             @SuppressWarnings("unchecked")
 278             final T newNode = node == null ? null : (T)node.accept(visitor);
 279             if (newNode != node) {
 280                 if (newList == null) {
 281                     newList = new ArrayList<>(size);
 282                     for (int j = 0; j < i; j++) {
 283                         newList.add(list.get(j));
 284                     }
 285                 }
 286                 newList.add(newNode);
 287             } else {
 288                 if (newList != null) {
 289                     newList.add(node);
 290                 }
 291             }
 292         }
 293 
 294         return newList == null ? list : newList;
 295     }
 296 
 297     static <T extends LexicalContextNode> T replaceInLexicalContext(final LexicalContext lc, final T oldNode, final T newNode) {
 298         if (lc != null) {
 299             lc.replace(oldNode, newNode);
 300         }
 301         return newNode;
 302     }
 303 }