/*
 *  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.transform.stc

import org.codehaus.groovy.ast.ClassNode
import org.codehaus.groovy.ast.MethodNode
import org.codehaus.groovy.ast.Parameter
import org.junit.jupiter.api.Test

import java.lang.reflect.Modifier

import static org.codehaus.groovy.ast.ClassHelper.Integer_TYPE
import static org.codehaus.groovy.ast.ClassHelper.OBJECT_TYPE
import static org.codehaus.groovy.ast.ClassHelper.STRING_TYPE
import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.chooseBestMethod

final class StaticTypeCheckingSupportTest {

    // GROOVY-12156
    @Test
    void testUnionTypeCandidateOrder() {
        // MethodNode has identity equals/hashCode, and HotSpot's identity hash comes from a
        // thread-local PRNG, so the hash a node receives depends on how many identity hashes
        // the thread has already handed out; vary that, as a real compile would
        (0..<64).each { int warmup ->
            warmup.times { new Object().hashCode() }

            ClassNode a = new ClassNode('A', Modifier.PUBLIC, OBJECT_TYPE)
            ClassNode b = new ClassNode('B', Modifier.PUBLIC, OBJECT_TYPE)
            MethodNode am = a.addMethod('m', Modifier.PUBLIC, STRING_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null)
            MethodNode bm = b.addMethod('m', Modifier.PUBLIC, Integer_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null)

            // GROOVY-8965: candidates must follow the union's delegate order; callers that accept
            // more than one candidate fold their return types with lowestUpperBound, so the order
            // reaches the inferred type and therefore the generated bytecode
            def candidates = chooseBestMethod(new UnionTypeClassNode(a, b), [am, bm], ClassNode.EMPTY_ARRAY)

            assert candidates == [am, bm]
        }
    }
}
