Compare commits

..

188 Commits

Author SHA1 Message Date
Dmitry Jemerov
812ea5f778 typo 2017-06-12 19:15:16 +02:00
Dmitry Jemerov
bce8e22401 Sort plugins before uploading 2017-06-12 19:10:56 +02:00
Dmitry Jemerov
003a616079 Changelog for 1.1.2-x 2017-06-12 18:25:16 +02:00
Sergey Igushkin
38b866df6b (minor) Fix after cherry-pick with missing refactoring commit 2017-06-07 15:07:00 +03:00
Sergey Igushkin
ea378096d1 (minor) Improve exception message in case no Android plugin was found
(cherry picked from commit df3b8e8)

(cherry picked from commit 4490b9b)
2017-06-06 16:54:56 +03:00
Sergey Igushkin
e035bdc19f Fix for the Databinding issue where the kapt task started too early, not
letting the Databinding pre-process the project.

(cherry picked from commit efffda2)

(cherry picked from commit 8da5834)
2017-06-06 16:54:42 +03:00
Sergey Igushkin
ba9b7dc192 Add support for com.android.feature plugin.
(cherry picked from commit 495f4b1)

(cherry picked from commit c42fa4b)
2017-06-06 16:54:20 +03:00
Sergey Igushkin
7f83c67898 Fix UnsupportedOperationException caused by mutation of FileCollection 2017-05-29 20:23:10 +03:00
Alexey Tsvetkov
3390631696 Copy actual .gitignore from master
.gitignore should contain patterns for Gradle build dirs
2017-05-26 14:47:40 +03:00
Alexey Tsvetkov
b8ccc1a6ca Refactor Gradle tests with Jack
Jack is deprecated and Kotlin Gradle plugin throws,
so one test checking that build is failing with the exception
is enough.
2017-05-26 14:47:40 +03:00
Alexey Tsvetkov
e8767c0dbf Minor: simplify expression 2017-05-26 14:47:39 +03:00
Alexey Tsvetkov
caf769de3f Simplify friend paths configuration 2017-05-26 14:47:39 +03:00
Sergey Igushkin
8aadaef00e Various fixes
* Expose internals as public to use them in the agp25 source set
* Refactor of Android25ProjectHandler.kt
* Fix Kapt3 for non-Android projects

(cherry picked from commit 344512a)
2017-05-26 14:47:38 +03:00
Sergey Igushkin
4a32258c6d Fix Kapt task depending on compileKotlin because of incorrect filtering
of compileJava dependencies

(cherry picked from commit 9a2c3b0)
2017-05-24 11:29:51 +03:00
Alexey Tsvetkov
caec9fdcb8 Add missing Gradle configuration for deployment to sonatype 2017-05-23 21:48:16 +03:00
Dmitry Jemerov
a61d8c0fbb Add module documentation for kotlin.test
(cherry picked from commit 927cd04)
2017-05-19 19:52:49 +02:00
Alexey Tsvetkov
72dd2e4b64 Publish javadoc.jar and sources.jar for libraries projects built with Gradle
Maven central will not publish modules without these artifacts
2017-05-19 16:39:20 +03:00
Alexey Tsvetkov
56a9086248 Update gradle wrapper permissions
It was not executable on linux
2017-05-19 15:54:59 +03:00
Sergey Igushkin
fffe2e812a Add a Gradle wrapper and a dummy buildscript to libraries/
(cherry picked from commit 9b04548)
2017-05-19 15:35:17 +03:00
Sergey Igushkin
341e9543c3 Use the Google Maven repository instead of local preview.
(cherry picked from commit 4279335)

(cherry picked from commit 0e8b850)
2017-05-19 15:35:06 +03:00
Alexey Tsvetkov
2e15fe7e19 Minor: fix 'location' nullability in MessageCollector#report
In master `location` is nullable

(cherry picked from commit 024c555)
2017-05-19 15:34:54 +03:00
Alexander Udalov
58444eb769 Support .jar archives in friend paths (for internal visibility)
(cherry picked from commit 668e53a)
2017-05-19 15:34:40 +03:00
Sergey Igushkin
3a57737379 (minor) Fix missing dependency on JUnit
(cherry picked from commit 7ad5d04)
2017-05-19 15:34:24 +03:00
Sergey Igushkin
608e17ca16 Fix friend paths configuration with the new API for compile*Test tasks
Add lazy `friendClasspathEntries` to KotlinCompile
Set `friendClasspathEntries` in the Android25Pro
Change to AGP 3.0.0-alpha1;

(cherry picked from commit 1d6dd5c)

(cherry picked from commit 6cdf501)
2017-05-19 15:34:11 +03:00
Sergey Igushkin
e4167473e9 Fix registering the non-existent Kapt3 classes directory as bytecode if
Kapt3 is disabled.

(cherry picked from commit 692e23c)

(cherry picked from commit 1cbdb6c)
2017-05-19 15:34:01 +03:00
Sergey Igushkin
776faec1e2 Change the legacy API threshold to 2.5.0
(cherry picked from commit fca2e23)

(cherry picked from commit 9394d15)
2017-05-19 15:33:46 +03:00
Sergey Igushkin
1b7f57c84e Tasks wiring improvements & Kapt3 integration through variant wrapping
(cherry picked from commit b84e1ad)

(cherry picked from commit b7784b6)
2017-05-19 15:33:35 +03:00
Sergey Igushkin
8878843a16 Task wiring
* Generalized tasks wiring
* Moved the old implementation to LegacyAndroidAndroidProjectHandler.kt
* Added an implementation with the new AGP API

(cherry picked from commit 1b4592d)

(cherry picked from commit 50a75d4)
2017-05-19 15:33:19 +03:00
Sergey Igushkin
777d81c351 Add prototype against the new AGP API
* Add a separate Gradle source set, that is compiled against the new
  versions of AGP and Gradle

* Separate the public AGP API usages from the old internal API usages
  in KotlinPlugin.kt -- see AbstractAndroidProjectHandler

* Implement Android25ProjectHandler with the new AGP API, wired it
  to KotlinAndroidPlugin through reflection

(cherry picked from commit e6dbf54)

(cherry picked from commit 88e3d4b)
2017-05-19 15:33:06 +03:00
Sergey Igushkin
48e75bf869 Fix rootDir mis-use in commonConfiguration.gradle:
replace with `kotlin_root`, that is set in the projects

(cherry picked from commit e4b6a22)

(cherry picked from commit 2ec0661)
2017-05-19 15:32:51 +03:00
Sergey Igushkin
a203e7e129 Gradle build fixes & improvements:
* Fix Java not compiled in kotlin-gradle-plugin Kotlin source set
* Fix the integration tests running under Java 6
* Fix kotlin-gradle-subplugin-example not being installed -- needed
  for a test
* Fix Android tests being always excluded
* Move versions out of `build.gradle` (x2) to a common `versions.gradle`
* Move JDK, dist and bootstrap to `commonConfiguration.gradle`
* Build `kotlin-gradle-plugin` with JDK_18

(cherry picked from commit 9a18f45)

(cherry picked from commit 1bdbbe0)
2017-05-19 15:32:40 +03:00
Sergey Igushkin
c63562e956 Gradle plugins migration to Gradle build
* Add gradle-tools subproject
* Add Gradle buildscripts to the related projects
* Remove the projects from the libraries pom.xml
* Move AndroidGradleWrapper.groovy to separate source root
* Changed artifact dependencies to project dependencies where needed
* Extract common configuration into commonConfiguration.gradle
* (convert functions to closures to be able to call them)
* Refactor DSL usage
* Replace `project.properties` with `findProperty`
* Unify Gradle wrapper between `libraries` and `gradle-tools`
(as a temporary solution, just made the wrapper files the same)

(cherry picked from commit 200b326)

(cherry picked from commit d00b3ef)
2017-05-19 15:32:24 +03:00
Ilya Gorbunov
c35d7905a0 Use JDK_16 as jdkHome when building runtime for dist
#KT-17872 Fixed
2017-05-12 21:30:10 +03:00
Vyacheslav Gerasimov
ed04194185 Update changelog for 1.1.2-2 2017-04-28 16:10:56 +03:00
Yan Zhulanow
7f8c57a2e5 Android Extensions: Fix availability in Android/JPS projects (KT-17610) 2017-04-27 21:23:34 +03:00
Denis Zharkov
7e26cc23aa Fix callable reference resolution regression
The regression appeared after
b5a8ffaddc
when we started trying both static and member methods until
first success and when there is no successful
we were just leaving the last one (e.g. private member)

But the actual problem is that we were commiting the trace
in case of single (but incorrect) result in resolution mode of
SHAPE_FUNCTION_ARGUMENTS when we couldn't yet choose the
correct static method

Also we shouldn't choose a shape for callable reference
using only the knowledge that result is single:
it may lead to the wrong inference result
(see test with Pattern::compile)

 #KT-17597 Fixed
2017-04-27 16:41:08 +03:00
Vyacheslav Gerasimov
3451bc250c Remove from changelog items about multiplatform 2017-04-26 11:27:41 +03:00
Vyacheslav Gerasimov
c9ab1f7521 Prettify changelog for 1.1.2 again 2017-04-25 17:27:30 +03:00
Vyacheslav Gerasimov
53e9f2caef Prettify changelog for 1.1.2 2017-04-25 16:55:27 +03:00
Dmitry Petrov
2ff7e27634 Turn off captured vars optimization in 1.1.2 2017-04-25 14:56:32 +03:00
Vyacheslav Gerasimov
8c8ed411c6 Update 1.1.2 changelog 2017-04-24 14:06:32 +03:00
Sergey Igushkin
e6e7f334bd Changed to prepending annotation processor path instead of appending it
to classpath and existing annotation processors.

(cherry picked from commit 2360d5f)
2017-04-20 20:37:30 +03:00
Pavel V. Talanov
1775856d8e 1.1.2: turn off lighter classes for classes and objects 2017-04-20 15:46:00 +03:00
Pavel V. Talanov
df423cfb61 Light classes: do not rely on dummy resolve for members with DeprecationLevel.HIDDEN
Use heuristic psi check to determine such cases
2017-04-20 15:37:34 +03:00
Dmitry Jemerov
85033abc7c Correctly honor expected type when converting string templates to UAST
#KT-17315 Fixed
 #KT-17316 Fixed

(cherry picked from commit 03cef30)
2017-04-19 11:47:51 +02:00
Ilya Chernikov
2ebfe809b3 Relax error reporting on script dependencies resolving
to avoid exceptions reported on the gradle model problems, e.g. missing
dependencies
2017-04-18 19:58:49 +02:00
Ilya Chernikov
a682d35edd Attempt to eliminate crashes if script template is broken
Attempts to fix issues similar to EA-100334 completely
2017-04-18 14:15:31 +02:00
Ilya Chernikov
81f6ea621e Restore another part of script template resolving for even older legacy code
complements d284979
Fixes EA-100334
2017-04-18 12:19:33 +02:00
Pavel V. Talanov
1b55bbc5da Codegen: fix NPE in NO_ANNOTATION_VISITOR
EA-100245 fixed
2017-04-17 14:07:22 +03:00
Pavel V. Talanov
0b7576f246 Light class codegen: do not apply compiler plugins
Applying plugins leads to failures when matching members in LazyLightClassDataHolder
    because plugins rely on analysis results
This decision has its drawbacks (java won't see results of plugin execution)
    but more work on light classes is needed if we want to support this usecase
We can argue that plugins should only generate synthetic members
    but there is no such restriction atm
2017-04-17 14:07:20 +03:00
Pavel V. Talanov
30fb24911c KtLazyLightClass: do not store references to LightClassDataHolder
Otherwise any cached reference to light class can lead to severe memory leaks in IDE
    since LightClassBuiderResult holds GenerationState which holds ModuleDescriptor
2017-04-17 14:07:18 +03:00
Pavel V. Talanov
6f69a9c96e IDELightClassContexts#isDummyResolveApplicable: add missing check
Missing check caused exact resolve being applied to every class that had 'equals' overridden
2017-04-17 14:07:15 +03:00
Pavel V. Talanov
90db318cc7 PsiBasedClassResolver: get default imports without resolution facade
Using DefaultImportProvider is expensive in this scenario
2017-04-17 14:07:13 +03:00
Pavel V. Talanov
4d2e9dd070 TargetPlatform#getDefaultImports(): cache result in all implementations 2017-04-17 14:07:11 +03:00
Pavel V. Talanov
9ab9fb45fb Minor: fix erroneous refactoring 2017-04-17 14:07:09 +03:00
Alexey Tsvetkov
22514a132e Delete daemon client file when Gradle process stops
#KT-17177 fixed
2017-04-13 23:05:37 +03:00
Alexey Tsvetkov
6dbe3ae123 Minor: rename test KotlinDaemonAdvaced->KotlinDaemonIT 2017-04-13 23:05:32 +03:00
Ilya Chernikov
d28497987d Restore parts of the template resolving code in the compiler...
that was moved to the script-runtime, that it a row caused the incompatibility
with old GSK implementations. Now the legacy template resolving related code
is restored, marked obsolete and wrapped for compatibility with the new code.
2017-04-12 17:57:48 +02:00
Vyacheslav Gerasimov
9ebdd5ebaf Update changelog for 1.1.2 EAP 2 2017-04-11 15:45:58 +03:00
Ilya Gorbunov
cae95e5247 Rebuild sources for kotlin-daemon-client and compiler-client-embeddable in maven build
Do not build these sources in ant.
Do not require them as artifact dependencies.

(cherry picked from commit e7dc7ec)
2017-04-11 03:02:34 +03:00
Ilya Gorbunov
e56ea84084 Do not produce javadoc for kotlin-compiler and do not attach it to maven artifacts
(cherry picked from commit c740c0b177)
2017-04-11 02:33:34 +03:00
Anton Bannykh
8fa55ccbde JS: polyfill ArrayBuffer.isView in order to support PhantomJS
(cherry picked from commit 3eb5ce7d9a)
2017-04-11 02:33:25 +03:00
Yan Zhulanow
6f2ab29889 Kapt: Support specifying javac options (KT-17245) 2017-04-10 22:47:35 +03:00
Sergey Igushkin
708b813ef2 Fixed duplicated kapt options caused by multiple call to args setup
Separated kapt args from other plugin options.

Issues: #KT-16965 Fixed

Fix indentation

(cherry picked from commit 8cdb08c)
2017-04-10 21:54:28 +03:00
Sergey Igushkin
15cd5411de Implemented resolving the compiler jar using the class loader
Added resolving the compiler jar using the class loader urls as the
first step with the fallback to the original resolution method. Also
helps if the compiler is not present in the classpath dependencies.

Issues: #KT-16580 Fixed

Changed to getting plugin version from the applied plugin instead of
the plugin JAR name.

Removed unnecessary working with version of AbstractKotlinPlugin.

(cherry picked from commit ea3adb0)
2017-04-10 21:54:07 +03:00
Sergey Igushkin
093c2bfeda Filling in and reverting annotationProcessor
Added reverting processor path back.
Appending processor path instead of setting it.

Issues: #KT-17255 Fixed

(cherry picked from commit 843844b)

Added a test checking that -processorpath is set for all Gradle versions

(cherry picked from commit bda59e5)
2017-04-10 21:53:37 +03:00
Sergey Igushkin
8746113e08 Refactoring in AnnotationProcessingManager.kt.
(cherry picked from commit 64278a0)
2017-04-10 21:53:14 +03:00
Sergey Igushkin
8e2d24341f Partial fix for the processor path not being set up properly.
Issues: #KT-17255

(cherry picked from commit 80daae9)
2017-04-10 21:52:59 +03:00
Alexey Tsvetkov
79c52eeaa0 Avoid changing java.rmi.server.hostname property 2017-04-10 20:42:53 +03:00
Alexey Tsvetkov
4221fc8813 Import 'implement' dependency of platform project transitively
#KT-16926 fixed
2017-04-10 20:42:47 +03:00
Alexey Tsvetkov
97b66cdeb6 Minor: fix maven IC tests with custom local repository 2017-04-10 20:42:39 +03:00
Alexey Tsvetkov
478caf27e1 Invalidate cache version if corresponding file is empty
Sometimes an expression `versionFile.readText()`
returns an empty string, so that `toInt()` fails
with `NumberFormatException`.

It can happen in with both JPS and Gradle.
I could not reproduce the problem,
and it seems to be impossible (under normal circumstances),
because we always write a non-empty string,
and the file is checked to exist before reading.
Maybe it could be caused by an FS error.

The only "solution" to the problem I could think
is to swallow the exception, and assume
that cache version is not valid (so it would cause a rebuild of a module).

    #KT-17125 fixed
2017-04-10 20:42:33 +03:00
Alexey Tsvetkov
4f6edbaf69 Fix printing daemon client messages
Fixing the problem introduced in the commit 9819de1abd:
the daemon client messages should be reported
when the debug log level is enabled
or when the connection not successful

    #KT-17199 fixed
2017-04-10 20:42:28 +03:00
Alexey Tsvetkov
b7e1cd95a6 Provide incremental compilation for Maven
#KT-11916 fixed

To use the IC either:
1. set the `kotlin.compiler.incremental` property to `true` in a pom.xml:
```
<properties>
    <kotlin.compiler.incremental>true</kotlin.compiler.incremental>
</properties>
```
2. pass the `kotlin.compiler.incremental` property in a command line:
```
mvn install -Dkotlin.compiler.incremental=true
```

When IC is on Kotlin plugin is expected to print the warning in the log:
```
Using experimental Kotlin incremental compilation
```

After each call an incremental compiler will also log how many files it has compiled:
```
Compiled %SOME_NUMBER% Kotlin files using incremental compiler
```

Note that the first build will be non-incremental.

For more diagnostic information (such as an exact list of compiled files) use the `kotlin.compiler.incremental.log.level` system property:
```
mvn install -Dkotlin.compiler.incremental=true -Dkotlin.compiler.incremental.log.level=info
```

To force the rebuild just run the 'clean' goal:
```
mvn clean install
```
2017-04-10 20:42:20 +03:00
Mikhael Bogdanov
05fb47531a Delete clean reference instructions on dereferencing captured variables
Codegen generates clean instructions for ref values (captured vars)
on block exit so we should delete them on dereferencing captured values.

  #KT-17200 FIXED

(cherry picked from commit b51cb9a)
2017-04-10 15:49:46 +02:00
Mikhael Bogdanov
59caeff3db Don't eliminate redundant casts to multi-dimension arrays
Dex doesn't recognize ANEWARRAY [Ljava/lang/Object; types as Object [][], but Object [].
It's not clear is it bug in dex or not

 #KT-17200 InProgress

(cherry picked from commit f3e2abf)
2017-04-10 15:49:41 +02:00
Vyacheslav Gerasimov
adc74268f4 Implement getTypeElement for UastKotlinPsiVariable
#KT-16849 Fixed

(cherry picked from commit 107879a)
2017-04-10 12:54:44 +03:00
Vyacheslav Gerasimov
63e109b061 Register Android api quickfixes for inlined api inspection
#KT-14857 Fixed

(cherry picked from commit 1d134ff)
2017-04-10 12:54:44 +03:00
Vyacheslav Gerasimov
e73f70d323 Fix NoSwingUnderWriteActionException in KotlinAndroidAddStringResource
(cherry picked from commit 70d24d0)
2017-04-10 12:54:43 +03:00
Pavel V. Talanov
591b972bfd Light classes: do not rely on dummy context when data class autogenerated members conflict with declared members
Fix related issues with nested classes
2017-04-09 15:33:46 +03:00
Pavel V. Talanov
f113624180 Light class test: avoid checking method visibility when NoLaziness is not specified
Allows to avoid putting NoLaziness flag on every test that mentions 'override' modifier
2017-04-09 15:33:44 +03:00
Pavel V. Talanov
0ca1481fd6 Light classes: generate ACC_STATIC for DefaultImpls classes
To provide consistency between light classes and their delegates

IdeLightClass#testExtendingInterfaceWithDefaultImpls still failing since
    we do not generate implementations delegating to DefaultImpls of superinterfaces
2017-04-09 15:33:42 +03:00
Pavel V. Talanov
84ca3735ff Light classes: test consistency for inner classes 2017-04-09 15:33:40 +03:00
Pavel V. Talanov
99f9b5e4a9 Light class builder: do not generate methods delegating to DefaultImpls in kotlin classes
Class APIs from java point of view stays the same so we can avoid generating those methods
Otherwise we have to calculate all supertypes when getMethods() is called,
    which imposes severe performance penalties
We have to pretend these methods are not 'abstract' (also we consider them 'default' for safety)
    so java highlighting does not report "class should be abstract" for all inheritors
We have to manually report "class should be abstract" on some of the java inheritors,
    specifically those that are implementing interfaces directly
	    as opposed to extending kotlin classes implementing those interfaces
2017-04-09 15:33:38 +03:00
Pavel V. Talanov
6a4e7c8c3e Minor, refactor: Move hasBody() to KtProperty 2017-04-09 15:14:15 +03:00
Pavel V. Talanov
716efa9ba2 LazyLightClassDataHolder: minor, improve diagnostics 2017-04-09 15:14:12 +03:00
Pavel V. Talanov
4fe07270e6 AbstractIdeLightClassTest: minor, refactor 2017-04-09 15:14:10 +03:00
Vyacheslav Gerasimov
ecd828e479 Fix MovePropertyToConstructorIntention applicability and type rendering
#KT-17238 Fixed

(cherry picked from commit 6b92420)
2017-04-07 14:51:34 +03:00
Ilya Chernikov
98d842841a Fix environment arg parsing regex - avoid SO on the long strings 2017-04-06 18:51:59 +02:00
Ilya Chernikov
ab82ab0a9b minor: Fix daemon shutdown livelock
due to wrong minimal aliveness, daemon was in some situations livelocked
in the last session state on shutdown.
2017-04-06 10:23:03 +02:00
Ilya Chernikov
b4af84f44e Fix CRLF handling in source-sections plugin 2017-04-06 10:23:02 +02:00
Ilya Chernikov
5412f0ca00 Add new compiler argument for passing script resolver environment 2017-04-06 10:23:01 +02:00
Ilya Chernikov
03508e309a minor: improve daemon start failure diagnostic 2017-04-06 10:23:00 +02:00
Ilya Chernikov
194ea17413 Add actual sources to compiler and daemon client jars 2017-04-06 10:22:59 +02:00
Ilya Chernikov
5219033917 minor: remove redundant runWhenSmart on index changes notification 2017-04-06 10:22:58 +02:00
Ilya Chernikov
ce267dca54 Port compiler to the script-runtime with script base classes 2017-04-06 10:22:57 +02:00
Ilya Chernikov
f6d652a5d4 Add new artifact kotlin-compiler-client-embeddable.jar 2017-04-06 10:22:56 +02:00
Ilya Chernikov
5a73faf09c minor: move native platform launcher to separate file to make native-platform dependency optional 2017-04-06 10:22:55 +02:00
mglukhikh
1a4cbb4687 Find enclosing element for object literal in delegate #KT-8187 Fixed
(cherry picked from commit 9fa1636)
2017-04-05 20:22:38 +03:00
mglukhikh
baa7fe71b8 Do not add a new label to labeled loop
Relevant situation: break / continue in when #KT-16128 Fixed

(cherry picked from commit 6277476)
2017-04-05 20:22:23 +03:00
mglukhikh
b39bb3d10d Don't suggest destructuring if at least half components not used
So #KT-16828 Fixed

(cherry picked from commit feb9dd4)
2017-04-05 20:22:09 +03:00
Anton Bannykh
41bb820083 JS: make tests dependent on primitive array is checks pass even when -Xtypedarray is disabled (related: KT-17137)
(cherry picked from commit 867bd13)
2017-04-05 15:39:07 +03:00
Anton Bannykh
a9d66e30a2 JS: fix maven SeleniumTest
(cherry picked from commit 7d4c26c)
2017-04-05 15:39:07 +03:00
Anton Bannykh
15539122c9 JS: fixed <Type>Array.iterator methods; added -Xtypedarray compiler key
The <Type>Array.iterator used to lack next<Type>() method (KT-16626).

The -Xtypedarray compiler key enables translation of primitive arrays
to TypedArrays, and primitive array`is`-checks (KT-15358, KT-14007,
KT-14614, KT-16056).

(cherry picked from commit 9b34e21)
2017-04-05 15:39:07 +03:00
mglukhikh
24376fd857 KT-15870: run getTargetDirectory() in write action
(cherry picked from commit 1b2edf6)
2017-04-05 13:13:18 +03:00
mglukhikh
6c9fe38ff7 Set startInWrite... in intention-based quick fix as in intention
So #KT-15870 Fixed

(cherry picked from commit ee239d5)
2017-04-05 13:13:02 +03:00
Mikhail Glukhikh
80432d7b71 Fix "must not be null" in KotlinInlineFunctionDialog #KT-17233 Fixed
(cherry picked from commit 318314f)
2017-04-05 13:12:08 +03:00
mglukhikh
056d631a65 Make destructure intention work on library data classes
So #KT-16468 Fixed
So #KT-14402 Fixed

(cherry picked from commit f139977)
2017-04-05 13:11:10 +03:00
mglukhikh
27d389f9e5 KT-16828: use _ when appropriate in destructure intention
(cherry picked from commit 8a02ce3)
2017-04-05 13:10:45 +03:00
Mikhail Glukhikh
917da3d445 Introduce UNUSED_ANONYMOUS_PARAMETER for anonymous functions
It is not reported for 1.0 language version because
renaming to _ is not possible. It has weak warning severity

So #KT-8813 Fixed
So #KT-16875 Fixed

(cherry picked from commit 7a53b2f)
2017-04-05 13:09:14 +03:00
Dmitry Jemerov
441148fa9e KotlinAnnotatedElementsSearcher optimization
When possible, try to resolve references in types using only the PSI
without building the full resolve session.

(cherry picked from commit 296fe69)
2017-04-04 12:41:00 +02:00
Nikolay Krasko
62510f6ead Ad hoc solution to avoid resolution in language injection by receiver (KT-16995)
#KT-16995 Fixed

(cherry picked from commit eb4e6e6)
2017-04-03 19:56:09 +03:00
Mikhail Zarechenskiy
41c8efc688 Do not show warning about useless elvis for error function types
#KT-17214 Fixed
 #KT-12112 Fixed
2017-04-03 16:33:03 +03:00
Mikhail Zarechenskiy
1f31aa82f3 Warn for unnecessary (!!) assertion after method with generics
#KT-12276 Fixed
2017-04-03 16:33:01 +03:00
Mikhail Zarechenskiy
6e506fccde Fix warning about useless elvis when generics are involved
#KT-13648 Fixed
2017-04-03 16:33:00 +03:00
Vyacheslav Gerasimov
5317abb00d Add link to previous release to changelog 2017-03-31 21:15:31 +03:00
Ilya Chernikov
5595bea2ea Remove xerces from compiler uberjar, pack compiler with explicit jar names
xercesImpl was unnecessarily added to the compiler uberjar during migration
to the idea platform 171. This caused NCDFE about classes from org.w3c
package.
And to simplify application of this commit and to ensure that only required
jars are packed into the uberjar, the build.xml was altered to use
explicit list of the jars from the ideaSdk/core directory, rather than
a mask.

Fixes #KT-17143 and #KT-17157
2017-03-30 19:28:46 +02:00
Mikhail Glukhikh
36a6288dee Inline function: add extra tests taken from intellij-community
(cherry picked from commit 8cfcd7e)
2017-03-30 19:51:05 +03:00
Mikhail Glukhikh
411962ee57 Inline function: keep the function if some usages are not processed
(cherry picked from commit b8b7d1f)
2017-03-30 19:50:49 +03:00
Mikhail Glukhikh
6532442701 Inline function: process usages in children-first order
(cherry picked from commit 091e875)
2017-03-30 19:50:34 +03:00
Mikhail Glukhikh
53cfd2095d Inline function: use "function" in GUI messages
(cherry picked from commit fc0bf47)
2017-03-30 19:50:19 +03:00
Mikhail Glukhikh
6b47229cf8 Inline function: handle callable references through lambdas
(cherry picked from commit 93b624f)
2017-03-30 19:50:05 +03:00
Mikhail Glukhikh
6991eadcf5 Inline function: handle recursive calls
(cherry picked from commit 75bb599)
2017-03-30 19:49:49 +03:00
Mikhail Glukhikh
25ed1553d1 Introduce dialog for function inlining #KT-6159 Fixed
See KotlinInlineFunctionProcessor and KotlinInlineFunctionDialog

(cherry picked from commit e79f006)
2017-03-30 19:49:34 +03:00
Mikhail Glukhikh
279bbb4732 KT-6159: generate Unit while code inlining when needed
(cherry picked from commit b6803af)
2017-03-30 19:49:17 +03:00
Mikhail Glukhikh
d6f86b7c05 Minor: deprecation fix in ScopeUtils
(cherry picked from commit 7de0197)
2017-03-30 19:49:03 +03:00
Mikhail Glukhikh
61664c02cd Fix code inlining for expression body with multiple occurrences
So #KT-17022 Fixed

(cherry picked from commit 081caad)
2017-03-30 19:48:43 +03:00
Mikhail Glukhikh
52a33cc494 Minor: style fix in KotlinInlineFunctionHandler
(cherry picked from commit 96846d0)
2017-03-30 19:48:24 +03:00
Mikhail Glukhikh
f80e78ac57 KT-6159: rename duplicates met
(cherry picked from commit 7788834)
2017-03-30 19:48:10 +03:00
Mikhail Glukhikh
d3587bb028 Do not perform function inlining if it's not supported
(cherry picked from commit 342118d)
2017-03-30 19:47:55 +03:00
Mikhail Glukhikh
2aff73b432 KT-6159: allow local / private functions inlining
(cherry picked from commit de86106)
2017-03-30 19:47:41 +03:00
Mikhail Glukhikh
f08fd888a8 Some inline tests that do not work
(cherry picked from commit 127b7c8)
2017-03-30 19:47:19 +03:00
Mikhail Glukhikh
08abb61e12 KT-6159: Inline function refactoring enabled
(cherry picked from commit 1d5b8ea)
2017-03-30 19:47:01 +03:00
Dmitry Jemerov
ef6669e865 Optimize isReferenceTo() when searching for PsiMethod usages
Avoid resolving references when we know from context that a reference
at given location can't resolve to a PsiMethod.

(cherry picked from commit f255f2a)
2017-03-30 15:34:48 +02:00
Mikhail Glukhikh
e7f7673123 Use library-only sources as resolve scope from library #KT-12264 Fixed
(cherry picked from commit e3f0a60)
2017-03-30 14:02:00 +03:00
Mikhail Glukhikh
e85ca8de52 Evaluate allImplementingModules lazily #KT-17136 Fixed
(cherry picked from commit a35b770)
2017-03-29 18:22:01 +03:00
Simon Ogorodnik
c6385f9309 Fix ImportFixBase to compute suggestions not on EDT
(cherry picked from commit ddcff3c)
2017-03-29 17:36:47 +03:00
Vyacheslav Gerasimov
c2417ac243 Add changelog for 1.1.2
(cherry picked from commit 94b261d)
2017-03-29 16:12:39 +03:00
Dmitry Petrov
9e236c4a23 KT-16264 Forbid usage of _ without backticks
Forbid underscore-only (_, __, ___, ...) names as callees and as types.

If CHECK_TYPE directive is on, filter out UNDERSCORE_USAGE_WITHOUT_BACKTICKS messages.
2017-03-29 15:54:34 +03:00
Yan Zhulanow
dd32987eb2 Fix 'kotlin-spring' and 'kotlin-noarg' Gradle plugin importing (KT-17049)
Allopen and Noarg plugins now use 'presets' that should be handled in the Gradle importer as well.
2017-03-29 13:52:00 +03:00
Pavel V. Talanov
b141f3754a KtLightElements: fix KtLightMember not extending KtLightDeclaration
Fix problem introduced in 4b85fd9fbe
2017-03-28 19:48:19 +03:00
Yan Zhulanow
2fc74d2819 Minor: fix failing CliTestGenerated#testPluginSimple test
Add missing Android Dialog stub cause Android Extensions plugin now generates the synthetic property for Dialog.
2017-03-28 16:09:23 +03:00
Dmitry Jemerov
6c6e163881 Log fallbacks to plain text search when searching expressions of type
This will help diagnose performance problems in IDEA inspections.

(cherry picked from commit 8ec70f4)
2017-03-28 13:07:50 +02:00
Sergey Igushkin
0ee4ddfda9 Support omitting version of org.jetbrains.kotlin dependencies
Related to #KT-12792

(cherry picked from commit ae2b4f5)
2017-03-28 08:39:35 +03:00
Sergey Igushkin
01c92992c9 Fixed classes copying fail in cases when destinationDir has changed
Added @Input to the property returning classes dirs: it will make
Gradle fall back to non-incremental input when the property value
changes.

Issues: #KT-16820 Fixed

(cherry picked from commit 9ba84df)
2017-03-28 08:39:11 +03:00
Jonathan Leitschuh
4154bba5a3 Java IC compatibility fix for Gradle 2.14+
Added version check to switch between old and new approaches because
Gradle versions before 2.14 have a bug in Java IC.
Added Kotlin classes to Java task input.
Added  annotationsFile into task input to include it into up-to-date check.

Related issues: #KT-16585 Fixed

(cherry picked from commit cc0ac36)
2017-03-28 08:38:51 +03:00
Ilya Gorbunov
cf6cef71e2 Remove 'nearly_stateless' category, do not mention statefulness for terminal operations.
#KT-16994

(cherry picked from commit c98c2d9)
2017-03-28 00:11:53 +03:00
Ilya Gorbunov
ce5a104eb2 Sequence operation classification regarding their statefulness and laziness.
#KT-16994 Fixed

(cherry picked from commit 4018db6)
2017-03-28 00:11:46 +03:00
Simon Ogorodnik
94b5148d5b Revert: Fix Sample reference to resolve cross-module packages correctly 2017-03-27 21:41:07 +03:00
Pavel V. Talanov
5c0831d5ad findDecompiledDeclaration: find builtIns more accurately
Use resolveScope of a reference to help searching for builtIn binaries
Do not search non-builtIn descriptors in random scopes
2017-03-27 21:23:40 +03:00
Alexander Udalov
894f85d822 Disallow using named arguments for members of header classes
#KT-17083 Fixed

(cherry picked from commit ccd3781403)
2017-03-27 20:12:17 +03:00
Alexander Udalov
9e1a4992d8 Allow impl declarations to have flexible types
Types of the corresponding parameters (or type parameter bounds, types
in supertypes, etc) are now compatible not only if they're equal, but
also if values of those types are mutually assignable (if "a" is subtype
of "b" and "b" is subtype of "a")

 #KT-17005 Fixed

(cherry picked from commit b971ac9312)
2017-03-27 20:12:15 +03:00
Alexander Udalov
1b7198cb03 Allow impl declarations to have non-stable parameter names
#KT-17027 Fixed

(cherry picked from commit 116380a826)
2017-03-27 20:12:14 +03:00
Alexander Udalov
24182e39d8 Render incompatible impl member in "no impl for header" diagnostic
(cherry picked from commit 633798db18)
2017-03-27 20:12:12 +03:00
Alexander Udalov
b6e32cc03d Serialize and deserialize 'header' modifier for descriptors
This fixes KT-17001 because now 'header' modifier is loaded correctly
for deserialized members and the standard disambiguation in
OverloadingConflictResolver.compareCallsByUsedArguments takes place,
where header members are discriminated against the corresponding impl
members

 #KT-17001 Fixed

(cherry picked from commit db1f039586)
2017-03-27 20:12:10 +03:00
Pavel V. Talanov
4518c5bac6 Light class tests: hidden deprecated affects codegen
Provide fix later
2017-03-27 18:02:43 +03:00
Pavel V. Talanov
58ad4b1386 Lazy light classes: can't use laziness for classes with supertypes delegates 2017-03-27 18:02:41 +03:00
Pavel V. Talanov
1f62636400 KtLightMethod: isVarArgs() does not trigger exact delegate computation 2017-03-27 18:02:39 +03:00
Pavel V. Talanov
b10adf2de0 Light members: allow to get modifier list without computing delegate 2017-03-27 18:02:38 +03:00
Pavel V. Talanov
5befeb4ccf LazyLightClassDataHolder: rollback optimization on suspected inherited internal visibility
Internal visibility affects member names
2017-03-27 18:02:36 +03:00
Pavel V. Talanov
614a4fec22 Light classes: refactor, move getOrigin to corresponding classes 2017-03-27 18:02:34 +03:00
Pavel V. Talanov
bd45c70083 Lazy light classes: fix visibility modifier in case of inherited protected visibility 2017-03-27 18:02:33 +03:00
Pavel V. Talanov
2961301297 LightClassTest: test corner cases related to inherited visiblity
EA-99155
 #KT-16899 Fixed
2017-03-27 18:02:31 +03:00
Pavel V. Talanov
bdde75a6a3 Refactor light members: introduce KtLightMemberImpl
Holds common code for fields and methods
2017-03-27 18:02:29 +03:00
Pavel V. Talanov
e325523034 Introduce KotlinOverridableInternalMembersShortNameIndex
Keeping track of all potentially overridable internal members
To optimize certain scenarios in light classes
2017-03-27 18:02:27 +03:00
Pavel V. Talanov
84f17ba1a1 Minor, stubs: isTrait -> isInterface 2017-03-27 18:02:25 +03:00
Alexander Udalov
c649752e8e Do not use CoreJavaFileManager in KotlinCliJavaFileManagerImpl
The inheritance is still needed because of the code in intellij-core,
specifically in JavaCoreProjectEnvironment.addSourcesToClasspath and
CoreJavaDirectoryService.getPackage, which assumes that the
JavaFileManager instance in the project is a CoreJavaFileManager

(cherry picked from commit 1c7ac2da5a)
2017-03-27 17:20:10 +03:00
Alexander Udalov
9cace66246 Support nested classes in KotlinCliJavaFileManagerImpl.findClass
findClass(String, GlobalSearchScope) is invoked for example when we're
resolving supertypes of classes in Java libraries. Previously, it never
found nested classes and falled back to CoreJavaFileManager's
implementation, which lacks a fix for the original issue (KT-12664,
which was fixed in JvmDependenciesIndex in 5a533a52 and 164c72e8)

 #KT-16931 Fixed

(cherry picked from commit c67eb84369)
2017-03-27 17:20:08 +03:00
Alexander Udalov
6375fb773d Refactor JvmDependenciesIndex
- Move collectKnownClassNamesInPackage to the only place where it's used
- Fix warnings/inspections and simplify implementation a bit

(cherry picked from commit f1a1ebae01)
2017-03-27 17:20:07 +03:00
Alexander Udalov
b6f1cf8107 Refactor KotlinJavaPsiFacade.KotlinPsiElementFinderImpl
Split KotlinPsiElementFinderImpl into two classes: one is used in the
compiler (boolean field isCliFileManager previously handled that), the
other is used in IDE and possibly other non-CLI scenarios.

Also avoid a possible class cast exception in
KotlinJavaPsiFacade.knownClassNamesInPackage

(cherry picked from commit 801a93edbc)
2017-03-27 17:20:05 +03:00
Ilya Gorbunov
86ced88e0d Run gradle unit tests with Java 8
(cherry picked from commit d54f114)
2017-03-27 11:39:32 +03:00
Ilya Gorbunov
06e909acad Fix missing kotlin-test dependencies
(previously it was bundled to kotlin-compiler-embeddable)

(cherry picked from commit 6dc4056)
2017-03-27 11:39:32 +03:00
Vyacheslav Gerasimov
95d774697c Fix MovePropertyToConstructorIntention and broken tests
(cherry picked from commit 8c41e44)
2017-03-27 11:39:32 +03:00
Alexey Sedunov
7bc246f614 Move: Fix conflict checking when switching between similar libraries
#KT-17006 Fixed

(cherry picked from commit 298ee26)
2017-03-26 16:28:49 +03:00
Alexey Sedunov
a2bb0ace05 Resolution Facade: Add explicit property for file target platform
(cherry picked from commit 45b8cd2)
2017-03-26 16:28:33 +03:00
Alexey Sedunov
3594294d0a Move: Fix runtime unconfiguration for multiple modules
(cherry picked from commit 87ea13b)
2017-03-26 16:28:13 +03:00
Alexey Sedunov
fca79f9bf9 Move: Fix processing of calls and callable references
Fix CCE on callable references to Java methods.
Fix qualification of callable references without receivers.
Fix processing of calls/callable references to object extensions
and extension members.
Do not explicate short companion references

 #KT-16809 Fixed

(cherry picked from commit 1d01624)
2017-03-26 16:28:00 +03:00
Alexey Sedunov
fd5bb25349 Move: Perform extension import insertion after reference shortening
(cherry picked from commit 5849555)
2017-03-26 16:27:46 +03:00
Alexey Sedunov
5fbd738f24 Refactor KotlinShortenReferencesRefactringHelper
Rename refactoring helper and its infrastructure
Add support for different request types

(cherry picked from commit b3274ac)
2017-03-26 16:27:34 +03:00
Alexey Sedunov
63e4beab76 Move: Do not shorten references unaffected by the refactoring
(cherry picked from commit dc04b20)
2017-03-26 16:27:12 +03:00
Alexey Sedunov
89caa70987 Shorten References: Skip companion receivers on callable references
This is temporary fix due to KT-13934 which prevents resolution
of references like X::foo where foo is a member or extension
of X companion object

(cherry picked from commit aad11ff)
2017-03-26 16:26:58 +03:00
Alexey Sedunov
ea8b082355 Move: Fix "scanEntireFile" values after the refactoring
#KT-17032 Fixed

(cherry picked from commit d71cefe)
2017-03-26 16:26:01 +03:00
Alexey Sedunov
ae0218431c Kotlin Facet: Detect module platform by 'kotlin'/'kotlin2js' plugin
(cherry picked from commit b818ef0)
2017-03-26 16:25:23 +03:00
Alexey Sedunov
77dff7b7f5 Kotlin Facet: Fix settings initialization
(cherry picked from commit 0ad2822)
2017-03-26 16:24:40 +03:00
Alexander Udalov
15502b4153 Update to ASM 6-alpha from intellij 171
Will be needed to read module-info files
2017-03-24 20:17:43 +03:00
Alexander Udalov
b9891c36e2 Remove unused library 'intellij-core-analysis' 2017-03-24 20:17:40 +03:00
Yan Zhulanow
d3a9008bd3 Kapt3: Fix Maven build on CI
'tools_jar_profile' Maven profile is activated only if 'kotlin-annotation-processing-maven-build.txt' exists.
It already works this say for the 'kotlin-annotation-processing' artifact.
2017-03-24 20:06:09 +03:00
Yan Zhulanow
249a3a0ec9 Kapt3: Use 'compilerArgs' safely (KT-16990)
'android-apt' (com.neenbedankt) adds the 'File' instance to 'compilerArgs' (List<String>).
2017-03-24 20:06:02 +03:00
10394 changed files with 84518 additions and 256818 deletions

1
.gitignore vendored
View File

@@ -21,4 +21,3 @@ workspace.xml
.gradle/
build/
!**/src/**/build

View File

@@ -60,17 +60,16 @@
<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>
<element id="archive" name="android-lint.jar">
@@ -92,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>
@@ -103,8 +103,6 @@
<element id="module-output" name="kotlin-gradle-tooling" />
</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>
<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

@@ -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,19 +5,7 @@
<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="file://$PROJECT_DIR$/ideaSDK/core" />
</CLASSES>
<JAVADOC />
<SOURCES>
@@ -25,5 +13,6 @@
<root url="jar://$PROJECT_DIR$/ideaSDK/sources/sources.jar!/" />
<root url="jar://$PROJECT_DIR$/dependencies/asm-src.zip!/" />
</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-core">
<CLASSES>
<root url="jar://$PROJECT_DIR$/dependencies/kotlinx-coroutines-core.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$PROJECT_DIR$/dependencies/kotlinx-coroutines-core-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>

2
.idea/misc.xml generated
View File

@@ -48,7 +48,7 @@
<component name="ProjectResources">
<default-html-doctype>http://www.w3.org/1999/xhtml</default-html-doctype>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="false" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_6" default="false" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
<component name="SuppressABINotification">

3
.idea/modules.xml generated
View File

@@ -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" />
@@ -64,11 +63,9 @@
<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$/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$/compiler/javac-wrapper/javac-wrapper.iml" filepath="$PROJECT_DIR$/compiler/javac-wrapper/javac-wrapper.iml" group="compiler" />
<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" />

View File

@@ -3,7 +3,7 @@
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<module name="android-tests" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="true" />
<option name="ALTERNATIVE_JRE_PATH" value="1.8" />
<option name="ALTERNATIVE_JRE_PATH" value="1.6" />
<option name="PACKAGE_NAME" value="org.jetbrains.kotlin.android.tests" />
<option name="MAIN_CLASS_NAME" value="org.jetbrains.kotlin.android.tests.AndroidRunner" />
<option name="METHOD_NAME" value="" />

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

@@ -1,6 +1,5 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="IDEA" type="Application" factoryName="Application" singleton="true">
<log_file path="$PROJECT_DIR$/ideaSDK/system-idea/log/idea.log" checked="true" skipped="true" show_all="false" alias="idea.log" />
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<option name="MAIN_CLASS_NAME" value="com.intellij.idea.Main" />
<option name="VM_PARAMETERS" value="-Xmx1250m -XX:ReservedCodeCacheSize=128m -XX:+HeapDumpOnOutOfMemoryError -ea -Didea.is.internal=true -Didea.debug.mode=true -Didea.system.path=../system-idea -Didea.config.path=../config-idea -Dapple.laf.useScreenMenuBar=true -Dapple.awt.graphics.UseQuartz=true -Dsun.io.useCanonCaches=false -Dplugin.path=$PROJECT_DIR$/out/artifacts/Kotlin -Dkotlin.internal.mode.enabled=true -Didea.additional.classpath=../idea-kotlin-runtime/kotlin-runtime.jar,../idea-kotlin-runtime/kotlin-reflect.jar" />

View File

@@ -1,6 +1,5 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="IDEA (No ProcessCanceledException)" type="Application" factoryName="Application" singleton="true">
<log_file path="$PROJECT_DIR$/ideaSDK/system-idea/log/idea.log" checked="true" skipped="true" show_all="false" alias="idea.log" />
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<option name="MAIN_CLASS_NAME" value="com.intellij.idea.Main" />
<option name="VM_PARAMETERS" value="-Xmx1250m -XX:ReservedCodeCacheSize=128m -XX:+HeapDumpOnOutOfMemoryError -ea -Didea.is.internal=true -Didea.debug.mode=true -Didea.system.path=../system-idea -Didea.config.path=../config-idea -Dapple.laf.useScreenMenuBar=true -Dapple.awt.graphics.UseQuartz=true -Dsun.io.useCanonCaches=false -Dplugin.path=$PROJECT_DIR$/out/artifacts/Kotlin -Didea.ProcessCanceledException=disabled -Dkotlin.internal.mode.enabled=true -Didea.additional.classpath=../idea-kotlin-runtime/kotlin-runtime.jar,../idea-kotlin-runtime/kotlin-reflect.jar" />

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,69 +14,35 @@
<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/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" />

106
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
@@ -32,7 +32,7 @@ In order to build Kotlin distribution you need to have:
- JDK 1.6, 1.7 and 1.8
- Setup environment variables as following:
JAVA_HOME="path to JDK 1.8"
JAVA_HOME="path to JDK 1.6"
JDK_16="path to JDK 1.6"
JDK_17="path to JDK 1.7"
JDK_18="path to JDK 1.8"
@@ -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

@@ -17,7 +17,6 @@
<property name="compiler.version.java.bk" value="${version_substitute_dir}/KotlinCompilerVersion.java.bk"/>
<property name="compiler.version.java.versioned" value="${compiler.version.java}.versioned"/>
<property name="compiler.version.number" value="${build.number}"/>
<property name="compiler.ant.fork.jvmargs" value="-Xmx1024m"/>
<property name="plugin.zip" value="${artifact.output.path}/kotlin-plugin-${build.number}.zip"/>
@@ -151,8 +150,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

@@ -61,11 +61,11 @@ data class JvmBuildMetaInfo(
fun JvmBuildMetaInfo(args: CommonCompilerArguments): JvmBuildMetaInfo =
JvmBuildMetaInfo(isEAP = KotlinCompilerVersion.isPreRelease(),
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,
languageVersionString = args.languageVersion ?: LanguageVersion.LATEST.versionString,
apiVersionString = args.apiVersion ?: ApiVersion.LATEST.versionString,
coroutinesEnable = args.coroutinesEnable,
coroutinesWarn = args.coroutinesWarn,
coroutinesError = args.coroutinesError,
multiplatformEnable = args.multiPlatform,
metadataVersionMajor = JvmMetadataVersion.INSTANCE.major,
metadataVersionMinor = JvmMetadataVersion.INSTANCE.minor,

View File

@@ -16,33 +16,32 @@
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<>();
List<String> result = new ArrayList<String>();
convertArgumentsToStringList(arguments, arguments.getClass().newInstance(), arguments.getClass(), result);
result.addAll(arguments.freeArgs);
return result;
}
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

@@ -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

@@ -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))
}
}
}

689
build.xml
View File

@@ -4,30 +4,34 @@
<!-- Set to false to disable proguard run on kotlin-compiler.jar. Speeds up the build -->
<property name="shrink" value="true"/>
<!-- Set to false to disable compiler's javadoc generation. Speeds up the build -->
<property name="generate.javadoc" value="false"/>
<!-- Set to false to prevent jarjar and metadata stripping on kotlin-reflect.jar and reflection sources. Use to debug reflection -->
<property name="obfuscate.reflect" value="true"/>
<property name="max.heap.size.for.forked.jvm" value="1024m"/>
<property name="bootstrap.home" value="${basedir}/dependencies/bootstrap-compiler"/>
<property name="bootstrap.compiler.home" value="${bootstrap.home}/Kotlin/kotlinc"/>
<property name="bootstrap.runtime" value="${bootstrap.compiler.home}/lib/kotlin-stdlib.jar"/>
<property name="bootstrap.runtime" value="${bootstrap.compiler.home}/lib/kotlin-runtime.jar"/>
<property name="bootstrap.reflect" value="${bootstrap.compiler.home}/lib/kotlin-reflect.jar"/>
<property name="bootstrap.script.runtime" value="${bootstrap.compiler.home}/lib/kotlin-script-runtime.jar"/>
<property name="bootstrap.kotlin.test" value="${bootstrap.compiler.home}/lib/kotlin-test.jar" />
<property name="intermediate-sources" value="out/src" />
<property name="kotlin-home" value="${output}/kotlinc"/>
<property name="build.number" value="snapshot"/>
<property name="bootstrap.build.no.tests" value="false"/>
<property name="idea.sdk" value="${basedir}/ideaSDK"/>
<property name="protobuf.jar" value="${basedir}/dependencies/protobuf-2.6.1.jar"/>
<property name="protobuf-lite.jar" value="${basedir}/dependencies/protobuf-2.6.1-lite.jar"/>
<property name="javax.inject.jar" value="${basedir}/lib/javax.inject.jar"/>
<property name="gradle.logging.level" value=""/>
<property environment="env"/>
<property name="tools.jar" value="${env.JDK_18}/lib/tools.jar"/>
<property name="java.target" value="1.8"/>
<property name="java.target.1.6" value="1.6"/>
<condition property="bootstrap.or.local.build" value="true" else="false">
<condition property="bootstrap.or.local.build" value="true">
<or>
<istrue value="${bootstrap.build.no.tests}"/>
<not>
@@ -36,18 +40,25 @@
</or>
</condition>
<include file="jslib_files.xml" />
<property name="compiled.builtins.js" value="builtins.js"/>
<property name="compiled.stdlib.js" value="stdlib.js"/>
<property name="compiled.stdlib.meta.js" value="kotlin.meta.js"/>
<property name="stdlib.js.dir" value="${basedir}/js/js.libraries/src/js"/>
<!--
The compiler produced on the first step of the build (Bootstrap No Tests) is only guaranteed to work against the OLD runtime
located in dependencies/bootstrap-compiler/.../kotlin-stdlib.jar, because the newly built compiler is just a Kotlin application,
located in dependencies/bootstrap-compiler/.../kotlin-runtime.jar, because the newly built compiler is just a Kotlin application,
compiled by the old compiler with the old runtime in classpath. If you advance the ABI version, the newly built compiler will NOT work
against the runtime it will produce on its own because they have different ABI versions.
So on the first step of bootstrap we copy that runtime to kotlin-stdlib-internal-bootstrap.jar (see 'prepare-dist' target) and change
So on the first step of bootstrap we copy that runtime to kotlin-runtime-internal-bootstrap.jar (see 'prepare-dist' target) and change
the compiler classpath accordingly. On the second step this is believed to be not required, because there are
little to no differences between the new and the newest runtime.
-->
<condition property="compiler.manifest.class.path"
value="kotlin-stdlib-internal-bootstrap.jar kotlin-reflect-internal-bootstrap.jar kotlin-script-runtime-internal-bootstrap.jar"
else="kotlin-stdlib.jar kotlin-reflect.jar kotlin-script-runtime.jar">
value="kotlin-runtime-internal-bootstrap.jar kotlin-reflect-internal-bootstrap.jar kotlin-script-runtime-internal-bootstrap.jar"
else="kotlin-runtime.jar kotlin-reflect.jar kotlin-script-runtime.jar">
<istrue value="${bootstrap.or.local.build}"/>
</condition>
@@ -58,13 +69,10 @@
<file file="${bootstrap.script.runtime}"/>
<fileset dir="${idea.sdk}" includes="core/*.jar"/>
<pathelement location="${protobuf.jar}"/>
<pathelement location="${tools.jar}"/>
<fileset dir="${basedir}/lib" includes="**/*.jar"/>
<fileset dir="${dependencies}" includes="jansi.jar"/>
<fileset dir="${dependencies}" includes="jline.jar"/>
<fileset dir="${dependencies}" includes="javaslang-2.0.6.jar"/>
<fileset dir="${dependencies}" includes="json-org.jar"/>
<fileset dir="${basedir}/ideaSDK/jps" includes="jps-model.jar"/>
</path>
@@ -89,7 +97,6 @@
<include name="compiler/ir/ir.psi2ir/src"/>
<include name="compiler/ir/ir.tree/src"/>
<include name="compiler/builtins-serializer/src"/>
<include name="compiler/javac-wrapper/src"/>
<include name="compiler/cli/src"/>
<include name="compiler/cli/cli-common/src"/>
<include name="compiler/conditional-preprocessor/src/"/>
@@ -101,7 +108,6 @@
<include name="compiler/plugin-api/src"/>
<include name="compiler/daemon/src"/>
<include name="compiler/daemon/daemon-common/src"/>
<include name="compiler/frontend.script/src"/>
<include name="build-common/src"/>
<include name="compiler/incremental-compilation-impl/src"/>
<include name="compiler/serialization/src"/>
@@ -112,7 +118,6 @@
<include name="js/js.inliner/src"/>
<include name="js/js.parser/src"/>
<include name="js/js.serializer/src"/>
<include name="js/js.dce/src"/>
<include name="plugins/annotation-collector/src"/>
</dirset>
@@ -137,7 +142,6 @@
<include name="conditional-preprocessor/**"/>
<include name="daemon/**"/>
<include name="daemon-common/**"/>
<include name="frontend.script/**"/>
<include name="build-common/**"/>
<include name="incremental-compilation-impl/**"/>
<include name="util/**"/>
@@ -146,15 +150,12 @@
<include name="plugin-api/**"/>
<include name="annotation-collector/**"/>
<include name="builtins-serializer/**"/>
<include name="javac-wrapper/**"/>
<include name="js.ast/**"/>
<include name="js.translator/**"/>
<include name="js.frontend/**"/>
<include name="js.inliner/**"/>
<include name="js.parser/**"/>
<include name="js.serializer/**"/>
<include name="js.dce/**"/>
<exclude name="**/META-INF/services/**"/>
</patternset>
<path id="compilerSources.path">
@@ -182,9 +183,6 @@
<target name="init">
<mkdir dir="${kotlin-home}"/>
<mkdir dir="${kotlin-home}/lib"/>
<fail unless="env.JDK_16" message="JDK_16 environment variable is not set."/>
<fail unless="env.JDK_18" message="JDK_18 environment variable is not set."/>
</target>
<target name="prepare-dist">
@@ -202,18 +200,18 @@
<chmod dir="${kotlin-home}/bin" excludes="**/*.bat" perm="755"/>
<sequential if:true="${bootstrap.or.local.build}">
<copy file="${bootstrap.runtime}" tofile="${kotlin-home}/lib/kotlin-stdlib-internal-bootstrap.jar"/>
<copy file="${bootstrap.runtime}" tofile="${kotlin-home}/lib/kotlin-runtime-internal-bootstrap.jar"/>
<copy file="${bootstrap.reflect}" tofile="${kotlin-home}/lib/kotlin-reflect-internal-bootstrap.jar"/>
<copy file="${bootstrap.script.runtime}" tofile="${kotlin-home}/lib/kotlin-script-runtime-internal-bootstrap.jar"/>
<copy file="${bootstrap.kotlin.test}" tofile="${kotlin-home}/lib/kotlin-test-internal-bootstrap.jar" failonerror="false"/>
<jar destfile="${kotlin-home}/lib/kotlin-reflect-internal-bootstrap.jar" update="true">
<manifest>
<attribute name="Class-Path" value="kotlin-stdlib-internal-bootstrap.jar"/>
<attribute name="Class-Path" value="kotlin-runtime-internal-bootstrap.jar"/>
</manifest>
</jar>
<jar destfile="${kotlin-home}/lib/kotlin-test-internal-bootstrap.jar" update="true">
<manifest>
<attribute name="Class-Path" value="kotlin-stdlib-internal-bootstrap.jar"/>
<attribute name="Class-Path" value="kotlin-runtime-internal-bootstrap.jar"/>
</manifest>
</jar>
</sequential>
@@ -233,15 +231,6 @@
</copy>
</target>
<target name="copy-bootstrap-to-dist"
depends="clean"
description="Use bootstrap compiler instead of building one from sources">
<mkdir dir="${kotlin-home}"/>
<copy todir="${kotlin-home}">
<fileset dir="${bootstrap.compiler.home}"/>
</copy>
</target>
<target name="compiler-sources">
<jar jarfile="${output}/kotlin-compiler-sources.jar">
<!-- TODO How to convert it from pathset or dirset ? -->
@@ -256,7 +245,6 @@
<fileset dir="compiler/ir/ir.psi2ir/src"/>
<fileset dir="compiler/ir/ir.tree/src"/>
<fileset dir="compiler/builtins-serializer/src"/>
<fileset dir="compiler/javac-wrapper/src"/>
<fileset dir="compiler/cli/src"/>
<fileset dir="compiler/cli/cli-common/src"/>
<fileset dir="compiler/conditional-preprocessor/src"/>
@@ -269,7 +257,6 @@
<fileset dir="compiler/resolution/src"/>
<fileset dir="compiler/frontend.java/src"/>
<fileset dir="compiler/light-classes/src"/>
<fileset dir="compiler/frontend.script/src"/>
<fileset dir="compiler/plugin-api/src"/>
<fileset dir="plugins/annotation-collector/src"/>
<fileset dir="compiler/serialization/src"/>
@@ -280,7 +267,6 @@
<fileset dir="js/js.inliner/src"/>
<fileset dir="js/js.parser/src"/>
<fileset dir="js/js.serializer/src"/>
<fileset dir="js/js.dce/src"/>
<zipfileset file="${kotlin-home}/build.txt" prefix="META-INF"/>
<manifest>
@@ -291,12 +277,230 @@
<attribute name="Implementation-Version" value="${build.number}"/>
</manifest>
</jar>
<sequential if:true="${generate.javadoc}">
<delete dir="${output}/kotlin-compiler-javadoc" failonerror="false"/>
<javadoc destdir="${output}/kotlin-compiler-javadoc"
sourcepathref="compilerSources.path"
classpathref="classpath"
linksource="yes"
windowtitle="${manifest.impl.title.kotlin.compiler}"/>
<jar jarfile="${output}/kotlin-compiler-javadoc.jar">
<fileset dir="${output}/kotlin-compiler-javadoc"/>
<zipfileset file="${kotlin-home}/build.txt" prefix="META-INF"/>
<manifest>
<attribute name="Built-By" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Vendor" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Title" value="${manifest.impl.title.kotlin.compiler.javadoc}"/>
<attribute name="Implementation-Version" value="${build.number}"/>
</manifest>
</jar>
</sequential>
<sequential unless:true="${generate.javadoc}">
<jar jarfile="${output}/kotlin-compiler-javadoc.jar">
<manifest>
<attribute name="Built-By" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Vendor" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Title" value="${manifest.impl.title.kotlin.compiler.javadoc}"/>
<attribute name="Implementation-Version" value="${build.number}"/>
</manifest>
</jar>
</sequential>
</target>
<macrodef name="new-kotlin2js">
<attribute name="output"/>
<attribute name="additionalOptions" default=""/>
<element name="src"/>
<sequential>
<local name="src.line"/>
<path id="src.path">
<src/>
</path>
<pathconvert property="src.line" refid="src.path" pathsep=" "/>
<java classname="org.jetbrains.kotlin.preloading.Preloader" failonerror="true" fork="true"
maxmemory="${max.heap.size.for.forked.jvm}">
<classpath>
<pathelement location="${kotlin-home}/lib/kotlin-preloader.jar"/>
</classpath>
<assertions>
<enable/>
</assertions>
<arg value="-cp"/>
<arg value="${kotlin-home}/lib/kotlin-compiler.jar"/>
<arg value="org.jetbrains.kotlin.cli.js.K2JSCompiler"/>
<arg line="${src.line}"/>
<arg value="-output"/>
<arg value="@{output}"/>
<arg value="-no-stdlib"/>
<arg value="-version"/>
<arg line="@{additionalOptions}"/>
<arg line="-main noCall"/>
<arg line="-module-kind commonjs"/>
<arg value="-Xallow-kotlin-package"/>
</java>
</sequential>
</macrodef>
<target name="js-stdlib-merge">
<!-- value should be one of: whitespace, simple, advanced -->
<property name="compilationLevel" value="whitespace"/>
<!-- value should be one of: default, quiet, verbose -->
<property name="warningLevel" value="default"/>
<taskdef name="closure-compiler"
classname="com.google.javascript.jscomp.ant.CompileTask"
classpath="${dependencies}/closure-compiler.jar"/>
<closure-compiler
compilationLevel="${compilationLevel}"
prettyprint="true"
languagein="ECMASCRIPT5_STRICT"
warning="${warningLevel}"
output="${js.stdlib.output.dir}/kotlin.js"
outputWrapperFile="${stdlib.js.dir}/closure-wrapper.txt">
<path>
<fileset dir="${stdlib.js.dir}">
<include name="**/*.js"/>
<exclude name="externs.js"/>
</fileset>
<fileset dir="${js.stdlib.output.dir}">
<include name="${compiled.builtins.js}"/>
<include name="${compiled.stdlib.js}"/>
</fileset>
</path>
<externs dir="${stdlib.js.dir}">
<file name="externs.js"/>
</externs>
</closure-compiler>
<!--
Few hacks to compose one kotlin.js from several smaller files:
1. Wrapper function takes Kotlin and _, whereas they are already defined above (see closure-wrapper.txt), so delete these
parameters.
2. Since we deleted parameters, we can get rid or arguments passed to wrapper function.
They are module.exports and require("Kotlin"), accordingly to CommonJS spec.
3. We can omit return _, since it's already exported by the code in UMD wrapper.
-->
<replaceregexp file="${js.stdlib.output.dir}/kotlin.js"
match="module.exports,\s*require\([^)]+\)"
replace=""
byline="true" encoding="UTF-8" />
<replaceregexp file="${js.stdlib.output.dir}/kotlin.js"
match="function\s*\(_,\s*Kotlin\)"
replace="function()"
byline="true" encoding="UTF-8" />
<replaceregexp file="${js.stdlib.output.dir}/kotlin.js"
match="return\s+_;"
replace=""
byline="true" encoding="UTF-8" />
</target>
<target name="js-stdlib-preprocess">
<kotlin-pp src="libraries/stdlib/src" output="${intermediate-sources}/stdlib/js" profile="JS" />
</target>
<target name="js-stdlib" depends="js-stdlib-preprocess">
<property environment="env"/>
<cleandir dir="${js.stdlib.output.dir}"/>
<!-- We don't want descriptors for built-ins to be serialized, so we compile these files separately. -->
<new-kotlin2js output="${js.stdlib.output.dir}/tmp-builtins/kotlin.js">
<src>
<union>
<resources refid="kotlin.builtin.native.files"/>
</union>
</src>
</new-kotlin2js>
<new-kotlin2js output="${js.stdlib.output.dir}/tmp/kotlin.js" additionalOptions="-meta-info">
<src>
<union>
<fileset refid="kotlin.builtin.files"/>
<resources refid="js.lib.files"/>
</union>
</src>
</new-kotlin2js>
<move file="${js.stdlib.output.dir}/tmp-builtins/kotlin.js" tofile="${js.stdlib.output.dir}/${compiled.builtins.js}" />
<move file="${js.stdlib.output.dir}/tmp/kotlin.js" tofile="${js.stdlib.output.dir}/${compiled.stdlib.js}" />
<move file="${js.stdlib.output.dir}/tmp/kotlin" todir="${js.stdlib.output.dir}" />
<move file="${js.stdlib.output.dir}/tmp/${compiled.stdlib.meta.js}" tofile="${js.stdlib.output.dir}/${compiled.stdlib.meta.js}" />
<condition property="jdk17" value="${env.JDK_17}" else="${env.JAVA_HOME}">
<isset property="env.JDK_17" />
</condition>
<java classname="org.apache.tools.ant.launch.Launcher"
fork="true"
failonerror="true"
timeout="4000000"
taskname="startAnt"
jvm="${jdk17}/bin/java">
<env key="JAVA_HOME" value="${jdk17}"/>
<classpath>
<pathelement location="${ant.home}/lib/ant-launcher.jar"/>
</classpath>
<arg line="-f" />
<arg line="build.xml" />
<arg line="js-stdlib-merge" />
</java>
<jar jarfile="${kotlin-home}/lib/kotlin-stdlib-js.jar" duplicate="fail">
<zipfileset file="${kotlin-home}/build.txt" prefix="META-INF"/>
<zipfileset dir="${js.stdlib.output.dir}" prefix="">
<include name="kotlin.js"/>
<include name="${compiled.stdlib.meta.js}"/>
<include name="kotlin/**"/>
</zipfileset>
<manifest>
<attribute name="Built-By" value="${manifest.impl.vendor}"/>
<attribute name="${manifest.impl.attribute.kotlin.version}" value="${manifest.impl.value.kotlin.version}"/>
<attribute name="${manifest.impl.attribute.kotlin.runtime.component}" value="${manifest.impl.value.kotlin.runtime.component.main}"/>
<attribute name="Implementation-Vendor" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Title" value="${manifest.impl.title.kotlin.javascript.stdlib}"/>
<attribute name="Implementation-Version" value="${build.number}"/>
<attribute name="Specification-Title" value="${manifest.spec.title.kotlin.javascript.lib}"/>
</manifest>
</jar>
<copy file="${kotlin-home}/lib/kotlin-stdlib-js.jar" tofile="${kotlin-home}/lib/kotlin-jslib.jar" />
</target>
<target name="pack-js-stdlib-sources" depends="js-stdlib-preprocess">
<jar destfile="${kotlin-home}/lib/kotlin-stdlib-js-sources.jar" duplicate="fail">
<resources refid="js.lib.files" />
<fileset refid="kotlin.builtin.files" />
<manifest>
<attribute name="Built-By" value="${manifest.impl.vendor}"/>
<attribute name="${manifest.impl.attribute.kotlin.version}" value="${manifest.impl.value.kotlin.version}"/>
<attribute name="${manifest.impl.attribute.kotlin.runtime.component}" value="${manifest.impl.value.kotlin.runtime.component.main}"/>
<attribute name="Implementation-Vendor" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Title" value="${manifest.impl.title.kotlin.jvm.runtime.sources}"/>
<attribute name="Implementation-Version" value="${build.number}"/>
</manifest>
</jar>
<copy file="${kotlin-home}/lib/kotlin-stdlib-js-sources.jar" tofile="${kotlin-home}/lib/kotlin-jslib-sources.jar" />
</target>
<target name="kotlin-js-stdlib" depends="js-stdlib,js-kotlin-test,pack-js-stdlib-sources"/>
<target name="preloader">
<cleandir dir="${output}/classes/preloader"/>
<javac destdir="${output}/classes/preloader" debug="true" debuglevel="lines,vars,source" includeAntRuntime="false"
source="1.6" target="1.6">
source="${java.target}" target="${java.target}">
<src location="${basedir}/compiler/preloader/src"/>
</javac>
@@ -306,7 +510,7 @@
<manifest>
<attribute name="Built-By" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Vendor" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Title" value="Kotlin Preloader"/>
<attribute name="Implementation-Title" value="${manifest.impl.title.kotlin.preloader}"/>
<attribute name="Implementation-Version" value="${build.number}"/>
<attribute name="Main-Class" value="org.jetbrains.kotlin.preloading.Preloader"/>
</manifest>
@@ -317,13 +521,10 @@
<cleandir dir="${output}/classes/runner"/>
<kotlinc output="${output}/classes/runner">
<src location="${basedir}/compiler/cli/cli-runner/src"/>
<compilerarg line="-jvm-target 1.6"/>
<compilerarg value="-jdk-home"/>
<compilerarg value="${env.JDK_16}"/>
</kotlinc>
<local name="runtime.jar"/>
<condition property="runtime.jar" value="kotlin-stdlib-internal-bootstrap.jar" else="kotlin-stdlib.jar">
<condition property="runtime.jar" value="kotlin-runtime-internal-bootstrap.jar" else="kotlin-runtime.jar">
<istrue value="${bootstrap.or.local.build}"/>
</condition>
@@ -333,7 +534,7 @@
<manifest>
<attribute name="Built-By" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Vendor" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Title" value="Kotlin Runner"/>
<attribute name="Implementation-Title" value="${manifest.impl.title.kotlin.runner}"/>
<attribute name="Implementation-Version" value="${build.number}"/>
<attribute name="Main-Class" value="org.jetbrains.kotlin.runner.Main"/>
<attribute name="Class-Path" value="${runtime.jar}"/>
@@ -370,7 +571,6 @@
<fileset dir="${output}/builtins">
<include name="kotlin/**"/>
</fileset>
<fileset dir="${basedir}/core/deserialization/src" includes="META-INF/services/**"/>
<fileset dir="${basedir}/core/descriptor.loader.java/src" includes="META-INF/services/**"/>
<fileset dir="${basedir}/compiler/frontend.java/src" includes="META-INF/services/**"/>
<fileset dir="${basedir}/compiler/backend/src" includes="META-INF/services/**"/>
@@ -388,20 +588,18 @@
<zipfileset src="${basedir}/ideaSDK/core/asm-all.jar"/>
<zipfileset src="${basedir}/ideaSDK/core/guava-19.0.jar"/>
<zipfileset src="${basedir}/ideaSDK/core/intellij-core.jar"/>
<zipfileset src="${basedir}/ideaSDK/core/jdom.jar" excludes="META-INF/jb/** META-INF/LICENSE"/>
<zipfileset src="${basedir}/ideaSDK/core/jdom.jar"/>
<zipfileset src="${basedir}/ideaSDK/core/jna.jar"/>
<zipfileset src="${basedir}/ideaSDK/core/log4j.jar" excludes="META-INF/jb/** META-INF/LICENSE"/>
<zipfileset src="${basedir}/ideaSDK/core/log4j.jar"/>
<zipfileset src="${basedir}/ideaSDK/core/picocontainer.jar"/>
<zipfileset src="${basedir}/ideaSDK/core/snappy-in-java-0.5.1.jar"/>
<zipfileset src="${basedir}/ideaSDK/core/trove4j.jar"/>
<zipfileset src="${basedir}/ideaSDK/core/xpp3-1.1.4-min.jar"/>
<zipfileset src="${basedir}/ideaSDK/core/xstream-1.4.8.jar"/>
<zipfileset src="${idea.sdk}/lib/jna-platform.jar"/>
<zipfileset src="${idea.sdk}/lib/oromatcher.jar" excludes="META-INF/jb/** META-INF/LICENSE"/>
<zipfileset src="${idea.sdk}/lib/oromatcher.jar"/>
<zipfileset src="${idea.sdk}/jps/jps-model.jar"/>
<zipfileset src="${dependencies}/jline.jar"/>
<zipfileset src="${dependencies}/javaslang-2.0.6.jar"/>
<zipfileset src="${dependencies}/json-org.jar"/>
<zipfileset src="${protobuf.jar}"/>
<manifest>
@@ -431,29 +629,6 @@
<pack-compiler jarfile="${kotlin-home}/lib/kotlin-compiler.jar" compress="false"/>
</target>
<target name="compiler-fork">
<local name="jvmargs" />
<condition property="jvmargs" value="${compiler.ant.fork.jvmargs}" else="">
<isset property="compiler.ant.fork.jvmargs" />
</condition>
<java classname="org.apache.tools.ant.launch.Launcher"
fork="true"
failonerror="true"
timeout="4000000"
taskname="ant-fork">
<jvmarg line="${jvmargs}" />
<classpath>
<pathelement location="${ant.home}/lib/ant-launcher.jar"/>
</classpath>
<arg line="-Dbootstrap.or.local.build=${bootstrap.or.local.build}" />
<arg line="-Dbuild.number=${build.number}" />
<arg line="-f" />
<arg line="build.xml" />
<arg line="compiler" />
</java>
</target>
<target name="compiler">
<cleandir dir="${output}/classes/compiler"/>
@@ -537,12 +712,10 @@
</sequential>
</macrodef>
<target name="pack-compiler-for-maven">
<target name="compiler-for-maven">
<pack-compiler-for-maven/>
</target>
<target name="compiler-quick-for-maven" depends="compiler-quick,pack-compiler-for-maven"/>
<target name="kotlin-build-common-test">
<cleandir dir="${output}/classes/kotlin-build-common-test"/>
@@ -576,7 +749,7 @@
<manifest>
<attribute name="Built-By" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Vendor" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Title" value="Kotlin Build Common"/>
<attribute name="Implementation-Title" value="${manifest.impl.title.kotlin.build.common}"/>
<attribute name="Implementation-Version" value="${build.number}"/>
</manifest>
</jarjar>
@@ -604,7 +777,7 @@
<attribute name="Built-By" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Vendor" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Title" value="Kotlin Compile Daemon Client"/>
<attribute name="Implementation-Title" value="${manifest.impl.title.kotlin.daemon.client}"/>
<attribute name="Implementation-Version" value="${build.number}"/>
</manifest>
</jar>
@@ -637,7 +810,7 @@
<manifest>
<attribute name="Built-By" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Vendor" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Title" value="Kotlin Compiler Client Embeddable"/>
<attribute name="Implementation-Title" value="${manifest.impl.title.kotlin.compiler.client.embeddable}"/>
<attribute name="Implementation-Version" value="${build.number}"/>
<attribute name="Class-Path" value="kotlin-stdlib.jar"/>
</manifest>
@@ -752,13 +925,35 @@
</classpath>
</javac2>
<jar destfile="${kotlin-home}/lib/kotlin-source-sections-compiler-plugin.jar">
<jar destfile="${kotlin-home}/lib/source-sections-compiler-plugin.jar">
<fileset dir="${output}/classes/source-sections-compiler-plugin"/>
<zipfileset file="${kotlin-home}/build.txt" prefix="META-INF"/>
<fileset dir="${basedir}/plugins/source-sections/source-sections-compiler/src" includes="META-INF/services/**"/>
</jar>
</target>
<target name="annotation-processing-under-jdk8">
<property environment="env"/>
<condition property="jdk18" value="${env.JDK_18}" else="${env.JAVA_HOME}">
<isset property="env.JDK_18" />
</condition>
<java classname="org.apache.tools.ant.launch.Launcher"
fork="true"
failonerror="true"
timeout="4000000"
taskname="startAnt"
jvm="${jdk18}/bin/java">
<env key="JAVA_HOME" value="${jdk18}"/>
<classpath>
<pathelement location="${ant.home}/lib/ant-launcher.jar"/>
</classpath>
<arg line="-f" />
<arg line="build.xml" />
<arg line="annotation-processing" />
</java>
</target>
<target name="annotation-processing">
<cleandir dir="${output}/classes/annotation-processing"/>
@@ -820,7 +1015,7 @@
<attribute name="Built-By" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Vendor" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Title" value="Kotlin Compiler Ant Tasks"/>
<attribute name="Implementation-Title" value="${manifest.impl.title.kotlin.compiler.ant.task}"/>
<attribute name="Implementation-Version" value="${build.number}"/>
<attribute name="Class-Path" value="${compiler.manifest.class.path} kotlin-preloader.jar"/>
@@ -836,6 +1031,8 @@
<element name="class-path"/>
<sequential>
<property environment="env"/>
<cleandir dir="@{output}"/>
<dirset dir="${basedir}" id="src.dirset">
@@ -868,13 +1065,15 @@
<arg line="@{additionalOptions}"/>
<arg value="-classpath"/>
<arg value="${toString:classpath.path}"/>
<arg value="-jdk-home" />
<arg value="${env.JDK_16}" />
<arg value="-module-name"/>
<arg value="@{moduleName}"/>
<arg value="-Xallow-kotlin-package"/>
</java>
<javac2 srcdir="${toString:src.dirset}" destdir="@{output}" debug="true" debuglevel="lines,vars,source"
includeAntRuntime="false" source="1.6" target="1.6">
includeAntRuntime="false" source="${java.target.1.6}" target="${java.target.1.6}">
<skip pattern="kotlin/Metadata"/>
<classpath>
<path refid="classpath.path"/>
@@ -885,10 +1084,162 @@
</sequential>
</macrodef>
<macrodef name="kotlin-pp">
<attribute name="src"/>
<attribute name="output"/>
<attribute name="profile"/>
<sequential>
<java classname="org.jetbrains.kotlin.preloading.Preloader" failonerror="true" fork="true" maxmemory="${max.heap.size.for.forked.jvm}">
<classpath>
<pathelement location="${bootstrap.compiler.home}/lib/kotlin-preloader.jar"/>
</classpath>
<assertions>
<enable/>
</assertions>
<arg value="-cp"/>
<arg value="${bootstrap.compiler.home}/lib/kotlin-compiler.jar"/>
<arg value="org.jetbrains.kotlin.preprocessor.PreprocessorCLI"/>
<arg value="@{src}"/>
<arg value="@{output}"/>
<arg value="@{profile}"/>
</java>
</sequential>
</macrodef>
<target name="builtins">
<new-kotlinc output="${output}/classes/builtins" moduleName="kotlin-runtime">
<src>
<include name="core/builtins/src"/>
<include name="core/runtime.jvm/src"/>
</src>
<class-path>
<!-- TODO: serialize and compile built-ins in one step here instead -->
<pathelement path="${output}/builtins"/>
</class-path>
</new-kotlinc>
</target>
<target name="stdlib">
<new-kotlinc output="${output}/classes/stdlib" moduleName="kotlin-stdlib" additionalOptions="-Xmultifile-parts-inherit -Xdump-declarations-to ${output}/declarations/stdlib-declarations.json">
<src>
<include name="libraries/stdlib/src"/>
</src>
<class-path>
<pathelement path="${output}/classes/builtins"/>
<pathelement path="${output}/builtins"/>
</class-path>
</new-kotlinc>
</target>
<target name="kotlin-test">
<path id="kotlin-test-compile-classpath">
<pathelement location="${output}/builtins"/>
<pathelement location="${output}/classes/builtins"/>
<pathelement location="${output}/classes/stdlib"/>
<pathelement location="libraries/lib/junit-4.11.jar"/>
</path>
<java classname="org.jetbrains.kotlin.preloading.Preloader" failonerror="true" fork="true" maxmemory="${max.heap.size.for.forked.jvm}">
<classpath>
<pathelement location="${kotlin-home}/lib/kotlin-preloader.jar"/>
</classpath>
<assertions>
<enable/>
</assertions>
<arg value="-cp"/>
<arg value="${kotlin-home}/lib/kotlin-compiler.jar"/>
<arg value="org.jetbrains.kotlin.cli.jvm.K2JVMCompiler"/>
<arg value="-d"/>
<arg value="${output}/classes/kotlin-test"/>
<arg value="-version"/>
<arg value="-no-stdlib"/>
<arg value="-classpath"/>
<arg value="${toString:kotlin-test-compile-classpath}"/>
<arg value="-module-name"/>
<arg value="kotlin-test"/>
<arg value="-Xallow-kotlin-package"/>
<arg value="-Xmulti-platform"/>
<arg value="libraries/kotlin.test/common/src/main/kotlin"/>
<arg value="libraries/kotlin.test/jvm/src/main/kotlin"/>
<arg value="libraries/kotlin.test/junit/src/main/kotlin"/>
</java>
<pack-runtime-jar jar-name="kotlin-test.jar" implementation-title="${manifest.impl.title.kotlin.test}" runtime-component="Test">
<jar-content>
<fileset dir="${output}/classes/kotlin-test" includes="**/*" excludes="kotlin/internal/OnlyInputTypes*,kotlin/internal/InlineOnly*,kotlin/internal"/>
</jar-content>
</pack-runtime-jar>
</target>
<target name="js-kotlin-test">
<java classname="org.jetbrains.kotlin.preloading.Preloader" failonerror="true" fork="true" maxmemory="${max.heap.size.for.forked.jvm}">
<classpath>
<pathelement location="${kotlin-home}/lib/kotlin-preloader.jar"/>
</classpath>
<assertions>
<enable/>
</assertions>
<arg value="-cp"/>
<arg value="${kotlin-home}/lib/kotlin-compiler.jar"/>
<arg value="org.jetbrains.kotlin.cli.js.K2JSCompiler"/>
<arg value="-output"/>
<arg value="${output}/classes/kotlin-test-js/kotlin-test.js"/>
<arg value="-version"/>
<arg value="-meta-info"/>
<arg line="-main noCall"/>
<arg line="-module-kind umd"/>
<arg value="-Xmulti-platform"/>
<arg value="-Xallow-kotlin-package"/>
<arg value="libraries/kotlin.test/common/src/main/kotlin"/>
<arg value="libraries/kotlin.test/js/src/main/kotlin"/>
</java>
<pack-runtime-jar jar-name="kotlin-test-js.jar" implementation-title="${manifest.impl.title.kotlin.test}" runtime-component="TestJs">
<jar-content>
<fileset dir="${output}/classes/kotlin-test-js" includes="**/*" excludes="kotlin/internal/OnlyInputTypes*,kotlin/internal/InlineOnly*,kotlin/internal"/>
</jar-content>
</pack-runtime-jar>
</target>
<target name="core">
<new-kotlinc output="${output}/classes/core" moduleName="kotlin-core">
<src>
<include name="core/descriptor.loader.java/src"/>
<include name="core/descriptors/src"/>
<include name="core/descriptors.runtime/src"/>
<include name="core/deserialization/src"/>
<include name="core/util.runtime/src"/>
</src>
<class-path>
<pathelement path="${output}/classes/builtins"/>
<pathelement path="${output}/classes/stdlib"/>
<pathelement path="${protobuf-lite.jar}"/>
<pathelement path="${javax.inject.jar}"/>
<pathelement path="${output}/builtins"/>
</class-path>
</new-kotlinc>
</target>
<target name="reflection">
<new-kotlinc output="${output}/classes/reflection" moduleName="kotlin-reflection">
<src>
<include name="core/reflection.jvm/src"/>
</src>
<class-path>
<pathelement path="${output}/classes/builtins"/>
<pathelement path="${output}/classes/stdlib"/>
<pathelement path="${output}/classes/core"/>
<pathelement path="${protobuf-lite.jar}"/>
<pathelement path="${output}/builtins"/>
</class-path>
</new-kotlinc>
</target>
<macrodef name="pack-runtime-jar">
<attribute name="jar-dir" default="${kotlin-home}/lib"/>
<attribute name="jar-name"/>
<attribute name="implementation-title"/>
<attribute name="runtime-component" default="${manifest.impl.value.kotlin.runtime.component.main}"/>
<element name="jar-content"/>
<sequential>
@@ -900,6 +1251,8 @@
<manifest>
<attribute name="Built-By" value="${manifest.impl.vendor}"/>
<attribute name="${manifest.impl.attribute.kotlin.version}" value="${manifest.impl.value.kotlin.version}"/>
<attribute name="${manifest.impl.attribute.kotlin.runtime.component}" value="@{runtime-component}"/>
<attribute name="Implementation-Vendor" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Title" value="@{implementation-title}"/>
@@ -909,62 +1262,151 @@
</sequential>
</macrodef>
<macrodef name="run-gradle-build">
<attribute name="tasks" />
<sequential>
<local name="deployVersion" />
<condition property="deployVersion" value="" else="-PdeployVersion=${build.number}">
<equals arg1="${build.number}" arg2="snapshot" />
</condition>
<target name="pack-runtime">
<pack-runtime-jar jar-name="kotlin-stdlib.jar" implementation-title="${manifest.impl.title.kotlin.jvm.runtime}">
<jar-content>
<fileset dir="${output}/classes/builtins"/>
<fileset dir="${output}/classes/stdlib"/>
<zipfileset dir="${output}/builtins">
<include name="kotlin/**"/>
<!-- TODO: load metadata from @Metadata annotation in KotlinBuiltIns on JVM and restore this exclusion (also below in mock-runtime) -->
<!-- exclude name="kotlin/reflect/**"/ -->
</zipfileset>
</jar-content>
</pack-runtime-jar>
<copy file="${kotlin-home}/lib/kotlin-stdlib.jar" tofile="${kotlin-home}/lib/kotlin-runtime.jar"/>
<java classname="org.gradle.wrapper.GradleWrapperMain"
fork="true"
dir="${basedir}/libraries"
failonerror="true"
timeout="4000000"
maxmemory="400m"
taskname="gradle">
<pack-runtime-jar jar-dir="${output}" jar-name="kotlin-reflect-before-jarjar.jar" implementation-title="${manifest.impl.title.kotlin.jvm.reflect}">
<jar-content>
<fileset dir="${basedir}/core/descriptor.loader.java/src" includes="META-INF/services/**"/>
<fileset dir="${output}/classes/reflection"/>
<fileset dir="${output}/classes/core"/>
<zipfileset src="${protobuf-lite.jar}"/>
<zipfileset src="${javax.inject.jar}"/>
</jar-content>
</pack-runtime-jar>
<jar destfile="${output}/kotlin-reflect-before-jarjar.jar" update="true">
<manifest>
<attribute name="Class-Path" value="kotlin-runtime.jar"/>
</manifest>
</jar>
<sequential if:true="${obfuscate.reflect}">
<taskdef name="jarjar" classname="com.tonicsystems.jarjar.JarJarTask" classpath="dependencies/jarjar.jar"/>
<delete file="${output}/kotlin-reflect-after-jarjar.jar" failonerror="false"/>
<jarjar jarfile="${output}/kotlin-reflect-after-jarjar.jar" filesonly="true" filesetmanifest="merge">
<zipfileset src="${output}/kotlin-reflect-before-jarjar.jar"/>
<rule pattern="org.jetbrains.kotlin.**" result="kotlin.reflect.jvm.internal.impl.@1"/>
<rule pattern="javax.inject.**" result="kotlin.reflect.jvm.internal.impl.javax.inject.@1"/>
</jarjar>
<kotlinc src="${basedir}/generators/infrastructure/strip-kotlin-annotations.kts" output="">
<compilerarg value="-version"/>
<compilerarg value="-script"/>
<compilerarg value="kotlin/Metadata"/> <!-- Annotation to strip -->
<compilerarg value="kotlin/reflect/jvm/internal/impl/.*"/> <!-- Classes to strip from -->
<compilerarg value="${output}/kotlin-reflect-after-jarjar.jar"/>
<compilerarg value="${output}/kotlin-reflect-before-proguard.jar"/>
<classpath>
<pathelement location="${basedir}/libraries/gradle/wrapper/gradle-wrapper.jar"/>
<pathelement location="${idea.sdk}/lib/asm-all.jar"/>
</classpath>
<arg line="@{tasks}" />
<arg line="--no-daemon -Dkotlin.daemon.jvm.options=-Xmx700m -Dkotlin.daemon.verbose=true" />
<arg line="${deployVersion}" />
<arg line="${gradle.logging.level}" />
</java>
</kotlinc>
<shrink configuration="${basedir}/core/reflection.jvm/reflection.pro"/>
</sequential>
</macrodef>
<target name="gradle-runtime">
<run-gradle-build tasks="clean dist publish" />
<!-- legacy artifact, required for migration on teamcity -->
<jar destfile="${output}/kotlin-reflect-sources-for-maven.jar" />
<sequential unless:true="${obfuscate.reflect}">
<echo message="Obfuscation of kotlin-reflect is disabled"/>
<copy file="${output}/kotlin-reflect-before-jarjar.jar" tofile="${kotlin-home}/lib/kotlin-reflect.jar" overwrite="true"/>
</sequential>
</target>
<target name="stdlib-js">
<run-gradle-build tasks=":kotlin-stdlib-js:dist :kotlin-test:kotlin-test-js:dist --rerun-tasks" />
<target name="pack-runtime-sources">
<delete dir="${output}/core.src" failonerror="false"/>
<local name="runtime.sources.base.dir"/>
<condition property="runtime.sources.base.dir"
value="${output}/core.src/kotlin/reflect/jvm/internal/impl"
else="${output}/core.src/org/jetbrains/kotlin">
<istrue value="${obfuscate.reflect}"/>
</condition>
<copy todir="${runtime.sources.base.dir}">
<fileset dir="core">
<include name="descriptor.loader.java/src/**"/>
<include name="descriptors/src/**"/>
<include name="descriptors.runtime/src/**"/>
<include name="deserialization/src/**"/>
<include name="util.runtime/src/**"/>
</fileset>
<cutdirsmapper dirs="5"/> <!-- module/src/org/jetbrains/kotlin -->
</copy>
<sequential if:true="${obfuscate.reflect}">
<!-- Rename packages in the sources of reflection impl (core) -->
<replaceregexp match="org\.jetbrains\.kotlin" replace="kotlin.reflect.jvm.internal.impl" flags="g">
<fileset dir="${output}/core.src"/>
</replaceregexp>
</sequential>
<pack-runtime-jar jar-name="kotlin-stdlib-sources.jar" implementation-title="${manifest.impl.title.kotlin.jvm.runtime.sources}">
<jar-content>
<fileset dir="${basedir}/core/builtins/native" includes="**/*"/>
<fileset dir="${basedir}/core/builtins/src" includes="**/*"/>
<fileset dir="${basedir}/core/reflection.jvm/src" includes="**/*"/>
<fileset dir="${basedir}/core/runtime.jvm/src" includes="**/*"/>
<fileset dir="${basedir}/libraries/stdlib/src" includes="**/*"/>
<fileset dir="${output}/core.src" includes="**/*"/>
</jar-content>
</pack-runtime-jar>
<copy file="${kotlin-home}/lib/kotlin-stdlib-sources.jar" tofile="${kotlin-home}/lib/kotlin-runtime-sources.jar"/>
<pack-runtime-jar jar-dir="${output}" jar-name="kotlin-reflect-sources-for-maven.jar"
implementation-title="${manifest.impl.title.kotlin.jvm.reflect.sources}">
<jar-content>
<fileset dir="${basedir}/core/reflection.jvm/src" includes="**/*"/>
<fileset dir="${output}/core.src" includes="**/*"/>
</jar-content>
</pack-runtime-jar>
</target>
<target name="compiler-quick-and-stdlib-js"
depends="compiler-quick-for-maven,stdlib-js"/>
<target name="script-runtime">
<new-kotlinc output="${output}/classes/script-runtime" moduleName="kotlin-script-runtime">
<src>
<include name="core/script.runtime/src"/>
</src>
<class-path>
<pathelement path="${output}/classes/builtins"/>
<pathelement path="${output}/builtins"/>
</class-path>
</new-kotlinc>
<pack-runtime-jar jar-name="kotlin-script-runtime.jar" implementation-title="${manifest.impl.title.kotlin.script.runtime}">
<jar-content>
<fileset dir="${output}/classes/script-runtime"/>
</jar-content>
</pack-runtime-jar>
<pack-runtime-jar jar-name="kotlin-script-runtime-sources.jar" implementation-title="${manifest.impl.title.kotlin.script.runtime.sources}">
<jar-content>
<fileset dir="${basedir}/core/script.runtime/src" includes="**/*"/>
</jar-content>
</pack-runtime-jar>
</target>
<target name="runtime"
depends="gradle-runtime,mock-runtime-for-test"/>
<target name="other-artifacts"
depends="android-extensions-compiler,allopen-compiler-plugin,noarg-compiler-plugin,sam-with-receiver-compiler-plugin,source-sections-compiler-plugin,annotation-processing,daemon-client,compiler-client-embeddable,kotlin-build-common-test" />
depends="builtins,stdlib,kotlin-test,core,reflection,pack-runtime,pack-runtime-sources,script-runtime,mock-runtime-for-test"/>
<target name="dist"
depends="clean,init,prepare-dist,preloader,runner,serialize-builtins,compiler-fork,compiler-sources,ant-tools,runtime,other-artifacts"
depends="clean,init,prepare-dist,preloader,runner,serialize-builtins,compiler,compiler-sources,ant-tools,runtime,kotlin-js-stdlib,android-extensions-compiler,allopen-compiler-plugin,noarg-compiler-plugin,sam-with-receiver-compiler-plugin,source-sections-compiler-plugin,annotation-processing-under-jdk8,daemon-client,compiler-client-embeddable,kotlin-build-common-test"
description="Builds redistributables from sources"/>
<target name="dist-no-fork"
depends="clean,init,prepare-dist,preloader,runner,serialize-builtins,compiler,compiler-sources,ant-tools,runtime,other-artifacts"
description="Builds redistributables from sources"/>
<target name="dist-quick"
depends="clean,init,prepare-dist,preloader,serialize-builtins,compiler-quick,ant-tools,runtime,kotlin-js-stdlib,android-extensions-compiler,allopen-compiler-plugin,noarg-compiler-plugin,sam-with-receiver-compiler-plugin,source-sections-compiler-plugin,annotation-processing-under-jdk8"
description="Builds everything, but classes are reused from project out dir, doesn't run proguard and javadoc"/>
<target name="dist-quick-compiler-only"
depends="init,prepare-dist,preloader,serialize-builtins,compiler-quick-for-maven"
depends="init,prepare-dist,preloader,serialize-builtins,compiler-quick"
description="Builds compiler jar from project out dir"/>
<target name="zip-compiler">
@@ -998,7 +1440,8 @@
<include name="dist/mock-runtime-src"/>
</src>
<class-path>
<pathelement path="${output}/kotlinc/lib/kotlin-stdlib.jar" />
<pathelement path="${output}/classes/builtins"/>
<pathelement path="${output}/builtins"/>
</class-path>
</new-kotlinc>

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();
@@ -148,7 +151,7 @@ public class CodegenTestsOnAndroidRunner {
for (int i = 0; i < testCases.getLength(); i++) {
Element item = (Element) testCases.item(i);
NodeList failure = item.getElementsByTagName("failure");
final NodeList failure = item.getElementsByTagName("failure");
String name = item.getAttribute("name");
String clazz = item.getAttribute("classname");

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>();
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() {
@@ -195,18 +195,21 @@ public class SDKDownloader {
}
try {
byte[] buf = new byte[1024];
ZipEntry zipEntry = null;
try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(pathToFile))) {
zipEntry = zipInputStream.getNextEntry();
while (zipEntry != null) {
String entryName = zipEntry.getName();
ZipInputStream zipinputstream;
ZipEntry zipentry;
zipinputstream = new ZipInputStream(new FileInputStream(pathToFile));
zipentry = zipinputstream.getNextEntry();
try {
while (zipentry != null) {
String entryName = zipentry.getName();
int n;
File outputFile = new File(outputFolder + "/" + entryName);
if (zipEntry.isDirectory()) {
if (zipentry.isDirectory()) {
outputFile.mkdirs();
zipInputStream.closeEntry();
zipEntry = zipInputStream.getNextEntry();
zipinputstream.closeEntry();
zipentry = zipinputstream.getNextEntry();
continue;
}
else {
@@ -217,19 +220,23 @@ public class SDKDownloader {
outputFile.createNewFile();
}
try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {
while ((n = zipInputStream.read(buf, 0, 1024)) > -1) {
fileOutputStream.write(buf, 0, n);
FileOutputStream fileoutputstream = new FileOutputStream(outputFile);
try {
while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
fileoutputstream.write(buf, 0, n);
}
}
zipInputStream.closeEntry();
zipEntry = zipInputStream.getNextEntry();
finally {
fileoutputstream.close();
}
zipinputstream.closeEntry();
zipentry = zipinputstream.getNextEntry();
}
zipinputstream.close();
}
catch (IOException e) {
if (zipEntry != null) {
System.err.println("Entry name: " + zipEntry.getName());
}
System.err.println("Entry name: " + zipentry.getName());
e.printStackTrace();
}
}

View File

@@ -30,7 +30,7 @@ public class GradleRunner {
private final List<String> listOfCommands;
public GradleRunner(PathManager pathManager) {
listOfCommands = new ArrayList<>();
listOfCommands = new ArrayList<String>();
String cmdName = SystemInfo.isWindows ? "gradle.bat" : "gradle";
listOfCommands.add(pathManager.getGradleBinFolder() + "/" + cmdName);
listOfCommands.add("--build-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

@@ -86,15 +86,22 @@ public class RunUtils {
return run(settings);
}
public static void executeOnSeparateThread(@NotNull RunSettings settings) {
public static void executeOnSeparateThread(@NotNull final RunSettings settings) {
assert !settings.waitForEnd : "Use execute() instead";
new Thread(() -> run(settings)).start();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
RunUtils.run(settings);
}
});
t.start();
}
private static RunResult run(RunSettings settings) {
private static RunResult run(final RunSettings settings) {
System.out.println("RUN COMMAND: " + settings);
StringBuilder stdOut = new StringBuilder();
StringBuilder stdErr = new StringBuilder();
final StringBuilder stdOut = new StringBuilder();
final StringBuilder stdErr = new StringBuilder();
OSProcessHandler handler;
try {
@@ -104,7 +111,10 @@ public class RunUtils {
}
close(handler.getProcessInput());
}
catch (ExecutionException | IOException e) {
catch (ExecutionException e) {
return new RunResult(false, getStackTrace(e));
}
catch (IOException e) {
return new RunResult(false, getStackTrace(e));
}

View File

@@ -64,8 +64,11 @@ public class AndroidRunner extends TestSuite {
private static void writeAndroidSkdToLocalProperties() throws IOException {
System.out.println("Writing android sdk to local.properties: " + pathManager.getAndroidSdkRoot());
File file = new File(pathManager.getTmpFolder() + "/local.properties");
try (FileWriter fw = new FileWriter(file)) {
FileWriter fw = new FileWriter(file);
try {
fw.write("sdk.dir=" + pathManager.getAndroidSdkRoot());
} finally {
fw.close();
}
}
}

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();
@@ -143,7 +142,7 @@ public class CodegenTestsOnAndroidGenerator extends KtUsefulTestCase {
private final boolean isFullJdkAndRuntime;
private final boolean inheritMultifileParts;
public List<KtFile> files = new ArrayList<>();
public List<KtFile> files = new ArrayList<KtFile>();
private KotlinCoreEnvironment environment;
private FilesWriter(boolean isFullJdkAndRuntime, boolean inheritMultifileParts) {
@@ -176,7 +175,7 @@ public class CodegenTestsOnAndroidGenerator extends KtUsefulTestCase {
public void writeFilesOnDisk() {
writeFiles(files);
files = new ArrayList<>();
files = new ArrayList<KtFile>();
environment = createEnvironment(isFullJdkAndRuntime);
}
@@ -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) {};
@@ -38,7 +37,7 @@ public abstract class AbstractClassBuilder implements ClassBuilder {
private final JvmSerializationBindings serializationBindings = new JvmSerializationBindings();
private final List<FileMapping> fileMappings = new ArrayList<>();
private final List<FileMapping> fileMappings = new ArrayList<FileMapping>();
private String sourceName;
@@ -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

@@ -56,7 +56,7 @@ public class AccessorForFunctionDescriptor extends AbstractAccessorForFunctionDe
setSuspend(descriptor.isSuspend());
if (descriptor.getUserData(CoroutineCodegenUtilKt.INITIAL_DESCRIPTOR_FOR_SUSPEND_FUNCTION) != null) {
userDataMap = new LinkedHashMap<>();
userDataMap = new LinkedHashMap<UserDataKey<?>, Object>();
userDataMap.put(
CoroutineCodegenUtilKt.INITIAL_DESCRIPTOR_FOR_SUSPEND_FUNCTION,
descriptor.getUserData(CoroutineCodegenUtilKt.INITIAL_DESCRIPTOR_FOR_SUSPEND_FUNCTION)

View File

@@ -27,18 +27,14 @@ import org.jetbrains.kotlin.load.java.JvmAnnotationNames;
import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.resolve.AnnotationChecker;
import org.jetbrains.kotlin.resolve.constants.*;
import org.jetbrains.kotlin.resolve.constants.StringValue;
import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt;
import org.jetbrains.kotlin.types.FlexibleType;
import org.jetbrains.kotlin.types.FlexibleTypesKt;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.kotlin.types.TypeUtils;
import org.jetbrains.kotlin.types.*;
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 {
@@ -101,7 +97,7 @@ public abstract class AnnotationCodegen {
return;
}
Set<String> annotationDescriptorsAlreadyPresent = new HashSet<>();
Set<String> annotationDescriptorsAlreadyPresent = new HashSet<String>();
Annotations annotations = annotated.getAnnotations();
@@ -214,7 +210,8 @@ public abstract class AnnotationCodegen {
generateAnnotationIfNotPresent(annotationDescriptorsAlreadyPresent, annotationClass);
}
private static final Map<KotlinTarget, ElementType> annotationTargetMap = new EnumMap<>(KotlinTarget.class);
private static final Map<KotlinTarget, ElementType> annotationTargetMap =
new EnumMap<KotlinTarget, ElementType>(KotlinTarget.class);
static {
annotationTargetMap.put(KotlinTarget.CLASS, ElementType.TYPE);
@@ -291,7 +288,7 @@ public abstract class AnnotationCodegen {
@Nullable
private String genAnnotation(@NotNull AnnotationDescriptor annotationDescriptor) {
ClassifierDescriptor classifierDescriptor = getAnnotationClass(annotationDescriptor);
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) {
@@ -321,9 +318,9 @@ public abstract class AnnotationCodegen {
}
private void genCompileTimeValue(
@Nullable String name,
@Nullable final String name,
@NotNull ConstantValue<?> value,
@NotNull AnnotationVisitor annotationVisitor
@NotNull final AnnotationVisitor annotationVisitor
) {
AnnotationArgumentVisitor argumentVisitor = new AnnotationArgumentVisitor<Void, Void>() {
@Override
@@ -431,7 +428,8 @@ public abstract class AnnotationCodegen {
value.accept(argumentVisitor, null);
}
private static final Map<KotlinRetention, RetentionPolicy> annotationRetentionMap = new EnumMap<>(KotlinRetention.class);
private static final Map<KotlinRetention, RetentionPolicy> annotationRetentionMap =
new EnumMap<KotlinRetention, RetentionPolicy>(KotlinRetention.class);
static {
annotationRetentionMap.put(KotlinRetention.SOURCE, RetentionPolicy.SOURCE);
@@ -497,7 +495,7 @@ public abstract class AnnotationCodegen {
abstract AnnotationVisitor visitAnnotation(String descr, boolean visible);
public static AnnotationCodegen forClass(
@NotNull ClassVisitor cv,
final @NotNull ClassVisitor cv,
@NotNull InnerClassConsumer innerClassConsumer,
@NotNull KotlinTypeMapper mapper
) {
@@ -511,7 +509,7 @@ public abstract class AnnotationCodegen {
}
public static AnnotationCodegen forMethod(
@NotNull MethodVisitor mv,
final @NotNull MethodVisitor mv,
@NotNull InnerClassConsumer innerClassConsumer,
@NotNull KotlinTypeMapper mapper
) {
@@ -525,7 +523,7 @@ public abstract class AnnotationCodegen {
}
public static AnnotationCodegen forField(
@NotNull FieldVisitor fv,
final @NotNull FieldVisitor fv,
@NotNull InnerClassConsumer innerClassConsumer,
@NotNull KotlinTypeMapper mapper
) {
@@ -539,8 +537,8 @@ public abstract class AnnotationCodegen {
}
public static AnnotationCodegen forParameter(
int parameter,
@NotNull MethodVisitor mv,
final int parameter,
final @NotNull MethodVisitor mv,
@NotNull InnerClassConsumer innerClassConsumer,
@NotNull KotlinTypeMapper mapper
) {
@@ -554,7 +552,7 @@ public abstract class AnnotationCodegen {
}
public static AnnotationCodegen forAnnotationDefaultValue(
@NotNull MethodVisitor mv,
final @NotNull MethodVisitor mv,
@NotNull InnerClassConsumer innerClassConsumer,
@NotNull KotlinTypeMapper mapper
) {

View File

@@ -21,18 +21,17 @@ import com.google.common.collect.Sets;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.tree.IElementType;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
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.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;
@@ -67,7 +66,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;
@@ -353,7 +352,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;
@@ -397,10 +396,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)) {
@@ -451,7 +446,7 @@ public class AsmUtil {
}
public static void genClosureFields(@NotNull CalculatedClosure closure, ClassBuilder v, KotlinTypeMapper typeMapper) {
List<Pair<String, Type>> allFields = new ArrayList<>();
List<Pair<String, Type>> allFields = new ArrayList<Pair<String, Type>>();
ClassifierDescriptor captureThis = closure.getCaptureThis();
if (captureThis != null) {
@@ -505,16 +500,19 @@ public class AsmUtil {
v.invokevirtual("java/lang/StringBuilder", "append", "(" + type.getDescriptor() + ")Ljava/lang/StringBuilder;", false);
}
public static StackValue genToString(StackValue receiver, Type receiverType) {
return StackValue.operation(JAVA_STRING_TYPE, v -> {
Type type = stringValueOfType(receiverType);
receiver.put(type, v);
v.invokestatic("java/lang/String", "valueOf", "(" + type.getDescriptor() + ")Ljava/lang/String;", false);
return null;
public static StackValue genToString(final StackValue receiver, final Type receiverType) {
return StackValue.operation(JAVA_STRING_TYPE, new Function1<InstructionAdapter, Unit>() {
@Override
public Unit invoke(InstructionAdapter v) {
Type type = stringValueOfType(receiverType);
receiver.put(type, v);
v.invokestatic("java/lang/String", "valueOf", "(" + type.getDescriptor() + ")Ljava/lang/String;", false);
return null;
}
});
}
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) {
@@ -527,6 +525,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();
@@ -535,24 +543,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
}
}
@@ -571,25 +563,28 @@ public class AsmUtil {
@NotNull
public static StackValue genEqualsForExpressionsOnStack(
@NotNull IElementType opToken,
@NotNull StackValue left,
@NotNull StackValue right
final @NotNull IElementType opToken,
final @NotNull StackValue left,
final @NotNull StackValue right
) {
Type leftType = left.type;
Type rightType = right.type;
final Type leftType = left.type;
final Type rightType = right.type;
if (isPrimitive(leftType) && leftType == rightType) {
return StackValue.cmp(opToken, leftType, left, right);
}
return StackValue.operation(Type.BOOLEAN_TYPE, v -> {
left.put(leftType, v);
right.put(rightType, v);
genAreEqualCall(v);
return StackValue.operation(Type.BOOLEAN_TYPE, new Function1<InstructionAdapter, Unit>() {
@Override
public Unit invoke(InstructionAdapter v) {
left.put(leftType, v);
right.put(rightType, v);
genAreEqualCall(v);
if (opToken == KtTokens.EXCLEQ || opToken == KtTokens.EXCLEQEQEQ) {
genInvertBoolean(v);
if (opToken == KtTokens.EXCLEQ || opToken == KtTokens.EXCLEQEQEQ) {
genInvertBoolean(v);
}
return Unit.INSTANCE;
}
return Unit.INSTANCE;
});
}
@@ -654,8 +649,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;
@@ -693,8 +686,8 @@ public class AsmUtil {
@NotNull
public static StackValue genNotNullAssertions(
@NotNull GenerationState state,
@NotNull StackValue stackValue,
@Nullable RuntimeAssertionInfo runtimeAssertionInfo
@NotNull final StackValue stackValue,
@Nullable final RuntimeAssertionInfo runtimeAssertionInfo
) {
if (state.isCallAssertionsDisabled()) return stackValue;
if (runtimeAssertionInfo == null || !runtimeAssertionInfo.getNeedNotNullAssertion()) return stackValue;
@@ -798,16 +791,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());
}
@@ -824,22 +807,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;

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

@@ -209,9 +209,33 @@ class NumberCompare(
right: StackValue
) : BranchedValue(left, right, operandType, NumberCompare.getNumberCompareOpcode(opToken)) {
override fun patchOpcode(opcode: Int, v: InstructionAdapter): Int =
patchOpcode(opcode, v, opToken, operandType)
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"
}
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) {
@@ -226,27 +250,6 @@ class NumberCompare(
}
}
}
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
}
Type.LONG_TYPE -> {
v.lcmp()
opcode
}
else ->
opcode + (IF_ICMPEQ - IFEQ)
}
}
}
}
@@ -267,91 +270,3 @@ class ObjectCompare(
}
}
}
abstract class SafeCallFusedWithPrimitiveEqualityBase(
val opToken: IElementType,
operandType: Type,
left: StackValue,
right: StackValue
) : BranchedValue(left, right, operandType, NumberCompare.getNumberCompareOpcode(opToken)) {
private val trueIfEqual = opToken == KtTokens.EQEQ || opToken == KtTokens.EQEQEQ
protected abstract fun cleanupOnNullReceiver(v: InstructionAdapter)
override fun patchOpcode(opcode: Int, v: InstructionAdapter): Int =
NumberCompare.patchOpcode(opcode, v, opToken, operandType)
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,
val safeReceiverType: Type,
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,
val safeReceiverType: Type,
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)
}
}

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

@@ -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(
@@ -59,7 +54,7 @@ public abstract class ClassBodyCodegen extends MemberCodegen<KtPureClassOrObject
@Override
protected void generateBody() {
List<KtObjectDeclaration> companions = new ArrayList<>();
List<KtObjectDeclaration> companions = new ArrayList<KtObjectDeclaration>();
if (kind != OwnerKind.DEFAULT_IMPLS) {
//generate nested classes first and only then generate class body. It necessary to access to nested CodegenContexts
for (KtDeclaration declaration : myClass.getDeclarations()) {

View File

@@ -101,7 +101,7 @@ public class ClassBuilderFactories {
}
@NotNull
public static ClassBuilderFactory binaries(boolean generateSourceRetentionAnnotations) {
public static ClassBuilderFactory binaries(final boolean generateSourceRetentionAnnotations) {
return new ClassBuilderFactory() {
@NotNull
@Override

View File

@@ -18,6 +18,8 @@ package org.jetbrains.kotlin.codegen;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import kotlin.collections.CollectionsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -42,12 +44,12 @@ import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.getMappingFileName;
public class ClassFileFactory implements OutputFileCollection {
private final GenerationState state;
private final ClassBuilderFactory builderFactory;
private final Map<String, OutAndSourceFileList> generators = new LinkedHashMap<>();
private final Map<String, OutAndSourceFileList> generators = new LinkedHashMap<String, OutAndSourceFileList>();
private boolean isDone = false;
private final Set<File> packagePartSourceFiles = new HashSet<>();
private final Map<String, PackageParts> partsGroupedByPackage = new LinkedHashMap<>();
private final Set<File> packagePartSourceFiles = new HashSet<File>();
private final Map<String, PackageParts> partsGroupedByPackage = new LinkedHashMap<String, PackageParts>();
public ClassFileFactory(@NotNull GenerationState state, @NotNull ClassBuilderFactory builderFactory) {
this.state = state;
@@ -92,7 +94,7 @@ public class ClassFileFactory implements OutputFileCollection {
}
private void writeModuleMappings() {
JvmPackageTable.PackageTable.Builder builder = JvmPackageTable.PackageTable.newBuilder();
final JvmPackageTable.PackageTable.Builder builder = JvmPackageTable.PackageTable.newBuilder();
String outputFilePath = getMappingFileName(state.getModuleName());
for (PackageParts part : ClassFileUtilsKt.addCompiledPartsAndSort(partsGroupedByPackage.values(), state)) {
@@ -128,7 +130,12 @@ public class ClassFileFactory implements OutputFileCollection {
@NotNull
public List<OutputFile> getCurrentOutput() {
return CollectionsKt.map(generators.keySet(), OutputClassFile::new);
return ContainerUtil.map(generators.keySet(), new Function<String, OutputFile>() {
@Override
public OutputFile fun(String relativeClassFilePath) {
return new OutputClassFile(relativeClassFilePath);
}
});
}
@Override
@@ -153,7 +160,7 @@ public class ClassFileFactory implements OutputFileCollection {
@NotNull
@TestOnly
public Map<String, String> createTextForEachFile() {
Map<String, String> answer = new LinkedHashMap<>();
Map<String, String> answer = new LinkedHashMap<String, String>();
for (OutputFile file : asList()) {
answer.put(file.getRelativePath(), file.asText());
}
@@ -175,10 +182,17 @@ public class ClassFileFactory implements OutputFileCollection {
}
private PackagePartRegistry buildNewPackagePartRegistry(@NotNull FqName packageFqName) {
String packageFqNameAsString = packageFqName.asString();
return (partShortName, facadeShortName) -> {
PackageParts packageParts = partsGroupedByPackage.computeIfAbsent(packageFqNameAsString, PackageParts::new);
packageParts.addPart(partShortName, facadeShortName);
final String packageFqNameAsString = packageFqName.asString();
return new PackagePartRegistry() {
@Override
public void addPart(@NotNull String partShortName, @Nullable String facadeShortName) {
PackageParts packageParts = partsGroupedByPackage.get(packageFqNameAsString);
if (packageParts == null) {
packageParts = new PackageParts(packageFqNameAsString);
partsGroupedByPackage.put(packageFqNameAsString, packageParts);
}
packageParts.addPart(partShortName, facadeShortName);
}
};
}
@@ -188,7 +202,7 @@ public class ClassFileFactory implements OutputFileCollection {
@NotNull
private static List<File> toIoFilesIgnoringNonPhysical(@NotNull Collection<? extends PsiFile> psiFiles) {
List<File> result = new ArrayList<>(psiFiles.size());
List<File> result = new ArrayList<File>(psiFiles.size());
for (PsiFile psiFile : psiFiles) {
VirtualFile virtualFile = psiFile.getVirtualFile();
// We ignore non-physical files here, because this code is needed to tell the make what inputs affect which outputs

View File

@@ -21,12 +21,14 @@ import com.intellij.util.ArrayUtil;
import kotlin.Pair;
import kotlin.Unit;
import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.codegen.binding.CalculatedClosure;
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;
@@ -47,6 +49,7 @@ import org.jetbrains.kotlin.serialization.ProtoBuf;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils;
import org.jetbrains.kotlin.util.OperatorNameConventions;
import org.jetbrains.org.objectweb.asm.AnnotationVisitor;
import org.jetbrains.org.objectweb.asm.MethodVisitor;
import org.jetbrains.org.objectweb.asm.Type;
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
@@ -59,7 +62,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;
@@ -100,7 +102,7 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
this.strategy = strategy;
if (samType == null) {
this.superInterfaceTypes = new ArrayList<>();
this.superInterfaceTypes = new ArrayList<KotlinType>();
KotlinType superClassType = null;
for (KotlinType supertype : classDescriptor.getTypeConstructor().getSupertypes()) {
@@ -158,7 +160,7 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
superInterfaceAsmTypes
);
initDefaultSourceMappingIfNeeded(context, this, state);
InlineCodegenUtil.initDefaultSourceMappingIfNeeded(context, this, state);
v.visitSource(element.getContainingFile().getName(), null);
}
@@ -234,14 +236,17 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
assert method != null : "No method for " + frontendFunDescriptor;
v.getSerializationBindings().put(METHOD_FOR_FUNCTION, freeLambdaDescriptor, method);
DescriptorSerializer serializer =
final DescriptorSerializer serializer =
DescriptorSerializer.createForLambda(new JvmSerializerExtension(v.getSerializationBindings(), state));
ProtoBuf.Function functionProto = serializer.functionProto(freeLambdaDescriptor).build();
final ProtoBuf.Function functionProto = serializer.functionProto(freeLambdaDescriptor).build();
WriteAnnotationUtilKt.writeKotlinMetadata(v, state, KotlinClassHeader.Kind.SYNTHETIC_CLASS, 0, av -> {
writeAnnotationData(av, serializer, functionProto);
return Unit.INSTANCE;
WriteAnnotationUtilKt.writeKotlinMetadata(v, state, KotlinClassHeader.Kind.SYNTHETIC_CLASS, 0, new Function1<AnnotationVisitor, Unit>() {
@Override
public Unit invoke(AnnotationVisitor av) {
writeAnnotationData(av, serializer, functionProto);
return Unit.INSTANCE;
}
});
}
@@ -250,9 +255,9 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
* This is needed because once we're serializing this to a proto, there's no place to store information about external type parameters.
*/
@NotNull
public static FunctionDescriptor createFreeLambdaDescriptor(@NotNull FunctionDescriptor descriptor) {
private static FunctionDescriptor createFreeLambdaDescriptor(@NotNull FunctionDescriptor descriptor) {
FunctionDescriptor.CopyBuilder<? extends FunctionDescriptor> builder = descriptor.newCopyBuilder();
List<TypeParameterDescriptor> typeParameters = new ArrayList<>(0);
List<TypeParameterDescriptor> typeParameters = new ArrayList<TypeParameterDescriptor>(0);
builder.setTypeParameters(typeParameters);
DeclarationDescriptor container = descriptor.getContainingDeclaration();
@@ -276,22 +281,25 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
}
@NotNull
public StackValue putInstanceOnStack(@NotNull ExpressionCodegen codegen, @Nullable StackValue functionReferenceReceiver) {
public StackValue putInstanceOnStack(@NotNull final ExpressionCodegen codegen, @Nullable final StackValue functionReferenceReceiver) {
return StackValue.operation(
functionReferenceTarget != null ? K_FUNCTION : asmType,
v -> {
if (isConst(closure)) {
v.getstatic(asmType.getInternalName(), JvmAbi.INSTANCE_FIELD, asmType.getDescriptor());
}
else {
v.anew(asmType);
v.dup();
new Function1<InstructionAdapter, Unit>() {
@Override
public Unit invoke(InstructionAdapter v) {
if (isConst(closure)) {
v.getstatic(asmType.getInternalName(), JvmAbi.INSTANCE_FIELD, asmType.getDescriptor());
}
else {
v.anew(asmType);
v.dup();
codegen.pushClosureOnStack(classDescriptor, true, codegen.defaultCallGenerator, functionReferenceReceiver);
v.invokespecial(asmType.getInternalName(), "<init>", constructor.getDescriptor(), false);
}
codegen.pushClosureOnStack(classDescriptor, true, codegen.defaultCallGenerator, functionReferenceReceiver);
v.invokespecial(asmType.getInternalName(), "<init>", constructor.getDescriptor(), false);
}
return Unit.INSTANCE;
return Unit.INSTANCE;
}
}
);
}

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

@@ -17,11 +17,15 @@
package org.jetbrains.kotlin.codegen;
public interface CompilationErrorHandler {
CompilationErrorHandler THROW_EXCEPTION = (exception, fileUrl) -> {
if (exception instanceof RuntimeException) {
throw (RuntimeException) exception;
CompilationErrorHandler THROW_EXCEPTION = new CompilationErrorHandler() {
@Override
public void reportException(Throwable exception, String fileUrl) {
if (exception instanceof RuntimeException) {
throw (RuntimeException) exception;
}
throw new IllegalStateException(exception);
}
throw new IllegalStateException(exception);
};
void reportException(Throwable exception, String fileUrl);

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

@@ -22,11 +22,19 @@ import org.jetbrains.kotlin.psi.KtParameter;
import static org.jetbrains.kotlin.resolve.DescriptorToSourceUtils.descriptorToDeclaration;
public interface DefaultParameterValueLoader {
StackValue genValue(ValueParameterDescriptor descriptor, ExpressionCodegen codegen);
DefaultParameterValueLoader DEFAULT = (descriptor, codegen) -> {
KtParameter ktParameter = (KtParameter) descriptorToDeclaration(descriptor);
assert ktParameter != null;
return codegen.gen(ktParameter.getDefaultValue());
DefaultParameterValueLoader DEFAULT = new DefaultParameterValueLoader() {
@Override
public StackValue genValue(
ValueParameterDescriptor descriptor,
ExpressionCodegen codegen
) {
KtParameter jetParameter = (KtParameter) descriptorToDeclaration(descriptor);
assert jetParameter != null;
return codegen.gen(jetParameter.getDefaultValue());
}
};
}

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

@@ -20,16 +20,17 @@ import com.google.common.collect.Lists;
import com.intellij.openapi.util.Trinity;
import gnu.trove.TObjectIntHashMap;
import gnu.trove.TObjectIntIterator;
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor;
import org.jetbrains.org.objectweb.asm.Type;
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class FrameMap {
private final TObjectIntHashMap<DeclarationDescriptor> myVarIndex = new TObjectIntHashMap<>();
private final TObjectIntHashMap<DeclarationDescriptor> myVarSizes = new TObjectIntHashMap<>();
private final TObjectIntHashMap<DeclarationDescriptor> myVarIndex = new TObjectIntHashMap<DeclarationDescriptor>();
private final TObjectIntHashMap<DeclarationDescriptor> myVarSizes = new TObjectIntHashMap<DeclarationDescriptor>();
private int myMaxIndex = 0;
public int enter(DeclarationDescriptor descriptor, Type type) {
@@ -81,7 +82,7 @@ public class FrameMap {
}
public void dropTo() {
List<DeclarationDescriptor> descriptorsToDrop = new ArrayList<>();
List<DeclarationDescriptor> descriptorsToDrop = new ArrayList<DeclarationDescriptor>();
TObjectIntIterator<DeclarationDescriptor> iterator = myVarIndex.iterator();
while (iterator.hasNext()) {
iterator.advance();
@@ -114,7 +115,15 @@ public class FrameMap {
descriptors.add(Trinity.create(descriptor, varIndex, varSize));
}
descriptors.sort(Comparator.comparingInt(left -> left.second));
Collections.sort(descriptors, new Comparator<Trinity<DeclarationDescriptor, Integer, Integer>>() {
@Override
public int compare(
Trinity<DeclarationDescriptor, Integer, Integer> left,
Trinity<DeclarationDescriptor, Integer, Integer> right
) {
return left.second - right.second;
}
});
sb.append("size=").append(myMaxIndex);

View File

@@ -19,6 +19,9 @@ package org.jetbrains.kotlin.codegen;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.psi.PsiElement;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import kotlin.Unit;
import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull;
@@ -62,7 +65,6 @@ import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodParameterSignature
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.kotlin.types.TypeUtils;
import org.jetbrains.kotlin.utils.StringsKt;
import org.jetbrains.org.objectweb.asm.*;
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
import org.jetbrains.org.objectweb.asm.commons.Method;
@@ -77,13 +79,11 @@ import java.util.Set;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isNullableAny;
import static org.jetbrains.kotlin.codegen.AsmUtil.*;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isAnnotationOrJvmInterfaceWithoutDefaults;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isJvm8InterfaceWithDefaultsMember;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.*;
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 +132,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 +188,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,69 +201,19 @@ 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);
v.getSerializationBindings().put(
METHOD_FOR_FUNCTION,
CodegenUtilKt.<FunctionDescriptor>unwrapFrontendVersion(functionDescriptor),
asmMethod
);
}
generateMethodAnnotations(functionDescriptor, asmMethod, mv);
@@ -320,7 +268,7 @@ public class FunctionCodegen {
}
private void generateDelegateForDefaultImpl(
@NotNull FunctionDescriptor functionDescriptor,
@NotNull final FunctionDescriptor functionDescriptor,
@Nullable PsiElement element
) {
Method defaultImplMethod = typeMapper.mapAsmMethod(functionDescriptor, OwnerKind.DEFAULT_IMPLS);
@@ -329,17 +277,20 @@ public class FunctionCodegen {
v, "Default Impl delegate in interface", Opcodes.ACC_SYNTHETIC | Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC,
new Method(defaultImplMethod.getName() + JvmAbi.DEFAULT_IMPLS_DELEGATE_SUFFIX, defaultImplMethod.getDescriptor()),
element, JvmDeclarationOrigin.NO_ORIGIN,
state, adapter -> {
Method interfaceMethod = typeMapper.mapAsmMethod(functionDescriptor, OwnerKind.IMPLEMENTATION);
Type type = typeMapper.mapOwner(functionDescriptor);
generateDelegateToMethodBody(
-1, adapter,
interfaceMethod,
type.getInternalName(),
Opcodes.INVOKESPECIAL,
true
);
return null;
state, new Function1<InstructionAdapter, Unit>() {
@Override
public Unit invoke(InstructionAdapter adapter) {
Method interfaceMethod = typeMapper.mapAsmMethod(functionDescriptor, OwnerKind.IMPLEMENTATION);
Type type = typeMapper.mapOwner(functionDescriptor);
generateDelegateToMethodBody(
-1, adapter,
interfaceMethod,
type.getInternalName(),
Opcodes.INVOKESPECIAL,
true
);
return null;
}
}
);
}
@@ -491,7 +442,7 @@ public class FunctionCodegen {
mv.visitLabel(methodBegin);
KotlinTypeMapper typeMapper = parentCodegen.typeMapper;
if (BuiltinSpecialBridgesUtil.shouldHaveTypeSafeBarrier(functionDescriptor, typeMapper::mapAsmMethod)) {
if (BuiltinSpecialBridgesUtil.shouldHaveTypeSafeBarrier(functionDescriptor, getSignatureMapper(typeMapper))) {
generateTypeCheckBarrierIfNeeded(
new InstructionAdapter(mv), functionDescriptor, signature.getReturnType(), /* delegateParameterTypes = */null);
}
@@ -691,11 +642,14 @@ public class FunctionCodegen {
}
private static String joinParameterNames(@NotNull List<VariableDescriptor> variables) {
// stub for anonymous destructuring declaration entry
return StringsKt.join(
CollectionsKt.map(variables, descriptor -> descriptor.getName().isSpecial() ? "$_$" : descriptor.getName().asString()),
"_"
);
return org.jetbrains.kotlin.utils.StringsKt.join(CollectionsKt.map(variables, new Function1<VariableDescriptor, String>() {
@Override
public String invoke(VariableDescriptor descriptor) {
// stub for anonymous destructuring declaration entry
if (descriptor.getName().isSpecial()) return "$_$";
return descriptor.getName().asString();
}
}), "_");
}
private static void generateFacadeDelegateMethodBody(
@@ -804,13 +758,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;
@@ -823,8 +770,11 @@ public class FunctionCodegen {
Set<Bridge<Method>> bridgesToGenerate;
if (!isSpecial) {
bridgesToGenerate =
ImplKt.generateBridgesForFunctionDescriptor(descriptor, typeMapper::mapAsmMethod, IS_PURE_INTERFACE_CHECKER);
bridgesToGenerate = ImplKt.generateBridgesForFunctionDescriptor(
descriptor,
getSignatureMapper(typeMapper),
IS_PURE_INTERFACE_CHECKER
);
if (!bridgesToGenerate.isEmpty()) {
PsiElement origin = descriptor.getKind() == DECLARATION ? getSourceFromDescriptor(descriptor) : null;
boolean isSpecialBridge =
@@ -837,7 +787,9 @@ public class FunctionCodegen {
}
else {
Set<BridgeForBuiltinSpecial<Method>> specials = BuiltinSpecialBridgesUtil.generateBridgesForBuiltinSpecial(
descriptor, typeMapper::mapAsmMethod, IS_PURE_INTERFACE_CHECKER
descriptor,
getSignatureMapper(typeMapper),
IS_PURE_INTERFACE_CHECKER
);
if (!specials.isEmpty()) {
@@ -856,18 +808,30 @@ 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);
}
}
}
}
public static boolean isThereOverriddenInKotlinClass(@NotNull CallableMemberDescriptor descriptor) {
return CollectionsKt.any(
getAllOverriddenDescriptors(descriptor),
overridden -> !(overridden.getContainingDeclaration() instanceof JavaClassDescriptor) &&
isClass(overridden.getContainingDeclaration())
);
return CollectionsKt.any(getAllOverriddenDescriptors(descriptor), new Function1<CallableMemberDescriptor, Boolean>() {
@Override
public Boolean invoke(CallableMemberDescriptor descriptor) {
return !(descriptor.getContainingDeclaration() instanceof JavaClassDescriptor) &&
isClass(descriptor.getContainingDeclaration());
}
});
}
@NotNull
private static Function1<FunctionDescriptor, Method> getSignatureMapper(final @NotNull KotlinTypeMapper typeMapper) {
return new Function1<FunctionDescriptor, Method>() {
@Override
public Method invoke(FunctionDescriptor descriptor) {
return typeMapper.mapAsmMethod(descriptor);
}
};
}
public static boolean isMethodOfAny(@NotNull FunctionDescriptor descriptor) {
@@ -883,7 +847,7 @@ public class FunctionCodegen {
}
@NotNull
public static String[] getThrownExceptions(@NotNull FunctionDescriptor function, @NotNull KotlinTypeMapper mapper) {
public static String[] getThrownExceptions(@NotNull FunctionDescriptor function, @NotNull final KotlinTypeMapper mapper) {
AnnotationDescriptor annotation = function.getAnnotations().findAnnotation(new FqName("kotlin.throws"));
if (annotation == null) {
annotation = function.getAnnotations().findAnnotation(new FqName("kotlin.jvm.Throws"));
@@ -898,15 +862,18 @@ public class FunctionCodegen {
if (!(value instanceof ArrayValue)) return ArrayUtil.EMPTY_STRING_ARRAY;
ArrayValue arrayValue = (ArrayValue) value;
List<String> strings = CollectionsKt.mapNotNull(
List<String> strings = ContainerUtil.mapNotNull(
arrayValue.getValue(),
(ConstantValue<?> constant) -> {
if (constant instanceof KClassValue) {
KClassValue classValue = (KClassValue) constant;
ClassDescriptor classDescriptor = DescriptorUtils.getClassDescriptorForType(classValue.getValue());
return mapper.mapClass(classDescriptor).getInternalName();
new Function<ConstantValue<?>, String>() {
@Override
public String fun(ConstantValue<?> constant) {
if (constant instanceof KClassValue) {
KClassValue classValue = (KClassValue) constant;
ClassDescriptor classDescriptor = DescriptorUtils.getClassDescriptorForType(classValue.getValue());
return mapper.mapClass(classDescriptor).getInternalName();
}
return null;
}
return null;
}
);
return ArrayUtil.toStringArray(strings);
@@ -932,7 +899,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 +969,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 +1108,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();
@@ -1278,11 +1234,11 @@ public class FunctionCodegen {
}
private void genDelegate(
@NotNull FunctionDescriptor delegateFunction,
FunctionDescriptor delegatedTo,
@NotNull final FunctionDescriptor delegateFunction,
final FunctionDescriptor delegatedTo,
@NotNull JvmDeclarationOrigin declarationOrigin,
ClassDescriptor toClass,
StackValue field
final ClassDescriptor toClass,
final StackValue field
) {
generateMethod(
declarationOrigin, delegateFunction,

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

@@ -35,10 +35,7 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue;
import org.jetbrains.org.objectweb.asm.Type;
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.isObject;
@@ -81,17 +78,17 @@ public class FunctionReferenceGenerationStrategy extends FunctionGenerationStrat
*/
KtCallExpression fakeExpression = CodegenUtil.constructFakeFunctionCall(state.getProject(), referencedFunction);
List<? extends ValueArgument> fakeArguments = fakeExpression.getValueArguments();
final List<? extends ValueArgument> fakeArguments = fakeExpression.getValueArguments();
ReceiverValue dispatchReceiver = computeAndSaveReceiver(signature, codegen, referencedFunction.getDispatchReceiverParameter());
ReceiverValue extensionReceiver = computeAndSaveReceiver(signature, codegen, referencedFunction.getExtensionReceiverParameter());
final ReceiverValue dispatchReceiver = computeAndSaveReceiver(signature, codegen, referencedFunction.getDispatchReceiverParameter());
final ReceiverValue extensionReceiver = computeAndSaveReceiver(signature, codegen, referencedFunction.getExtensionReceiverParameter());
computeAndSaveArguments(fakeArguments, codegen);
ResolvedCall<CallableDescriptor> fakeResolvedCall = new DelegatingResolvedCall<CallableDescriptor>(resolvedCall) {
private final Map<ValueParameterDescriptor, ResolvedValueArgument> argumentMap;
{
argumentMap = new LinkedHashMap<>(fakeArguments.size());
argumentMap = new LinkedHashMap<ValueParameterDescriptor, ResolvedValueArgument>(fakeArguments.size());
int index = 0;
List<ValueParameterDescriptor> parameters = functionDescriptor.getValueParameters();
for (ValueArgument argument : fakeArguments) {
@@ -115,7 +112,7 @@ public class FunctionReferenceGenerationStrategy extends FunctionGenerationStrat
@NotNull
@Override
public List<ResolvedValueArgument> getValueArgumentsByIndex() {
return new ArrayList<>(argumentMap.values());
return new ArrayList<ResolvedValueArgument>(argumentMap.values());
}
@NotNull

View File

@@ -21,6 +21,8 @@ import com.intellij.psi.PsiElement;
import com.intellij.util.ArrayUtil;
import kotlin.Unit;
import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.functions.Function2;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -31,6 +33,7 @@ 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;
@@ -40,12 +43,8 @@ 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;
@@ -73,12 +72,12 @@ 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;
@@ -104,7 +103,8 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
private final DelegationFieldsInfo delegationFieldsInfo;
private final List<Function2<ImplementationBodyCodegen, ClassBuilder, Unit>> additionalTasks = new ArrayList<>();
private final List<Function2<ImplementationBodyCodegen, ClassBuilder, Unit>> additionalTasks =
new ArrayList<Function2<ImplementationBodyCodegen, ClassBuilder, Unit>>();
public ImplementationBodyCodegen(
@NotNull KtPureClassOrObject aClass,
@@ -217,7 +217,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
v.visitSource(myClass.getContainingKtFile().getName(), null);
initDefaultSourceMappingIfNeeded(context, this, state);
InlineCodegenUtil.initDefaultSourceMappingIfNeeded(context, this, state);
writeEnclosingMethod();
@@ -258,22 +258,25 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
}
private static final Map<FqName, String> KOTLIN_MARKER_INTERFACES = new HashMap<>();
private static final Map<FqName, String> KOTLIN_MARKER_INTERFACES = new HashMap<FqName, String>();
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
@@ -302,29 +305,20 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
sw.writeSuperclassEnd();
LinkedHashSet<String> superInterfaces = new LinkedHashSet<>();
Set<String> kotlinMarkerInterfaces = new LinkedHashSet<>();
LinkedHashSet<String> superInterfaces = new LinkedHashSet<String>();
Set<String> kotlinMarkerInterfaces = new LinkedHashSet<String>();
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);
}
}
@@ -339,7 +333,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
superInterfaces.addAll(kotlinMarkerInterfaces);
return new JvmClassSignature(classAsmType.getInternalName(), superClassInfo.getType().getInternalName(),
new ArrayList<>(superInterfaces), sw.makeJavaGenericSignature());
new ArrayList<String>(superInterfaces), sw.makeJavaGenericSignature());
}
private void getSuperClass() {
@@ -348,12 +342,9 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
@Override
protected void generateSyntheticPartsBeforeBody() {
protected void generateSyntheticParts() {
generatePropertyMetadataArrayFieldIfNeeded(classAsmType);
}
@Override
protected void generateSyntheticPartsAfterBody() {
generateFieldForSingleton();
generateCompanionObjectBackingFieldCopies();
@@ -370,12 +361,9 @@ 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);
@@ -396,7 +384,10 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
generateSecondaryConstructor(secondaryConstructor);
}
}
catch (CompilationException | ProcessCanceledException e) {
catch (CompilationException e) {
throw e;
}
catch (ProcessCanceledException e) {
throw e;
}
catch (RuntimeException e) {
@@ -407,14 +398,15 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
private void generateToArray() {
if (descriptor.getKind() == ClassKind.INTERFACE) return;
KotlinBuiltIns builtIns = DescriptorUtilsKt.getBuiltIns(descriptor);
final KotlinBuiltIns builtIns = DescriptorUtilsKt.getBuiltIns(descriptor);
if (!isSubclass(descriptor, builtIns.getCollection())) return;
if (CollectionsKt.any(DescriptorUtilsKt.getAllSuperclassesWithoutAny(descriptor),
classDescriptor -> !(classDescriptor instanceof JavaClassDescriptor) &&
isSubclass(classDescriptor, builtIns.getCollection()))) {
return;
}
if (CollectionsKt.any(DescriptorUtilsKt.getAllSuperclassesWithoutAny(descriptor), new Function1<ClassDescriptor, Boolean>() {
@Override
public Boolean invoke(ClassDescriptor classDescriptor) {
return !(classDescriptor instanceof JavaClassDescriptor) && isSubclass(classDescriptor, builtIns.getCollection());
}
})) return;
Collection<SimpleFunctionDescriptor> functions = descriptor.getDefaultType().getMemberScope().getContributedFunctions(
Name.identifier("toArray"), NoLookupLocation.FROM_BACKEND
@@ -576,7 +568,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();
@@ -648,7 +640,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
@Override
public void generateComponentFunction(@NotNull FunctionDescriptor function, @NotNull ValueParameterDescriptor parameter) {
public void generateComponentFunction(@NotNull FunctionDescriptor function, @NotNull final ValueParameterDescriptor parameter) {
PsiElement originalElement = DescriptorToSourceUtils.descriptorToDeclaration(parameter);
functionCodegen.generateMethod(JvmDeclarationOriginKt.OtherOrigin(originalElement, function), function, new FunctionGenerationStrategy() {
@Override
@@ -676,12 +668,12 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
@Override
public void generateCopyFunction(
@NotNull FunctionDescriptor function,
@NotNull final FunctionDescriptor function,
@NotNull List<? extends KtParameter> constructorParameters
) {
Type thisDescriptorType = typeMapper.mapType(descriptor);
final 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,
@@ -749,12 +741,15 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
functionCodegen.generateDefaultIfNeeded(
context.intoFunction(function), function, OwnerKind.IMPLEMENTATION,
(valueParameter, codegen) -> {
assert ((ClassDescriptor) function.getContainingDeclaration()).isData()
: "Function container must have [data] modifier: " + function;
PropertyDescriptor property = bindingContext.get(BindingContext.VALUE_PARAMETER_AS_PROPERTY, valueParameter);
assert property != null : "Copy function doesn't correspond to any property: " + function;
return codegen.intermediateValueForProperty(property, false, null, StackValue.LOCAL_0);
new DefaultParameterValueLoader() {
@Override
public StackValue genValue(ValueParameterDescriptor valueParameter, ExpressionCodegen codegen) {
assert ((ClassDescriptor) function.getContainingDeclaration()).isData()
: "Function container must have [data] modifier: " + function;
PropertyDescriptor property = bindingContext.get(BindingContext.VALUE_PARAMETER_AS_PROPERTY, valueParameter);
assert property != null : "Copy function doesn't correspond to any property: " + function;
return codegen.intermediateValueForProperty(property, false, null, StackValue.LOCAL_0);
}
},
null
);
@@ -781,7 +776,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;
@@ -796,11 +791,14 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
private void generateEnumValueOfMethod() {
FunctionDescriptor valueOfFunction =
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(),
"(Ljava/lang/String;)" + classAsmType.getDescriptor(), null, null);
CollectionsKt.single(descriptor.getStaticScope().getContributedFunctions(ENUM_VALUE_OF, NoLookupLocation.FROM_BACKEND), new Function1<FunctionDescriptor, Boolean>() {
@Override
public Boolean invoke(FunctionDescriptor descriptor) {
return DescriptorUtilsKt.isEnumValueOfMethod(descriptor);
}
});
MethodVisitor mv = 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;
mv.visitCode();
@@ -817,7 +815,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);
@@ -901,15 +899,15 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
StackValue.singleton(companionObject, typeMapper).store(instance, codegen.v, true);
}
private void generatePrimaryConstructor(DelegationFieldsInfo delegationFieldsInfo) {
private void generatePrimaryConstructor(final DelegationFieldsInfo delegationFieldsInfo) {
if (isInterface(descriptor) || isAnnotationClass(descriptor)) return;
ClassConstructorDescriptor constructorDescriptor = descriptor.getUnsubstitutedPrimaryConstructor();
final ClassConstructorDescriptor constructorDescriptor = descriptor.getUnsubstitutedPrimaryConstructor();
if (constructorDescriptor == null) return;
ConstructorContext constructorContext = context.intoConstructor(constructorDescriptor);
KtPrimaryConstructor primaryConstructor = myClass.getPrimaryConstructor();
final KtPrimaryConstructor primaryConstructor = myClass.getPrimaryConstructor();
JvmDeclarationOrigin origin = JvmDeclarationOriginKt
.OtherOrigin(primaryConstructor != null ? primaryConstructor : myClass.getPsiOrParent(), constructorDescriptor);
functionCodegen.generateMethod(origin, constructorDescriptor, constructorContext,
@@ -927,7 +925,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
new DefaultParameterValueSubstitutor(state).generatePrimaryConstructorOverloadsIfNeeded(constructorDescriptor, v, this, kind, myClass);
}
private void generateSecondaryConstructor(@NotNull ClassConstructorDescriptor constructorDescriptor) {
private void generateSecondaryConstructor(@NotNull final ClassConstructorDescriptor constructorDescriptor) {
if (!canHaveDeclaredConstructors(descriptor)) return;
ConstructorContext constructorContext = context.intoConstructor(constructorDescriptor);
@@ -999,7 +997,13 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
if (JvmAbi.isCompanionObjectWithBackingFieldsInOuter(descriptor)) {
generateInitializers(((ImplementationBodyCodegen) getParentCodegen())::createOrGetClInitCodegen);
final ImplementationBodyCodegen parentCodegen = (ImplementationBodyCodegen) getParentCodegen();
generateInitializers(new Function0<ExpressionCodegen>() {
@Override
public ExpressionCodegen invoke() {
return parentCodegen.createOrGetClInitCodegen();
}
});
}
else {
generateInitializers(codegen);
@@ -1049,7 +1053,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
else if (constructor.hasBody() && !(constructor instanceof KtSecondaryConstructor && !((KtSecondaryConstructor) constructor).hasImplicitDelegationCall())) {
KtBlockExpression bodyExpression = constructor.getBodyExpression();
List<KtExpression> statements = bodyExpression != null ? bodyExpression.getStatements() : Collections.emptyList();
List<KtExpression> statements = bodyExpression != null ? bodyExpression.getStatements() : Collections.<KtExpression>emptyList();
if (!statements.isEmpty()) {
codegen.markStartLineNumber(statements.iterator().next());
}
@@ -1062,8 +1066,13 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
}
public void generateInitializers(@NotNull ExpressionCodegen codegen) {
generateInitializers(() -> codegen);
private void generateInitializers(@NotNull final ExpressionCodegen codegen) {
generateInitializers(new Function0<ExpressionCodegen>() {
@Override
public ExpressionCodegen invoke() {
return codegen;
}
});
}
private void generateClosureInitialization(@NotNull InstructionAdapter iv) {
@@ -1106,13 +1115,11 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
return StackValue.field(type, classAsmType, name, false, StackValue.none());
}
}
private final Map<KtDelegatedSuperTypeEntry, Field> fields = new HashMap<>();
private final Map<KtDelegatedSuperTypeEntry, Field> fields = new HashMap<KtDelegatedSuperTypeEntry, Field>();
@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) {
@@ -1132,8 +1139,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);
@@ -1141,14 +1146,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++;
@@ -1157,13 +1157,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(
@@ -1175,8 +1171,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);
@@ -1298,7 +1292,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
private void generateTraitMethods() {
if (isAnnotationOrJvmInterfaceWithoutDefaults(descriptor, state)) return;
List<FunctionDescriptor> restrictedInheritance = new ArrayList<>();
List<FunctionDescriptor> restrictedInheritance = new ArrayList<FunctionDescriptor>();
for (Map.Entry<FunctionDescriptor, FunctionDescriptor> entry : CodegenUtil.getNonPrivateTraitMethods(descriptor).entrySet()) {
FunctionDescriptor interfaceFun = entry.getKey();
//skip java 8 default methods
@@ -1315,8 +1309,7 @@ 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 final FunctionDescriptor interfaceFun, @NotNull final FunctionDescriptor inheritedFun) {
functionCodegen.generateMethod(
new JvmDeclarationOrigin(CLASS_MEMBER_DELEGATION_TO_DEFAULT_IMPL, descriptorToDeclaration(interfaceFun), interfaceFun),
inheritedFun,
@@ -1563,7 +1556,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());
@@ -1622,15 +1615,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);
}
}
}
@@ -1663,7 +1651,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
public void addCompanionObjectPropertyToCopy(@NotNull PropertyDescriptor descriptor, Object defaultValue) {
if (companionObjectPropertiesToCopy == null) {
companionObjectPropertiesToCopy = new ArrayList<>();
companionObjectPropertiesToCopy = new ArrayList<PropertyAndDefaultValue>();
}
companionObjectPropertiesToCopy.add(new PropertyAndDefaultValue(descriptor, defaultValue));
}

View File

@@ -70,7 +70,7 @@ class InterfaceImplBodyCodegen(
return classDescriptorImpl
}
override fun generateSyntheticPartsAfterBody() {
override fun generateSyntheticParts() {
for (memberDescriptor in descriptor.defaultType.memberScope.getContributedDescriptors()) {
if (memberDescriptor !is CallableMemberDescriptor) continue

View File

@@ -19,6 +19,7 @@ package org.jetbrains.kotlin.codegen;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
import kotlin.text.StringsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -175,10 +176,14 @@ public class JvmCodegenUtil {
}
public static boolean hasAbstractMembers(@NotNull ClassDescriptor classDescriptor) {
return CollectionsKt.any(
DescriptorUtils.getAllDescriptors(classDescriptor.getDefaultType().getMemberScope()),
descriptor -> descriptor instanceof CallableMemberDescriptor &&
((CallableMemberDescriptor) descriptor).getModality() == ABSTRACT
return CollectionsKt.any(DescriptorUtils.getAllDescriptors(classDescriptor.getDefaultType().getMemberScope()),
new Function1<DeclarationDescriptor, Boolean>() {
@Override
public Boolean invoke(DeclarationDescriptor descriptor) {
return descriptor instanceof CallableMemberDescriptor &&
((CallableMemberDescriptor) descriptor).getModality() == ABSTRACT;
}
}
);
}

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

@@ -49,8 +49,8 @@ public class KotlinCodegenFacade {
@NotNull GenerationState state,
@NotNull CompilationErrorHandler errorHandler
) {
MultiMap<FqName, KtFile> filesInPackages = new MultiMap<>();
MultiMap<FqName, KtFile> filesInMultifileClasses = new MultiMap<>();
MultiMap<FqName, KtFile> filesInPackages = new MultiMap<FqName, KtFile>();
MultiMap<FqName, KtFile> filesInMultifileClasses = new MultiMap<FqName, KtFile>();
for (KtFile file : files) {
if (file == null) throw new IllegalArgumentException("A null file given for compilation");
@@ -65,13 +65,13 @@ public class KotlinCodegenFacade {
}
}
Set<FqName> obsoleteMultifileClasses = new HashSet<>(state.getObsoleteMultifileClasses());
Set<FqName> obsoleteMultifileClasses = new HashSet<FqName>(state.getObsoleteMultifileClasses());
for (FqName multifileClassFqName : Sets.union(filesInMultifileClasses.keySet(), obsoleteMultifileClasses)) {
doCheckCancelled(state);
generateMultifileClass(state, multifileClassFqName, filesInMultifileClasses.get(multifileClassFqName), errorHandler);
}
Set<FqName> packagesWithObsoleteParts = new HashSet<>(state.getPackagesWithObsoleteParts());
Set<FqName> packagesWithObsoleteParts = new HashSet<FqName>(state.getPackagesWithObsoleteParts());
for (FqName packageFqName : Sets.union(packagesWithObsoleteParts, filesInPackages.keySet())) {
doCheckCancelled(state);
generatePackage(state, packageFqName, filesInPackages.get(packageFqName), errorHandler);

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.
@@ -20,15 +20,13 @@ import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.psi.PsiElement;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;
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.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;
@@ -62,10 +60,7 @@ import org.jetbrains.kotlin.storage.LockBasedStorageManager;
import org.jetbrains.kotlin.storage.NotNullLazyValue;
import org.jetbrains.kotlin.types.ErrorUtils;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.org.objectweb.asm.Label;
import org.jetbrains.org.objectweb.asm.MethodVisitor;
import org.jetbrains.org.objectweb.asm.Opcodes;
import org.jetbrains.org.objectweb.asm.Type;
import org.jetbrains.org.objectweb.asm.*;
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
import org.jetbrains.org.objectweb.asm.commons.Method;
@@ -74,7 +69,6 @@ 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.*;
@@ -98,7 +92,7 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
private final JvmFileClassesProvider fileClassesProvider;
private final MemberCodegen<?> parentCodegen;
private final ReifiedTypeParametersUsages reifiedTypeParametersUsages = new ReifiedTypeParametersUsages();
private final Collection<ClassDescriptor> innerClasses = new LinkedHashSet<>();
private final Collection<ClassDescriptor> innerClasses = new LinkedHashSet<ClassDescriptor>();
private ExpressionCodegen clInit;
private NameGenerator inlineNameGenerator;
@@ -131,18 +125,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) {
@@ -154,12 +141,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();
@@ -209,7 +193,10 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
try {
functionCodegen.gen((KtNamedFunction) declaration);
}
catch (ProcessCanceledException | CompilationException e) {
catch (ProcessCanceledException e) {
throw e;
}
catch (CompilationException e) {
throw e;
}
catch (Exception e) {
@@ -220,7 +207,10 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
try {
propertyCodegen.gen((KtProperty) declaration);
}
catch (ProcessCanceledException | CompilationException e) {
catch (ProcessCanceledException e) {
throw e;
}
catch (CompilationException e) {
throw e;
}
catch (Exception e) {
@@ -230,17 +220,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);
}
@@ -310,7 +289,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();
@@ -451,7 +430,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;
@@ -477,7 +456,8 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
private SimpleFunctionDescriptorImpl createClInitFunctionDescriptor(@NotNull DeclarationDescriptor descriptor) {
SimpleFunctionDescriptorImpl clInit = SimpleFunctionDescriptorImpl.create(descriptor, Annotations.Companion.getEMPTY(),
Name.special("<clinit>"), SYNTHESIZED, KotlinSourceElementKt.toSourceElement(element));
clInit.initialize(null, null, Collections.emptyList(), Collections.emptyList(),
clInit.initialize(null, null, Collections.<TypeParameterDescriptor>emptyList(),
Collections.<ValueParameterDescriptor>emptyList(),
DescriptorUtilsKt.getModule(descriptor).getBuiltIns().getUnitType(),
null, Visibilities.PRIVATE);
return clInit;
@@ -491,9 +471,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) {
@@ -608,7 +585,7 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
}
protected void generatePropertyMetadataArrayFieldIfNeeded(@NotNull Type thisAsmType) {
List<KtProperty> delegatedProperties = new ArrayList<>();
List<KtProperty> delegatedProperties = new ArrayList<KtProperty>();
for (KtDeclaration declaration : ((KtDeclarationContainer) element).getDeclarations()) {
if (declaration instanceof KtProperty) {
KtProperty property = (KtProperty) declaration;
@@ -685,7 +662,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;
@@ -693,7 +670,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
);
@@ -714,8 +691,8 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
private void generateSyntheticAccessor(@NotNull AccessorForCallableDescriptor<?> accessorForCallableDescriptor) {
if (accessorForCallableDescriptor instanceof FunctionDescriptor) {
FunctionDescriptor accessor = (FunctionDescriptor) accessorForCallableDescriptor;
FunctionDescriptor original = (FunctionDescriptor) accessorForCallableDescriptor.getCalleeDescriptor();
final FunctionDescriptor accessor = (FunctionDescriptor) accessorForCallableDescriptor;
final FunctionDescriptor original = (FunctionDescriptor) accessorForCallableDescriptor.getCalleeDescriptor();
functionCodegen.generateMethod(
Synthetic(null, original), accessor,
new FunctionGenerationStrategy.CodegenBased(state) {
@@ -731,8 +708,8 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
);
}
else if (accessorForCallableDescriptor instanceof AccessorForPropertyDescriptor) {
AccessorForPropertyDescriptor accessor = (AccessorForPropertyDescriptor) accessorForCallableDescriptor;
PropertyDescriptor original = accessor.getCalleeDescriptor();
final AccessorForPropertyDescriptor accessor = (AccessorForPropertyDescriptor) accessorForCallableDescriptor;
final PropertyDescriptor original = accessor.getCalleeDescriptor();
class PropertyAccessorStrategy extends FunctionGenerationStrategy.CodegenBased {
private final PropertyAccessorDescriptor callableDescriptor;
@@ -838,16 +815,19 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
}
protected void generateKotlinClassMetadataAnnotation(@NotNull ClassDescriptor descriptor, boolean isScript) {
DescriptorSerializer serializer =
final DescriptorSerializer serializer =
DescriptorSerializer.create(descriptor, new JvmSerializerExtension(v.getSerializationBindings(), state));
ProtoBuf.Class classProto = serializer.classProto(descriptor).build();
final ProtoBuf.Class classProto = serializer.classProto(descriptor).build();
int flags = isScript ? JvmAnnotationNames.METADATA_SCRIPT_FLAG : 0;
WriteAnnotationUtilKt.writeKotlinMetadata(v, state, KotlinClassHeader.Kind.CLASS, flags, av -> {
writeAnnotationData(av, serializer, classProto);
return Unit.INSTANCE;
WriteAnnotationUtilKt.writeKotlinMetadata(v, state, KotlinClassHeader.Kind.CLASS, flags, new Function1<AnnotationVisitor, Unit>() {
@Override
public Unit invoke(AnnotationVisitor av) {
writeAnnotationData(av, serializer, classProto);
return Unit.INSTANCE;
}
});
}
}

View File

@@ -186,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

@@ -99,7 +99,7 @@ public class PackageCodegenImpl implements PackageCodegen {
boolean generatePackagePart = false;
List<KtClassOrObject> classOrObjects = new ArrayList<>();
List<KtClassOrObject> classOrObjects = new ArrayList<KtClassOrObject>();
for (KtDeclaration declaration : file.getDeclarations()) {
if (declaration.hasModifier(KtTokens.HEADER_KEYWORD)) continue;
@@ -135,7 +135,7 @@ public class PackageCodegenImpl implements PackageCodegen {
@Nullable
private PackageFragmentDescriptor getOnlyPackageFragment(@NotNull FqName expectedPackageFqName) {
SmartList<PackageFragmentDescriptor> fragments = new SmartList<>();
SmartList<PackageFragmentDescriptor> fragments = new SmartList<PackageFragmentDescriptor>();
for (KtFile file : files) {
PackageFragmentDescriptor fragment = state.getBindingContext().get(BindingContext.FILE_TO_PACKAGE_FRAGMENT, file);
assert fragment != null : "package fragment is null for " + file + "\n" + file.getText();

View File

@@ -18,6 +18,8 @@ package org.jetbrains.kotlin.codegen;
import com.intellij.util.ArrayUtil;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.codegen.annotation.AnnotatedSimple;
import org.jetbrains.kotlin.codegen.context.FieldOwnerContext;
@@ -36,6 +38,7 @@ import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.serialization.DescriptorSerializer;
import org.jetbrains.kotlin.serialization.ProtoBuf;
import org.jetbrains.org.objectweb.asm.AnnotationVisitor;
import org.jetbrains.org.objectweb.asm.Type;
import java.util.ArrayList;
@@ -75,7 +78,7 @@ public class PackagePartCodegen extends MemberCodegen<KtFile> {
}
private void generateAnnotationsForPartClass() {
List<AnnotationDescriptor> fileAnnotationDescriptors = new ArrayList<>();
List<AnnotationDescriptor> fileAnnotationDescriptors = new ArrayList<AnnotationDescriptor>();
for (KtAnnotationEntry annotationEntry : element.getAnnotationEntries()) {
AnnotationDescriptor annotationDescriptor = state.getBindingContext().get(BindingContext.ANNOTATION, annotationEntry);
if (annotationDescriptor != null) {
@@ -97,13 +100,18 @@ public class PackagePartCodegen extends MemberCodegen<KtFile> {
}
if (state.getClassBuilderMode().generateBodies) {
generateInitializers(this::createOrGetClInitCodegen);
generateInitializers(new Function0<ExpressionCodegen>() {
@Override
public ExpressionCodegen invoke() {
return createOrGetClInitCodegen();
}
});
}
}
@Override
protected void generateKotlinMetadataAnnotation() {
List<DeclarationDescriptor> members = new ArrayList<>();
List<DeclarationDescriptor> members = new ArrayList<DeclarationDescriptor>();
for (KtDeclaration declaration : element.getDeclarations()) {
if (declaration instanceof KtNamedFunction) {
SimpleFunctionDescriptor functionDescriptor = bindingContext.get(BindingContext.FUNCTION, declaration);
@@ -119,18 +127,21 @@ public class PackagePartCodegen extends MemberCodegen<KtFile> {
}
}
DescriptorSerializer serializer =
final DescriptorSerializer serializer =
DescriptorSerializer.createTopLevel(new JvmSerializerExtension(v.getSerializationBindings(), state));
ProtoBuf.Package packageProto = serializer.packagePartProto(element.getPackageFqName(), members).build();
final ProtoBuf.Package packageProto = serializer.packagePartProto(element.getPackageFqName(), members).build();
WriteAnnotationUtilKt.writeKotlinMetadata(v, state, KotlinClassHeader.Kind.FILE_FACADE, 0, av -> {
writeAnnotationData(av, serializer, packageProto);
return Unit.INSTANCE;
WriteAnnotationUtilKt.writeKotlinMetadata(v, state, KotlinClassHeader.Kind.FILE_FACADE, 0, new Function1<AnnotationVisitor, Unit>() {
@Override
public Unit invoke(AnnotationVisitor av) {
writeAnnotationData(av, serializer, packageProto);
return Unit.INSTANCE;
}
});
}
@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.
@@ -38,7 +38,6 @@ 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;
@@ -106,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);
@@ -142,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
) {
@@ -565,7 +537,7 @@ public class PropertyCodegen {
@NotNull ExpressionCodegen codegen,
@NotNull KotlinTypeMapper typeMapper,
@NotNull ResolvedCall<FunctionDescriptor> resolvedCall,
int indexInPropertyMetadataArray,
final int indexInPropertyMetadataArray,
int propertyMetadataArgumentIndex
) {
StackValue.Property receiver = codegen.intermediateValueForProperty(propertyDescriptor, true, null, StackValue.LOCAL_0);
@@ -579,14 +551,14 @@ public class PropertyCodegen {
@NotNull ExpressionCodegen codegen,
@NotNull KotlinTypeMapper typeMapper,
@NotNull ResolvedCall<FunctionDescriptor> resolvedCall,
int indexInPropertyMetadataArray,
final int indexInPropertyMetadataArray,
int propertyMetadataArgumentIndex,
@Nullable StackValue receiver,
@NotNull PropertyDescriptor propertyDescriptor
) {
Type owner = JvmAbi.isPropertyWithBackingFieldInOuterClass(propertyDescriptor) ?
codegen.getState().getTypeMapper().mapOwner(propertyDescriptor) :
getDelegatedPropertyMetadataOwner(codegen, typeMapper);
final Type owner = JvmAbi.isPropertyWithBackingFieldInOuterClass(propertyDescriptor) ?
codegen.getState().getTypeMapper().mapOwner(propertyDescriptor) :
getDelegatedPropertyMetadataOwner(codegen, typeMapper);
codegen.tempVariables.put(
resolvedCall.getCall().getValueArguments().get(propertyMetadataArgumentIndex).asElement(),

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.
@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.codegen;
import kotlin.jvm.functions.Function0;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.codegen.context.CodegenContext;
import org.jetbrains.kotlin.codegen.context.MethodContext;
@@ -60,7 +61,7 @@ public class ScriptCodegen extends MemberCodegen<KtScript> {
List<ScriptDescriptor> earlierScripts = state.getReplSpecific().getEarlierScriptsForReplInterpreter();
ScriptContext scriptContext = parentContext.intoScript(
scriptDescriptor,
earlierScripts == null ? Collections.emptyList() : earlierScripts,
earlierScripts == null ? Collections.<ScriptDescriptor>emptyList() : earlierScripts,
scriptDescriptor,
state.getTypeMapper()
);
@@ -105,14 +106,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 +159,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,25 +186,28 @@ public class ScriptCodegen extends MemberCodegen<KtScript> {
FrameMap frameMap = new FrameMap();
frameMap.enterTemp(OBJECT_TYPE);
if (!context.getEarlierScripts().isEmpty()) {
int scriptsParamIndex = frameMap.enterTemp(AsmUtil.getArrayType(OBJECT_TYPE));
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 importedScript : context.getEarlierScripts()) {
frameMap.enter(importedScript, OBJECT_TYPE);
}
ExpressionCodegen codegen = new ExpressionCodegen(mv, frameMap, Type.VOID_TYPE, methodContext, state, this);
int offset = 1;
generateInitializers(() -> codegen);
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());
}
final ExpressionCodegen codegen = new ExpressionCodegen(mv, frameMap, Type.VOID_TYPE, methodContext, state, this);
generateInitializers(new Function0<ExpressionCodegen>() {
@Override
public ExpressionCodegen invoke() {
return codegen;
}
});
iv.areturn(Type.VOID_TYPE);
}
@@ -232,11 +232,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

@@ -65,9 +65,12 @@ public abstract class StackValue {
private static final String NULLABLE_LONG_TYPE_NAME = "java/lang/Long";
public static final StackValue.Local LOCAL_0 = local(0, OBJECT_TYPE);
private static final StackValue UNIT = operation(UNIT_TYPE, v -> {
v.visitFieldInsn(GETSTATIC, UNIT_TYPE.getInternalName(), JvmAbi.INSTANCE_FIELD, UNIT_TYPE.getDescriptor());
return null;
private static final StackValue UNIT = operation(UNIT_TYPE, new Function1<InstructionAdapter, Unit>() {
@Override
public Unit invoke(InstructionAdapter v) {
v.visitFieldInsn(GETSTATIC, UNIT_TYPE.getInternalName(), JvmAbi.INSTANCE_FIELD, UNIT_TYPE.getDescriptor());
return null;
}
});
@NotNull
@@ -181,35 +184,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);
@@ -770,9 +744,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);
@@ -1087,7 +1061,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*/

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;
@@ -47,8 +45,8 @@ public abstract class TransformationMethodVisitor extends MethodVisitor {
super(Opcodes.ASM5);
this.delegate = delegate;
this.methodNode = new MethodNode(access, name, desc, signature, exceptions);
this.methodNode.localVariables = new ArrayList<>(5);
this.mv = wrapWithMaxLocalCalc(methodNode);
this.methodNode.localVariables = new ArrayList<LocalVariableNode>(5);
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

@@ -22,6 +22,7 @@ import com.intellij.psi.tree.TokenSet;
import com.intellij.util.containers.Stack;
import kotlin.Pair;
import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.ReflectionTypes;
@@ -38,7 +39,7 @@ 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.Name;
import org.jetbrains.kotlin.psi.*;
@@ -70,10 +71,10 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
TokenSet.create(PLUS, MINUS, MUL, DIV, PERC, RANGE, LT, GT, LTEQ, GTEQ, IDENTIFIER)
);
private final Map<String, Integer> anonymousSubclassesCount = new HashMap<>();
private final Map<String, Integer> anonymousSubclassesCount = new HashMap<String, Integer>();
private final Stack<ClassDescriptor> classStack = new Stack<>();
private final Stack<String> nameStack = new Stack<>();
private final Stack<ClassDescriptor> classStack = new Stack<ClassDescriptor>();
private final Stack<String> nameStack = new Stack<String>();
private final BindingTrace bindingTrace;
private final BindingContext bindingContext;
@@ -103,20 +104,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,
@@ -468,23 +455,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) {
@@ -493,18 +475,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();
@@ -646,7 +639,7 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
String currentClassName = getCurrentTopLevelClassOrPackagePartInternalName(expression.getContainingKtFile());
if (bindingContext.get(MAPPINGS_FOR_WHENS_BY_ENUM_IN_CLASS_FILE, currentClassName) == null) {
bindingTrace.record(MAPPINGS_FOR_WHENS_BY_ENUM_IN_CLASS_FILE, currentClassName, new ArrayList<>(1));
bindingTrace.record(MAPPINGS_FOR_WHENS_BY_ENUM_IN_CLASS_FILE, currentClassName, new ArrayList<WhenByEnumsMapping>(1));
}
List<WhenByEnumsMapping> mappings = bindingContext.get(MAPPINGS_FOR_WHENS_BY_ENUM_IN_CLASS_FILE, currentClassName);
@@ -682,7 +675,12 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
expression,
bindingContext,
shouldInlineConstVals,
constant -> constant instanceof EnumValue || constant instanceof NullValue
new Function1<ConstantValue<?>, Boolean>() {
@Override
public Boolean invoke(@NotNull ConstantValue<?> constant) {
return constant instanceof EnumValue || constant instanceof NullValue;
}
}
);
}

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