Compare commits

..

34 Commits

Author SHA1 Message Date
Nicolay Mitropolsky
9ec715e879 [draft] UAST: KotlinNullabilityUAnnotation now is created for every AbstractKotlinUVariable 2017-10-20 10:43:57 +03:00
Nicolay Mitropolsky
79143680bd [UAST] Annotation retrieving via Kotlin moved to AbstractKotlinUVariable 2017-10-18 20:40:14 +03:00
Nicolay Mitropolsky
1962a8094d Uast: KotlinUField annotations now are retrieved from Kotlin Psi, not from compiled 2017-10-18 20:40:11 +03:00
Nicolay Mitropolsky
26de71f88e UAST: WrappedUAnnotation as replacement for usage of JavaUAnnotation 2017-10-18 20:40:09 +03:00
Nikolay Krasko
f2c3d85d1e Update file structure tests as FileStructurePopup api was changed in 173 2017-10-18 17:58:18 +03:00
Nicolay Mitropolsky
454f24a480 Spring-Kotlin: Gutter repaired (KT-20550, KT-20566)
Platform now allows Gutter to be placed only on leafs elements, this patch fixes it for `KotlinSpringClassAnnotator`.
2017-10-18 17:54:27 +03:00
Ilya Gorbunov
c79b427883 streamex version was changed in 173-snapshot to 0.6.5 2017-10-17 12:53:57 +03:00
Nicolay Mitropolsky
1d8de52c62 UAST: support for JvmDeclarationUElement 2017-10-17 12:53:56 +03:00
Nicolay Mitropolsky
56f9e58301 UAST test data fixes: LocalVariableWithAnnotationKt fix for variable type
it is not clear for me why it was not `String`
2017-10-17 12:53:55 +03:00
Nicolay Mitropolsky
d459dd770b UAST test data fixes: @null in render
as a "nullability" annotation for primitive types
2017-10-17 12:53:54 +03:00
Nicolay Mitropolsky
6a4c835be8 idea-version set to since-build="173.1" until-build="181.*" 2017-10-17 12:53:53 +03:00
Vyacheslav Gerasimov
0477f5fd2a Fix GradleNoduleBuilder use qualified names check 2017-10-17 12:53:52 +03:00
Nicolay Mitropolsky
142b6dd81b JvmFacade-related tests repair 2017-10-17 12:53:51 +03:00
Simon Ogorodnik
fd422b6296 Fix proguard settings for 173 2017-10-17 12:53:50 +03:00
Simon Ogorodnik
78570c1294 Fix compilation in 173 2017-10-17 12:53:49 +03:00
Anton Bannykh
66c1b88946 Fix compilation (MockParameterInfoUIContext.java)
(cherry picked from commit 21b0956)
2017-10-17 12:53:47 +03:00
Nicolay Mitropolsky
a7b19e9beb KotlinLanguageInjector using Registry to enable annotation injections
(cherry picked from commit 8bdfeb7)
2017-10-17 12:53:46 +03:00
Nikolay Krasko
d796ce0606 TODO: Remove js tests from non-compiler tests
(cherry picked from commit 38c42a2)
2017-10-17 12:53:45 +03:00
Simon Ogorodnik
a1c3f968c9 Fix compilation 2017-10-17 12:53:44 +03:00
Dmitry Jemerov
614a89ba90 Fix compatibility with BuildScriptDataBuilder API changes 2017-10-17 12:53:43 +03:00
Nicolay Mitropolsky
6a5dcbb35b KotlinLanguageInjector#injectInAnnotationCall optimization: using PsiClassNamePatternCondition to avoid calling getResolvedCall 2017-10-17 12:53:42 +03:00
Nicolay Mitropolsky
4d750606db KotlinLanguageInjector can inject into files modified for autocompletion 2017-10-17 12:53:41 +03:00
Nicolay Mitropolsky
dfb2000a69 KotlinLanguageInjector understands patterns-injections into Java annotations 2017-10-17 12:53:40 +03:00
xiexed
a0916b2cc2 KtLightAbstractAnnotation build fix for 173 (#1283) 2017-10-17 12:53:39 +03:00
Dmitry Jemerov
5e2983c1d5 Register new service and EPs added in 173 2017-10-17 12:53:38 +03:00
xiexed
c6378a245c Fixes for 173 after 28.08.17 changes in IDEA (#1271)
* `JarFileSystem.getJarRootForLocalFile` now is nullable in IDEA

* Spring-related renamings following ones in IDEA
2017-10-17 12:53:37 +03:00
Nicolay Mitropolsky
3bd5bb8028 Build fix for KotlinSpringClassAnnotator after collectNavigationMarkers nullability changes in IDEA 173 2017-10-17 12:53:36 +03:00
Vyacheslav Gerasimov
301b70a112 UAST: Fix testPropertyWithAnnotation 2017-10-17 12:53:35 +03:00
Vyacheslav Gerasimov
9c877e4e3f UAST: Add testConvertTypeInAnnotation 2017-10-17 12:53:34 +03:00
Vyacheslav Gerasimov
85979fe842 UAST: override getFunctionalInterfaceType + test 2017-10-17 12:53:33 +03:00
Vyacheslav Gerasimov
a54e3b9e9c UAST: Properly handle annotations on local variables 2017-10-17 12:53:32 +03:00
Vyacheslav Gerasimov
1bd9c229d9 Fix compilation 2017-10-17 12:53:31 +03:00
Vyacheslav Gerasimov
4901adf5ad Download IDEA 173.3188.16 2017-10-17 12:52:57 +03:00
Nikolay Krasko
88f1be9d15 == 172 -> 173 ^^^ == 2017-10-17 12:47:10 +03:00
1685 changed files with 11857 additions and 25168 deletions

1
.idea/ant.xml generated
View File

@@ -18,5 +18,6 @@
</properties>
</buildFile>
<buildFile url="file://$PROJECT_DIR$/TeamCityRelay.xml" />
<buildFile url="file://$PROJECT_DIR$/node_utils.xml" />
</component>
</project>

View File

@@ -2,8 +2,14 @@
<code_scheme name="Project" version="173">
<option name="OTHER_INDENT_OPTIONS">
<value>
<option name="INDENT_SIZE" value="4" />
<option name="CONTINUATION_INDENT_SIZE" value="4" />
<option name="TAB_SIZE" value="8" />
<option name="USE_TAB_CHARACTER" value="false" />
<option name="SMART_TABS" value="false" />
<option name="LABEL_INDENT_SIZE" value="0" />
<option name="LABEL_INDENT_ABSOLUTE" value="false" />
<option name="USE_RELATIVE_INDENTS" value="false" />
</value>
</option>
<option name="LINE_SEPARATOR" value="&#10;" />
@@ -75,10 +81,12 @@
<option name="TERNARY_OPERATION_SIGNS_ON_NEXT_LINE" value="true" />
<option name="FOR_STATEMENT_WRAP" value="5" />
<option name="ASSIGNMENT_WRAP" value="1" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
</codeStyleSettings>
<codeStyleSettings language="CoffeeScript">
<option name="ALIGN_MULTILINE_PARAMETERS_IN_CALLS" value="true" />
<option name="METHOD_PARAMETERS_WRAP" value="5" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
</codeStyleSettings>
<codeStyleSettings language="ECMA Script Level 4">
<option name="ELSE_ON_NEW_LINE" value="true" />
@@ -103,6 +111,7 @@
<option name="DOWHILE_BRACE_FORCE" value="1" />
<option name="WHILE_BRACE_FORCE" value="1" />
<option name="FOR_BRACE_FORCE" value="1" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
</codeStyleSettings>
<codeStyleSettings language="GSP">
<indentOptions>
@@ -136,6 +145,7 @@
<option name="WHILE_BRACE_FORCE" value="1" />
<option name="FOR_BRACE_FORCE" value="1" />
<option name="FIELD_ANNOTATION_WRAP" value="0" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
</codeStyleSettings>
<codeStyleSettings language="HTML">
<indentOptions>
@@ -182,6 +192,7 @@
<option name="WHILE_BRACE_FORCE" value="1" />
<option name="FOR_BRACE_FORCE" value="1" />
<option name="FIELD_ANNOTATION_WRAP" value="0" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
<indentOptions>
<option name="TAB_SIZE" value="8" />
</indentOptions>
@@ -206,6 +217,7 @@
<option name="DOWHILE_BRACE_FORCE" value="1" />
<option name="WHILE_BRACE_FORCE" value="1" />
<option name="FOR_BRACE_FORCE" value="1" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
</codeStyleSettings>
<codeStyleSettings language="Scala">
<option name="KEEP_BLANK_LINES_BEFORE_RBRACE" value="0" />
@@ -253,6 +265,7 @@
<option name="DOWHILE_BRACE_FORCE" value="1" />
<option name="WHILE_BRACE_FORCE" value="1" />
<option name="FOR_BRACE_FORCE" value="1" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
</codeStyleSettings>
<codeStyleSettings language="XML">
<indentOptions>
@@ -267,6 +280,7 @@
<option name="FINALLY_ON_NEW_LINE" value="true" />
<option name="ALIGN_MULTILINE_PARAMETERS_IN_CALLS" value="true" />
<option name="ALIGN_MULTILINE_BINARY_OPERATION" value="true" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
</codeStyleSettings>
</code_scheme>
</component>

View File

@@ -1,24 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Generate Compiler Tests" type="GradleRunConfiguration" factoryName="Gradle">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$/compiler" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value=":compiler:generateTests" />
<option value=":compiler:tests-java8:generateTests" />
<option value=":js:js.tests:generateTests" />
<option value=":core:descriptors.runtime:generateTests" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<method />
</configuration>
</component>

View File

@@ -1,10 +1,10 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Generate All Tests" type="GradleRunConfiguration" factoryName="Gradle">
<configuration default="false" name="Generate Tests" type="GradleRunConfiguration" factoryName="Gradle">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalProjectPath" value="$PROJECT_DIR$/generators" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="-x :ultimate:generateTests" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>

View File

@@ -4,7 +4,7 @@
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$/libraries/tools/kotlin-stdlib-gen" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="--configure-on-demand" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>

2
.idea/scopes/IDE.xml generated
View File

@@ -1,3 +1,3 @@
<component name="DependencyValidationManager">
<scope name="IDE" pattern="file[idea_main]:*/||file[idea]:testData/*/||file[idea-formatter_main]:*/||file[ide-common_main]:*/||file[idea-android_main]:*/||file[idea-android-output-parser_main]:*/||file[idea]:idea-completion/testData/*/||file[idea-core_main]:*/||file[idea-gradle_main]:*/||file[idea-jps-common_main]:*/||file[idea-jvm_main]:*/||file[idea]:idea-live-templates/src/*/||file[idea]:idea-live-templates/testData/*/||file[idea-maven_main]:*/||file[idea-repl]:*/||file[idea-test-framework_main]:*/||file[kotlin-gradle-tooling_main]:*/" />
<scope name="IDE" pattern="file[idea]:src/*/||file[idea]:testData/*/||file[ide-common]:src/*/||file[idea-analysis]:src/*/||file[idea-android]:src/*/||file[idea-completion]:src/*/||file[idea-completion]:testData/*/||file[idea-core]:src/*/||file[idea-jps-common]:/*/||file[idea-live-templates]:/*/||file[idea-live-templates]:testData/*/||file[idea-repl]:/*/||src[idea-android-output-parser]:*..*" />
</component>

View File

@@ -73,7 +73,7 @@ on Windows.
- `install` - build and install all public artifacts into local maven repository
- `runIde` - build IDEA plugin and run IDEA with it
- `coreLibsTest` - build and run stdlib, reflect and kotlin-test tests
- `gradlePluginTest` - build and run gradle plugin tests
- `gradlePluginsTest` - build and run gradle plugin tests
- `compilerTest` - build and run all compiler tests
- `ideaPluginTest` - build and run all IDEA plugin tests

View File

@@ -75,7 +75,14 @@
</macrodef>
<target name="writeCompilerVersionToTemplateFile">
<!-- empty, version is written in gradle build -->
<mkdir dir="${version_substitute_dir}"/>
<substituteVersionInFile
target.file="${compiler.version.java}"
target.file.bk="${compiler.version.java.bk}"
target.file.versioned="${compiler.version.java.versioned}"
test.string="public static final String VERSION = &quot;@snapshot@&quot;;"
version="${compiler.version.number}"/>
</target>
<target name="writePluginVersionToTemplateFile">

View File

@@ -11,14 +11,11 @@ dependencies {
compileOnly(project(":js:js.serializer"))
compileOnly(project(":js:js.frontend"))
compileOnly(ideaSdkDeps("util"))
testCompileOnly(project(":compiler:cli-common"))
testCompile(projectTests(":compiler:tests-common"))
testCompile(commonDep("junit:junit"))
testCompile(project(":compiler.tests-common"))
testCompile(protobufFull())
testCompile(projectDist(":kotlin-stdlib"))
testCompile(projectDist(":kotlin-reflect"))
testCompileOnly(ideaSdkDeps("openapi"))
testRuntime(projectDist(":kotlin-compiler"))
testRuntime(projectDist(":kotlin-stdlib"))
testRuntime(projectDist(":kotlin-reflect"))
}
sourceSets {
@@ -34,4 +31,4 @@ testsJar()
projectTest()
publish()
publish()

View File

@@ -44837,19 +44837,6 @@ public final class DebugJsAstProtoBuf {
*/
int getSuperNameId();
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
java.util.List<java.lang.Integer> getInterfaceNameIdList();
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
int getInterfaceNameIdCount();
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
int getInterfaceNameId(int index);
/**
* <code>optional .org.jetbrains.kotlin.serialization.js.ast.GlobalBlock post_declaration_block = 3;</code>
*/
@@ -44938,27 +44925,6 @@ public final class DebugJsAstProtoBuf {
bitField0_ |= 0x00000004;
break;
}
case 32: {
if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) {
interfaceNameId_ = new java.util.ArrayList<java.lang.Integer>();
mutable_bitField0_ |= 0x00000004;
}
interfaceNameId_.add(input.readInt32());
break;
}
case 34: {
int length = input.readRawVarint32();
int limit = input.pushLimit(length);
if (!((mutable_bitField0_ & 0x00000004) == 0x00000004) && input.getBytesUntilLimit() > 0) {
interfaceNameId_ = new java.util.ArrayList<java.lang.Integer>();
mutable_bitField0_ |= 0x00000004;
}
while (input.getBytesUntilLimit() > 0) {
interfaceNameId_.add(input.readInt32());
}
input.popLimit(limit);
break;
}
}
}
} catch (org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException e) {
@@ -44967,9 +44933,6 @@ public final class DebugJsAstProtoBuf {
throw new org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) {
interfaceNameId_ = java.util.Collections.unmodifiableList(interfaceNameId_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
@@ -45032,28 +44995,6 @@ public final class DebugJsAstProtoBuf {
return superNameId_;
}
public static final int INTERFACE_NAME_ID_FIELD_NUMBER = 4;
private java.util.List<java.lang.Integer> interfaceNameId_;
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
public java.util.List<java.lang.Integer>
getInterfaceNameIdList() {
return interfaceNameId_;
}
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
public int getInterfaceNameIdCount() {
return interfaceNameId_.size();
}
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
public int getInterfaceNameId(int index) {
return interfaceNameId_.get(index);
}
public static final int POST_DECLARATION_BLOCK_FIELD_NUMBER = 3;
private org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock postDeclarationBlock_;
/**
@@ -45078,7 +45019,6 @@ public final class DebugJsAstProtoBuf {
private void initFields() {
nameId_ = 0;
superNameId_ = 0;
interfaceNameId_ = java.util.Collections.emptyList();
postDeclarationBlock_ = org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock.getDefaultInstance();
}
private byte memoizedIsInitialized = -1;
@@ -45113,9 +45053,6 @@ public final class DebugJsAstProtoBuf {
if (((bitField0_ & 0x00000004) == 0x00000004)) {
output.writeMessage(3, postDeclarationBlock_);
}
for (int i = 0; i < interfaceNameId_.size(); i++) {
output.writeInt32(4, interfaceNameId_.get(i));
}
getUnknownFields().writeTo(output);
}
@@ -45137,15 +45074,6 @@ public final class DebugJsAstProtoBuf {
size += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeMessageSize(3, postDeclarationBlock_);
}
{
int dataSize = 0;
for (int i = 0; i < interfaceNameId_.size(); i++) {
dataSize += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeInt32SizeNoTag(interfaceNameId_.get(i));
}
size += dataSize;
size += 1 * getInterfaceNameIdList().size();
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
@@ -45268,14 +45196,12 @@ public final class DebugJsAstProtoBuf {
bitField0_ = (bitField0_ & ~0x00000001);
superNameId_ = 0;
bitField0_ = (bitField0_ & ~0x00000002);
interfaceNameId_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000004);
if (postDeclarationBlockBuilder_ == null) {
postDeclarationBlock_ = org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock.getDefaultInstance();
} else {
postDeclarationBlockBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000008);
bitField0_ = (bitField0_ & ~0x00000004);
return this;
}
@@ -45312,12 +45238,7 @@ public final class DebugJsAstProtoBuf {
to_bitField0_ |= 0x00000002;
}
result.superNameId_ = superNameId_;
if (((bitField0_ & 0x00000004) == 0x00000004)) {
interfaceNameId_ = java.util.Collections.unmodifiableList(interfaceNameId_);
bitField0_ = (bitField0_ & ~0x00000004);
}
result.interfaceNameId_ = interfaceNameId_;
if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
if (postDeclarationBlockBuilder_ == null) {
@@ -45347,16 +45268,6 @@ public final class DebugJsAstProtoBuf {
if (other.hasSuperNameId()) {
setSuperNameId(other.getSuperNameId());
}
if (!other.interfaceNameId_.isEmpty()) {
if (interfaceNameId_.isEmpty()) {
interfaceNameId_ = other.interfaceNameId_;
bitField0_ = (bitField0_ & ~0x00000004);
} else {
ensureInterfaceNameIdIsMutable();
interfaceNameId_.addAll(other.interfaceNameId_);
}
onChanged();
}
if (other.hasPostDeclarationBlock()) {
mergePostDeclarationBlock(other.getPostDeclarationBlock());
}
@@ -45461,72 +45372,6 @@ public final class DebugJsAstProtoBuf {
return this;
}
private java.util.List<java.lang.Integer> interfaceNameId_ = java.util.Collections.emptyList();
private void ensureInterfaceNameIdIsMutable() {
if (!((bitField0_ & 0x00000004) == 0x00000004)) {
interfaceNameId_ = new java.util.ArrayList<java.lang.Integer>(interfaceNameId_);
bitField0_ |= 0x00000004;
}
}
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
public java.util.List<java.lang.Integer>
getInterfaceNameIdList() {
return java.util.Collections.unmodifiableList(interfaceNameId_);
}
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
public int getInterfaceNameIdCount() {
return interfaceNameId_.size();
}
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
public int getInterfaceNameId(int index) {
return interfaceNameId_.get(index);
}
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
public Builder setInterfaceNameId(
int index, int value) {
ensureInterfaceNameIdIsMutable();
interfaceNameId_.set(index, value);
onChanged();
return this;
}
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
public Builder addInterfaceNameId(int value) {
ensureInterfaceNameIdIsMutable();
interfaceNameId_.add(value);
onChanged();
return this;
}
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
public Builder addAllInterfaceNameId(
java.lang.Iterable<? extends java.lang.Integer> values) {
ensureInterfaceNameIdIsMutable();
org.jetbrains.kotlin.protobuf.AbstractMessageLite.Builder.addAll(
values, interfaceNameId_);
onChanged();
return this;
}
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
public Builder clearInterfaceNameId() {
interfaceNameId_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
private org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock postDeclarationBlock_ = org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock.getDefaultInstance();
private org.jetbrains.kotlin.protobuf.SingleFieldBuilder<
org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock, org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock.Builder, org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlockOrBuilder> postDeclarationBlockBuilder_;
@@ -45534,7 +45379,7 @@ public final class DebugJsAstProtoBuf {
* <code>optional .org.jetbrains.kotlin.serialization.js.ast.GlobalBlock post_declaration_block = 3;</code>
*/
public boolean hasPostDeclarationBlock() {
return ((bitField0_ & 0x00000008) == 0x00000008);
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional .org.jetbrains.kotlin.serialization.js.ast.GlobalBlock post_declaration_block = 3;</code>
@@ -45559,7 +45404,7 @@ public final class DebugJsAstProtoBuf {
} else {
postDeclarationBlockBuilder_.setMessage(value);
}
bitField0_ |= 0x00000008;
bitField0_ |= 0x00000004;
return this;
}
/**
@@ -45573,7 +45418,7 @@ public final class DebugJsAstProtoBuf {
} else {
postDeclarationBlockBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000008;
bitField0_ |= 0x00000004;
return this;
}
/**
@@ -45581,7 +45426,7 @@ public final class DebugJsAstProtoBuf {
*/
public Builder mergePostDeclarationBlock(org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock value) {
if (postDeclarationBlockBuilder_ == null) {
if (((bitField0_ & 0x00000008) == 0x00000008) &&
if (((bitField0_ & 0x00000004) == 0x00000004) &&
postDeclarationBlock_ != org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock.getDefaultInstance()) {
postDeclarationBlock_ =
org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock.newBuilder(postDeclarationBlock_).mergeFrom(value).buildPartial();
@@ -45592,7 +45437,7 @@ public final class DebugJsAstProtoBuf {
} else {
postDeclarationBlockBuilder_.mergeFrom(value);
}
bitField0_ |= 0x00000008;
bitField0_ |= 0x00000004;
return this;
}
/**
@@ -45605,14 +45450,14 @@ public final class DebugJsAstProtoBuf {
} else {
postDeclarationBlockBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000008);
bitField0_ = (bitField0_ & ~0x00000004);
return this;
}
/**
* <code>optional .org.jetbrains.kotlin.serialization.js.ast.GlobalBlock post_declaration_block = 3;</code>
*/
public org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock.Builder getPostDeclarationBlockBuilder() {
bitField0_ |= 0x00000008;
bitField0_ |= 0x00000004;
onChanged();
return getPostDeclarationBlockFieldBuilder().getBuilder();
}
@@ -49531,34 +49376,33 @@ public final class DebugJsAstProtoBuf {
"expression\030\002 \002(\01325.org.jetbrains.kotlin." +
"serialization.js.ast.Expression\"3\n\013NameB" +
"inding\022\024\n\014signature_id\030\001 \002(\005\022\016\n\006nameId\030\002" +
" \002(\005\"\247\001\n\nClassModel\022\017\n\007name_id\030\001 \002(\005\022\025\n\r" +
"super_name_id\030\002 \001(\005\022\031\n\021interface_name_id" +
"\030\004 \003(\005\022V\n\026post_declaration_block\030\003 \001(\01326" +
".org.jetbrains.kotlin.serialization.js.a" +
"st.GlobalBlock\";\n\014InlineModule\022\024\n\014signat" +
"ure_id\030\001 \002(\005\022\025\n\rexpression_id\030\002 \002(\005\"\034\n\013S" +
"tringTable\022\r\n\005entry\030\001 \003(\t\"K\n\tNameTable\022>",
"\n\005entry\030\001 \003(\0132/.org.jetbrains.kotlin.ser" +
"ialization.js.ast.Name\"\263\001\n\004Name\022\021\n\ttempo" +
"rary\030\001 \002(\010\022\022\n\nidentifier\030\002 \001(\005\022\025\n\rlocal_" +
"name_id\030\003 \001(\005\022\027\n\010imported\030\004 \001(\010:\005false\022T" +
"\n\020special_function\030\005 \001(\0162:.org.jetbrains" +
".kotlin.serialization.js.ast.SpecialFunc" +
"tion\"\346\001\n\005Chunk\022L\n\014string_table\030\001 \002(\01326.o" +
"rg.jetbrains.kotlin.serialization.js.ast" +
".StringTable\022H\n\nname_table\030\002 \002(\01324.org.j" +
"etbrains.kotlin.serialization.js.ast.Nam",
"eTable\022E\n\010fragment\030\003 \002(\01323.org.jetbrains" +
".kotlin.serialization.js.ast.Fragment*@\n" +
"\013SideEffects\022\021\n\rAFFECTS_STATE\020\001\022\024\n\020DEPEN" +
"DS_ON_STATE\020\002\022\010\n\004PURE\020\003*?\n\016InlineStrateg" +
"y\022\017\n\013AS_FUNCTION\020\000\022\014\n\010IN_PLACE\020\001\022\016\n\nNOT_" +
"INLINE\020\002*\275\001\n\017SpecialFunction\022\032\n\026DEFINE_I" +
"NLINE_FUNCTION\020\001\022\021\n\rWRAP_FUNCTION\020\002\022\021\n\rT" +
"O_BOXED_CHAR\020\003\022\016\n\nUNBOX_CHAR\020\004\022\020\n\014SUSPEN" +
"D_CALL\020\005\022\024\n\020COROUTINE_RESULT\020\006\022\030\n\024COROUT" +
"INE_CONTROLLER\020\007\022\026\n\022COROUTINE_RECEIVER\020\010",
"B\024B\022DebugJsAstProtoBuf"
" \002(\005\"\214\001\n\nClassModel\022\017\n\007name_id\030\001 \002(\005\022\025\n\r" +
"super_name_id\030\002 \001(\005\022V\n\026post_declaration_" +
"block\030\003 \001(\01326.org.jetbrains.kotlin.seria" +
"lization.js.ast.GlobalBlock\";\n\014InlineMod" +
"ule\022\024\n\014signature_id\030\001 \002(\005\022\025\n\rexpression_" +
"id\030\002 \002(\005\"\034\n\013StringTable\022\r\n\005entry\030\001 \003(\t\"K" +
"\n\tNameTable\022>\n\005entry\030\001 \003(\0132/.org.jetbrai",
"ns.kotlin.serialization.js.ast.Name\"\263\001\n\004" +
"Name\022\021\n\ttemporary\030\001 \002(\010\022\022\n\nidentifier\030\002 " +
"\001(\005\022\025\n\rlocal_name_id\030\003 \001(\005\022\027\n\010imported\030\004" +
" \001(\010:\005false\022T\n\020special_function\030\005 \001(\0162:." +
"org.jetbrains.kotlin.serialization.js.as" +
"t.SpecialFunction\"\346\001\n\005Chunk\022L\n\014string_ta" +
"ble\030\001 \002(\01326.org.jetbrains.kotlin.seriali" +
"zation.js.ast.StringTable\022H\n\nname_table\030" +
"\002 \002(\01324.org.jetbrains.kotlin.serializati" +
"on.js.ast.NameTable\022E\n\010fragment\030\003 \002(\01323.",
"org.jetbrains.kotlin.serialization.js.as" +
"t.Fragment*@\n\013SideEffects\022\021\n\rAFFECTS_STA" +
"TE\020\001\022\024\n\020DEPENDS_ON_STATE\020\002\022\010\n\004PURE\020\003*?\n\016" +
"InlineStrategy\022\017\n\013AS_FUNCTION\020\000\022\014\n\010IN_PL" +
"ACE\020\001\022\016\n\nNOT_INLINE\020\002*\275\001\n\017SpecialFunctio" +
"n\022\032\n\026DEFINE_INLINE_FUNCTION\020\001\022\021\n\rWRAP_FU" +
"NCTION\020\002\022\021\n\rTO_BOXED_CHAR\020\003\022\016\n\nUNBOX_CHA" +
"R\020\004\022\020\n\014SUSPEND_CALL\020\005\022\024\n\020COROUTINE_RESUL" +
"T\020\006\022\030\n\024COROUTINE_CONTROLLER\020\007\022\026\n\022COROUTI" +
"NE_RECEIVER\020\010B\024B\022DebugJsAstProtoBuf"
};
org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
@@ -49871,7 +49715,7 @@ public final class DebugJsAstProtoBuf {
internal_static_org_jetbrains_kotlin_serialization_js_ast_ClassModel_fieldAccessorTable = new
org.jetbrains.kotlin.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_org_jetbrains_kotlin_serialization_js_ast_ClassModel_descriptor,
new java.lang.String[] { "NameId", "SuperNameId", "InterfaceNameId", "PostDeclarationBlock", });
new java.lang.String[] { "NameId", "SuperNameId", "PostDeclarationBlock", });
internal_static_org_jetbrains_kotlin_serialization_js_ast_InlineModule_descriptor =
getDescriptor().getMessageTypes().get(50);
internal_static_org_jetbrains_kotlin_serialization_js_ast_InlineModule_fieldAccessorTable = new

View File

@@ -1,5 +1,5 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: core/descriptors.jvm/src/jvm_package_table.debug.proto
// source: core/descriptor.loader.java/src/jvm_package_table.debug.proto
package org.jetbrains.kotlin.serialization.jvm;
@@ -3379,21 +3379,21 @@ public final class DebugJvmPackageTable {
descriptor;
static {
java.lang.String[] descriptorData = {
"\n6core/descriptors.jvm/src/jvm_package_t" +
"able.debug.proto\022&org.jetbrains.kotlin.s" +
"erialization.jvm\"\303\001\n\014PackageTable\022K\n\rpac" +
"kage_parts\030\001 \003(\01324.org.jetbrains.kotlin." +
"serialization.jvm.PackageParts\022L\n\016metada" +
"ta_parts\030\002 \003(\01324.org.jetbrains.kotlin.se" +
"rialization.jvm.PackageParts\022\030\n\020jvm_pack" +
"age_name\030\003 \003(\t\"\366\001\n\014PackageParts\022\027\n\017packa" +
"ge_fq_name\030\001 \002(\t\022\030\n\020short_class_name\030\002 \003" +
"(\t\022*\n\036multifile_facade_short_name_id\030\003 \003",
"(\005B\002\020\001\022#\n\033multifile_facade_short_name\030\004 " +
"\003(\t\022.\n&class_with_jvm_package_name_short" +
"_name\030\005 \003(\t\0222\n&class_with_jvm_package_na" +
"me_package_id\030\006 \003(\005B\002\020\001B\026B\024DebugJvmPacka" +
"geTable"
"\n=core/descriptor.loader.java/src/jvm_pa" +
"ckage_table.debug.proto\022&org.jetbrains.k" +
"otlin.serialization.jvm\"\303\001\n\014PackageTable" +
"\022K\n\rpackage_parts\030\001 \003(\01324.org.jetbrains." +
"kotlin.serialization.jvm.PackageParts\022L\n" +
"\016metadata_parts\030\002 \003(\01324.org.jetbrains.ko" +
"tlin.serialization.jvm.PackageParts\022\030\n\020j" +
"vm_package_name\030\003 \003(\t\"\366\001\n\014PackageParts\022\027" +
"\n\017package_fq_name\030\001 \002(\t\022\030\n\020short_class_n" +
"ame\030\002 \003(\t\022*\n\036multifile_facade_short_name",
"_id\030\003 \003(\005B\002\020\001\022#\n\033multifile_facade_short_" +
"name\030\004 \003(\t\022.\n&class_with_jvm_package_nam" +
"e_short_name\030\005 \003(\t\0222\n&class_with_jvm_pac" +
"kage_name_package_id\030\006 \003(\005B\002\020\001B\026B\024DebugJ" +
"vmPackageTable"
};
org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {

View File

@@ -1,5 +1,5 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: core/descriptors.jvm/src/jvm_descriptors.debug.proto
// source: core/descriptor.loader.java/src/jvm_descriptors.debug.proto
package org.jetbrains.kotlin.serialization.jvm;
@@ -4655,62 +4655,62 @@ public final class DebugJvmProtoBuf {
descriptor;
static {
java.lang.String[] descriptorData = {
"\n4core/descriptors.jvm/src/jvm_descripto" +
"rs.debug.proto\022&org.jetbrains.kotlin.ser" +
"ialization.jvm\0320core/deserialization/src" +
"/ext_options.debug.proto\0320core/deseriali" +
"zation/src/descriptors.debug.proto\"\244\003\n\020S" +
"tringTableTypes\022O\n\006record\030\001 \003(\0132?.org.je" +
"tbrains.kotlin.serialization.jvm.StringT" +
"ableTypes.Record\022\026\n\nlocal_name\030\005 \003(\005B\002\020\001" +
"\032\246\002\n\006Record\022\020\n\005range\030\001 \001(\005:\0011\022\030\n\020predefi" +
"ned_index\030\002 \001(\005\022\016\n\006string\030\006 \001(\t\022b\n\topera",
"tion\030\003 \001(\0162I.org.jetbrains.kotlin.serial" +
"ization.jvm.StringTableTypes.Record.Oper" +
"ation:\004NONE\022\033\n\017substring_index\030\004 \003(\005B\002\020\001" +
"\022\030\n\014replace_char\030\005 \003(\005B\002\020\001\"E\n\tOperation\022" +
"\010\n\004NONE\020\000\022\030\n\024INTERNAL_TO_CLASS_ID\020\001\022\024\n\020D" +
"ESC_TO_CLASS_ID\020\002\"<\n\022JvmMethodSignature\022" +
"\022\n\004name\030\001 \001(\005B\004\230\265\030\001\022\022\n\004desc\030\002 \001(\005B\004\230\265\030\001\"" +
";\n\021JvmFieldSignature\022\022\n\004name\030\001 \001(\005B\004\230\265\030\001" +
"\022\022\n\004desc\030\002 \001(\005B\004\230\265\030\001\"\316\002\n\024JvmPropertySign" +
"ature\022H\n\005field\030\001 \001(\01329.org.jetbrains.kot",
"lin.serialization.jvm.JvmFieldSignature\022" +
"T\n\020synthetic_method\030\002 \001(\0132:.org.jetbrain" +
"s.kotlin.serialization.jvm.JvmMethodSign" +
"ature\022J\n\006getter\030\003 \001(\0132:.org.jetbrains.ko" +
"tlin.serialization.jvm.JvmMethodSignatur" +
"e\022J\n\006setter\030\004 \001(\0132:.org.jetbrains.kotlin" +
".serialization.jvm.JvmMethodSignature:\212\001" +
"\n\025constructor_signature\022/.org.jetbrains." +
"kotlin.serialization.Constructor\030d \001(\0132:" +
".org.jetbrains.kotlin.serialization.jvm.",
"JvmMethodSignature:\202\001\n\020method_signature\022" +
",.org.jetbrains.kotlin.serialization.Fun" +
"ction\030d \001(\0132:.org.jetbrains.kotlin.seria" +
"lization.jvm.JvmMethodSignature:\206\001\n\022prop" +
"erty_signature\022,.org.jetbrains.kotlin.se" +
"rialization.Property\030d \001(\0132<.org.jetbrai" +
"ns.kotlin.serialization.jvm.JvmPropertyS" +
"ignature:q\n\017type_annotation\022(.org.jetbra" +
"ins.kotlin.serialization.Type\030d \003(\0132..or" +
"g.jetbrains.kotlin.serialization.Annotat",
"ion:8\n\006is_raw\022(.org.jetbrains.kotlin.ser" +
"ialization.Type\030e \001(\010:\204\001\n\031type_parameter" +
"_annotation\0221.org.jetbrains.kotlin.seria" +
"lization.TypeParameter\030d \003(\0132..org.jetbr" +
"ains.kotlin.serialization.Annotation:J\n\021" +
"class_module_name\022).org.jetbrains.kotlin" +
".serialization.Class\030e \001(\005B\004\230\265\030\001:u\n\024clas" +
"s_local_variable\022).org.jetbrains.kotlin." +
"serialization.Class\030f \003(\0132,.org.jetbrain" +
"s.kotlin.serialization.Property:N\n\023packa",
"ge_module_name\022+.org.jetbrains.kotlin.se" +
"rialization.Package\030e \001(\005B\004\230\265\030\001:y\n\026packa" +
"ge_local_variable\022+.org.jetbrains.kotlin" +
".serialization.Package\030f \003(\0132,.org.jetbr" +
"ains.kotlin.serialization.PropertyB\022B\020De" +
"bugJvmProtoBuf"
"\n;core/descriptor.loader.java/src/jvm_de" +
"scriptors.debug.proto\022&org.jetbrains.kot" +
"lin.serialization.jvm\0320core/deserializat" +
"ion/src/ext_options.debug.proto\0320core/de" +
"serialization/src/descriptors.debug.prot" +
"o\"\244\003\n\020StringTableTypes\022O\n\006record\030\001 \003(\0132?" +
".org.jetbrains.kotlin.serialization.jvm." +
"StringTableTypes.Record\022\026\n\nlocal_name\030\005 " +
"\003(\005B\002\020\001\032\246\002\n\006Record\022\020\n\005range\030\001 \001(\005:\0011\022\030\n\020" +
"predefined_index\030\002 \001(\005\022\016\n\006string\030\006 \001(\t\022b",
"\n\toperation\030\003 \001(\0162I.org.jetbrains.kotlin" +
".serialization.jvm.StringTableTypes.Reco" +
"rd.Operation:\004NONE\022\033\n\017substring_index\030\004 " +
"\003(\005B\002\020\001\022\030\n\014replace_char\030\005 \003(\005B\002\020\001\"E\n\tOpe" +
"ration\022\010\n\004NONE\020\000\022\030\n\024INTERNAL_TO_CLASS_ID" +
"\020\001\022\024\n\020DESC_TO_CLASS_ID\020\002\"<\n\022JvmMethodSig" +
"nature\022\022\n\004name\030\001 \001(\005B\004\230\265\030\001\022\022\n\004desc\030\002 \001(\005" +
"B\004\230\265\030\001\";\n\021JvmFieldSignature\022\022\n\004name\030\001 \001(" +
"\005B\004\230\265\030\001\022\022\n\004desc\030\002 \001(\005B\004\230\265\030\001\"\316\002\n\024JvmPrope" +
"rtySignature\022H\n\005field\030\001 \001(\01329.org.jetbra",
"ins.kotlin.serialization.jvm.JvmFieldSig" +
"nature\022T\n\020synthetic_method\030\002 \001(\0132:.org.j" +
"etbrains.kotlin.serialization.jvm.JvmMet" +
"hodSignature\022J\n\006getter\030\003 \001(\0132:.org.jetbr" +
"ains.kotlin.serialization.jvm.JvmMethodS" +
"ignature\022J\n\006setter\030\004 \001(\0132:.org.jetbrains" +
".kotlin.serialization.jvm.JvmMethodSigna" +
"ture:\212\001\n\025constructor_signature\022/.org.jet" +
"brains.kotlin.serialization.Constructor\030" +
"d \001(\0132:.org.jetbrains.kotlin.serializati",
"on.jvm.JvmMethodSignature:\202\001\n\020method_sig" +
"nature\022,.org.jetbrains.kotlin.serializat" +
"ion.Function\030d \001(\0132:.org.jetbrains.kotli" +
"n.serialization.jvm.JvmMethodSignature:\206" +
"\001\n\022property_signature\022,.org.jetbrains.ko" +
"tlin.serialization.Property\030d \001(\0132<.org." +
"jetbrains.kotlin.serialization.jvm.JvmPr" +
"opertySignature:q\n\017type_annotation\022(.org" +
".jetbrains.kotlin.serialization.Type\030d \003" +
"(\0132..org.jetbrains.kotlin.serialization.",
"Annotation:8\n\006is_raw\022(.org.jetbrains.kot" +
"lin.serialization.Type\030e \001(\010:\204\001\n\031type_pa" +
"rameter_annotation\0221.org.jetbrains.kotli" +
"n.serialization.TypeParameter\030d \003(\0132..or" +
"g.jetbrains.kotlin.serialization.Annotat" +
"ion:J\n\021class_module_name\022).org.jetbrains" +
".kotlin.serialization.Class\030e \001(\005B\004\230\265\030\001:" +
"u\n\024class_local_variable\022).org.jetbrains." +
"kotlin.serialization.Class\030f \003(\0132,.org.j" +
"etbrains.kotlin.serialization.Property:N",
"\n\023package_module_name\022+.org.jetbrains.ko" +
"tlin.serialization.Package\030e \001(\005B\004\230\265\030\001:y" +
"\n\026package_local_variable\022+.org.jetbrains" +
".kotlin.serialization.Package\030f \003(\0132,.or" +
"g.jetbrains.kotlin.serialization.Propert" +
"yB\022B\020DebugJvmProtoBuf"
};
org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {

View File

@@ -9,7 +9,7 @@ import org.jetbrains.kotlin.gradle.tasks.Kotlin2JsCompile
buildscript {
extra["defaultSnapshotVersion"] = "1.2-SNAPSHOT"
kotlinBootstrapFrom(BootstrapOption.TeamCity("1.2.0-dev-439", onlySuccessBootstrap = false))
kotlinBootstrapFrom(BootstrapOption.TeamCity("1.2.0-dev-92", onlySuccessBootstrap = false))
val repos = listOfNotNull(
bootstrapKotlinRepo,
@@ -23,7 +23,7 @@ buildscript {
repositories {
for (repo in repos) {
maven(url = repo)
maven { setUrl(repo) }
}
}
@@ -64,10 +64,12 @@ allprojects {
extra["kotlin_root"] = rootDir
val bootstrapCompileCfg = configurations.create("bootstrapCompile")
val scriptCompileCfg = configurations.create("scriptCompile").extendsFrom(bootstrapCompileCfg)
val scriptRuntimeCfg = configurations.create("scriptRuntime").extendsFrom(scriptCompileCfg)
repositories {
for (repo in (rootProject.extra["repos"] as List<String>)) {
maven(url = repo)
maven { setUrl(repo) }
}
}
@@ -117,39 +119,35 @@ extra["versions.android"] = "2.3.1"
extra["ideaCoreSdkJars"] = arrayOf("annotations", "asm-all", "guava", "intellij-core", "jdom", "jna", "log4j", "picocontainer",
"snappy-in-java", "streamex", "trove4j", "xpp3-1.1.4-min", "xstream")
extra["compilerModules"] = arrayOf(
":compiler:util",
":compiler:container",
":compiler:conditional-preprocessor",
":compiler:resolution",
":compiler:serialization",
":compiler:frontend",
":compiler:frontend.java",
":compiler:frontend.script",
":compiler:cli-common",
":compiler:daemon-common",
":compiler:daemon",
":compiler:ir.tree",
":compiler:ir.psi2ir",
":compiler:backend-common",
":compiler:backend",
":compiler:plugin-api",
":compiler:light-classes",
":compiler:cli",
":compiler:incremental-compilation-impl",
":js:js.ast",
":js:js.serializer",
":js:js.parser",
":js:js.frontend",
":js:js.translator",
":js:js.dce",
":compiler",
":kotlin-build-common",
":core:descriptors",
":core:descriptors.jvm",
":core:deserialization",
":core:util.runtime"
)
extra["compilerModules"] = arrayOf(":compiler:util",
":compiler:container",
":compiler:conditional-preprocessor",
":compiler:resolution",
":compiler:serialization",
":compiler:frontend",
":compiler:frontend.java",
":compiler:frontend.script",
":compiler:cli-common",
":compiler:daemon-common",
":compiler:daemon",
":compiler:ir.tree",
":compiler:ir.psi2ir",
":compiler:backend-common",
":compiler:backend",
":compiler:plugin-api",
":compiler:light-classes",
":compiler:cli",
":compiler:incremental-compilation-impl",
":js:js.ast",
":js:js.serializer",
":js:js.parser",
":js:js.frontend",
":js:js.translator",
":js:js.dce",
":compiler",
":kotlin-build-common",
":core:util.runtime",
":core")
val coreLibProjects = listOf(
":kotlin-stdlib",
@@ -219,7 +217,6 @@ fun Task.listConfigurationContents(configName: String) {
val defaultJvmTarget = "1.8"
val defaultJavaHome = jdkPath(defaultJvmTarget!!)
val ignoreTestFailures by extra(project.findProperty("ignoreTestFailures")?.toString()?.toBoolean() ?: project.hasProperty("teamcity"))
allprojects {
@@ -239,26 +236,14 @@ allprojects {
}
configureJvmProject(javaHome!!, jvmTarget!!)
val commonCompilerArgs = listOf("-Xallow-kotlin-package")
tasks.withType<org.jetbrains.kotlin.gradle.dsl.KotlinCompile<*>> {
kotlinOptions {
languageVersion = kotlinLanguageVersion
apiVersion = kotlinLanguageVersion
freeCompilerArgs = commonCompilerArgs
freeCompilerArgs = listOf("-Xallow-kotlin-package", "-Xnormalize-constructor-calls=enable")
}
}
tasks.withType<org.jetbrains.kotlin.gradle.dsl.KotlinJvmCompile> {
kotlinOptions {
freeCompilerArgs = commonCompilerArgs + listOf("-Xnormalize-constructor-calls=enable")
}
}
tasks.withType(VerificationTask::class.java as Class<Task>) {
(this as VerificationTask).ignoreFailures = ignoreTestFailures
}
tasks.withType<Javadoc> {
enabled = false
}
@@ -304,6 +289,11 @@ task<Copy>("ideaPlugin") {
into("$ideaPluginDir/lib")
}
task("dist-plugin") {
dependsOn("ideaPlugin")
doFirst { logger.warn("'$name' task is deprecated, use '${dependsOn.last()}' instead") }
}
tasks {
"clean" {
doLast {
@@ -329,6 +319,11 @@ tasks {
}
}
"gradlePluginsTest" {
// deprecated
dependsOn("gradlePluginTest")
}
"gradlePluginIntegrationTest" {
dependsOn(":kotlin-gradle-plugin-integration-tests:check")
}
@@ -340,9 +335,18 @@ tasks {
":compiler:tests-java8:test")
}
"compiler-tests" {
dependsOn("jvmCompilerTest")
doFirst { logger.warn("'$name' task is deprecated, use '${dependsOn.last()}' instead") }
}
"jsCompilerTest" {
dependsOn(":js:js.tests:test")
dependsOn(":js:js.tests:runMocha")
}
"js-tests" {
dependsOn("jsCompilerTest")
doFirst { logger.warn("'$name' task is deprecated, use '${dependsOn.last()}' instead") }
}
"scriptingTest" {
@@ -350,6 +354,11 @@ tasks {
dependsOn(":kotlin-script-util:test")
}
"scripting-tests" {
dependsOn("scriptingTest")
doFirst { logger.warn("'$name' task is deprecated, use '${dependsOn.last()}' instead") }
}
"compilerTest" {
dependsOn("jvmCompilerTest")
dependsOn("jsCompilerTest")
@@ -371,9 +380,6 @@ tasks {
dependsOn("examplesTest")
}
"androidCodegenTest" {
dependsOn(":compiler:android-tests:test")
}
"jps-tests" {
dependsOn("dist")
@@ -399,11 +405,12 @@ tasks {
"idea-plugin-additional-tests")
}
"android-ide-tests" {
"android-tests" {
dependsOn("dist")
dependsOn(":plugins:android-extensions-ide:test",
":idea:idea-android:test",
":kotlin-annotation-processing:test")
":kotlin-annotation-processing:test",
":compiler:android-tests:test")
}
"plugins-tests" {
@@ -415,13 +422,20 @@ tasks {
":kotlin-annotation-processing-gradle:test")
}
"other-tests" {
dependsOn("dist")
dependsOn(":kotlin-build-common:test",
":generators:test")
doFirst { logger.warn("'$name' task is deprecated") }
}
"ideaPluginTest" {
dependsOn(
"idea-plugin-tests",
"jps-tests",
"plugins-tests",
"android-ide-tests",
"android-tests",
":generators:test"
)
}
@@ -462,16 +476,18 @@ fun jdkPath(version: String): String = jdkPathIfFound(version)
?: throw GradleException ("Please set environment variable JDK_${version.replace(".", "")} to point to JDK $version installation")
fun Project.configureJvmProject(javaHome: String, javaVersion: String) {
tasks.withType<JavaCompile> {
options.isFork = true
options.forkOptions.javaHome = file(javaHome)
options.compilerArgs.add("-proc:none")
options.encoding = "UTF-8"
}
tasks.withType<KotlinCompile> {
kotlinOptions.jdkHome = javaHome
kotlinOptions.jvmTarget = javaVersion
doFirst {
System.setProperty("kotlin.colors.enabled", "false")
}
}
tasks.withType<Test> {

View File

@@ -79,8 +79,8 @@
<typedef name="skip" classname="com.intellij.ant.ClassFilterAnnotationRegexp" classpathref="javac2.classpath" loaderref="javac2.loader"/>
<dirset id="compilerSources.dirset" dir="${basedir}/">
<include name="core/descriptor.loader.java/src"/>
<include name="core/descriptors/src"/>
<include name="core/descriptors.jvm/src"/>
<include name="core/deserialization/src"/>
<include name="core/util.runtime/src"/>
<include name="compiler/backend/src"/>
@@ -125,7 +125,7 @@
<include name="descriptors/**"/>
<include name="deserialization/**"/>
<include name="serialization/**"/>
<include name="descriptors.jvm/**"/>
<include name="descriptor.loader.java/**"/>
<include name="frontend.java/**"/>
<include name="backend/**"/>
<include name="backend-common/**"/>
@@ -246,8 +246,8 @@
<target name="compiler-sources">
<jar jarfile="${output}/kotlin-compiler-sources.jar">
<!-- TODO How to convert it from pathset or dirset ? -->
<fileset dir="core/descriptor.loader.java/src"/>
<fileset dir="core/descriptors/src"/>
<fileset dir="core/descriptors.jvm/src"/>
<fileset dir="core/deserialization/src"/>
<fileset dir="core/util.runtime/src"/>
<fileset dir="compiler/backend/src"/>
@@ -372,14 +372,16 @@
<include name="kotlin/**"/>
</fileset>
<fileset dir="${basedir}/core/deserialization/src" includes="META-INF/services/**"/>
<fileset dir="${basedir}/core/descriptors.jvm/src" includes="META-INF/services/**"/>
<fileset dir="${basedir}/core/descriptor.loader.java/src" includes="META-INF/services/**"/>
<fileset dir="${basedir}/compiler/frontend.java/src" includes="META-INF/services/**"/>
<fileset dir="${basedir}/compiler/backend/src" includes="META-INF/services/**"/>
<fileset dir="${basedir}/compiler/cli/src" includes="META-INF/services/**"/>
<fileset dir="${basedir}/resources" includes="kotlinManifest.properties"/>
<fileset dir="idea/src">
<include name="META-INF/extensions/compiler.xml"/>
<include name="META-INF/extensions/common.xml"/>
<include name="META-INF/extensions/kotlin2jvm.xml"/>
<include name="META-INF/extensions/kotlin2js.xml"/>
</fileset>
<zipgroupfileset dir="${basedir}/lib" includes="*.jar"/>

View File

@@ -1,12 +1,12 @@
buildscript {
val buildSrcKotlinVersion: String by extra(findProperty("buildSrc.kotlin.version")?.toString() ?: embeddedKotlinVersion)
val buildSrcKotlinRepo: String? by extra(findProperty("buildSrc.kotlin.repo") as String?)
extra["buildSrcKotlinRepo"] = findProperty("buildSrc.kotlin.repo")
extra["versions.shadow"] = "2.0.1"
repositories {
buildSrcKotlinRepo?.let {
maven(url = it)
extra["buildSrcKotlinRepo"]?.let {
maven { setUrl(it) }
}
}
@@ -31,7 +31,7 @@ plugins {
repositories {
extra["buildSrcKotlinRepo"]?.let {
maven(url = it)
maven { setUrl(it) }
}
maven(url = "https://dl.bintray.com/kotlin/kotlin-dev") // for dex-method-list
// maven { setUrl("https://repo.gradle.org/gradle/libs-releases-local") }
@@ -45,7 +45,6 @@ dependencies {
// TODO: adding the dep to the plugin breaks the build unexpectedly, resolve and uncomment
// compile("org.jetbrains.kotlin:kotlin-gradle-plugin:${rootProject.extra["bootstrap_kotlin_version"]}")
compile("com.github.jengelman.gradle.plugins:shadow:${property("versions.shadow")}")
compile("org.ow2.asm:asm-all:6.0_BETA")
}
samWithReceiver {

View File

@@ -62,9 +62,3 @@ var Project.jvmTarget: String?
var Project.javaHome: String?
get() = extra.takeIf { it.has("javaHome") }?.get("javaHome") as? String
set(v) { extra["javaHome"] = v }
fun Project.generator(fqName: String) = task<JavaExec> {
classpath = the<JavaPluginConvention>().sourceSets["test"].runtimeClasspath
main = fqName
workingDir = rootDir
}

View File

@@ -65,11 +65,11 @@ fun Project.ideaUltimatePluginDeps(vararg artifactBaseNames: String, plugin: Str
fun Project.kotlinDep(artifactBaseName: String, version: String): String = "org.jetbrains.kotlin:kotlin-$artifactBaseName:$version"
fun DependencyHandler.projectDist(name: String): ProjectDependency = project(name, configuration = "distJar").apply { isTransitive = false }
fun DependencyHandler.projectTests(name: String): ProjectDependency = project(name, configuration = "tests-jar")
fun DependencyHandler.projectRuntimeJar(name: String): ProjectDependency = project(name, configuration = "runtimeJar")
fun DependencyHandler.projectArchives(name: String): ProjectDependency = project(name, configuration = "archives")
fun DependencyHandler.projectClasses(name: String): ProjectDependency = project(name, configuration = "classes-dirs")
fun DependencyHandler.projectDist(name: String): Dependency = project(name, configuration = "distJar").apply { isTransitive = false }
fun DependencyHandler.projectTests(name: String): Dependency = project(name, configuration = "tests-jar").apply { isTransitive = false }
fun DependencyHandler.projectRuntimeJar(name: String): Dependency = project(name, configuration = "runtimeJar")
fun DependencyHandler.projectArchives(name: String): Dependency = project(name, configuration = "archives")
fun DependencyHandler.projectClasses(name: String): Dependency = project(name, configuration = "classes-dirs")
val protobufLiteProject = ":custom-dependencies:protobuf-lite"
fun DependencyHandler.protobufLite(): ProjectDependency =

View File

@@ -4,7 +4,7 @@ import org.codehaus.groovy.runtime.InvokerHelper
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.maven.MavenDeployment
import org.gradle.api.artifacts.maven.MavenDeployer
import org.gradle.api.artifacts.maven.MavenResolver
import org.gradle.api.plugins.MavenRepositoryHandlerConvention
@@ -100,16 +100,21 @@ open class PublishedKotlinModule : Plugin<Project> {
var repository: MavenRemoteRepository by Delegates.notNull()
val signPom = rootProject.extra["signPom"] as groovy.lang.Closure<*>
repositories {
withConvention(MavenRepositoryHandlerConvention::class) {
mavenDeployer {
signPom.call(project, this as MavenDeployer)
withGroovyBuilder {
"beforeDeployment" {
val signing = project.the<SigningExtension>()
if (signing.isRequired)
signing.signPom(delegate as MavenDeployment)
}
// TODO: Use with kotlin-dsl 0.12+ instead of signPom
// "beforeDeployment" {
// val signing = project.the<SigningExtension>()
// if (signing.isRequired)
// signing.signPom(this as MavenDeployment)
// }
"repository"("url" to repoUrl)!!.also { repository = it as MavenRemoteRepository }.withGroovyBuilder {
if (username != null && password != null) {

View File

@@ -1,19 +1,3 @@
/*
* Copyright 2010-2017 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.
*/
@file:Suppress("unused") // usages in build scripts are not tracked properly
import org.gradle.api.Project
@@ -56,16 +40,6 @@ fun Project.projectTest(taskName: String = "test", body: Test.() -> Unit = {}):
}
}
doFirst {
val agent = tasks.findByPath(":test-instrumenter:jar")!!.outputs.files.singleFile
val args = project.findProperty("kotlin.test.instrumentation.args")?.let { "=$it" }.orEmpty()
jvmArgs("-javaagent:$agent$args")
}
dependsOn(":test-instrumenter:jar")
jvmArgs("-ea", "-XX:+HeapDumpOnOutOfMemoryError", "-Xmx1100m", "-XX:+UseCodeCacheFlushing", "-XX:ReservedCodeCacheSize=128m", "-Djna.nosys=true")
maxHeapSize = "1100m"
systemProperty("idea.is.unit.test", "true")
@@ -73,7 +47,7 @@ fun Project.projectTest(taskName: String = "test", body: Test.() -> Unit = {}):
environment("PROJECT_CLASSES_DIRS", the<JavaPluginConvention>().sourceSets.getByName("test").output.classesDirs.asPath)
environment("PROJECT_BUILD_DIR", buildDir)
systemProperty("jps.kotlin.home", rootProject.extra["distKotlinHomeDir"])
systemProperty("kotlin.ni", if (rootProject.hasProperty("newInferenceTests")) "true" else "false")
ignoreFailures = System.getenv("kotlin_build_ignore_test_failures")?.let { it == "yes" } ?: false
body()
}

View File

@@ -0,0 +1,36 @@
// Have to stay in the separate dir: attempt to move it to the source root dir lead to invalid import into IDEA
apply { plugin("kotlin") }
dependencies {
compile(project(":core"))
compile(project(":core::util.runtime"))
compile(project(":compiler:util"))
compile(project(":compiler:backend"))
compile(project(":compiler:frontend"))
compile(project(":compiler:frontend.java"))
compile(project(":compiler:util"))
compile(project(":compiler:cli-common"))
compile(project(":compiler:cli"))
compile(project(":compiler:light-classes"))
compile(project(":compiler:serialization"))
compile(project(":kotlin-preloader"))
compile(project(":compiler:daemon-common"))
compile(project(":kotlin-daemon-client"))
compile(project(":js:js.serializer"))
compile(project(":js:js.frontend"))
compile(project(":js:js.translator"))
compileOnly(project(":plugins:android-extensions-compiler"))
compile(project(":kotlin-test:kotlin-test-jvm"))
compile(project(":compiler:tests-common-jvm6"))
compile(commonDep("junit:junit"))
compile(ideaSdkCoreDeps("intellij-core"))
compile(ideaSdkDeps("openapi", "idea", "idea_rt"))
compile(preloadedDeps("dx", subdir = "android-5.0/lib"))
}
sourceSets {
"main" { java.srcDir("../compiler/tests-common") }
"test" {}
}

View File

@@ -7,7 +7,7 @@ buildscript {
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0'
classpath 'com.android.tools.build:gradle:3.0.0-beta4'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
@@ -22,7 +22,7 @@ repositories {
android {
compileSdkVersion 19
buildToolsVersion "26.0.2"
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "org.jetbrains.kotlin.android.tests"

View File

@@ -6,20 +6,18 @@ jvmTarget = "1.6"
dependencies {
compile(project(":compiler:util"))
compile(project(":compiler:cli"))
compile(project(":compiler.tests-common"))
compile(project(":compiler:frontend"))
compile(project(":compiler:backend"))
compile(projectTests(":compiler:tests-common"))
compile(commonDep("junit:junit"))
compile(ideaSdkDeps("openapi"))
testCompile(project(":compiler:incremental-compilation-impl"))
testCompile(project(":core:descriptors"))
testCompile(project(":core:descriptors.jvm"))
testCompile(project(":core"))
testCompile(project(":compiler:frontend.java"))
testCompile(projectTests(":jps-plugin"))
testCompile(commonDep("junit:junit"))
testCompile(ideaSdkDeps("jps-model.jar", subdir = "jps"))
testCompile(ideaSdkDeps("groovy-all"))
testCompile(ideaSdkDeps("idea", "idea_rt"))
testCompile(ideaSdkDeps("openapi", "idea"))
testCompile(ideaSdkDeps("jps-build-test", subdir = "jps/test"))
testCompile(ideaSdkDeps("jps-builders"))
}

View File

@@ -0,0 +1,175 @@
/*
* Copyright 2010-2015 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.android.tests;
import com.intellij.util.PlatformUtils;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.android.tests.download.SDKDownloader;
import org.jetbrains.kotlin.android.tests.emulator.Emulator;
import org.jetbrains.kotlin.android.tests.gradle.GradleRunner;
import org.jetbrains.kotlin.android.tests.run.PermissionManager;
import org.junit.Assert;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CodegenTestsOnAndroidRunner {
private final PathManager pathManager;
public static TestSuite getTestSuite(PathManager pathManager) {
return new CodegenTestsOnAndroidRunner(pathManager).generateTestSuite();
}
private CodegenTestsOnAndroidRunner(PathManager pathManager) {
this.pathManager = pathManager;
}
private TestSuite generateTestSuite() {
TestSuite suite = new TestSuite("MySuite");
String resultOutput = runTests();
String reportFolder = pathManager.getTmpFolder() + "/build/outputs/androidTest-results/connected";
try {
List<TestCase> testCases = parseSingleReportInFolder(reportFolder);
for (TestCase aCase : testCases) {
suite.addTest(aCase);
}
Assert.assertNotEquals("There is no test results in report", 0, testCases.size());
}
catch (Exception e) {
throw new RuntimeException("Can't parse test results in " + reportFolder +"\n" + resultOutput);
}
return suite;
}
@Nullable
public String runTests() {
File rootForAndroidDependencies = new File(pathManager.getDependenciesRoot());
if (!rootForAndroidDependencies.exists()) {
rootForAndroidDependencies.mkdirs();
}
SDKDownloader downloader = new SDKDownloader(pathManager);
downloader.downloadAll();
downloader.unzipAll();
PermissionManager.setPermissions(pathManager);
Emulator emulator = new Emulator(pathManager, Emulator.ARM);
GradleRunner gradleRunner = new GradleRunner(pathManager);
gradleRunner.clean();
gradleRunner.build();
emulator.createEmulator();
String platformPrefixProperty = System.setProperty(PlatformUtils.PLATFORM_PREFIX_KEY, "Idea");
try {
emulator.startEmulator();
try {
emulator.waitEmulatorStart();
//runTestsViaAdb(emulator, gradleRunner);
return gradleRunner.connectedDebugAndroidTest();
}
catch (RuntimeException e) {
e.printStackTrace();
throw e;
}
finally {
emulator.stopEmulator();
}
}
catch (RuntimeException e) {
e.printStackTrace();
throw e;
}
finally {
if (platformPrefixProperty != null) {
System.setProperty(PlatformUtils.PLATFORM_PREFIX_KEY, platformPrefixProperty);
}
else {
System.clearProperty(PlatformUtils.PLATFORM_PREFIX_KEY);
}
emulator.finishEmulatorProcesses();
}
}
private String runTestsViaAdb(Emulator emulator, GradleRunner gradleRunner) {
gradleRunner.installDebugAndroidTest();
String result = emulator.runTestsViaAdb();
System.out.println(result);
gradleRunner.uninstallDebugAndroidTest();
return result;
}
private static List<TestCase> parseSingleReportInFolder(String reportFolder) throws
IOException,
SAXException,
ParserConfigurationException {
File folder = new File(reportFolder);
File[] files = folder.listFiles();
assert files != null;
assert files.length == 1;
File reportFile = files[0];
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(reportFile);
Element root = doc.getDocumentElement();
NodeList testCases = root.getElementsByTagName("testcase");
List<TestCase> result = new ArrayList(testCases.getLength());
for (int i = 0; i < testCases.getLength(); i++) {
Element item = (Element) testCases.item(i);
NodeList failure = item.getElementsByTagName("failure");
String name = item.getAttribute("name");
String clazz = item.getAttribute("classname");
if (failure.getLength() == 0) {
result.add(new TestCase(name) {
@Override
protected void runTest() throws Throwable {
}
});
}
else {
result.add(new TestCase(name) {
@Override
protected void runTest() throws Throwable {
Assert.fail(failure.item(0).getTextContent());
}
});
}
}
return result;
}
}

View File

@@ -1,189 +0,0 @@
/*
* Copyright 2010-2015 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.android.tests
import com.intellij.util.PlatformUtils
import junit.framework.TestCase
import junit.framework.TestSuite
import org.jetbrains.kotlin.android.tests.download.SDKDownloader
import org.jetbrains.kotlin.android.tests.emulator.Emulator
import org.jetbrains.kotlin.android.tests.gradle.GradleRunner
import org.jetbrains.kotlin.android.tests.run.PermissionManager
import org.junit.Assert
import org.w3c.dom.Element
import org.xml.sax.SAXException
import java.io.File
import java.io.IOException
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.parsers.ParserConfigurationException
class CodegenTestsOnAndroidRunner private constructor(private val pathManager: PathManager) {
private fun runTestsInEmulator(): TestSuite {
val rootSuite = TestSuite("Root")
downloadDependencies()
val emulator = Emulator(pathManager, Emulator.ARM)
emulator.createEmulator()
val gradleRunner = GradleRunner(pathManager)
//old dex
cleanAndBuildProject(gradleRunner)
try {
emulator.startEmulator()
try {
emulator.waitEmulatorStart()
runTestsOnEmulator(gradleRunner, TestSuite("Dex")).apply {
rootSuite.addTest(this)
}
enableD8(true)
runTestsOnEmulator(gradleRunner, TestSuite("D8")).apply {
(0 until this.countTestCases()).forEach {
val testCase = testAt(it) as TestCase
testCase.name += "_D8"
}
rootSuite.addTest(this)
}
}
catch (e: RuntimeException) {
e.printStackTrace()
throw e
}
finally {
emulator.stopEmulator()
}
}
catch (e: RuntimeException) {
e.printStackTrace()
throw e
}
finally {
emulator.finishEmulatorProcesses()
}
return rootSuite
}
private fun enableD8(enable: Boolean) {
val file = File(pathManager.androidTmpFolder, "gradle.properties")
val lines = file.readLines().map {
if (it.startsWith("android.enableD8=")) {
"android.enableD8=$enable"
}
else it
}
file.writeText(lines.joinToString("\n"))
}
private fun processReport(suite: TestSuite, resultOutput: String) {
val reportFolder = pathManager.tmpFolder + "/build/outputs/androidTest-results/connected"
try {
val testCases = parseSingleReportInFolder(reportFolder)
testCases.forEach { aCase -> suite.addTest(aCase) }
Assert.assertNotEquals("There is no test results in report", 0, testCases.size.toLong())
}
catch (e: Exception) {
throw RuntimeException("Can't parse test results in " + reportFolder + "\n" + resultOutput)
}
}
private fun runTestsOnEmulator(gradleRunner: GradleRunner, suite: TestSuite): TestSuite {
val platformPrefixProperty = System.setProperty(PlatformUtils.PLATFORM_PREFIX_KEY, "Idea")
try {
val resultOutput = gradleRunner.connectedDebugAndroidTest()
processReport(suite, resultOutput)
return suite
}
finally {
if (platformPrefixProperty != null) {
System.setProperty(PlatformUtils.PLATFORM_PREFIX_KEY, platformPrefixProperty)
}
else {
System.clearProperty(PlatformUtils.PLATFORM_PREFIX_KEY)
}
}
}
private fun downloadDependencies() {
val rootForAndroidDependencies = File(pathManager.dependenciesRoot)
if (!rootForAndroidDependencies.exists()) {
rootForAndroidDependencies.mkdirs()
}
val downloader = SDKDownloader(pathManager)
downloader.downloadAll()
downloader.unzipAll()
PermissionManager.setPermissions(pathManager)
}
companion object {
@JvmStatic
fun runTestsInEmulator(pathManager: PathManager): TestSuite {
return CodegenTestsOnAndroidRunner(pathManager).runTestsInEmulator()
}
private fun cleanAndBuildProject(gradleRunner: GradleRunner) {
gradleRunner.clean()
gradleRunner.build()
}
@Throws(IOException::class, SAXException::class, ParserConfigurationException::class)
private fun parseSingleReportInFolder(reportFolder: String): List<TestCase> {
val folder = File(reportFolder)
val files = folder.listFiles()!!
assert(files.size == 1)
val reportFile = files[0]
val dbFactory = DocumentBuilderFactory.newInstance()
val dBuilder = dbFactory.newDocumentBuilder()
val doc = dBuilder.parse(reportFile)
val root = doc.documentElement
val testCases = root.getElementsByTagName("testcase")
return (0 until testCases.length).map { i ->
val item = testCases.item(i) as Element
val failure = item.getElementsByTagName("failure")
val name = item.getAttribute("name")
val clazz = item.getAttribute("classname")
if (failure.length == 0) {
object : TestCase(name) {
@Throws(Throwable::class)
override fun runTest() {
}
}
}
else {
object : TestCase(name) {
@Throws(Throwable::class)
override fun runTest() {
Assert.fail(failure.item(0).textContent)
}
}
}
}
}
}
}

View File

@@ -68,10 +68,6 @@ public class PathManager {
return tmpFolder + "/src";
}
public String getAndroidTmpFolder() {
return tmpFolder;
}
public String getAndroidSdkRoot() {
return getDependenciesRoot() + "/android-sdk";
}

View File

@@ -41,9 +41,9 @@ public class SDKDownloader {
//NOTE: PLATFORM_TOOLS 23.1.0 requires only 64 bit build agents
private static final String PLATFORM_TOOLS = "23.0.1";
private static final String SDK_TOOLS = "25.1.1";
public static final String BUILD_TOOLS = "26.0.2";
public static final String BUILD_TOOLS = "26.0.1";
private static final int ANDROID_VERSION = 19;
public static final String GRADLE_VERSION = "4.3";
public static final String GRADLE_VERSION = "4.1";
public SDKDownloader(PathManager pathManager) {
@@ -62,8 +62,8 @@ public class SDKDownloader {
}
private void downloadAbi() {
download("https://dl.google.com/android/repository/sys-img/android/armeabi-v7a-" + ANDROID_VERSION + "_r05.zip", armImage); //Same for all platforms
download("https://dl.google.com/android/repository/sys-img/android/x86-" + ANDROID_VERSION + "_r06.zip", x86Image); //Same for all platforms
download("https://dl.google.com/android/repository/sys-img/android/sysimg_armv7a-" + ANDROID_VERSION + "_r03.zip", armImage); //Same for all platforms
download("https://dl.google.com/android/repository/sys-img/android/sysimg_x86-" + ANDROID_VERSION + "_r03.zip", x86Image); //Same for all platforms
}
public void downloadPlatformTools() {
@@ -127,7 +127,7 @@ public class SDKDownloader {
String buildToolsFolder = buildTools + BUILD_TOOLS + "/";
new File(buildToolsFolder).delete();
unzip(buildToolsZipPath, buildTools);
new File(buildTools + "/android-8.1.0").renameTo(new File(buildToolsFolder));
new File(buildTools + "/android-8.0.0").renameTo(new File(buildToolsFolder));
}
public void deleteAll() {

View File

@@ -74,10 +74,7 @@ public class Emulator {
commandLine.setExePath(pathManager.getToolsFolderInAndroidSdk() + "/" + emulatorCmdName);
commandLine.addParameter("-avd");
commandLine.addParameter("my_avd");
if (platform != X86) {
//problem with qemu options
commandLine.addParameter("-no-audio");
}
commandLine.addParameter("-no-audio");
commandLine.addParameter("-no-window");
return commandLine;
}

View File

@@ -33,7 +33,6 @@ public class PermissionManager {
setExecPermissionForSimpleNamedFiles(new File(pathManager.getToolsFolderInAndroidSdk() + "/bin64"));
setExecPermissionForSimpleNamedFiles(new File(pathManager.getBuildToolsFolderInAndroidSdk() + "/" + SDKDownloader.BUILD_TOOLS));
setExecPermissionForSimpleNamedFiles(new File(pathManager.getPlatformToolsFolderInAndroidSdk()));
setExecPermissionForSimpleNamedFiles(new File(pathManager.getToolsFolderInAndroidSdk() +"/qemu/linux-x86_64"));
RunUtils.execute(generateChmodCmd(pathManager.getGradleBinFolder() + "/gradle"));
}
}

View File

@@ -17,12 +17,10 @@
package org.jetbrains.kotlin.android.tests;
import org.jetbrains.kotlin.jps.build.BaseKotlinJpsBuildTestCase;
import org.junit.Ignore;
import java.io.File;
import java.io.IOException;
@Ignore
public class AndroidJpsBuildTestCase extends BaseKotlinJpsBuildTestCase {
private static final String PROJECT_NAME = "android-module";
private static final String SDK_NAME = "Android_SDK";

View File

@@ -19,17 +19,13 @@ package org.jetbrains.kotlin.android.tests;
import com.google.common.io.Files;
import com.intellij.openapi.util.io.FileUtil;
import junit.framework.TestSuite;
import kotlin.io.FilesKt;
import org.jetbrains.annotations.NotNull;
import org.junit.runner.RunWith;
import org.junit.runners.AllTests;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
@RunWith(AllTests.class)
public class AndroidRunner {
public class AndroidRunner extends TestSuite {
private static PathManager pathManager;
@@ -53,7 +49,7 @@ public class AndroidRunner {
CodegenTestsOnAndroidGenerator.generate(pathManager);
System.out.println("Run tests on android...");
TestSuite suite = CodegenTestsOnAndroidRunner.runTestsInEmulator(pathManager);
TestSuite suite = CodegenTestsOnAndroidRunner.getTestSuite(pathManager);
//AndroidJpsBuildTestCase indirectly depends on UsefulTestCase which compiled against java 8
//TODO: Need add separate run configuration for AndroidJpsBuildTestCase
//suite.addTest(new AndroidJpsBuildTestCase());
@@ -66,11 +62,10 @@ public class AndroidRunner {
}
private static void writeAndroidSkdToLocalProperties() throws IOException {
String sdkRoot = FilesKt.getInvariantSeparatorsPath(new File(pathManager.getAndroidSdkRoot()));
System.out.println("Writing android sdk to local.properties: " + sdkRoot);
System.out.println("Writing android sdk to local.properties: " + pathManager.getAndroidSdkRoot());
File file = new File(pathManager.getTmpFolder() + "/local.properties");
try (FileWriter fw = new FileWriter(file)) {
fw.write("sdk.dir=" + sdkRoot);
fw.write("sdk.dir=" + pathManager.getAndroidSdkRoot());
}
}
}

View File

@@ -42,14 +42,12 @@ import org.jetbrains.kotlin.test.*;
import org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase;
import org.jetbrains.kotlin.utils.Printer;
import org.junit.Assert;
import org.junit.Ignore;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Ignore
public class CodegenTestsOnAndroidGenerator extends KtUsefulTestCase {
private final PathManager pathManager;

View File

@@ -123,13 +123,6 @@ public class SpecialFiles {
excludedFiles.add("closureOfInnerLocalClass.kt");
excludedFiles.add("closureWithSelfInstantiation.kt");
excludedFiles.add("quotedClassName.kt");
//wrong function resolution after package renaming
excludedFiles.add("apiVersionAtLeast1.kt");
//special flags
excludedFiles.add("inlineFunInConstructorCallWithEnabledNormalization.kt");
excludedFiles.add("kt9532_lv10.kt");
}
private SpecialFiles() {

View File

@@ -4,8 +4,7 @@ apply { plugin("kotlin") }
jvmTarget = "1.6"
dependencies {
compile(project(":core:descriptors"))
compile(project(":core:descriptors.jvm"))
compile(project(":core"))
compile(project(":compiler:util"))
compile(project(":compiler:frontend"))
compile(project(":compiler:ir.tree"))

View File

@@ -17,19 +17,16 @@
package org.jetbrains.kotlin.backend.common
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.PropertyGetterDescriptor
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.DescriptorEquivalenceForOverrides
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.descriptorUtil.module
val SUSPEND_COROUTINE_OR_RETURN_NAME = Name.identifier("suspendCoroutineOrReturn")
val COROUTINE_SUSPENDED_NAME = Name.identifier("COROUTINE_SUSPENDED")
val COROUTINES_INTRINSICS_PACKAGE_FQ_NAME = DescriptorUtils.COROUTINES_PACKAGE_FQ_NAME.child(Name.identifier("intrinsics"))
val COROUTINE_CONTEXT_FQ_NAME = COROUTINES_INTRINSICS_PACKAGE_FQ_NAME.child(Name.identifier("coroutineContext"))
fun FunctionDescriptor.isBuiltInSuspendCoroutineOrReturn(): Boolean {
if (name != SUSPEND_COROUTINE_OR_RETURN_NAME) return false
@@ -45,7 +42,3 @@ fun FunctionDescriptor.getBuiltInSuspendCoroutineOrReturn() =
module.getPackage(COROUTINES_INTRINSICS_PACKAGE_FQ_NAME).memberScope
.getContributedFunctions(SUSPEND_COROUTINE_OR_RETURN_NAME, NoLookupLocation.FROM_BACKEND)
.singleOrNull()
fun FunctionDescriptor.isBuiltInCoroutineContext() =
(this as? PropertyGetterDescriptor)?.correspondingProperty?.fqNameSafe == COROUTINE_CONTEXT_FQ_NAME

View File

@@ -0,0 +1,47 @@
/*
* Copyright 2010-2015 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.codegen;
import kotlin.jvm.functions.Function0;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.storage.LockBasedStorageManager;
import org.jetbrains.kotlin.storage.NotNullLazyValue;
public class ClassBuilderOnDemand extends DelegatingClassBuilder {
private final NotNullLazyValue<ClassBuilder> classBuilder;
public ClassBuilderOnDemand(@NotNull Function0<ClassBuilder> createClassBuilder) {
this.classBuilder = LockBasedStorageManager.NO_LOCKS.createLazyValue(createClassBuilder);
}
@Override
@NotNull
protected ClassBuilder getDelegate() {
return classBuilder.invoke();
}
@Override
public void done() {
if (isComputed()) {
classBuilder.invoke().done();
}
}
public boolean isComputed() {
return classBuilder.isComputed();
}
}

View File

@@ -1,38 +0,0 @@
/*
* Copyright 2010-2015 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.codegen
import org.jetbrains.kotlin.storage.LockBasedStorageManager
class ClassBuilderOnDemand(createClassBuilder: () -> ClassBuilder) : DelegatingClassBuilder() {
private val classBuilder = LockBasedStorageManager.NO_LOCKS.createLazyValue(createClassBuilder)
val isComputed: Boolean
get() = classBuilder.isComputed()
override fun getDelegate() = classBuilder()
fun ensureGenerated() {
classBuilder()
}
override fun done() {
if (isComputed) {
classBuilder().done()
}
}
}

View File

@@ -51,7 +51,6 @@ import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
import org.jetbrains.kotlin.codegen.when.SwitchCodegen;
import org.jetbrains.kotlin.codegen.when.SwitchCodegenProvider;
import org.jetbrains.kotlin.config.ApiVersion;
import org.jetbrains.kotlin.config.LanguageFeature;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor;
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor;
@@ -308,12 +307,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
RuntimeAssertionInfo runtimeAssertionInfo = null;
if (selector instanceof KtExpression) {
KtExpression expression = (KtExpression) selector;
runtimeAssertionInfo = bindingContext.get(JvmBindingContextSlices.RUNTIME_ASSERTION_INFO, expression);
if (runtimeAssertionInfo == null &&
state.getLanguageVersionSettings().supportsFeature(LanguageFeature.StrictJavaNullabilityAssertions)) {
runtimeAssertionInfo = bindingContext.get(JvmBindingContextSlices.BODY_RUNTIME_ASSERTION_INFO, expression);
}
runtimeAssertionInfo = bindingContext.get(JvmBindingContextSlices.RUNTIME_ASSERTION_INFO, (KtExpression) selector);
}
if (BuiltinSpecialBridgesKt.isValueArgumentForCallToMethodWithTypeCheckBarrier(selector, bindingContext)) return stackValue;
@@ -392,6 +386,13 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
ClassContext objectContext = context.intoAnonymousClass(descriptor, this, OwnerKind.IMPLEMENTATION);
new ImplementationBodyCodegen(declaration, objectContext, classBuilder, state, getParentCodegen(), /* isLocal = */ true).generate();
if (declaration instanceof KtClass && ((KtClass) declaration).isInterface()) {
Type traitImplType = state.getTypeMapper().mapDefaultImpls(descriptor);
ClassBuilder traitImplBuilder = state.getFactory().newVisitor(JvmDeclarationOriginKt.DefaultImpls(declaration, descriptor), traitImplType, declaration.getContainingFile());
ClassContext traitImplContext = context.intoAnonymousClass(descriptor, this, OwnerKind.DEFAULT_IMPLS);
new InterfaceImplBodyCodegen(declaration, traitImplContext, traitImplBuilder, state, parentCodegen).generate();
}
return StackValue.none();
}
@@ -1079,15 +1080,11 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
for (Map.Entry<DeclarationDescriptor, EnclosedValueDescriptor> entry : closure.getCaptureVariables().entrySet()) {
DeclarationDescriptor declarationDescriptor = entry.getKey();
EnclosedValueDescriptor valueDescriptor = entry.getValue();
Type sharedVarType = typeMapper.getSharedVarType(declarationDescriptor);
boolean asSharedVar = sharedVarType != null;
Type sharedVarType = typeMapper.getSharedVarType(entry.getKey());
if (sharedVarType == null) {
sharedVarType = typeMapper.mapType((VariableDescriptor) declarationDescriptor);
sharedVarType = typeMapper.mapType((VariableDescriptor) entry.getKey());
}
StackValue capturedVar = lookupOuterValue(valueDescriptor, asSharedVar);
StackValue capturedVar = lookupOuterValue(entry.getValue());
callGenerator.putCapturedValueOnStack(capturedVar, sharedVarType, paramIndex++);
}
@@ -1141,16 +1138,11 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
@NotNull
private StackValue lookupOuterValue(EnclosedValueDescriptor d, boolean asSharedVar) {
public StackValue lookupOuterValue(EnclosedValueDescriptor d) {
DeclarationDescriptor descriptor = d.getDescriptor();
for (LocalLookup.LocalLookupCase aCase : LocalLookup.LocalLookupCase.values()) {
if (aCase.isCase(descriptor)) {
StackValue outerValue = aCase.outerValue(d, this);
if (asSharedVar && outerValue instanceof StackValue.FieldForSharedVar) {
StackValue.FieldForSharedVar fieldForSharedVar = (StackValue.FieldForSharedVar) outerValue;
return fieldForSharedVar.receiver;
}
return outerValue;
return aCase.outerValue(d, this);
}
}
throw new IllegalStateException("Can't get outer value in " + this + " for " + d);
@@ -1229,7 +1221,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
@Nullable
public StackValue genCoroutineInstanceForSuspendLambda(@NotNull FunctionDescriptor suspendFunction) {
private StackValue genCoroutineInstanceForSuspendLambda(@NotNull FunctionDescriptor suspendFunction) {
if (!(suspendFunction instanceof AnonymousFunctionDescriptor)) return null;
ClassDescriptor suspendLambdaClassDescriptor = bindingContext.get(CodegenBinding.CLASS_FOR_CALLABLE, suspendFunction);
@@ -1725,22 +1717,12 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
private boolean shouldGenerateSingletonAsThisOrOuterFromContext(ClassDescriptor classDescriptor) {
if (!isPossiblyUninitializedSingleton(classDescriptor)) return false;
if (!isInsideSingleton(classDescriptor)) return false;
// We are inside a singleton class 'S' with possibly uninitialized static instance
// (enum entry, interface companion object).
// Such singleton can be referenced by name, or as an explicit or implicit 'this'.
// For a given singleton class 'S' we either use 'this@S' from context (local or captured),
// or 'S' as a static instance.
//
// Local or captured 'this@S' should be used if:
// - we are in the constructor for 'S',
// and corresponding instance is initialized by super or delegating constructor call;
// - we are in any other member of 'S' or any of its inner classes.
//
// Otherwise, a static instance should be used.
return isPossiblyUninitializedSingleton(classDescriptor) &&
isInsideSingleton(classDescriptor) &&
isThisInitialized(classDescriptor);
}
private boolean isThisInitialized(ClassDescriptor classDescriptor) {
CodegenContext context = this.context;
while (context != null) {
if (context instanceof ConstructorContext) {
@@ -1750,24 +1732,9 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
return constructorContext.isThisInitialized();
}
}
else if (context instanceof ClassContext) {
ClassDescriptor contextClass = ((ClassContext) context).getContextDescriptor();
if (isInInnerClassesChainFor(contextClass, classDescriptor)) {
return true;
}
}
context = context.getParentContext();
}
return false;
}
private static boolean isInInnerClassesChainFor(ClassDescriptor innerClass, ClassDescriptor outerClass) {
if (innerClass == outerClass) return true;
if (!innerClass.isInner()) return false;
DeclarationDescriptor containingDeclaration = innerClass.getContainingDeclaration();
if (!(containingDeclaration instanceof ClassDescriptor)) return false;
return isInInnerClassesChainFor((ClassDescriptor) containingDeclaration, outerClass);
return true;
}
@Nullable
@@ -1861,17 +1828,8 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
@Override
public boolean isLocal(DeclarationDescriptor descriptor) {
if (lookupLocalIndex(descriptor) != -1) return true;
if (context.isContextWithUninitializedThis()) {
LocalLookup outerLookup = context.getParentContext().getEnclosingLocalLookup();
if (outerLookup != null) {
return outerLookup.isLocal(descriptor);
}
}
return false;
public boolean lookupLocal(DeclarationDescriptor descriptor) {
return lookupLocalIndex(descriptor) != -1;
}
public int lookupLocalIndex(DeclarationDescriptor descriptor) {
@@ -2171,10 +2129,15 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
resolvedCall, state.getProject(), state.getBindingContext()
);
if (callWithRealDescriptor != null) {
prepareCoroutineArgumentForSuspendCall(resolvedCall, callWithRealDescriptor.getFakeContinuationExpression());
StackValue coroutineInstanceValueForSuspensionPoint = getCoroutineInstanceValueForSuspensionPoint(resolvedCall);
StackValue coroutineInstanceValue =
coroutineInstanceValueForSuspensionPoint != null
? coroutineInstanceValueForSuspensionPoint
: getContinuationParameterFromEnclosingSuspendFunction(resolvedCall);
tempVariables.put(callWithRealDescriptor.getFakeContinuationExpression(), coroutineInstanceValue);
return invokeFunction(callWithRealDescriptor.getResolvedCall(), receiver);
}
FunctionDescriptor fd = accessibleFunctionDescriptor(resolvedCall);
ClassDescriptor superCallTarget = getSuperCallTarget(call);
@@ -2194,18 +2157,6 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
return callable.invokeMethodWithArguments(resolvedCall, receiver, this);
}
private void prepareCoroutineArgumentForSuspendCall(
@NotNull ResolvedCall<?> resolvedCall,
@NotNull KtExpression continuationExpression
) {
StackValue coroutineInstanceValueForSuspensionPoint = getCoroutineInstanceValueForSuspensionPoint(resolvedCall);
StackValue coroutineInstanceValue =
coroutineInstanceValueForSuspensionPoint != null
? coroutineInstanceValueForSuspensionPoint
: getContinuationParameterFromEnclosingSuspendFunction(resolvedCall);
tempVariables.put(continuationExpression, coroutineInstanceValue);
}
private StackValue getContinuationParameterFromEnclosingSuspendFunction(@NotNull ResolvedCall<?> resolvedCall) {
FunctionDescriptor enclosingSuspendFunction =
bindingContext.get(BindingContext.ENCLOSING_SUSPEND_FUNCTION_FOR_SUSPEND_FUNCTION_CALL, resolvedCall.getCall());
@@ -2218,11 +2169,6 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
assert enclosingSuspendFunctionJvmView != null : "No JVM view function found for " + enclosingSuspendFunction;
return getContinuationParameterFromEnclosingSuspendFunctionDescriptor(enclosingSuspendFunctionJvmView);
}
@Nullable
public StackValue getContinuationParameterFromEnclosingSuspendFunctionDescriptor(@NotNull FunctionDescriptor enclosingSuspendFunctionJvmView) {
ValueParameterDescriptor continuationParameter =
enclosingSuspendFunctionJvmView.getValueParameters()
.get(enclosingSuspendFunctionJvmView.getValueParameters().size() - 1);
@@ -2624,40 +2570,40 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
@NotNull
public StackValue generateThisOrOuter(@NotNull ClassDescriptor thisOrOuterClass, boolean isSuper, boolean forceOuter) {
if (!thisOrOuterClass.getKind().isSingleton()) {
return generateThisOrOuterFromContext(thisOrOuterClass, isSuper, forceOuter);
public StackValue generateThisOrOuter(@NotNull ClassDescriptor calleeContainingClass, boolean isSuper, boolean forceOuter) {
if (!calleeContainingClass.getKind().isSingleton()) {
return generateThisOrOuterFromContext(calleeContainingClass, isSuper, forceOuter);
}
if (thisOrOuterClass.equals(context.getThisDescriptor()) &&
if (calleeContainingClass.equals(context.getThisDescriptor()) &&
!CodegenUtilKt.isJvmStaticInObjectOrClass(context.getFunctionDescriptor())) {
return StackValue.local(0, typeMapper.mapType(thisOrOuterClass));
return StackValue.local(0, typeMapper.mapType(calleeContainingClass));
}
else if (shouldGenerateSingletonAsThisOrOuterFromContext(thisOrOuterClass)) {
return generateThisOrOuterFromContext(thisOrOuterClass, isSuper, forceOuter);
else if (shouldGenerateSingletonAsThisOrOuterFromContext(calleeContainingClass)) {
return generateThisOrOuterFromContext(calleeContainingClass, isSuper, forceOuter);
}
else if (isEnumEntry(thisOrOuterClass)) {
return StackValue.enumEntry(thisOrOuterClass, typeMapper);
else if (isEnumEntry(calleeContainingClass)) {
return StackValue.enumEntry(calleeContainingClass, typeMapper);
}
else {
return StackValue.singleton(thisOrOuterClass, typeMapper);
return StackValue.singleton(calleeContainingClass, typeMapper);
}
}
private StackValue generateThisOrOuterFromContext(@NotNull ClassDescriptor thisOrOuterClass, boolean isSuper, boolean forceOuter) {
private StackValue generateThisOrOuterFromContext(@NotNull ClassDescriptor calleeContainingClass, boolean isSuper, boolean forceOuter) {
CodegenContext cur = context;
Type type = asmType(thisOrOuterClass.getDefaultType());
Type type = asmType(calleeContainingClass.getDefaultType());
StackValue result = StackValue.local(0, type);
boolean inStartConstructorContext = cur instanceof ConstructorContext;
while (cur != null) {
ClassDescriptor thisDescriptor = cur.getThisDescriptor();
if (!isSuper && thisDescriptor == thisOrOuterClass) {
if (!isSuper && thisDescriptor == calleeContainingClass) {
return result;
}
if (!forceOuter && isSuper && DescriptorUtils.isSubclass(thisDescriptor, thisOrOuterClass)) {
return castToRequiredTypeOfInterfaceIfNeeded(result, thisDescriptor, thisOrOuterClass);
if (!forceOuter && isSuper && DescriptorUtils.isSubclass(thisDescriptor, calleeContainingClass)) {
return castToRequiredTypeOfInterfaceIfNeeded(result, thisDescriptor, calleeContainingClass);
}
forceOuter = false;
@@ -2673,7 +2619,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
result = cur.getOuterExpression(result, false);
}
cur = cur.getEnclosingClassContext();
cur = cur.getParentContext();
}
throw new UnsupportedOperationException();
@@ -2838,7 +2784,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
@Nullable
public StackValue generateCallableReferenceReceiver(@NotNull ResolvedCall<?> resolvedCall) {
private StackValue generateCallableReferenceReceiver(@NotNull ResolvedCall<?> resolvedCall) {
CallableDescriptor descriptor = resolvedCall.getResultingDescriptor();
if (descriptor.getExtensionReceiverParameter() == null && descriptor.getDispatchReceiverParameter() == null) return null;
@@ -3412,16 +3358,6 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
private StackValue generateAugmentedAssignment(KtBinaryExpression expression) {
return StackValue.operation(Type.VOID_TYPE, adapter -> {
ResolvedCall<?> resolvedCall = CallUtilKt.getResolvedCallWithAssert(expression, bindingContext);
ResolvedCallWithRealDescriptor callWithRealDescriptor =
CoroutineCodegenUtilKt.replaceSuspensionFunctionWithRealDescriptor(
resolvedCall, state.getProject(), state.getBindingContext()
);
if (callWithRealDescriptor != null) {
prepareCoroutineArgumentForSuspendCall(resolvedCall, callWithRealDescriptor.getFakeContinuationExpression());
resolvedCall = callWithRealDescriptor.getResolvedCall();
}
FunctionDescriptor descriptor = accessibleFunctionDescriptor(resolvedCall);
Callable callable = resolveToCallable(descriptor, false, resolvedCall);
KtExpression lhs = expression.getLeft();
@@ -4251,29 +4187,14 @@ The "returned" value of try expression with no finally is either the last expres
putReifiedOperationMarkerIfTypeIsReifiedParameter(type, operationKind, v, this);
}
public static void putReifiedOperationMarkerIfTypeIsReifiedParameterWithoutPropagation(
@NotNull KotlinType type, @NotNull ReifiedTypeInliner.OperationKind operationKind, @NotNull InstructionAdapter v
) {
putReifiedOperationMarkerIfTypeIsReifiedParameterImpl(type, operationKind, v, null);
}
public static void putReifiedOperationMarkerIfTypeIsReifiedParameter(
@NotNull KotlinType type, @NotNull ReifiedTypeInliner.OperationKind operationKind, @NotNull InstructionAdapter v,
@NotNull BaseExpressionCodegen codegen
) {
putReifiedOperationMarkerIfTypeIsReifiedParameterImpl(type, operationKind, v, codegen);
}
private static void putReifiedOperationMarkerIfTypeIsReifiedParameterImpl(
@NotNull KotlinType type, @NotNull ReifiedTypeInliner.OperationKind operationKind, @NotNull InstructionAdapter v,
@Nullable BaseExpressionCodegen codegen
) {
Pair<TypeParameterDescriptor, ReificationArgument> typeParameterAndReificationArgument = extractReificationArgument(type);
if (typeParameterAndReificationArgument != null && typeParameterAndReificationArgument.getFirst().isReified()) {
TypeParameterDescriptor typeParameterDescriptor = typeParameterAndReificationArgument.getFirst();
if (codegen != null) {
codegen.consumeReifiedOperationMarker(typeParameterDescriptor);
}
codegen.consumeReifiedOperationMarker(typeParameterDescriptor);
v.iconst(operationKind.getId());
v.visitLdcInsn(typeParameterAndReificationArgument.getSecond().asString());
v.invokestatic(

View File

@@ -77,6 +77,7 @@ import java.util.Set;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isNullableAny;
import static org.jetbrains.kotlin.codegen.AsmUtil.*;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isAnnotationOrJvmInterfaceWithoutDefaults;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isJvm8InterfaceWithDefaultsMember;
import static org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings.METHOD_FOR_FUNCTION;
import static org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.DECLARATION;
@@ -100,7 +101,7 @@ public class FunctionCodegen {
private final Function1<DeclarationDescriptor, Boolean> IS_PURE_INTERFACE_CHECKER = new Function1<DeclarationDescriptor, Boolean>() {
@Override
public Boolean invoke(DeclarationDescriptor descriptor) {
return JvmCodegenUtil.isInterfaceWithoutDefaults(descriptor, state);
return JvmCodegenUtil.isAnnotationOrJvmInterfaceWithoutDefaults(descriptor, state);
}
};
@@ -865,7 +866,7 @@ public class FunctionCodegen {
public void generateBridges(@NotNull FunctionDescriptor descriptor) {
if (descriptor instanceof ConstructorDescriptor) return;
if (owner.getContextKind() == OwnerKind.DEFAULT_IMPLS) return;
if (IS_PURE_INTERFACE_CHECKER.invoke(descriptor.getContainingDeclaration())) return;
if (isAnnotationOrJvmInterfaceWithoutDefaults(descriptor.getContainingDeclaration(), state)) return;
// equals(Any?), hashCode(), toString() never need bridges
if (isMethodOfAny(descriptor)) return;

View File

@@ -1338,7 +1338,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
private void generateTraitMethods() {
if (isInterfaceWithoutDefaults(descriptor, state)) return;
if (isAnnotationOrJvmInterfaceWithoutDefaults(descriptor, state)) return;
List<FunctionDescriptor> restrictedInheritance = new ArrayList<>();
for (Map.Entry<FunctionDescriptor, FunctionDescriptor> entry : CodegenUtil.getNonPrivateTraitMethods(descriptor).entrySet()) {

View File

@@ -42,6 +42,7 @@ import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils;
import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.resolve.inline.InlineUtil;
import org.jetbrains.kotlin.resolve.jvm.JvmConstantsKt;
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue;
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedCallableMemberDescriptor;
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor;
@@ -62,12 +63,15 @@ public class JvmCodegenUtil {
private JvmCodegenUtil() {
}
public static boolean isInterfaceWithoutDefaults(@NotNull DeclarationDescriptor descriptor, @NotNull GenerationState state) {
return isInterfaceWithoutDefaults(descriptor, state.isJvm8Target(), state.isJvm8TargetWithDefaults());
public static boolean isAnnotationOrJvmInterfaceWithoutDefaults(@NotNull DeclarationDescriptor descriptor, @NotNull GenerationState state) {
return isAnnotationOrJvmInterfaceWithoutDefaults(descriptor, state.isJvm8Target(), state.isJvm8TargetWithDefaults());
}
private static boolean isInterfaceWithoutDefaults(@NotNull DeclarationDescriptor descriptor, boolean isJvm8Target, boolean isJvm8TargetWithDefaults) {
if (!DescriptorUtils.isInterface(descriptor)) return false;
private static boolean isAnnotationOrJvmInterfaceWithoutDefaults(@NotNull DeclarationDescriptor descriptor, boolean isJvm8Target, boolean isJvm8TargetWithDefaults) {
if (!isJvmInterface(descriptor)) {
return false;
}
if (ANNOTATION_CLASS == ((ClassDescriptor) descriptor).getKind()) return true;
if (descriptor instanceof DeserializedClassDescriptor) {
SourceElement source = ((DeserializedClassDescriptor) descriptor).getSource();
@@ -87,7 +91,7 @@ public class JvmCodegenUtil {
}
public static boolean isJvm8InterfaceWithDefaults(@NotNull DeclarationDescriptor descriptor, boolean isJvm8Target, boolean isJvm8TargetWithDefaults) {
return DescriptorUtils.isInterface(descriptor) && !isInterfaceWithoutDefaults(descriptor, isJvm8Target, isJvm8TargetWithDefaults);
return DescriptorUtils.isInterface(descriptor) && !isAnnotationOrJvmInterfaceWithoutDefaults(descriptor, isJvm8Target, isJvm8TargetWithDefaults);
}
public static boolean isJvm8InterfaceWithDefaultsMember(@NotNull CallableMemberDescriptor descriptor, @NotNull GenerationState state) {

View File

@@ -812,10 +812,7 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
((AccessorForCallableDescriptor) accessorDescriptor).getSuperCallTarget() != null
);
boolean isJvmStaticInObjectOrClass = CodegenUtilKt.isJvmStaticInObjectOrClass(functionDescriptor);
boolean hasDispatchReceiver = !isStaticDeclaration(functionDescriptor) &&
!isNonDefaultInterfaceMember(functionDescriptor, state) &&
!isJvmStaticInObjectOrClass;
boolean hasDispatchReceiver = !isStaticDeclaration(functionDescriptor) && !isNonDefaultInterfaceMember(functionDescriptor, state);
boolean accessorIsConstructor = accessorDescriptor instanceof AccessorForConstructorDescriptor;
int accessorParam = (hasDispatchReceiver && !accessorIsConstructor) ? 1 : 0;
@@ -827,7 +824,7 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
accessorParam = 0;
}
else if (KotlinTypeMapper.isAccessor(accessorDescriptor) && (hasDispatchReceiver || accessorIsConstructor)) {
if (!isJvmStaticInObjectOrClass) {
if (!CodegenUtilKt.isJvmStaticInObjectOrClass(functionDescriptor)) {
iv.load(0, OBJECT_TYPE);
}
}

View File

@@ -317,10 +317,7 @@ class MultifileClassCodegenImpl(
}
private fun writeKotlinMultifileFacadeAnnotationIfNeeded() {
if (!state.classBuilderMode.generateMetadata) {
classBuilder.ensureGenerated()
return
}
if (!state.classBuilderMode.generateMetadata) return
if (files.any { it.isScript() }) return
val extraFlags = if (shouldGeneratePartHierarchy) JvmAnnotationNames.METADATA_MULTIFILE_PARTS_INHERIT_FLAG else 0

View File

@@ -85,7 +85,7 @@ public abstract class TransformationMethodVisitor extends MethodVisitor {
delegate.visitEnd();
}
catch (Throwable t) {
throw new CompilationException("Couldn't transform method node:\n" + getNodeText(methodNode), t, null);
throw new CompilationException("Couldn't transform method node: " + getNodeText(methodNode), t, null);
}
}

View File

@@ -32,7 +32,6 @@ import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.codegen.state.TypeMapperUtilsKt;
import org.jetbrains.kotlin.codegen.when.SwitchCodegenProvider;
import org.jetbrains.kotlin.codegen.when.WhenByEnumsMapping;
import org.jetbrains.kotlin.config.LanguageVersionSettings;
import org.jetbrains.kotlin.coroutines.CoroutineUtilKt;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.annotations.Annotations;
@@ -57,7 +56,6 @@ import org.jetbrains.kotlin.resolve.constants.ConstantValue;
import org.jetbrains.kotlin.resolve.constants.EnumValue;
import org.jetbrains.kotlin.resolve.constants.NullValue;
import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt;
import org.jetbrains.kotlin.resolve.jvm.RuntimeAssertionsOnDeclarationBodyChecker;
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue;
import org.jetbrains.kotlin.resolve.scopes.receivers.TransientReceiver;
import org.jetbrains.kotlin.types.KotlinType;
@@ -81,7 +79,6 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
private final Stack<ClassDescriptor> classStack = new Stack<>();
private final Stack<String> nameStack = new Stack<>();
private final Set<ClassDescriptor> uninitializedClasses = new HashSet<>();
private final BindingTrace bindingTrace;
private final BindingContext bindingContext;
@@ -89,8 +86,6 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
private final JvmRuntimeTypes runtimeTypes;
private final TypeMappingConfiguration<Type> typeMappingConfiguration;
private final SwitchCodegenProvider switchCodegenProvider;
private final LanguageVersionSettings languageVersionSettings;
private final ClassBuilderMode classBuilderMode;
public CodegenAnnotatingVisitor(@NotNull GenerationState state) {
this.bindingTrace = state.getBindingTrace();
@@ -99,8 +94,6 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
this.runtimeTypes = state.getJvmRuntimeTypes();
this.typeMappingConfiguration = state.getTypeMapper().getTypeMappingConfiguration();
this.switchCodegenProvider = new SwitchCodegenProvider(state);
this.languageVersionSettings = state.getLanguageVersionSettings();
this.classBuilderMode = state.getClassBuilderMode();
}
@NotNull
@@ -137,7 +130,7 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
) {
String simpleName = name.substring(name.lastIndexOf('/') + 1);
ClassDescriptor classDescriptor = new SyntheticClassDescriptorForLambda(
customContainer != null ? customContainer : correctContainerForLambda(callableDescriptor),
customContainer != null ? customContainer : correctContainerForLambda(callableDescriptor, element),
Name.special("<closure-" + simpleName + ">"),
supertypes,
element
@@ -149,7 +142,7 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
@NotNull
@SuppressWarnings("ConstantConditions")
private DeclarationDescriptor correctContainerForLambda(@NotNull CallableDescriptor descriptor) {
private DeclarationDescriptor correctContainerForLambda(@NotNull CallableDescriptor descriptor, @NotNull KtElement function) {
DeclarationDescriptor container = descriptor.getContainingDeclaration();
// In almost all cases the function's direct container is the correct container to consider in JVM back-end
@@ -158,11 +151,23 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
// in this case it's constructed in the outer code, despite being located under the object PSI- and descriptor-wise
// TODO: consider the possibility of fixing this in the compiler front-end
while (container instanceof ConstructorDescriptor) {
ClassDescriptor classDescriptor = ((ConstructorDescriptor) container).getConstructedClass();
if (!DescriptorUtils.isAnonymousObject(classDescriptor)) break;
if (!uninitializedClasses.contains(classDescriptor)) break;
container = classDescriptor.getContainingDeclaration();
if (container instanceof ConstructorDescriptor && DescriptorUtils.isAnonymousObject(container.getContainingDeclaration())) {
PsiElement element = function;
while (element != null) {
PsiElement child = element;
element = element.getParent();
if (bindingContext.get(DECLARATION_TO_DESCRIPTOR, element) == container) return container;
if (element instanceof KtObjectDeclaration &&
element.getParent() instanceof KtObjectLiteralExpression &&
child instanceof KtSuperTypeList) {
// If we're passing an anonymous object's super call, it means "container" is ConstructorDescriptor of that object.
// To reach outer context, we should call getContainingDeclaration() twice
// TODO: this is probably not entirely correct, mostly because DECLARATION_TO_DESCRIPTOR can return null
container = container.getContainingDeclaration().getContainingDeclaration();
}
}
}
return container;
@@ -383,18 +388,7 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
@NotNull
private MutableClosure recordClosure(@NotNull ClassDescriptor classDescriptor, @NotNull String name) {
return CodegenBinding.recordClosure(bindingTrace, classDescriptor, getProperEnclosingClass(), Type.getObjectType(name));
}
@Nullable
private ClassDescriptor getProperEnclosingClass() {
for (int i = classStack.size() - 1; i >= 0; i--) {
ClassDescriptor fromStack = classStack.get(i);
if (!uninitializedClasses.contains(fromStack)) {
return fromStack;
}
}
return null;
return CodegenBinding.recordClosure(bindingTrace, classDescriptor, peekFromStack(classStack), Type.getObjectType(name));
}
private void recordLocalVariablePropertyMetadata(LocalVariableDescriptor variableDescriptor) {
@@ -417,8 +411,6 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
// working around a problem with shallow analysis
if (descriptor == null) return;
checkRuntimeAsserionsOnDeclarationBody(property, descriptor);
if (descriptor instanceof LocalVariableDescriptor) {
recordLocalVariablePropertyMetadata((LocalVariableDescriptor) descriptor);
}
@@ -455,14 +447,6 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
nameStack.pop();
}
private void checkRuntimeAsserionsOnDeclarationBody(@NotNull KtDeclaration declaration, DeclarationDescriptor descriptor) {
if (classBuilderMode.generateBodies) {
// NB This is required only for bodies generation.
// In light class generation can cause recursion in types resolution.
RuntimeAssertionsOnDeclarationBodyChecker.check(declaration, descriptor, bindingTrace, languageVersionSettings);
}
}
@NotNull
private Type getMetadataOwner(@NotNull KtProperty property) {
for (int i = classStack.size() - 1; i >= 0; i--) {
@@ -485,24 +469,12 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
return Type.getObjectType(JvmFileClassUtil.getFileClassInternalName(property.getContainingKtFile()));
}
@Override
public void visitPropertyAccessor(@NotNull KtPropertyAccessor accessor) {
PropertyAccessorDescriptor accessorDescriptor = bindingContext.get(PROPERTY_ACCESSOR, accessor);
if (accessorDescriptor != null) {
checkRuntimeAsserionsOnDeclarationBody(accessor, accessorDescriptor);
}
super.visitPropertyAccessor(accessor);
}
@Override
public void visitNamedFunction(@NotNull KtNamedFunction function) {
FunctionDescriptor functionDescriptor = (FunctionDescriptor) bindingContext.get(DECLARATION_TO_DESCRIPTOR, function);
// working around a problem with shallow analysis
if (functionDescriptor == null) return;
checkRuntimeAsserionsOnDeclarationBody(function, functionDescriptor);
String nameForClassOrPackageMember = getNameForClassOrPackageMember(functionDescriptor);
if (functionDescriptor instanceof SimpleFunctionDescriptor && functionDescriptor.isSuspend()) {
@@ -627,42 +599,10 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
@Override
public void visitSuperTypeCallEntry(@NotNull KtSuperTypeCallEntry call) {
// Closures in super type constructor calls for anonymous objects are created in outer context
if (!isSuperTypeCallForAnonymousObject(call)) {
withinUninitializedClass(call, () -> super.visitSuperTypeCallEntry(call));
}
else {
super.visitSuperTypeCallEntry(call);
}
super.visitSuperTypeCallEntry(call);
checkSamCall(call);
}
private static boolean isSuperTypeCallForAnonymousObject(@NotNull KtSuperTypeCallEntry call) {
PsiElement parent = call.getParent();
if (!(parent instanceof KtSuperTypeList)) return false;
parent = parent.getParent();
if (!(parent instanceof KtObjectDeclaration)) return false;
parent = parent.getParent();
if (!(parent instanceof KtObjectLiteralExpression)) return false;
return true;
}
@Override
public void visitConstructorDelegationCall(@NotNull KtConstructorDelegationCall call) {
withinUninitializedClass(call, () -> super.visitConstructorDelegationCall(call));
}
private void withinUninitializedClass(@NotNull KtElement element, @NotNull Runnable operation) {
ClassDescriptor currentClass = peekFromStack(classStack);
assert currentClass != null : element.getClass().getSimpleName() + " should be inside a class: " + element.getText();
assert !uninitializedClasses.contains(currentClass) : "Class entered twice: " + currentClass;
uninitializedClasses.add(currentClass);
operation.run();
boolean removed = uninitializedClasses.remove(currentClass);
assert removed : "Inconsistent uninitialized class stack: " + currentClass;
}
private void recordSamConstructorIfNeeded(@NotNull KtCallElement expression, @NotNull ResolvedCall<?> call) {
CallableDescriptor callableDescriptor = call.getResultingDescriptor();
if (!(callableDescriptor.getOriginal() instanceof SamConstructorDescriptor)) return;

View File

@@ -17,9 +17,9 @@
package org.jetbrains.kotlin.codegen
import com.google.common.collect.Maps
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.codegen.context.CodegenContext
import org.jetbrains.kotlin.codegen.context.FieldOwnerContext
import org.jetbrains.kotlin.codegen.context.PackageContext
import org.jetbrains.kotlin.codegen.coroutines.unwrapInitialDescriptorForSuspendFunction
@@ -30,6 +30,7 @@ import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.deserialization.PLATFORM_DEPENDENT_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.descriptors.impl.TypeAliasConstructorDescriptor
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
import org.jetbrains.kotlin.diagnostics.rendering.Renderers
import org.jetbrains.kotlin.diagnostics.rendering.RenderingContext
@@ -422,13 +423,4 @@ fun ExpressionCodegen.generateCallSingleArgument(rangeCall: ResolvedCall<out Cal
fun ClassDescriptor.isPossiblyUninitializedSingleton() =
DescriptorUtils.isEnumEntry(this) ||
DescriptorUtils.isCompanionObject(this) && DescriptorUtils.isInterface(this.containingDeclaration)
val CodegenContext<*>.parentContextsWithSelf
get() = generateSequence(this) { it.parentContext }
val CodegenContext<*>.parentContexts
get() = parentContext?.parentContextsWithSelf ?: emptySequence()
val CodegenContext<*>.contextStackText
get() = parentContextsWithSelf.joinToString(separator = "\n") { it.toString() }
DescriptorUtils.isCompanionObject(this) && DescriptorUtils.isInterface(this.containingDeclaration)

View File

@@ -215,13 +215,13 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
private StackValue getOuterExpression(@Nullable StackValue prefix, boolean ignoreNoOuter, boolean captureThis) {
if (outerExpression.invoke() == null) {
if (!ignoreNoOuter) {
throw new UnsupportedOperationException("Don't know how to generate outer expression: " + this);
throw new UnsupportedOperationException("Don't know how to generate outer expression for " + getContextDescriptor());
}
return null;
}
if (captureThis) {
if (closure == null) {
throw new IllegalStateException("Can't capture this for context without closure: " + this);
throw new IllegalStateException("Can't capture this for context without closure: " + getContextDescriptor());
}
closure.setCaptureThis();
}
@@ -348,40 +348,13 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
return parentContext;
}
public boolean isContextWithUninitializedThis() {
return false;
}
@Nullable
public CodegenContext getEnclosingClassContext() {
CodegenContext cur = getEnclosingThisContext();
while (cur != null) {
DeclarationDescriptor curDescriptor = cur.getContextDescriptor();
if (curDescriptor instanceof ClassDescriptor) {
return cur;
}
public ClassDescriptor getEnclosingClass() {
CodegenContext cur = getParentContext();
while (cur != null && !(cur.getContextDescriptor() instanceof ClassDescriptor)) {
cur = cur.getParentContext();
}
return null;
}
@Nullable
public CodegenContext getEnclosingThisContext() {
CodegenContext cur = getParentContext();
while (cur != null && cur.isContextWithUninitializedThis()) {
CodegenContext parent = cur.getParentContext();
assert parent != null : "Context " + cur + " should have a parent";
cur = parent.getParentContext();
}
return cur;
}
@Nullable
public ClassDescriptor getEnclosingClass() {
// TODO store enclosing context class in the context itself
CodegenContext enclosingClassContext = getEnclosingClassContext();
if (enclosingClassContext == null) return null;
return (ClassDescriptor) enclosingClassContext.getContextDescriptor();
return cur == null ? null : (ClassDescriptor) cur.getContextDescriptor();
}
@Nullable
@@ -501,8 +474,7 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
);
}
else {
throw new UnsupportedOperationException("Do not know how to create accessor for descriptor " + descriptor +
" in context " + this);
throw new UnsupportedOperationException("Do not know how to create accessor for descriptor " + descriptor);
}
accessors.put(key, accessor);
@@ -518,9 +490,9 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
public StackValue lookupInContext(DeclarationDescriptor d, @Nullable StackValue result, GenerationState state, boolean ignoreNoOuter) {
StackValue myOuter = null;
if (closure != null) {
EnclosedValueDescriptor capturedVariable = closure.getCaptureVariables().get(d);
if (capturedVariable != null) {
return StackValue.changeReceiverForFieldAndSharedVar(capturedVariable.getInnerValue(), result);
EnclosedValueDescriptor answer = closure.getCaptureVariables().get(d);
if (answer != null) {
return StackValue.changeReceiverForFieldAndSharedVar(answer.getInnerValue(), result);
}
for (LocalLookup.LocalLookupCase aCase : LocalLookup.LocalLookupCase.values()) {
@@ -543,10 +515,8 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
StackValue resultValue;
if (myOuter != null && getEnclosingClass() == d) {
resultValue = result;
}
else {
CodegenContext enclosingClassContext = getEnclosingThisContext();
resultValue = enclosingClassContext != null ? enclosingClassContext.lookupInContext(d, result, state, ignoreNoOuter) : null;
} else {
resultValue = parentContext != null ? parentContext.lookupInContext(d, result, state, ignoreNoOuter) : null;
}
if (myOuter != null && resultValue != null && !isStaticField(resultValue)) {
@@ -713,9 +683,4 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
public CodegenContext getFirstCrossInlineOrNonInlineContext() {
return this;
}
@Nullable
public LocalLookup getEnclosingLocalLookup() {
return enclosingLocalLookup;
}
}

View File

@@ -59,13 +59,8 @@ public class ConstructorContext extends MethodContext {
this.thisInitialized = thisInitialized;
}
@Override
public boolean isContextWithUninitializedThis() {
return !isThisInitialized();
}
@Override
public String toString() {
return "Constructor: " + (isThisInitialized() ? "" : "UNINITIALIZED ") + getContextDescriptor();
return "Constructor: " + getContextDescriptor();
}
}

View File

@@ -16,7 +16,6 @@
package org.jetbrains.kotlin.codegen.context;
import kotlin.text.StringsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.codegen.ExpressionCodegen;
import org.jetbrains.kotlin.codegen.JvmCodegenUtil;
@@ -34,7 +33,7 @@ import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.*;
import static org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils.isLocalFunction;
public interface LocalLookup {
boolean isLocal(DeclarationDescriptor descriptor);
boolean lookupLocal(DeclarationDescriptor descriptor);
enum LocalLookupCase {
VAR {
@@ -53,7 +52,7 @@ public interface LocalLookup {
) {
VariableDescriptor vd = (VariableDescriptor) d;
boolean idx = localLookup != null && localLookup.isLocal(vd);
boolean idx = localLookup != null && localLookup.lookupLocal(vd);
if (!idx) return null;
KotlinType delegateType =
@@ -101,28 +100,20 @@ public interface LocalLookup {
) {
FunctionDescriptor vd = (FunctionDescriptor) d;
boolean idx = localLookup != null && localLookup.isLocal(vd);
boolean idx = localLookup != null && localLookup.lookupLocal(vd);
if (!idx) return null;
BindingContext bindingContext = state.getBindingContext();
Type localType = asmTypeForAnonymousClass(bindingContext, vd);
ClassDescriptor callableClass = bindingContext.get(CLASS_FOR_CALLABLE, vd);
assert callableClass != null : "No CLASS_FOR_CALLABLE:" + vd;
MutableClosure localFunClosure = bindingContext.get(CLOSURE, callableClass);
MutableClosure localFunClosure = bindingContext.get(CLOSURE, bindingContext.get(CLASS_FOR_CALLABLE, vd));
if (localFunClosure != null && JvmCodegenUtil.isConst(localFunClosure)) {
// This is an optimization: we can obtain an instance of a const closure simply by GETSTATIC ...$instance
// (instead of passing this instance to the constructor and storing as a field)
return StackValue.field(localType, localType, JvmAbi.INSTANCE_FIELD, true, StackValue.LOCAL_0, vd);
}
String internalName = localType.getInternalName();
String simpleName = StringsKt.substringAfterLast(internalName, "/", internalName);
int localClassIndexStart = simpleName.lastIndexOf('$');
String localFunSuffix = localClassIndexStart >= 0 ? simpleName.substring(localClassIndexStart) : "";
String fieldName = "$" + vd.getName() + localFunSuffix;
String fieldName = "$" + vd.getName();
StackValue.StackValueWithSimpleReceiver innerValue = StackValue.field(localType, classType, fieldName, false,
StackValue.LOCAL_0, vd);

View File

@@ -17,7 +17,9 @@
package org.jetbrains.kotlin.codegen.coroutines
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.backend.common.*
import org.jetbrains.kotlin.backend.common.COROUTINES_INTRINSICS_PACKAGE_FQ_NAME
import org.jetbrains.kotlin.backend.common.COROUTINE_SUSPENDED_NAME
import org.jetbrains.kotlin.backend.common.isBuiltInSuspendCoroutineOrReturn
import org.jetbrains.kotlin.builtins.isBuiltinFunctionalType
import org.jetbrains.kotlin.codegen.StackValue
import org.jetbrains.kotlin.codegen.binding.CodegenBinding
@@ -64,9 +66,6 @@ val COROUTINES_JVM_INTERNAL_PACKAGE_FQ_NAME =
@JvmField
val CONTINUATION_ASM_TYPE = DescriptorUtils.CONTINUATION_INTERFACE_FQ_NAME.topLevelClassAsmType()
@JvmField
val COROUTINE_CONTEXT_ASM_TYPE = DescriptorUtils.COROUTINES_PACKAGE_FQ_NAME.child(Name.identifier("CoroutineContext")).topLevelClassAsmType()
@JvmField
val COROUTINE_IMPL_ASM_TYPE = COROUTINES_JVM_INTERNAL_PACKAGE_FQ_NAME.child(Name.identifier("CoroutineImpl")).topLevelClassAsmType()
@@ -77,7 +76,6 @@ private val INTERNAL_COROUTINE_INTRINSICS_OWNER_INTERNAL_NAME =
COROUTINES_JVM_INTERNAL_PACKAGE_FQ_NAME.child(Name.identifier("CoroutineIntrinsics")).topLevelClassInternalName()
private val NORMALIZE_CONTINUATION_METHOD_NAME = "normalizeContinuation"
private val GET_CONTEXT_METHOD_NAME = "getContext"
data class ResolvedCallWithRealDescriptor(val resolvedCall: ResolvedCall<*>, val fakeContinuationExpression: KtExpression)
@@ -289,35 +287,6 @@ fun createMethodNodeForSuspendCoroutineOrReturn(
return node
}
fun createMethodNodeForCoroutineContext(functionDescriptor: FunctionDescriptor): MethodNode {
assert(functionDescriptor.isBuiltInCoroutineContext()) {
"functionDescriptor must be kotlin.coroutines.intrinsics.coroutineContext property getter"
}
val node =
MethodNode(
Opcodes.ASM5,
Opcodes.ACC_STATIC,
"fake",
Type.getMethodDescriptor(COROUTINE_CONTEXT_ASM_TYPE, CONTINUATION_ASM_TYPE),
null, null
)
node.visitVarInsn(Opcodes.ALOAD, 0)
node.visitMethodInsn(
Opcodes.INVOKEINTERFACE,
CONTINUATION_ASM_TYPE.internalName,
GET_CONTEXT_METHOD_NAME,
Type.getMethodDescriptor(COROUTINE_CONTEXT_ASM_TYPE),
true
)
node.visitInsn(Opcodes.ARETURN)
node.visitMaxs(1, 1)
return node
}
@Suppress("UNCHECKED_CAST")
fun <D : CallableDescriptor?> D.unwrapInitialDescriptorForSuspendFunction(): D =
this.safeAs<SimpleFunctionDescriptor>()?.getUserData(INITIAL_DESCRIPTOR_FOR_SUSPEND_FUNCTION) as D ?: this

View File

@@ -22,8 +22,8 @@ import org.jetbrains.org.objectweb.asm.tree.*
import java.util.*
abstract class CoveringTryCatchNodeProcessor(parameterSize: Int) {
val tryBlocksMetaInfo: IntervalMetaInfo<TryCatchBlockNodeInfo> = IntervalMetaInfo(this)
val localVarsMetaInfo: IntervalMetaInfo<LocalVarNodeWrapper> = IntervalMetaInfo(this)
val tryBlocksMetaInfo: IntervalMetaInfo<TryCatchBlockNodeInfo> = IntervalMetaInfo()
val localVarsMetaInfo: IntervalMetaInfo<LocalVarNodeWrapper> = IntervalMetaInfo()
var nextFreeLocalIndex: Int = parameterSize
private set
@@ -84,27 +84,24 @@ abstract class CoveringTryCatchNodeProcessor(parameterSize: Int) {
}
}
class IntervalMetaInfo<T : SplittableInterval<T>>(private val processor: CoveringTryCatchNodeProcessor) {
class IntervalMetaInfo<T : SplittableInterval<T>> {
val intervalStarts = LinkedListMultimap.create<LabelNode, T>()
val intervalEnds = LinkedListMultimap.create<LabelNode, T>()
val allIntervals: ArrayList<T> = arrayListOf()
val currentIntervals: MutableSet<T> = linkedSetOf()
fun addNewInterval(newInfo: T) {
newInfo.verify(processor)
intervalStarts.put(newInfo.startLabel, newInfo)
intervalEnds.put(newInfo.endLabel, newInfo)
allIntervals.add(newInfo)
}
private fun remapStartLabel(oldStart: LabelNode, remapped: T) {
remapped.verify(processor)
intervalStarts.remove(oldStart, remapped)
intervalStarts.put(remapped.startLabel, remapped)
}
private fun remapEndLabel(oldEnd: LabelNode, remapped: T) {
remapped.verify(processor)
intervalEnds.remove(oldEnd, remapped)
intervalEnds.put(remapped.endLabel, remapped)
}
@@ -113,10 +110,6 @@ class IntervalMetaInfo<T : SplittableInterval<T>>(private val processor: Coverin
return currentIntervals.map { split(it, by, keepStart) }
}
fun splitAndRemoveCurrentIntervals(by: Interval, keepStart: Boolean) {
currentIntervals.map { splitAndRemoveInterval(it, by, keepStart) }
}
fun processCurrent(curIns: LabelNode, directOrder: Boolean) {
getInterval(curIns, directOrder).forEach {
val added = currentIntervals.add(it)

View File

@@ -18,13 +18,12 @@ package org.jetbrains.kotlin.codegen.inline
import com.intellij.psi.PsiElement
import com.intellij.util.ArrayUtil
import org.jetbrains.kotlin.backend.common.isBuiltInCoroutineContext
import org.jetbrains.kotlin.builtins.BuiltInsPackageFragment
import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.AsmUtil.getMethodAsmFlags
import org.jetbrains.kotlin.codegen.AsmUtil.isPrimitive
import org.jetbrains.kotlin.codegen.context.ClosureContext
import org.jetbrains.kotlin.codegen.coroutines.*
import org.jetbrains.kotlin.codegen.coroutines.createMethodNodeForSuspendCoroutineOrReturn
import org.jetbrains.kotlin.codegen.coroutines.isBuiltInSuspendCoroutineOrReturnInJvm
import org.jetbrains.kotlin.codegen.intrinsics.bytecode
import org.jetbrains.kotlin.codegen.intrinsics.classId
import org.jetbrains.kotlin.codegen.state.GenerationState
@@ -51,6 +50,8 @@ import org.jetbrains.kotlin.serialization.deserialization.descriptors.Deserializ
import org.jetbrains.kotlin.types.expressions.DoubleColonLHS
import org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils.isFunctionLiteral
import org.jetbrains.kotlin.types.expressions.LabelResolver
import org.jetbrains.kotlin.utils.DFS
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
@@ -166,7 +167,7 @@ abstract class InlineCodegen<out T: BaseExpressionCodegen>(
var nodeAndSmap: SMAPAndMethodNode? = null
try {
nodeAndSmap = createInlineMethodNode(functionDescriptor, jvmSignature, callDefault, resolvedCall, state, sourceCompiler)
nodeAndSmap = createInlineMethodNode(functionDescriptor, jvmSignature, codegen, callDefault, resolvedCall, state, sourceCompiler)
endCall(inlineCall(nodeAndSmap, callDefault))
}
catch (e: CompilationException) {
@@ -184,11 +185,6 @@ abstract class InlineCodegen<out T: BaseExpressionCodegen>(
}
private fun canSkipStackSpillingOnInline(methodNode: MethodNode): Boolean {
// Temporary disable this optimization until
// https://issuetracker.google.com/issues/68796377 is fixed
// or until d8 substitute dex
return false
// Stack spilling before inline function 'f' call is required if:
// - 'f' is a suspend function
// - 'f' has try-catch blocks
@@ -229,19 +225,6 @@ abstract class InlineCodegen<out T: BaseExpressionCodegen>(
return true
}
private fun continuationValue(): StackValue {
assert(codegen is ExpressionCodegen) { "Expected ExpressionCodegen in coroutineContext inlining" }
codegen as ExpressionCodegen
val parentContext = codegen.context.parentContext
return if (parentContext is ClosureContext) {
val originalSuspendLambdaDescriptor = parentContext.originalSuspendLambdaDescriptor ?: error("No original lambda descriptor found")
codegen.genCoroutineInstanceForSuspendLambda(originalSuspendLambdaDescriptor) ?: error("No stack value for coroutine instance of lambda found")
}
else
codegen.getContinuationParameterFromEnclosingSuspendFunctionDescriptor(codegen.context.functionDescriptor) ?: error("No stack value for continuation parameter of suspend function")
}
protected fun inlineCall(nodeAndSmap: SMAPAndMethodNode, callDefault: Boolean): InlineResult {
assert(delayedHiddenWriting == null) { "'putHiddenParamsIntoLocals' should be called after 'processAndPutHiddenParameters(true)'" }
defaultSourceMapper.callSiteMarker = CallSiteMarker(codegen.lastLineNumber)
@@ -269,9 +252,6 @@ abstract class InlineCodegen<out T: BaseExpressionCodegen>(
addInlineMarker(codegen.v, true)
}
if (functionDescriptor.isBuiltInCoroutineContext())
invocationParamBuilder.addNextValueParameter(CONTINUATION_ASM_TYPE, false, continuationValue(), 0)
val parameters = invocationParamBuilder.buildParameters()
val info = RootInliningContext(
@@ -472,32 +452,30 @@ abstract class InlineCodegen<out T: BaseExpressionCodegen>(
internal fun createInlineMethodNode(
functionDescriptor: FunctionDescriptor,
jvmSignature: JvmMethodSignature,
codegen: BaseExpressionCodegen,
callDefault: Boolean,
resolvedCall: ResolvedCall<*>?,
state: GenerationState,
sourceCompilerForInline: SourceCompilerForInline
): SMAPAndMethodNode {
when {
isSpecialEnumMethod(functionDescriptor) -> {
val arguments = resolvedCall!!.typeArguments
if (isSpecialEnumMethod(functionDescriptor)) {
val arguments = resolvedCall!!.typeArguments
val node = createSpecialEnumMethodBody(
functionDescriptor.name.asString(),
arguments.keys.single().defaultType,
state.typeMapper
)
return SMAPAndMethodNode(node, SMAPParser.parseOrCreateDefault(null, null, "fake", -1, -1))
}
functionDescriptor.isBuiltInSuspendCoroutineOrReturnInJvm() ->
return SMAPAndMethodNode(
createMethodNodeForSuspendCoroutineOrReturn(functionDescriptor, state.typeMapper),
val node = createSpecialEnumMethodBody(
codegen,
functionDescriptor.name.asString(),
arguments.keys.single().defaultType,
state.typeMapper
)
return SMAPAndMethodNode(node, SMAPParser.parseOrCreateDefault(null, null, "fake", -1, -1))
}
else if (functionDescriptor.isBuiltInSuspendCoroutineOrReturnInJvm()) {
return SMAPAndMethodNode(
createMethodNodeForSuspendCoroutineOrReturn(
functionDescriptor, state.typeMapper
),
SMAPParser.parseOrCreateDefault(null, null, "fake", -1, -1)
)
functionDescriptor.isBuiltInCoroutineContext() ->
return SMAPAndMethodNode(
createMethodNodeForCoroutineContext(functionDescriptor),
SMAPParser.parseOrCreateDefault(null, null, "fake", -1, -1)
)
)
}
val asmMethod = if (callDefault)

View File

@@ -66,7 +66,7 @@ class InlineCodegenForDefaultBody(
}
override fun genCallInner(callableMethod: Callable, resolvedCall: ResolvedCall<*>?, callDefault: Boolean, codegen: ExpressionCodegen) {
val nodeAndSmap = InlineCodegen.createInlineMethodNode(functionDescriptor, jvmSignature, callDefault, null, state, sourceCompilerForInline)
val nodeAndSmap = InlineCodegen.createInlineMethodNode(functionDescriptor, jvmSignature, codegen, callDefault, null, state, sourceCompilerForInline)
val childSourceMapper = InlineCodegen.createNestedSourceMapper(nodeAndSmap, sourceMapper)
val node = nodeAndSmap.node

View File

@@ -366,7 +366,7 @@ class PsiSourceCompilerForInline(private val codegen: ExpressionCodegen, overrid
insertNodeBefore(finallyNode, intoNode, curInstr)
val splitBy = SimpleInterval(start.info as LabelNode, extension.finallyIntervalEnd)
processor.tryBlocksMetaInfo.splitAndRemoveCurrentIntervals(splitBy, true)
processor.tryBlocksMetaInfo.splitCurrentIntervals(splitBy, true)
//processor.getLocalVarsMetaInfo().splitAndRemoveIntervalsFromCurrents(splitBy);

View File

@@ -16,7 +16,6 @@
package org.jetbrains.kotlin.codegen.inline
import org.jetbrains.kotlin.codegen.optimization.common.InsnSequence
import org.jetbrains.org.objectweb.asm.tree.LabelNode
import org.jetbrains.org.objectweb.asm.tree.TryCatchBlockNode
@@ -36,12 +35,6 @@ interface Interval {
/*note that some intervals are mutable */
fun isEmpty(): Boolean = startLabel == endLabel
fun verify(processor: CoveringTryCatchNodeProcessor) {
assert (processor.instructionIndex(startLabel) <= processor.instructionIndex(endLabel)) {
"Try block body starts after body end: ${processor.instructionIndex(startLabel)} > ${processor.instructionIndex(endLabel)}"
}
}
}
interface SplittableInterval<out T : Interval> : Interval {
@@ -84,9 +77,6 @@ class TryCatchBlockNodeInfo(
}
}
val TryCatchBlockNodeInfo.bodyInstuctions
get() = InsnSequence(startLabel, endLabel)
class TryCatchBlockNodePosition(
val nodeInfo: TryCatchBlockNodeInfo,
var position: TryCatchPosition

View File

@@ -511,6 +511,7 @@ internal fun isSpecialEnumMethod(functionDescriptor: FunctionDescriptor): Boolea
}
internal fun createSpecialEnumMethodBody(
codegen: BaseExpressionCodegen,
name: String,
type: KotlinType,
typeMapper: KotlinTypeMapper
@@ -519,7 +520,7 @@ internal fun createSpecialEnumMethodBody(
val invokeType = typeMapper.mapType(type)
val desc = getSpecialEnumFunDescriptor(invokeType, isValueOf)
val node = MethodNode(API, Opcodes.ACC_STATIC, "fake", desc, null, null)
ExpressionCodegen.putReifiedOperationMarkerIfTypeIsReifiedParameterWithoutPropagation(type, ReifiedTypeInliner.OperationKind.ENUM_REIFIED, InstructionAdapter(node))
ExpressionCodegen.putReifiedOperationMarkerIfTypeIsReifiedParameter(type, ReifiedTypeInliner.OperationKind.ENUM_REIFIED, InstructionAdapter(node), codegen)
if (isValueOf) {
node.visitInsn(Opcodes.ACONST_NULL)
node.visitVarInsn(Opcodes.ALOAD, 0)

View File

@@ -36,8 +36,10 @@ object LateinitIsInitialized : IntrinsicPropertyGetter() {
private fun getStackValue(resolvedCall: ResolvedCall<*>, codegen: ExpressionCodegen): StackValue? {
val expression =
(resolvedCall.extensionReceiver as? ExpressionReceiver)?.expression as? KtCallableReferenceExpression ?: return null
val referenceResolvedCall = expression.callableReference.getResolvedCallWithAssert(codegen.bindingContext)
val receiver = codegen.generateCallableReferenceReceiver(referenceResolvedCall) ?: StackValue.none()
val target = referenceResolvedCall.resultingDescriptor as PropertyDescriptor
return codegen.intermediateValueForProperty(target, true, false, null, false, receiver, null, true)
// TODO: support properties imported from objects as soon as KT-18982 is fixed
val receiver = expression.receiverExpression?.let(codegen::gen) ?: StackValue.none()
val target = expression.callableReference.getResolvedCallWithAssert(codegen.bindingContext).resultingDescriptor
return codegen.intermediateValueForProperty(target as PropertyDescriptor, true, false, null, false, receiver, null, true)
}

View File

@@ -79,22 +79,18 @@ class PopBackwardPropagationTransformer : MethodTransformer() {
private fun analyzeMethodBody(): Array<out Frame<SourceValue>?> {
val frames = Analyzer<SourceValue>(HazardsTrackingInterpreter()).analyze("fake", methodNode)
postprocessStackHazards(frames)
postprocessDupNxM(frames)
return frames
}
private fun postprocessStackHazards(frames: Array<out Frame<SourceValue>?>) {
private fun postprocessDupNxM(frames: Array<out Frame<SourceValue>?>) {
val insns = methodNode.instructions.toArray()
for (i in frames.indices) {
val frame = frames[i] ?: continue
val insn = insns[i]
when (insn.opcode) {
Opcodes.POP2 -> {
val top2 = frame.peekWords(2) ?: throwIncorrectBytecode(insn, frame)
top2.forEach { it.insns.markAsDontTouch() }
}
Opcodes.DUP_X1 -> {
val top2 = frame.peekWords(1, 1) ?: throwIncorrectBytecode(insn, frame)
top2.forEach { it.insns.markAsDontTouch() }

View File

@@ -29,14 +29,13 @@ val testDistProjects = listOf(
":kotlin-test:kotlin-test-jvm",
":kotlin-test:kotlin-test-junit",
":kotlin-test:kotlin-test-js",
":kotlin-daemon-client",
":kotlin-preloader",
":plugins:android-extensions-compiler",
":kotlin-ant",
":kotlin-annotations-jvm",
":kotlin-annotations-android")
val testJvm6ServerRuntime by configurations.creating
dependencies {
depDistProjects.forEach {
testCompile(projectDist(it))
@@ -44,24 +43,16 @@ dependencies {
testCompile(commonDep("junit:junit"))
testCompileOnly(projectDist(":kotlin-test:kotlin-test-jvm"))
testCompileOnly(projectDist(":kotlin-test:kotlin-test-junit"))
testCompile(projectTests(":compiler:tests-common"))
testCompile(projectTests(":generators:test-generator"))
testCompile(project(":compiler.tests-common"))
testCompile(project(":compiler:tests-common-jvm6"))
testCompile(project(":compiler:ir.ir2cfg"))
testCompile(project(":compiler:ir.tree")) // used for deepCopyWithSymbols call that is removed by proguard from the compiler TODO: make it more straightforward
testCompileOnly(project(":kotlin-daemon-client"))
otherCompilerModules.forEach {
testCompileOnly(project(it))
}
testCompile(ideaSdkDeps("openapi", "idea", "util", "asm-all", "commons-httpclient-3.1-patched"))
testRuntime(projectDist(":kotlin-compiler"))
testRuntime(projectDist(":kotlin-daemon-client"))
testRuntime(preloadedDeps("dx", subdir = "android-5.0/lib"))
testRuntime(ideaSdkCoreDeps("*.jar"))
testRuntime(ideaSdkDeps("*.jar"))
testRuntime(files("${System.getProperty("java.home")}/../lib/tools.jar"))
testJvm6ServerRuntime(projectTests(":compiler:tests-common-jvm6"))
}
sourceSets {
@@ -77,7 +68,9 @@ val jar: Jar by tasks
jar.apply {
from(the<JavaPluginConvention>().sourceSets.getByName("main").output)
from("../idea/src").apply {
include("META-INF/extensions/compiler.xml")
include("META-INF/extensions/common.xml",
"META-INF/extensions/kotlin2jvm.xml",
"META-INF/extensions/kotlin2js.xml")
}
}
@@ -89,9 +82,9 @@ projectTest {
systemProperty("kotlin.test.script.classpath", the<JavaPluginConvention>().sourceSets.getByName("test").output.classesDirs.joinToString(File.pathSeparator))
}
fun Project.codegenTest(target: Int, jvm: Int,
jdk: String = "JDK_${if (jvm <= 8) "1" else ""}$jvm",
body: Test.() -> Unit): Test = projectTest("codegenTarget${target}Jvm${jvm}Test") {
evaluationDependsOn(":compiler:tests-common-jvm6")
fun Project.codegenTest(taskName: String, jdk: String, body: Test.() -> Unit): Test = projectTest(taskName) {
dependsOn(*testDistProjects.map { "$it:dist" }.toTypedArray())
workingDir = rootDir
@@ -106,25 +99,34 @@ fun Project.codegenTest(target: Int, jvm: Int,
}
body()
doFirst {
val jdkPath = project.findProperty(jdk) ?: error("$jdk is not optional to run this test")
val jdkPath = project.property(jdk) ?: error("$jdk is not optional to run this test")
executable = "$jdkPath/bin/java"
println("Running test with $executable")
}
group = "verification"
}.also {
task(taskName.replace(Regex("-[a-z]"), { it.value.takeLast(1).toUpperCase() })) {
dependsOn(it)
group = "verification"
}
}
codegenTest(target = 6, jvm = 6, jdk = "JDK_18") {
dependsOn(testJvm6ServerRuntime)
codegenTest("codegen-target6-jvm6-test", "JDK_18") {
dependsOn(":compiler:tests-common-jvm6:build")
val port = project.findProperty("kotlin.compiler.codegen.tests.port")?.toString() ?: "5100"
//TODO make port flexible
val port = "5100"
var jdkProcess: Process? = null
doFirst {
logger.info("Configuring JDK 6 server...")
val jdkPath = project.findProperty("JDK_16") ?: error("JDK_16 is not optional to run this test")
val jdkPath = project.property("JDK_16") ?: error("JDK_16 is not optional to run this test")
val executable = "$jdkPath/bin/java"
val main = "org.jetbrains.kotlin.test.clientserver.TestProcessServer"
val classpath = testJvm6ServerRuntime.asPath
val classpath = getSourceSetsFrom(":compiler:tests-common-jvm6")["main"].output.asPath + ":" +
getSourceSetsFrom(":kotlin-stdlib")["main"].output.asPath + ":" +
getSourceSetsFrom(":kotlin-stdlib")["builtins"].output.asPath + ":" +
getSourceSetsFrom(":kotlin-test:kotlin-test-jvm")["main"].output.asPath
logger.debug("Server classpath: $classpath")
@@ -148,21 +150,19 @@ codegenTest(target = 6, jvm = 6, jdk = "JDK_18") {
}
}
codegenTest(target = 6, jvm = 9) {
codegenTest("codegen-target6-jvm9-test", "JDK_9") {
systemProperty("kotlin.test.default.jvm.target", "1.6")
}
codegenTest(target = 8, jvm = 8) {
codegenTest("codegen-target8-jvm8-test", "JDK_18") {
systemProperty("kotlin.test.default.jvm.target", "1.8")
}
codegenTest(target = 8, jvm = 9) {
codegenTest("codegen-target8-jvm9-test", "JDK_9") {
systemProperty("kotlin.test.default.jvm.target", "1.8")
}
codegenTest(target = 9, jvm = 9) {
codegenTest("codegen-target9-jvm9-test", "JDK_9") {
systemProperty("kotlin.test.default.jvm.target", "1.8")
systemProperty("kotlin.test.substitute.bytecode.1.8.to.1.9", "true")
}
val generateTests by generator("org.jetbrains.kotlin.generators.tests.GenerateCompilerTestsKt")

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
* 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.
@@ -106,12 +106,6 @@ abstract class CommonCompilerArguments : CommonToolArguments() {
)
var coroutinesState: String? by FreezableVar(WARN)
@Argument(
value = "-Xnew-inference",
description = "Enable new experimental generic type inference algorithm"
)
var newInference: Boolean by FreezableVar(false)
open fun configureAnalysisFlags(collector: MessageCollector): MutableMap<AnalysisFlag<*>, Any> {
return HashMap<AnalysisFlag<*>, Any>().apply {
put(AnalysisFlag.skipMetadataVersionCheck, skipMetadataVersionCheck)

View File

@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.cli.common.arguments
import org.jetbrains.kotlin.utils.SmartList
import java.io.Serializable
abstract class CommonToolArguments : Freezable(), Serializable {
@@ -23,7 +24,7 @@ abstract class CommonToolArguments : Freezable(), Serializable {
@JvmStatic private val serialVersionUID = 0L
}
var freeArgs: List<String> by FreezableVar(emptyList())
var freeArgs: MutableList<String> = SmartList()
@Transient var errors: ArgumentParseErrors = ArgumentParseErrors()

View File

@@ -106,16 +106,16 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
@Argument(value = "-Xno-param-assertions", description = "Don't generate not-null assertions on parameters of methods accessible from Java")
var noParamAssertions: Boolean by FreezableVar(false)
@Argument(value = "-Xstrict-java-nullability-assertions", description = "Generate nullability assertions for non-null Java expressions")
var strictJavaNullabilityAssertions: Boolean by FreezableVar(false)
@Argument(value = "-Xno-optimize", description = "Disable optimizations")
var noOptimize: Boolean by FreezableVar(false)
@Argument(
value = "-Xnormalize-constructor-calls",
valueDescription = "{disable|enable}",
description = "Normalize constructor calls (disable: don't normalize; enable: normalize), default is disable"
valueDescription = "{disable|enable|preserve-class-initialization}",
description = "Normalize constructor calls " +
"(disable: don't normalize; enable: normalize; " +
"preserve-class-initialization: normalize preserving class initialization order), " +
"default is disable"
)
var constructorCallNormalizationMode: String? by FreezableVar(JVMConstructorCallNormalizationMode.DEFAULT.description)

View File

@@ -16,7 +16,7 @@
package org.jetbrains.kotlin.cli.common.arguments
import org.jetbrains.kotlin.utils.SmartList
import com.intellij.util.SmartList
import kotlin.reflect.KClass
import kotlin.reflect.KMutableProperty1
import kotlin.reflect.full.findAnnotation
@@ -100,14 +100,12 @@ fun <A : CommonToolArguments> parseCommandLineArguments(args: List<String>, resu
return argument.value == arg
}
val freeArgs = ArrayList<String>()
var i = 0
loop@ while (i < args.size) {
val arg = args[i++]
if (freeArgsStarted) {
freeArgs.add(arg)
result.freeArgs.add(arg)
continue
}
if (arg == FREE_ARGS_DELIMITER) {
@@ -120,7 +118,7 @@ fun <A : CommonToolArguments> parseCommandLineArguments(args: List<String>, resu
when {
arg.startsWith(ADVANCED_ARGUMENT_PREFIX) -> errors.unknownExtraFlags.add(arg)
arg.startsWith("-") -> errors.unknownArgs.add(arg)
else -> freeArgs.add(arg)
else -> result.freeArgs.add(arg)
}
continue
}
@@ -150,8 +148,6 @@ fun <A : CommonToolArguments> parseCommandLineArguments(args: List<String>, resu
updateField(property, result, value, argument.delimiter)
}
result.freeArgs += freeArgs
}
private fun <A : CommonToolArguments> updateField(property: KMutableProperty1<A, Any?>, result: A, value: Any, delimiter: String) {

View File

@@ -1,3 +0,0 @@
# Note that this file is also present in idea/src/META-INF/services
org.jetbrains.kotlin.resolve.jvm.diagnostics.DefaultErrorMessagesJvm
org.jetbrains.kotlin.js.resolve.diagnostics.DefaultErrorMessagesJs

View File

@@ -204,12 +204,6 @@ public abstract class CLICompiler<A extends CommonCompilerArguments> extends CLI
extraLanguageFeatures.put(LanguageFeature.Coroutines, coroutinesState);
}
if (arguments.getNewInference() || configuration.getBoolean(CommonConfigurationKeys.USE_NEW_INFERENCE)) {
extraLanguageFeatures.put(LanguageFeature.NewInference, LanguageFeature.State.ENABLED);
}
setupPlatformSpecificLanguageFeatureSettings(extraLanguageFeatures, arguments);
CommonConfigurationKeysKt.setLanguageVersionSettings(configuration, new LanguageVersionSettingsImpl(
languageVersion,
ApiVersion.createByLanguageVersion(apiVersion),
@@ -218,13 +212,6 @@ public abstract class CLICompiler<A extends CommonCompilerArguments> extends CLI
));
}
protected void setupPlatformSpecificLanguageFeatureSettings(
@NotNull Map<LanguageFeature, LanguageFeature.State> extraLanguageFeatures,
@NotNull A commandLineArguments
) {
// do nothing
}
@Nullable
private static KotlinPaths computeKotlinPaths(@NotNull MessageCollector messageCollector, @NotNull CommonCompilerArguments arguments) {
KotlinPaths paths;

View File

@@ -1,44 +0,0 @@
/*
* Copyright 2010-2017 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.cli.common.script
import org.jetbrains.kotlin.script.KotlinScriptDefinition
import org.jetbrains.kotlin.script.ScriptDefinitionProvider
import org.jetbrains.kotlin.script.StandardScriptDefinition
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.write
class CliScriptDefinitionProvider : ScriptDefinitionProvider {
private val definitions: MutableList<KotlinScriptDefinition> = arrayListOf(StandardScriptDefinition)
private val lock = ReentrantReadWriteLock()
override fun findScriptDefinition(fileName: String) = lock.read {
definitions.firstOrNull { it.isScript(fileName) }
}
override fun isScript(fileName: String) = lock.read {
definitions.any { it.isScript(fileName) }
}
fun setScriptDefinitions(newDefinitions: List<KotlinScriptDefinition>) {
lock.write {
definitions.clear()
definitions.addAll(newDefinitions)
}
}
}

View File

@@ -19,9 +19,9 @@ package org.jetbrains.kotlin.cli.common.script
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.kotlin.script.ScriptContentLoader
import org.jetbrains.kotlin.script.ScriptDefinitionProvider
import org.jetbrains.kotlin.script.KotlinScriptDefinitionProvider
import org.jetbrains.kotlin.script.ScriptDependenciesProvider
import org.jetbrains.kotlin.script.ScriptContentLoader
import java.io.File
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
@@ -30,7 +30,7 @@ import kotlin.script.experimental.dependencies.ScriptDependencies
class CliScriptDependenciesProvider(
project: Project,
private val scriptDefinitionProvider: ScriptDefinitionProvider
private val scriptDefinitionProvider: KotlinScriptDefinitionProvider
) : ScriptDependenciesProvider {
private val cacheLock = ReentrantReadWriteLock()

View File

@@ -47,7 +47,7 @@ import org.jetbrains.kotlin.javac.JavacWrapper
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.load.kotlin.incremental.components.IncrementalCompilationComponents
import org.jetbrains.kotlin.script.KotlinScriptDefinitionFromAnnotatedTemplate
import org.jetbrains.kotlin.script.ScriptDefinitionProvider
import org.jetbrains.kotlin.script.KotlinScriptDefinitionProvider
import org.jetbrains.kotlin.script.StandardScriptDefinition
import org.jetbrains.kotlin.util.PerformanceCounter
import org.jetbrains.kotlin.utils.KotlinPaths
@@ -166,7 +166,7 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
val environment = createEnvironmentWithScriptingSupport(rootDisposable, configuration, arguments, messageCollector)
?: return COMPILATION_ERROR
val scriptDefinitionProvider = ScriptDefinitionProvider.getInstance(environment.project)!!
val scriptDefinitionProvider = KotlinScriptDefinitionProvider.getInstance(environment.project)!!
val scriptFile = File(sourcePath)
if (scriptFile.isDirectory || !scriptDefinitionProvider.isScript(scriptFile.name)) {
val extensionHint =
@@ -228,17 +228,6 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
}
}
override fun setupPlatformSpecificLanguageFeatureSettings(
extraLanguageFeatures: MutableMap<LanguageFeature, LanguageFeature.State>,
commandLineArguments: K2JVMCompilerArguments
) {
if (commandLineArguments.strictJavaNullabilityAssertions) {
extraLanguageFeatures[LanguageFeature.StrictJavaNullabilityAssertions] = LanguageFeature.State.ENABLED
}
super.setupPlatformSpecificLanguageFeatureSettings(extraLanguageFeatures, commandLineArguments)
}
private fun registerJavacIfNeeded(environment: KotlinCoreEnvironment,
arguments: K2JVMCompilerArguments): Boolean {
if (arguments.useJavac) {
@@ -355,8 +344,6 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
}
private fun putAdvancedOptions(configuration: CompilerConfiguration, arguments: K2JVMCompilerArguments) {
configuration.put(CommonConfigurationKeys.USE_NEW_INFERENCE, arguments.newInference)
configuration.put(JVMConfigurationKeys.DISABLE_CALL_ASSERTIONS, arguments.noCallAssertions)
configuration.put(JVMConfigurationKeys.DISABLE_RECEIVER_ASSERTIONS, arguments.noReceiverAssertions)
configuration.put(JVMConfigurationKeys.DISABLE_PARAM_ASSERTIONS, arguments.noParamAssertions)
@@ -387,6 +374,8 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
configuration.put(JVMConfigurationKeys.ADD_BUILT_INS_FROM_COMPILER_TO_DEPENDENCIES, arguments.addCompilerBuiltIns)
configuration.put(JVMConfigurationKeys.CREATE_BUILT_INS_FROM_MODULE_DEPENDENCIES, arguments.loadBuiltInsFromDependencies)
arguments.declarationsOutputPath?.let { configuration.put(JVMConfigurationKeys.DECLARATIONS_JSON_PATH, it) }
}
@@ -460,7 +449,7 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
for (template in scriptTemplates) {
try {
val cls = classloader.loadClass(template)
val def = KotlinScriptDefinitionFromAnnotatedTemplate(cls.kotlin, scriptResolverEnv)
val def = KotlinScriptDefinitionFromAnnotatedTemplate(cls.kotlin, null, null, scriptResolverEnv)
configuration.add(JVMConfigurationKeys.SCRIPT_DEFINITIONS, def)
messageCollector.report(
INFO,

View File

@@ -16,9 +16,23 @@
package org.jetbrains.kotlin.cli.jvm.compiler;
import java.util.Arrays;
import java.util.List;
public enum EnvironmentConfigFiles {
JVM_CONFIG_FILES,
JS_CONFIG_FILES,
NATIVE_CONFIG_FILES,
METADATA_CONFIG_FILES,
JVM_CONFIG_FILES("extensions/common.xml", "extensions/kotlin2jvm.xml"),
JS_CONFIG_FILES("extensions/common.xml", "extensions/kotlin2js.xml"),
NATIVE_CONFIG_FILES("extensions/common.xml"),
METADATA_CONFIG_FILES("extensions/common.xml"),
EMPTY();
private final List<String> files;
EnvironmentConfigFiles(String... fileArray) {
files = Arrays.asList(fileArray);
}
public List<String> getFiles() {
return files;
}
}

View File

@@ -80,7 +80,7 @@ class KotlinCliJavaFileManagerImpl(private val myPsiManager: PsiManager) : CoreJ
private val binaryCache: MutableMap<ClassId, JavaClass?> = THashMap()
private val signatureParsingComponent =
BinaryClassSignatureParser()
BinaryClassSignatureParser(ClassifierResolutionContext { findClass(it, allScope) })
override fun findClass(classId: ClassId, searchScope: GlobalSearchScope): JavaClass? {
val virtualFile = findVirtualFileForTopLevelClass(classId, searchScope) ?: return null

View File

@@ -28,7 +28,11 @@ import com.intellij.ide.highlighter.JavaFileType
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.lang.MetaLanguage
import com.intellij.lang.java.JavaParserDefinition
import com.intellij.lang.jvm.facade.JvmElementProvider
import com.intellij.lang.jvm.facade.JvmFacade
import com.intellij.lang.jvm.facade.JvmFacadeImpl
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.TransactionGuard
import com.intellij.openapi.application.TransactionGuardImpl
import com.intellij.openapi.components.ServiceManager
@@ -38,11 +42,13 @@ import com.intellij.openapi.fileTypes.FileTypeExtensionPoint
import com.intellij.openapi.fileTypes.PlainTextFileType
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.*
import com.intellij.openapi.vfs.impl.ZipHandler
import com.intellij.psi.FileContextProvider
import com.intellij.psi.JavaModuleSystem
import com.intellij.psi.PsiElementFinder
import com.intellij.psi.PsiManager
import com.intellij.psi.augment.PsiAugmentProvider
@@ -69,7 +75,6 @@ import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.ERROR
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.STRONG_WARNING
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.script.CliScriptDefinitionProvider
import org.jetbrains.kotlin.cli.common.script.CliScriptDependenciesProvider
import org.jetbrains.kotlin.cli.common.script.CliScriptReportSink
import org.jetbrains.kotlin.cli.common.toBooleanLenient
@@ -103,10 +108,9 @@ import org.jetbrains.kotlin.resolve.jvm.extensions.PackageFragmentProviderExtens
import org.jetbrains.kotlin.resolve.jvm.modules.JavaModuleResolver
import org.jetbrains.kotlin.resolve.lazy.declarations.CliDeclarationProviderFactoryService
import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactoryService
import org.jetbrains.kotlin.script.ScriptDefinitionProvider
import org.jetbrains.kotlin.script.KotlinScriptDefinitionProvider
import org.jetbrains.kotlin.script.ScriptDependenciesProvider
import org.jetbrains.kotlin.script.ScriptReportSink
import org.jetbrains.kotlin.script.StandardScriptDefinition
import org.jetbrains.kotlin.utils.PathUtil
import java.io.File
import java.util.zip.ZipFile
@@ -155,9 +159,7 @@ class KotlinCoreEnvironment private constructor(
val configuration: CompilerConfiguration = initialConfiguration.apply { setupJdkClasspathRoots(configFiles) }.copy()
init {
PersistentFSConstants::class.java.getDeclaredField("ourMaxIntellisenseFileSize")
.apply { isAccessible = true }
.setInt(null, FileUtilRt.LARGE_FOR_CONTENT_LOADING)
PersistentFSConstants.setMaxIntellisenseFileSize(FileUtilRt.LARGE_FOR_CONTENT_LOADING)
val project = projectEnvironment.project
@@ -189,8 +191,7 @@ class KotlinCoreEnvironment private constructor(
})
sourceFiles.sortBy { it.virtualFile.path }
val scriptDefinitionProvider = ScriptDefinitionProvider.getInstance(project) as? CliScriptDefinitionProvider
if (scriptDefinitionProvider != null) {
KotlinScriptDefinitionProvider.getInstance(project)?.let { scriptDefinitionProvider ->
scriptDefinitionProvider.setScriptDefinitions(
configuration.getList(JVMConfigurationKeys.SCRIPT_DEFINITIONS))
@@ -383,15 +384,14 @@ class KotlinCoreEnvironment private constructor(
private var ourApplicationEnvironment: JavaCoreApplicationEnvironment? = null
private var ourProjectCount = 0
@JvmStatic
fun createForProduction(
@JvmStatic fun createForProduction(
parentDisposable: Disposable, configuration: CompilerConfiguration, configFiles: EnvironmentConfigFiles
): KotlinCoreEnvironment {
setCompatibleBuild()
val appEnv = getOrCreateApplicationEnvironmentForProduction(configuration)
val appEnv = getOrCreateApplicationEnvironmentForProduction(configuration, configFiles.files)
// Disposing of the environment is unsafe in production then parallel builds are enabled, but turning it off universally
// breaks a lot of tests, therefore it is disabled for production and enabled for tests
if (System.getProperty(KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY).toBooleanLenient() != true) {
if (!(System.getProperty(KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY).toBooleanLenient() ?: false)) {
// JPS may run many instances of the compiler in parallel (there's an option for compiling independent modules in parallel in IntelliJ)
// All projects share the same ApplicationEnvironment, and when the last project is disposed, the ApplicationEnvironment is disposed as well
Disposer.register(parentDisposable, Disposable {
@@ -417,33 +417,28 @@ class KotlinCoreEnvironment private constructor(
}
@TestOnly
@JvmStatic
fun createForTests(
parentDisposable: Disposable, initialConfiguration: CompilerConfiguration, extensionConfigs: EnvironmentConfigFiles
@JvmStatic fun createForTests(
parentDisposable: Disposable, configuration: CompilerConfiguration, extensionConfigs: EnvironmentConfigFiles
): KotlinCoreEnvironment {
val configuration = initialConfiguration.copy()
if (configuration.getList(JVMConfigurationKeys.SCRIPT_DEFINITIONS).isEmpty()) {
configuration.add(JVMConfigurationKeys.SCRIPT_DEFINITIONS, StandardScriptDefinition)
}
// Tests are supposed to create a single project and dispose it right after use
return KotlinCoreEnvironment(
parentDisposable,
createApplicationEnvironment(parentDisposable, configuration, unitTestMode = true),
configuration,
extensionConfigs
)
return KotlinCoreEnvironment(parentDisposable,
createApplicationEnvironment(parentDisposable, configuration, extensionConfigs.files),
configuration,
extensionConfigs)
}
// used in the daemon for jar cache cleanup
val applicationEnvironment: JavaCoreApplicationEnvironment? get() = ourApplicationEnvironment
private fun getOrCreateApplicationEnvironmentForProduction(configuration: CompilerConfiguration): JavaCoreApplicationEnvironment {
private fun getOrCreateApplicationEnvironmentForProduction(
configuration: CompilerConfiguration, configFilePaths: List<String>
): JavaCoreApplicationEnvironment {
synchronized (APPLICATION_LOCK) {
if (ourApplicationEnvironment != null)
return ourApplicationEnvironment!!
val parentDisposable = Disposer.newDisposable()
ourApplicationEnvironment = createApplicationEnvironment(parentDisposable, configuration, unitTestMode = false)
ourApplicationEnvironment = createApplicationEnvironment(parentDisposable, configuration, configFilePaths)
ourProjectCount = 0
Disposer.register(parentDisposable, Disposable {
synchronized (APPLICATION_LOCK) {
@@ -464,17 +459,17 @@ class KotlinCoreEnvironment private constructor(
}
private fun createApplicationEnvironment(
parentDisposable: Disposable,
configuration: CompilerConfiguration,
unitTestMode: Boolean
parentDisposable: Disposable, configuration: CompilerConfiguration, configFilePaths: List<String>
): JavaCoreApplicationEnvironment {
Extensions.cleanRootArea(parentDisposable)
registerAppExtensionPoints()
val applicationEnvironment = object : JavaCoreApplicationEnvironment(parentDisposable, unitTestMode) {
val applicationEnvironment = object : JavaCoreApplicationEnvironment(parentDisposable) {
override fun createJrtFileSystem(): VirtualFileSystem? = CoreJrtFileSystem()
}
registerApplicationExtensionPointsAndExtensionsFrom(configuration, "extensions/compiler.xml")
for (configPath in configFilePaths) {
registerApplicationExtensionPointsAndExtensionsFrom(configuration, configPath)
}
registerApplicationServicesForCLI(applicationEnvironment)
registerApplicationServices(applicationEnvironment)
@@ -496,6 +491,8 @@ class KotlinCoreEnvironment private constructor(
//
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), TypeAnnotationModifier.EP_NAME, TypeAnnotationModifier::class.java)
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), MetaLanguage.EP_NAME, MetaLanguage::class.java)
//
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), JavaModuleSystem.EP_NAME, JavaModuleSystem::class.java)
}
private fun registerApplicationExtensionPointsAndExtensionsFrom(configuration: CompilerConfiguration, configFilePath: String) {
@@ -545,15 +542,16 @@ class KotlinCoreEnvironment private constructor(
private fun registerProjectExtensionPoints(area: ExtensionsArea) {
CoreApplicationEnvironment.registerExtensionPoint(area, PsiTreeChangePreprocessor.EP_NAME, PsiTreeChangePreprocessor::class.java)
CoreApplicationEnvironment.registerExtensionPoint(area, PsiElementFinder.EP_NAME, PsiElementFinder::class.java)
CoreApplicationEnvironment.registerExtensionPoint(area, JvmElementProvider.EP_NAME, JvmElementProvider::class.java)
}
// made public for Upsource
@JvmStatic
fun registerProjectServices(projectEnvironment: JavaCoreProjectEnvironment, messageCollector: MessageCollector?) {
with (projectEnvironment.project) {
val scriptDefinitionProvider = CliScriptDefinitionProvider()
registerService(ScriptDefinitionProvider::class.java, scriptDefinitionProvider)
registerService(ScriptDependenciesProvider::class.java, CliScriptDependenciesProvider(projectEnvironment.project, scriptDefinitionProvider))
val kotlinScriptDefinitionProvider = KotlinScriptDefinitionProvider()
registerService(KotlinScriptDefinitionProvider::class.java, kotlinScriptDefinitionProvider)
registerService(ScriptDependenciesProvider::class.java, CliScriptDependenciesProvider(projectEnvironment.project, kotlinScriptDefinitionProvider))
registerService(KotlinJavaPsiFacade::class.java, KotlinJavaPsiFacade(this))
registerService(KtLightClassForFacade.FacadeStubCache::class.java, KtLightClassForFacade.FacadeStubCache(this))
if (messageCollector != null) {

View File

@@ -20,7 +20,7 @@ import com.intellij.mock.MockProject
import com.sun.tools.javac.util.Context
import org.jetbrains.kotlin.asJava.LightClassGenerationSupport
import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.ERROR
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.STRONG_WARNING
import org.jetbrains.kotlin.cli.jvm.config.jvmClasspathRoots
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.JVMConfigurationKeys
@@ -48,7 +48,7 @@ object JavacWrapperRegistrar {
Class.forName(JAVAC_CONTEXT_CLASS)
}
catch (e: ClassNotFoundException) {
messageCollector.report(ERROR, "'$JAVAC_CONTEXT_CLASS' class can't be found ('tools.jar' is not found)")
messageCollector.report(STRONG_WARNING, "'$JAVAC_CONTEXT_CLASS' class can't be found ('tools.jar' is not found)")
return false
}

View File

@@ -153,8 +153,8 @@ class ReplCodeAnalyzer(environment: KotlinCoreEnvironment) {
return delegateFactory.getPackageMemberDeclarationProvider(packageFqName)
}
override fun diagnoseMissingPackageFragment(fqName: FqName, file: KtFile?) {
delegateFactory.diagnoseMissingPackageFragment(fqName, file)
override fun diagnoseMissingPackageFragment(file: KtFile) {
delegateFactory.diagnoseMissingPackageFragment(file)
}
class AdaptablePackageMemberDeclarationProvider(

View File

@@ -61,6 +61,7 @@ messages/**)
-dontwarn net.jpountz.lz4.LZ4Factory
-dontwarn org.jetbrains.annotations.ReadOnly
-dontwarn org.jetbrains.annotations.Mutable
-dontwarn com.intellij.util.io.TarUtil
#-libraryjars '<rtjar>'
#-libraryjars '<jssejar>'
@@ -216,9 +217,4 @@ messages/**)
-keep class com.sun.source.** { *; }
# for coroutines
-keep class kotlinx.coroutines.** { *; }
# for webdemo
-keep class com.intellij.openapi.progress.ProgressManager { *; }
-keep class kotlinx.coroutines.** { *; }

View File

@@ -52,7 +52,7 @@ class Preprocessor(val logger: Logger = SystemOutLogger) {
init {
val configuration = CompilerConfiguration()
val environment = KotlinCoreEnvironment.createForProduction(Disposable { }, configuration, EnvironmentConfigFiles.JVM_CONFIG_FILES)
val environment = KotlinCoreEnvironment.createForProduction(Disposable { }, configuration, EnvironmentConfigFiles.EMPTY)
val project = environment.project
jetPsiFactory = KtPsiFactory(project)

View File

@@ -4,8 +4,7 @@ apply { plugin("kotlin") }
jvmTarget = "1.6"
dependencies {
compile(project(":core:descriptors"))
compile(project(":core:descriptors.jvm"))
compile(project(":core"))
compile(project(":compiler:util"))
compile(project(":compiler:cli-common"))
compile(ideaSdkCoreDeps(*(rootProject.extra["ideaCoreSdkJars"] as Array<String>)))

View File

@@ -63,7 +63,7 @@ open class KotlinJvmReplService(
try {
val cls = classloader.loadClass(templateClassName)
val def = KotlinScriptDefinitionFromAnnotatedTemplate(cls.kotlin, emptyMap())
val def = KotlinScriptDefinitionFromAnnotatedTemplate(cls.kotlin, null, null, emptyMap())
messageCollector.report(INFO, "New script definition $templateClassName: files pattern = \"${def.scriptFilePattern}\", " +
"resolver = ${def.dependencyResolver.javaClass.name}")
return def

View File

@@ -4,8 +4,7 @@ apply { plugin("kotlin") }
jvmTarget = "1.6"
dependencies {
compile(project(":core:descriptors"))
compile(project(":core:descriptors.jvm"))
compile(project(":core"))
compile(project(":compiler:util"))
compile(project(":compiler:frontend"))
}

View File

@@ -16,11 +16,14 @@
package org.jetbrains.kotlin.load.java.structure.impl.classFiles
import com.intellij.psi.CommonClassNames
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.kotlin.builtins.PrimitiveType
import org.jetbrains.kotlin.load.java.structure.JavaClassifierType
import org.jetbrains.kotlin.load.java.structure.JavaType
import org.jetbrains.kotlin.load.java.structure.JavaTypeParameter
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.utils.addToStdlib.flattenTo
import org.jetbrains.kotlin.utils.compact
@@ -30,11 +33,14 @@ import java.text.StringCharacterIterator
/**
* Take a look at com.intellij.psi.impl.compiled.SignatureParsing
* NOTE: currently this class can simply be converted to an object, but there are postponed plans
* to introduce cached instance for java.lang.Object type that would require injected class finder.
* So please, do not convert it to object
*/
class BinaryClassSignatureParser {
class BinaryClassSignatureParser(globalContext: ClassifierResolutionContext) {
companion object {
private val JAVA_LANG_OBJECT = ClassId.topLevel(FqName(CommonClassNames.JAVA_LANG_OBJECT))
}
private val JAVA_LANG_OBJECT_CLASSIFIER_TYPE: JavaClassifierType =
PlainJavaClassifierType({ globalContext.resolveClass(JAVA_LANG_OBJECT) }, emptyList())
fun parseTypeParametersDeclaration(signature: CharacterIterator, context: ClassifierResolutionContext): List<JavaTypeParameter> {
if (signature.current() != '<') {
@@ -62,14 +68,25 @@ class BinaryClassSignatureParser {
val parameterName = name.toString()
// postpone list allocation till a second bound is seen; ignore sole Object bound
val bounds: MutableList<JavaClassifierType> = ContainerUtil.newSmartList()
var bounds: MutableList<JavaClassifierType>? = null
var jlo = false
while (signature.current() == ':') {
signature.next()
val bound = parseClassifierRefSignature(signature, context) ?: continue
if (bounds == null) {
if (JAVA_LANG_OBJECT_CLASSIFIER_TYPE === bound) {
jlo = true
continue
}
bounds = ContainerUtil.newSmartList()
if (jlo) {
bounds.add(JAVA_LANG_OBJECT_CLASSIFIER_TYPE)
}
}
bounds.add(bound)
}
return BinaryJavaTypeParameter(Name.identifier(parameterName), bounds)
return BinaryJavaTypeParameter(Name.identifier(parameterName), bounds ?: emptyList())
}
fun parseClassifierRefSignature(signature: CharacterIterator, context: ClassifierResolutionContext): JavaClassifierType? {
@@ -131,6 +148,8 @@ class BinaryClassSignatureParser {
}
signature.next()
if (canonicalName.toString() == "java/lang/Object") return JAVA_LANG_OBJECT_CLASSIFIER_TYPE
return PlainJavaClassifierType(
{ context.resolveByInternalName(canonicalName.toString()) },
argumentGroups.reversed().flattenTo(arrayListOf()).compact()

View File

@@ -32,9 +32,6 @@ object JvmBindingContextSlices {
@JvmField
val RECEIVER_RUNTIME_ASSERTION_INFO: WritableSlice<ExpressionReceiver, RuntimeAssertionInfo> = BasicWritableSlice(RewritePolicy.DO_NOTHING)
@JvmField
val BODY_RUNTIME_ASSERTION_INFO: WritableSlice<KtExpression, RuntimeAssertionInfo> = BasicWritableSlice(RewritePolicy.DO_NOTHING)
@JvmField
val LOAD_FROM_JAVA_SIGNATURE_ERRORS: WritableSlice<DeclarationDescriptor, List<String>> = Slices.createCollectiveSlice()

View File

@@ -1,43 +0,0 @@
/*
* Copyright 2010-2017 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.resolve.jvm
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.annotations.FilteredAnnotations
import org.jetbrains.kotlin.load.java.JvmAnnotationNames
import org.jetbrains.kotlin.resolve.BindingTrace
import org.jetbrains.kotlin.resolve.DeclarationReturnTypeSanitizer
import org.jetbrains.kotlin.types.UnwrappedType
import org.jetbrains.kotlin.types.WrappedTypeFactory
object JvmDeclarationReturnTypeSanitizer : DeclarationReturnTypeSanitizer {
override fun sanitizeReturnType(
inferred: UnwrappedType,
wrappedTypeFactory: WrappedTypeFactory,
trace: BindingTrace,
languageVersionSettings: LanguageVersionSettings
): UnwrappedType =
if (languageVersionSettings.supportsFeature(LanguageFeature.StrictJavaNullabilityAssertions)) {
// NB can't check for presence of EnhancedNullability here,
// because it will also cause recursion in declaration type resolution.
inferred.replaceAnnotations(FilteredAnnotations(inferred.annotations) {
it != JvmAnnotationNames.ENHANCED_NULLABILITY_ANNOTATION
})
}
else inferred
}

View File

@@ -18,34 +18,34 @@ package org.jetbrains.kotlin.resolve.jvm
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor
import org.jetbrains.kotlin.load.java.typeEnhancement.hasEnhancedNullability
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingTrace
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.resolve.calls.callUtil.isSafeCall
import org.jetbrains.kotlin.resolve.calls.checkers.AdditionalTypeChecker
import org.jetbrains.kotlin.resolve.calls.checkers.CallChecker
import org.jetbrains.kotlin.resolve.calls.checkers.CallCheckerContext
import org.jetbrains.kotlin.resolve.calls.context.ResolutionContext
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValue
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.checker.isClassType
import org.jetbrains.kotlin.types.typeUtil.immediateSupertypes
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class RuntimeAssertionInfo(val needNotNullAssertion: Boolean, val message: String) {
interface DataFlowExtras {
class OnlyMessage(message: String) : DataFlowExtras {
override val canBeNull: Boolean get() = true
override val possibleTypes: Set<KotlinType> get() = setOf()
override val presentableText: String = message
}
val canBeNull: Boolean
val possibleTypes: Set<KotlinType>
val presentableText: String
}
@@ -83,22 +83,17 @@ class RuntimeAssertionInfo(val needNotNullAssertion: Boolean, val message: Strin
}
}
private val KtExpression.textForRuntimeAssertionInfo
get() = StringUtil.trimMiddle(text, 50)
class RuntimeAssertionsDataFlowExtras(
private val c: ResolutionContext<*>,
private val expressionType: KotlinType,
private val dataFlowValue: DataFlowValue,
private val expression: KtExpression
) : RuntimeAssertionInfo.DataFlowExtras {
private val dataFlowValue by lazy(LazyThreadSafetyMode.PUBLICATION) {
DataFlowValueFactory.createDataFlowValue(expression, expressionType, c)
}
override val canBeNull: Boolean
get() = c.dataFlowInfo.getStableNullability(dataFlowValue).canBeNull()
override val possibleTypes: Set<KotlinType>
get() = c.dataFlowInfo.getCollectedTypes(dataFlowValue)
override val presentableText: String
get() = expression.textForRuntimeAssertionInfo
get() = StringUtil.trimMiddle(expression.text, 50)
}
object RuntimeAssertionsTypeChecker : AdditionalTypeChecker {
@@ -108,7 +103,7 @@ object RuntimeAssertionsTypeChecker : AdditionalTypeChecker {
val assertionInfo = RuntimeAssertionInfo.create(
c.expectedType,
expressionType,
RuntimeAssertionsDataFlowExtras(c, expressionType, expression)
RuntimeAssertionsDataFlowExtras(c, DataFlowValueFactory.createDataFlowValue(expression, expressionType, c), expression)
)
if (assertionInfo != null) {
@@ -131,112 +126,16 @@ object RuntimeAssertionsOnExtensionReceiverCallChecker : CallChecker {
val expressionReceiverValue = receiverValue.safeAs<ExpressionReceiver>() ?: return
val receiverExpression = expressionReceiverValue.expression
val c = context.resolutionContext
val dataFlowValue = DataFlowValueFactory.createDataFlowValue(receiverExpression, receiverValue.type, c)
val assertionInfo = RuntimeAssertionInfo.create(
receiverParameter.type,
receiverValue.type,
RuntimeAssertionsDataFlowExtras(c, receiverValue.type, receiverExpression)
RuntimeAssertionsDataFlowExtras(c, dataFlowValue, receiverExpression)
)
if (assertionInfo != null) {
c.trace.record(JvmBindingContextSlices.RECEIVER_RUNTIME_ASSERTION_INFO, expressionReceiverValue, assertionInfo)
}
}
}
object RuntimeAssertionsOnDeclarationBodyChecker {
@JvmStatic
fun check(
declaration: KtDeclaration,
descriptor: DeclarationDescriptor,
bindingTrace: BindingTrace,
languageVersionSettings: LanguageVersionSettings
) {
if (!languageVersionSettings.supportsFeature(LanguageFeature.StrictJavaNullabilityAssertions)) return
when {
declaration is KtProperty && descriptor is VariableDescriptor ->
checkLocalVariable(declaration, descriptor, bindingTrace)
declaration is KtFunction && descriptor is FunctionDescriptor ->
checkFunction(declaration, descriptor, bindingTrace)
declaration is KtProperty && descriptor is PropertyDescriptor ->
checkProperty(declaration, descriptor, bindingTrace)
declaration is KtPropertyAccessor && descriptor is PropertyAccessorDescriptor ->
checkPropertyAccessor(declaration, descriptor, bindingTrace)
}
}
private fun checkLocalVariable(
declaration: KtProperty,
descriptor: VariableDescriptor,
bindingTrace: BindingTrace
) {
if (declaration.typeReference != null) return
checkNullabilityAssertion(declaration.initializer ?: return, descriptor.type, bindingTrace)
}
private fun checkFunction(
declaration: KtFunction,
descriptor: FunctionDescriptor,
bindingTrace: BindingTrace
) {
if (declaration.typeReference != null || declaration.hasBlockBody()) return
checkNullabilityAssertion(declaration.bodyExpression ?: return, descriptor.returnType ?: return,
bindingTrace)
}
private fun checkProperty(
declaration: KtProperty,
descriptor: PropertyDescriptor,
bindingTrace: BindingTrace
) {
if (declaration.typeReference != null) return
// TODO nullability assertion on delegate initialization expression, see KT-20823
if (declaration.hasDelegateExpression()) return
checkNullabilityAssertion(declaration.initializer ?: return, descriptor.type, bindingTrace)
}
private fun checkPropertyAccessor(
declaration: KtPropertyAccessor,
descriptor: PropertyAccessorDescriptor,
bindingTrace: BindingTrace
) {
if (declaration.property.typeReference != null || declaration.hasBlockBody()) return
checkNullabilityAssertion(declaration.bodyExpression ?: return, descriptor.correspondingProperty.type,
bindingTrace)
}
private fun checkNullabilityAssertion(
expression: KtExpression,
declarationType: KotlinType,
bindingTrace: BindingTrace
) {
if (declarationType.unwrap().canContainNull()) return
val expressionType = bindingTrace.getType(expression) ?: return
if (expressionType.isError) return
if (!expressionType.hasEnhancedNullability()) return
bindingTrace.record(
JvmBindingContextSlices.BODY_RUNTIME_ASSERTION_INFO,
expression,
RuntimeAssertionInfo(true, expression.textForRuntimeAssertionInfo)
)
}
private fun UnwrappedType.canContainNull(): Boolean {
val upper = upperIfFlexible()
return when {
upper.isMarkedNullable -> true
upper.isClassType -> false
else -> upper.immediateSupertypes().all { it.unwrap().canContainNull() }
}
}
}
}

View File

@@ -44,7 +44,7 @@ class JavaNullabilityChecker : AdditionalTypeChecker {
doCheckType(
expressionType,
c.expectedType,
{ DataFlowValueFactory.createDataFlowValue(expression, expressionType, c) } ,
DataFlowValueFactory.createDataFlowValue(expression, expressionType, c),
c.dataFlowInfo
) { expectedMustNotBeNull, actualMayBeNull ->
c.trace.report(ErrorsJvm.NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS.on(expression, expectedMustNotBeNull, actualMayBeNull))
@@ -57,15 +57,16 @@ class JavaNullabilityChecker : AdditionalTypeChecker {
val subjectExpression = expression.subjectExpression ?: return
val type = c.trace.getType(subjectExpression) ?: return
if (type.isFlexible() && TypeUtils.isNullableType(type.asFlexibleType().upperBound)) {
val dataFlowValue = DataFlowValueFactory.createDataFlowValue(subjectExpression, type, c)
val dataFlowInfo = c.trace[BindingContext.EXPRESSION_TYPE_INFO, subjectExpression]?.dataFlowInfo
if (dataFlowInfo != null && !dataFlowInfo.getStableNullability(dataFlowValue).canBeNull()) {
return
}
val enumClassDescriptor = WhenChecker.getClassDescriptorOfTypeIfEnum(type) ?: return
val context = c.trace.bindingContext
if (WhenChecker.getEnumMissingCases(expression, context, enumClassDescriptor).isEmpty()
&& !WhenChecker.containsNullCase(expression, context)) {
val subjectDataFlowValue = DataFlowValueFactory.createDataFlowValue(subjectExpression, type, c)
val dataFlowInfo = c.trace[BindingContext.EXPRESSION_TYPE_INFO, subjectExpression]?.dataFlowInfo
if (dataFlowInfo != null && !dataFlowInfo.getStableNullability(subjectDataFlowValue).canBeNull()) {
return
}
c.trace.report(ErrorsJvm.WHEN_ENUM_CAN_BE_NULL_IN_JAVA.on(expression.subjectExpression!!))
}
@@ -76,9 +77,7 @@ class JavaNullabilityChecker : AdditionalTypeChecker {
val baseExpression = expression.baseExpression ?: return
val baseExpressionType = c.trace.getType(baseExpression) ?: return
doIfNotNull(
baseExpressionType,
{ DataFlowValueFactory.createDataFlowValue(baseExpression, baseExpressionType, c) },
c
DataFlowValueFactory.createDataFlowValue(baseExpression, baseExpressionType, c), c
) {
c.trace.report(Errors.UNNECESSARY_NOT_NULL_ASSERTION.on(expression.operationReference, baseExpressionType))
}
@@ -94,7 +93,7 @@ class JavaNullabilityChecker : AdditionalTypeChecker {
expression, expression.left!!, expression.right!!, c,
{ c.trace.getType(it) },
{ value ->
doIfNotNull(value.type, { value }, c) { Nullability.NOT_NULL } ?: Nullability.UNKNOWN
doIfNotNull(value, c) { Nullability.NOT_NULL } ?: Nullability.UNKNOWN
}
)
}
@@ -104,12 +103,9 @@ class JavaNullabilityChecker : AdditionalTypeChecker {
}
override fun checkReceiver(receiverParameter: ReceiverParameterDescriptor, receiverArgument: ReceiverValue, safeAccess: Boolean, c: CallResolutionContext<*>) {
val dataFlowValue by lazy(LazyThreadSafetyMode.NONE) {
DataFlowValueFactory.createDataFlowValue(receiverArgument, c)
}
val dataFlowValue = DataFlowValueFactory.createDataFlowValue(receiverArgument, c)
if (safeAccess) {
doIfNotNull(receiverArgument.type, { dataFlowValue }, c) {
doIfNotNull(dataFlowValue, c) {
c.trace.report(Errors.UNNECESSARY_SAFE_CALL.on(c.call.callOperationNode!!.psi, receiverArgument.type))
}
@@ -119,7 +115,7 @@ class JavaNullabilityChecker : AdditionalTypeChecker {
doCheckType(
receiverArgument.type,
receiverParameter.type,
{ dataFlowValue },
dataFlowValue,
c.dataFlowInfo
) { expectedMustNotBeNull,
actualMayBeNull ->
@@ -133,7 +129,7 @@ class JavaNullabilityChecker : AdditionalTypeChecker {
private fun doCheckType(
expressionType: KotlinType,
expectedType: KotlinType,
dataFlowValue: () -> DataFlowValue,
dataFlowValue: DataFlowValue,
dataFlowInfo: DataFlowInfo,
reportWarning: (expectedMustNotBeNull: ErrorsJvm.NullabilityInformationSource, actualMayBeNull: ErrorsJvm.NullabilityInformationSource) -> Unit
) {
@@ -142,28 +138,26 @@ class JavaNullabilityChecker : AdditionalTypeChecker {
}
val expectedMustNotBeNull = expectedType.mustNotBeNull()
if (dataFlowInfo.getStableNullability(dataFlowValue) == Nullability.NOT_NULL) {
return
}
val actualMayBeNull = expressionType.mayBeNull()
if (expectedMustNotBeNull == ErrorsJvm.NullabilityInformationSource.KOTLIN && actualMayBeNull == ErrorsJvm.NullabilityInformationSource.KOTLIN) {
// a type mismatch error will be reported elsewhere
return
}
if (expectedMustNotBeNull != null && actualMayBeNull != null &&
dataFlowInfo.getStableNullability(dataFlowValue()) != Nullability.NOT_NULL) {
if (expectedMustNotBeNull != null && actualMayBeNull != null) {
reportWarning(expectedMustNotBeNull, actualMayBeNull)
}
}
private fun <T : Any> doIfNotNull(
type: KotlinType,
dataFlowValue: () -> DataFlowValue,
c: ResolutionContext<*>,
body: () -> T
) = if (type.mustNotBeNull() == ErrorsJvm.NullabilityInformationSource.JAVA &&
c.dataFlowInfo.getStableNullability(dataFlowValue()).canBeNull())
body()
else
null
private fun <T : Any> doIfNotNull(dataFlowValue: DataFlowValue, c: ResolutionContext<*>, body: () -> T): T? =
if (c.dataFlowInfo.getStableNullability(dataFlowValue).canBeNull() &&
dataFlowValue.type.mustNotBeNull() == ErrorsJvm.NullabilityInformationSource.JAVA)
body()
else null
private fun KotlinType.mustNotBeNull(): ErrorsJvm.NullabilityInformationSource? = when {
!isError && !isFlexible() && !TypeUtils.acceptsNullable(this) -> ErrorsJvm.NullabilityInformationSource.KOTLIN

View File

@@ -81,9 +81,7 @@ object JvmPlatformConfigurator : PlatformConfigurator(
delegationFilter = JvmDelegationFilter,
overridesBackwardCompatibilityHelper = JvmOverridesBackwardCompatibilityHelper,
declarationReturnTypeSanitizer = JvmDeclarationReturnTypeSanitizer
overridesBackwardCompatibilityHelper = JvmOverridesBackwardCompatibilityHelper
) {
override fun configureModuleComponents(container: StorageComponentContainer) {
container.useImpl<JvmReflectionAPICallChecker>()

View File

@@ -1 +0,0 @@
org.jetbrains.kotlin.script.ScriptHelperImpl

View File

@@ -35,17 +35,21 @@ import kotlin.script.templates.AcceptedAnnotations
open class KotlinScriptDefinitionFromAnnotatedTemplate(
template: KClass<out Any>,
providedResolver: DependenciesResolver? = null,
providedScriptFilePattern: String? = null,
val environment: Map<String, Any?>? = null,
val templateClasspath: List<File> = emptyList()
) : KotlinScriptDefinition(template) {
val scriptFilePattern by lazy {
takeUnlessError { template.annotations.firstIsInstanceOrNull<kotlin.script.templates.ScriptTemplateDefinition>()?.scriptFilePattern }
providedScriptFilePattern
?: takeUnlessError { template.annotations.firstIsInstanceOrNull<kotlin.script.templates.ScriptTemplateDefinition>()?.scriptFilePattern }
?: takeUnlessError { template.annotations.firstIsInstanceOrNull<org.jetbrains.kotlin.script.ScriptTemplateDefinition>()?.scriptFilePattern }
?: DEFAULT_SCRIPT_FILE_PATTERN
}
override val dependencyResolver: DependenciesResolver by lazy {
providedResolver ?:
resolverFromAnnotation(template) ?:
resolverFromLegacyAnnotation(template) ?:
DependenciesResolver.NoDependencies

View File

@@ -14,14 +14,16 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.idea.core.script
package org.jetbrains.kotlin.script
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionPointName
import org.jetbrains.kotlin.script.KotlinScriptDefinition
import com.intellij.openapi.extensions.Extensions
import com.intellij.openapi.project.Project
import java.io.File
import java.net.URLClassLoader
import kotlin.script.experimental.dependencies.DependenciesResolver
@Deprecated("Use ScriptDefinitionContributor EP and loadDefinitionsFromTemplates top level function")
interface ScriptTemplatesProvider {
// for resolving ambiguities
@@ -30,8 +32,7 @@ interface ScriptTemplatesProvider {
@Deprecated("Parameter isn't used for resolving priorities anymore. " +
"com.intellij.openapi.extensions.LoadingOrder constants can be used to order providers when registered from Intellij plugin.",
ReplaceWith("0"))
val version: Int
get() = 0
val version: Int get() = 0
val isValid: Boolean
@@ -59,13 +60,36 @@ interface ScriptTemplatesProvider {
}
}
class ScriptTemplatesProviderAdapter(private val templatesProvider: ScriptTemplatesProvider) : ScriptDefinitionContributor {
override val id: String
get() = templatesProvider.id
fun makeScriptDefsFromTemplatesProviderExtensions(project: Project,
errorsHandler: ((ScriptTemplatesProvider, Throwable) -> Unit)
): List<KotlinScriptDefinition> =
makeScriptDefsFromTemplatesProviders(Extensions.getArea(project).getExtensionPoint(ScriptTemplatesProvider.EP_NAME).extensions.asIterable(),
errorsHandler)
override fun getDefinitions(): List<KotlinScriptDefinition> {
return loadDefinitionsFromTemplates(
templatesProvider.templateClassNames.toList(), templatesProvider.templateClasspath,
templatesProvider.environment.orEmpty(), templatesProvider.additionalResolverClasspath)
fun makeScriptDefsFromTemplatesProviders(providers: Iterable<ScriptTemplatesProvider>,
errorsHandler: ((ScriptTemplatesProvider, Throwable) -> Unit) = { _, ex -> throw ex }
): List<KotlinScriptDefinition> = providers.flatMap { provider ->
try {
val loader = createClassLoader(provider)
provider.templateClassNames.map {
KotlinScriptDefinitionFromAnnotatedTemplate(
loader.loadClass(it).kotlin, provider.resolver,
provider.filePattern, provider.environment, provider.templateClasspath
)
}
}
}
catch (ex: Throwable) {
LOG.info("Templates provider ${provider.id} is invalid: ${ex.message}")
errorsHandler(provider, ex)
emptyList<KotlinScriptDefinition>()
}
}
private fun createClassLoader(provider: ScriptTemplatesProvider): ClassLoader {
val classpath = provider.templateClasspath + provider.additionalResolverClasspath
LOG.info("[kts] loading script definitions ${provider.templateClassNames} using cp: ${classpath.joinToString(File.pathSeparator)}")
val baseLoader = ScriptTemplatesProvider::class.java.classLoader
return if (classpath.isEmpty()) baseLoader else URLClassLoader(classpath.map { it.toURI().toURL() }.toTypedArray(), baseLoader)
}
private val LOG = Logger.getInstance("ScriptTemplatesProviders")

View File

@@ -4,8 +4,7 @@ apply { plugin("kotlin") }
jvmTarget = "1.6"
dependencies {
compile(project(":core:descriptors"))
compile(project(":core:deserialization"))
compile(project(":core"))
compile(project(":compiler:util"))
compile(project(":compiler:container"))
compile(project(":compiler:resolution"))
@@ -17,3 +16,4 @@ sourceSets {
"main" { projectDefault() }
"test" {}
}

View File

@@ -52,7 +52,6 @@ import org.jetbrains.kotlin.resolve.calls.resolvedCallUtil.getDispatchReceiverWi
import org.jetbrains.kotlin.resolve.calls.resolvedCallUtil.hasThisOrNoDispatchReceiver
import org.jetbrains.kotlin.resolve.calls.util.FakeCallableDescriptorForObject
import org.jetbrains.kotlin.resolve.calls.util.isSingleUnderscore
import org.jetbrains.kotlin.resolve.checkers.PlatformDiagnosticSuppressor
import org.jetbrains.kotlin.resolve.descriptorUtil.isEffectivelyExternal
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.types.KotlinType
@@ -65,26 +64,15 @@ class ControlFlowInformationProvider private constructor(
private val subroutine: KtElement,
private val trace: BindingTrace,
private val pseudocode: Pseudocode,
private val languageVersionSettings: LanguageVersionSettings,
private val diagnosticSuppressor: PlatformDiagnosticSuppressor
private val languageVersionSettings: LanguageVersionSettings
) {
private val pseudocodeVariablesData by lazy {
PseudocodeVariablesData(pseudocode, trace.bindingContext)
}
constructor(
declaration: KtElement,
trace: BindingTrace,
languageVersionSettings: LanguageVersionSettings,
diagnosticSuppressor: PlatformDiagnosticSuppressor
) : this(
declaration,
trace,
ControlFlowProcessor(trace).generatePseudocode(declaration),
languageVersionSettings,
diagnosticSuppressor
)
constructor(declaration: KtElement, trace: BindingTrace, languageVersionSettings: LanguageVersionSettings)
: this(declaration, trace, ControlFlowProcessor(trace).generatePseudocode(declaration), languageVersionSettings)
fun checkForLocalClassOrObjectMode() {
// Local classes and objects are analyzed twice: when TopDownAnalyzer processes it and as a part of its container.
@@ -190,8 +178,7 @@ class ControlFlowInformationProvider private constructor(
val expectedType = functionDescriptor?.returnType
val providerForLocalDeclaration = ControlFlowInformationProvider(
element, trace, localDeclarationInstruction.body, languageVersionSettings, diagnosticSuppressor
)
element, trace, localDeclarationInstruction.body, languageVersionSettings)
providerForLocalDeclaration.checkFunction(expectedType)
}
@@ -367,8 +354,7 @@ class ControlFlowInformationProvider private constructor(
}
}
is VariableDescriptor ->
if (!variableDescriptor.isLateInit &&
!(variableDescriptor is MemberDescriptor && variableDescriptor.isEffectivelyExternal())) {
if (!variableDescriptor.isLateInit) {
report(Errors.UNINITIALIZED_VARIABLE.on(element, variableDescriptor), ctxt)
}
}
@@ -670,10 +656,8 @@ class ControlFlowInformationProvider private constructor(
is KtPrimaryConstructor -> if (!element.hasValOrVar()) {
val containingClass = owner.getContainingClassOrObject()
val containingClassDescriptor = trace.get(DECLARATION_TO_DESCRIPTOR, containingClass) as? ClassDescriptor
if (!DescriptorUtils.isAnnotationClass(containingClassDescriptor) &&
containingClassDescriptor?.isExpect == false &&
!containingClassDescriptor.isEffectivelyExternal() &&
diagnosticSuppressor.shouldReportUnusedParameter(variableDescriptor)
if (!DescriptorUtils.isAnnotationClass(containingClassDescriptor) && containingClassDescriptor?.isExpect == false &&
!containingClassDescriptor.isEffectivelyExternal()
) {
report(UNUSED_PARAMETER.on(element, variableDescriptor), ctxt)
}
@@ -696,8 +680,7 @@ class ControlFlowInformationProvider private constructor(
|| functionDescriptor.isEffectivelyExternal()
|| OperatorNameConventions.GET_VALUE == functionName
|| OperatorNameConventions.SET_VALUE == functionName
|| OperatorNameConventions.PROVIDE_DELEGATE == functionName
|| !diagnosticSuppressor.shouldReportUnusedParameter(variableDescriptor)) {
|| OperatorNameConventions.PROVIDE_DELEGATE == functionName) {
return
}
if (anonymous) {

View File

@@ -190,10 +190,7 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon
}
private fun WriteValueInstruction.isTrivialInitializer() =
// WriteValueInstruction having KtDeclaration as an element means
// it must be a write happened at the same time when
// the variable (common variable/parameter/object) has been declared
element is KtDeclaration
element is KtVariableDeclaration || element is KtParameter
private inner class ReadOnlyInitControlFlowInfoImpl(
val declaredSet: ImmutableSet<VariableDescriptor>,
@@ -294,14 +291,8 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon
val variableUseStatusData: Map<Instruction, Edges<ReadOnlyUseControlFlowInfo>>
get() {
val edgesForTrivialVals = computeUseInfoForTrivialVals()
if (rootVariables.nonTrivialVariables.isEmpty()) {
return hashMapOf<Instruction, Edges<ReadOnlyUseControlFlowInfo>>().apply {
pseudocode.traverse(TraversalOrder.FORWARD) { instruction ->
put(instruction, edgesForTrivialVals)
}
}
}
val resultForTrivialVals = computeUseInfoForTrivialVals()
if (rootVariables.nonTrivialVariables.isEmpty()) return resultForTrivialVals
return pseudocodeVariableDataCollector.collectData(TraversalOrder.BACKWARD, UseControlFlowInfo()) { instruction: Instruction, incomingEdgesData: Collection<UseControlFlowInfo> ->
@@ -342,16 +333,17 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon
Edges(enterResult, exitResult)
}
}.mapValues {
(_, edges) ->
(instruction, edges) ->
val edgeForTrivialVals = resultForTrivialVals[instruction]!!
Edges(
edgesForTrivialVals.incoming.replaceDelegate(edges.incoming),
edgesForTrivialVals.outgoing.replaceDelegate(edges.outgoing)
edgeForTrivialVals.incoming.replaceDelegate(edges.incoming),
edgeForTrivialVals.outgoing.replaceDelegate(edges.outgoing)
)
}
}
private fun computeUseInfoForTrivialVals(): Edges<ReadOnlyUseControlFlowInfoImpl> {
private fun computeUseInfoForTrivialVals(): Map<Instruction, Edges<ReadOnlyUseControlFlowInfoImpl>> {
val used = hashSetOf<VariableDescriptor>()
pseudocode.traverse(TraversalOrder.FORWARD) { instruction ->
@@ -363,7 +355,13 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon
}
val constantUseInfo = ReadOnlyUseControlFlowInfoImpl(used, null)
return Edges(constantUseInfo, constantUseInfo)
val constantEdges = Edges(constantUseInfo, constantUseInfo)
val result = hashMapOf<Instruction, Edges<ReadOnlyUseControlFlowInfoImpl>>()
pseudocode.traverse(TraversalOrder.FORWARD) { instruction ->
result[instruction] = constantEdges
}
return result
}
private fun extractValWithTrivialInitializer(instruction: Instruction): VariableDescriptor? {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
* 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.
@@ -80,26 +80,23 @@ public class CheckerTestUtil {
private static final String IGNORE_DIAGNOSTIC_PARAMETER = "IGNORE";
private static final String SHOULD_BE_ESCAPED = "\\)\\(;";
private static final String DIAGNOSTIC_PARAMETER = "(?:(?:\\\\[" + SHOULD_BE_ESCAPED + "])|[^" + SHOULD_BE_ESCAPED + "])+";
private static final String INDIVIDUAL_DIAGNOSTIC = "(\\w+;)?(\\w+:)?(\\w+)(\\(" + DIAGNOSTIC_PARAMETER + "(;\\s*" + DIAGNOSTIC_PARAMETER + ")*\\))?";
private static final String INDIVIDUAL_DIAGNOSTIC = "(\\w+:)?(\\w+)(\\(" + DIAGNOSTIC_PARAMETER + "(;\\s*" + DIAGNOSTIC_PARAMETER + ")*\\))?";
private static final Pattern RANGE_START_OR_END_PATTERN = Pattern.compile("(<!" +
INDIVIDUAL_DIAGNOSTIC + "(,\\s*" +
INDIVIDUAL_DIAGNOSTIC + ")*!>)|(<!>)");
private static final Pattern INDIVIDUAL_DIAGNOSTIC_PATTERN = Pattern.compile(INDIVIDUAL_DIAGNOSTIC);
private static final Pattern INDIVIDUAL_PARAMETER_PATTERN = Pattern.compile(DIAGNOSTIC_PARAMETER);
private static final String NEW_INFERENCE_PREFIX = "NI";
@NotNull
public static List<ActualDiagnostic> getDiagnosticsIncludingSyntaxErrors(
@NotNull BindingContext bindingContext,
@NotNull List<Pair<MultiTargetPlatform, BindingContext>> implementingModulesBindings,
@NotNull PsiElement root,
boolean markDynamicCalls,
@Nullable List<DeclarationDescriptor> dynamicCallDescriptors,
boolean withNewInference
@Nullable List<DeclarationDescriptor> dynamicCallDescriptors
) {
List<ActualDiagnostic> result =
getDiagnosticsIncludingSyntaxErrors(bindingContext, root, markDynamicCalls, dynamicCallDescriptors, null, withNewInference);
getDiagnosticsIncludingSyntaxErrors(bindingContext, root, markDynamicCalls, dynamicCallDescriptors, null);
List<Pair<MultiTargetPlatform, BindingContext>> sortedBindings = CollectionsKt.sortedWith(
implementingModulesBindings,
@@ -112,7 +109,7 @@ public class CheckerTestUtil {
result.addAll(getDiagnosticsIncludingSyntaxErrors(
binding.getSecond(), root, markDynamicCalls, dynamicCallDescriptors,
((MultiTargetPlatform.Specific) platform).getPlatform(), withNewInference
((MultiTargetPlatform.Specific) platform).getPlatform()
));
}
@@ -125,21 +122,20 @@ public class CheckerTestUtil {
@NotNull PsiElement root,
boolean markDynamicCalls,
@Nullable List<DeclarationDescriptor> dynamicCallDescriptors,
@Nullable String platform,
boolean withNewInference
@Nullable String platform
) {
List<ActualDiagnostic> diagnostics = new ArrayList<>();
for (Diagnostic diagnostic : bindingContext.getDiagnostics().all()) {
if (PsiTreeUtil.isAncestor(root, diagnostic.getPsiElement(), false)) {
diagnostics.add(new ActualDiagnostic(diagnostic, platform, withNewInference));
diagnostics.add(new ActualDiagnostic(diagnostic, platform));
}
}
for (PsiErrorElement errorElement : AnalyzingUtils.getSyntaxErrorRanges(root)) {
diagnostics.add(new ActualDiagnostic(new SyntaxErrorDiagnostic(errorElement), platform, withNewInference));
diagnostics.add(new ActualDiagnostic(new SyntaxErrorDiagnostic(errorElement), platform));
}
diagnostics.addAll(getDebugInfoDiagnostics(root, bindingContext, markDynamicCalls, dynamicCallDescriptors, platform, withNewInference));
diagnostics.addAll(getDebugInfoDiagnostics(root, bindingContext, markDynamicCalls, dynamicCallDescriptors, platform));
return diagnostics;
}
@@ -150,8 +146,7 @@ public class CheckerTestUtil {
@NotNull BindingContext bindingContext,
boolean markDynamicCalls,
@Nullable List<DeclarationDescriptor> dynamicCallDescriptors,
@Nullable String platform,
boolean withNewInference
@Nullable String platform
) {
List<ActualDiagnostic> debugAnnotations = new ArrayList<>();
@@ -183,7 +178,7 @@ public class CheckerTestUtil {
}
private void newDiagnostic(KtElement element, DebugInfoDiagnosticFactory factory) {
debugAnnotations.add(new ActualDiagnostic(new DebugInfoDiagnostic(element, factory), platform, withNewInference));
debugAnnotations.add(new ActualDiagnostic(new DebugInfoDiagnostic(element, factory), platform));
}
});
@@ -198,8 +193,7 @@ public class CheckerTestUtil {
)) {
for (KtExpression expression : bindingContext.getSliceContents(factory.getFirst()).keySet()) {
if (PsiTreeUtil.isAncestor(root, expression, false)) {
debugAnnotations.add(new ActualDiagnostic(new DebugInfoDiagnostic(expression, factory.getSecond()), platform,
withNewInference));
debugAnnotations.add(new ActualDiagnostic(new DebugInfoDiagnostic(expression, factory.getSecond()), platform));
}
}
}
@@ -213,12 +207,6 @@ public class CheckerTestUtil {
void wrongParametersDiagnostic(TextDiagnostic expectedDiagnostic, TextDiagnostic actualDiagnostic, int start, int end);
void unexpectedDiagnostic(TextDiagnostic diagnostic, int actualStart, int actualEnd);
void uncheckedDiagnostic(TextDiagnostic diagnostic, int expectedStart, int expectedEnd);
boolean shouldUseDiagnosticsForNI();
boolean isWithNewInferenceDirective();
}
public static Map<ActualDiagnostic, TextDiagnostic> diagnosticsDiff(
@@ -231,21 +219,13 @@ public class CheckerTestUtil {
assertSameFile(actual);
Iterator<DiagnosedRange> expectedDiagnostics = expected.iterator();
List<ActualDiagnosticDescriptor> sortedDiagnosticDescriptors =
getActualSortedDiagnosticDescriptors(actual, !callbacks.isWithNewInferenceDirective());
Iterator<ActualDiagnosticDescriptor> actualDiagnostics = sortedDiagnosticDescriptors.iterator();
List<DiagnosticDescriptor> sortedDiagnosticDescriptors = getSortedDiagnosticDescriptors(actual);
Iterator<DiagnosticDescriptor> actualDiagnostics = sortedDiagnosticDescriptors.iterator();
DiagnosedRange currentExpected = safeAdvance(expectedDiagnostics);
ActualDiagnosticDescriptor currentActual = safeAdvance(actualDiagnostics);
DiagnosticDescriptor currentActual = safeAdvance(actualDiagnostics);
while (currentExpected != null || currentActual != null) {
if (currentExpected != null) {
boolean currentDiagnosticsForNI = CollectionsKt.any(currentExpected.diagnostics, diagnostic -> diagnostic.withNewInference);
if (callbacks.shouldUseDiagnosticsForNI() != currentDiagnosticsForNI) {
uncheckedDiagnostics(callbacks, currentExpected);
currentExpected = safeAdvance(expectedDiagnostics);
continue;
}
if (currentActual == null) {
missingDiagnostics(callbacks, currentExpected);
currentExpected = safeAdvance(expectedDiagnostics);
@@ -295,7 +275,7 @@ public class CheckerTestUtil {
private static void compareDiagnostics(
@NotNull DiagnosticDiffCallbacks callbacks,
@NotNull DiagnosedRange currentExpected,
@NotNull ActualDiagnosticDescriptor currentActual,
@NotNull DiagnosticDescriptor currentActual,
@NotNull Map<ActualDiagnostic, TextDiagnostic> diagnosticToInput
) {
int expectedStart = currentExpected.getStart();
@@ -359,9 +339,9 @@ public class CheckerTestUtil {
}
}
private static void unexpectedDiagnostics(ActualDiagnosticDescriptor descriptor, DiagnosticDiffCallbacks callbacks) {
private static void unexpectedDiagnostics(DiagnosticDescriptor descriptor, DiagnosticDiffCallbacks callbacks) {
for (ActualDiagnostic diagnostic : descriptor.diagnostics) {
callbacks.unexpectedDiagnostic(TextDiagnostic.asTextDiagnostic(diagnostic), descriptor.getStart(), descriptor.getEnd());
callbacks.unexpectedDiagnostic(TextDiagnostic.asTextDiagnostic(diagnostic), descriptor.start, descriptor.end);
}
}
@@ -371,12 +351,6 @@ public class CheckerTestUtil {
}
}
private static void uncheckedDiagnostics(DiagnosticDiffCallbacks callbacks, DiagnosedRange currentExpected) {
for (TextDiagnostic diagnostic : currentExpected.getDiagnostics()) {
callbacks.uncheckedDiagnostic(diagnostic, currentExpected.getStart(), currentExpected.getEnd());
}
}
private static <T> T safeAdvance(Iterator<T> iterator) {
return iterator.hasNext() ? iterator.next() : null;
}
@@ -413,114 +387,97 @@ public class CheckerTestUtil {
}
public static StringBuffer addDiagnosticMarkersToText(@NotNull PsiFile psiFile, @NotNull Collection<ActualDiagnostic> diagnostics) {
return addDiagnosticMarkersToText(psiFile, diagnostics, Collections.emptyMap(), PsiElement::getText, Collections.emptyList(), false);
return addDiagnosticMarkersToText(psiFile, diagnostics, Collections.emptyMap(), PsiElement::getText);
}
public static StringBuffer addDiagnosticMarkersToText(
@NotNull PsiFile psiFile,
@NotNull Collection<ActualDiagnostic> diagnostics,
@NotNull Map<ActualDiagnostic, TextDiagnostic> diagnosticToExpectedDiagnostic,
@NotNull Function<PsiFile, String> getFileText,
@NotNull Collection<PositionalTextDiagnostic> uncheckedDiagnostics,
boolean withNewInferenceDirective
@NotNull Function<PsiFile, String> getFileText
) {
String text = getFileText.fun(psiFile);
StringBuffer result = new StringBuffer();
diagnostics = CollectionsKt.filter(diagnostics, actualDiagnostic -> psiFile.equals(actualDiagnostic.getFile()));
if (diagnostics.isEmpty() && uncheckedDiagnostics.isEmpty()) {
result.append(text);
return result;
}
if (!diagnostics.isEmpty()) {
List<DiagnosticDescriptor> diagnosticDescriptors = getSortedDiagnosticDescriptors(diagnostics);
List<AbstractDiagnosticDescriptor> diagnosticDescriptors = getSortedDiagnosticDescriptors(diagnostics, uncheckedDiagnostics, !withNewInferenceDirective);
Stack<DiagnosticDescriptor> opened = new Stack<>();
ListIterator<DiagnosticDescriptor> iterator = diagnosticDescriptors.listIterator();
DiagnosticDescriptor currentDescriptor = iterator.next();
Stack<AbstractDiagnosticDescriptor> opened = new Stack<>();
ListIterator<AbstractDiagnosticDescriptor> iterator = diagnosticDescriptors.listIterator();
AbstractDiagnosticDescriptor currentDescriptor = iterator.next();
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
while (!opened.isEmpty() && i == opened.peek().end) {
closeDiagnosticString(result);
opened.pop();
}
while (currentDescriptor != null && i == currentDescriptor.start) {
openDiagnosticsString(result, currentDescriptor, diagnosticToExpectedDiagnostic);
if (currentDescriptor.getEnd() == i) {
closeDiagnosticString(result);
}
else {
opened.push(currentDescriptor);
}
if (iterator.hasNext()) {
currentDescriptor = iterator.next();
}
else {
currentDescriptor = null;
}
}
result.append(c);
}
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
while (!opened.isEmpty() && i == opened.peek().end) {
if (currentDescriptor != null) {
assert currentDescriptor.start == text.length();
assert currentDescriptor.end == text.length();
openDiagnosticsString(result, currentDescriptor, diagnosticToExpectedDiagnostic);
opened.push(currentDescriptor);
}
while (!opened.isEmpty() && text.length() == opened.peek().end) {
closeDiagnosticString(result);
opened.pop();
}
while (currentDescriptor != null && i == currentDescriptor.start) {
openDiagnosticsString(result, currentDescriptor, diagnosticToExpectedDiagnostic);
if (currentDescriptor.getEnd() == i) {
closeDiagnosticString(result);
}
else {
opened.push(currentDescriptor);
}
if (iterator.hasNext()) {
currentDescriptor = iterator.next();
}
else {
currentDescriptor = null;
}
}
result.append(c);
assert opened.isEmpty() : "Stack is not empty: " + opened;
}
if (currentDescriptor != null) {
assert currentDescriptor.start == text.length();
assert currentDescriptor.end == text.length();
openDiagnosticsString(result, currentDescriptor, diagnosticToExpectedDiagnostic);
opened.push(currentDescriptor);
else {
result.append(text);
}
while (!opened.isEmpty() && text.length() == opened.peek().end) {
closeDiagnosticString(result);
opened.pop();
}
assert opened.isEmpty() : "Stack is not empty: " + opened;
return result;
}
private static void openDiagnosticsString(
StringBuffer result,
AbstractDiagnosticDescriptor currentDescriptor,
DiagnosticDescriptor currentDescriptor,
Map<ActualDiagnostic, TextDiagnostic> diagnosticToExpectedDiagnostic
) {
result.append("<!");
if (currentDescriptor instanceof TextDiagnosticDescriptor) {
TextDiagnostic diagnostic = ((TextDiagnosticDescriptor) currentDescriptor).getTextDiagnostic();
result.append(diagnostic.asString());
}
else if (currentDescriptor instanceof ActualDiagnosticDescriptor) {
List<ActualDiagnostic> diagnostics = ((ActualDiagnosticDescriptor) currentDescriptor).getDiagnostics();
for (Iterator<ActualDiagnostic> iterator = diagnostics.iterator(); iterator.hasNext(); ) {
ActualDiagnostic diagnostic = iterator.next();
TextDiagnostic expectedDiagnostic = diagnosticToExpectedDiagnostic.get(diagnostic);
if (expectedDiagnostic != null) {
TextDiagnostic actualTextDiagnostic = TextDiagnostic.asTextDiagnostic(diagnostic);
if (compareTextDiagnostic(expectedDiagnostic, actualTextDiagnostic)) {
result.append(expectedDiagnostic.asString());
}
else {
result.append(actualTextDiagnostic.asString());
}
for (Iterator<ActualDiagnostic> iterator = currentDescriptor.diagnostics.iterator(); iterator.hasNext(); ) {
ActualDiagnostic diagnostic = iterator.next();
TextDiagnostic expectedDiagnostic = diagnosticToExpectedDiagnostic.get(diagnostic);
if (expectedDiagnostic != null) {
TextDiagnostic actualTextDiagnostic = TextDiagnostic.asTextDiagnostic(diagnostic);
if (compareTextDiagnostic(expectedDiagnostic, actualTextDiagnostic)) {
result.append(expectedDiagnostic.asString());
}
else {
if (diagnostic.withNewInference) {
result.append(NEW_INFERENCE_PREFIX);
result.append(";");
}
if (diagnostic.platform != null) {
result.append(diagnostic.platform);
result.append(":");
}
result.append(diagnostic.getName());
}
if (iterator.hasNext()) {
result.append(", ");
result.append(actualTextDiagnostic.asString());
}
}
}
else {
throw new IllegalStateException("Unknown diagnostic descriptor: " + currentDescriptor);
else {
if (diagnostic.platform != null) {
result.append(diagnostic.platform);
result.append(":");
}
result.append(diagnostic.getName());
}
if (iterator.hasNext()) {
result.append(", ");
}
}
result.append("!>");
}
@@ -629,80 +586,45 @@ public class CheckerTestUtil {
}
}
private static List<ActualDiagnosticDescriptor> getActualSortedDiagnosticDescriptors(
@NotNull Collection<ActualDiagnostic> diagnostics,
boolean groupDiagnosticsByRange
) {
return CollectionsKt.filterIsInstance(
getSortedDiagnosticDescriptors(diagnostics, Collections.emptyList(), groupDiagnosticsByRange),
ActualDiagnosticDescriptor.class
);
}
@NotNull
private static List<AbstractDiagnosticDescriptor> getSortedDiagnosticDescriptors(
@NotNull Collection<ActualDiagnostic> diagnostics,
@NotNull Collection<PositionalTextDiagnostic> uncheckedDiagnostics,
boolean groupDiagnosticsByRange
) {
List<ActualDiagnostic> validDiagnostics = CollectionsKt.filter(diagnostics, actualDiagnostic -> actualDiagnostic.diagnostic.isValid());
List<AbstractDiagnosticDescriptor> diagnosticDescriptors = groupDiagnosticsByRange ?
groupDiagnosticsByTextRange(validDiagnostics) :
asPlainDiagnosticDescriptors(validDiagnostics);
for (PositionalTextDiagnostic diagnostic : uncheckedDiagnostics) {
diagnosticDescriptors.add(new TextDiagnosticDescriptor(diagnostic));
}
diagnosticDescriptors.sort((d1, d2) -> {
if (d1.start != d2.start) return d1.start - d2.start;
if (d1.end != d2.end) return d2.end - d1.end;
if (d1.isWithNewInference() && !d2.isWithNewInference()) return -1;
if (!d1.isWithNewInference() && d2.isWithNewInference()) return 1;
return 0;
});
return diagnosticDescriptors;
}
private static List<AbstractDiagnosticDescriptor> asPlainDiagnosticDescriptors(@NotNull Collection<ActualDiagnostic> diagnostics) {
List<AbstractDiagnosticDescriptor> diagnosticDescriptors = Lists.newArrayList();
for (ActualDiagnostic actualDiagnostic : diagnostics) {
for (TextRange range : actualDiagnostic.diagnostic.getTextRanges()) {
diagnosticDescriptors.add(
new ActualDiagnosticDescriptor(
range.getStartOffset(),
range.getEndOffset(),
Collections.singletonList(actualDiagnostic))
);
}
}
return diagnosticDescriptors;
}
@NotNull
private static List<AbstractDiagnosticDescriptor> groupDiagnosticsByTextRange(@NotNull Collection<ActualDiagnostic> diagnostics) {
private static List<DiagnosticDescriptor> getSortedDiagnosticDescriptors(@NotNull Collection<ActualDiagnostic> diagnostics) {
LinkedListMultimap<TextRange, ActualDiagnostic> diagnosticsGroupedByRanges = LinkedListMultimap.create();
for (ActualDiagnostic actualDiagnostic : diagnostics) {
Diagnostic diagnostic = actualDiagnostic.diagnostic;
if (!diagnostic.isValid()) continue;
for (TextRange textRange : diagnostic.getTextRanges()) {
diagnosticsGroupedByRanges.put(textRange, actualDiagnostic);
}
}
return CollectionsKt.map(diagnosticsGroupedByRanges.keySet(), range ->
new ActualDiagnosticDescriptor(
range.getStartOffset(),
range.getEndOffset(),
diagnosticsGroupedByRanges.get(range))
);
List<DiagnosticDescriptor> diagnosticDescriptors = Lists.newArrayList();
for (TextRange range : diagnosticsGroupedByRanges.keySet()) {
diagnosticDescriptors.add(
new DiagnosticDescriptor(range.getStartOffset(), range.getEndOffset(), diagnosticsGroupedByRanges.get(range)));
}
diagnosticDescriptors.sort((d1, d2) -> {
// Start early -- go first; start at the same offset, the one who end later is the outer, i.e. goes first
return (d1.start != d2.start) ? d1.start - d2.start : d2.end - d1.end;
});
return diagnosticDescriptors;
}
private static abstract class AbstractDiagnosticDescriptor {
private static class DiagnosticDescriptor {
private final int start;
private final int end;
private final List<ActualDiagnostic> diagnostics;
AbstractDiagnosticDescriptor(int start, int end) {
DiagnosticDescriptor(int start, int end, List<ActualDiagnostic> diagnostics) {
this.start = start;
this.end = end;
this.diagnostics = diagnostics;
}
public Map<ActualDiagnostic, TextDiagnostic> getTextDiagnosticsMap() {
Map<ActualDiagnostic, TextDiagnostic> diagnosticMap = new HashMap<>();
for (ActualDiagnostic diagnostic : diagnostics) {
diagnosticMap.put(diagnostic, TextDiagnostic.asTextDiagnostic(diagnostic));
}
return diagnosticMap;
}
public int getStart() {
@@ -716,63 +638,15 @@ public class CheckerTestUtil {
public TextRange getTextRange() {
return new TextRange(start, end);
}
public abstract boolean isWithNewInference();
}
private static class ActualDiagnosticDescriptor extends AbstractDiagnosticDescriptor {
private final List<ActualDiagnostic> diagnostics;
ActualDiagnosticDescriptor(int start, int end, List<ActualDiagnostic> diagnostics) {
super(start, end);
this.diagnostics = diagnostics;
}
public List<ActualDiagnostic> getDiagnostics() {
return diagnostics;
}
public Map<ActualDiagnostic, TextDiagnostic> getTextDiagnosticsMap() {
Map<ActualDiagnostic, TextDiagnostic> diagnosticMap = new HashMap<>();
for (ActualDiagnostic diagnostic : diagnostics) {
diagnosticMap.put(diagnostic, TextDiagnostic.asTextDiagnostic(diagnostic));
}
return diagnosticMap;
}
@Override
public boolean isWithNewInference() {
return false;
}
}
private static class TextDiagnosticDescriptor extends AbstractDiagnosticDescriptor {
private final PositionalTextDiagnostic positionalTextDiagnostic;
TextDiagnosticDescriptor(PositionalTextDiagnostic positionalTextDiagnostic) {
super(positionalTextDiagnostic.getStart(), positionalTextDiagnostic.getEnd());
this.positionalTextDiagnostic = positionalTextDiagnostic;
}
public TextDiagnostic getTextDiagnostic() {
return positionalTextDiagnostic.getDiagnostic();
}
@Override
public boolean isWithNewInference() {
return positionalTextDiagnostic.getDiagnostic().withNewInference;
}
}
public static class ActualDiagnostic {
public final Diagnostic diagnostic;
public final String platform;
public final boolean withNewInference;
ActualDiagnostic(@NotNull Diagnostic diagnostic, @Nullable String platform, boolean withNewInference) {
ActualDiagnostic(@NotNull Diagnostic diagnostic, @Nullable String platform) {
this.diagnostic = diagnostic;
this.platform = platform;
this.withNewInference = withNewInference;
}
@NotNull
@@ -792,21 +666,17 @@ public class CheckerTestUtil {
ActualDiagnostic other = (ActualDiagnostic) obj;
// '==' on diagnostics is intentional here
return other.diagnostic == diagnostic &&
(other.platform == null ? platform == null : other.platform.equals(platform)) &&
(other.withNewInference == withNewInference);
(other.platform == null ? platform == null : other.platform.equals(platform));
}
@Override
public int hashCode() {
int result = System.identityHashCode(diagnostic);
result = 31 * result + (platform != null ? platform.hashCode() : 0);
result = 31 * result + (withNewInference ? 0 : 1);
return result;
return System.identityHashCode(diagnostic) * 31 + (platform != null ? platform.hashCode() : 0);
}
@Override
public String toString() {
return (withNewInference ? NEW_INFERENCE_PREFIX + ";" : "") + (platform != null ? platform + ":" : "") + diagnostic.toString();
return (platform != null ? platform + ":" : "") + diagnostic.toString();
}
}
@@ -817,25 +687,21 @@ public class CheckerTestUtil {
if (!matcher.find())
throw new IllegalArgumentException("Could not parse diagnostic: " + text);
boolean withNewInference = NEW_INFERENCE_PREFIX.equals(extractDataBefore(matcher.group(1), ";"));
String platform = extractDataBefore(matcher.group(2), ":");
String platformPrefix = matcher.group(1);
assert platformPrefix == null || platformPrefix.endsWith(":") : platformPrefix;
String platform = platformPrefix == null ? null : StringsKt.substringBeforeLast(platformPrefix, ":", platformPrefix);
String name = matcher.group(3);
String parameters = matcher.group(4);
String name = matcher.group(2);
String parameters = matcher.group(3);
if (parameters == null) {
return new TextDiagnostic(name, platform, null, withNewInference);
return new TextDiagnostic(name, platform, null);
}
List<String> parsedParameters = new SmartList<>();
Matcher parametersMatcher = INDIVIDUAL_PARAMETER_PATTERN.matcher(parameters);
while (parametersMatcher.find())
parsedParameters.add(unescape(parametersMatcher.group().trim()));
return new TextDiagnostic(name, platform, parsedParameters, withNewInference);
}
private static String extractDataBefore(@Nullable String prefix, @NotNull String anchor) {
assert prefix == null || prefix.endsWith(anchor) : prefix;
return prefix == null ? null : StringsKt.substringBeforeLast(prefix, anchor, prefix);
return new TextDiagnostic(name, platform, parsedParameters);
}
private static @NotNull String escape(@NotNull String s) {
@@ -856,9 +722,9 @@ public class CheckerTestUtil {
//noinspection unchecked
Object[] renderParameters = ((AbstractDiagnosticWithParametersRenderer) renderer).renderParameters(diagnostic);
List<String> parameters = ContainerUtil.map(renderParameters, Object::toString);
return new TextDiagnostic(diagnosticName, actualDiagnostic.platform, parameters, actualDiagnostic.withNewInference);
return new TextDiagnostic(diagnosticName, actualDiagnostic.platform, parameters);
}
return new TextDiagnostic(diagnosticName, actualDiagnostic.platform, null, actualDiagnostic.withNewInference);
return new TextDiagnostic(diagnosticName, actualDiagnostic.platform, null);
}
@NotNull
@@ -867,13 +733,11 @@ public class CheckerTestUtil {
private final String platform;
@Nullable
private final List<String> parameters;
private final boolean withNewInference;
public TextDiagnostic(@NotNull String name, @Nullable String platform, @Nullable List<String> parameters, boolean withNewInference) {
public TextDiagnostic(@NotNull String name, @Nullable String platform, @Nullable List<String> parameters) {
this.name = name;
this.platform = platform;
this.parameters = parameters;
this.withNewInference = withNewInference;
}
@Nullable
@@ -901,7 +765,6 @@ public class CheckerTestUtil {
if (!name.equals(that.name)) return false;
if (platform != null ? !platform.equals(that.platform) : that.platform != null) return false;
if (parameters != null ? !parameters.equals(that.parameters) : that.parameters != null) return false;
if (withNewInference != that.withNewInference) return false;
return true;
}
@@ -911,17 +774,12 @@ public class CheckerTestUtil {
int result = name.hashCode();
result = 31 * result + (platform != null ? platform.hashCode() : 0);
result = 31 * result + (parameters != null ? parameters.hashCode() : 0);
result = 31 * result + (withNewInference ? 0 : 1);
return result;
}
@NotNull
public String asString() {
StringBuilder result = new StringBuilder();
if (withNewInference) {
result.append(NEW_INFERENCE_PREFIX);
result.append(";");
}
if (platform != null) {
result.append(platform);
result.append(":");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
* Copyright 2010-2015 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.
@@ -33,9 +33,6 @@ object CommonConfigurationKeys {
@JvmField
val LOOKUP_TRACKER = CompilerConfigurationKey.create<LookupTracker>("lookup tracker")
@JvmField
val USE_NEW_INFERENCE = CompilerConfigurationKey.create<Boolean>("use new inference")
}
var CompilerConfiguration.languageVersionSettings: LanguageVersionSettings

View File

@@ -27,7 +27,6 @@ import org.jetbrains.kotlin.config.LanguageFeature;
import org.jetbrains.kotlin.config.LanguageVersion;
import org.jetbrains.kotlin.config.LanguageVersionSettings;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.diagnostics.rendering.DiagnosticRenderer;
import org.jetbrains.kotlin.lexer.KtKeywordToken;
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken;
import org.jetbrains.kotlin.lexer.KtTokens;
@@ -981,12 +980,11 @@ public interface Errors {
DiagnosticFactory0<PsiElement> NON_LOCAL_SUSPENSION_POINT = DiagnosticFactory0.create(ERROR);
DiagnosticFactory1<PsiElement, CallableDescriptor> ILLEGAL_SUSPEND_FUNCTION_CALL = DiagnosticFactory1.create(ERROR);
DiagnosticFactory1<PsiElement, CallableDescriptor> ILLEGAL_SUSPEND_PROPERTY_ACCESS = DiagnosticFactory1.create(ERROR);
DiagnosticFactory0<PsiElement> ILLEGAL_RESTRICTED_SUSPENDING_FUNCTION_CALL = DiagnosticFactory0.create(ERROR);
DiagnosticFactory1<PsiElement, RenderedDiagnostic<?>> PLUGIN_ERROR = DiagnosticFactory1.create(ERROR);
DiagnosticFactory1<PsiElement, RenderedDiagnostic<?>> PLUGIN_WARNING = DiagnosticFactory1.create(WARNING);
DiagnosticFactory1<PsiElement, RenderedDiagnostic<?>> PLUGIN_INFO = DiagnosticFactory1.create(INFO);
DiagnosticFactory2<PsiElement, String, String> PLUGIN_ERROR = DiagnosticFactory2.create(ERROR);
DiagnosticFactory2<PsiElement, String, String> PLUGIN_WARNING = DiagnosticFactory2.create(WARNING);
DiagnosticFactory2<PsiElement, String, String> PLUGIN_INFO = DiagnosticFactory2.create(INFO);
// Function contracts
DiagnosticFactory1<KtElement, String> ERROR_IN_CONTRACT_DESCRIPTION = DiagnosticFactory1.create(ERROR);

View File

@@ -16,6 +16,9 @@
package org.jetbrains.kotlin.diagnostics
import com.intellij.mock.MockApplication
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.builtins.isFunctionType
import org.jetbrains.kotlin.descriptors.CallableDescriptor
@@ -164,15 +167,19 @@ inline fun <reified T : KtDeclaration> reportOnDeclarationAs(trace: BindingTrace
}
fun <D : Diagnostic> DiagnosticSink.reportFromPlugin(diagnostic: D, ext: DefaultErrorMessages.Extension) {
if (ApplicationManager.getApplication() !is MockApplication) {
return this.report(diagnostic)
}
@Suppress("UNCHECKED_CAST")
val renderer = ext.map[diagnostic.factory] as? DiagnosticRenderer<D>
?: error("Renderer not found for diagnostic ${diagnostic.factory.name}")
val renderedDiagnostic = RenderedDiagnostic(diagnostic, renderer)
val text = renderer.render(diagnostic)
when (diagnostic.severity) {
Severity.ERROR -> report(Errors.PLUGIN_ERROR.on(diagnostic.psiElement, renderedDiagnostic))
Severity.WARNING -> report(Errors.PLUGIN_WARNING.on(diagnostic.psiElement, renderedDiagnostic))
Severity.INFO -> report(Errors.PLUGIN_INFO.on(diagnostic.psiElement, renderedDiagnostic))
Severity.ERROR -> report(Errors.PLUGIN_ERROR.on(diagnostic.psiElement, diagnostic.factory.name, text))
Severity.WARNING -> report(Errors.PLUGIN_WARNING.on(diagnostic.psiElement, diagnostic.factory.name, text))
Severity.INFO -> report(Errors.PLUGIN_INFO.on(diagnostic.psiElement, diagnostic.factory.name, text))
}
}
}

View File

@@ -16,11 +16,12 @@
package org.jetbrains.kotlin.diagnostics.rendering;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.util.io.FileUtil;
import kotlin.Pair;
import kotlin.collections.CollectionsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.kotlin.config.LanguageVersion;
import org.jetbrains.kotlin.diagnostics.Diagnostic;
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory;
@@ -28,14 +29,13 @@ import org.jetbrains.kotlin.diagnostics.Errors;
import org.jetbrains.kotlin.resolve.VarianceConflictDiagnosticData;
import org.jetbrains.kotlin.serialization.deserialization.descriptors.VersionRequirement;
import org.jetbrains.kotlin.types.KotlinTypeKt;
import org.jetbrains.kotlin.util.MappedExtensionProvider;
import org.jetbrains.kotlin.util.OperatorNameConventions;
import org.jetbrains.kotlin.utils.addToStdlib.AddToStdlibKt;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;
import static org.jetbrains.kotlin.diagnostics.Errors.*;
import static org.jetbrains.kotlin.diagnostics.rendering.Renderers.*;
@@ -44,30 +44,47 @@ import static org.jetbrains.kotlin.diagnostics.rendering.RenderingContext.of;
public class DefaultErrorMessages {
public interface Extension {
ExtensionPointName<Extension> EP_NAME = ExtensionPointName.create("org.jetbrains.kotlin.defaultErrorMessages");
@NotNull
DiagnosticFactoryToRendererMap getMap();
}
private static final DiagnosticFactoryToRendererMap MAP = new DiagnosticFactoryToRendererMap("Default");
private static final List<DiagnosticFactoryToRendererMap> RENDERER_MAPS =
CollectionsKt.plus(
Collections.singletonList(MAP),
CollectionsKt.map(ServiceLoader.load(Extension.class, DefaultErrorMessages.class.getClassLoader()), Extension::getMap)
);
private static final MappedExtensionProvider<Extension, List<DiagnosticFactoryToRendererMap>> RENDERER_MAPS = MappedExtensionProvider.create(
Extension.EP_NAME,
extensions -> {
List<DiagnosticFactoryToRendererMap> result = new ArrayList<>(extensions.size() + 1);
for (Extension extension : extensions) {
result.add(extension.getMap());
}
result.add(MAP);
return result;
});
@NotNull
@SuppressWarnings("unchecked")
public static String render(@NotNull Diagnostic diagnostic) {
DiagnosticRenderer renderer = getRendererForDiagnostic(diagnostic);
if (renderer != null) {
return renderer.render(diagnostic);
for (DiagnosticFactoryToRendererMap map : RENDERER_MAPS.get()) {
DiagnosticRenderer renderer = map.get(diagnostic.getFactory());
if (renderer != null) {
//noinspection unchecked
return renderer.render(diagnostic);
}
}
return diagnostic.toString() + " (error: could not render message)";
throw new IllegalArgumentException("Don't know how to render diagnostic of type " + diagnostic.getFactory().getName() +
" with the following renderer maps: " + RENDERER_MAPS.get());
}
@TestOnly
@Nullable
public static DiagnosticRenderer getRendererForDiagnostic(@NotNull Diagnostic diagnostic) {
return AddToStdlibKt.firstNotNullResult(RENDERER_MAPS, map -> map.get(diagnostic.getFactory()));
for (DiagnosticFactoryToRendererMap map : RENDERER_MAPS.get()) {
DiagnosticRenderer renderer = map.get(diagnostic.getFactory());
if (renderer != null) return renderer;
}
return null;
}
static {
@@ -869,12 +886,11 @@ public class DefaultErrorMessages {
MAP.put(NON_LOCAL_RETURN_IN_DISABLED_INLINE, "Non-local returns are not allowed with inlining disabled");
MAP.put(NON_LOCAL_SUSPENSION_POINT, "Suspension functions can be called only within coroutine body");
MAP.put(ILLEGAL_SUSPEND_FUNCTION_CALL, "Suspend function ''{0}'' should be called only from a coroutine or another suspend function", NAME);
MAP.put(ILLEGAL_SUSPEND_PROPERTY_ACCESS, "Suspend property ''{0}'' should be accessed only from a coroutine or suspend function", NAME);
MAP.put(ILLEGAL_RESTRICTED_SUSPENDING_FUNCTION_CALL, "Restricted suspending functions can only invoke member or extension suspending functions on their restricted coroutine scope");
MAP.put(PLUGIN_ERROR, "{0}", (d, c) -> d.getText());
MAP.put(PLUGIN_WARNING, "{0}", (d, c) -> d.getText());
MAP.put(PLUGIN_INFO, "{0}", (d, c) -> d.getText());
MAP.put(PLUGIN_ERROR, "{0}: {1}", TO_STRING, TO_STRING);
MAP.put(PLUGIN_WARNING, "{0}: {1}", TO_STRING, TO_STRING);
MAP.put(PLUGIN_INFO, "{0}: {1}", TO_STRING, TO_STRING);
MAP.put(ERROR_IN_CONTRACT_DESCRIPTION, "Error in contract description: {0}", TO_STRING);
MAP.put(CONTRACT_NOT_ALLOWED, "Contract is not allowed here");

View File

@@ -23,14 +23,14 @@ import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.script.ScriptDefinitionProvider;
import org.jetbrains.kotlin.script.KotlinScriptDefinitionProvider;
public class KotlinParser implements PsiParser {
private final ScriptDefinitionProvider scriptDefinitionProvider;
private final KotlinScriptDefinitionProvider scriptDefinitionProvider;
public KotlinParser(Project project) {
scriptDefinitionProvider = ScriptDefinitionProvider.Companion.getInstance(project);
scriptDefinitionProvider = KotlinScriptDefinitionProvider.getInstance(project);
}
@Override

View File

@@ -1263,11 +1263,11 @@ public class KotlinParsing extends AbstractKotlinParsing {
LOCAL(true, false),
SCRIPT_TOPLEVEL(true, true);
public final boolean destructuringAllowed;
public final boolean desctructuringAllowed;
public final boolean accessorsAllowed;
PropertyParsingMode(boolean destructuringAllowed, boolean accessorsAllowed) {
this.destructuringAllowed = destructuringAllowed;
PropertyParsingMode(boolean desctructuringAllowed, boolean accessorsAllowed) {
this.desctructuringAllowed = desctructuringAllowed;
this.accessorsAllowed = accessorsAllowed;
}
}
@@ -1295,7 +1295,7 @@ public class KotlinParsing extends AbstractKotlinParsing {
if (multiDeclaration) {
PsiBuilder.Marker multiDecl = mark();
parseMultiDeclarationName(propertyNameFollow);
errorIf(multiDecl, !mode.destructuringAllowed, "Destructuring declarations are only allowed for local variables/values");
errorIf(multiDecl, !mode.desctructuringAllowed, "Destructuring declarations are only allowed for local variables/values");
}
else {
parseFunctionOrPropertyName(receiverTypeDeclared, "property", propertyNameFollow, /*nameRequired = */ true);

View File

@@ -30,11 +30,6 @@ public class KtConstructorDelegationCall extends KtElementImpl implements KtCall
super(node);
}
@Override
public <R, D> R accept(@NotNull KtVisitor<R, D> visitor, D data) {
return visitor.visitConstructorDelegationCall(this, data);
}
@Override
@Nullable
public KtValueArgumentList getValueArgumentList() {

View File

@@ -28,7 +28,7 @@ object KotlinStubVersions {
// Binary stub version should be increased if stub format (org.jetbrains.kotlin.psi.stubs.impl) is changed
// or changes are made to the core stub building code (org.jetbrains.kotlin.idea.decompiler.stubBuilder).
// Increasing this version will lead to reindexing of all binary files that are potentially kotlin binaries (including all class files).
private const val BINARY_STUB_VERSION = 63
private const val BINARY_STUB_VERSION = 62
// Classfile stub version should be increased if changes are made to classfile stub building subsystem (org.jetbrains.kotlin.idea.decompiler.classFile)
// Increasing this version will lead to reindexing of all classfiles.

View File

@@ -25,7 +25,6 @@ import org.jetbrains.kotlin.descriptors.PropertyAccessorDescriptor;
import org.jetbrains.kotlin.descriptors.PropertyDescriptor;
import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor;
import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.resolve.checkers.PlatformDiagnosticSuppressor;
import org.jetbrains.kotlin.types.KotlinType;
import java.util.Map;
@@ -33,21 +32,16 @@ import java.util.Map;
import static org.jetbrains.kotlin.types.TypeUtils.NO_EXPECTED_TYPE;
public class ControlFlowAnalyzer {
private final BindingTrace trace;
private final KotlinBuiltIns builtIns;
private final LanguageVersionSettings languageVersionSettings;
private final PlatformDiagnosticSuppressor diagnosticSuppressor;
@NotNull private final BindingTrace trace;
@NotNull private final KotlinBuiltIns builtIns;
@NotNull private final LanguageVersionSettings languageVersionSettings;
public ControlFlowAnalyzer(
@NotNull BindingTrace trace,
@NotNull KotlinBuiltIns builtIns,
@NotNull LanguageVersionSettings languageVersionSettings,
@NotNull PlatformDiagnosticSuppressor diagnosticSuppressor
@NotNull BindingTrace trace, @NotNull KotlinBuiltIns builtIns, @NotNull LanguageVersionSettings languageVersionSettings
) {
this.trace = trace;
this.builtIns = builtIns;
this.languageVersionSettings = languageVersionSettings;
this.diagnosticSuppressor = diagnosticSuppressor;
}
public void process(@NotNull BodiesResolveContext c) {
@@ -80,7 +74,7 @@ public class ControlFlowAnalyzer {
private void checkSecondaryConstructor(@NotNull KtSecondaryConstructor constructor) {
ControlFlowInformationProvider controlFlowInformationProvider =
new ControlFlowInformationProvider(constructor, trace, languageVersionSettings, diagnosticSuppressor);
new ControlFlowInformationProvider(constructor, trace, languageVersionSettings);
controlFlowInformationProvider.checkDeclaration();
controlFlowInformationProvider.checkFunction(builtIns.getUnitType());
}
@@ -88,9 +82,8 @@ public class ControlFlowAnalyzer {
private void checkDeclarationContainer(@NotNull BodiesResolveContext c, KtDeclarationContainer declarationContainer) {
// A pseudocode of class/object initialization corresponds to a class/object
// or initialization of properties corresponds to a package declared in a file
ControlFlowInformationProvider controlFlowInformationProvider = new ControlFlowInformationProvider(
(KtElement) declarationContainer, trace, languageVersionSettings, diagnosticSuppressor
);
ControlFlowInformationProvider controlFlowInformationProvider =
new ControlFlowInformationProvider((KtElement) declarationContainer, trace, languageVersionSettings);
if (c.getTopDownAnalysisMode().isLocalDeclarations()) {
controlFlowInformationProvider.checkForLocalClassOrObjectMode();
return;
@@ -109,11 +102,9 @@ public class ControlFlowAnalyzer {
}
}
private void checkFunction(
@NotNull BodiesResolveContext c, @NotNull KtDeclarationWithBody function, @Nullable KotlinType expectedReturnType
) {
private void checkFunction(@NotNull BodiesResolveContext c, @NotNull KtDeclarationWithBody function, @Nullable KotlinType expectedReturnType) {
ControlFlowInformationProvider controlFlowInformationProvider =
new ControlFlowInformationProvider(function, trace, languageVersionSettings, diagnosticSuppressor);
new ControlFlowInformationProvider(function, trace, languageVersionSettings);
if (c.getTopDownAnalysisMode().isLocalDeclarations()) {
controlFlowInformationProvider.checkForLocalClassOrObjectMode();
return;

View File

@@ -1,40 +0,0 @@
/*
* Copyright 2010-2017 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.resolve
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.UnwrappedType
import org.jetbrains.kotlin.types.WrappedTypeFactory
interface DeclarationReturnTypeSanitizer {
fun sanitizeReturnType(
inferred: UnwrappedType,
wrappedTypeFactory: WrappedTypeFactory,
trace: BindingTrace,
languageVersionSettings: LanguageVersionSettings
): UnwrappedType
object Default : DeclarationReturnTypeSanitizer {
override fun sanitizeReturnType(
inferred: UnwrappedType,
wrappedTypeFactory: WrappedTypeFactory,
trace: BindingTrace,
languageVersionSettings: LanguageVersionSettings
) = inferred
}
}

Some files were not shown because too many files have changed in this diff Show More