/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 */
package org.codehaus.groovy.classgen.asm.sc;

import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.VariableExpression;
import org.codehaus.groovy.classgen.asm.StatementMetaTypeChooser;
import org.codehaus.groovy.transform.stc.StaticTypesMarker;

import static org.codehaus.groovy.ast.ClassHelper.isPrimitiveVoid;

/**
 * A {@link org.codehaus.groovy.classgen.asm.TypeChooser TypeChooser} which reads
 * type information from node metadata generated by the static type checker.
 */
public class StaticTypesTypeChooser extends StatementMetaTypeChooser {
    @Override
    public ClassNode resolveType(final Expression exp, final ClassNode current) {
        ASTNode target = getTarget(exp); // see GROOVY-9344, GROOVY-9607

        ClassNode inferredType = target.getNodeMetaData(StaticTypesMarker.DECLARATION_INFERRED_TYPE);
        if (inferredType == null) {
            inferredType = target.getNodeMetaData(StaticTypesMarker.INFERRED_TYPE);
        }
        if (inferredType != null && !isPrimitiveVoid(inferredType)) {
            return inferredType;
        }

        // AsmClassGenerator may create "this" expressions that the type checker knows nothing about
        if (target instanceof VariableExpression && ((VariableExpression) target).isThisExpression()) {
            return current;
        }

        return super.resolveType(exp, current);
    }

    /**
     * The inferred type, in case of a variable expression, can be set on the
     * accessed variable, so we take it instead of the reference.
     *
     * @param exp the expression for which to return the target expression
     * @return the target node
     */
    private static ASTNode getTarget(final Expression exp) {
        ASTNode target = exp;
        while (target instanceof VariableExpression) {
            Object var = ((VariableExpression) target).getAccessedVariable();
            if (var instanceof ASTNode && var != target) {
                target = (ASTNode) var;
            } else {
                break;
            }
        }
        return target;
    }
}
