001 // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
002 // for details. All rights reserved. Use of this source code is governed by a
003 // BSD-style license that can be found in the LICENSE file.
004
005 package org.jetbrains.kotlin.js.backend.ast;
006
007 import org.jetbrains.kotlin.js.common.Symbol;
008 import org.jetbrains.kotlin.js.util.AstUtil;
009 import org.jetbrains.annotations.NotNull;
010 import org.jetbrains.annotations.Nullable;
011
012 /**
013 * Represents a JavaScript expression that references a name.
014 */
015 public final class JsNameRef extends JsExpression implements HasName {
016 private String ident;
017 private JsName name;
018 private JsExpression qualifier;
019
020 public JsNameRef(@NotNull JsName name) {
021 this.name = name;
022 }
023
024 public JsNameRef(@NotNull String ident) {
025 this.ident = ident;
026 }
027
028 public JsNameRef(@NotNull String ident, JsExpression qualifier) {
029 this.ident = ident;
030 this.qualifier = qualifier;
031 }
032
033 public JsNameRef(@NotNull String ident, @NotNull String qualifier) {
034 this(ident, new JsNameRef(qualifier));
035 }
036
037 public JsNameRef(@NotNull JsName name, JsExpression qualifier) {
038 this.name = name;
039 this.qualifier = qualifier;
040 }
041
042 @NotNull
043 public String getIdent() {
044 return (name == null) ? ident : name.getIdent();
045 }
046
047 @Nullable
048 @Override
049 public JsName getName() {
050 return name;
051 }
052
053 @Override
054 public void setName(JsName name) {
055 this.name = name;
056 }
057
058 @Nullable
059 @Override
060 public Symbol getSymbol() {
061 return name;
062 }
063
064 @Nullable
065 public JsExpression getQualifier() {
066 return qualifier;
067 }
068
069 @Override
070 public boolean isLeaf() {
071 return qualifier == null;
072 }
073
074 public void resolve(JsName name) {
075 this.name = name;
076 ident = null;
077 }
078
079 public void setQualifier(JsExpression qualifier) {
080 this.qualifier = qualifier;
081 }
082
083 @Override
084 public void accept(JsVisitor v) {
085 v.visitNameRef(this);
086 }
087
088 @Override
089 public void acceptChildren(JsVisitor visitor) {
090 if (qualifier != null) {
091 visitor.accept(qualifier);
092 }
093 }
094
095 @Override
096 public void traverse(JsVisitorWithContext v, JsContext ctx) {
097 if (v.visit(this, ctx)) {
098 if (qualifier != null) {
099 qualifier = v.accept(qualifier);
100 }
101 }
102 v.endVisit(this, ctx);
103 }
104
105 @NotNull
106 @Override
107 public JsNameRef deepCopy() {
108 JsExpression qualifierCopy = AstUtil.deepCopy(qualifier);
109
110 if (name != null) return new JsNameRef(name, qualifierCopy).withMetadataFrom(this);
111
112 return new JsNameRef(ident, qualifierCopy).withMetadataFrom(this);
113 }
114 }