NameExpr.java

/*
 * Copyright (C) 2007-2010 J��lio Vilmar Gesser.
 * Copyright (C) 2011, 2013-2026 The JavaParser Team.
 *
 * This file is part of JavaParser.
 *
 * JavaParser can be used either under the terms of
 * a) the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * b) the terms of the Apache License
 *
 * You should have received a copy of both licenses in LICENCE.LGPL and
 * LICENCE.APACHE. Please refer to those files for details.
 *
 * JavaParser is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 */
package com.github.javaparser.ast.expr;

import static com.github.javaparser.utils.Utils.assertNotNull;

import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.nodeTypes.NodeWithSimpleName;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.NameExprMetaModel;
import com.github.javaparser.resolution.Resolvable;
import com.github.javaparser.resolution.UnsolvedSymbolException;
import com.github.javaparser.resolution.declarations.ResolvedDeclaration;
import com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration;
import com.github.javaparser.resolution.declarations.ResolvedValueDeclaration;
import java.util.Optional;
import java.util.function.Consumer;

/**
 * Whenever a SimpleName is used in an expression, it is wrapped in NameExpr.
 * <br>In {@code int x = a + 3;} a is a SimpleName inside a NameExpr.
 *
 * @author Julio Vilmar Gesser
 */
/**
 * BREAKING CHANGE (introduced to fix issue #2684):
 * This class previously implemented {@code Resolvable<ResolvedValueDeclaration>}, implying that
 * every {@code NameExpr} denotes a value. That assumption is incorrect per JLS ��6.5: a simple
 * name is contextually ambiguous and may denote either a <em>value</em> (variable, field,
 * parameter) or a <em>type</em> (class, interface, enum), depending on where it appears in the
 * source code.
 *
 * <p>The type parameter has been widened to {@code ResolvedDeclaration}, the common supertype
 * of both {@link ResolvedValueDeclaration} and {@link ResolvedTypeDeclaration}, so that
 * {@link #resolve()} can return the correct kind of declaration without throwing for type-denoting
 * names such as {@code System} in {@code System.out.println()}.
 *
 * <p><b>Migration guide for existing callers of {@code resolve()}:</b>
 * <ul>
 *   <li>If you know the name is a value (variable, field, parameter), cast the result:
 *       {@code (ResolvedValueDeclaration) nameExpr.resolve()} ��� or check first with
 *       {@code !decl.isType()}.</li>
 *   <li>If you know the name is a type, cast to {@link ResolvedTypeDeclaration} and verify
 *       with {@code decl.isType()}.</li>
 *   <li>If the kind is unknown (e.g., when iterating all {@code NameExpr} nodes), branch on
 *       {@code decl.isType()} before casting.</li>
 * </ul>
 */
public class NameExpr extends Expression implements NodeWithSimpleName<NameExpr>, Resolvable<ResolvedDeclaration> {

    private SimpleName name;

    public NameExpr() {
        this(null, new SimpleName());
    }

    public NameExpr(final String name) {
        this(null, new SimpleName(name));
    }

    @AllFieldsConstructor
    public NameExpr(final SimpleName name) {
        this(name.getTokenRange().orElse(null), name);
        setRange(name.getRange().orElse(null));
    }

    /**
     * This constructor is used by the parser and is considered private.
     */
    @Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
    public NameExpr(TokenRange tokenRange, SimpleName name) {
        super(tokenRange);
        setName(name);
        customInitialization();
    }

    @Override
    @Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
    public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
        return v.visit(this, arg);
    }

    @Override
    @Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
    public <A> void accept(final VoidVisitor<A> v, final A arg) {
        v.visit(this, arg);
    }

    @Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
    public SimpleName getName() {
        return name;
    }

    @Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
    public NameExpr setName(final SimpleName name) {
        assertNotNull(name);
        if (name == this.name) {
            return this;
        }
        notifyPropertyChange(ObservableProperty.NAME, this.name, name);
        if (this.name != null) this.name.setParentNode(null);
        this.name = name;
        setAsParentNodeOf(name);
        return this;
    }

    @Override
    @Generated("com.github.javaparser.generator.core.node.CloneGenerator")
    public NameExpr clone() {
        return (NameExpr) accept(new CloneVisitor(), null);
    }

    @Override
    @Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
    public NameExprMetaModel getMetaModel() {
        return JavaParserMetaModel.nameExprMetaModel;
    }

    @Override
    @Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
    public boolean replace(Node node, Node replacementNode) {
        if (node == null) {
            return false;
        }
        if (node == name) {
            setName((SimpleName) replacementNode);
            return true;
        }
        return super.replace(node, replacementNode);
    }

    @Override
    @Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
    public boolean isNameExpr() {
        return true;
    }

    @Override
    @Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
    public NameExpr asNameExpr() {
        return this;
    }

    @Override
    @Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
    public void ifNameExpr(Consumer<NameExpr> action) {
        action.accept(this);
    }

    /**
     * Resolves the declaration corresponding to this name expression.
     *
     * <p>A {@code NameExpr} is contextually ambiguous per JLS ��6.5: the same syntactic construct
     * may denote either a <em>value</em> (variable, field, parameter, enum constant) or a
     * <em>type</em> (class, interface, enum), depending on where it appears in the source code.
     * Examples:
     * <ul>
     *   <li>{@code count} in {@code count + 1} is a value name ��� resolves to a
     *       {@link ResolvedValueDeclaration}.</li>
     *   <li>{@code System} in {@code System.out.println()} is a type name ��� resolves to a
     *       {@link ResolvedTypeDeclaration}.</li>
     * </ul>
     *
     * <p>The return type is {@link ResolvedDeclaration}, the common supertype of both
     * {@link ResolvedValueDeclaration} and {@link ResolvedTypeDeclaration}. Use
     * {@link ResolvedDeclaration#isType()} on the result to determine the actual kind, then
     * cast accordingly:
     * <pre>{@code
     * ResolvedDeclaration decl = nameExpr.resolve();
     * if (decl.isType()) {
     *     ResolvedTypeDeclaration typeDecl = (ResolvedTypeDeclaration) decl;
     * } else {
     *     ResolvedValueDeclaration valueDecl = (ResolvedValueDeclaration) decl;
     * }
     * }</pre>
     *
     * <p><b>Note for existing callers (breaking change from prior versions):</b> this method
     * previously returned {@link ResolvedValueDeclaration}. Code that assigns the result to a
     * {@code ResolvedValueDeclaration} variable must either widen the variable type to
     * {@link ResolvedDeclaration} or add a cast for the value case.
     *
     * @return a {@link ResolvedDeclaration} ��� either a {@link ResolvedValueDeclaration} for
     *         value-denoting names or a {@link ResolvedTypeDeclaration} for type-denoting names.
     * @throws UnsolvedSymbolException if the name cannot be resolved as a value or as a type.
     * @see FieldAccessExpr#resolve()
     * @see MethodCallExpr#resolve()
     * @see ObjectCreationExpr#resolve()
     * @see ExplicitConstructorInvocationStmt#resolve()
     */
    @Override
    public ResolvedDeclaration resolve() {
        return getSymbolResolver().resolveDeclaration(this, ResolvedDeclaration.class);
    }

    @Override
    @Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
    public Optional<NameExpr> toNameExpr() {
        return Optional.of(this);
    }
}