JS: prohibit is checks against native interfaces. Warn about casts to native interfaces. Fix #KT-14037, fix #KT-14038

This commit is contained in:
Alexey Andreev
2016-09-28 19:32:25 +03:00
parent 2bb81e6a18
commit acf7fcaebf
21 changed files with 341 additions and 9 deletions
@@ -22,6 +22,7 @@ import org.jetbrains.kotlin.container.useInstance
import org.jetbrains.kotlin.js.resolve.diagnostics.JsCallChecker
import org.jetbrains.kotlin.js.resolve.diagnostics.JsNameChecker
import org.jetbrains.kotlin.js.resolve.diagnostics.JsNameClashChecker
import org.jetbrains.kotlin.js.resolve.diagnostics.JsNativeRttiChecker
import org.jetbrains.kotlin.js.resolve.diagnostics.NativeInnerClassChecker
import org.jetbrains.kotlin.platform.PlatformToKotlinClassMap
import org.jetbrains.kotlin.resolve.IdentifierChecker
@@ -51,5 +52,6 @@ object JsPlatformConfigurator : PlatformConfigurator(
container.useInstance(JsTypeSpecificityComparator)
container.useInstance(JsNameClashChecker())
container.useImpl<JsReflectionAPICallChecker>()
container.useImpl<JsNativeRttiChecker>()
}
}
@@ -19,12 +19,13 @@ package org.jetbrains.kotlin.js.resolve.diagnostics
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages
import org.jetbrains.kotlin.diagnostics.rendering.DiagnosticFactoryToRendererMap
import org.jetbrains.kotlin.diagnostics.rendering.Renderers
import org.jetbrains.kotlin.diagnostics.rendering.Renderers.RENDER_TYPE
private val DIAGNOSTIC_FACTORY_TO_RENDERER by lazy {
with(DiagnosticFactoryToRendererMap("JS")) {
put(ErrorsJs.NATIVE_ANNOTATIONS_ALLOWED_ONLY_ON_MEMBER_OR_EXTENSION_FUN,
"Annotation ''{0}'' is allowed only on member functions of declaration annotated as ''kotlin.js.native'' or on toplevel extension functions", Renderers.RENDER_TYPE)
"Annotation ''{0}'' is allowed only on member functions of declaration annotated as ''kotlin.js.native'' or on toplevel extension functions", RENDER_TYPE)
put(ErrorsJs.NATIVE_INDEXER_KEY_SHOULD_BE_STRING_OR_NUMBER, "Native {0}''s first parameter type should be ''kotlin.String'' or subtype of ''kotlin.Number''", Renderers.STRING)
put(ErrorsJs.NATIVE_INDEXER_CAN_NOT_HAVE_DEFAULT_ARGUMENTS, "Native {0}''s parameter can not have default value", Renderers.STRING)
put(ErrorsJs.NATIVE_GETTER_RETURN_TYPE_SHOULD_BE_NULLABLE, "Native getter's return type should be nullable")
@@ -47,6 +48,8 @@ private val DIAGNOSTIC_FACTORY_TO_RENDERER by lazy {
put(ErrorsJs.JS_NAME_PROHIBITED_FOR_OVERRIDE, "@JsName is prohibited for overridden members")
put(ErrorsJs.JS_NAME_PROHIBITED_FOR_EXTENSION_PROPERTY, "@JsName is prohibited for extension properties")
put(ErrorsJs.JS_NAME_PROHIBITED_FOR_NAMED_NATIVE, "@JsName is prohibited for @native declaration with explicit name")
put(ErrorsJs.CANNOT_CHECK_FOR_NATIVE_INTERFACE, "Cannot check for native interface: {0}", RENDER_TYPE)
put(ErrorsJs.UNCHECKED_CAST_TO_NATIVE_INTERFACE, "Unchecked cast to native interface: {0} to {1}", RENDER_TYPE, RENDER_TYPE)
this
}
@@ -52,6 +52,8 @@ public interface ErrorsJs {
DiagnosticFactory0<PsiElement> JS_NAME_PROHIBITED_FOR_OVERRIDE = DiagnosticFactory0.create(ERROR);
DiagnosticFactory0<PsiElement> JS_NAME_PROHIBITED_FOR_EXTENSION_PROPERTY = DiagnosticFactory0.create(ERROR);
DiagnosticFactory0<PsiElement> JS_NAME_PROHIBITED_FOR_NAMED_NATIVE = DiagnosticFactory0.create(ERROR);
DiagnosticFactory1<PsiElement, KotlinType> CANNOT_CHECK_FOR_NATIVE_INTERFACE = DiagnosticFactory1.create(ERROR);
DiagnosticFactory2<PsiElement, KotlinType, KotlinType> UNCHECKED_CAST_TO_NATIVE_INTERFACE = DiagnosticFactory2.create(WARNING);
@SuppressWarnings("UnusedDeclaration")
Object _initializer = new Object() {
@@ -0,0 +1,42 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed 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.jetbrains.kotlin.js.resolve.diagnostics
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.js.translate.utils.AnnotationsUtils
import org.jetbrains.kotlin.resolve.BindingTrace
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.checkers.RttiExpressionChecker
import org.jetbrains.kotlin.resolve.calls.checkers.RttiExpressionInformation
import org.jetbrains.kotlin.resolve.calls.checkers.RttiOperation
class JsNativeRttiChecker : RttiExpressionChecker {
override fun check(rttiInformation: RttiExpressionInformation, reportOn: PsiElement, trace: BindingTrace) {
val sourceType = rttiInformation.sourceType
val targetType = rttiInformation.targetType
val targetDescriptor = targetType?.constructor?.declarationDescriptor
if (sourceType != null && targetDescriptor != null && AnnotationsUtils.isNativeInterface(targetDescriptor)) {
when (rttiInformation.operation) {
RttiOperation.IS,
RttiOperation.NOT_IS -> trace.report(ErrorsJs.CANNOT_CHECK_FOR_NATIVE_INTERFACE.on(reportOn, targetType))
RttiOperation.AS,
RttiOperation.SAFE_AS -> trace.report(ErrorsJs.UNCHECKED_CAST_TO_NATIVE_INTERFACE.on(reportOn, sourceType, targetType))
}
}
}
}
@@ -112,6 +112,10 @@ public final class AnnotationsUtils {
return false;
}
public static boolean isNativeInterface(@NotNull DeclarationDescriptor descriptor) {
return isNativeObject(descriptor) && DescriptorUtils.isInterface(descriptor);
}
public static boolean isLibraryObject(@NotNull DeclarationDescriptor descriptor) {
return hasAnnotationOrInsideAnnotatedClass(descriptor, PredefinedAnnotation.LIBRARY);
}
@@ -5492,6 +5492,24 @@ public class BoxJsTestGenerated extends AbstractBoxJsTest {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("js/js.translator/testData/box/native"), Pattern.compile("^([^_](.+))\\.kt$"), TargetBackend.ANY, true);
}
@TestMetadata("castToNativeClassChecked.kt")
public void testCastToNativeClassChecked() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("js/js.translator/testData/box/native/castToNativeClassChecked.kt");
doTest(fileName);
}
@TestMetadata("castToNativeInterface.kt")
public void testCastToNativeInterface() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("js/js.translator/testData/box/native/castToNativeInterface.kt");
doTest(fileName);
}
@TestMetadata("castToTypeParamBoundedByNativeInterface.kt")
public void testCastToTypeParamBoundedByNativeInterface() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("js/js.translator/testData/box/native/castToTypeParamBoundedByNativeInterface.kt");
doTest(fileName);
}
@TestMetadata("class.kt")
public void testClass() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("js/js.translator/testData/box/native/class.kt");
@@ -32,6 +32,7 @@ import org.jetbrains.kotlin.js.translate.context.TranslationContext;
import org.jetbrains.kotlin.js.translate.general.AbstractTranslator;
import org.jetbrains.kotlin.js.translate.general.Translation;
import org.jetbrains.kotlin.js.translate.intrinsic.functions.factories.TopLevelFIF;
import org.jetbrains.kotlin.js.translate.utils.AnnotationsUtils;
import org.jetbrains.kotlin.js.translate.reference.ReferenceTranslator;
import org.jetbrains.kotlin.js.translate.utils.BindingUtils;
import org.jetbrains.kotlin.js.translate.utils.TranslationUtils;
@@ -124,6 +125,10 @@ public final class PatternTranslator extends AbstractTranslator {
if (sourceType != null && !DynamicTypesKt.isDynamic(sourceType) && TypeUtilsKt.isSubtypeOf(sourceType, targetType)) return null;
JsExpression checkFunReference = doGetIsTypeCheckCallable(targetType);
if (checkFunReference == null) {
return null;
}
boolean isReifiedType = isReifiedTypeParameter(targetType);
if (!isReifiedType && isNullableType(targetType) ||
isReifiedType && findChildByType(targetTypeReference, KtNodeTypes.NULLABLE_TYPE) != null
@@ -137,6 +142,9 @@ public final class PatternTranslator extends AbstractTranslator {
@NotNull
public JsExpression getIsTypeCheckCallable(@NotNull KotlinType type) {
JsExpression callable = doGetIsTypeCheckCallable(type);
assert callable != null : "This method should be called only to translate reified type parameters. " +
"`callable` should never be null for reified type parameters. " +
"Actual type: " + type;
// If the type is reified, rely on the corresponding is type callable.
// Otherwise make sure that passing null yields true
@@ -147,8 +155,13 @@ public final class PatternTranslator extends AbstractTranslator {
return callable;
}
@NotNull
@Nullable
private JsExpression doGetIsTypeCheckCallable(@NotNull KotlinType type) {
ClassifierDescriptor targetDescriptor = type.getConstructor().getDeclarationDescriptor();
if (targetDescriptor != null && AnnotationsUtils.isNativeInterface(targetDescriptor)) {
return null;
}
JsExpression builtinCheck = getIsTypeCheckCallableForBuiltin(type);
if (builtinCheck != null) return builtinCheck;
@@ -164,13 +177,13 @@ public final class PatternTranslator extends AbstractTranslator {
JsExpression result = null;
for (KotlinType upperBound : typeParameterDescriptor.getUpperBounds()) {
JsExpression next = doGetIsTypeCheckCallable(upperBound);
result = result != null ? namer().andPredicate(result, next) : next;
if (next != null) {
result = result != null ? namer().andPredicate(result, next) : next;
}
}
assert result != null : "KotlinType is expected to return at least one upper bound: " + type;
return result;
}
ClassDescriptor referencedClass = DescriptorUtils.getClassDescriptorForType(type);
JsExpression typeName = ReferenceTranslator.translateAsTypeReference(referencedClass, context());
return namer().isInstanceOf(typeName);
@@ -0,0 +1,29 @@
// FILE: castToNativeClassChecked.kt
@native abstract class S() {
abstract fun foo(): String
}
@native class A(x: String) {
fun foo(): String = noImpl
}
fun createObject(): Any = A("fail: CCE not thrown")
fun box(): String {
try {
return (createObject() as S).foo()
}
catch (e: ClassCastException) {
return "OK"
}
}
// FILE: castToNativeClassChecked.js
function S() {
}
function A(x) {
this.x = x;
}
A.prototype.foo = function() {
return this.x;
}
@@ -0,0 +1,20 @@
// FILE: castToNativeInterface.kt
@native interface I {
fun foo(): String
}
@native class A(x: String) : I {
override fun foo(): String = noImpl
}
fun createObject(): Any = A("OK")
fun box() = (createObject() as I).foo()
// FILE: castToNativeInterface.js
function A(x) {
this.x = x;
}
A.prototype.foo = function() {
return this.x;
}
@@ -0,0 +1,32 @@
// FILE: castToTypeParamBoundedByNativeInterface.kt
@native interface I {
fun foo(): String
}
interface J {
fun bar(): String
}
@native abstract class B() : I
@native class A(x: String) : B() {
override fun foo(): String = noImpl
}
fun createObject(): Any = A("OK")
fun <T> castToI(o: Any): T where T : I, T : B = o as T
fun box() = castToI<A>(createObject()).foo()
// FILE: castToTypeParamBoundedByNativeInterface.js
function B() {
}
function A(x) {
this.x = x;
}
A.prototype = Object.create(B.prototype);
A.prototype.foo = function() {
return this.x;
}