001 /* 002 * Copyright 2010-2015 JetBrains s.r.o. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017 package org.jetbrains.kotlin.resolve; 018 019 import org.jetbrains.annotations.NotNull; 020 import org.jetbrains.kotlin.descriptors.ScriptDescriptor; 021 import org.jetbrains.kotlin.psi.KtScript; 022 import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo; 023 import org.jetbrains.kotlin.resolve.lazy.ForceResolveUtil; 024 import org.jetbrains.kotlin.types.ErrorUtils; 025 import org.jetbrains.kotlin.types.KotlinType; 026 import org.jetbrains.kotlin.types.expressions.CoercionStrategy; 027 import org.jetbrains.kotlin.types.expressions.ExpressionTypingContext; 028 import org.jetbrains.kotlin.types.expressions.ExpressionTypingServices; 029 import org.jetbrains.kotlin.types.expressions.PreliminaryDeclarationVisitor; 030 031 import java.util.Map; 032 033 import static org.jetbrains.kotlin.types.TypeUtils.NO_EXPECTED_TYPE; 034 035 036 // SCRIPT: resolve symbols in scripts 037 public class ScriptBodyResolver { 038 039 @NotNull private final ExpressionTypingServices expressionTypingServices; 040 041 public ScriptBodyResolver( 042 @NotNull ExpressionTypingServices expressionTypingServices 043 ) { 044 this.expressionTypingServices = expressionTypingServices; 045 } 046 047 public void resolveScriptBodies(@NotNull BodiesResolveContext c) { 048 for (Map.Entry<KtScript, ScriptDescriptor> e : c.getScripts().entrySet()) { 049 ScriptDescriptor descriptor = e.getValue(); 050 ForceResolveUtil.forceResolveAllContents(descriptor); 051 } 052 } 053 054 @NotNull 055 public KotlinType resolveScriptReturnType( 056 @NotNull KtScript script, 057 @NotNull ScriptDescriptor scriptDescriptor, 058 @NotNull BindingTrace trace 059 ) { 060 // Resolve all contents of the script 061 ExpressionTypingContext context = ExpressionTypingContext.newContext( 062 trace, 063 scriptDescriptor.getScopeForBodyResolution(), 064 DataFlowInfo.EMPTY, 065 NO_EXPECTED_TYPE 066 ); 067 PreliminaryDeclarationVisitor.Companion.createForDeclaration(script, trace); 068 KotlinType returnType = expressionTypingServices.getBlockReturnedType(script.getBlockExpression(), CoercionStrategy.NO_COERCION, context).getType(); 069 if (returnType == null) { 070 returnType = ErrorUtils.createErrorType("getBlockReturnedType returned null"); 071 } 072 return returnType; 073 } 074 }