Compare commits

..

1 Commits

Author SHA1 Message Date
Anton Bannykh
0863e97f71 Inject through xml's 2017-04-07 21:06:39 +03:00
10706 changed files with 90115 additions and 285946 deletions

View File

@@ -60,19 +60,17 @@
<element id="module-output" name="backend.jvm" />
<element id="module-output" name="ir.psi2ir" />
<element id="module-output" name="annotation-based-compiler-plugins-ide-support" />
<element id="module-output" name="frontend.script" />
</element>
<element id="library" level="project" name="javax.inject" />
<element id="directory" name="jps">
<element id="artifact" artifact-name="KotlinJpsPlugin" />
</element>
<element id="library" level="project" name="markdown" />
<element id="archive" name="android-extensions-ide.jar">
<element id="archive" name="kotlin-android-extensions-plugin.jar">
<element id="module-output" name="android-extensions-idea" />
</element>
<element id="archive" name="android-extensions-compiler.jar">
<element id="archive" name="kotlin-android-extensions-compiler-plugin.jar">
<element id="module-output" name="android-extensions-compiler" />
<element id="module-output" name="android-extensions-runtime" />
</element>
<element id="archive" name="android-lint.jar">
<element id="module-output" name="uast-kotlin" />
@@ -93,7 +91,8 @@
<element id="archive" name="noarg-ide-plugin.jar">
<element id="module-output" name="noarg-ide" />
</element>
<element id="file-copy" path="$PROJECT_DIR$/dependencies/bootstrap-compiler/Kotlin/kotlinc/lib/kotlin-script-runtime.jar" />
<element id="file-copy" path="$PROJECT_DIR$/dist/kotlinc/lib/kotlin-daemon-client.jar" />
<element id="file-copy" path="$PROJECT_DIR$/dist/kotlinc/lib/kotlin-script-runtime.jar" />
<element id="archive" name="sam-with-receiver-compiler-plugin.jar">
<element id="module-output" name="sam-with-receiver-cli" />
</element>
@@ -105,8 +104,6 @@
</element>
<element id="library" level="project" name="uast-java" />
<element id="library" level="project" name="kotlinx-coroutines-core" />
<element id="library" level="project" name="javaslang" />
<element id="library" level="project" name="kotlinx-coroutines-jdk8" />
</element>
<element id="directory" name="kotlinc">
<element id="dir-copy" path="$PROJECT_DIR$/dist/kotlinc" />

14
.idea/libraries/Rhino.xml generated Normal file
View File

@@ -0,0 +1,14 @@
<component name="libraryTable">
<library name="Rhino">
<ANNOTATIONS>
<root url="file://$PROJECT_DIR$/annotations" />
</ANNOTATIONS>
<CLASSES>
<root url="jar://$PROJECT_DIR$/dependencies/rhino-1.7.6.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$PROJECT_DIR$/dependencies/rhino-1.7.6-sources.jar!/rhino1.7.6/src" />
</SOURCES>
</library>
</component>

View File

@@ -1,9 +0,0 @@
<component name="libraryTable">
<library name="android-layoutlib">
<CLASSES>
<root url="jar://$PROJECT_DIR$/ideaSDK/plugins/android/lib/layoutlib.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</component>

View File

@@ -6,6 +6,7 @@
<CLASSES>
<root url="file://$PROJECT_DIR$/ideaSDK/plugins/android/lib" />
<root url="file://$PROJECT_DIR$/ideaSDK/plugins/android/lib/jps" />
<root url="jar://$PROJECT_DIR$/ideaSDK/lib/android-common.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>

View File

@@ -3,6 +3,7 @@
<CLASSES>
<root url="jar://$PROJECT_DIR$/ideaSDK/plugins/coverage/lib/coverage.jar!/" />
<root url="jar://$PROJECT_DIR$/ideaSDK/plugins/coverage/lib/jacocoant.jar!/" />
<root url="jar://$PROJECT_DIR$/ideaSDK/plugins/coverage/lib/coverage-agent.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>

View File

@@ -5,27 +5,14 @@
<root url="jar://$PROJECT_DIR$/ideaSDK/sources/sources.jar!/" />
</ANNOTATIONS>
<CLASSES>
<root url="jar://$PROJECT_DIR$/ideaSDK/core/annotations.jar!/" />
<root url="jar://$PROJECT_DIR$/ideaSDK/core/asm-all.jar!/" />
<root url="jar://$PROJECT_DIR$/ideaSDK/core/guava-19.0.jar!/" />
<root url="jar://$PROJECT_DIR$/ideaSDK/core/intellij-core.jar!/" />
<root url="jar://$PROJECT_DIR$/ideaSDK/core/jdom.jar!/" />
<root url="jar://$PROJECT_DIR$/ideaSDK/core/jna.jar!/" />
<root url="jar://$PROJECT_DIR$/ideaSDK/core/log4j.jar!/" />
<root url="jar://$PROJECT_DIR$/ideaSDK/core/picocontainer.jar!/" />
<root url="jar://$PROJECT_DIR$/ideaSDK/core/snappy-in-java-0.5.1.jar!/" />
<root url="jar://$PROJECT_DIR$/ideaSDK/core/trove4j.jar!/" />
<root url="jar://$PROJECT_DIR$/ideaSDK/core/util.jar!/" />
<root url="jar://$PROJECT_DIR$/ideaSDK/core/xpp3-1.1.4-min.jar!/" />
<root url="jar://$PROJECT_DIR$/ideaSDK/core/xstream-1.4.8.jar!/" />
<root url="jar://$PROJECT_DIR$/ideaSDK/lib/jsr305.jar!/" />
<root url="file://$PROJECT_DIR$/ideaSDK/core" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$PROJECT_DIR$/dependencies/guava-19.0-sources.jar!/" />
<root url="jar://$PROJECT_DIR$/ideaSDK/sources/sources.jar!/" />
<root url="jar://$PROJECT_DIR$/dependencies/asm-src.zip!/" />
<root url="jar://$PROJECT_DIR$/ideaSDK/lib/jsr305.jar!/" />
</SOURCES>
<jarDirectory url="file://$PROJECT_DIR$/ideaSDK/core" recursive="false" />
</library>
</component>

View File

@@ -1,11 +0,0 @@
<component name="libraryTable">
<library name="javaslang">
<CLASSES>
<root url="jar://$PROJECT_DIR$/dependencies/javaslang-2.0.6.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$PROJECT_DIR$/dependencies/javaslang-2.0.6-sources.jar!/" />
</SOURCES>
</library>
</component>

View File

@@ -9,6 +9,17 @@
<JAVADOC />
<SOURCES>
<root url="jar://$PROJECT_DIR$/ideaSDK/sources/sources.jar!/" />
<root url="jar://$PROJECT_DIR$/ideaSDK/sources/sources.jar!/jps/antLayout/src" />
<root url="jar://$PROJECT_DIR$/ideaSDK/sources/sources.jar!/jps/jps-builders/src" />
<root url="jar://$PROJECT_DIR$/ideaSDK/sources/sources.jar!/jps/jps-builders/testSrc" />
<root url="jar://$PROJECT_DIR$/ideaSDK/sources/sources.jar!/jps/jps-launcher/src" />
<root url="jar://$PROJECT_DIR$/ideaSDK/sources/sources.jar!/jps/model-api/src" />
<root url="jar://$PROJECT_DIR$/ideaSDK/sources/sources.jar!/jps/model-impl/src" />
<root url="jar://$PROJECT_DIR$/ideaSDK/sources/sources.jar!/jps/model-impl/testSrc" />
<root url="jar://$PROJECT_DIR$/ideaSDK/sources/sources.jar!/jps/model-serialization/src" />
<root url="jar://$PROJECT_DIR$/ideaSDK/sources/sources.jar!/jps/model-serialization/testSrc" />
<root url="jar://$PROJECT_DIR$/ideaSDK/sources/sources.jar!/jps/plugin-system/src" />
<root url="jar://$PROJECT_DIR$/ideaSDK/sources/sources.jar!/jps/standalone-builder/src" />
</SOURCES>
<jarDirectory url="file://$PROJECT_DIR$/ideaSDK/jps" recursive="false" />
</library>

View File

@@ -1,9 +0,0 @@
<component name="libraryTable">
<library name="json-org">
<CLASSES>
<root url="jar://$PROJECT_DIR$/dependencies/json-org.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</component>

View File

@@ -4,9 +4,6 @@
<root url="jar://$KOTLIN_BUNDLED$/lib/kotlin-reflect.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="file://$PROJECT_DIR$/core/reflection.jvm/src" />
<root url="file://$PROJECT_DIR$/core/descriptors.runtime/src" />
</SOURCES>
<SOURCES />
</library>
</component>

View File

@@ -1,13 +1,13 @@
<component name="libraryTable">
<library name="kotlin-test">
<CLASSES>
<root url="jar://$KOTLIN_BUNDLED$/lib/kotlin-test.jar!/" />
<root url="jar://$KOTLIN_BUNDLED$/lib/kotlin-test.jar!/"/>
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="file://$PROJECT_DIR$/libraries/kotlin.test/shared/src/main/kotlin" />
<root url="file://$PROJECT_DIR$/libraries/kotlin.test/shared/src/main/kotlin.jvm" />
<root url="file://$PROJECT_DIR$/libraries/kotlin.test/junit/src/main/kotlin" />
<root url="file://$PROJECT_DIR$/libraries/kotlin.test/common/src/main/kotlin" />
<root url="file://$PROJECT_DIR$/libraries/kotlin.test/jvm/src/main/kotlin" />
</SOURCES>
</library>
</component>

View File

@@ -1,11 +0,0 @@
<component name="libraryTable">
<library name="kotlinx-coroutines-jdk8">
<CLASSES>
<root url="jar://$PROJECT_DIR$/dependencies/kotlinx-coroutines-jdk8.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$PROJECT_DIR$/dependencies/kotlinx-coroutines-jdk8-sources.jar!/" />
</SOURCES>
</library>
</component>

View File

@@ -7,6 +7,11 @@
<root url="jar://$PROJECT_DIR$/ideaSDK/lib/trove4j.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
<SOURCES>
<root url="jar://$PROJECT_DIR$/ideaSDK/lib/src/trove4j_src.jar!/core/src" />
<root url="jar://$PROJECT_DIR$/ideaSDK/lib/src/trove4j_src.jar!/generated/src" />
<root url="jar://$PROJECT_DIR$/ideaSDK/lib/src/trove4j_src.jar!/test/src" />
<root url="jar://$PROJECT_DIR$/ideaSDK/lib/src/trove4j_src.jar!/util/src" />
</SOURCES>
</library>
</component>

16
.idea/modules.xml generated
View File

@@ -9,11 +9,11 @@
<module fileurl="file://$PROJECT_DIR$/plugins/android-extensions/android-extensions-compiler/android-extensions-compiler.iml" filepath="$PROJECT_DIR$/plugins/android-extensions/android-extensions-compiler/android-extensions-compiler.iml" group="plugins/android-extensions" />
<module fileurl="file://$PROJECT_DIR$/plugins/android-extensions/android-extensions-idea/android-extensions-idea.iml" filepath="$PROJECT_DIR$/plugins/android-extensions/android-extensions-idea/android-extensions-idea.iml" group="plugins/android-extensions" />
<module fileurl="file://$PROJECT_DIR$/plugins/android-extensions/android-extensions-jps/android-extensions-jps.iml" filepath="$PROJECT_DIR$/plugins/android-extensions/android-extensions-jps/android-extensions-jps.iml" group="plugins/android-extensions" />
<module fileurl="file://$PROJECT_DIR$/plugins/android-extensions/android-extensions-runtime/android-extensions-runtime.iml" filepath="$PROJECT_DIR$/plugins/android-extensions/android-extensions-runtime/android-extensions-runtime.iml" group="plugins/android-extensions" />
<module fileurl="file://$PROJECT_DIR$/android-studio/android-studio.iml" filepath="$PROJECT_DIR$/android-studio/android-studio.iml" group="ide" />
<module fileurl="file://$PROJECT_DIR$/compiler/android-tests/android-tests.iml" filepath="$PROJECT_DIR$/compiler/android-tests/android-tests.iml" group="compiler" />
<module fileurl="file://$PROJECT_DIR$/plugins/annotation-based-compiler-plugins-ide-support/annotation-based-compiler-plugins-ide-support.iml" filepath="$PROJECT_DIR$/plugins/annotation-based-compiler-plugins-ide-support/annotation-based-compiler-plugins-ide-support.iml" group="plugins" />
<module fileurl="file://$PROJECT_DIR$/plugins/annotation-collector/annotation-collector.iml" filepath="$PROJECT_DIR$/plugins/annotation-collector/annotation-collector.iml" group="plugins" />
<module fileurl="file://$PROJECT_DIR$/plugins/annotation-processing/annotation-processing.iml" filepath="$PROJECT_DIR$/plugins/annotation-processing/annotation-processing.iml" group="plugins" />
<module fileurl="file://$PROJECT_DIR$/ant/ant.iml" filepath="$PROJECT_DIR$/ant/ant.iml" />
<module fileurl="file://$PROJECT_DIR$/compiler/backend/backend.iml" filepath="$PROJECT_DIR$/compiler/backend/backend.iml" group="compiler/java" />
<module fileurl="file://$PROJECT_DIR$/compiler/backend-common/backend-common.iml" filepath="$PROJECT_DIR$/compiler/backend-common/backend-common.iml" group="compiler" />
@@ -41,7 +41,6 @@
<module fileurl="file://$PROJECT_DIR$/idea/formatter/formatter.iml" filepath="$PROJECT_DIR$/idea/formatter/formatter.iml" group="ide" />
<module fileurl="file://$PROJECT_DIR$/compiler/frontend/frontend.iml" filepath="$PROJECT_DIR$/compiler/frontend/frontend.iml" group="compiler" />
<module fileurl="file://$PROJECT_DIR$/compiler/frontend.java/frontend.java.iml" filepath="$PROJECT_DIR$/compiler/frontend.java/frontend.java.iml" group="compiler/java" />
<module fileurl="file://$PROJECT_DIR$/compiler/frontend.script/frontend.script.iml" filepath="$PROJECT_DIR$/compiler/frontend.script/frontend.script.iml" group="compiler" />
<module fileurl="file://$PROJECT_DIR$/generators/generators.iml" filepath="$PROJECT_DIR$/generators/generators.iml" group="infrastructure" />
<module fileurl="file://$PROJECT_DIR$/grammar/grammar.iml" filepath="$PROJECT_DIR$/grammar/grammar.iml" group="compiler" />
<module fileurl="file://$PROJECT_DIR$/idea/ide-common/ide-common.iml" filepath="$PROJECT_DIR$/idea/ide-common/ide-common.iml" group="ide" />
@@ -63,11 +62,10 @@
<module fileurl="file://$PROJECT_DIR$/compiler/ir/ir.psi2ir/ir.psi2ir.iml" filepath="$PROJECT_DIR$/compiler/ir/ir.psi2ir/ir.psi2ir.iml" group="compiler/ir" />
<module fileurl="file://$PROJECT_DIR$/compiler/ir/ir.tree/ir.tree.iml" filepath="$PROJECT_DIR$/compiler/ir/ir.tree/ir.tree.iml" group="compiler/ir" />
<module fileurl="file://$PROJECT_DIR$/j2k/j2k.iml" filepath="$PROJECT_DIR$/j2k/j2k.iml" group="j2k" />
<module fileurl="file://$PROJECT_DIR$/compiler/javac-wrapper/javac-wrapper.iml" filepath="$PROJECT_DIR$/compiler/javac-wrapper/javac-wrapper.iml" group="compiler" />
<module fileurl="file://$PROJECT_DIR$/plugins/java-model-wrappers/java-model-wrappers.iml" filepath="$PROJECT_DIR$/plugins/java-model-wrappers/java-model-wrappers.iml" group="plugins" />
<module fileurl="file://$PROJECT_DIR$/jps-plugin/jps-plugin.iml" filepath="$PROJECT_DIR$/jps-plugin/jps-plugin.iml" group="ide/jps" />
<module fileurl="file://$PROJECT_DIR$/jps-plugin/jps-tests/jps-tests.iml" filepath="$PROJECT_DIR$/jps-plugin/jps-tests/jps-tests.iml" group="ide/jps" />
<module fileurl="file://$PROJECT_DIR$/js/js.ast/js.ast.iml" filepath="$PROJECT_DIR$/js/js.ast/js.ast.iml" group="compiler/js" />
<module fileurl="file://$PROJECT_DIR$/js/js.dce/js.dce.iml" filepath="$PROJECT_DIR$/js/js.dce/js.dce.iml" group="compiler/js" />
<module fileurl="file://$PROJECT_DIR$/js/js.frontend/js.frontend.iml" filepath="$PROJECT_DIR$/js/js.frontend/js.frontend.iml" group="compiler/js" />
<module fileurl="file://$PROJECT_DIR$/js/js.inliner/js.inliner.iml" filepath="$PROJECT_DIR$/js/js.inliner/js.inliner.iml" group="compiler/js" />
<module fileurl="file://$PROJECT_DIR$/js/js.parser/js.parser.iml" filepath="$PROJECT_DIR$/js/js.parser/js.parser.iml" group="compiler/js" />
@@ -75,14 +73,14 @@
<module fileurl="file://$PROJECT_DIR$/js/js.tests/js.tests.iml" filepath="$PROJECT_DIR$/js/js.tests/js.tests.iml" group="compiler/js" />
<module fileurl="file://$PROJECT_DIR$/js/js.translator/js.translator.iml" filepath="$PROJECT_DIR$/js/js.translator/js.translator.iml" group="compiler/js" />
<module fileurl="file://$PROJECT_DIR$/jps-plugin/kannotator-jps-plugin-test/kannotator-jps-plugin-test.iml" filepath="$PROJECT_DIR$/jps-plugin/kannotator-jps-plugin-test/kannotator-jps-plugin-test.iml" group="ide/jps" />
<module fileurl="file://$PROJECT_DIR$/plugins/kapt3/kapt3.iml" filepath="$PROJECT_DIR$/plugins/kapt3/kapt3.iml" group="plugins" />
<module fileurl="file://$PROJECT_DIR$/plugins/kapt3/kapt3.iml" filepath="$PROJECT_DIR$/plugins/kapt3/kapt3.iml" />
<module fileurl="file://$PROJECT_DIR$/idea/kotlin-gradle-tooling/kotlin-gradle-tooling.iml" filepath="$PROJECT_DIR$/idea/kotlin-gradle-tooling/kotlin-gradle-tooling.iml" />
<module fileurl="file://$PROJECT_DIR$/compiler/light-classes/light-classes.iml" filepath="$PROJECT_DIR$/compiler/light-classes/light-classes.iml" group="compiler/java" />
<module fileurl="file://$PROJECT_DIR$/plugins/lint/lint-api/lint-api.iml" filepath="$PROJECT_DIR$/plugins/lint/lint-api/lint-api.iml" group="plugins/lint" />
<module fileurl="file://$PROJECT_DIR$/plugins/lint/lint-checks/lint-checks.iml" filepath="$PROJECT_DIR$/plugins/lint/lint-checks/lint-checks.iml" group="plugins/lint" />
<module fileurl="file://$PROJECT_DIR$/plugins/lint/lint-idea/lint-idea.iml" filepath="$PROJECT_DIR$/plugins/lint/lint-idea/lint-idea.iml" group="plugins/lint" />
<module fileurl="file://$PROJECT_DIR$/plugins/noarg/noarg-cli/noarg-cli.iml" filepath="$PROJECT_DIR$/plugins/noarg/noarg-cli/noarg-cli.iml" group="plugins/noarg" />
<module fileurl="file://$PROJECT_DIR$/plugins/noarg/noarg-ide/noarg-ide.iml" filepath="$PROJECT_DIR$/plugins/noarg/noarg-ide/noarg-ide.iml" group="plugins/noarg" />
<module fileurl="file://$PROJECT_DIR$/plugins/noarg/noarg-cli/noarg-cli.iml" filepath="$PROJECT_DIR$/plugins/noarg/noarg-cli/noarg-cli.iml" />
<module fileurl="file://$PROJECT_DIR$/plugins/noarg/noarg-ide/noarg-ide.iml" filepath="$PROJECT_DIR$/plugins/noarg/noarg-ide/noarg-ide.iml" />
<module fileurl="file://$PROJECT_DIR$/non-compiler-tests/non-compiler-tests.iml" filepath="$PROJECT_DIR$/non-compiler-tests/non-compiler-tests.iml" />
<module fileurl="file://$PROJECT_DIR$/compiler/plugin-api/plugin-api.iml" filepath="$PROJECT_DIR$/compiler/plugin-api/plugin-api.iml" group="compiler" />
<module fileurl="file://$PROJECT_DIR$/plugins/plugins-tests/plugins-tests.iml" filepath="$PROJECT_DIR$/plugins/plugins-tests/plugins-tests.iml" group="plugins" />
@@ -90,8 +88,8 @@
<module fileurl="file://$PROJECT_DIR$/core/reflection.jvm/reflection.jvm.iml" filepath="$PROJECT_DIR$/core/reflection.jvm/reflection.jvm.iml" group="core" />
<module fileurl="file://$PROJECT_DIR$/compiler/resolution/resolution.iml" filepath="$PROJECT_DIR$/compiler/resolution/resolution.iml" group="compiler" />
<module fileurl="file://$PROJECT_DIR$/core/runtime.jvm/runtime.jvm.iml" filepath="$PROJECT_DIR$/core/runtime.jvm/runtime.jvm.iml" group="core" />
<module fileurl="file://$PROJECT_DIR$/plugins/sam-with-receiver/sam-with-receiver-cli/sam-with-receiver-cli.iml" filepath="$PROJECT_DIR$/plugins/sam-with-receiver/sam-with-receiver-cli/sam-with-receiver-cli.iml" group="plugins/sam-with-receiver" />
<module fileurl="file://$PROJECT_DIR$/plugins/sam-with-receiver/sam-with-receiver-ide/sam-with-receiver-ide.iml" filepath="$PROJECT_DIR$/plugins/sam-with-receiver/sam-with-receiver-ide/sam-with-receiver-ide.iml" group="plugins/sam-with-receiver" />
<module fileurl="file://$PROJECT_DIR$/plugins/sam-with-receiver/sam-with-receiver-cli/sam-with-receiver-cli.iml" filepath="$PROJECT_DIR$/plugins/sam-with-receiver/sam-with-receiver-cli/sam-with-receiver-cli.iml" />
<module fileurl="file://$PROJECT_DIR$/plugins/sam-with-receiver/sam-with-receiver-ide/sam-with-receiver-ide.iml" filepath="$PROJECT_DIR$/plugins/sam-with-receiver/sam-with-receiver-ide/sam-with-receiver-ide.iml" />
<module fileurl="file://$PROJECT_DIR$/core/script.runtime/script.runtime.iml" filepath="$PROJECT_DIR$/core/script.runtime/script.runtime.iml" group="core" />
<module fileurl="file://$PROJECT_DIR$/compiler/serialization/serialization.iml" filepath="$PROJECT_DIR$/compiler/serialization/serialization.iml" group="compiler" />
<module fileurl="file://$PROJECT_DIR$/plugins/source-sections/source-sections-compiler/source-sections-compiler.iml" filepath="$PROJECT_DIR$/plugins/source-sections/source-sections-compiler/source-sections-compiler.iml" group="plugins" />

View File

@@ -1,28 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Codegen Tests with JVM target 1.6 on JDK 1.6" type="JUnit" factoryName="JUnit">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea">
<pattern>
<option name="PATTERN" value="org.jetbrains.kotlin.codegen.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<module name="compiler-tests" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="true" />
<option name="ALTERNATIVE_JRE_PATH" value="1.8" />
<option name="PACKAGE_NAME" value="org.jetbrains.kotlin.codegen" />
<option name="MAIN_CLASS_NAME" value="org.jetbrains.kotlin.codegen.CodegenJdkCommonTestSuite" />
<option name="METHOD_NAME" value="" />
<option name="TEST_OBJECT" value="class" />
<option name="VM_PARAMETERS" value="-Dkotlin.test.default.jvm.target=1.6 -Dkotlin.test.box.in.separate.process.port=5100 -Dkotlin.test.java.compilation.target=1.6 -ea -XX:+HeapDumpOnOutOfMemoryError -Xmx1024m -XX:+UseCodeCacheFlushing -XX:ReservedCodeCacheSize=128m -Djna.nosys=true" />
<option name="PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<envs />
<patterns />
<method />
</configuration>
</component>

View File

@@ -1,28 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Codegen Tests with JVM target 1.6 on JDK 9" type="JUnit" factoryName="JUnit">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea">
<pattern>
<option name="PATTERN" value="org.jetbrains.kotlin.codegen.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<module name="compiler-tests" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="true" />
<option name="ALTERNATIVE_JRE_PATH" value="9-ea" />
<option name="PACKAGE_NAME" value="org.jetbrains.kotlin.codegen" />
<option name="MAIN_CLASS_NAME" value="org.jetbrains.kotlin.codegen.CodegenJdkCommonTestSuite" />
<option name="METHOD_NAME" value="" />
<option name="TEST_OBJECT" value="class" />
<option name="VM_PARAMETERS" value="-Dkotlin.test.default.jvm.target=1.6 -ea -XX:+HeapDumpOnOutOfMemoryError -XX:+UseCodeCacheFlushing -XX:ReservedCodeCacheSize=128m -Djna.nosys=true --add-opens java.desktop/javax.swing=ALL-UNNAMED --add-opens java.base/java.io=ALL-UNNAMED" />
<option name="PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<envs />
<patterns />
<method />
</configuration>
</component>

View File

@@ -1,28 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Codegen Tests with JVM target 1.8 on JDK 1.8" type="JUnit" factoryName="JUnit">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea">
<pattern>
<option name="PATTERN" value="org.jetbrains.kotlin.codegen.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<module name="compiler-tests" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="true" />
<option name="ALTERNATIVE_JRE_PATH" value="1.8" />
<option name="PACKAGE_NAME" value="org.jetbrains.kotlin.codegen" />
<option name="MAIN_CLASS_NAME" value="org.jetbrains.kotlin.codegen.CodegenJdkCommonTestSuite" />
<option name="METHOD_NAME" value="" />
<option name="TEST_OBJECT" value="class" />
<option name="VM_PARAMETERS" value="-Dkotlin.test.default.jvm.target=1.8 -ea -XX:+HeapDumpOnOutOfMemoryError -Xmx1024m -XX:+UseCodeCacheFlushing -XX:ReservedCodeCacheSize=128m -Djna.nosys=true" />
<option name="PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<envs />
<patterns />
<method />
</configuration>
</component>

View File

@@ -1,28 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Codegen Tests with JVM target 1.8 on JDK 9" type="JUnit" factoryName="JUnit">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea">
<pattern>
<option name="PATTERN" value="org.jetbrains.kotlin.codegen.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<module name="compiler-tests" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="true" />
<option name="ALTERNATIVE_JRE_PATH" value="9-ea" />
<option name="PACKAGE_NAME" value="org.jetbrains.kotlin.codegen" />
<option name="MAIN_CLASS_NAME" value="org.jetbrains.kotlin.codegen.CodegenJdkCommonTestSuite" />
<option name="METHOD_NAME" value="" />
<option name="TEST_OBJECT" value="class" />
<option name="VM_PARAMETERS" value="-Dkotlin.test.default.jvm.target=1.8 -ea -XX:+HeapDumpOnOutOfMemoryError -XX:+UseCodeCacheFlushing -XX:ReservedCodeCacheSize=128m -Djna.nosys=true --add-opens java.desktop/javax.swing=ALL-UNNAMED --add-opens java.base/java.io=ALL-UNNAMED" />
<option name="PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<envs />
<patterns />
<method />
</configuration>
</component>

View File

@@ -1,28 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Codegen Tests with JVM target 9 on JDK 9 " type="JUnit" factoryName="JUnit">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea">
<pattern>
<option name="PATTERN" value="org.jetbrains.kotlin.codegen.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<module name="compiler-tests" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="true" />
<option name="ALTERNATIVE_JRE_PATH" value="9-ea" />
<option name="PACKAGE_NAME" value="org.jetbrains.kotlin.codegen" />
<option name="MAIN_CLASS_NAME" value="org.jetbrains.kotlin.codegen.CodegenJdkCommonTestSuite" />
<option name="METHOD_NAME" value="" />
<option name="TEST_OBJECT" value="class" />
<option name="VM_PARAMETERS" value="-Dkotlin.test.default.jvm.target=1.8 -Dkotlin.test.substitute.bytecode.1.8.to.1.9=true -ea -XX:+HeapDumpOnOutOfMemoryError -XX:+UseCodeCacheFlushing -XX:ReservedCodeCacheSize=128m -Djna.nosys=true --add-opens java.desktop/javax.swing=ALL-UNNAMED --add-opens java.base/java.io=ALL-UNNAMED" />
<option name="PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<envs />
<patterns />
<method />
</configuration>
</component>

View File

@@ -8,7 +8,7 @@
<option name="MAIN_CLASS_NAME" value="" />
<option name="METHOD_NAME" value="" />
<option name="TEST_OBJECT" value="package" />
<option name="VM_PARAMETERS" value="-ea -XX:+HeapDumpOnOutOfMemoryError -Xmx1250m -XX:+UseCodeCacheFlushing -Djna.nosys=true -Dkotlin.js.skipMinificationTest=false" />
<option name="VM_PARAMETERS" value="-ea -XX:+HeapDumpOnOutOfMemoryError -Xmx1250m -XX:+UseCodeCacheFlushing -Djna.nosys=true" />
<option name="PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$" />
<option name="ENV_VARIABLES" />

File diff suppressed because it is too large Load Diff

View File

@@ -14,73 +14,37 @@
<excludeFolder url="file://$MODULE_DIR$/ideaSDK/system" />
<excludeFolder url="file://$MODULE_DIR$/ideaSDK/system-idea" />
<excludeFolder url="file://$MODULE_DIR$/libraries/.idea" />
<excludeFolder url="file://$MODULE_DIR$/libraries/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/examples/annotation-processor-example/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/examples/browser-example-with-library/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/docs/apidoc/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/docs/website/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/examples/browser-example/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/examples/js-example/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/examples/kotlin-gradle-subplugin-example/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/examples/kotlin-java-example/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/examples/kotlin-js-library-example/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/examples/kotlin-jsr223-daemon-local-eval-example/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/examples/kotlin-jsr223-local-example/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/kotlin.test/common/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/kotlin.test/js/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/kotlin.test/js/it/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/kotlin.test/js/it/node_modules" />
<excludeFolder url="file://$MODULE_DIR$/libraries/kotlin.test/junit/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/kotlin.test/jvm/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/stdlib/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/stdlib/common/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/stdlib/jre7/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/stdlib/jre8/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/stdlib/js/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/stdlib/js/node_modules" />
<excludeFolder url="file://$MODULE_DIR$/libraries/kotlin-jdbc/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/kotlin-swing/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/kunit/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/stdlib/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/stdlib/validator/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/.idea" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/binary-compatibility-validator/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/gradle-tools/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/idl2k/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-allopen/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-allopen/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-android-extensions/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-annotation-processing-maven/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-annotation-processing/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-build-common-test/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-compiler-client-embeddable-test/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-compiler-client-embeddable/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-compiler-embeddable/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-compiler-runner/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kdoc-maven-plugin/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kdoc/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-compiler/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-daemon-client/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-gradle-plugin-api/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-gradle-plugin-api/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-gradle-plugin-integration-tests/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-gradle-plugin-integration-tests/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-gradle-plugin/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-gradle-plugin-core/local-repo" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-gradle-plugin-core/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-gradle-plugin-test/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-gradle-plugin/local-repo" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-gradle-plugin/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-maven-allopen/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-maven-noarg/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-js-library/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-js-tests-junit/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-js-tests/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-maven-plugin-test/local-repo" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-maven-plugin-test/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-maven-plugin/local-repo" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-maven-plugin/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-noarg/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-noarg/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-osgi-bundle/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-reflect/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-sam-with-receiver-compiler-plugin/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-script-util/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-source-sections-compiler-plugin/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-stdlib-gen/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/maven-archetypes/kotlin-archetype-js/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/maven-archetypes/kotlin-archetype-jvm/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/native-platform/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/protobuf-lite/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/runtime/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/script-runtime/build" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-reflect/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/kotlin-stdlib-gen/target" />
<excludeFolder url="file://$MODULE_DIR$/libraries/tools/runtime/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
</module>

104
ReadMe.md
View File

@@ -1,4 +1,4 @@
<a href="http://slack.kotlinlang.org/"><img src="http://slack.kotlinlang.org/badge.svg" height="20"></a>
<a href="https://kotlinslackin.herokuapp.com"><img src="https://kotlinslackin.herokuapp.com/badge.svg" height="20"></a>
[![TeamCity (simple build status)](https://img.shields.io/teamcity/http/teamcity.jetbrains.com/s/bt345.svg)](https://teamcity.jetbrains.com/viewType.html?buildTypeId=bt345&branch_Kotlin=%3Cdefault%3E&tab=buildTypeStatusDiv)
[![Maven Central](https://img.shields.io/maven-central/v/org.jetbrains.kotlin/kotlin-maven-plugin.svg)](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.jetbrains.kotlin%22)
[![GitHub license](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg?style=flat)](http://www.apache.org/licenses/LICENSE-2.0)
@@ -9,13 +9,13 @@ Welcome to [Kotlin](https://kotlinlang.org/)! Some handy links:
* [Kotlin Site](https://kotlinlang.org/)
* [Getting Started Guide](https://kotlinlang.org/docs/tutorials/getting-started.html)
* [Try Kotlin](https://try.kotlinlang.org/)
* [Try Kotlin](http://try.kotlinlang.org/)
* [Kotlin Standard Library](https://kotlinlang.org/api/latest/jvm/stdlib/index.html)
* [Issue Tracker](https://youtrack.jetbrains.com/issues/KT)
* [Forum](https://discuss.kotlinlang.org/)
* [Kotlin Blog](https://blog.jetbrains.com/kotlin/)
* [Follow Kotlin on Twitter](https://twitter.com/kotlin)
* [Public Slack channel](http://slack.kotlinlang.org/)
* [Public Slack channel](https://kotlinslackin.herokuapp.com/)
* [TeamCity CI build](https://teamcity.jetbrains.com/project.html?tab=projectOverview&projectId=Kotlin)
## Editing Kotlin
@@ -45,49 +45,65 @@ To build this project, first time you try to build you need to run this:
which will setup the dependencies on
* `intellij-core` is a part of command line compiler and contains only necessary APIs.
* `idea-full` is a full blown IntelliJ IDEA Community Edition to be used in the plugin module.
* intellij-core: is a part of command line compiler and contains only necessary APIs.
* idea-full: is a full blown IntelliJ IDEA Community Edition to be used in former plugin module.
Then, you need to run
ant -f build.xml
which will build the binaries of the compiler and put them into the `dist` directory. You may need to increase the **heap size** for Ant using
which will build the binaries of the compiler and put them into the 'dist' directory. You may need to increase the **heap size** for Ant using
[ANT_OPTS](https://web.liferay.com/community/wiki/-/wiki/Main/Ant+opts).
**OPTIONAL:** Maven artifact distribution is built separately, go into `libraries` directory after building the compiler and run:
**OPTIONAL:** Maven distribution is built separately, run
./gradlew build install
mvn install
mvn package
> Note: on Windows type `gradlew` without the leading `./`
Refer to [libraries/ReadMe.md](libraries/ReadMe.md) for details.
from 'libraries' directory after building the compiler. Refer to [libraries/ReadMe.md](libraries/ReadMe.md) for details.
## Working with the project in IntelliJ IDEA
The [root kotlin project](https://github.com/JetBrains/kotlin) already has an IntelliJ IDEA project, you can just open it in IntelliJ IDEA.
You may need to set the Project SDK (`File -> Project Structure -> Project`).
You may also need to add `tools.jar` to your SDK:
File -> Project Structure -> SDKs -> <Your JDK> -> Classpath
You may need to set the Project SDK (File -> Project Structure -> Project).
You may also need to add `tools.jar` to your SDK: File -> Project Structure -> SDKs -> <Your JDK> -> Classpath,
then choose the `tools.jar` in the JDK's `lib` directory.
If you are not dealing with Android, you may need to disable the Android Plugin in order to compile the project.
### <a name="installing-plugin"></a> Installing the latest Kotlin plugin
Since Kotlin project contains code written in Kotlin itself, you will also need a Kotlin plugin to build the project in IntelliJ IDEA.
To keep the plugin version in sync with the rest of the team and our [Continuous Integration server](https://teamcity.jetbrains.com/project.html?projectId=Kotlin&tab=projectOverview)
you should install the according to the [instructions below](#plugin-for-contributors).
You probably want to have locally the same version of plugin that build server is using for building.
If you want to have an IntelliJ IDEA installation without the Kotlin plugin which is separate to your default IntelliJ IDEA installation which has the Kotlin
plugin [see this document](https://devnet.jetbrains.com/docs/DOC-181) which describes how to have multiple IntelliJ IDEA installations using different configurations and plugin directories.
From this root project there are Run/Debug Configurations for running IDEA or the Compiler Tests for example; so if you want to try out the latest and greatest IDEA plugin
* VCS -> Git -> Pull
* Run IntelliJ IDEA
* a child IntelliJ IDEA with the Kotlin plugin will then startup
* you can now open the [kotlin libraries project](https://github.com/JetBrains/kotlin/tree/master/libraries) to then work with the various kotlin libraries etc.
### <a name="pre-built-plugin"></a>Using a pre-built Kotlin IntelliJ IDEA plugin
There are several options for getting Kotlin plugin. A stable version can be obtained as any other plugin for IntelliJ IDEA:
Preferences -> Plugins -> Install JetBrains plugin... -> Search with "Kotlin" string
The most recent version of the plugin can be downloaded from the
[IDEA Plugin and Tests CI build](https://teamcity.jetbrains.com/project.html?projectId=project67&tab=projectOverview). When downloading is
finished you can install it with "Install plugin from disk...":
Preferences -> Plugins -> Install plugin from disk...
You can now open any Kotlin based projects.
<a name="plugin-for-contributors"></a>
**Note for contributors**: If you are planning to contribute to Kotlin project you probably want to have locally the same version of plugin that build server is using for building.
As this version is constantly moving, the best way to always be updated is to let IntelliJ IDEA notify you when it is time to renew your plugin.
To keep the plugin version in sync with the rest of the team and our [Continuous Integration server](https://teamcity.jetbrains.com/project.html?projectId=Kotlin&tab=projectOverview)
you should setup IDEA to update the plugin directly from the build server.
Open:
Open
Preferences -> Plugins -> Browse Repositories -> Manage Repositories...
@@ -97,22 +113,10 @@ and add the following URL to your repositories:
Then update the list of plugins in "Browse Repositories", you'll see two versions of Kotlin there, install the one with the higher version number.
If you want to keep an IntelliJ IDEA installation with that bleeding edge Kotlin plugin for working Kotlin project sources only separate to your default IntelliJ IDEA installation with the stable Kotlin
plugin [see this document](https://intellij-support.jetbrains.com/hc/en-us/articles/207240985-Changing-IDE-default-directories-used-for-config-plugins-and-caches-storage), which describes how to have multiple IntelliJ IDEA installations using different configurations and plugin directories.
### Compiling and running
From this root project there are Run/Debug Configurations for running IDEA or the Compiler Tests for example; so if you want to try out the latest and greatest IDEA plugin
* VCS -> Git -> Pull
* Run IntelliJ IDEA
* a child IntelliJ IDEA with the Kotlin plugin will then startup
* you can now open the [kotlin libraries project](https://github.com/JetBrains/kotlin/tree/master/libraries) to then work with the various kotlin libraries etc.
# Contributing
We love contributions! There's [lots to do on Kotlin](https://youtrack.jetbrains.com/issues/KT) and on the
[standard library](https://youtrack.jetbrains.com/issues/KT?q=%23Kotlin%20%23Unresolved%20and%20(links:%20KT-2554,%20KT-4089%20or%20%23Libraries)) so why not chat with us
[standard library](https://youtrack.jetbrains.com/issues/KT?q=Subtask+of%3A+KT-2554+%23Unresolved) so why not chat with us
about what you're interested in doing? Please join the #kontributors channel in [our Slack chat](http://kotlinslackin.herokuapp.com/)
and let us know about your plans.
@@ -124,8 +128,8 @@ A nice gentle way to contribute would be to review the [standard library docs](h
and find classes or functions which are not documented very well and submit a patch.
In particular it'd be great if all functions included a nice example of how to use it such as for the
[`hashMapOf()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/hash-map-of.html) function.
This is implemented using the [`@sample`](https://github.com/JetBrains/kotlin/blob/1.1.0/libraries/stdlib/src/kotlin/collections/Maps.kt#L91)
[`hashMapOf()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/hash-map-of.html) function.
This is implemented using the [`@sample`](https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/src/kotlin/collections/Maps.kt#L64)
macro to include code from a test function. The benefits of this approach are twofold; First, the API's documentation is improved via beneficial examples that help new users and second, the code coverage is increased.
Also the [JavaScript translation](https://github.com/JetBrains/kotlin/blob/master/js/ReadMe.md) could really use your help. See the [JavaScript contribution section](https://github.com/JetBrains/kotlin/blob/master/js/ReadMe.md) for more details.
@@ -135,8 +139,8 @@ Also the [JavaScript translation](https://github.com/JetBrains/kotlin/blob/maste
The Kotlin compiler is written in Java and Kotlin (we gradually migrate more and more of it to pure Kotlin). So the easiest way to work on the compiler or IntelliJ IDEA plugin is
* download a recent [IntelliJ IDEA](https://www.jetbrains.com/idea/?fromMenu#chooseYourEdition), Community edition is enough
* [install the Kotlin plugin](#installing-plugin)
* download a clean [IDEA 15 EAP build](https://confluence.jetbrains.com/display/IDEADEV/IDEA+15+EAP)
* [install the Kotlin plugin](#pre-built-plugin)
* open the [root kotlin project](https://github.com/JetBrains/kotlin) in IDEA (opening the kotlin directory)
You can now run the various Run/Debug Configurations such as
@@ -148,19 +152,16 @@ You can now run the various Run/Debug Configurations such as
## If you want to work on the Kotlin libraries
* download a recent [IntelliJ IDEA](https://www.jetbrains.com/idea/?fromMenu#chooseYourEdition), Community edition is enough
* [install the Kotlin plugin](#installing-plugin)
* download a clean [IDEA 15 EAP build](https://confluence.jetbrains.com/display/IDEADEV/IDEA+15+EAP)
* [install the Kotlin plugin](#pre-built-plugin)
* open the [kotlin libraries project](https://github.com/JetBrains/kotlin/tree/master/libraries)
Then build via
cd libraries
./gradlew build install
mvn install
> Note: on Windows type `gradlew` without the leading `./`
Some of the code in the standard library is created by generating code from templates. See the [README](libraries/stdlib/ReadMe.md) in the stdlib section for how run the code generator. The existing templates can be used as examples for creating new ones.
Some of the code in the standard library is created by generating code from templates. See the [README](https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/ReadMe.md) in the stdlib section for how run the code generator. The existing templates can be used as examples for creating new ones.
## Submitting patches
@@ -168,15 +169,12 @@ The best way to submit a patch is to [fork the project on github](https://help.g
[pull request](https://help.github.com/articles/creating-a-pull-request/) via [github](https://github.com).
If you create your own fork, it might help to enable rebase by default
when you pull by executing
``` bash
git config --global pull.rebase true
```
This will avoid your local repo having too many merge commits
when you pull by executing `git config --global pull.rebase
true`. This will avoid your local repo having too many merge commits
which will help keep your pull request simple and easy to apply.
## Commit comments
If you include in your comment this text (where KT-1234 is the Issue ID in the [Issue Tracker](https://youtrack.jetbrains.com/issues/KT)), the issue will get automatically marked as fixed.
If you include in your comment this text (where KT-1234 is the Issue ID in the [Issue Tracker](https://youtrack.jetbrains.com/issues/KT), the issue will get automatically marked as fixed.
#KT-1234 Fixed

View File

@@ -151,8 +151,8 @@
<print-file-size-statistic path="${kotlin-home}/lib" file-name="kotlin-stdlib-js.jar"/>
<print-file-size-statistic path="${js.stdlib.output.dir}" file-name="kotlin.js"/>
<print-file-size-statistic path="${js.stdlib.output.dir}" file-name="kotlin-test.js"/>
<print-file-size-statistic path="${basedir}/libraries/stdlib/js/build/classes/main" file-name="kotlin.meta.js"/>
<print-file-size-statistic path="${js.stdlib.output.dir}" file-name="${compiled.stdlib.meta.js}"/>
<print-file-size-statistic path="${js.stdlib.output.dir}" file-name="${compiled.stdlib.js}"/>
</target>
<target name="post_build" depends="zipArtifacts, revertTemplateFiles, printStatistics, remove_internal_artifacts, dont_remove_internal_artifacts"/>

View File

@@ -18,7 +18,6 @@ package org.jetbrains.kotlin.ant
import org.apache.tools.ant.BuildException
import org.apache.tools.ant.MagicNames
import org.apache.tools.ant.Project.MSG_ERR
import org.apache.tools.ant.Project.MSG_WARN
import org.apache.tools.ant.taskdefs.compilers.Javac13
import org.apache.tools.ant.taskdefs.condition.AntVersion
@@ -45,11 +44,6 @@ class KotlinCompilerAdapter : Javac13() {
@Throws(BuildException::class)
override fun execute(): Boolean {
if (javac.isForkedJavac) {
javac.log("<withKotlin> task does not yet support the fork mode", MSG_ERR)
return false
}
val javac = javac
checkAntVersion()

View File

@@ -14,6 +14,5 @@
<orderEntry type="module" module-name="util" />
<orderEntry type="module" module-name="tests-common" scope="TEST" />
<orderEntry type="library" scope="TEST" name="idea-full" level="project" />
<orderEntry type="library" name="kotlin-reflect" level="project" />
</component>
</module>

View File

@@ -63,13 +63,13 @@ fun JvmBuildMetaInfo(args: CommonCompilerArguments): JvmBuildMetaInfo =
compilerBuildVersion = KotlinCompilerVersion.VERSION,
languageVersionString = args.languageVersion ?: LanguageVersion.LATEST_STABLE.versionString,
apiVersionString = args.apiVersion ?: ApiVersion.LATEST_STABLE.versionString,
coroutinesEnable = args.coroutinesState == CommonCompilerArguments.ENABLE,
coroutinesWarn = args.coroutinesState == CommonCompilerArguments.WARN,
coroutinesError = args.coroutinesState == CommonCompilerArguments.ERROR,
coroutinesEnable = args.coroutinesEnable,
coroutinesWarn = args.coroutinesWarn,
coroutinesError = args.coroutinesError,
multiplatformEnable = args.multiPlatform,
metadataVersionMajor = JvmMetadataVersion.INSTANCE.major,
metadataVersionMinor = JvmMetadataVersion.INSTANCE.minor,
metadataVersionPatch = JvmMetadataVersion.INSTANCE.patch,
bytecodeVersionMajor = JvmBytecodeBinaryVersion.INSTANCE.major,
bytecodeVersionMinor = JvmBytecodeBinaryVersion.INSTANCE.minor,
bytecodeVersionPatch = JvmBytecodeBinaryVersion.INSTANCE.patch)
bytecodeVersionPatch = JvmBytecodeBinaryVersion.INSTANCE.patch)

View File

@@ -16,23 +16,22 @@
package org.jetbrains.kotlin.compilerRunner;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.ComparatorUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.cli.common.arguments.Argument;
import org.jetbrains.kotlin.cli.common.arguments.CommonToolArguments;
import org.jetbrains.kotlin.cli.common.arguments.ParseCommandLineArgumentsKt;
import org.jetbrains.kotlin.utils.StringsKt;
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments;
import org.jetbrains.kotlin.cli.common.parser.com.sampullara.cli.Argument;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
public class ArgumentUtils {
private ArgumentUtils() {}
@NotNull
public static List<String> convertArgumentsToStringList(@NotNull CommonToolArguments arguments)
public static List<String> convertArgumentsToStringList(@NotNull CommonCompilerArguments arguments)
throws InstantiationException, IllegalAccessException {
List<String> result = new ArrayList<>();
convertArgumentsToStringList(arguments, arguments.getClass().newInstance(), arguments.getClass(), result);
@@ -41,8 +40,8 @@ public class ArgumentUtils {
}
private static void convertArgumentsToStringList(
@NotNull CommonToolArguments arguments,
@NotNull CommonToolArguments defaultArguments,
@NotNull CommonCompilerArguments arguments,
@NotNull CommonCompilerArguments defaultArguments,
@NotNull Class<?> clazz,
@NotNull List<String> result
) throws IllegalAccessException, InstantiationException {
@@ -61,26 +60,27 @@ public class ArgumentUtils {
continue;
}
if (value == null || Objects.equals(value, defaultValue)) continue;
if (ComparatorUtil.equalsNullable(value, defaultValue)) continue;
String name = getAlias(argument);
if (name == null) {
name = getName(argument, field);
}
Class<?> fieldType = field.getType();
if (fieldType.isArray()) {
Object[] values = (Object[]) value;
if (values.length == 0) continue;
value = StringsKt.join(Arrays.asList(values), ",");
//noinspection unchecked
value = StringUtil.join(values, Function.TO_STRING, argument.delimiter());
}
result.add(argument.value());
result.add(argument.prefix() + name);
if (fieldType == boolean.class || fieldType == Boolean.class) continue;
if (ParseCommandLineArgumentsKt.isAdvanced(argument)) {
result.set(result.size() - 1, argument.value() + "=" + value.toString());
}
else {
result.add(value.toString());
}
result.add(value.toString());
}
Class<?> superClazz = clazz.getSuperclass();
@@ -88,4 +88,14 @@ public class ArgumentUtils {
convertArgumentsToStringList(arguments, defaultArguments, superClazz, result);
}
}
private static String getAlias(Argument argument) {
String alias = argument.alias();
return alias.isEmpty() ? null : alias;
}
private static String getName(Argument argument, Field field) {
String name = argument.value();
return name.isEmpty() ? field.getName() : name;
}
}

View File

@@ -27,7 +27,7 @@ interface ICReporter {
fun reportCompileIteration(sourceFiles: Collection<File>, exitCode: ExitCode) {}
fun pathsAsString(files: Iterable<File>): String =
files.joinToString { it.canonicalPath }
files.map { it.canonicalPath }.joinToString()
fun pathsAsString(vararg files: File): String =
pathsAsString(files.toList())

View File

@@ -197,7 +197,7 @@ open class LookupStorage(private val targetDataDir: File) : BasicMapsOwner() {
}
class LookupTrackerImpl(private val delegate: LookupTracker) : LookupTracker {
val lookups = MultiMap.createSet<LookupSymbol, String>()
val lookups = MultiMap<LookupSymbol, String>()
val pathInterner = StringInterner()
private val interner = StringInterner()

View File

@@ -56,12 +56,6 @@ open class ProtoCompareGenerated(val oldNameResolver: NameResolver, val newNameR
if (!checkStringEquals(old.getExtension(JvmProtoBuf.packageModuleName), new.getExtension(JvmProtoBuf.packageModuleName))) return false
}
if (old.getExtensionCount(JvmProtoBuf.packageLocalVariable) != new.getExtensionCount(JvmProtoBuf.packageLocalVariable)) return false
for(i in 0..old.getExtensionCount(JvmProtoBuf.packageLocalVariable) - 1) {
if (!checkEquals(old.getExtension(JvmProtoBuf.packageLocalVariable, i), new.getExtension(JvmProtoBuf.packageLocalVariable, i))) return false
}
return true
}
enum class ProtoBufPackageKind {
@@ -70,8 +64,7 @@ open class ProtoCompareGenerated(val oldNameResolver: NameResolver, val newNameR
TYPE_ALIAS_LIST,
TYPE_TABLE,
SINCE_KOTLIN_INFO_TABLE,
PACKAGE_MODULE_NAME,
PACKAGE_LOCAL_VARIABLE_LIST
PACKAGE_MODULE_NAME
}
fun difference(old: ProtoBuf.Package, new: ProtoBuf.Package): EnumSet<ProtoBufPackageKind> {
@@ -98,12 +91,6 @@ open class ProtoCompareGenerated(val oldNameResolver: NameResolver, val newNameR
if (!checkStringEquals(old.getExtension(JvmProtoBuf.packageModuleName), new.getExtension(JvmProtoBuf.packageModuleName))) result.add(ProtoBufPackageKind.PACKAGE_MODULE_NAME)
}
if (old.getExtensionCount(JvmProtoBuf.packageLocalVariable) != new.getExtensionCount(JvmProtoBuf.packageLocalVariable)) result.add(ProtoBufPackageKind.PACKAGE_LOCAL_VARIABLE_LIST)
for(i in 0..old.getExtensionCount(JvmProtoBuf.packageLocalVariable) - 1) {
if (!checkEquals(old.getExtension(JvmProtoBuf.packageLocalVariable, i), new.getExtension(JvmProtoBuf.packageLocalVariable, i))) result.add(ProtoBufPackageKind.PACKAGE_LOCAL_VARIABLE_LIST)
}
return result
}
@@ -160,12 +147,6 @@ open class ProtoCompareGenerated(val oldNameResolver: NameResolver, val newNameR
if (!checkStringEquals(old.getExtension(JvmProtoBuf.classModuleName), new.getExtension(JvmProtoBuf.classModuleName))) return false
}
if (old.getExtensionCount(JvmProtoBuf.classLocalVariable) != new.getExtensionCount(JvmProtoBuf.classLocalVariable)) return false
for(i in 0..old.getExtensionCount(JvmProtoBuf.classLocalVariable) - 1) {
if (!checkEquals(old.getExtension(JvmProtoBuf.classLocalVariable, i), new.getExtension(JvmProtoBuf.classLocalVariable, i))) return false
}
return true
}
enum class ProtoBufClassKind {
@@ -185,8 +166,7 @@ open class ProtoCompareGenerated(val oldNameResolver: NameResolver, val newNameR
TYPE_TABLE,
SINCE_KOTLIN_INFO,
SINCE_KOTLIN_INFO_TABLE,
CLASS_MODULE_NAME,
CLASS_LOCAL_VARIABLE_LIST
CLASS_MODULE_NAME
}
fun difference(old: ProtoBuf.Class, new: ProtoBuf.Class): EnumSet<ProtoBufClassKind> {
@@ -244,12 +224,6 @@ open class ProtoCompareGenerated(val oldNameResolver: NameResolver, val newNameR
if (!checkStringEquals(old.getExtension(JvmProtoBuf.classModuleName), new.getExtension(JvmProtoBuf.classModuleName))) result.add(ProtoBufClassKind.CLASS_MODULE_NAME)
}
if (old.getExtensionCount(JvmProtoBuf.classLocalVariable) != new.getExtensionCount(JvmProtoBuf.classLocalVariable)) result.add(ProtoBufClassKind.CLASS_LOCAL_VARIABLE_LIST)
for(i in 0..old.getExtensionCount(JvmProtoBuf.classLocalVariable) - 1) {
if (!checkEquals(old.getExtension(JvmProtoBuf.classLocalVariable, i), new.getExtension(JvmProtoBuf.classLocalVariable, i))) result.add(ProtoBufClassKind.CLASS_LOCAL_VARIABLE_LIST)
}
return result
}
@@ -1079,10 +1053,6 @@ fun ProtoBuf.Package.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int)
hashCode = 31 * hashCode + stringIndexes(getExtension(JvmProtoBuf.packageModuleName))
}
for(i in 0..getExtensionCount(JvmProtoBuf.packageLocalVariable) - 1) {
hashCode = 31 * hashCode + getExtension(JvmProtoBuf.packageLocalVariable, i).hashCode(stringIndexes, fqNameIndexes)
}
return hashCode
}
@@ -1155,10 +1125,6 @@ fun ProtoBuf.Class.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) ->
hashCode = 31 * hashCode + stringIndexes(getExtension(JvmProtoBuf.classModuleName))
}
for(i in 0..getExtensionCount(JvmProtoBuf.classLocalVariable) - 1) {
hashCode = 31 * hashCode + getExtension(JvmProtoBuf.classLocalVariable, i).hashCode(stringIndexes, fqNameIndexes)
}
return hashCode
}

View File

@@ -19,6 +19,7 @@
package org.jetbrains.kotlin.incremental
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.kotlin.build.GeneratedFile
@@ -41,7 +42,9 @@ import java.util.*
fun Iterable<File>.javaSourceRoots(roots: Iterable<File>): Iterable<File> =
filter(File::isJavaFile).mapNotNull { findSrcDirRoot(it, roots) }
filter(File::isJavaFile)
.map { findSrcDirRoot(it, roots) }
.filterNotNull()
fun makeModuleFile(name: String, isTest: Boolean, outputDir: File, sourcesToCompile: Iterable<File>, javaSourceRoots: Iterable<File>, classpath: Iterable<File>, friendDirs: Iterable<File>): File {
val builder = KotlinModuleXmlBuilder()
@@ -51,7 +54,6 @@ fun makeModuleFile(name: String, isTest: Boolean, outputDir: File, sourcesToComp
sourcesToCompile,
javaSourceRoots.map { JvmSourceRoot(it) },
classpath,
null,
"java-production",
isTest,
// this excludes the output directories from the class path, to be removed for true incremental compilation
@@ -164,13 +166,12 @@ fun<Target> OutputItemsCollectorImpl.generatedFiles(
return outputs.map { outputItem ->
val target =
outputItem.sourceFiles.firstOrNull()?.let { sourceToTarget[it] } ?:
targets.singleOrNull { getOutputDir(it)?.let { outputItem.outputFile.startsWith(it) } ?: false } ?:
targets.filter { getOutputDir(it)?.let { outputItem.outputFile.startsWith(it) } ?: false }.singleOrNull() ?:
representativeTarget
when (outputItem.outputFile.extension) {
"class" -> GeneratedJvmClass(target, outputItem.sourceFiles, outputItem.outputFile)
else -> GeneratedFile(target, outputItem.sourceFiles, outputItem.outputFile)
}
if (outputItem.outputFile.name.endsWith(".class"))
GeneratedJvmClass(target, outputItem.sourceFiles, outputItem.outputFile)
else
GeneratedFile(target, outputItem.sourceFiles, outputItem.outputFile)
}
}

View File

@@ -186,8 +186,7 @@ private class DifferenceCalculatorForClass(oldData: ProtoMapValue, newData: Prot
}
for (kind in diff) {
@Suppress("UNUSED_VARIABLE") // To make this 'when' exhaustive
val unused: Any = when (kind!!) {
when (kind!!) {
ProtoBufClassKind.COMPANION_OBJECT_NAME -> {
if (oldProto.hasCompanionObjectName()) oldProto.companionObjectName.oldToNames()
if (newProto.hasCompanionObjectName()) newProto.companionObjectName.newToNames()
@@ -204,7 +203,10 @@ private class DifferenceCalculatorForClass(oldData: ProtoMapValue, newData: Prot
}
ProtoBufClassKind.CONSTRUCTOR_LIST -> {
val differentNonPrivateConstructors = calcDifferenceForNonPrivateMembers(ProtoBuf.Class::getConstructorList)
isClassAffected = isClassAffected || differentNonPrivateConstructors.isNotEmpty()
if (differentNonPrivateConstructors.isNotEmpty()) {
isClassAffected = true
}
}
ProtoBufClassKind.FUNCTION_LIST ->
names.addAll(calcDifferenceForNonPrivateMembers(ProtoBuf.Class::getFunctionList))
@@ -236,9 +238,6 @@ private class DifferenceCalculatorForClass(oldData: ProtoMapValue, newData: Prot
ProtoBufClassKind.CLASS_MODULE_NAME -> {
// TODO
}
ProtoBufClassKind.CLASS_LOCAL_VARIABLE_LIST -> {
// Not affected, local variables are not accessible outside of a file
}
}
}
@@ -268,8 +267,7 @@ private class DifferenceCalculatorForPackageFacade(oldData: ProtoMapValue, newDa
}
for (kind in diff) {
@Suppress("UNUSED_VARIABLE") // To make this 'when' exhaustive
val unused: Any = when (kind!!) {
when (kind!!) {
ProtoBufPackageKind.FUNCTION_LIST ->
names.addAll(calcDifferenceForNonPrivateMembers(ProtoBuf.Package::getFunctionList))
ProtoBufPackageKind.PROPERTY_LIST ->
@@ -281,9 +279,7 @@ private class DifferenceCalculatorForPackageFacade(oldData: ProtoMapValue, newDa
ProtoBufPackageKind.PACKAGE_MODULE_NAME -> {
// TODO
}
ProtoBufPackageKind.PACKAGE_LOCAL_VARIABLE_LIST -> {
// Not affected, local variables are not accessible outside of a file
}
else -> throw IllegalArgumentException("Unsupported kind: $kind")
}
}

View File

@@ -42,5 +42,5 @@ open class BasicMapsOwner {
maps.forEach { it.flush(memoryCachesOnly) }
}
@TestOnly fun dump(): String = maps.joinToString("\n\n") { it.dump() }
@TestOnly fun dump(): String = maps.map { it.dump() }.joinToString("\n\n")
}

View File

@@ -39,7 +39,6 @@ class KotlinModuleXmlBuilder {
sourceFiles: Iterable<File>,
javaSourceRoots: Iterable<JvmSourceRoot>,
classpathRoots: Iterable<File>,
modularJdkRoot: File?,
targetTypeId: String,
isTests: Boolean,
directoriesToFilterOut: Set<File>,
@@ -65,10 +64,6 @@ class KotlinModuleXmlBuilder {
processJavaSourceRoots(javaSourceRoots)
processClasspath(classpathRoots, directoriesToFilterOut)
if (modularJdkRoot != null) {
p.println("<", MODULAR_JDK_ROOT, " ", PATH, "=\"", getEscapedPath(modularJdkRoot), "\"/>")
}
closeTag(p, MODULE)
return this
}

View File

@@ -17,8 +17,10 @@
package org.jetbrains.kotlin.build
import junit.framework.TestCase
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.config.KotlinCompilerVersion
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.load.kotlin.JvmMetadataVersion
import org.junit.Assert.assertNotEquals
import org.junit.Test
@@ -62,14 +64,14 @@ class JvmBuildMetaInfoTest : TestCase() {
@Test
fun testEquals() {
val args1 = K2JVMCompilerArguments()
args1.coroutinesState = CommonCompilerArguments.ENABLE
args1.coroutinesEnable = true
val info1 = JvmBuildMetaInfo(args1)
val args2 = K2JVMCompilerArguments()
args2.coroutinesState = CommonCompilerArguments.WARN
args2.coroutinesEnable = false
val info2 = JvmBuildMetaInfo(args2)
assertNotEquals(info1, info2)
assertEquals(info1, info2.copy(coroutinesEnable = true, coroutinesWarn = false))
assertEquals(info1, info2.copy(coroutinesEnable = true))
}
}
}

View File

@@ -22202,8 +22202,8 @@ public final class DebugProtoBuf {
* <code>optional int32 flags = 1 [default = 0];</code>
*
* <pre>
*hasAnnotations
*declaresDefault
*hasAnnotations
*isCrossinline
*isNoinline
* </pre>
@@ -22213,8 +22213,8 @@ public final class DebugProtoBuf {
* <code>optional int32 flags = 1 [default = 0];</code>
*
* <pre>
*hasAnnotations
*declaresDefault
*hasAnnotations
*isCrossinline
*isNoinline
* </pre>
@@ -22419,8 +22419,8 @@ public final class DebugProtoBuf {
* <code>optional int32 flags = 1 [default = 0];</code>
*
* <pre>
*hasAnnotations
*declaresDefault
*hasAnnotations
*isCrossinline
*isNoinline
* </pre>
@@ -22432,8 +22432,8 @@ public final class DebugProtoBuf {
* <code>optional int32 flags = 1 [default = 0];</code>
*
* <pre>
*hasAnnotations
*declaresDefault
*hasAnnotations
*isCrossinline
*isNoinline
* </pre>
@@ -22913,8 +22913,8 @@ public final class DebugProtoBuf {
* <code>optional int32 flags = 1 [default = 0];</code>
*
* <pre>
*hasAnnotations
*declaresDefault
*hasAnnotations
*isCrossinline
*isNoinline
* </pre>
@@ -22926,8 +22926,8 @@ public final class DebugProtoBuf {
* <code>optional int32 flags = 1 [default = 0];</code>
*
* <pre>
*hasAnnotations
*declaresDefault
*hasAnnotations
*isCrossinline
*isNoinline
* </pre>
@@ -22939,8 +22939,8 @@ public final class DebugProtoBuf {
* <code>optional int32 flags = 1 [default = 0];</code>
*
* <pre>
*hasAnnotations
*declaresDefault
*hasAnnotations
*isCrossinline
*isNoinline
* </pre>
@@ -22955,8 +22955,8 @@ public final class DebugProtoBuf {
* <code>optional int32 flags = 1 [default = 0];</code>
*
* <pre>
*hasAnnotations
*declaresDefault
*hasAnnotations
*isCrossinline
*isNoinline
* </pre>

View File

@@ -14,9 +14,7 @@ public final class DebugJvmProtoBuf {
registry.add(org.jetbrains.kotlin.serialization.jvm.DebugJvmProtoBuf.isRaw);
registry.add(org.jetbrains.kotlin.serialization.jvm.DebugJvmProtoBuf.typeParameterAnnotation);
registry.add(org.jetbrains.kotlin.serialization.jvm.DebugJvmProtoBuf.classModuleName);
registry.add(org.jetbrains.kotlin.serialization.jvm.DebugJvmProtoBuf.classLocalVariable);
registry.add(org.jetbrains.kotlin.serialization.jvm.DebugJvmProtoBuf.packageModuleName);
registry.add(org.jetbrains.kotlin.serialization.jvm.DebugJvmProtoBuf.packageLocalVariable);
}
public interface StringTableTypesOrBuilder extends
// @@protoc_insertion_point(interface_extends:org.jetbrains.kotlin.serialization.jvm.StringTableTypes)
@@ -4588,17 +4586,6 @@ public final class DebugJvmProtoBuf {
.newFileScopedGeneratedExtension(
java.lang.Integer.class,
null);
public static final int CLASS_LOCAL_VARIABLE_FIELD_NUMBER = 102;
/**
* <code>extend .org.jetbrains.kotlin.serialization.Class { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.serialization.DebugProtoBuf.Class,
java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Property>> classLocalVariable = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.class,
org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.getDefaultInstance());
public static final int PACKAGE_MODULE_NAME_FIELD_NUMBER = 101;
/**
* <code>extend .org.jetbrains.kotlin.serialization.Package { ... }</code>
@@ -4610,17 +4597,6 @@ public final class DebugJvmProtoBuf {
.newFileScopedGeneratedExtension(
java.lang.Integer.class,
null);
public static final int PACKAGE_LOCAL_VARIABLE_FIELD_NUMBER = 102;
/**
* <code>extend .org.jetbrains.kotlin.serialization.Package { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.serialization.DebugProtoBuf.Package,
java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Property>> packageLocalVariable = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.class,
org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.getDefaultInstance());
private static final org.jetbrains.kotlin.protobuf.Descriptors.Descriptor
internal_static_org_jetbrains_kotlin_serialization_jvm_StringTableTypes_descriptor;
private static
@@ -4702,15 +4678,9 @@ public final class DebugJvmProtoBuf {
"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"
"N\n\023package_module_name\022+.org.jetbrains.k" +
"otlin.serialization.Package\030e \001(\005B\004\230\265\030\001B" +
"\022B\020DebugJvmProtoBuf"
};
org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
@@ -4763,9 +4733,7 @@ public final class DebugJvmProtoBuf {
isRaw.internalInit(descriptor.getExtensions().get(4));
typeParameterAnnotation.internalInit(descriptor.getExtensions().get(5));
classModuleName.internalInit(descriptor.getExtensions().get(6));
classLocalVariable.internalInit(descriptor.getExtensions().get(7));
packageModuleName.internalInit(descriptor.getExtensions().get(8));
packageLocalVariable.internalInit(descriptor.getExtensions().get(9));
packageModuleName.internalInit(descriptor.getExtensions().get(7));
org.jetbrains.kotlin.protobuf.ExtensionRegistry registry =
org.jetbrains.kotlin.protobuf.ExtensionRegistry.newInstance();
registry.add(org.jetbrains.kotlin.serialization.DebugExtOptionsProtoBuf.stringIdInTable);

717
build.xml

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,18 @@
# This file is used to override default values used by the Ant build system.
#
# This file must be checked into Version Control Systems, as it is
# integral to the build system of your project.
# This file is only used by the Ant script.
# You can use this to override default values such as
# 'source.dir' for the location of your java source folder and
# 'out.dir' for the location of your output folder.
# You can also use it define how the release builds are signed by declaring
# the following properties:
# 'key.store' for the location of your keystore and
# 'key.alias' for the name of the key to use.
# The password will be asked during the build when you use the 'release' target.
tested.project.dir=tested-module

View File

@@ -64,27 +64,12 @@ android {
dexOptions {
dexInProcess false
javaMaxHeapSize "300m"
javaMaxHeapSize "700m"
//default is 4 and Total Memory = maxProcessCount * javaMaxHeapSize
maxProcessCount 1
additionalParameters "--debug"
maxProcessCount 2
}
}
task jarTestFolders() {
println "Jar folders..."
new File("${projectDir}/libs/").listFiles().each { File file ->
if (file.isDirectory()) {
println "Jar '${file.name}' folder..."
ant.jar(basedir: "libs/${file.name}/", destfile: "libs/" + file.name + ".jar")
}
}
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn jarTestFolders
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile 'junit:junit:4.12'

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="testsForAndroid" default="help" basedir="">
<property file="local.properties"/>
<property file="ant.properties"/>
<loadproperties srcFile="project.properties"/>
<import file="custom_rules.xml" optional="true"/>
<import file="${sdk.dir}/tools/ant/build.xml"/>
<target name="pack_libraries">
<jar basedir="libs/codegen-test-output" destfile="libs/test.jar"/>
<delete dir="libs/codegen-test-output"/>
</target>
</project>

View File

@@ -1,2 +0,0 @@
#don't try to download android specific tools within gradle: licence acceptance will be required
android.builder.sdkDownload=false

View File

@@ -20,6 +20,7 @@ import com.intellij.util.PlatformUtils;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.android.tests.ant.AntRunner;
import org.jetbrains.kotlin.android.tests.download.SDKDownloader;
import org.jetbrains.kotlin.android.tests.emulator.Emulator;
import org.jetbrains.kotlin.android.tests.gradle.GradleRunner;
@@ -82,6 +83,8 @@ public class CodegenTestsOnAndroidRunner {
downloader.unzipAll();
PermissionManager.setPermissions(pathManager);
AntRunner antRunner = new AntRunner(pathManager);
antRunner.packLibraries();
Emulator emulator = new Emulator(pathManager, Emulator.ARM);
GradleRunner gradleRunner = new GradleRunner(pathManager);
gradleRunner.clean();

View File

@@ -52,8 +52,8 @@ public class PathManager {
return getAndroidSdkRoot() + "/build-tools";
}
public String getOutputForCompiledFiles(int index) {
return tmpFolder + "/libs/libtest" + index;
public String getOutputForCompiledFiles() {
return tmpFolder + "/libs/codegen-test-output";
}
public String getLibsFolderInAndroidTestedModuleTmpFolder() {
@@ -84,6 +84,10 @@ public class PathManager {
return getDependenciesRoot() + "/download";
}
public String getAntBinDirectory() {
return rootFolder + "/dependencies/ant-1.8/bin";
}
public String getAndroidModuleRoot() {
return rootFolder + "/compiler/android-tests/android-module";
}

View File

@@ -0,0 +1,105 @@
/*
* 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.ant;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.openapi.util.SystemInfo;
import org.jetbrains.kotlin.android.tests.OutputUtils;
import org.jetbrains.kotlin.android.tests.PathManager;
import org.jetbrains.kotlin.android.tests.run.RunResult;
import org.jetbrains.kotlin.android.tests.run.RunUtils;
import org.jetbrains.kotlin.utils.ExceptionUtilsKt;
import java.util.ArrayList;
import java.util.List;
public class AntRunner {
private final List<String> listOfAntCommands;
public AntRunner(PathManager pathManager) {
listOfAntCommands = new ArrayList<>();
String antCmdName = SystemInfo.isWindows ? "ant.bat" : "ant";
listOfAntCommands.add(pathManager.getAntBinDirectory() + "/" + antCmdName);
listOfAntCommands.add("-Dsdk.dir=" + pathManager.getAndroidSdkRoot());
listOfAntCommands.add("-buildfile");
listOfAntCommands.add(pathManager.getTmpFolder() + "/build.xml");
}
/* Pack compiled sources on first step to one jar file */
public void packLibraries() {
System.out.println("Pack libraries...");
RunResult result = RunUtils.execute(generateCommandLine("pack_libraries"));
OutputUtils.checkResult(result);
}
/* Clean output directory */
public void cleanOutput() {
System.out.println("Clearing output directory...");
RunResult result = RunUtils.execute(generateCommandLine("clean"));
OutputUtils.checkResult(result);
}
public void compileSources() {
System.out.println("Compiling sources...");
RunResult result = RunUtils.execute(generateCommandLine("debug"));
OutputUtils.checkResult(result);
}
public void installApplicationOnEmulator() {
System.out.println("Installing apk...");
RunResult result = RunUtils.execute(generateCommandLine("installt"));
String resultOutput = result.getOutput();
if (!isInstallSuccessful(resultOutput)) {
installApplicationOnEmulator();
return;
}
else {
if (result.getStatus()) {
System.out.println(resultOutput);
}
}
OutputUtils.checkResult(result);
}
public String runTestsOnEmulator() {
System.out.println("Running tests...");
RunResult result = RunUtils.execute(generateCommandLine("test"));
String resultOutput = result.getOutput();
OutputUtils.checkResult(result);
return resultOutput;
}
private static boolean isInstallSuccessful(String output) {
if (output.contains("Is the system running?")) {
System.out.println("Device not ready. Waiting for 20 sec.");
try {
Thread.sleep(20000);
}
catch (InterruptedException e) {
throw ExceptionUtilsKt.rethrow(e);
}
return false;
}
return true;
}
private GeneralCommandLine generateCommandLine(String taskName) {
GeneralCommandLine commandLine = new GeneralCommandLine(listOfAntCommands);
commandLine.addParameter(taskName);
return commandLine;
}
}

View File

@@ -54,7 +54,7 @@ public class SDKDownloader {
platformToolsZipPath = pathManager.getRootForDownload() + "/platform-tools.zip";
skdToolsZipPath = pathManager.getRootForDownload() + "/tools.zip";
buildToolsZipPath = pathManager.getRootForDownload() + "/build-tools.zip";
gradleZipPath = pathManager.getRootForDownload() + "/gradle" + GRADLE_VERSION + ".zip";
gradleZipPath = pathManager.getRootForDownload() + "/gradle.zip";
}
public void downloadPlatform() {

View File

@@ -46,9 +46,7 @@ public class GradleRunner {
public void build() {
System.out.println("Building gradle project...");
GeneralCommandLine build = generateCommandLine("build");
build.addParameter("--stacktrace");
RunResult result = RunUtils.execute(build);
RunResult result = RunUtils.execute(generateCommandLine("build"));
OutputUtils.checkResult(result);
}

View File

@@ -29,6 +29,7 @@ public class PermissionManager {
public static void setPermissions(PathManager pathManager) {
if (!SystemInfo.isWindows) {
RunUtils.execute(generateChmodCmd(pathManager.getAntBinDirectory() + "/ant"));
setExecPermissionForSimpleNamedFiles(new File(pathManager.getToolsFolderInAndroidSdk()));
setExecPermissionForSimpleNamedFiles(new File(pathManager.getToolsFolderInAndroidSdk() + "/bin64"));
setExecPermissionForSimpleNamedFiles(new File(pathManager.getBuildToolsFolderInAndroidSdk() + "/" + SDKDownloader.BUILD_TOOLS));

View File

@@ -55,7 +55,6 @@ public class CodegenTestsOnAndroidGenerator extends KtUsefulTestCase {
private static final String generatorName = "CodegenTestsOnAndroidGenerator";
private static int MODULE_INDEX = 1;
private int WRITED_FILES_COUNT = 0;
private final List<String> generatedTestNames = Lists.newArrayList();
@@ -192,15 +191,10 @@ public class CodegenTestsOnAndroidGenerator extends KtUsefulTestCase {
private void writeFiles(List<KtFile> filesToCompile) {
if (filesToCompile.isEmpty()) return;
//1000 files per folder, each folder would be jared by build.gradle script
// We can't create one big jar with all test cause dex has problem with memory on teamcity
WRITED_FILES_COUNT += filesToCompile.size();
File outputDir = new File(pathManager.getOutputForCompiledFiles(WRITED_FILES_COUNT / 1000));
System.out.println("Generating " + filesToCompile.size() + " files" +
(inheritMultifileParts
? " (JVM.INHERIT_MULTIFILE_PARTS)"
: isFullJdkAndRuntime ? " (full jdk and runtime)" : "") + " into " + outputDir.getName() + "...");
: isFullJdkAndRuntime ? " (full jdk and runtime)" : "") + "...");
OutputFileCollection outputFiles;
try {
outputFiles = GenerationUtils.compileFiles(filesToCompile, environment).getFactory();
@@ -209,6 +203,7 @@ public class CodegenTestsOnAndroidGenerator extends KtUsefulTestCase {
throw new RuntimeException(e);
}
File outputDir = new File(pathManager.getOutputForCompiledFiles());
if (!outputDir.exists()) {
outputDir.mkdirs();
}

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.
@@ -47,7 +47,6 @@ public class SpecialFiles {
excludedFiles.add("arrayOfKClasses.kt");
excludedFiles.add("enumKClassAnnotation.kt");
excludedFiles.add("primitivesAndArrays.kt");
excludedFiles.add("getDelegateWithoutReflection.kt");
// Reflection is used to check full class name
excludedFiles.add("native");
@@ -97,14 +96,6 @@ public class SpecialFiles {
excludedFiles.add("kt11121.kt");
excludedFiles.add("kt5112.kt");
// Different format of inner signature on Android and JVM
excludedFiles.add("signatureOfDeepGenericInner.kt");
excludedFiles.add("signatureOfDeepInner.kt");
excludedFiles.add("signatureOfDeepInnerLastGeneric.kt");
excludedFiles.add("signatureOfGenericInnerGenericOuter.kt");
excludedFiles.add("signatureOfGenericInnerSimpleOuter.kt");
excludedFiles.add("signatureOfSimpleInnerSimpleOuter.kt");
// Some classes are not visible on android
excludedFiles.add("classpath.kt");

View File

@@ -7,6 +7,7 @@
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="intellij-core" level="project" />
<orderEntry type="module" module-name="frontend" />
<orderEntry type="module" module-name="util" />
</component>

View File

@@ -101,11 +101,12 @@ object CodegenUtil {
}
@JvmStatic
fun getSuperClassBySuperTypeListEntry(specifier: KtSuperTypeListEntry, bindingContext: BindingContext): ClassDescriptor? {
fun getSuperClassBySuperTypeListEntry(specifier: KtSuperTypeListEntry, bindingContext: BindingContext): ClassDescriptor {
val superType = bindingContext.get(BindingContext.TYPE, specifier.typeReference!!)
?: error("superType should not be null: ${specifier.text}")
return superType.constructor.declarationDescriptor as? ClassDescriptor
?: error("ClassDescriptor of superType should not be null: ${specifier.text}")
}
@JvmStatic
@@ -158,7 +159,7 @@ object CodegenUtil {
@JvmStatic
fun constructFakeFunctionCall(project: Project, referencedFunction: FunctionDescriptor): KtCallExpression {
val fakeFunctionCall = StringBuilder("callableReferenceFakeCall(")
fakeFunctionCall.append(referencedFunction.valueParameters.joinToString(", ") { "p${it.index}" })
fakeFunctionCall.append(referencedFunction.valueParameters.map { "p${it.index}" }.joinToString(", "))
fakeFunctionCall.append(")")
return KtPsiFactory(project, markGenerated = false).createExpression(fakeFunctionCall.toString()) as KtCallExpression
}

View File

@@ -33,7 +33,7 @@ import org.jetbrains.kotlin.resolve.BindingContextUtils
* TODO: data class with zero components gets no toString/equals/hashCode methods. This is inconsistent and should be
* changed here with the platform backends adopted.
*/
abstract class DataClassMethodGenerator(protected val declaration: KtClassOrObject, private val bindingContext: BindingContext) {
abstract class DataClassMethodGenerator(private val declaration: KtClassOrObject, private val bindingContext: BindingContext) {
protected val classDescriptor: ClassDescriptor = BindingContextUtils.getNotNull(bindingContext, BindingContext.CLASS, declaration)
fun generate() {

View File

@@ -9,8 +9,11 @@
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module" module-name="frontend" />
<orderEntry type="module" module-name="frontend.java" />
<orderEntry type="library" scope="PROVIDED" name="intellij-core" level="project" />
<orderEntry type="module" module-name="serialization" />
<orderEntry type="module" module-name="backend-common" exported="" />
<orderEntry type="module" module-name="util" />
<orderEntry type="module" module-name="backend.jvm" />
<orderEntry type="module" module-name="ir.tree" />
</component>
</module>

View File

@@ -20,6 +20,7 @@ import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.codegen.inline.FileMapping;
import org.jetbrains.kotlin.codegen.inline.InlineCodegenUtil;
import org.jetbrains.kotlin.codegen.inline.SMAPBuilder;
import org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings;
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin;
@@ -28,8 +29,6 @@ import org.jetbrains.org.objectweb.asm.*;
import java.util.ArrayList;
import java.util.List;
import static org.jetbrains.kotlin.codegen.inline.InlineCodegenUtilsKt.GENERATE_SMAP;
public abstract class AbstractClassBuilder implements ClassBuilder {
protected static final MethodVisitor EMPTY_METHOD_VISITOR = new MethodVisitor(Opcodes.ASM5) {};
protected static final FieldVisitor EMPTY_FIELD_VISITOR = new FieldVisitor(Opcodes.ASM5) {};
@@ -106,7 +105,7 @@ public abstract class AbstractClassBuilder implements ClassBuilder {
@Override
public void done() {
if (!fileMappings.isEmpty() && GENERATE_SMAP) {
if (!fileMappings.isEmpty() && InlineCodegenUtil.GENERATE_SMAP) {
FileMapping origin = fileMappings.get(0);
assert sourceName == null || origin.getName().equals(sourceName) : "Error " + origin.getName() + " != " + sourceName;
getVisitor().visitSource(origin.getName(), new SMAPBuilder(origin.getName(), origin.getPath(), fileMappings).build());

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.

View File

@@ -16,7 +16,6 @@
package org.jetbrains.kotlin.codegen;
import kotlin.collections.CollectionsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.codegen.annotation.WrappedAnnotated;
@@ -26,7 +25,6 @@ import org.jetbrains.kotlin.descriptors.annotations.*;
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor;
import org.jetbrains.kotlin.load.java.JvmAnnotationNames;
import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.resolve.AnnotationChecker;
import org.jetbrains.kotlin.resolve.constants.*;
import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt;
@@ -39,8 +37,6 @@ import org.jetbrains.org.objectweb.asm.*;
import java.lang.annotation.*;
import java.util.*;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt.getAnnotationClass;
public abstract class AnnotationCodegen {
public static final class JvmFlagAnnotation {
@@ -71,17 +67,7 @@ public abstract class AnnotationCodegen {
new JvmFlagAnnotation("kotlin.jvm.Synchronized", Opcodes.ACC_SYNCHRONIZED)
);
private static final AnnotationVisitor NO_ANNOTATION_VISITOR = new AnnotationVisitor(Opcodes.ASM5) {
@Override
public AnnotationVisitor visitAnnotation(String name, @NotNull String desc) {
return safe(super.visitAnnotation(name, desc));
}
@Override
public AnnotationVisitor visitArray(String name) {
return safe(super.visitArray(name));
}
};
private static final AnnotationVisitor NO_ANNOTATION_VISITOR = new AnnotationVisitor(Opcodes.ASM5) {};
private final InnerClassConsumer innerClassConsumer;
private final KotlinTypeMapper typeMapper;
@@ -293,27 +279,32 @@ public abstract class AnnotationCodegen {
@Nullable
private String genAnnotation(@NotNull AnnotationDescriptor annotationDescriptor) {
ClassDescriptor classDescriptor = getAnnotationClass(annotationDescriptor);
assert classDescriptor != null : "Annotation descriptor has no class: " + annotationDescriptor;
RetentionPolicy rp = getRetentionPolicy(classDescriptor);
ClassifierDescriptor classifierDescriptor = annotationDescriptor.getType().getConstructor().getDeclarationDescriptor();
assert classifierDescriptor != null : "Annotation descriptor has no class: " + annotationDescriptor;
RetentionPolicy rp = getRetentionPolicy(classifierDescriptor);
if (rp == RetentionPolicy.SOURCE && !typeMapper.getClassBuilderMode().generateSourceRetentionAnnotations) {
return null;
}
innerClassConsumer.addInnerClassInfoFromAnnotation(classDescriptor);
String descriptor = typeMapper.mapType(annotationDescriptor.getType()).getDescriptor();
String asmTypeDescriptor = typeMapper.mapType(annotationDescriptor.getType()).getDescriptor();
AnnotationVisitor annotationVisitor = visitAnnotation(asmTypeDescriptor, rp == RetentionPolicy.RUNTIME);
if (classifierDescriptor instanceof ClassDescriptor) {
innerClassConsumer.addInnerClassInfoFromAnnotation(((ClassDescriptor) classifierDescriptor));
}
AnnotationVisitor annotationVisitor = visitAnnotation(descriptor, rp == RetentionPolicy.RUNTIME);
genAnnotationArguments(annotationDescriptor, annotationVisitor);
annotationVisitor.visitEnd();
return asmTypeDescriptor;
return descriptor;
}
private void genAnnotationArguments(AnnotationDescriptor annotationDescriptor, AnnotationVisitor annotationVisitor) {
for (Map.Entry<Name, ConstantValue<?>> entry : annotationDescriptor.getAllValueArguments().entrySet()) {
genCompileTimeValue(entry.getKey().asString(), entry.getValue(), annotationVisitor);
for (Map.Entry<ValueParameterDescriptor, ConstantValue<?>> entry : annotationDescriptor.getAllValueArguments().entrySet()) {
ValueParameterDescriptor descriptor = entry.getKey();
String name = descriptor.getName().asString();
genCompileTimeValue(name, entry.getValue(), annotationVisitor);
}
}
@@ -472,13 +463,16 @@ public abstract class AnnotationCodegen {
}
AnnotationDescriptor retentionAnnotation = descriptor.getAnnotations().findAnnotation(new FqName(Retention.class.getName()));
if (retentionAnnotation != null) {
ConstantValue<?> compileTimeConstant = CollectionsKt.firstOrNull(retentionAnnotation.getAllValueArguments().values());
if (compileTimeConstant instanceof EnumValue) {
ClassDescriptor enumEntry = ((EnumValue) compileTimeConstant).getValue();
KotlinType classObjectType = DescriptorUtilsKt.getClassValueType(enumEntry);
if (classObjectType != null) {
if ("java/lang/annotation/RetentionPolicy".equals(typeMapper.mapType(classObjectType).getInternalName())) {
return RetentionPolicy.valueOf(enumEntry.getName().asString());
Collection<ConstantValue<?>> valueArguments = retentionAnnotation.getAllValueArguments().values();
if (!valueArguments.isEmpty()) {
ConstantValue<?> compileTimeConstant = valueArguments.iterator().next();
if (compileTimeConstant instanceof EnumValue) {
ClassDescriptor enumEntry = ((EnumValue) compileTimeConstant).getValue();
KotlinType classObjectType = DescriptorUtilsKt.getClassValueType(enumEntry);
if (classObjectType != null) {
if ("java/lang/annotation/RetentionPolicy".equals(typeMapper.mapType(classObjectType).getInternalName())) {
return RetentionPolicy.valueOf(enumEntry.getName().asString());
}
}
}
}

View File

@@ -27,18 +27,15 @@ import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.builtins.PrimitiveType;
import org.jetbrains.kotlin.codegen.binding.CalculatedClosure;
import org.jetbrains.kotlin.codegen.context.CodegenContext;
import org.jetbrains.kotlin.codegen.intrinsics.HashCode;
import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicMethods;
import org.jetbrains.kotlin.codegen.serialization.JvmStringTable;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
import org.jetbrains.kotlin.config.JvmTarget;
import org.jetbrains.kotlin.config.LanguageVersionSettingsImpl;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.lexer.KtTokens;
import org.jetbrains.kotlin.load.java.JavaVisibilities;
import org.jetbrains.kotlin.load.java.JvmAnnotationNames;
import org.jetbrains.kotlin.name.ClassId;
import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.protobuf.MessageLite;
import org.jetbrains.kotlin.renderer.DescriptorRenderer;
@@ -68,7 +65,7 @@ import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isPrimitiveClass;
import static org.jetbrains.kotlin.codegen.CodegenUtilKt.isToArrayFromCollection;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isConstOrHasJvmFieldAnnotation;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isJvmInterface;
import static org.jetbrains.kotlin.descriptors.annotations.AnnotationUtilKt.isEffectivelyInlineOnly;
import static org.jetbrains.kotlin.descriptors.annotations.AnnotationUtilKt.isInlineOnlyOrReifiable;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.*;
import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.*;
import static org.jetbrains.kotlin.types.TypeUtils.isNullableType;
@@ -140,18 +137,10 @@ public class AsmUtil {
return primitiveTypeByBoxedType.get(boxedType);
}
public static boolean isBoxedTypeOf(@NotNull Type boxedType, @NotNull Type unboxedType) {
return unboxPrimitiveTypeOrNull(boxedType) == unboxedType;
}
public static boolean isIntPrimitive(Type type) {
return type == Type.INT_TYPE || type == Type.SHORT_TYPE || type == Type.BYTE_TYPE || type == Type.CHAR_TYPE;
}
public static boolean isIntOrLongPrimitive(Type type) {
return isIntPrimitive(type) || type == Type.LONG_TYPE;
}
public static boolean isNumberPrimitiveOrBoolean(Type type) {
return isNumberPrimitive(type) || type.getSort() == Type.BOOLEAN;
}
@@ -362,7 +351,7 @@ public class AsmUtil {
DeclarationDescriptor containingDeclaration = memberDescriptor.getContainingDeclaration();
Visibility memberVisibility = memberDescriptor.getVisibility();
if (isEffectivelyInlineOnly(memberDescriptor)) return ACC_PRIVATE;
if (isInlineOnlyOrReifiable(memberDescriptor)) return ACC_PRIVATE;
if (memberVisibility == Visibilities.LOCAL && memberDescriptor instanceof CallableMemberDescriptor) {
return ACC_PUBLIC;
@@ -406,10 +395,6 @@ public class AsmUtil {
return null;
}
if (memberDescriptor instanceof FunctionDescriptor && ((FunctionDescriptor) memberDescriptor).isSuspend()) {
return NO_FLAG_PACKAGE_PRIVATE;
}
// the following code is only for PRIVATE visibility of member
if (memberDescriptor instanceof ConstructorDescriptor) {
if (isEnumEntry(containingDeclaration)) {
@@ -523,7 +508,7 @@ public class AsmUtil {
});
}
static void genHashCode(MethodVisitor mv, InstructionAdapter iv, Type type, JvmTarget jvmTarget) {
static void genHashCode(MethodVisitor mv, InstructionAdapter iv, Type type) {
if (type.getSort() == Type.ARRAY) {
Type elementType = correctElementType(type);
if (elementType.getSort() == Type.OBJECT || elementType.getSort() == Type.ARRAY) {
@@ -536,6 +521,16 @@ public class AsmUtil {
else if (type.getSort() == Type.OBJECT) {
iv.invokevirtual("java/lang/Object", "hashCode", "()I", false);
}
else if (type.getSort() == Type.LONG) {
genLongHashCode(mv, iv);
}
else if (type.getSort() == Type.DOUBLE) {
iv.invokestatic("java/lang/Double", "doubleToLongBits", "(D)J", false);
genLongHashCode(mv, iv);
}
else if (type.getSort() == Type.FLOAT) {
iv.invokestatic("java/lang/Float", "floatToIntBits", "(F)I", false);
}
else if (type.getSort() == Type.BOOLEAN) {
Label end = new Label();
iv.dup();
@@ -544,24 +539,8 @@ public class AsmUtil {
iv.iconst(1);
iv.mark(end);
}
else {
if (JvmTarget.JVM_1_6 == jvmTarget) {
if (type.getSort() == Type.LONG) {
genLongHashCode(mv, iv);
}
else if (type.getSort() == Type.DOUBLE) {
iv.invokestatic("java/lang/Double", "doubleToLongBits", "(D)J", false);
genLongHashCode(mv, iv);
}
else if (type.getSort() == Type.FLOAT) {
iv.invokestatic("java/lang/Float", "floatToIntBits", "(F)I", false);
}
else { // byte short char int
// do nothing
}
} else {
HashCode.Companion.invokeHashCode(iv, type);
}
else { // byte short char int
// do nothing
}
}
@@ -663,8 +642,6 @@ public class AsmUtil {
@NotNull FrameMap frameMap
) {
if (state.isParamAssertionsDisabled()) return;
// currently when resuming a suspend function we pass default values instead of real arguments (i.e. nulls for references)
if (descriptor.isSuspend()) return;
// Private method is not accessible from other classes, no assertions needed
if (getVisibilityAccessFlag(descriptor) == ACC_PRIVATE) return;
@@ -717,7 +694,7 @@ public class AsmUtil {
if (innerType.getSort() == Type.OBJECT || innerType.getSort() == Type.ARRAY) {
v.dup();
v.visitLdcInsn(runtimeAssertionInfo.getMessage());
v.invokestatic(IntrinsicMethods.INTRINSICS_CLASS_NAME, "checkExpressionValueIsNotNull",
v.invokestatic("kotlin/jvm/internal/Intrinsics", "checkExpressionValueIsNotNull",
"(Ljava/lang/Object;Ljava/lang/String;)V", false);
}
StackValue.coerce(innerType, type, v);
@@ -807,16 +784,6 @@ public class AsmUtil {
}
}
public static void pop2(@NotNull MethodVisitor v, @NotNull Type type) {
if (type.getSize() == 2) {
v.visitInsn(Opcodes.POP2);
v.visitInsn(Opcodes.POP2);
}
else {
v.visitInsn(Opcodes.POP2);
}
}
public static void dup(@NotNull InstructionAdapter v, @NotNull Type type) {
dup(v, type.getSize());
}
@@ -833,22 +800,6 @@ public class AsmUtil {
}
}
public static void dupx(@NotNull InstructionAdapter v, @NotNull Type type) {
dupx(v, type.getSize());
}
private static void dupx(@NotNull InstructionAdapter v, int size) {
if (size == 2) {
v.dup2X2();
}
else if (size == 1) {
v.dupX1();
}
else {
throw new UnsupportedOperationException();
}
}
public static void dup(@NotNull InstructionAdapter v, @NotNull Type topOfStack, @NotNull Type afterTop) {
if (topOfStack.getSize() == 0 && afterTop.getSize() == 0) {
return;
@@ -904,11 +855,6 @@ public class AsmUtil {
return Type.getObjectType(internalNameByFqNameWithoutInnerClasses(fqName));
}
@NotNull
public static Type asmTypeByClassId(@NotNull ClassId classId) {
return Type.getObjectType(classId.asString().replace('.', '$'));
}
@NotNull
public static String internalNameByFqNameWithoutInnerClasses(@NotNull FqName fqName) {
return JvmClassName.byFqNameWithoutInnerClasses(fqName).getInternalName();

View File

@@ -1,48 +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.codegen
import org.jetbrains.kotlin.codegen.inline.NameGenerator
import org.jetbrains.kotlin.codegen.inline.ReifiedTypeParametersUsages
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
interface BaseExpressionCodegen {
val frameMap: FrameMap
val visitor: InstructionAdapter
val inlineNameGenerator: NameGenerator
val lastLineNumber: Int
fun consumeReifiedOperationMarker(typeParameterDescriptor: TypeParameterDescriptor)
fun propagateChildReifiedTypeParametersUsages(reifiedTypeParametersUsages: ReifiedTypeParametersUsages)
fun pushClosureOnStack(
classDescriptor: ClassDescriptor,
putThis: Boolean,
callGenerator: CallGenerator,
functionReferenceReceiver: StackValue?
)
fun markLineNumberAfterInlineIfNeeded()
}

View File

@@ -1,308 +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.codegen
import com.intellij.psi.tree.IElementType
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.org.objectweb.asm.Label
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
abstract class NumberLikeCompare(
left: StackValue,
right: StackValue,
operandType: Type,
private val opToken: IElementType
) : BranchedValue(left, right, operandType, NumberCompare.getNumberCompareOpcode(opToken)) {
override fun patchOpcode(opcode: Int, v: InstructionAdapter): Int =
NumberCompare.patchOpcode(opcode, v, opToken, operandType)
}
abstract class SafeCallFusedWithPrimitiveEqualityBase(
opToken: IElementType,
operandType: Type,
left: StackValue,
right: StackValue
) : NumberLikeCompare(left, right, operandType, opToken) {
private val trueIfEqual = opToken == KtTokens.EQEQ || opToken == KtTokens.EQEQEQ
protected abstract fun cleanupOnNullReceiver(v: InstructionAdapter)
override fun condJump(jumpLabel: Label, v: InstructionAdapter, jumpIfFalse: Boolean) {
val endLabel = Label()
arg1.put(operandType, v)
arg2!!.put(operandType, v)
v.visitJumpInsn(patchOpcode(if (jumpIfFalse) opcode else negatedOperations[opcode]!!, v), jumpLabel)
v.goTo(endLabel)
cleanupOnNullReceiver(v)
if (jumpIfFalse == trueIfEqual) {
v.goTo(jumpLabel)
}
v.mark(endLabel)
}
override fun putSelector(type: Type, v: InstructionAdapter) {
val falseLabel = Label()
val endLabel = Label()
arg1.put(operandType, v)
arg2!!.put(operandType, v)
v.visitJumpInsn(patchOpcode(opcode, v), falseLabel)
if (!trueIfEqual) {
val trueLabel = Label()
v.goTo(trueLabel)
cleanupOnNullReceiver(v)
v.mark(trueLabel)
}
v.iconst(1)
v.goTo(endLabel)
if (trueIfEqual) {
cleanupOnNullReceiver(v)
}
v.mark(falseLabel)
v.iconst(0)
v.mark(endLabel)
coerceTo(type, v)
}
}
class SafeCallToPrimitiveEquality(
opToken: IElementType,
operandType: Type,
left: StackValue,
right: StackValue,
private val safeReceiverType: Type,
private val safeReceiverIsNull: Label
) : SafeCallFusedWithPrimitiveEqualityBase(opToken, operandType, left, right) {
override fun cleanupOnNullReceiver(v: InstructionAdapter) {
v.mark(safeReceiverIsNull)
AsmUtil.pop(v, safeReceiverType)
}
}
class PrimitiveToSafeCallEquality(
opToken: IElementType,
operandType: Type,
left: StackValue,
right: StackValue,
private val safeReceiverType: Type,
private val safeReceiverIsNull: Label
) : SafeCallFusedWithPrimitiveEqualityBase(opToken, operandType, left, right) {
override fun cleanupOnNullReceiver(v: InstructionAdapter) {
v.mark(safeReceiverIsNull)
AsmUtil.pop(v, safeReceiverType)
AsmUtil.pop(v, arg1.type)
}
}
class BoxedToPrimitiveEquality private constructor(
leftBoxed: StackValue,
rightPrimitive: StackValue,
primitiveType: Type,
private val frameMap: FrameMap
) : NumberLikeCompare(leftBoxed, rightPrimitive, primitiveType, KtTokens.EQEQ) {
private val boxedType = arg1.type
override fun condJump(jumpLabel: Label, v: InstructionAdapter, jumpIfFalse: Boolean) {
if (arg2!!.canHaveSideEffects()) {
val tmp = frameMap.enterTemp(operandType)
doJump(
v, jumpLabel, jumpIfFalse,
{
arg1.put(boxedType, v)
arg2.put(operandType, v)
v.store(tmp, operandType)
},
{ v.load(tmp, operandType) }
)
frameMap.leaveTemp(operandType)
}
else {
doJump(
v, jumpLabel, jumpIfFalse,
{ arg1.put(boxedType, v) },
{ arg2.put(operandType, v) }
)
}
}
private inline fun doJump(
v: InstructionAdapter,
jumpLabel: Label,
jumpIfFalse: Boolean,
putArg1: () -> Unit,
putArg2: () -> Unit
) {
val notNullLabel = Label()
val endLabel = Label()
putArg1()
AsmUtil.dup(v, boxedType)
v.ifnonnull(notNullLabel)
AsmUtil.pop(v, boxedType)
if (jumpIfFalse) v.goTo(jumpLabel) else v.goTo(endLabel)
v.mark(notNullLabel)
coerce(boxedType, operandType, v)
putArg2()
v.visitJumpInsn(patchOpcode(if (jumpIfFalse) opcode else negatedOperations[opcode]!!, v), jumpLabel)
v.mark(endLabel)
}
companion object {
@JvmStatic
fun create(
opToken: IElementType,
left: StackValue,
leftType: Type,
right: StackValue,
rightType: Type,
frameMap: FrameMap
): BranchedValue =
if (!isApplicable(opToken, leftType, rightType))
throw IllegalArgumentException("Not applicable for $opToken, $leftType, $rightType")
else when (opToken) {
KtTokens.EQEQ -> BoxedToPrimitiveEquality(left, right, rightType, frameMap)
KtTokens.EXCLEQ -> Invert(BoxedToPrimitiveEquality(left, right, rightType, frameMap))
else -> throw AssertionError("Unexpected opToken: $opToken")
}
@JvmStatic
fun isApplicable(opToken: IElementType, leftType: Type, rightType: Type) =
(opToken == KtTokens.EQEQ || opToken == KtTokens.EXCLEQ) &&
AsmUtil.isIntOrLongPrimitive(rightType) &&
AsmUtil.isBoxedTypeOf(leftType, rightType)
}
}
abstract class PrimitiveToSomethingEquality
protected constructor(
leftPrimitive: StackValue,
right: StackValue,
primitiveType: Type
) : NumberLikeCompare(leftPrimitive, right, primitiveType, KtTokens.EQEQ) {
protected val primitiveType = leftPrimitive.type
protected val rightType = right.type
override fun condJump(jumpLabel: Label, v: InstructionAdapter, jumpIfFalse: Boolean) {
val notNullLabel = Label()
val endLabel = Label()
arg1.put(primitiveType, v)
arg2!!.put(rightType, v)
AsmUtil.dup(v, rightType)
jumpIfCanCompareTopWithPrimitive(v, notNullLabel)
AsmUtil.pop(v, rightType)
AsmUtil.pop(v, primitiveType)
if (jumpIfFalse) v.goTo(jumpLabel) else v.goTo(endLabel)
v.mark(notNullLabel)
coerceRightToPrimitive(v)
v.visitJumpInsn(patchOpcode(if (jumpIfFalse) opcode else negatedOperations[opcode]!!, v), jumpLabel)
v.mark(endLabel)
}
protected abstract fun jumpIfCanCompareTopWithPrimitive(v: InstructionAdapter, label: Label)
protected abstract fun coerceRightToPrimitive(v: InstructionAdapter)
}
class PrimitiveToBoxedEquality private constructor(
leftPrimitive: StackValue,
rightBoxed: StackValue,
primitiveType: Type
) : PrimitiveToSomethingEquality(leftPrimitive, rightBoxed, primitiveType) {
private val boxedType = rightBoxed.type
override fun jumpIfCanCompareTopWithPrimitive(v: InstructionAdapter, label: Label) {
v.ifnonnull(label)
}
override fun coerceRightToPrimitive(v: InstructionAdapter) {
coerce(boxedType, primitiveType, v)
}
companion object {
@JvmStatic
fun create(opToken: IElementType, left: StackValue, leftType: Type, right: StackValue, rightType: Type): BranchedValue =
if (!isApplicable(opToken, leftType, rightType))
throw IllegalArgumentException("Not applicable for $opToken, $leftType, $rightType")
else when (opToken) {
KtTokens.EQEQ -> PrimitiveToBoxedEquality(left, right, leftType)
KtTokens.EXCLEQ -> Invert(PrimitiveToBoxedEquality(left, right, leftType))
else -> throw AssertionError("Unexpected opToken: $opToken")
}
@JvmStatic
fun isApplicable(opToken: IElementType, leftType: Type, rightType: Type) =
(opToken == KtTokens.EQEQ || opToken == KtTokens.EXCLEQ) &&
AsmUtil.isIntOrLongPrimitive(leftType) &&
AsmUtil.isBoxedTypeOf(rightType, leftType)
}
}
class PrimitiveToObjectEquality private constructor(
leftPrimitive: StackValue,
rightObject: StackValue,
primitiveType: Type
) : PrimitiveToSomethingEquality(leftPrimitive, rightObject, primitiveType) {
private val boxedType = AsmUtil.boxType(primitiveType)
override fun jumpIfCanCompareTopWithPrimitive(v: InstructionAdapter, label: Label) {
v.instanceOf(boxedType)
v.ifne(label)
}
override fun coerceRightToPrimitive(v: InstructionAdapter) {
coerce(rightType, boxedType, v)
coerce(boxedType, primitiveType, v)
}
companion object {
@JvmStatic
fun create(opToken: IElementType, left: StackValue, leftType: Type, right: StackValue, rightType: Type): BranchedValue =
if (!isApplicable(opToken, leftType, rightType))
throw IllegalArgumentException("Not applicable for $opToken, $leftType, $rightType")
else when (opToken) {
KtTokens.EQEQ -> PrimitiveToObjectEquality(left, right, leftType)
KtTokens.EXCLEQ -> Invert(PrimitiveToObjectEquality(left, right, leftType))
else -> throw AssertionError("Unexpected opToken: $opToken")
}
@JvmStatic
fun isApplicable(opToken: IElementType, leftType: Type, rightType: Type) =
(opToken == KtTokens.EQEQ || opToken == KtTokens.EXCLEQ) &&
AsmUtil.isIntOrLongPrimitive(leftType) &&
rightType.sort == Type.OBJECT
}
}

View File

@@ -54,7 +54,9 @@ open class BranchedValue(
condJump(jumpLabel, v, jumpIfFalse)
}
protected open fun patchOpcode(opcode: Int, v: InstructionAdapter): Int = opcode
protected open fun patchOpcode(opcode: Int, v: InstructionAdapter): Int {
return opcode
}
companion object {
val negatedOperations = hashMapOf<Int, Int>()
@@ -118,9 +120,13 @@ open class BranchedValue(
negatedOperations.put(negatedOp, op)
}
fun booleanConstant(value: Boolean): BranchedValue = if (value) TRUE else FALSE
fun booleanConstant(value: Boolean): BranchedValue {
return if (value) TRUE else FALSE
}
fun createInvertValue(argument: StackValue): StackValue = Invert(condJump(argument))
fun createInvertValue(argument: StackValue): StackValue {
return Invert(condJump(argument))
}
fun condJump(condition: StackValue, label: Label, jumpIfFalse: Boolean, iv: InstructionAdapter) {
condJump(condition).condJump(label, iv, jumpIfFalse)
@@ -130,11 +136,14 @@ open class BranchedValue(
condJump(condition).loopJump(label, iv, jumpIfFalse)
}
fun condJump(condition: StackValue): CondJump =
CondJump(
condition as? BranchedValue ?: BranchedValue(condition, null, Type.BOOLEAN_TYPE, IFEQ),
IFEQ
)
fun condJump(condition: StackValue): CondJump {
return CondJump(if (condition is BranchedValue) {
condition
}
else {
BranchedValue(condition, null, Type.BOOLEAN_TYPE, IFEQ)
}, IFEQ)
}
fun cmp(opToken: IElementType, operandType: Type, left: StackValue, right: StackValue): StackValue =
if (operandType.sort == Type.OBJECT)
@@ -194,46 +203,51 @@ class CondJump(val condition: BranchedValue, op: Int) : BranchedValue(condition,
}
class NumberCompare(
private val opToken: IElementType,
val opToken: IElementType,
operandType: Type,
left: StackValue,
right: StackValue
) : BranchedValue(left, right, operandType, NumberCompare.getNumberCompareOpcode(opToken)) {
override fun patchOpcode(opcode: Int, v: InstructionAdapter): Int =
patchOpcode(opcode, v, opToken, operandType)
companion object {
fun getNumberCompareOpcode(opToken: IElementType): Int = when (opToken) {
KtTokens.EQEQ, KtTokens.EQEQEQ -> IFNE
KtTokens.EXCLEQ, KtTokens.EXCLEQEQEQ -> IFEQ
KtTokens.GT -> IFLE
KtTokens.GTEQ -> IFLT
KtTokens.LT -> IFGE
KtTokens.LTEQ -> IFGT
else -> {
throw UnsupportedOperationException("Don't know how to generate this condJump: " + opToken)
}
override fun patchOpcode(opcode: Int, v: InstructionAdapter): Int {
// Opcode takes one int operand from the stack
assert(opcode in IFEQ..IFLE) {
"Opcode for comparing must be in range ${IFEQ..IFLE}, but $opcode was found"
}
fun patchOpcode(opcode: Int, v: InstructionAdapter, opToken: IElementType, operandType: Type): Int {
assert(opcode in IFEQ..IFLE) {
"Opcode for comparing must be in range ${IFEQ..IFLE}, but $opcode was found"
return when (operandType) {
Type.FLOAT_TYPE, Type.DOUBLE_TYPE -> {
if (opToken == KtTokens.GT || opToken == KtTokens.GTEQ) {
v.cmpl(operandType)
}
else {
v.cmpg(operandType)
}
opcode
}
return when (operandType) {
Type.FLOAT_TYPE, Type.DOUBLE_TYPE -> {
if (opToken == KtTokens.GT || opToken == KtTokens.GTEQ)
v.cmpl(operandType)
else
v.cmpg(operandType)
opcode
Type.LONG_TYPE -> {
v.lcmp()
opcode
}
else -> {
opcode + (IF_ICMPEQ - IFEQ)
}
}
}
companion object {
fun getNumberCompareOpcode(opToken: IElementType): Int {
return when (opToken) {
KtTokens.EQEQ, KtTokens.EQEQEQ -> IFNE
KtTokens.EXCLEQ, KtTokens.EXCLEQEQEQ -> IFEQ
KtTokens.GT -> IFLE
KtTokens.GTEQ -> IFLT
KtTokens.LT -> IFGE
KtTokens.LTEQ -> IFGT
else -> {
throw UnsupportedOperationException("Don't know how to generate this condJump: " + opToken)
}
Type.LONG_TYPE -> {
v.lcmp()
opcode
}
else ->
opcode + (IF_ICMPEQ - IFEQ)
}
}
}
@@ -247,11 +261,12 @@ class ObjectCompare(
) : BranchedValue(left, right, operandType, ObjectCompare.getObjectCompareOpcode(opToken)) {
companion object {
fun getObjectCompareOpcode(opToken: IElementType): Int = when (opToken) {
KtTokens.EQEQEQ -> IF_ACMPNE
KtTokens.EXCLEQEQEQ -> IF_ACMPEQ
else -> throw UnsupportedOperationException("don't know how to generate this condjump")
fun getObjectCompareOpcode(opToken: IElementType): Int {
return when (opToken) {
KtTokens.EQEQEQ -> IF_ACMPNE
KtTokens.EXCLEQEQEQ -> IF_ACMPEQ
else -> throw UnsupportedOperationException("don't know how to generate this condjump")
}
}
}
}

View File

@@ -17,18 +17,18 @@
package org.jetbrains.kotlin.codegen;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.descriptors.CallableDescriptor;
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor;
import org.jetbrains.kotlin.psi.KtExpression;
import org.jetbrains.kotlin.psi.ValueArgument;
import org.jetbrains.kotlin.resolve.calls.model.DefaultValueArgument;
import org.jetbrains.kotlin.resolve.calls.model.ExpressionValueArgument;
import org.jetbrains.kotlin.resolve.calls.model.VarargValueArgument;
import org.jetbrains.kotlin.resolve.calls.model.*;
import org.jetbrains.kotlin.types.FlexibleTypesKt;
import org.jetbrains.org.objectweb.asm.Type;
import java.util.List;
import static org.jetbrains.kotlin.codegen.StackValue.createDefaulValue;
import static org.jetbrains.kotlin.codegen.AsmUtil.pushDefaultValueOnStack;
public class CallBasedArgumentGenerator extends ArgumentGenerator {
private final ExpressionCodegen codegen;
@@ -51,6 +51,21 @@ public class CallBasedArgumentGenerator extends ArgumentGenerator {
"Value parameters and their types mismatch in sizes: " + valueParameters.size() + " != " + valueParameterTypes.size();
}
@NotNull
@Override
public DefaultCallArgs generate(
@NotNull List<? extends ResolvedValueArgument> valueArgumentsByIndex,
@NotNull List<? extends ResolvedValueArgument> valueArgs,
@Nullable CallableDescriptor calleeDescriptor
) {
boolean shouldMarkLineNumbers = this.codegen.isShouldMarkLineNumbers();
this.codegen.setShouldMarkLineNumbers(false);
DefaultCallArgs defaultArgs = super.generate(valueArgumentsByIndex, valueArgs, calleeDescriptor);
this.codegen.setShouldMarkLineNumbers(shouldMarkLineNumbers);
return defaultArgs;
}
@Override
protected void generateExpression(int i, @NotNull ExpressionValueArgument argument) {
ValueParameterDescriptor parameter = valueParameters.get(i);
@@ -64,16 +79,19 @@ public class CallBasedArgumentGenerator extends ArgumentGenerator {
@Override
protected void generateDefault(int i, @NotNull DefaultValueArgument argument) {
callGenerator.putValueIfNeeded(valueParameterTypes.get(i), createDefaulValue(valueParameterTypes.get(i)), ValueKind.DEFAULT_PARAMETER, i);
Type type = valueParameterTypes.get(i);
pushDefaultValueOnStack(type, codegen.v);
callGenerator.afterParameterPut(type, null, i);
}
@Override
protected void generateVararg(int i, @NotNull VarargValueArgument argument) {
ValueParameterDescriptor parameter = valueParameters.get(i);
Type type = valueParameterTypes.get(i);
// Upper bound for type of vararg parameter should always have a form of 'Array<out T>',
// while its lower bound may be Nothing-typed after approximation
StackValue lazyVararg = codegen.genVarargs(argument, FlexibleTypesKt.upperIfFlexible(parameter.getType()));
callGenerator.putValueIfNeeded(valueParameterTypes.get(i), lazyVararg, ValueKind.GENERAL_VARARG, i);
codegen.genVarargs(argument, FlexibleTypesKt.upperIfFlexible(parameter.getType()));
callGenerator.afterParameterPut(type, null, i);
}
@Override

View File

@@ -21,19 +21,9 @@ import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.org.objectweb.asm.Type
enum class ValueKind {
GENERAL,
GENERAL_VARARG,
DEFAULT_PARAMETER,
DEFAULT_MASK,
METHOD_HANDLE_IN_DEFAULT,
CAPTURED,
DEFAULT_LAMBDA_CAPTURED_PARAMETER
}
abstract class CallGenerator {
interface CallGenerator {
class DefaultCallGenerator(private val codegen: ExpressionCodegen) : CallGenerator {
internal class DefaultCallGenerator(private val codegen: ExpressionCodegen) : CallGenerator() {
override fun genCallInner(
callableMethod: Callable,
@@ -48,6 +38,13 @@ interface CallGenerator {
}
}
override fun afterParameterPut(
type: Type,
stackValue: StackValue?,
parameterIndex: Int) {
}
override fun processAndPutHiddenParameters(justProcess: Boolean) {
}
@@ -70,7 +67,8 @@ interface CallGenerator {
stackValue.put(stackValue.type, codegen.v)
}
override fun putValueIfNeeded(parameterType: Type, value: StackValue, kind: ValueKind, parameterIndex: Int) {
override fun putValueIfNeeded(
parameterType: Type, value: StackValue) {
value.put(value.type, codegen.v)
}
@@ -106,34 +104,31 @@ interface CallGenerator {
genCallInner(callableMethod, resolvedCall, callDefault, codegen)
}
fun genCallInner(callableMethod: Callable, resolvedCall: ResolvedCall<*>?, callDefault: Boolean, codegen: ExpressionCodegen)
abstract fun genCallInner(callableMethod: Callable, resolvedCall: ResolvedCall<*>?, callDefault: Boolean, codegen: ExpressionCodegen)
fun genValueAndPut(
abstract fun afterParameterPut(
type: Type,
stackValue: StackValue?,
parameterIndex: Int)
abstract fun genValueAndPut(
valueParameterDescriptor: ValueParameterDescriptor,
argumentExpression: KtExpression,
parameterType: Type,
parameterIndex: Int)
fun putValueIfNeeded(
abstract fun putValueIfNeeded(
parameterType: Type,
value: StackValue) {
putValueIfNeeded(parameterType, value, ValueKind.GENERAL)
}
value: StackValue)
fun putValueIfNeeded(
parameterType: Type,
value: StackValue,
kind: ValueKind = ValueKind.GENERAL,
parameterIndex: Int = -1)
fun putCapturedValueOnStack(
abstract fun putCapturedValueOnStack(
stackValue: StackValue,
valueType: Type, paramIndex: Int)
fun processAndPutHiddenParameters(justProcess: Boolean)
abstract fun processAndPutHiddenParameters(justProcess: Boolean)
/*should be called if justProcess = true in processAndPutHiddenParameters*/
fun putHiddenParamsIntoLocals()
abstract fun putHiddenParamsIntoLocals()
fun reorderArgumentsIfNeeded(actualArgsWithDeclIndex: List<ArgumentAndDeclIndex>, valueParameterTypes: List<Type>)
abstract fun reorderArgumentsIfNeeded(actualArgsWithDeclIndex: List<ArgumentAndDeclIndex>, valueParameterTypes: List<Type>)
}

View File

@@ -1,168 +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.codegen;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.codegen.intrinsics.JavaClassProperty;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall;
import org.jetbrains.org.objectweb.asm.Type;
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
public class CallReceiver extends StackValue {
private final StackValue dispatchReceiver;
private final StackValue extensionReceiver;
private final Type secondReceiverType;
private CallReceiver(
@NotNull StackValue dispatchReceiver,
@NotNull StackValue extensionReceiver,
@NotNull Type type,
@Nullable Type secondReceiverType
) {
super(type, dispatchReceiver.canHaveSideEffects() || extensionReceiver.canHaveSideEffects());
this.dispatchReceiver = dispatchReceiver;
this.extensionReceiver = extensionReceiver;
this.secondReceiverType = secondReceiverType;
}
public StackValue withoutReceiverArgument() {
return new CallReceiver(dispatchReceiver, none(), type, secondReceiverType);
}
public static StackValue generateCallReceiver(
@NotNull ResolvedCall<?> resolvedCall,
@NotNull ExpressionCodegen codegen,
@Nullable Callable callableMethod,
@Nullable ReceiverParameterDescriptor dispatchReceiverParameter,
@NotNull StackValue dispatchReceiver,
@Nullable ReceiverParameterDescriptor extensionReceiverParameter,
@NotNull StackValue extensionReceiver
) {
KotlinTypeMapper typeMapper = codegen.typeMapper;
GenerationState state = codegen.getState();
Type type;
Type secondReceiverType = null;
if (extensionReceiverParameter != null) {
type = calcExtensionReceiverType(resolvedCall, extensionReceiverParameter, typeMapper, callableMethod, state);
if (dispatchReceiverParameter != null) {
secondReceiverType = calcDispatchReceiverType(resolvedCall, dispatchReceiverParameter, typeMapper, callableMethod);
}
}
else if (dispatchReceiverParameter != null) {
type = calcDispatchReceiverType(resolvedCall, dispatchReceiverParameter, typeMapper, callableMethod);
}
else if (isLocalFunCall(callableMethod)) {
type = callableMethod.getGenerateCalleeType();
}
else {
type = Type.VOID_TYPE;
}
assert type != null : "Could not map receiver type for " + resolvedCall;
return new CallReceiver(dispatchReceiver, extensionReceiver, type, secondReceiverType);
}
private static Type calcDispatchReceiverType(
@NotNull ResolvedCall<?> resolvedCall,
@Nullable ReceiverParameterDescriptor dispatchReceiver,
@NotNull KotlinTypeMapper typeMapper,
@Nullable Callable callableMethod
) {
if (dispatchReceiver == null) return null;
CallableDescriptor descriptor = resolvedCall.getResultingDescriptor();
if (CodegenUtilKt.isJvmStaticInObjectOrClass(descriptor)) {
return Type.VOID_TYPE;
}
if (callableMethod != null) {
return callableMethod.getDispatchReceiverType();
}
// Extract the receiver from the resolved call, workarounding the fact that ResolvedCall#dispatchReceiver doesn't have
// all the needed information, for example there's no way to find out whether or not a smart cast was applied to the receiver.
DeclarationDescriptor container = descriptor.getContainingDeclaration();
if (container instanceof ClassDescriptor) {
return typeMapper.mapClass((ClassDescriptor) container);
}
return typeMapper.mapType(dispatchReceiver);
}
private static Type calcExtensionReceiverType(
@NotNull ResolvedCall<?> resolvedCall,
@Nullable ReceiverParameterDescriptor extensionReceiver,
@NotNull KotlinTypeMapper typeMapper,
@Nullable Callable callableMethod,
@NotNull GenerationState state
) {
if (extensionReceiver == null) return null;
CallableDescriptor descriptor = resolvedCall.getCandidateDescriptor();
if (descriptor instanceof PropertyDescriptor &&
// hackaround: boxing changes behaviour of T.javaClass intrinsic
state.getIntrinsics().getIntrinsic((PropertyDescriptor) descriptor) != JavaClassProperty.INSTANCE
) {
ReceiverParameterDescriptor receiverCandidate = descriptor.getExtensionReceiverParameter();
assert receiverCandidate != null;
return typeMapper.mapType(receiverCandidate.getType());
}
return callableMethod != null ? callableMethod.getExtensionReceiverType() : typeMapper.mapType(extensionReceiver.getType());
}
@Override
public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
StackValue currentExtensionReceiver = extensionReceiver;
boolean hasExtensionReceiver = extensionReceiver != none();
if (extensionReceiver instanceof SafeCall) {
currentExtensionReceiver.put(currentExtensionReceiver.type, v);
currentExtensionReceiver = StackValue.onStack(currentExtensionReceiver.type);
}
Type dispatchReceiverType = secondReceiverType != null ? secondReceiverType :
hasExtensionReceiver ? dispatchReceiver.type :
type;
dispatchReceiver.put(dispatchReceiverType, v);
currentExtensionReceiver
.moveToTopOfStack(hasExtensionReceiver ? type : currentExtensionReceiver.type, v, dispatchReceiverType.getSize());
}
@Override
public void dup(@NotNull InstructionAdapter v, boolean withReceiver) {
AsmUtil.dup(v, extensionReceiver.type, dispatchReceiver.type);
}
@NotNull
public StackValue getDispatchReceiver() {
return dispatchReceiver;
}
@NotNull
public StackValue getExtensionReceiver() {
return extensionReceiver;
}
}

View File

@@ -45,7 +45,7 @@ interface Callable {
}
}
fun afterReceiverGeneration(v: InstructionAdapter, frameMap: FrameMap) {
fun afterReceiverGeneration(v: InstructionAdapter) {
}
}

View File

@@ -35,13 +35,8 @@ import java.util.List;
import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.enumEntryNeedSubclass;
public abstract class ClassBodyCodegen extends MemberCodegen<KtPureClassOrObject> {
@NotNull
public final KtPureClassOrObject myClass;
@NotNull
public final OwnerKind kind;
@NotNull
public final ClassDescriptor descriptor;
protected ClassBodyCodegen(

View File

@@ -24,17 +24,16 @@ import kotlin.collections.CollectionsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.codegen.binding.CalculatedClosure;
import org.jetbrains.kotlin.codegen.binding.CodegenBinding;
import org.jetbrains.kotlin.codegen.context.ClosureContext;
import org.jetbrains.kotlin.codegen.context.EnclosedValueDescriptor;
import org.jetbrains.kotlin.codegen.coroutines.CoroutineCodegenUtilKt;
import org.jetbrains.kotlin.codegen.inline.InlineCodegenUtil;
import org.jetbrains.kotlin.codegen.serialization.JvmSerializerExtension;
import org.jetbrains.kotlin.codegen.signature.BothSignatureWriter;
import org.jetbrains.kotlin.codegen.signature.JvmSignatureWriter;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor;
import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl;
import org.jetbrains.kotlin.incremental.components.NoLookupLocation;
import org.jetbrains.kotlin.load.java.JvmAbi;
@@ -61,7 +60,6 @@ import java.util.List;
import static org.jetbrains.kotlin.codegen.AsmUtil.*;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isConst;
import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.CLOSURE;
import static org.jetbrains.kotlin.codegen.inline.InlineCodegenUtils2Kt.initDefaultSourceMappingIfNeeded;
import static org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings.METHOD_FOR_FUNCTION;
import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.*;
import static org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin.NO_ORIGIN;
@@ -160,7 +158,7 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
superInterfaceAsmTypes
);
initDefaultSourceMappingIfNeeded(context, this, state);
InlineCodegenUtil.initDefaultSourceMappingIfNeeded(context, this, state);
v.visitSource(element.getContainingFile().getName(), null);
}
@@ -231,10 +229,9 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
@Override
protected void generateKotlinMetadataAnnotation() {
FunctionDescriptor frontendFunDescriptor = CodegenUtilKt.unwrapFrontendVersion(funDescriptor);
FunctionDescriptor freeLambdaDescriptor = createFreeLambdaDescriptor(frontendFunDescriptor);
Method method = v.getSerializationBindings().get(METHOD_FOR_FUNCTION, frontendFunDescriptor);
assert method != null : "No method for " + frontendFunDescriptor;
FunctionDescriptor freeLambdaDescriptor = FakeDescriptorsForReferencesKt.createFreeFakeLambdaDescriptor(frontendFunDescriptor);
v.getSerializationBindings().put(METHOD_FOR_FUNCTION, freeLambdaDescriptor, method);
DescriptorSerializer serializer =
@@ -248,6 +245,30 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
});
}
/**
* Given a function descriptor, creates another function descriptor with type parameters copied from outer context(s).
* This is needed because once we're serializing this to a proto, there's no place to store information about external type parameters.
*/
@NotNull
private static FunctionDescriptor createFreeLambdaDescriptor(@NotNull FunctionDescriptor descriptor) {
FunctionDescriptor.CopyBuilder<? extends FunctionDescriptor> builder = descriptor.newCopyBuilder();
List<TypeParameterDescriptor> typeParameters = new ArrayList<>(0);
builder.setTypeParameters(typeParameters);
DeclarationDescriptor container = descriptor.getContainingDeclaration();
while (container != null) {
if (container instanceof ClassDescriptor) {
typeParameters.addAll(((ClassDescriptor) container).getDeclaredTypeParameters());
}
else if (container instanceof CallableDescriptor && !(container instanceof ConstructorDescriptor)) {
typeParameters.addAll(((CallableDescriptor) container).getTypeParameters());
}
container = container.getContainingDeclaration();
}
return typeParameters.isEmpty() ? descriptor : builder.build();
}
@Override
protected void done() {
writeOuterClassAndEnclosingMethod();
@@ -360,30 +381,13 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
@NotNull GenerationState state
) {
DeclarationDescriptor container = descriptor.getContainingDeclaration();
if (container instanceof ClassDescriptor) {
// TODO: getDefaultType() here is wrong and won't work for arrays
putJavaLangClassInstance(iv, state.getTypeMapper().mapType(((ClassDescriptor) container).getDefaultType()));
wrapJavaClassIntoKClass(iv);
}
else if (container instanceof PackageFragmentDescriptor) {
iv.aconst(state.getTypeMapper().mapOwner(descriptor));
}
else if (descriptor instanceof VariableDescriptorWithAccessors) {
iv.aconst(state.getBindingContext().get(
CodegenBinding.DELEGATED_PROPERTY_METADATA_OWNER, ((VariableDescriptorWithAccessors) descriptor)
));
}
else {
iv.aconst(null);
return;
}
boolean isContainerPackage =
descriptor instanceof LocalVariableDescriptor
? DescriptorUtils.getParentOfType(descriptor, ClassDescriptor.class) == null
: container instanceof PackageFragmentDescriptor;
if (isContainerPackage) {
// Note that this name is not used in reflection. There should be the name of the referenced declaration's module instead,
// but there's no nice API to obtain that name here yet
// TODO: write the referenced declaration's module name and use it in reflection
@@ -392,7 +396,7 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
Type.getMethodDescriptor(K_DECLARATION_CONTAINER_TYPE, getType(Class.class), getType(String.class)), false);
}
else {
wrapJavaClassIntoKClass(iv);
iv.aconst(null);
}
}

View File

@@ -36,7 +36,7 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.descriptorUtil.getAllSuperclassesWithoutAny
import org.jetbrains.kotlin.resolve.descriptorUtil.overriddenTreeUniqueAsSequence
import org.jetbrains.kotlin.resolve.jvm.diagnostics.CollectionStub
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodGenericSignature
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
@@ -337,7 +337,7 @@ class CollectionStubMethodGenerator(
val access = ACC_PUBLIC or (if (synthetic) ACC_SYNTHETIC else 0)
val asmMethod = signature.asmMethod
val genericSignature = if (synthetic) null else signature.genericsSignature
val mv = v.newMethod(CollectionStub, access, asmMethod.name, asmMethod.descriptor, genericSignature, null)
val mv = v.newMethod(JvmDeclarationOrigin.NO_ORIGIN, access, asmMethod.name, asmMethod.descriptor, genericSignature, null)
mv.visitCode()
AsmUtil.genThrow(
InstructionAdapter(mv),
@@ -351,7 +351,7 @@ private val READ_ONLY_ARE_EQUAL_TO_MUTABLE_TYPE_CHECKER = KotlinTypeCheckerImpl.
val firstClass = x.declarationDescriptor as? ClassDescriptor ?: return@withAxioms x == y
val secondClass = y.declarationDescriptor as? ClassDescriptor ?: return@withAxioms x == y
val j2k = JavaToKotlinClassMap
val j2k = JavaToKotlinClassMap.INSTANCE
val firstReadOnly = if (j2k.isMutable(firstClass)) j2k.convertMutableToReadOnly(firstClass) else firstClass
val secondReadOnly = if (j2k.isMutable(secondClass)) j2k.convertMutableToReadOnly(secondClass) else secondClass
firstReadOnly.typeConstructor == secondReadOnly.typeConstructor

View File

@@ -18,6 +18,7 @@ package org.jetbrains.kotlin.codegen
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
import java.util.*
class DefaultCallArgs(val size: Int) {
@@ -55,11 +56,24 @@ class DefaultCallArgs(val size: Int) {
val toInts = toInts()
if (!toInts.isEmpty()) {
for (mask in toInts) {
callGenerator.putValueIfNeeded(Type.INT_TYPE, StackValue.constant(mask, Type.INT_TYPE), ValueKind.DEFAULT_MASK)
callGenerator.putValueIfNeeded(Type.INT_TYPE, StackValue.constant(mask, Type.INT_TYPE))
}
val parameterType = if (isConstructor) AsmTypes.DEFAULT_CONSTRUCTOR_MARKER else AsmTypes.OBJECT_TYPE
callGenerator.putValueIfNeeded(parameterType, StackValue.constant(null, parameterType), ValueKind.METHOD_HANDLE_IN_DEFAULT)
callGenerator.putValueIfNeeded(parameterType, StackValue.constant(null, parameterType))
}
return toInts.isNotEmpty()
}
fun generateOnStackIfNeeded(iv: InstructionAdapter, isConstructor: Boolean): Boolean {
val toInts = toInts()
if (!toInts.isEmpty()) {
for (mask in toInts) {
iv.iconst(mask)
}
val parameterType = if (isConstructor) AsmTypes.DEFAULT_CONSTRUCTOR_MARKER else AsmTypes.OBJECT_TYPE
iv.aconst(null)
}
return toInts.isNotEmpty()
}

View File

@@ -27,7 +27,6 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.hasDefaultValue
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.resolve.jvm.annotations.findJvmOverloadsAnnotation
import org.jetbrains.kotlin.resolve.jvm.diagnostics.OtherOrigin
import org.jetbrains.kotlin.resolve.jvm.diagnostics.OtherOriginFromPure
import org.jetbrains.org.objectweb.asm.Label
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.Type
@@ -137,7 +136,7 @@ class DefaultParameterValueSubstitutor(val state: GenerationState) {
(if (functionDescriptor.modality == Modality.FINAL && functionDescriptor !is ConstructorDescriptor) Opcodes.ACC_FINAL else 0) or
(if (remainingParameters.lastOrNull()?.varargElementType != null) Opcodes.ACC_VARARGS else 0)
val signature = typeMapper.mapSignatureWithCustomParameters(functionDescriptor, contextKind, remainingParameters, false)
val mv = classBuilder.newMethod(OtherOriginFromPure(methodElement, functionDescriptor), flags,
val mv = classBuilder.newMethod(OtherOrigin(methodElement, functionDescriptor), flags,
signature.asmMethod.name,
signature.asmMethod.descriptor,
signature.genericsSignature,

View File

@@ -81,9 +81,8 @@ import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isAnnotationOrJvmInter
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;
import static org.jetbrains.kotlin.descriptors.ModalityKt.isOverridable;
import static org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget.*;
import static org.jetbrains.kotlin.descriptors.annotations.AnnotationUtilKt.isEffectivelyInlineOnly;
import static org.jetbrains.kotlin.descriptors.annotations.AnnotationUtilKt.isInlineOnlyOrReifiable;
import static org.jetbrains.kotlin.resolve.DescriptorToSourceUtils.getSourceFromDescriptor;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.*;
import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.OBJECT_TYPE;
@@ -132,12 +131,11 @@ public class FunctionCodegen {
if (owner.getContextKind() != OwnerKind.DEFAULT_IMPLS || function.hasBody()) {
FunctionGenerationStrategy strategy;
if (functionDescriptor.isSuspend() && !functionDescriptor.isInline()) {
if (functionDescriptor.isSuspend()) {
strategy = new SuspendFunctionGenerationStrategy(
state,
CoroutineCodegenUtilKt.<FunctionDescriptor>unwrapInitialDescriptorForSuspendFunction(functionDescriptor),
function,
v.getThisName()
function
);
}
else {
@@ -189,8 +187,7 @@ public class FunctionCodegen {
return;
}
boolean hasSpecialBridge = hasSpecialBridgeMethod(functionDescriptor);
JvmMethodGenericSignature jvmSignature = typeMapper.mapSignatureWithGeneric(functionDescriptor, contextKind, hasSpecialBridge);
JvmMethodGenericSignature jvmSignature = typeMapper.mapSignatureWithGeneric(functionDescriptor, contextKind);
Method asmMethod = jvmSignature.getAsmMethod();
int flags = getMethodAsmFlags(functionDescriptor, contextKind, state);
@@ -203,66 +200,12 @@ public class FunctionCodegen {
// Native methods are only defined in facades and do not need package part implementations
return;
}
boolean isOpenSuspendInClass =
functionDescriptor.isSuspend() &&
functionDescriptor.getModality() != Modality.ABSTRACT && isOverridable(functionDescriptor) &&
!isInterface(functionDescriptor.getContainingDeclaration()) &&
origin.getOriginKind() != JvmDeclarationOriginKind.CLASS_MEMBER_DELEGATION_TO_DEFAULT_IMPL;
if (isOpenSuspendInClass) {
MethodVisitor mv =
v.newMethod(origin,
flags,
asmMethod.getName(),
asmMethod.getDescriptor(),
jvmSignature.getGenericsSignature(),
getThrownExceptions(functionDescriptor, typeMapper)
);
mv.visitCode();
mv.visitVarInsn(Opcodes.ALOAD, 0);
int index = 1;
for (Type type : asmMethod.getArgumentTypes()) {
mv.visitVarInsn(type.getOpcode(Opcodes.ILOAD), index);
index += type.getSize();
}
asmMethod = CoroutineCodegenUtilKt.getImplForOpenMethod(asmMethod, v.getThisName());
// remove generic signature as it's unnecessary for synthetic methods
jvmSignature =
new JvmMethodGenericSignature(
asmMethod,
jvmSignature.getValueParameters(),
null
);
mv.visitMethodInsn(
Opcodes.INVOKESTATIC,
v.getThisName(), asmMethod.getName(), asmMethod.getDescriptor(),
false
);
mv.visitInsn(Opcodes.ARETURN);
mv.visitEnd();
flags |= Opcodes.ACC_STATIC | Opcodes.ACC_SYNTHETIC;
flags &= ~getVisibilityAccessFlag(functionDescriptor);
flags |= AsmUtil.NO_FLAG_PACKAGE_PRIVATE;
}
MethodVisitor mv =
strategy.wrapMethodVisitor(
v.newMethod(origin,
flags,
asmMethod.getName(),
asmMethod.getDescriptor(),
jvmSignature.getGenericsSignature(),
getThrownExceptions(functionDescriptor, typeMapper)
),
flags, asmMethod.getName(),
asmMethod.getDescriptor()
);
MethodVisitor mv = v.newMethod(origin,
flags,
asmMethod.getName(),
asmMethod.getDescriptor(),
jvmSignature.getGenericsSignature(),
getThrownExceptions(functionDescriptor, typeMapper));
if (CodegenContextUtil.isImplClassOwner(owner)) {
v.getSerializationBindings().put(METHOD_FOR_FUNCTION, CodegenUtilKt.unwrapFrontendVersion(functionDescriptor), asmMethod);
@@ -804,13 +747,6 @@ public class FunctionCodegen {
return bytecode;
}
private boolean hasSpecialBridgeMethod(@NotNull FunctionDescriptor descriptor) {
if (SpecialBuiltinMembers.getOverriddenBuiltinReflectingJvmDescriptor(descriptor) == null) return false;
return !BuiltinSpecialBridgesUtil.generateBridgesForBuiltinSpecial(
descriptor, typeMapper::mapAsmMethod, IS_PURE_INTERFACE_CHECKER
).isEmpty();
}
public void generateBridges(@NotNull FunctionDescriptor descriptor) {
if (descriptor instanceof ConstructorDescriptor) return;
if (owner.getContextKind() == OwnerKind.DEFAULT_IMPLS) return;
@@ -856,7 +792,7 @@ public class FunctionCodegen {
if (!isThereOverriddenInKotlinClass(descriptor)) {
Method method = typeMapper.mapAsmMethod(descriptor);
int flags = ACC_ABSTRACT | getVisibilityAccessFlag(descriptor);
v.newMethod(JvmDeclarationOriginKt.AugmentedBuiltInApi(overridden), flags, method.getName(), method.getDescriptor(), null, null);
v.newMethod(JvmDeclarationOriginKt.OtherOrigin(overridden), flags, method.getName(), method.getDescriptor(), null, null);
}
}
}
@@ -932,7 +868,7 @@ public class FunctionCodegen {
// $default methods are never private to be accessible from other class files (e.g. inner) without the need of synthetic accessors
// $default methods are never protected to be accessible from subclass nested classes
int visibilityFlag = Visibilities.isPrivate(functionDescriptor.getVisibility()) ||
isEffectivelyInlineOnly(functionDescriptor) ?
isInlineOnlyOrReifiable(functionDescriptor) ?
AsmUtil.NO_FLAG_PACKAGE_PRIVATE : Opcodes.ACC_PUBLIC;
int flags = visibilityFlag | getDeprecatedAccessFlag(functionDescriptor) | ACC_SYNTHETIC;
if (!(functionDescriptor instanceof ConstructorDescriptor)) {
@@ -1002,19 +938,12 @@ public class FunctionCodegen {
capturedArgumentsCount++;
}
int maskIndex = 0;
List<ValueParameterDescriptor> valueParameters = functionDescriptor.getValueParameters();
assert valueParameters.size() > 0 : "Expecting value parameters to generate default function " + functionDescriptor;
int firstMaskIndex = frameMap.enterTemp(Type.INT_TYPE);
for (int index = 1; index < valueParameters.size(); index++) {
if (index % Integer.SIZE == 0) {
frameMap.enterTemp(Type.INT_TYPE);
}
}
//default handler or constructor marker
frameMap.enterTemp(AsmTypes.OBJECT_TYPE);
for (int index = 0; index < valueParameters.size(); index++) {
int maskIndex = firstMaskIndex + index / Integer.SIZE;
if (index % Integer.SIZE == 0) {
maskIndex = frameMap.enterTemp(Type.INT_TYPE);
}
ValueParameterDescriptor parameterDescriptor = valueParameters.get(index);
Type type = mappedParameters.get(capturedArgumentsCount + index).getAsmType();
@@ -1148,12 +1077,8 @@ public class FunctionCodegen {
boolean isSpecialOrDelegationToSuper = isSpecialBridge || isStubDeclarationWithDelegationToSuper;
int flags = ACC_PUBLIC | ACC_BRIDGE | (!isSpecialOrDelegationToSuper ? ACC_SYNTHETIC : 0) | (isSpecialBridge ? ACC_FINAL : 0); // TODO.
String bridgeSignature =
isSpecialBridge ? typeMapper.mapSignatureWithGeneric(descriptor, OwnerKind.IMPLEMENTATION).getGenericsSignature()
: null;
MethodVisitor mv = v.newMethod(JvmDeclarationOriginKt.Bridge(descriptor, origin), flags,
bridge.getName(), bridge.getDescriptor(), bridgeSignature, null);
MethodVisitor mv =
v.newMethod(JvmDeclarationOriginKt.Bridge(descriptor, origin), flags, bridge.getName(), bridge.getDescriptor(), null, null);
if (!state.getClassBuilderMode().generateBodies) return;
mv.visitCode();

View File

@@ -19,6 +19,7 @@ package org.jetbrains.kotlin.codegen;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.codegen.context.MethodContext;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.descriptors.CallableDescriptor;
import org.jetbrains.kotlin.psi.KtDeclarationWithBody;
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature;
import org.jetbrains.org.objectweb.asm.MethodVisitor;
@@ -32,10 +33,6 @@ public abstract class FunctionGenerationStrategy {
@NotNull MemberCodegen<?> parentCodegen
);
public MethodVisitor wrapMethodVisitor(@NotNull MethodVisitor mv, int access, @NotNull String name, @NotNull String desc) {
return mv;
}
public static class FunctionDefault extends CodegenBased {
private final KtDeclarationWithBody declaration;

View File

@@ -31,22 +31,18 @@ import org.jetbrains.kotlin.codegen.binding.CodegenBinding;
import org.jetbrains.kotlin.codegen.binding.MutableClosure;
import org.jetbrains.kotlin.codegen.context.*;
import org.jetbrains.kotlin.codegen.extensions.ExpressionCodegenExtension;
import org.jetbrains.kotlin.codegen.inline.InlineCodegenUtil;
import org.jetbrains.kotlin.codegen.signature.BothSignatureWriter;
import org.jetbrains.kotlin.codegen.signature.JvmSignatureWriter;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
import org.jetbrains.kotlin.config.LanguageFeature;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.incremental.components.NoLookupLocation;
import org.jetbrains.kotlin.lexer.KtTokens;
import org.jetbrains.kotlin.load.java.JvmAbi;
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor;
import org.jetbrains.kotlin.load.kotlin.TypeMappingMode;
import org.jetbrains.kotlin.name.ClassId;
import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.platform.JavaToKotlinClassMap;
import org.jetbrains.kotlin.platform.JavaToKotlinClassMap.PlatformMutabilityMapping;
import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.DelegationResolver;
@@ -65,18 +61,21 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.ExtensionReceiver;
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver;
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.org.objectweb.asm.*;
import org.jetbrains.org.objectweb.asm.FieldVisitor;
import org.jetbrains.org.objectweb.asm.Label;
import org.jetbrains.org.objectweb.asm.MethodVisitor;
import org.jetbrains.org.objectweb.asm.Type;
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
import org.jetbrains.org.objectweb.asm.commons.Method;
import java.util.*;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.FQ_NAMES;
import static org.jetbrains.kotlin.codegen.AsmUtil.*;
import static org.jetbrains.kotlin.codegen.CodegenUtilKt.isGenericToArray;
import static org.jetbrains.kotlin.codegen.CodegenUtilKt.isNonGenericToArray;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.*;
import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.enumEntryNeedSubclass;
import static org.jetbrains.kotlin.codegen.inline.InlineCodegenUtils2Kt.initDefaultSourceMappingIfNeeded;
import static org.jetbrains.kotlin.resolve.BindingContextUtils.getDelegationConstructorCall;
import static org.jetbrains.kotlin.resolve.BindingContextUtils.getNotNull;
import static org.jetbrains.kotlin.resolve.DescriptorToSourceUtils.descriptorToDeclaration;
@@ -84,7 +83,6 @@ import static org.jetbrains.kotlin.resolve.DescriptorUtils.*;
import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.JAVA_STRING_TYPE;
import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.OBJECT_TYPE;
import static org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin.NO_ORIGIN;
import static org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKind.CLASS_MEMBER_DELEGATION_TO_DEFAULT_IMPL;
import static org.jetbrains.kotlin.types.Variance.INVARIANT;
import static org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils.isLocalFunction;
import static org.jetbrains.org.objectweb.asm.Opcodes.*;
@@ -215,7 +213,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
v.visitSource(myClass.getContainingKtFile().getName(), null);
initDefaultSourceMappingIfNeeded(context, this, state);
InlineCodegenUtil.initDefaultSourceMappingIfNeeded(context, this, state);
writeEnclosingMethod();
@@ -257,21 +255,24 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
private static final Map<FqName, String> KOTLIN_MARKER_INTERFACES = new HashMap<>();
static {
for (PlatformMutabilityMapping platformMutabilityMapping : JavaToKotlinClassMap.INSTANCE.getMutabilityMappings()) {
KOTLIN_MARKER_INTERFACES.put(
platformMutabilityMapping.getKotlinReadOnly().asSingleFqName(),
"kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.iterator, "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.iterable, "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.collection, "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.list, "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.listIterator, "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.set, "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.map, "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.mapEntry, "kotlin/jvm/internal/markers/KMappedMarker");
ClassId mutableClassId = platformMutabilityMapping.getKotlinMutable();
KOTLIN_MARKER_INTERFACES.put(
mutableClassId.asSingleFqName(),
"kotlin/jvm/internal/markers/K" + mutableClassId.getRelativeClassName().asString()
.replace("MutableEntry", "Entry") // kotlin.jvm.internal.markers.KMutableMap.Entry for some reason
.replace(".", "$")
);
}
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.mutableIterator, "kotlin/jvm/internal/markers/KMutableIterator");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.mutableIterable, "kotlin/jvm/internal/markers/KMutableIterable");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.mutableCollection, "kotlin/jvm/internal/markers/KMutableCollection");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.mutableList, "kotlin/jvm/internal/markers/KMutableList");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.mutableListIterator, "kotlin/jvm/internal/markers/KMutableListIterator");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.mutableSet, "kotlin/jvm/internal/markers/KMutableSet");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.mutableMap, "kotlin/jvm/internal/markers/KMutableMap");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.mutableMapEntry, "kotlin/jvm/internal/markers/KMutableMap$Entry");
}
@NotNull
@@ -305,24 +306,15 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
for (KotlinType supertype : descriptor.getTypeConstructor().getSupertypes()) {
if (isJvmInterface(supertype.getConstructor().getDeclarationDescriptor())) {
FqName kotlinInterfaceName = DescriptorUtils.getFqName(supertype.getConstructor().getDeclarationDescriptor()).toSafe();
sw.writeInterface();
Type jvmInterfaceType = typeMapper.mapSupertype(supertype, sw);
sw.writeInterfaceEnd();
String jvmInterfaceInternalName = jvmInterfaceType.getInternalName();
superInterfaces.add(jvmInterfaceInternalName);
FqName kotlinInterfaceName = DescriptorUtils.getFqName(supertype.getConstructor().getDeclarationDescriptor()).toSafe();
String kotlinMarkerInterfaceInternalName = KOTLIN_MARKER_INTERFACES.get(kotlinInterfaceName);
if (kotlinMarkerInterfaceInternalName != null) {
if (typeMapper.getClassBuilderMode() == ClassBuilderMode.LIGHT_CLASSES) {
sw.writeInterface();
Type kotlinCollectionType = typeMapper.mapType(supertype, sw, TypeMappingMode.SUPER_TYPE_KOTLIN_COLLECTIONS_AS_IS);
sw.writeInterfaceEnd();
superInterfaces.add(kotlinCollectionType.getInternalName());
}
kotlinMarkerInterfaces.add(kotlinMarkerInterfaceInternalName);
}
}
@@ -346,12 +338,9 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
@Override
protected void generateSyntheticPartsBeforeBody() {
protected void generateSyntheticParts() {
generatePropertyMetadataArrayFieldIfNeeded(classAsmType);
}
@Override
protected void generateSyntheticPartsAfterBody() {
generateFieldForSingleton();
generateCompanionObjectBackingFieldCopies();
@@ -368,18 +357,13 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
generateFunctionsForDataClasses();
if (state.getClassBuilderMode() != ClassBuilderMode.LIGHT_CLASSES) {
new CollectionStubMethodGenerator(typeMapper, descriptor).generate(functionCodegen, v);
generateToArray();
}
new CollectionStubMethodGenerator(typeMapper, descriptor).generate(functionCodegen, v);
generateToArray();
if (context.closure != null)
genClosureFields(context.closure, v, typeMapper);
if (state.getClassBuilderMode() == ClassBuilderMode.LIGHT_CLASSES) return;
for (ExpressionCodegenExtension extension : ExpressionCodegenExtension.Companion.getInstances(state.getProject())) {
extension.generateClassSyntheticParts(this);
}
@@ -574,7 +558,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
iv.ifnull(ifNull);
}
genHashCode(mv, iv, asmType, state.getTarget());
genHashCode(mv, iv, asmType);
if (ifNull != null) {
Label end = new Label();
@@ -679,7 +663,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
) {
Type thisDescriptorType = typeMapper.mapType(descriptor);
functionCodegen.generateMethod(JvmDeclarationOriginKt.OtherOriginFromPure(myClass, function), function, new FunctionGenerationStrategy() {
functionCodegen.generateMethod(JvmDeclarationOriginKt.OtherOrigin(myClass, function), function, new FunctionGenerationStrategy() {
@Override
public void generateBody(
@NotNull MethodVisitor mv,
@@ -779,7 +763,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
FunctionDescriptor valuesFunction =
CollectionsKt.single(descriptor.getStaticScope().getContributedFunctions(ENUM_VALUES, NoLookupLocation.FROM_BACKEND));
MethodVisitor mv = v.newMethod(
JvmDeclarationOriginKt.OtherOriginFromPure(myClass, valuesFunction), ACC_PUBLIC | ACC_STATIC, ENUM_VALUES.asString(),
JvmDeclarationOriginKt.OtherOrigin(myClass, valuesFunction), ACC_PUBLIC | ACC_STATIC, ENUM_VALUES.asString(),
"()" + type.getDescriptor(), null, null
);
if (!state.getClassBuilderMode().generateBodies) return;
@@ -797,7 +781,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
CollectionsKt.single(descriptor.getStaticScope().getContributedFunctions(ENUM_VALUE_OF, NoLookupLocation.FROM_BACKEND),
DescriptorUtilsKt::isEnumValueOfMethod);
MethodVisitor mv =
v.newMethod(JvmDeclarationOriginKt.OtherOriginFromPure(myClass, valueOfFunction), ACC_PUBLIC | ACC_STATIC, ENUM_VALUE_OF.asString(),
v.newMethod(JvmDeclarationOriginKt.OtherOrigin(myClass, valueOfFunction), ACC_PUBLIC | ACC_STATIC, ENUM_VALUE_OF.asString(),
"(Ljava/lang/String;)" + classAsmType.getDescriptor(), null, null);
if (!state.getClassBuilderMode().generateBodies) return;
@@ -815,7 +799,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
if (isNonCompanionObject(descriptor)) {
StackValue.Field field = StackValue.singletonViaInstance(descriptor, typeMapper);
v.newField(JvmDeclarationOriginKt.OtherOriginFromPure(myClass),
v.newField(JvmDeclarationOriginKt.OtherOrigin(myClass),
ACC_PUBLIC | ACC_STATIC | ACC_FINAL,
field.name, field.type.getDescriptor(), null, null);
@@ -836,21 +820,9 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
@Nullable KtObjectDeclaration companionObject = CollectionsKt.firstOrNull(myClass.getCompanionObjects());
int properFieldVisibilityFlag = getVisibilityAccessFlag(companionObjectDescriptor);
boolean fieldShouldBeDeprecated =
state.getLanguageVersionSettings().supportsFeature(LanguageFeature.DeprecatedFieldForInvisibleCompanionObject) &&
(properFieldVisibilityFlag & (ACC_PRIVATE | ACC_PROTECTED)) != 0;
// TODO generate field with proper visibility in language version 1.3
int fieldAccessFlags = ACC_PUBLIC | ACC_STATIC | ACC_FINAL;
if (fieldShouldBeDeprecated) {
fieldAccessFlags |= ACC_DEPRECATED;
}
StackValue.Field field = StackValue.singleton(companionObjectDescriptor, typeMapper);
FieldVisitor fv = v.newField(JvmDeclarationOriginKt.OtherOrigin(companionObject == null ? myClass.getPsiOrParent() : companionObject),
fieldAccessFlags, field.name, field.type.getDescriptor(), null, null);
if (fieldShouldBeDeprecated) {
AnnotationCodegen.forField(fv, this, typeMapper).visitAnnotation("Ljava/lang/Deprecated;", true).visitEnd();
}
v.newField(JvmDeclarationOriginKt.OtherOrigin(companionObject == null ? myClass.getPsiOrParent() : companionObject),
ACC_PUBLIC | ACC_STATIC | ACC_FINAL, field.name, field.type.getDescriptor(), null, null);
}
private void generateCompanionObjectBackingFieldCopies() {
@@ -1072,7 +1044,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
}
public void generateInitializers(@NotNull ExpressionCodegen codegen) {
private void generateInitializers(@NotNull ExpressionCodegen codegen) {
generateInitializers(() -> codegen);
}
@@ -1118,11 +1090,9 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
private final Map<KtDelegatedSuperTypeEntry, Field> fields = new HashMap<>();
@Nullable
@NotNull
public Field getInfo(KtDelegatedSuperTypeEntry specifier) {
Field field = fields.get(specifier);
assert field != null || state.getClassBuilderMode() == ClassBuilderMode.LIGHT_CLASSES : "No field for " + specifier.getText();
return field;
return fields.get(specifier);
}
private void addField(KtDelegatedSuperTypeEntry specifier, PropertyDescriptor propertyDescriptor) {
@@ -1142,8 +1112,6 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
for (KtSuperTypeListEntry specifier : delegationSpecifiers) {
if (specifier instanceof KtDelegatedSuperTypeEntry) {
KtExpression expression = ((KtDelegatedSuperTypeEntry) specifier).getDelegateExpression();
if (expression == null) continue;
PropertyDescriptor propertyDescriptor = CodegenUtil.getDelegatePropertyIfAny(expression, descriptor, bindingContext);
@@ -1151,14 +1119,9 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
result.addField((KtDelegatedSuperTypeEntry) specifier, propertyDescriptor);
}
else {
KotlinType expressionType = bindingContext.getType(expression);
ClassDescriptor superClass = getSuperClass(specifier);
KotlinType expressionType = expression != null ? bindingContext.getType(expression) : null;
Type asmType =
expressionType != null ? typeMapper.mapType(expressionType) :
superClass != null ? typeMapper.mapType(superClass) : null;
if (asmType == null) continue;
expressionType != null ? typeMapper.mapType(expressionType) : typeMapper.mapType(getSuperClass(specifier));
result.addField((KtDelegatedSuperTypeEntry) specifier, asmType, JvmAbi.DELEGATE_SUPER_FIELD_PREFIX + n);
}
n++;
@@ -1167,13 +1130,9 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
return result;
}
@Nullable
@NotNull
private ClassDescriptor getSuperClass(@NotNull KtSuperTypeListEntry specifier) {
ClassDescriptor superClass = CodegenUtil.getSuperClassBySuperTypeListEntry(specifier, bindingContext);
assert superClass != null || state.getClassBuilderMode() == ClassBuilderMode.LIGHT_CLASSES
: "ClassDescriptor should not be null:" + specifier.getText();
return superClass;
return CodegenUtil.getSuperClassBySuperTypeListEntry(specifier, bindingContext);
}
private void genCallToDelegatorByExpressionSpecifier(
@@ -1185,8 +1144,6 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
KtExpression expression = specifier.getDelegateExpression();
DelegationFieldsInfo.Field fieldInfo = fieldsInfo.getInfo(specifier);
if (fieldInfo == null) return;
if (fieldInfo.generateField) {
iv.load(0, classAsmType);
fieldInfo.getStackValue().store(codegen.gen(expression), iv);
@@ -1247,8 +1204,9 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
}
private void lookupInContext(@NotNull DeclarationDescriptor toLookup) {
context.lookupInContext(toLookup, StackValue.LOCAL_0, state, true);
ExpressionCodegen.lookupValuaAndLocalVariableMetadata(toLookup, StackValue.LOCAL_0, state, true, context, null);
}
@Override
@@ -1324,15 +1282,14 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
CodegenUtilKt.reportTarget6InheritanceErrorIfNeeded(descriptor, myClass.getPsiOrParent(), restrictedInheritance, state);
}
private void generateDelegationToDefaultImpl(@NotNull FunctionDescriptor interfaceFun, @NotNull FunctionDescriptor inheritedFun) {
private void generateDelegationToDefaultImpl(@NotNull FunctionDescriptor traitFun, @NotNull FunctionDescriptor inheritedFun) {
functionCodegen.generateMethod(
new JvmDeclarationOrigin(CLASS_MEMBER_DELEGATION_TO_DEFAULT_IMPL, descriptorToDeclaration(interfaceFun), interfaceFun),
JvmDeclarationOriginKt.DelegationToDefaultImpls(descriptorToDeclaration(traitFun), traitFun),
inheritedFun,
new FunctionGenerationStrategy.CodegenBased(state) {
@Override
public void doGenerateBody(@NotNull ExpressionCodegen codegen, @NotNull JvmMethodSignature signature) {
DeclarationDescriptor containingDeclaration = interfaceFun.getContainingDeclaration();
DeclarationDescriptor containingDeclaration = traitFun.getContainingDeclaration();
if (!DescriptorUtils.isInterface(containingDeclaration)) return;
DeclarationDescriptor declarationInheritedFun = inheritedFun.getContainingDeclaration();
@@ -1344,12 +1301,12 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
ClassDescriptor containingTrait = (ClassDescriptor) containingDeclaration;
Type traitImplType = typeMapper.mapDefaultImpls(containingTrait);
Method traitMethod = typeMapper.mapAsmMethod(interfaceFun.getOriginal(), OwnerKind.DEFAULT_IMPLS);
Method traitMethod = typeMapper.mapAsmMethod(traitFun.getOriginal(), OwnerKind.DEFAULT_IMPLS);
Type[] argTypes = signature.getAsmMethod().getArgumentTypes();
Type[] originalArgTypes = traitMethod.getArgumentTypes();
assert originalArgTypes.length == argTypes.length + 1 :
"Invalid trait implementation signature: " + signature + " vs " + traitMethod + " for " + interfaceFun;
"Invalid trait implementation signature: " + signature + " vs " + traitMethod + " for " + traitFun;
InstructionAdapter iv = codegen.v;
iv.load(0, OBJECT_TYPE);
@@ -1572,7 +1529,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
InstructionAdapter iv = codegen.v;
Type arrayAsmType = typeMapper.mapType(DescriptorUtilsKt.getBuiltIns(descriptor).getArrayType(INVARIANT, descriptor.getDefaultType()));
v.newField(JvmDeclarationOriginKt.OtherOriginFromPure(myClass), ACC_PRIVATE | ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, ENUM_VALUES_FIELD_NAME,
v.newField(JvmDeclarationOriginKt.OtherOrigin(myClass), ACC_PRIVATE | ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, ENUM_VALUES_FIELD_NAME,
arrayAsmType.getDescriptor(), null, null);
iv.iconst(enumEntries.size());
@@ -1631,15 +1588,10 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
for (KtSuperTypeListEntry specifier : myClass.getSuperTypeListEntries()) {
if (specifier instanceof KtDelegatedSuperTypeEntry) {
DelegationFieldsInfo.Field field = delegationFieldsInfo.getInfo((KtDelegatedSuperTypeEntry) specifier);
if (field == null) continue;
generateDelegateField(field);
KtExpression delegateExpression = ((KtDelegatedSuperTypeEntry) specifier).getDelegateExpression();
KotlinType delegateExpressionType = delegateExpression != null ? bindingContext.getType(delegateExpression) : null;
ClassDescriptor superClass = getSuperClass(specifier);
if (superClass == null) continue;
generateDelegates(superClass, delegateExpressionType, field);
generateDelegates(getSuperClass(specifier), delegateExpressionType, field);
}
}
}

View File

@@ -29,8 +29,8 @@ import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtPureClassOrObject
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.jvm.diagnostics.DelegationToDefaultImpls
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKind
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.org.objectweb.asm.MethodVisitor
@@ -48,10 +48,8 @@ class InterfaceImplBodyCodegen(
get() = (v as InterfaceImplClassBuilder).isAnythingGenerated
override fun generateDeclaration() {
val codegenFlags = ACC_PUBLIC or ACC_FINAL or ACC_SUPER
val flags = if (state.classBuilderMode == ClassBuilderMode.LIGHT_CLASSES) codegenFlags or ACC_STATIC else codegenFlags
v.defineClass(
myClass.psiOrParent, state.classFileVersion, flags,
myClass.psiOrParent, state.classFileVersion, ACC_PUBLIC or ACC_FINAL or ACC_SUPER,
typeMapper.mapDefaultImpls(descriptor).internalName,
null, "java/lang/Object", ArrayUtil.EMPTY_STRING_ARRAY
)
@@ -70,7 +68,7 @@ class InterfaceImplBodyCodegen(
return classDescriptorImpl
}
override fun generateSyntheticPartsAfterBody() {
override fun generateSyntheticParts() {
for (memberDescriptor in descriptor.defaultType.memberScope.getContributedDescriptors()) {
if (memberDescriptor !is CallableMemberDescriptor) continue
@@ -115,10 +113,7 @@ class InterfaceImplBodyCodegen(
if (delegateTo is JavaMethodDescriptor) return
functionCodegen.generateMethod(
JvmDeclarationOrigin(
JvmDeclarationOriginKind.DEFAULT_IMPL_DELEGATION_TO_SUPERINTERFACE_DEFAULT_IMPL,
DescriptorToSourceUtils.descriptorToDeclaration(descriptor), descriptor
),
DelegationToDefaultImpls(DescriptorToSourceUtils.descriptorToDeclaration(descriptor), descriptor),
descriptor,
object : FunctionGenerationStrategy.CodegenBased(state) {
override fun doGenerateBody(codegen: ExpressionCodegen, signature: JvmMethodSignature) {

View File

@@ -85,6 +85,7 @@ class JvmRuntimeTypes(module: ModuleDescriptor) {
if (descriptor.isSuspend) {
return mutableListOf<KotlinType>().apply {
add(coroutineImplClass.defaultType)
if (descriptor.isSuspendLambda) {
add(functionType)
}

View File

@@ -94,7 +94,8 @@ class JvmStaticInCompanionObjectGenerator(
CallableMemberDescriptor.Kind.SYNTHESIZED,
false
)
return copies[descriptor]!!
val staticFunctionDescriptor = copies[descriptor]!!
return staticFunctionDescriptor
}
}
}

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.
@@ -24,19 +24,14 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.backend.common.CodegenUtil;
import org.jetbrains.kotlin.codegen.annotation.AnnotatedSimple;
import org.jetbrains.kotlin.codegen.binding.CodegenBinding;
import org.jetbrains.kotlin.codegen.context.*;
import org.jetbrains.kotlin.codegen.inline.DefaultSourceMapper;
import org.jetbrains.kotlin.codegen.inline.NameGenerator;
import org.jetbrains.kotlin.codegen.inline.ReifiedTypeParametersUsages;
import org.jetbrains.kotlin.codegen.inline.SourceMapper;
import org.jetbrains.kotlin.codegen.inline.*;
import org.jetbrains.kotlin.codegen.serialization.JvmSerializerExtension;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget;
import org.jetbrains.kotlin.descriptors.annotations.Annotations;
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor;
import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl;
import org.jetbrains.kotlin.fileClasses.FileClasses;
import org.jetbrains.kotlin.fileClasses.JvmFileClassesProvider;
@@ -49,8 +44,8 @@ import org.jetbrains.kotlin.name.SpecialNames;
import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.psi.synthetics.SyntheticClassOrObjectDescriptor;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.BindingContextUtils;
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils;
import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall;
import org.jetbrains.kotlin.resolve.constants.ConstantValue;
import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt;
@@ -71,15 +66,11 @@ import org.jetbrains.org.objectweb.asm.Type;
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
import org.jetbrains.org.objectweb.asm.commons.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.*;
import static org.jetbrains.kotlin.codegen.AsmUtil.*;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isJvm8InterfaceWithDefaultsMember;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isNonDefaultInterfaceMember;
import static org.jetbrains.kotlin.codegen.inline.InlineCodegenUtilsKt.getInlineName;
import static org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.SYNTHESIZED;
import static org.jetbrains.kotlin.resolve.BindingContext.*;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.*;
@@ -136,18 +127,11 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
public void generate() {
generateDeclaration();
boolean shouldGenerateSyntheticParts =
!(element instanceof KtClassOrObject) ||
state.getGenerateDeclaredClassFilter().shouldGenerateClassMembers((KtClassOrObject) element);
if (shouldGenerateSyntheticParts) {
generateSyntheticPartsBeforeBody();
}
generateBody();
if (shouldGenerateSyntheticParts) {
generateSyntheticPartsAfterBody();
if (!(element instanceof KtClassOrObject) ||
state.getGenerateDeclaredClassFilter().shouldGenerateClassMembers((KtClassOrObject) element)) {
generateSyntheticParts();
}
if (state.getClassBuilderMode().generateMetadata) {
@@ -159,12 +143,9 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
protected abstract void generateDeclaration();
protected void generateSyntheticPartsBeforeBody() {
}
protected abstract void generateBody();
protected void generateSyntheticPartsAfterBody() {
protected void generateSyntheticParts() {
}
protected abstract void generateKotlinMetadataAnnotation();
@@ -235,17 +216,6 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
else if (declaration instanceof KtTypeAlias) {
genTypeAlias((KtTypeAlias) declaration);
}
else if (declaration instanceof KtDestructuringDeclarationEntry) {
try {
propertyCodegen.genDestructuringDeclaration((KtDestructuringDeclarationEntry) declaration);
}
catch (ProcessCanceledException | CompilationException e) {
throw e;
}
catch (Exception e) {
throw new CompilationException("Failed to generate destructuring declaration entry " + declaration.getName(), e, declaration);
}
}
else {
throw new IllegalArgumentException("Unknown parameter: " + declaration);
}
@@ -315,7 +285,7 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
Type classType = state.getTypeMapper().mapClass(descriptor);
ClassBuilder classBuilder = state.getFactory().newVisitor(
JvmDeclarationOriginKt.OtherOriginFromPure(aClass, descriptor),
JvmDeclarationOriginKt.OtherOrigin(aClass, descriptor),
classType, aClass.getContainingKtFile());
ClassContext classContext = parentContext.intoClass(descriptor, OwnerKind.IMPLEMENTATION, state);
new ImplementationBodyCodegen(aClass, classContext, classBuilder, state, parentCodegen, false).generate();
@@ -456,7 +426,7 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
@NotNull
public NameGenerator getInlineNameGenerator() {
if (inlineNameGenerator == null) {
String prefix = getInlineName(context, typeMapper, fileClassesProvider);
String prefix = InlineCodegenUtil.getInlineName(context, typeMapper, fileClassesProvider);
inlineNameGenerator = new NameGenerator(prefix);
}
return inlineNameGenerator;
@@ -496,9 +466,6 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
initializeProperty(codegen.invoke(), (KtProperty) declaration);
}
}
else if (declaration instanceof KtDestructuringDeclaration) {
codegen.invoke().initializeDestructuringDeclaration((KtDestructuringDeclaration) declaration, true);
}
else if (declaration instanceof KtAnonymousInitializer) {
KtExpression body = ((KtAnonymousInitializer) declaration).getBody();
if (body != null) {
@@ -529,8 +496,11 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
StackValue provideDelegateReceiver = codegen.gen(initializer);
StackValue delegateValue = PropertyCodegen.invokeDelegatedPropertyConventionMethod(
codegen, provideDelegateResolvedCall, provideDelegateReceiver, propertyDescriptor
int indexOfDelegatedProperty = PropertyCodegen.indexOfDelegatedProperty(property);
StackValue delegateValue = PropertyCodegen.invokeDelegatedPropertyConventionMethodWithReceiver(
codegen, typeMapper, provideDelegateResolvedCall, indexOfDelegatedProperty, 1,
provideDelegateReceiver, propertyDescriptor
);
propValue.store(delegateValue, codegen.v);
@@ -610,8 +580,16 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
}
protected void generatePropertyMetadataArrayFieldIfNeeded(@NotNull Type thisAsmType) {
List<VariableDescriptorWithAccessors> delegatedProperties = bindingContext.get(CodegenBinding.DELEGATED_PROPERTIES, thisAsmType);
if (delegatedProperties == null || delegatedProperties.isEmpty()) return;
List<KtProperty> delegatedProperties = new ArrayList<>();
for (KtDeclaration declaration : ((KtDeclarationContainer) element).getDeclarations()) {
if (declaration instanceof KtProperty) {
KtProperty property = (KtProperty) declaration;
if (property.hasDelegate()) {
delegatedProperties.add(property);
}
}
}
if (delegatedProperties.isEmpty()) return;
v.newField(NO_ORIGIN, ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, JvmAbi.DELEGATED_PROPERTIES_ARRAY_NAME,
"[" + K_PROPERTY_TYPE, null, null);
@@ -623,7 +601,8 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
iv.newarray(K_PROPERTY_TYPE);
for (int i = 0, size = delegatedProperties.size(); i < size; i++) {
VariableDescriptorWithAccessors property = delegatedProperties.get(i);
PropertyDescriptor property =
(PropertyDescriptor) BindingContextUtils.getNotNull(bindingContext, VARIABLE, delegatedProperties.get(i));
iv.dup();
iv.iconst(i);
@@ -633,12 +612,10 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
Type implType = property.isVar() ? MUTABLE_PROPERTY_REFERENCE_IMPL[receiverCount] : PROPERTY_REFERENCE_IMPL[receiverCount];
iv.anew(implType);
iv.dup();
// TODO: generate the container once and save to a local field instead (KT-10495)
ClosureCodegen.generateCallableReferenceDeclarationContainer(iv, property, state);
iv.aconst(property.getName().asString());
PropertyReferenceCodegen.generateCallableReferenceSignature(iv, property, state);
iv.invokespecial(
implType.getInternalName(), "<init>",
Type.getMethodDescriptor(Type.VOID_TYPE, K_DECLARATION_CONTAINER_TYPE, JAVA_STRING_TYPE, JAVA_STRING_TYPE), false
@@ -680,7 +657,7 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
@NotNull
public DefaultSourceMapper getOrCreateSourceMapper() {
if (sourceMapper == null) {
// note: this is used in InlineCodegen and the element is always physical (KtElement) there
// note: this is used for in InlineCodegen and the element is always physical (KtElement) there
sourceMapper = new DefaultSourceMapper(SourceInfo.Companion.createInfo((KtElement)element, getClassName()));
}
return sourceMapper;
@@ -688,7 +665,7 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
protected void generateConstInstance(@NotNull Type thisAsmType, @NotNull Type fieldAsmType) {
v.newField(
JvmDeclarationOriginKt.OtherOriginFromPure(element), ACC_STATIC | ACC_FINAL | ACC_PUBLIC, JvmAbi.INSTANCE_FIELD,
JvmDeclarationOriginKt.OtherOrigin(element), ACC_STATIC | ACC_FINAL | ACC_PUBLIC, JvmAbi.INSTANCE_FIELD,
fieldAsmType.getDescriptor(), null, null
);

View File

@@ -205,8 +205,11 @@ class MultifileClassCodegenImpl(
val packageFragment = this.packageFragment
?: throw AssertionError("File part $file of $facadeFqName: no package fragment")
val partType = file.getFileClassFqName().toAsmType()
val partContext = state.rootContext.intoMultifileClassPart(packageFragment, facadeClassType, partType, file)
val partClassFqName = file.getFileClassFqName()
val partInitializerClassFqName = FqName(partClassFqName.asString() + "__Init")
val partType = partClassFqName.toAsmType()
val partInitializerType = partInitializerClassFqName.toAsmType()
val partContext = state.rootContext.intoMultifileClassPart(packageFragment, facadeClassType, partType, partInitializerType, file)
generateNonPartClassDeclarations(file, partContext)

View File

@@ -175,11 +175,8 @@ class MultifileClassPartCodegen(
}
}
val extension = JvmSerializerExtension(v.serializationBindings, state)
val serializer = DescriptorSerializer.createTopLevel(extension)
val builder = serializer.packagePartProto(packageFragment.fqName, members)
extension.serializeJvmPackage(builder, partType)
val packageProto = builder.build()
val serializer = DescriptorSerializer.createTopLevel(JvmSerializerExtension(v.serializationBindings, state))
val packageProto = serializer.packagePartProto(packageFragment.fqName, members).build()
val extraFlags = if (shouldGeneratePartHierarchy) JvmAnnotationNames.METADATA_MULTIFILE_PARTS_INHERIT_FLAG else 0
@@ -189,7 +186,7 @@ class MultifileClassPartCodegen(
}
}
override fun generateSyntheticPartsAfterBody() {
override fun generateSyntheticParts() {
generateSyntheticAccessors()
}

View File

@@ -0,0 +1,25 @@
/*
* 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;
public enum OwnerKind {
PACKAGE,
IMPLEMENTATION,
DEFAULT_IMPLS
}

View File

@@ -1,36 +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.codegen.descriptors.FileClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
enum class OwnerKind {
PACKAGE,
IMPLEMENTATION,
DEFAULT_IMPLS;
companion object {
fun getMemberOwnerKind(descriptor: DeclarationDescriptor): OwnerKind = when (descriptor) {
is FileClassDescriptor, is PackageFragmentDescriptor -> OwnerKind.PACKAGE
is ClassDescriptor -> OwnerKind.IMPLEMENTATION
else -> throw AssertionError("Unexpected declaration container: $this")
}
}
}

View File

@@ -119,11 +119,9 @@ public class PackagePartCodegen extends MemberCodegen<KtFile> {
}
}
JvmSerializerExtension extension = new JvmSerializerExtension(v.getSerializationBindings(), state);
DescriptorSerializer serializer = DescriptorSerializer.createTopLevel(extension);
ProtoBuf.Package.Builder builder = serializer.packagePartProto(element.getPackageFqName(), members);
extension.serializeJvmPackage(builder, packagePartType);
ProtoBuf.Package packageProto = builder.build();
DescriptorSerializer serializer =
DescriptorSerializer.createTopLevel(new JvmSerializerExtension(v.getSerializationBindings(), state));
ProtoBuf.Package packageProto = serializer.packagePartProto(element.getPackageFqName(), members).build();
WriteAnnotationUtilKt.writeKotlinMetadata(v, state, KotlinClassHeader.Kind.FILE_FACADE, 0, av -> {
writeAnnotationData(av, serializer, packageProto);
@@ -132,7 +130,7 @@ public class PackagePartCodegen extends MemberCodegen<KtFile> {
}
@Override
protected void generateSyntheticPartsAfterBody() {
protected void generateSyntheticParts() {
generateSyntheticAccessors();
}
}

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.
@@ -21,10 +21,7 @@ import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.codegen.annotation.AnnotatedWithFakeAnnotations;
import org.jetbrains.kotlin.codegen.context.CodegenContextUtil;
import org.jetbrains.kotlin.codegen.context.FieldOwnerContext;
import org.jetbrains.kotlin.codegen.context.MultifileClassFacadeContext;
import org.jetbrains.kotlin.codegen.context.MultifileClassPartContext;
import org.jetbrains.kotlin.codegen.context.*;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
import org.jetbrains.kotlin.descriptors.*;
@@ -35,12 +32,12 @@ import org.jetbrains.kotlin.descriptors.annotations.Annotations;
import org.jetbrains.kotlin.fileClasses.JvmFileClassUtilKt;
import org.jetbrains.kotlin.load.java.JvmAbi;
import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.psi.psiUtil.PsiUtilsKt;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.DescriptorFactory;
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils;
import org.jetbrains.kotlin.resolve.annotations.AnnotationUtilKt;
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall;
import org.jetbrains.kotlin.resolve.calls.util.UnderscoreUtilKt;
import org.jetbrains.kotlin.resolve.constants.ConstantValue;
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKt;
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodGenericSignature;
@@ -62,8 +59,6 @@ import static org.jetbrains.kotlin.codegen.AsmUtil.getDeprecatedAccessFlag;
import static org.jetbrains.kotlin.codegen.AsmUtil.getVisibilityForBackingField;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isConstOrHasJvmFieldAnnotation;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isJvmInterface;
import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.DELEGATED_PROPERTIES;
import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.DELEGATED_PROPERTY_METADATA_OWNER;
import static org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings.FIELD_FOR_PROPERTY;
import static org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings.SYNTHETIC_METHOD_FOR_PROPERTY;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.isCompanionObject;
@@ -110,18 +105,6 @@ public class PropertyCodegen {
gen(property, propertyDescriptor, property.getGetter(), property.getSetter());
}
public void genDestructuringDeclaration(@NotNull KtDestructuringDeclarationEntry entry) {
VariableDescriptor variableDescriptor = bindingContext.get(BindingContext.VARIABLE, entry);
if (!(variableDescriptor instanceof PropertyDescriptor)) {
throw ExceptionLogger.logDescriptorNotFound(
"Destructuring declaration entry" + entry.getName() + " should have a property descriptor: " + variableDescriptor, entry
);
}
PropertyDescriptor propertyDescriptor = (PropertyDescriptor) variableDescriptor;
genDestructuringDeclaration(entry, propertyDescriptor);
}
public void generateInPackageFacade(@NotNull DeserializedPropertyDescriptor deserializedProperty) {
assert context instanceof MultifileClassFacadeContext : "should be called only for generating facade: " + context;
gen(null, deserializedProperty, null, null);
@@ -146,21 +129,6 @@ public class PropertyCodegen {
}
}
private void genDestructuringDeclaration(
@NotNull KtDestructuringDeclarationEntry entry,
@NotNull PropertyDescriptor descriptor
) {
assert kind == OwnerKind.PACKAGE || kind == OwnerKind.IMPLEMENTATION || kind == OwnerKind.DEFAULT_IMPLS
: "Generating property with a wrong kind (" + kind + "): " + descriptor;
if (UnderscoreUtilKt.isSingleUnderscore(entry)) return;
genBackingFieldAndAnnotations(entry, descriptor, false);
generateGetter(entry, descriptor, null);
generateSetter(entry, descriptor, null);
}
private void genBackingFieldAndAnnotations(
@Nullable KtNamedDeclaration declaration, @NotNull PropertyDescriptor descriptor, boolean isParameter
) {
@@ -482,7 +450,7 @@ public class PropertyCodegen {
FunctionGenerationStrategy strategy;
if (accessor == null || !accessor.hasBody()) {
if (p instanceof KtProperty && ((KtProperty) p).hasDelegate()) {
strategy = new DelegatedPropertyAccessorStrategy(state, accessorDescriptor);
strategy = new DelegatedPropertyAccessorStrategy(state, accessorDescriptor, indexOfDelegatedProperty((KtProperty) p));
}
else {
strategy = new DefaultPropertyAccessorStrategy(state, accessorDescriptor);
@@ -495,9 +463,39 @@ public class PropertyCodegen {
functionCodegen.generateMethod(JvmDeclarationOriginKt.OtherOrigin(accessor != null ? accessor : p, accessorDescriptor), accessorDescriptor, strategy);
}
public static int indexOfDelegatedProperty(@NotNull KtProperty property) {
PsiElement parent = property.getParent();
KtDeclarationContainer container;
if (parent instanceof KtClassBody) {
container = ((KtClassOrObject) parent.getParent());
}
else if (parent instanceof KtFile) {
container = (KtFile) parent;
}
else if (KtPsiUtil.isScriptDeclaration(property)) {
container = KtPsiUtil.getScript(property);
assert container != null : "Script declaration for property '" + property.getText() + "' should be not null!";
}
else {
throw new UnsupportedOperationException("Unknown delegated property container: " + parent);
}
int index = 0;
for (KtDeclaration declaration : container.getDeclarations()) {
if (declaration instanceof KtProperty && ((KtProperty) declaration).hasDelegate()) {
if (declaration == property) {
return index;
}
index++;
}
}
throw new IllegalStateException("Delegated property not found in its parent: " + PsiUtilsKt.getElementTextWithContext(property));
}
private static class DefaultPropertyAccessorStrategy extends FunctionGenerationStrategy.CodegenBased {
private final PropertyAccessorDescriptor propertyAccessorDescriptor;
public DefaultPropertyAccessorStrategy(@NotNull GenerationState state, @NotNull PropertyAccessorDescriptor descriptor) {
super(state);
propertyAccessorDescriptor = descriptor;
@@ -535,45 +533,75 @@ public class PropertyCodegen {
}
public static StackValue invokeDelegatedPropertyConventionMethod(
@NotNull PropertyDescriptor propertyDescriptor,
@NotNull ExpressionCodegen codegen,
@NotNull KotlinTypeMapper typeMapper,
@NotNull ResolvedCall<FunctionDescriptor> resolvedCall,
int indexInPropertyMetadataArray,
int propertyMetadataArgumentIndex
) {
StackValue.Property receiver = codegen.intermediateValueForProperty(propertyDescriptor, true, null, StackValue.LOCAL_0);
return invokeDelegatedPropertyConventionMethodWithReceiver(
codegen, typeMapper, resolvedCall, indexInPropertyMetadataArray, propertyMetadataArgumentIndex,
receiver, propertyDescriptor
);
}
public static StackValue invokeDelegatedPropertyConventionMethodWithReceiver(
@NotNull ExpressionCodegen codegen,
@NotNull KotlinTypeMapper typeMapper,
@NotNull ResolvedCall<FunctionDescriptor> resolvedCall,
int indexInPropertyMetadataArray,
int propertyMetadataArgumentIndex,
@Nullable StackValue receiver,
@NotNull PropertyDescriptor propertyDescriptor
) {
Type owner = JvmAbi.isPropertyWithBackingFieldInOuterClass(propertyDescriptor) ?
codegen.getState().getTypeMapper().mapOwner(propertyDescriptor) :
getDelegatedPropertyMetadataOwner(codegen, typeMapper);
codegen.tempVariables.put(
resolvedCall.getCall().getValueArguments().get(1).asElement(),
getDelegatedPropertyMetadata(propertyDescriptor, codegen.getBindingContext())
resolvedCall.getCall().getValueArguments().get(propertyMetadataArgumentIndex).asElement(),
new StackValue(K_PROPERTY_TYPE) {
@Override
public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
Field array = StackValue.field(
Type.getType("[" + K_PROPERTY_TYPE), owner, JvmAbi.DELEGATED_PROPERTIES_ARRAY_NAME, true, StackValue.none()
);
StackValue.arrayElement(
K_PROPERTY_TYPE, array, StackValue.constant(indexInPropertyMetadataArray, Type.INT_TYPE)
).put(type, v);
}
}
);
return codegen.invokeFunction(resolvedCall, receiver);
}
@NotNull
public static StackValue getDelegatedPropertyMetadata(
@NotNull VariableDescriptorWithAccessors descriptor,
@NotNull BindingContext bindingContext
) {
Type owner = bindingContext.get(DELEGATED_PROPERTY_METADATA_OWNER, descriptor);
assert owner != null : "Delegated property owner not found: " + descriptor;
List<VariableDescriptorWithAccessors> allDelegatedProperties = bindingContext.get(DELEGATED_PROPERTIES, owner);
int index = allDelegatedProperties == null ? -1 : allDelegatedProperties.indexOf(descriptor);
if (index < 0) {
throw new AssertionError("Delegated property not found in " + owner + ": " + descriptor);
private static Type getDelegatedPropertyMetadataOwner(@NotNull ExpressionCodegen codegen, @NotNull KotlinTypeMapper typeMapper) {
CodegenContext<? extends ClassOrPackageFragmentDescriptor> ownerContext = codegen.getContext().getClassOrPackageParentContext();
if (ownerContext instanceof ClassContext) {
return typeMapper.mapClass(((ClassContext) ownerContext).getContextDescriptor());
}
else if (ownerContext instanceof PackageContext) {
return ((PackageContext) ownerContext).getPackagePartType();
}
else if (ownerContext instanceof MultifileClassContextBase) {
return ((MultifileClassContextBase) ownerContext).getFilePartType();
}
else {
throw new UnsupportedOperationException("Unknown context: " + ownerContext);
}
StackValue.Field array = StackValue.field(
Type.getType("[" + K_PROPERTY_TYPE), owner, JvmAbi.DELEGATED_PROPERTIES_ARRAY_NAME, true, StackValue.none()
);
return StackValue.arrayElement(K_PROPERTY_TYPE, array, StackValue.constant(index, Type.INT_TYPE));
}
private static class DelegatedPropertyAccessorStrategy extends FunctionGenerationStrategy.CodegenBased {
private final int index;
private final PropertyAccessorDescriptor propertyAccessorDescriptor;
public DelegatedPropertyAccessorStrategy(@NotNull GenerationState state, @NotNull PropertyAccessorDescriptor descriptor) {
public DelegatedPropertyAccessorStrategy(@NotNull GenerationState state, @NotNull PropertyAccessorDescriptor descriptor, int index) {
super(state);
this.propertyAccessorDescriptor = descriptor;
this.index = index;
propertyAccessorDescriptor = descriptor;
}
@Override
@@ -585,9 +613,8 @@ public class PropertyCodegen {
bindingContext.get(BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, propertyAccessorDescriptor);
assert resolvedCall != null : "Resolve call should be recorded for delegate call " + signature.toString();
PropertyDescriptor propertyDescriptor = propertyAccessorDescriptor.getCorrespondingProperty();
StackValue.Property receiver = codegen.intermediateValueForProperty(propertyDescriptor, true, null, StackValue.LOCAL_0);
StackValue lastValue = invokeDelegatedPropertyConventionMethod(codegen, resolvedCall, receiver, propertyDescriptor);
StackValue lastValue = invokeDelegatedPropertyConventionMethod(propertyAccessorDescriptor.getCorrespondingProperty(),
codegen, state.getTypeMapper(), resolvedCall, index, 1);
Type asmType = signature.getReturnType();
lastValue.put(asmType, v);
v.areturn(asmType);

View File

@@ -116,11 +116,10 @@ class PropertyReferenceCodegen(
generateCallableReferenceSignature(this, target, state)
}
generateMethod("property reference getOwner", ACC_PUBLIC, method("getOwner", K_DECLARATION_CONTAINER_TYPE)) {
ClosureCodegen.generateCallableReferenceDeclarationContainer(this, target, state)
}
if (!isLocalDelegatedProperty) {
generateMethod("property reference getOwner", ACC_PUBLIC, method("getOwner", K_DECLARATION_CONTAINER_TYPE)) {
ClosureCodegen.generateCallableReferenceDeclarationContainer(this, target, state)
}
generateAccessors()
}
}
@@ -195,17 +194,6 @@ class PropertyReferenceCodegen(
@JvmStatic
fun generateCallableReferenceSignature(iv: InstructionAdapter, callable: CallableDescriptor, state: GenerationState) {
if (callable is LocalVariableDescriptor) {
val asmType = state.bindingContext.get(CodegenBinding.DELEGATED_PROPERTY_METADATA_OWNER, callable)
val allDelegatedProperties = state.bindingContext.get(CodegenBinding.DELEGATED_PROPERTIES, asmType)
val index = allDelegatedProperties?.indexOf(callable) ?: -1
if (index < 0) {
throw AssertionError("Local delegated property is not found in $asmType: $callable")
}
iv.aconst("<v#$index>") // v = "variable"
return
}
val accessor = when (callable) {
is FunctionDescriptor -> callable
is VariableDescriptorWithAccessors ->

View File

@@ -0,0 +1,251 @@
/*
* 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 com.google.common.collect.ImmutableMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.builtins.PrimitiveType;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.lexer.KtTokens;
import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.name.FqNameUnsafe;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.resolve.calls.callUtil.CallUtilKt;
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall;
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver;
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.org.objectweb.asm.Type;
import java.util.Arrays;
import java.util.List;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.RANGES_PACKAGE_FQ_NAME;
import static org.jetbrains.kotlin.codegen.AsmUtil.isPrimitiveNumberClassDescriptor;
public class RangeCodegenUtil {
private static final ImmutableMap<FqName, PrimitiveType> RANGE_TO_ELEMENT_TYPE;
private static final ImmutableMap<FqName, PrimitiveType> PROGRESSION_TO_ELEMENT_TYPE;
@NotNull
public static List<PrimitiveType> supportedRangeTypes() {
return Arrays.asList(PrimitiveType.CHAR, PrimitiveType.INT, PrimitiveType.LONG);
}
static {
ImmutableMap.Builder<FqName, PrimitiveType> rangeBuilder = ImmutableMap.builder();
ImmutableMap.Builder<FqName, PrimitiveType> progressionBuilder = ImmutableMap.builder();
for (PrimitiveType primitiveType : supportedRangeTypes()) {
FqName rangeClassFqName = RANGES_PACKAGE_FQ_NAME.child(Name.identifier(primitiveType.getTypeName() + "Range"));
FqName progressionClassFqName = RANGES_PACKAGE_FQ_NAME.child(Name.identifier(primitiveType.getTypeName() + "Progression"));
rangeBuilder.put(rangeClassFqName, primitiveType);
progressionBuilder.put(progressionClassFqName, primitiveType);
}
RANGE_TO_ELEMENT_TYPE = rangeBuilder.build();
PROGRESSION_TO_ELEMENT_TYPE = progressionBuilder.build();
}
private RangeCodegenUtil() {}
public static boolean isRange(KotlinType rangeType) {
return !rangeType.isMarkedNullable() && getPrimitiveRangeElementType(rangeType) != null;
}
public static boolean isProgression(KotlinType rangeType) {
return !rangeType.isMarkedNullable() && getPrimitiveProgressionElementType(rangeType) != null;
}
@Nullable
public static ResolvedCall<? extends CallableDescriptor> getLoopRangeResolvedCall(@NotNull KtForExpression forExpression, @NotNull BindingContext bindingContext) {
KtExpression loopRange = KtPsiUtil.deparenthesize(forExpression.getLoopRange());
if (loopRange instanceof KtQualifiedExpression) {
KtQualifiedExpression qualifiedExpression = (KtQualifiedExpression) loopRange;
KtExpression selector = qualifiedExpression.getSelectorExpression();
if (selector instanceof KtCallExpression || selector instanceof KtSimpleNameExpression) {
return CallUtilKt.getResolvedCall(selector, bindingContext);
}
}
else if (loopRange instanceof KtSimpleNameExpression || loopRange instanceof KtCallExpression) {
return CallUtilKt.getResolvedCall(loopRange, bindingContext);
}
else if (loopRange instanceof KtBinaryExpression) {
return CallUtilKt.getResolvedCall(((KtBinaryExpression) loopRange).getOperationReference(), bindingContext);
}
return null;
}
@Nullable
private static PrimitiveType getPrimitiveRangeElementType(KotlinType rangeType) {
return getPrimitiveRangeOrProgressionElementType(rangeType, RANGE_TO_ELEMENT_TYPE);
}
@Nullable
private static PrimitiveType getPrimitiveProgressionElementType(KotlinType rangeType) {
return getPrimitiveRangeOrProgressionElementType(rangeType, PROGRESSION_TO_ELEMENT_TYPE);
}
@Nullable
private static PrimitiveType getPrimitiveRangeOrProgressionElementType(
@NotNull KotlinType rangeOrProgression,
@NotNull ImmutableMap<FqName, PrimitiveType> map
) {
ClassifierDescriptor declarationDescriptor = rangeOrProgression.getConstructor().getDeclarationDescriptor();
if (declarationDescriptor == null) return null;
FqNameUnsafe fqName = DescriptorUtils.getFqName(declarationDescriptor);
if (!fqName.isSafe()) return null;
return map.get(fqName.toSafe());
}
@Nullable
public static PrimitiveType getPrimitiveRangeOrProgressionElementType(@NotNull FqName rangeOrProgressionName) {
PrimitiveType result = RANGE_TO_ELEMENT_TYPE.get(rangeOrProgressionName);
return result != null ? result : PROGRESSION_TO_ELEMENT_TYPE.get(rangeOrProgressionName);
}
public static boolean isRangeOrProgression(@NotNull FqName className) {
return getPrimitiveRangeOrProgressionElementType(className) != null;
}
public static boolean isPrimitiveNumberRangeTo(CallableDescriptor rangeTo) {
if (!"rangeTo".equals(rangeTo.getName().asString())) return false;
if (!isPrimitiveNumberClassDescriptor(rangeTo.getContainingDeclaration())) return false;
return true;
}
private static boolean isPrimitiveRangeToExtension(@NotNull CallableDescriptor descriptor) {
if (!isTopLevelInPackage(descriptor, "rangeTo", "kotlin.ranges")) return false;
ReceiverParameterDescriptor extensionReceiver = descriptor.getExtensionReceiverParameter();
if (extensionReceiver == null) return false;
return KotlinBuiltIns.isPrimitiveType(extensionReceiver.getType());
}
public static boolean isPrimitiveNumberDownTo(@NotNull CallableDescriptor descriptor) {
if (!isTopLevelInPackage(descriptor, "downTo", "kotlin.ranges")) return false;
ReceiverParameterDescriptor extensionReceiver = descriptor.getExtensionReceiverParameter();
if (extensionReceiver == null) return false;
ClassifierDescriptor extensionReceiverClassifier = extensionReceiver.getType().getConstructor().getDeclarationDescriptor();
if (!isPrimitiveNumberClassDescriptor(extensionReceiverClassifier)) return false;
return true;
}
public static boolean isArrayOrPrimitiveArrayIndices(@NotNull CallableDescriptor descriptor) {
if (!isTopLevelInPackage(descriptor, "indices", "kotlin.collections")) return false;
ReceiverParameterDescriptor extensionReceiver = descriptor.getExtensionReceiverParameter();
if (extensionReceiver == null) return false;
KotlinType extensionReceiverType = extensionReceiver.getType();
if (!KotlinBuiltIns.isArray(extensionReceiverType) && !KotlinBuiltIns.isPrimitiveArray(extensionReceiverType)) return false;
return true;
}
public static boolean isCollectionIndices(@NotNull CallableDescriptor descriptor) {
if (!isTopLevelInPackage(descriptor, "indices", "kotlin.collections")) return false;
ReceiverParameterDescriptor extensionReceiver = descriptor.getExtensionReceiverParameter();
if (extensionReceiver == null) return false;
KotlinType extensionReceiverType = extensionReceiver.getType();
if (!KotlinBuiltIns.isCollectionOrNullableCollection(extensionReceiverType)) return false;
return true;
}
public static boolean isCharSequenceIndices(@NotNull CallableDescriptor descriptor) {
if (!isTopLevelInPackage(descriptor, "indices", "kotlin.text")) return false;
ReceiverParameterDescriptor extensionReceiver = descriptor.getExtensionReceiverParameter();
if (extensionReceiver == null) return false;
KotlinType extensionReceiverType = extensionReceiver.getType();
if (!KotlinBuiltIns.isCharSequenceOrNullableCharSequence(extensionReceiverType)) return false;
return true;
}
public static boolean isPrimitiveRangeToExtension(@NotNull KtSimpleNameExpression operationReference, @NotNull BindingContext bindingContext) {
ResolvedCall<? extends CallableDescriptor> resolvedCall = CallUtilKt
.getResolvedCallWithAssert(operationReference, bindingContext);
ReceiverValue receiver = resolvedCall.getDispatchReceiver();
/*
* Range is optimizable if
* 'in' receiver is expression 'rangeTo' from stdlib package
* and its argument has same primitive type as generic range parameter.
* For non-matching primitive types (e.g. int in double range)
* dispatch receiver will be null, because extension method will be called.
*/
if (!(receiver instanceof ExpressionReceiver)) return false;
ExpressionReceiver e = (ExpressionReceiver) receiver;
ResolvedCall<? extends CallableDescriptor> resolvedReceiver =
CallUtilKt.getResolvedCall(e.getExpression(), bindingContext);
if (resolvedReceiver == null) return false;
return isPrimitiveRangeToExtension(resolvedReceiver.getResultingDescriptor());
}
/*
* Checks whether for expression 'x in a..b' a..b is primitive integral range
* with same type as x.
*/
public static boolean isPrimitiveRangeSpecializationOfType(
@NotNull Type argumentType,
@NotNull KtExpression rangeExpression,
@NotNull BindingContext bindingContext
) {
if (rangeExpression instanceof KtBinaryExpression &&
((KtBinaryExpression) rangeExpression).getOperationReference().getReferencedNameElementType() == KtTokens.RANGE) {
KotlinType kotlinType = bindingContext.getType(rangeExpression);
assert kotlinType != null;
DeclarationDescriptor descriptor = kotlinType.getConstructor().getDeclarationDescriptor();
if (descriptor != null) {
FqNameUnsafe fqName = DescriptorUtils.getFqName(descriptor);
if (fqName.equals(KotlinBuiltIns.FQ_NAMES.longRange)) {
return argumentType == Type.LONG_TYPE;
}
if (fqName.equals(KotlinBuiltIns.FQ_NAMES.charRange) || fqName.equals(KotlinBuiltIns.FQ_NAMES.intRange)) {
return AsmUtil.isIntPrimitive(argumentType);
}
}
}
return false;
}
private static boolean isTopLevelInPackage(@NotNull CallableDescriptor descriptor, @NotNull String name, @NotNull String packageName) {
if (!name.equals(descriptor.getName().asString())) return false;
DeclarationDescriptor containingDeclaration = descriptor.getContainingDeclaration();
if (!(containingDeclaration instanceof PackageFragmentDescriptor)) return false;
String packageFqName = ((PackageFragmentDescriptor) containingDeclaration).getFqName().asString();
if (!packageName.equals(packageFqName)) return false;
return true;
}
}

View File

@@ -1,242 +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.codegen
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.KotlinBuiltIns.RANGES_PACKAGE_FQ_NAME
import org.jetbrains.kotlin.builtins.PrimitiveType
import org.jetbrains.kotlin.codegen.AsmUtil.isPrimitiveNumberClassDescriptor
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.org.objectweb.asm.Type
val supportedRangeTypes = listOf(PrimitiveType.CHAR, PrimitiveType.INT, PrimitiveType.LONG)
private val RANGE_TO_ELEMENT_TYPE: Map<FqName, PrimitiveType> =
supportedRangeTypes.associateBy {
RANGES_PACKAGE_FQ_NAME.child(Name.identifier(it.typeName.toString() + "Range"))
}
private val PROGRESSION_TO_ELEMENT_TYPE: Map<FqName, PrimitiveType> =
supportedRangeTypes.associateBy {
RANGES_PACKAGE_FQ_NAME.child(Name.identifier(it.typeName.toString() + "Progression"))
}
fun isPrimitiveRange(rangeType: KotlinType) =
!rangeType.isMarkedNullable && getPrimitiveRangeElementType(rangeType) != null
fun isPrimitiveProgression(rangeType: KotlinType) =
!rangeType.isMarkedNullable && getPrimitiveProgressionElementType(rangeType) != null
fun getPrimitiveRangeElementType(rangeType: KotlinType): PrimitiveType? =
getPrimitiveRangeOrProgressionElementType(rangeType, RANGE_TO_ELEMENT_TYPE)
private fun getPrimitiveProgressionElementType(rangeType: KotlinType) =
getPrimitiveRangeOrProgressionElementType(rangeType, PROGRESSION_TO_ELEMENT_TYPE)
private fun getPrimitiveRangeOrProgressionElementType(
rangeOrProgression: KotlinType,
map: Map<FqName, PrimitiveType>
): PrimitiveType? {
val declarationDescriptor = rangeOrProgression.constructor.declarationDescriptor ?: return null
val fqName = DescriptorUtils.getFqName(declarationDescriptor).takeIf { it.isSafe } ?: return null
return map[fqName.toSafe()]
}
fun getRangeOrProgressionElementType(rangeType: KotlinType): KotlinType? {
val rangeTypeDescriptor = rangeType.constructor.declarationDescriptor ?: return null
val builtIns = rangeTypeDescriptor.builtIns
return when {
isTopLevelInPackage(rangeTypeDescriptor, "CharRange", "kotlin.ranges") -> builtIns.charType
isTopLevelInPackage(rangeTypeDescriptor, "IntRange", "kotlin.ranges") -> builtIns.intType
isTopLevelInPackage(rangeTypeDescriptor, "LongRange", "kotlin.ranges") -> builtIns.longType
isTopLevelInPackage(rangeTypeDescriptor, "CharProgression", "kotlin.ranges") -> builtIns.charType
isTopLevelInPackage(rangeTypeDescriptor, "IntProgression", "kotlin.ranges") -> builtIns.intType
isTopLevelInPackage(rangeTypeDescriptor, "LongProgression", "kotlin.ranges") -> builtIns.longType
isTopLevelInPackage(rangeTypeDescriptor, "ClosedFloatRange", "kotlin.ranges") -> builtIns.floatType
isTopLevelInPackage(rangeTypeDescriptor, "ClosedDoubleRange", "kotlin.ranges") -> builtIns.doubleType
isTopLevelInPackage(rangeTypeDescriptor, "ClosedRange", "kotlin.ranges") -> rangeType.arguments.singleOrNull()?.type
isTopLevelInPackage(rangeTypeDescriptor, "ClosedFloatingPointRange", "kotlin.ranges") -> rangeType.arguments.singleOrNull()?.type
isTopLevelInPackage(rangeTypeDescriptor, "ComparableRange", "kotlin.ranges") -> rangeType.arguments.singleOrNull()?.type
else -> null
}
}
fun getPrimitiveRangeOrProgressionElementType(rangeOrProgressionName: FqName): PrimitiveType? =
RANGE_TO_ELEMENT_TYPE[rangeOrProgressionName] ?:
PROGRESSION_TO_ELEMENT_TYPE[rangeOrProgressionName]
fun isRangeOrProgression(className: FqName) =
getPrimitiveRangeOrProgressionElementType(className) != null
fun isPrimitiveNumberRangeTo(rangeTo: CallableDescriptor) =
"rangeTo" == rangeTo.name.asString() && isPrimitiveNumberClassDescriptor(rangeTo.containingDeclaration) ||
isPrimitiveRangeToExtension(rangeTo)
private fun isPrimitiveRangeToExtension(descriptor: CallableDescriptor): Boolean {
if (!isTopLevelInPackage(descriptor, "rangeTo", "kotlin.ranges")) return false
val extensionReceiver = descriptor.extensionReceiverParameter ?: return false
return KotlinBuiltIns.isPrimitiveType(extensionReceiver.type)
}
fun isPrimitiveNumberDownTo(descriptor: CallableDescriptor): Boolean {
if (!isTopLevelInPackage(descriptor, "downTo", "kotlin.ranges")) return false
val extensionReceiver = descriptor.extensionReceiverParameter ?: return false
val extensionReceiverClassifier = extensionReceiver.type.constructor.declarationDescriptor
return isPrimitiveNumberClassDescriptor(extensionReceiverClassifier)
}
fun isPrimitiveNumberUntil(descriptor: CallableDescriptor): Boolean {
if (!isTopLevelInPackage(descriptor, "until", "kotlin.ranges")) return false
val extensionReceiver = descriptor.extensionReceiverParameter ?: return false
val extensionReceiverClassifier = extensionReceiver.type.constructor.declarationDescriptor
return isPrimitiveNumberClassDescriptor(extensionReceiverClassifier)
}
fun isArrayOrPrimitiveArrayIndices(descriptor: CallableDescriptor): Boolean {
if (!isTopLevelInPackage(descriptor, "indices", "kotlin.collections")) return false
val extensionReceiver = descriptor.extensionReceiverParameter ?: return false
val extensionReceiverType = extensionReceiver.type
return KotlinBuiltIns.isArray(extensionReceiverType) || KotlinBuiltIns.isPrimitiveArray(extensionReceiverType)
}
fun isCollectionIndices(descriptor: CallableDescriptor): Boolean {
if (!isTopLevelInPackage(descriptor, "indices", "kotlin.collections")) return false
val extensionReceiver = descriptor.extensionReceiverParameter ?: return false
val extensionReceiverType = extensionReceiver.type
return KotlinBuiltIns.isCollectionOrNullableCollection(extensionReceiverType)
}
fun isCharSequenceIndices(descriptor: CallableDescriptor): Boolean {
if (!isTopLevelInPackage(descriptor, "indices", "kotlin.text")) return false
val extensionReceiver = descriptor.extensionReceiverParameter ?: return false
val extensionReceiverType = extensionReceiver.type
return KotlinBuiltIns.isCharSequenceOrNullableCharSequence(extensionReceiverType)
}
fun isComparableRangeTo(descriptor: CallableDescriptor): Boolean {
if (!isTopLevelInPackage(descriptor, "rangeTo", "kotlin.ranges")) return false
val extensionReceiver = descriptor.original.extensionReceiverParameter ?: return false
val extensionReceiverTypeDescriptor = extensionReceiver.type.constructor.declarationDescriptor as? TypeParameterDescriptor ?: return false
val upperBoundType = extensionReceiverTypeDescriptor.upperBounds.singleOrNull() ?: return false
val upperBoundClassDescriptor = upperBoundType.constructor.declarationDescriptor as? ClassDescriptor ?: return false
if (!isTopLevelInPackage(upperBoundClassDescriptor, "Comparable", "kotlin")) return false
return true
}
fun isClosedRangeContains(descriptor: CallableDescriptor): Boolean {
if (descriptor.name.asString() != "contains") return false
val containingClassDescriptor = descriptor.containingDeclaration as? ClassDescriptor ?: return false
if (!isTopLevelInPackage(containingClassDescriptor, "ClosedRange", "kotlin.ranges")) return false
return true
}
fun isPrimitiveRangeContains(descriptor: CallableDescriptor): Boolean {
if (descriptor.name.asString() != "contains") return false
val dispatchReceiverType = descriptor.dispatchReceiverParameter?.type ?: return false
if (!isPrimitiveRange(dispatchReceiverType)) return false
return true
}
fun isPrimitiveNumberRangeExtensionContainsPrimitiveNumber(descriptor: CallableDescriptor): Boolean {
if (descriptor.name.asString() != "contains") return false
val extensionReceiverType = descriptor.extensionReceiverParameter?.type ?: return false
val rangeElementType = getRangeOrProgressionElementType(extensionReceiverType) ?: return false
if (!isPrimitiveNumberType(rangeElementType)) return false
val argumentType = descriptor.valueParameters.singleOrNull()?.type ?: return false
if (!isPrimitiveNumberType(argumentType)) return false
return true
}
private fun isPrimitiveNumberType(type: KotlinType) =
KotlinBuiltIns.isByte(type) ||
KotlinBuiltIns.isShort(type) ||
KotlinBuiltIns.isInt(type) ||
KotlinBuiltIns.isChar(type) ||
KotlinBuiltIns.isLong(type) ||
KotlinBuiltIns.isFloat(type) ||
KotlinBuiltIns.isDouble(type)
fun isClosedFloatingPointRangeContains(descriptor: CallableDescriptor): Boolean {
if (descriptor.name.asString() != "contains") return false
val containingClassDescriptor = descriptor.containingDeclaration as? ClassDescriptor ?: return false
if (!isTopLevelInPackage(containingClassDescriptor, "ClosedFloatingPointRange", "kotlin.ranges")) return false
return true
}
fun getClosedFloatingPointRangeElementType(rangeType: KotlinType): KotlinType? {
val classDescriptor = rangeType.constructor.declarationDescriptor as? ClassDescriptor ?: return null
if (!isTopLevelInPackage(classDescriptor, "ClosedFloatingPointRange", "kotlin.ranges")) return null
return rangeType.arguments.singleOrNull()?.type
}
private fun isTopLevelInPackage(descriptor: DeclarationDescriptor, name: String, packageName: String): Boolean {
if (name != descriptor.name.asString()) return false
val containingDeclaration = descriptor.containingDeclaration as? PackageFragmentDescriptor ?: return false
val packageFqName = containingDeclaration.fqName.asString()
return packageName == packageFqName
}
fun getAsmRangeElementTypeForPrimitiveRangeOrProgression(rangeCallee: CallableDescriptor): Type {
val rangeType = rangeCallee.returnType!!
getPrimitiveRangeElementType(rangeType)?.let {
return AsmTypes.valueTypeForPrimitive(it)
}
getPrimitiveProgressionElementType(rangeType)?.let {
return AsmTypes.valueTypeForPrimitive(it)
}
getClosedFloatingPointRangeElementType(rangeType)?.let {
when {
KotlinBuiltIns.isDouble(it) -> return Type.DOUBLE_TYPE
KotlinBuiltIns.isFloat(it) -> return Type.FLOAT_TYPE
else -> {}
}
}
throw AssertionError("Unexpected range type: $rangeType")
}

View File

@@ -20,7 +20,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.descriptors.FunctionDescriptor;
import org.jetbrains.kotlin.descriptors.synthetic.SyntheticMemberDescriptor;
import org.jetbrains.kotlin.load.java.sam.SamAdapterDescriptor;
import org.jetbrains.kotlin.load.java.descriptors.SamAdapterDescriptor;
import org.jetbrains.kotlin.synthetic.SamAdapterExtensionFunctionDescriptor;
public class SamCodegenUtil {

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.
@@ -105,14 +105,10 @@ public class ScriptCodegen extends MemberCodegen<KtScript> {
}
@Override
protected void generateSyntheticPartsBeforeBody() {
protected void generateSyntheticParts() {
generatePropertyMetadataArrayFieldIfNeeded(classAsmType);
}
@Override
protected void generateSyntheticPartsAfterBody() {
}
@Override
protected void generateKotlinMetadataAnnotation() {
generateKotlinClassMetadataAnnotation(scriptDescriptor, true);
@@ -162,7 +158,7 @@ public class ScriptCodegen extends MemberCodegen<KtScript> {
iv.load(0, classType);
int valueParamStart = context.getEarlierScripts().isEmpty() ? 1 : 2; // this + array of earlier scripts if not empty
int valueParamStart = context.getEarlierScripts().size() + 1;
List<ValueParameterDescriptor> valueParameters = scriptDescriptor.getUnsubstitutedPrimaryConstructor().getValueParameters();
for (ValueParameterDescriptor superclassParam: ctorDesc.getValueParameters()) {
@@ -189,20 +185,18 @@ public class ScriptCodegen extends MemberCodegen<KtScript> {
FrameMap frameMap = new FrameMap();
frameMap.enterTemp(OBJECT_TYPE);
for (ScriptDescriptor importedScript : context.getEarlierScripts()) {
frameMap.enter(importedScript, OBJECT_TYPE);
}
if (!context.getEarlierScripts().isEmpty()) {
int scriptsParamIndex = frameMap.enterTemp(AsmUtil.getArrayType(OBJECT_TYPE));
int offset = 1;
int earlierScriptIndex = 0;
for (ScriptDescriptor earlierScript : context.getEarlierScripts()) {
Type earlierClassType = typeMapper.mapClass(earlierScript);
iv.load(0, classType);
iv.load(scriptsParamIndex, earlierClassType);
iv.aconst(earlierScriptIndex++);
iv.aload(OBJECT_TYPE);
iv.checkcast(earlierClassType);
iv.putfield(classType.getInternalName(), context.getScriptFieldName(earlierScript), earlierClassType.getDescriptor());
}
for (ScriptDescriptor earlierScript : context.getEarlierScripts()) {
Type earlierClassType = typeMapper.mapClass(earlierScript);
iv.load(0, classType);
iv.load(offset, earlierClassType);
offset += earlierClassType.getSize();
iv.putfield(classType.getInternalName(), context.getScriptFieldName(earlierScript), earlierClassType.getDescriptor());
}
ExpressionCodegen codegen = new ExpressionCodegen(mv, frameMap, Type.VOID_TYPE, methodContext, state, this);
@@ -232,11 +226,6 @@ public class ScriptCodegen extends MemberCodegen<KtScript> {
else if (declaration instanceof KtClassOrObject) {
genClassOrObject((KtClassOrObject) declaration);
}
else if (declaration instanceof KtDestructuringDeclaration) {
for (KtDestructuringDeclarationEntry entry : ((KtDestructuringDeclaration) declaration).getEntries()) {
genSimpleMember(entry);
}
}
}
}
}

View File

@@ -27,7 +27,7 @@ import org.jetbrains.org.objectweb.asm.FieldVisitor
import org.jetbrains.org.objectweb.asm.MethodVisitor
abstract class SignatureCollectingClassBuilderFactory(
delegate: ClassBuilderFactory, val shouldGenerate: (JvmDeclarationOrigin) -> Boolean
delegate: ClassBuilderFactory
) : DelegatingClassBuilderFactory(delegate) {
protected abstract fun handleClashingSignatures(data: ConflictingJvmDeclarationsData)
@@ -57,17 +57,11 @@ abstract class SignatureCollectingClassBuilderFactory(
override fun newField(origin: JvmDeclarationOrigin, access: Int, name: String, desc: String, signature: String?, value: Any?): FieldVisitor {
signatures.putValue(RawSignature(name, desc, MemberKind.FIELD), origin)
if (!shouldGenerate(origin)) {
return AbstractClassBuilder.EMPTY_FIELD_VISITOR
}
return super.newField(origin, access, name, desc, signature, value)
}
override fun newMethod(origin: JvmDeclarationOrigin, access: Int, name: String, desc: String, signature: String?, exceptions: Array<out String>?): MethodVisitor {
signatures.putValue(RawSignature(name, desc, MemberKind.METHOD), origin)
if (!shouldGenerate(origin)) {
return AbstractClassBuilder.EMPTY_METHOD_VISITOR
}
return super.newMethod(origin, access, name, desc, signature, exceptions)
}

View File

@@ -19,6 +19,7 @@ package org.jetbrains.kotlin.codegen;
import com.intellij.psi.tree.IElementType;
import kotlin.Unit;
import kotlin.collections.ArraysKt;
import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
@@ -26,6 +27,8 @@ import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.builtins.PrimitiveType;
import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicMethods;
import org.jetbrains.kotlin.codegen.intrinsics.JavaClassProperty;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.impl.SyntheticFieldDescriptor;
@@ -178,35 +181,6 @@ public abstract class StackValue {
}
}
public static StackValue createDefaulValue(@NotNull Type type) {
if (type.getSort() == Type.OBJECT || type.getSort() == Type.ARRAY) {
return constant(null, type);
}
else {
return createDefaultPrimitiveValue(type);
}
}
private static StackValue createDefaultPrimitiveValue(@NotNull Type type) {
assert Type.BOOLEAN <= type.getSort() && type.getSort() <= Type.DOUBLE :
"'createDefaultPrimitiveValue' method should be called only for primitive types, but " + type;
Object value = 0;
if (type.getSort() == Type.BOOLEAN) {
value = Boolean.FALSE;
}
else if (type.getSort() == Type.FLOAT) {
value = new Float(0.0);
}
else if (type.getSort() == Type.DOUBLE) {
value = new Double(0.0);
}
else if (type.getSort() == Type.LONG) {
value = new Long(0);
}
return constant(value, type);
}
@NotNull
public static StackValue cmp(@NotNull IElementType opToken, @NotNull Type type, StackValue left, StackValue right) {
return BranchedValue.Companion.cmp(opToken, type, left, right);
@@ -515,11 +489,9 @@ public abstract class StackValue {
descriptor
);
StackValue extensionReceiver = genReceiver(receiver, codegen, resolvedCall, callableMethod, callExtensionReceiver, true);
return CallReceiver.generateCallReceiver(
resolvedCall, codegen, callableMethod,
dispatchReceiverParameter, dispatchReceiver,
extensionReceiverParameter, extensionReceiver
);
Type type = CallReceiver.calcType(resolvedCall, dispatchReceiverParameter, extensionReceiverParameter, codegen.typeMapper, callableMethod, codegen.getState());
assert type != null : "Could not map receiver type for " + resolvedCall;
return new CallReceiver(dispatchReceiver, extensionReceiver, type);
}
return receiver;
}
@@ -568,13 +540,14 @@ public abstract class StackValue {
}
@Contract("null -> false")
static boolean isLocalFunCall(@Nullable Callable callableMethod) {
private static boolean isLocalFunCall(@Nullable Callable callableMethod) {
return callableMethod != null && callableMethod.getGenerateCalleeType() != null;
}
public static StackValue receiverWithoutReceiverArgument(StackValue receiverWithParameter) {
if (receiverWithParameter instanceof CallReceiver) {
return ((CallReceiver) receiverWithParameter).withoutReceiverArgument();
CallReceiver callReceiver = (CallReceiver) receiverWithParameter;
return new CallReceiver(callReceiver.dispatchReceiver, none(), callReceiver.type);
}
return receiverWithParameter;
}
@@ -768,9 +741,9 @@ public abstract class StackValue {
}
}
public static class Constant extends StackValue {
private static class Constant extends StackValue {
@Nullable
public final Object value;
private final Object value;
public Constant(@Nullable Object value, Type type) {
super(type, false);
@@ -1085,7 +1058,8 @@ public abstract class StackValue {
Type lastParameterType = ArraysKt.last(setter.getParameterTypes());
coerce(topOfStackType, lastParameterType, v);
getCallGenerator().putValueIfNeeded(lastParameterType, StackValue.onStack(lastParameterType));
getCallGenerator().afterParameterPut(lastParameterType, StackValue.onStack(lastParameterType),
CollectionsKt.getLastIndex(setter.getValueParameterTypes()));
//Convention setter couldn't have default parameters, just getter can have it at last positions
//We should remove default parameters of getter from stack*/
@@ -1515,6 +1489,101 @@ public abstract class StackValue {
}
}
public static class CallReceiver extends StackValue {
private final StackValue dispatchReceiver;
private final StackValue extensionReceiver;
public CallReceiver(
@NotNull StackValue dispatchReceiver,
@NotNull StackValue extensionReceiver,
@NotNull Type type
) {
super(type, dispatchReceiver.canHaveSideEffects() || extensionReceiver.canHaveSideEffects());
this.dispatchReceiver = dispatchReceiver;
this.extensionReceiver = extensionReceiver;
}
@Nullable
public static Type calcType(
@NotNull ResolvedCall<?> resolvedCall,
@Nullable ReceiverParameterDescriptor dispatchReceiver,
@Nullable ReceiverParameterDescriptor extensionReceiver,
@NotNull KotlinTypeMapper typeMapper,
@Nullable Callable callableMethod,
@NotNull GenerationState state
) {
if (extensionReceiver != null) {
CallableDescriptor descriptor = resolvedCall.getCandidateDescriptor();
if (descriptor instanceof PropertyDescriptor &&
// hackaround: boxing changes behaviour of T.javaClass intrinsic
state.getIntrinsics().getIntrinsic((PropertyDescriptor) descriptor) != JavaClassProperty.INSTANCE
) {
ReceiverParameterDescriptor receiverCandidate = descriptor.getExtensionReceiverParameter();
assert receiverCandidate != null;
return typeMapper.mapType(receiverCandidate.getType());
}
return callableMethod != null ? callableMethod.getExtensionReceiverType() : typeMapper.mapType(extensionReceiver.getType());
}
else if (dispatchReceiver != null) {
CallableDescriptor descriptor = resolvedCall.getResultingDescriptor();
if (CodegenUtilKt.isJvmStaticInObjectOrClass(descriptor)) {
return Type.VOID_TYPE;
}
if (callableMethod != null) {
return callableMethod.getDispatchReceiverType();
}
// Extract the receiver from the resolved call, workarounding the fact that ResolvedCall#dispatchReceiver doesn't have
// all the needed information, for example there's no way to find out whether or not a smart cast was applied to the receiver.
DeclarationDescriptor container = descriptor.getContainingDeclaration();
if (container instanceof ClassDescriptor) {
return typeMapper.mapClass((ClassDescriptor) container);
}
return typeMapper.mapType(dispatchReceiver);
}
else if (isLocalFunCall(callableMethod)) {
return callableMethod.getGenerateCalleeType();
}
return Type.VOID_TYPE;
}
@Override
public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
StackValue currentExtensionReceiver = extensionReceiver;
boolean hasExtensionReceiver = extensionReceiver != none();
if (extensionReceiver instanceof StackValue.SafeCall) {
currentExtensionReceiver.put(currentExtensionReceiver.type, v);
currentExtensionReceiver = StackValue.onStack(currentExtensionReceiver.type);
}
dispatchReceiver.put(hasExtensionReceiver ? dispatchReceiver.type : type, v);
currentExtensionReceiver
.moveToTopOfStack(hasExtensionReceiver ? type : currentExtensionReceiver.type, v, dispatchReceiver.type.getSize());
}
@Override
public void dup(@NotNull InstructionAdapter v, boolean withReceiver) {
AsmUtil.dup(v, extensionReceiver.type, dispatchReceiver.type);
}
@NotNull
public StackValue getDispatchReceiver() {
return dispatchReceiver;
}
@NotNull
public StackValue getExtensionReceiver() {
return extensionReceiver;
}
}
public abstract static class StackValueWithSimpleReceiver extends StackValue {
public final boolean isStaticPut;

View File

@@ -18,6 +18,7 @@ package org.jetbrains.kotlin.codegen;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.codegen.inline.InlineCodegenUtil;
import org.jetbrains.org.objectweb.asm.MethodVisitor;
import org.jetbrains.org.objectweb.asm.Opcodes;
import org.jetbrains.org.objectweb.asm.tree.LocalVariableNode;
@@ -28,9 +29,6 @@ import org.jetbrains.org.objectweb.asm.util.TraceMethodVisitor;
import java.util.ArrayList;
import java.util.List;
import static org.jetbrains.kotlin.codegen.inline.InlineCodegenUtilsKt.getNodeText;
import static org.jetbrains.kotlin.codegen.inline.InlineCodegenUtilsKt.wrapWithMaxLocalCalc;
public abstract class TransformationMethodVisitor extends MethodVisitor {
private final MethodNode methodNode;
@@ -48,7 +46,7 @@ public abstract class TransformationMethodVisitor extends MethodVisitor {
this.delegate = delegate;
this.methodNode = new MethodNode(access, name, desc, signature, exceptions);
this.methodNode.localVariables = new ArrayList<>(5);
this.mv = wrapWithMaxLocalCalc(methodNode);
this.mv = InlineCodegenUtil.wrapWithMaxLocalCalc(methodNode);
}
@Override
@@ -72,7 +70,7 @@ public abstract class TransformationMethodVisitor extends MethodVisitor {
// So we just do it here
if (methodNode.instructions.size() == 0
// MethodNode does not create a list of variables for abstract methods, so we would get NPE in accept() instead
&& (!(delegate instanceof MethodNode) || methodNode.localVariables != null)
&& (!(delegate instanceof MethodNode) || (methodNode.access & Opcodes.ACC_ABSTRACT) == 0)
) {
List<LocalVariableNode> localVariables = methodNode.localVariables;
// visits local variables
@@ -85,7 +83,7 @@ public abstract class TransformationMethodVisitor extends MethodVisitor {
delegate.visitEnd();
}
catch (Throwable t) {
throw new CompilationException("Couldn't transform method node: " + getNodeText(methodNode), t, null);
throw new CompilationException("Couldn't transform method node: " + InlineCodegenUtil.getNodeText(methodNode), t, null);
}
}

View File

@@ -20,6 +20,7 @@ import org.jetbrains.kotlin.descriptors.annotations.Annotated
import org.jetbrains.kotlin.descriptors.annotations.AnnotatedImpl
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.name.FqName
interface WrappedAnnotated : Annotated {
val originalAnnotated: Annotated
@@ -33,6 +34,10 @@ class AnnotatedWithOnlyTargetedAnnotations(original: Annotated) : Annotated {
private class UseSiteTargetedAnnotations(private val additionalAnnotations: Annotations) : Annotations {
override fun isEmpty() = true
override fun findAnnotation(fqName: FqName) = null
override fun findExternalAnnotation(fqName: FqName) = null
override fun getUseSiteTargetedAnnotations() = getAdditionalTargetedAnnotations()
override fun getAllAnnotations() = getAdditionalTargetedAnnotations()
@@ -43,4 +48,4 @@ class AnnotatedWithOnlyTargetedAnnotations(original: Annotated) : Annotated {
}
}
class AnnotatedSimple(annotations: Annotations) : AnnotatedImpl(annotations)
class AnnotatedSimple(annotations: Annotations) : AnnotatedImpl(annotations)

View File

@@ -38,9 +38,8 @@ import org.jetbrains.kotlin.descriptors.annotations.Annotations;
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor;
import org.jetbrains.kotlin.fileClasses.FileClasses;
import org.jetbrains.kotlin.fileClasses.JvmFileClassesProvider;
import org.jetbrains.kotlin.load.java.sam.SamConstructorDescriptor;
import org.jetbrains.kotlin.load.java.descriptors.SamConstructorDescriptor;
import org.jetbrains.kotlin.load.kotlin.TypeMappingConfiguration;
import org.jetbrains.kotlin.name.ClassId;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.resolve.BindingContext;
@@ -104,20 +103,6 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
return recordClassForCallable(element, callableDescriptor, supertypes, name, null);
}
@NotNull
private ClassDescriptor recordClassForFunction(
@NotNull KtElement element,
@NotNull FunctionDescriptor functionDescriptor,
@NotNull String name,
@Nullable DeclarationDescriptor customContainer
) {
return recordClassForCallable(
element, functionDescriptor,
runtimeTypes.getSupertypesForClosure(functionDescriptor),
name, customContainer
);
}
@NotNull
private ClassDescriptor recordClassForCallable(
@NotNull KtElement element,
@@ -371,13 +356,26 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
@NotNull
private MutableClosure recordClosure(@NotNull ClassDescriptor classDescriptor, @NotNull String name) {
return CodegenBinding.recordClosure(bindingTrace, classDescriptor, peekFromStack(classStack), Type.getObjectType(name));
return CodegenBinding.recordClosure(
bindingTrace, classDescriptor, peekFromStack(classStack), Type.getObjectType(name), fileClassesProvider
);
}
private void recordLocalVariablePropertyMetadata(LocalVariableDescriptor variableDescriptor) {
KotlinType delegateType = JvmCodegenUtil.getPropertyDelegateType(variableDescriptor, bindingContext);
if (delegateType == null) return;
LocalVariableDescriptor delegateVariableDescriptor = new LocalVariableDescriptor(
variableDescriptor.getContainingDeclaration(),
Annotations.Companion.getEMPTY(),
variableDescriptor.getName(),
delegateType,
false,
false,
SourceElement.NO_SOURCE
);
bindingTrace.record(LOCAL_VARIABLE_DELEGATE, variableDescriptor, delegateVariableDescriptor);
LocalVariableDescriptor metadataVariableDescriptor = new LocalVariableDescriptor(
variableDescriptor.getContainingDeclaration(),
Annotations.Companion.getEMPTY(),
@@ -416,38 +414,12 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
runtimeTypes.getSupertypeForPropertyReference(variableDescriptor, variableDescriptor.isVar(), /* bound = */ false);
ClassDescriptor classDescriptor = recordClassForCallable(delegate, variableDescriptor, Collections.singleton(supertype), name);
recordClosure(classDescriptor, name);
Type containerType = getMetadataOwner(property);
List<VariableDescriptorWithAccessors> descriptors = bindingTrace.get(DELEGATED_PROPERTIES, containerType);
if (descriptors == null) {
descriptors = new ArrayList<>(1);
bindingTrace.record(DELEGATED_PROPERTIES, containerType, descriptors);
}
descriptors.add(variableDescriptor);
bindingTrace.record(DELEGATED_PROPERTY_METADATA_OWNER, variableDescriptor, containerType);
}
super.visitProperty(property);
nameStack.pop();
}
@NotNull
private Type getMetadataOwner(@NotNull KtProperty property) {
for (int i = classStack.size() - 1; i >= 0; i--) {
ClassDescriptor descriptor = classStack.get(i);
// The first "real" containing class (not a synthetic class for lambda) is the owner of the delegated property metadata
if (!(descriptor instanceof SyntheticClassDescriptorForLambda)) {
ClassId classId = DescriptorUtilsKt.getClassId(descriptor);
return classId != null
? AsmUtil.asmTypeByClassId(classId)
: CodegenBinding.getAsmType(bindingContext, descriptor);
}
}
return Type.getObjectType(FileClasses.getFileClassInternalName(fileClassesProvider, property.getContainingKtFile()));
}
@Override
public void visitNamedFunction(@NotNull KtNamedFunction function) {
FunctionDescriptor functionDescriptor = (FunctionDescriptor) bindingContext.get(DECLARATION_TO_DESCRIPTOR, function);
@@ -482,23 +454,18 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
jvmSuspendFunctionView
);
if (nameForClassOrPackageMember != null) {
nameStack.push(nameForClassOrPackageMember);
if (CoroutineCodegenUtilKt.containsNonTailSuspensionCalls(functionDescriptor, bindingContext)) {
if (nameForClassOrPackageMember != null) {
nameStack.push(nameForClassOrPackageMember);
}
processNamedFunctionWithClosure(function, functionDescriptor, functionDescriptor).setSuspend(true);
if (nameForClassOrPackageMember != null) {
nameStack.pop();
}
return;
}
String name = inventAnonymousClassName();
ClassDescriptor classDescriptor =
recordClassForFunction(function, functionDescriptor, name, functionDescriptor);
MutableClosure closure = recordClosure(classDescriptor, name);
closure.setSuspend(true);
super.visitNamedFunction(function);
if (nameForClassOrPackageMember != null) {
nameStack.pop();
}
return;
}
if (nameForClassOrPackageMember != null) {
@@ -507,18 +474,29 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
nameStack.pop();
}
else {
String name = inventAnonymousClassName();
ClassDescriptor classDescriptor = recordClassForFunction(function, functionDescriptor, name, null);
recordClosure(classDescriptor, name);
classStack.push(classDescriptor);
nameStack.push(name);
super.visitNamedFunction(function);
nameStack.pop();
classStack.pop();
processNamedFunctionWithClosure(function, functionDescriptor, null);
}
}
private MutableClosure processNamedFunctionWithClosure(
@NotNull KtNamedFunction function,
@NotNull FunctionDescriptor functionDescriptor,
@Nullable DeclarationDescriptor customContainer
) {
String name = inventAnonymousClassName();
Collection<KotlinType> supertypes = runtimeTypes.getSupertypesForClosure(functionDescriptor);
ClassDescriptor classDescriptor = recordClassForCallable(function, functionDescriptor, supertypes, name, customContainer);
MutableClosure closure = recordClosure(classDescriptor, name);
classStack.push(classDescriptor);
nameStack.push(name);
super.visitNamedFunction(function);
nameStack.pop();
classStack.pop();
return closure;
}
@Nullable
private String getNameForClassOrPackageMember(@NotNull DeclarationDescriptor descriptor) {
DeclarationDescriptor containingDeclaration = descriptor.getContainingDeclaration();

View File

@@ -24,6 +24,7 @@ import org.jetbrains.kotlin.codegen.SamType;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.codegen.when.WhenByEnumsMapping;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.fileClasses.JvmFileClassesProvider;
import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.psi.psiUtil.PsiUtilsKt;
@@ -48,7 +49,7 @@ public class CodegenBinding {
public static final WritableSlice<ClassDescriptor, Boolean> ENUM_ENTRY_CLASS_NEED_SUBCLASS = Slices.createSimpleSetSlice();
private static final WritableSlice<ClassDescriptor, Collection<ClassDescriptor>> INNER_CLASSES = Slices.createSimpleSlice();
public static final WritableSlice<ClassDescriptor, Collection<ClassDescriptor>> INNER_CLASSES = Slices.createSimpleSlice();
public static final WritableSlice<KtExpression, SamType> SAM_VALUE = Slices.createSimpleSlice();
@@ -59,19 +60,18 @@ public class CodegenBinding {
public static final WritableSlice<String, List<WhenByEnumsMapping>> MAPPINGS_FOR_WHENS_BY_ENUM_IN_CLASS_FILE =
Slices.createSimpleSlice();
public static final WritableSlice<VariableDescriptor, VariableDescriptor> LOCAL_VARIABLE_DELEGATE =
Slices.createSimpleSlice();
public static final WritableSlice<VariableDescriptor, VariableDescriptor> LOCAL_VARIABLE_PROPERTY_METADATA =
Slices.createSimpleSlice();
public static final WritableSlice<FunctionDescriptor, FunctionDescriptor> SUSPEND_FUNCTION_TO_JVM_VIEW =
Slices.createSimpleSlice();
public static final WritableSlice<ValueParameterDescriptor, ValueParameterDescriptor> PARAMETER_SYNONYM =
Slices.createSimpleSlice();
public static final WritableSlice<Type, List<VariableDescriptorWithAccessors>> DELEGATED_PROPERTIES =
Slices.createSimpleSlice();
public static final WritableSlice<VariableDescriptorWithAccessors, Type> DELEGATED_PROPERTY_METADATA_OWNER =
Slices.createSimpleSlice();
public static final WritableSlice<VariableDescriptor, VariableDescriptor> LOCAL_VARIABLE_PROPERTY_METADATA =
Slices.createSimpleSlice();
static {
BasicWritableSlice.initSliceDebugNames(CodegenBinding.class);
}
@@ -150,7 +150,8 @@ public class CodegenBinding {
@NotNull BindingTrace trace,
@NotNull ClassDescriptor classDescriptor,
@Nullable ClassDescriptor enclosing,
@NotNull Type asmType
@NotNull Type asmType,
@NotNull JvmFileClassesProvider fileClassesManager
) {
KtElement element = (KtElement) DescriptorToSourceUtils.descriptorToDeclaration(classDescriptor);
assert element != null : "No source element for " + classDescriptor;
@@ -212,7 +213,7 @@ public class CodegenBinding {
sortedAnswer.sort(Comparator.comparing((KtFile file) -> {
VirtualFile virtualFile = file.getVirtualFile();
assert virtualFile != null : "VirtualFile is null for KtFile: " + file.getName();
assert virtualFile != null : "VirtualFile is null for JetFile: " + file.getName();
return virtualFile.getPath();
}));
@@ -226,6 +227,32 @@ public class CodegenBinding {
return type;
}
@NotNull
public static Collection<ClassDescriptor> getAllInnerClasses(
@NotNull BindingContext bindingContext, @NotNull ClassDescriptor outermostClass
) {
Collection<ClassDescriptor> innerClasses = bindingContext.get(INNER_CLASSES, outermostClass);
if (innerClasses == null || innerClasses.isEmpty()) return Collections.emptySet();
Set<ClassDescriptor> allInnerClasses = new HashSet<>();
Deque<ClassDescriptor> stack = new ArrayDeque<>(innerClasses);
do {
ClassDescriptor currentClass = stack.pop();
if (allInnerClasses.add(currentClass)) {
Collection<ClassDescriptor> nextClasses = bindingContext.get(INNER_CLASSES, currentClass);
if (nextClasses != null) {
for (ClassDescriptor nextClass : nextClasses) {
stack.push(nextClass);
}
}
}
}
while (!stack.isEmpty());
return allInnerClasses;
}
@NotNull
public static VariableDescriptor getDelegatedLocalVariableMetadata(
@NotNull VariableDescriptor variableDescriptor,

View File

@@ -17,20 +17,16 @@
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.FieldOwnerContext
import org.jetbrains.kotlin.codegen.context.PackageContext
import org.jetbrains.kotlin.codegen.coroutines.unwrapInitialDescriptorForSuspendFunction
import org.jetbrains.kotlin.codegen.inline.ReificationArgument
import org.jetbrains.kotlin.codegen.intrinsics.TypeIntrinsics
import org.jetbrains.kotlin.codegen.signature.JvmSignatureWriter
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
@@ -47,13 +43,13 @@ import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils.isSubclass
import org.jetbrains.kotlin.resolve.annotations.hasJvmStaticAnnotation
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import org.jetbrains.kotlin.resolve.scopes.receivers.TransientReceiver
import org.jetbrains.kotlin.serialization.deserialization.PLATFORM_DEPENDENT_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.types.ErrorUtils
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
@@ -243,9 +239,8 @@ fun reportTarget6InheritanceErrorIfNeeded(
state.diagnostics.report(
ErrorsJvm.TARGET6_INTERFACE_INHERITANCE.on(
classElement, classDescriptor, key,
value.joinToString(separator = "\n", prefix = "\n") {
Renderers.COMPACT.render(JvmCodegenUtil.getDirectMember(it), RenderingContext.Empty)
}
value.map { Renderers.COMPACT.render(JvmCodegenUtil.getDirectMember(it), RenderingContext.Empty) }.
joinToString(separator = "\n", prefix = "\n")
)
)
}
@@ -292,10 +287,14 @@ fun calcTypeForIEEE754ArithmeticIfNeeded(expression: KtExpression?, bindingConte
val dataFlow = DataFlowValueFactory.createDataFlowValue(expression!!, ktType, bindingContext, descriptor)
val stableTypes = bindingContext.getDataFlowInfoBefore(expression).getStableTypes(dataFlow)
return stableTypes.firstNotNullResult {
when {
KotlinBuiltIns.isDoubleOrNullableDouble(it) -> TypeAndNullability(Type.DOUBLE_TYPE, TypeUtils.isNullableType(it))
KotlinBuiltIns.isFloatOrNullableFloat(it) -> TypeAndNullability(Type.FLOAT_TYPE, TypeUtils.isNullableType(it))
else -> null
if (KotlinBuiltIns.isDoubleOrNullableDouble(it)) {
TypeAndNullability(Type.DOUBLE_TYPE, TypeUtils.isNullableType(it))
}
else if (KotlinBuiltIns.isFloatOrNullableFloat(it)) {
TypeAndNullability(Type.FLOAT_TYPE, TypeUtils.isNullableType(it))
}
else {
null
}
}
}
@@ -378,45 +377,3 @@ fun initializeVariablesForDestructuredLambdaParameters(codegen: ExpressionCodege
}
fun <D : CallableDescriptor> D.unwrapFrontendVersion() = unwrapInitialDescriptorForSuspendFunction()
inline fun FrameMap.useTmpVar(type: Type, block: (index: Int) -> Unit) {
val index = enterTemp(type)
block(index)
leaveTemp(type)
}
fun InstructionAdapter.generateNewInstanceDupAndPlaceBeforeStackTop(
frameMap: FrameMap,
topStackType: Type,
newInstanceInternalName: String
) {
frameMap.useTmpVar(topStackType) { index ->
store(index, topStackType)
anew(Type.getObjectType(newInstanceInternalName))
dup()
load(index, topStackType)
}
}
fun extractReificationArgument(type: KotlinType): Pair<TypeParameterDescriptor, ReificationArgument>? {
var type = type
var arrayDepth = 0
val isNullable = type.isMarkedNullable
while (KotlinBuiltIns.isArray(type)) {
arrayDepth++
type = type.arguments[0].type
}
val parameterDescriptor = TypeUtils.getTypeParameterDescriptorOrNull(type) ?: return null
return Pair(parameterDescriptor, ReificationArgument(parameterDescriptor.name.asString(), isNullable, arrayDepth))
}
fun unwrapInitialSignatureDescriptor(function: FunctionDescriptor): FunctionDescriptor =
function.initialSignatureDescriptor ?: function
fun ExpressionCodegen.generateCallReceiver(rangeCall: ResolvedCall<out CallableDescriptor>): StackValue =
generateReceiverValue(rangeCall.extensionReceiver ?: rangeCall.dispatchReceiver!!, false)
fun ExpressionCodegen.generateCallSingleArgument(rangeCall: ResolvedCall<out CallableDescriptor>): StackValue =
gen(ExpressionCodegen.getSingleArgumentExpression(rangeCall)!!)

View File

@@ -25,7 +25,7 @@ import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.load.java.JavaVisibilities;
import org.jetbrains.kotlin.load.java.sam.SamConstructorDescriptor;
import org.jetbrains.kotlin.load.java.descriptors.SamConstructorDescriptor;
import org.jetbrains.kotlin.psi.KtFile;
import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.storage.LockBasedStorageManager;
@@ -37,7 +37,7 @@ import java.util.*;
import static org.jetbrains.kotlin.codegen.AsmUtil.getVisibilityAccessFlag;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isNonDefaultInterfaceMember;
import static org.jetbrains.kotlin.descriptors.annotations.AnnotationUtilKt.isEffectivelyInlineOnly;
import static org.jetbrains.kotlin.descriptors.annotations.AnnotationUtilKt.isInlineOnlyOrReifiable;
import static org.jetbrains.org.objectweb.asm.Opcodes.ACC_PRIVATE;
import static org.jetbrains.org.objectweb.asm.Opcodes.ACC_PROTECTED;
@@ -248,9 +248,10 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
@NotNull PackageFragmentDescriptor descriptor,
@NotNull Type multifileClassType,
@NotNull Type filePartType,
@NotNull Type filePartInitializerType,
@NotNull KtFile sourceFile
) {
return new MultifileClassPartContext(descriptor, this, multifileClassType, filePartType, sourceFile);
return new MultifileClassPartContext(descriptor, this, multifileClassType, filePartType, filePartInitializerType, sourceFile);
}
@NotNull
@@ -639,7 +640,7 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
boolean withinInline,
boolean isSuperCall
) {
if (isEffectivelyInlineOnly(unwrappedDescriptor)) return false;
if (isInlineOnlyOrReifiable(unwrappedDescriptor)) return false;
return isSuperCall && withinInline ||
(accessFlag & ACC_PRIVATE) != 0 ||

View File

@@ -55,12 +55,9 @@ public interface LocalLookup {
boolean idx = localLookup != null && localLookup.lookupLocal(vd);
if (!idx) return null;
KotlinType delegateType =
vd instanceof VariableDescriptorWithAccessors
? JvmCodegenUtil.getPropertyDelegateType((VariableDescriptorWithAccessors) vd, state.getBindingContext())
: null;
VariableDescriptor delegateVariableDescriptor = state.getBindingContext().get(LOCAL_VARIABLE_DELEGATE, vd);
Type sharedVarType = state.getTypeMapper().getSharedVarType(vd);
Type localType = state.getTypeMapper().mapType(delegateType != null ? delegateType : vd.getType());
Type localType = state.getTypeMapper().mapType(delegateVariableDescriptor != null ? delegateVariableDescriptor : vd);
Type type = sharedVarType != null ? sharedVarType : localType;
String fieldName = "$" + vd.getName();

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