001/*
002 * Copyright (c) 2012-2018 Institut National des Sciences Appliquées de Lyon (INSA Lyon) and others
003 *
004 * This program and the accompanying materials are made available under the
005 * terms of the Eclipse Public License 2.0 which is available at
006 * http://www.eclipse.org/legal/epl-2.0.
007 *
008 * SPDX-License-Identifier: EPL-2.0
009 */
010
011package gololang.ir;
012
013/**
014 * A reference lookup in the golo code.
015 *
016 * <p>This expression represents every reference use, that is when a variable is considered as an expression.
017 */
018public final class ReferenceLookup extends ExpressionStatement<ReferenceLookup> {
019
020  private final String name;
021
022  private ReferenceLookup(String name) {
023    super();
024    this.name = name;
025  }
026
027  /**
028   * Creates a lookup to the reference defined by the given name.
029   */
030  public static ReferenceLookup of(Object name) {
031    if (name instanceof ReferenceLookup) {
032      return (ReferenceLookup) name;
033    }
034    if (name instanceof LocalReference) {
035      return new ReferenceLookup(((LocalReference) name).getName());
036    }
037    return new ReferenceLookup(name.toString());
038  }
039
040  protected ReferenceLookup self() { return this; }
041
042  public String getName() {
043    return name;
044  }
045
046  /**
047   * Resolves the reference in the given reference table.
048   *
049   * @param referenceTable the reference table in which to resolve the lookup.
050   * @return the corresponding local reference node, or {@code null} if the reference does not exists in the table.
051   */
052  public LocalReference resolveIn(ReferenceTable referenceTable) {
053    return referenceTable.get(name);
054  }
055
056  /**
057   * Creates a corresponding local reference.
058   * <p>
059   * The created local reference is a variable one, with the same name as this lookup.
060   *
061   * @return a new variable local reference.
062   */
063  public LocalReference varRef() {
064    return LocalReference.of(name).variable();
065  }
066
067  /**
068   * Creates a corresponding local reference.
069   * <p>
070   * The created local reference is an immutable one, with the same name as this lookup.
071   *
072   * @return a new immutable local reference.
073   */
074  public LocalReference letRef() {
075    return LocalReference.of(name);
076  }
077
078  /**
079   * {@inheritDoc}
080   */
081  @Override
082  public String toString() {
083    return String.format("Ref{name=%s}", getName());
084  }
085
086  /**
087   * {@inheritDoc}
088   */
089  @Override
090  public void accept(GoloIrVisitor visitor) {
091    visitor.visitReferenceLookup(this);
092  }
093
094  /**
095   * {@inheritDoc}
096   */
097  @Override
098  protected void replaceElement(GoloElement<?> original, GoloElement<?> newElement) {
099    throw cantReplace();
100  }
101}