Compare commits

...

863 Commits

Author SHA1 Message Date
Simon Ogorodnik
4380d054a9 Add IDEA action to show raw FIR of currently opened file 2018-10-24 15:01:34 +03:00
Mikhail Glukhikh
1a86a2a922 Implement raw FIR builder (initial version)
All necessary FIR tree implementations were created
FIR renderer & three first builder tests were added
#KT-24013 Fixed
2018-10-24 10:35:35 +03:00
Simon Ogorodnik
90678400a7 Create visitor generator for FIR (KT-24062 in progress) 2018-10-24 10:35:33 +03:00
Mikhail Glukhikh
3b318efd0d Create basic version of FIR interfaces (mostly declarations)
#KT-24014 Fixed
2018-10-24 10:35:32 +03:00
Simon Ogorodnik
1f63072abe Create modules for Frontend IR & its builder from PSI 2018-10-24 10:35:25 +03:00
Mikhail Glukhikh
7a589d69da Fix 183 build 2018-10-23 14:16:19 +03:00
Alexander Podkhalyuzin
16d3bf7716 Fixed KotlinConfidenceTests 2018-10-23 13:57:42 +03:00
Nikita Katkov
d66619b1c2 BlockingMethodInNonBlockingContextInspection: resolve mode switched to partial & coroutine "released" status check 2018-10-23 13:18:32 +03:00
Toshiaki Kameyama
90529dfda4 "Remove redundant receiver" quick fix: Remove unused type parameter #KT-23512 2018-10-23 13:02:44 +03:00
Toshiaki Kameyama
0cd25353bc Lift assignment: do not report in cases where argument are of different types #KT-21520 Fixed 2018-10-23 12:48:03 +03:00
Mikhail Glukhikh
fcc6395b14 SetterBackingFieldAssignment: minor refactoring 2018-10-23 12:35:35 +03:00
Toshiaki Kameyama
29cc727c5a Add inspection for suspicious 'var' property #KT-23691 Fixed 2018-10-23 12:31:42 +03:00
Toshiaki Kameyama
3ede93df11 Introduce inspection: "Setter backing field should be assigned"
#KT-20273 Fixed
2018-10-23 11:22:40 +03:00
Mikhail Glukhikh
784d9f14f6 Rollback language / API version at the end of IDE tests
This should fix some flaky tests
2018-10-23 10:57:09 +03:00
Nikolay Krasko
0eb5934e09 Update channels list in update Kotlin dropdown (KT-25429)
#KT-25429 Fixed
2018-10-23 01:23:21 +03:00
Yan Zhulanow
5d2a3c097c Minor: Update kapt test (nullability annotation is gone in Enum constructors) 2018-10-22 23:06:05 +03:00
Alexey Sedunov
af5d4b3156 MPP: Fix adjustment of transitive project dependencies
#KT-27632 Fixed
2018-10-22 19:18:35 +03:00
Alexey Sedunov
fd4c07f0e6 MPP: Populate BuildScriptClasspathData if it's absent
This happens when Java support is not available in the IDE
(e.g. in CLion)
2018-10-22 19:18:34 +03:00
Alexey Sedunov
839d936918 MPP: Implement directory selection UI supporting non-JVM roots
#KT-27291 Fixed
 #KT-26696 Fixed
2018-10-22 19:18:32 +03:00
Alexey Sedunov
aa4e87fc4b Refactor: Introduce MoveSource class 2018-10-22 19:18:31 +03:00
Mikhael Bogdanov
2131a314b0 Add file content to parsing errors 2018-10-22 16:32:57 +02:00
Mikhael Bogdanov
9c3b367b93 Skip JVM_TARGET and SKIP_JDK6 tests on android 2018-10-22 16:32:56 +02:00
Mikhael Bogdanov
ce1d6e7217 Fix test in JDK independent way 2018-10-22 16:32:56 +02:00
Mikhael Bogdanov
a4206a543a Skip test on JDK 6 2018-10-22 16:32:55 +02:00
Mikhael Bogdanov
db25343f90 Run tests on different JDKs via different suites and custom test runner 2018-10-22 16:32:54 +02:00
Mikhael Bogdanov
55880ef013 Fix delegateFilter reinitialization
Otherwise IDEA marks all test as skipped
2018-10-22 16:32:54 +02:00
Mikhael Bogdanov
5b8acd69e3 Mute JVM IR tests 2018-10-22 16:32:53 +02:00
Mikhael Bogdanov
edc648813d Regenerate box tests 2018-10-22 16:32:52 +02:00
Mikhael Bogdanov
ac8e1a0124 Move JVM8 box test to common 2018-10-22 16:32:52 +02:00
Mikhael Bogdanov
b61608aba7 Add TARGET_BACKEND for JVM 8 tests 2018-10-22 16:32:51 +02:00
Mikhael Bogdanov
6ec7b8e0d3 Fix test server and proxy 2018-10-22 16:32:50 +02:00
Vyacheslav Gerasimov
38902149d2 Add bunch set for AS 3.4 2018-10-22 17:21:22 +03:00
Ilya Gorbunov
4a10d954fc Unify and improve Regex docs 2018-10-22 17:14:46 +03:00
Ilya Gorbunov
709a28060f Unify coroutine intrinsic docs 2018-10-22 17:14:46 +03:00
Ilya Gorbunov
63c5e18149 capitalize/decapitalize docs in stdlib/js 2018-10-22 17:14:45 +03:00
Ilya Gorbunov
a1c0c679ee Common String.toNumber: clarify thrown exception types 2018-10-22 17:14:45 +03:00
Ilya Gorbunov
1ed136a621 kotlin.system docs improvements
- Rewrite exitProcess docs in a more common way
- Add [block] parameter reference
2018-10-22 17:14:45 +03:00
Ilya Gorbunov
3aff7112e0 Minor: code formatting in Unit docs 2018-10-22 17:14:45 +03:00
Ilya Gorbunov
ac5eeb885f Unify AbstractMutableMap JS docs 2018-10-22 17:14:45 +03:00
Ilya Gorbunov
7fc6f06b70 Correct parameter reference in copyInto docs 2018-10-22 17:14:44 +03:00
Ilya Gorbunov
ebe9d59df7 Unify print/println/readLine docs 2018-10-22 17:14:44 +03:00
Ilya Gorbunov
406bd7c980 Minor: split math sources into regions 2018-10-22 17:14:44 +03:00
Alexander Podkhalyuzin
5c0d516044 Refactored plugin.xml
#KT-27698 Fixed
2018-10-22 16:26:08 +03:00
Ilya Chernikov
dd28d55c7d Implement proper JDK home passing logic for scripts, deprecating old one
KT-27497 fixed, as well as failing tests on TC
2018-10-22 09:48:49 +02:00
Ilya Matveev
9ccaef2f6b Specify K/N default libs directory more precisely (#1934) 2018-10-21 10:50:46 +07:00
Anton Bannykh
b83df18e22 [JS IR BE] make default argument lowering support per-file mode 2018-10-19 23:49:18 +03:00
Roman Artemev
4c30888d89 Fix test data 2018-10-19 19:38:00 +03:00
Nikolay Krasko
2c98153c6c Use withIgnoredConflicts to fix compilation in 191 2018-10-19 19:16:25 +03:00
Nikolay Krasko
e3d7edb6ce Not null name in RunProfile since 191 2018-10-19 19:16:24 +03:00
Nikolay Krasko
31b4db7f67 191: PersistentStateComponent and other declarations were moved to platform-api 2018-10-19 19:16:22 +03:00
Nikolay Krasko
17421ed14d 191: asm-all has 7.0-beta version in Intellij 191
Pass project to fetch extra parameters for asm-all work
2018-10-19 19:16:21 +03:00
Nikolay Krasko
e86b1f2761 Workaround for generalized configuration classes in 191 2018-10-19 19:16:19 +03:00
Nikolay Krasko
8d48f9d719 Make parameters in KotlinDefaultTemplatePropertiesProvider not-null
Otherwise there's an error in 191
2018-10-19 19:16:18 +03:00
Nikolay Krasko
b79762ec63 Fallback for nullable name in PsiClass 2018-10-19 19:16:17 +03:00
Nikolay Krasko
06478f5147 Unify usages of JavaRunConfigurationExtensionManager.getInstance() for 191 2018-10-19 19:16:15 +03:00
Nikolay Krasko
210b5a8ca2 element utility is removed in 191, use Element constructor instead 2018-10-19 19:16:14 +03:00
Nikolay Krasko
9299ea8f5d Introduce 191 bunch 2018-10-19 19:16:12 +03:00
Nikolay Krasko
d381b4d3eb J2K: rewrite JetRunConfiguration 2018-10-19 19:16:11 +03:00
Nikolay Krasko
6d71d024e2 J2K: Rename JetRunConfiguration 2018-10-19 19:16:10 +03:00
Mikhail Glukhikh
a5e508a083 Unused symbol: handle functions with inline class parameters correctly
#KT-27357 Fixed
2018-10-19 19:07:59 +03:00
Mikhail Glukhikh
0678a56ca4 Add workaround for tests to avoid problems with UnusedSymbolInspection
#KT-27664 Fixed

In particular, this should solve
"Could not initialized UnusedSymbolInspection" and
"Modifications during highlighting are not allowed"
2018-10-19 18:19:21 +03:00
Natalia Selezneva
9653fe2fcf Do not threat sources from buildSrc folder as library sources
#KT-27674 Fixed
2018-10-19 16:36:58 +03:00
Natalia Selezneva
6decd06b1b Provide dependency on buildSrc module for .gradle.kts files
#KT-23603 Fixed
#KT-14862 Fixed
#KT-24623 Fixed
#KT-25354 Fixed
2018-10-19 16:36:57 +03:00
Sergey Igushkin
285620cb28 (minor) Add missing mavenLocal() repo to a Gradle IT project 2018-10-19 16:23:01 +03:00
Roman Artemev
1338d6d66f Update tests 2018-10-19 14:07:20 +03:00
Roman Artemev
41ccea6807 [JS IR BE] Fix name clashes between static and top-level functions 2018-10-19 14:07:20 +03:00
Roman Artemev
c496d8ed50 Fix Char.toLowerCase/Char.toUpperCase extensions 2018-10-19 14:03:06 +03:00
romanart
0260dc813f Update tests 2018-10-19 14:03:06 +03:00
Roman Artemev
79f7cb11f0 [JS IR BE] Fix invoke on dynamic types 2018-10-19 14:03:06 +03:00
Toshiaki Kameyama
ecba862dc9 Expand selection for labeled return #KT-26987 Fixed 2018-10-19 12:24:47 +03:00
Roman Elizarov
790c5632ea Broken doc link to suspendCoroutineOrReturn fixed 2018-10-19 09:58:40 +03:00
Sergey Igushkin
bccca5cfa8 (minor) Fix testResolveMppLibDependencyToMetadata after stdlib was added 2018-10-18 20:10:13 +03:00
Sergey Igushkin
91b435b4bc Check the MPP model for unused Kotlin source sets, warn when found
Issue #KT-26963 Fixed
2018-10-18 20:10:13 +03:00
romanart
44d9ff6c71 Update tests 2018-10-18 19:00:43 +03:00
romanart
df5872281b [JS IR BE] Support instance check for Nothing type 2018-10-18 19:00:43 +03:00
Ilya Gorbunov
c72cf02e6c Add more missing SinceKotlin("1.3") annotations 2018-10-18 16:16:34 +03:00
Pavel Punegov
0bdbcbc662 Ignore the test that uses JVM functions and String constructor 2018-10-18 16:08:38 +03:00
Lukas Welte
70d0c1a0ae Mark Result, its extensions and runCatching as available since 1.3 2018-10-18 16:05:33 +03:00
Matthew Runo
374eec04d4 KT-27445: Add QuickFix for DEPRECATED_JAVA_ANNOTATION compiler warning 2018-10-18 15:56:15 +03:00
Mikhail Glukhikh
570c770d58 MPP web wizard: integrate Ktor inside #KT-27491 Fixed 2018-10-18 15:16:46 +03:00
Mikhail Glukhikh
c770a80ab9 MPP wizard tests: run Native tests using correct task name 2018-10-18 15:16:46 +03:00
Anton Bannykh
3a105debb3 [JS IR BE] fix default arguments lowering 2018-10-18 14:25:48 +03:00
Anton Bannykh
e9c932260c [JS IR BE] minor refactoring 2018-10-18 14:25:48 +03:00
Anton Bannykh
29ff4d6677 [JS IR BE]: Disable incremental compilation tests until IC is supported 2018-10-18 14:24:05 +03:00
Anton Bannykh
995ac7aac2 [JS IR BE]: make deleteProperty non-inline due to new inliner limitations 2018-10-18 14:24:05 +03:00
Dmitry Savvinov
e2bf43c54f Minor: update testdata in ClsStubBuilder test on contracts 2018-10-18 13:15:05 +03:00
Alexander Udalov
5fb1bbe3f3 Add bytecode listing test on private default setter
Also fix test data of the kotlinp test and remove the newly added test
case in the obsolete PropertyGenTest

 #KT-20344 Fixed
2018-10-18 12:13:22 +02:00
Fabian Mastenbroek
05f6ed40f1 Don't generate setters for trivial private property setters
This change will prevent the compiler for generating Java bytecode for
private property setters that are trivial.

Since Kotlin uses direct field access for private properties, it will result
in the private setter never been used and since it cannot be accessed by any
other class without reflection, the setter cannot be covered by code
coverage tools.

See https://youtrack.jetbrains.com/issue/KT-20344 for the related YouTrack
issue.
2018-10-18 12:05:46 +02:00
Alexander Udalov
b1e82c78da Minor, remove obsolete KtMockFileTypeManager.java.183
This is a continuation of 4f0c31ef
2018-10-18 11:58:30 +02:00
Dmitry Savvinov
7887bafc5b Minor: update testdata in completion test on contracts 2018-10-18 12:09:10 +03:00
Dmitry Petrov
763e72603a Mark implicit 'invoke' calls with origin INVOKE 2018-10-18 10:59:24 +03:00
Dmitry Petrov
ad9953724f Basic infrastructure for psi2ir tests with JS front-end 2018-10-18 10:59:24 +03:00
Mikhail Glukhikh
01091ba1aa Refactor getKotlinTypeWithPossibleSmartCastToFP and related parts 2018-10-18 10:27:19 +03:00
Georgy Bronnikov
bbac1d802f JVM_IR. Support annotation classes with JvmField fields 2018-10-17 21:15:28 +03:00
Georgy Bronnikov
605afbae90 Move fields and init blocks of companions to their owners 2018-10-17 21:15:28 +03:00
Georgy Bronnikov
827494abbe JVM_IR. Mostly remove descriptors from ConstAndJvmFieldPropertiesLowering 2018-10-17 21:15:28 +03:00
Alexander Udalov
6e2e6794aa Remove unnecessary copy of ReflectionTypes
ReflectionTypes was copied from org.jetbrains.kotlin.builtins to
kotlin-native in
https://github.com/JetBrains/kotlin-native/commit/776f4c4b7, and then
was incorrectly copied back in 27365dc4be. This class is in fact only
needed in kotlin-native, where it was moved and simplified in
https://github.com/JetBrains/kotlin-native/commit/c3e921d53
2018-10-17 18:39:50 +02:00
Alexander Udalov
e3a332c393 Configure Java module path when compiler is invoked in -Xbuild-file mode
#KT-27626 Fixed
2018-10-17 18:39:50 +02:00
Alexander Udalov
1a1b7938fb Fix deprecated API usage in RemappingClassBuilder
#KT-25058 Fixed
2018-10-17 18:39:50 +02:00
Alexander Udalov
f868964e25 Fix most unchecked/deprecation javac warnings in compiler modules 2018-10-17 18:39:49 +02:00
Alexander Udalov
4f0c31eff3 Remove unneeded copied mock test framework classes
These classes were copied when tests-common were compiled with JDK 6, to
prevent dependencies on classes compiled with JDK 8
2018-10-17 18:39:49 +02:00
Alexander Udalov
23c210e9f2 Use JvmWildcard on return type of getContributedVariables/getContributedFunctions 2018-10-17 18:39:49 +02:00
Alexander Udalov
9dc53c38f3 Remove deprecated CompilerJarLocator 2018-10-17 18:39:49 +02:00
Alexey Tsvetkov
a44d70e79d Reformat kotlin-gradle-plugin according to code style 2018-10-17 19:31:30 +03:00
romanart
47b8e54f84 Update test data 2018-10-17 18:33:52 +03:00
romanart
d75434ac71 [JS IR BE] Support tailreq in JS 2018-10-17 18:33:52 +03:00
Zalim Bashorov
8ac2582e24 Forward gradle properties with prefix "fd." to test runner as system property("-D") w/o this prefix 2018-10-17 18:29:41 +03:00
Zalim Bashorov
99a131d0ab KJS test infrastructure: cache reference to global object and it's original state instead of evaluate them for each run 2018-10-17 18:29:41 +03:00
Zalim Bashorov
180215f3f8 Don't unmute passed tests by default 2018-10-17 18:29:40 +03:00
Zalim Bashorov
1ef3906481 Minor: reformat and cleanup NashornJsTestChecker.kt 2018-10-17 18:29:40 +03:00
Ingo Kegel
d853fcb642 Do not configure module SDK after the Gradle import if it was set explicitly with the Gradle Idea plugin (fixes KT-27530)
If `kotlinOptions.jdkHome` is set, this will still override the setting from the Gradle Idea plugin.
2018-10-17 17:48:27 +03:00
Alexey Sedunov
06e0fde74f Inspections: Report "unresolved property" only if reference is soft
#KT-27619 Fixed
2018-10-17 17:43:00 +03:00
Alexey Sedunov
0bf9a795aa Minor: Drop "(experimental)" from coroutines label
#KT-25681 Fixed
2018-10-17 17:43:00 +03:00
Dmitry Petrov
b13d270d77 Test: reference to constructor with inline class parameters 2018-10-17 16:38:22 +03:00
Dmitry Petrov
0af2a0dc19 Tests: references to private/internal primary val of inline class 2018-10-17 16:38:22 +03:00
Dmitry Petrov
5032c106af Support 'call' for references to inline class constructors
#KT-26748
2018-10-17 16:38:22 +03:00
Dmitry Petrov
94e1701089 Support 'call' for references to inline class members
This includes overriding and non-overriding functions and properties.

 #KT-26748
2018-10-17 16:38:22 +03:00
Dmitry Petrov
5003388d38 Unbox bound receiver if inline class type expected 2018-10-17 16:38:22 +03:00
Dmitry Petrov
9c7c0c8952 Propagate KotlinType to callable reference receivers 2018-10-17 16:38:22 +03:00
Dmitry Petrov
3dc4d01adc Tests for callable references and inline classes 2018-10-17 16:38:22 +03:00
Dmitry Petrov
8fc6b91f66 Minor: reformat 2018-10-17 16:38:22 +03:00
Dmitry Petrov
9a31e04062 Minor: reformat 2018-10-17 16:38:22 +03:00
Mikhail Glukhikh
0fc2a07ee4 Fix typo in import 2018-10-17 16:36:50 +03:00
Mikhail Glukhikh
94d87bfb67 MPP wizard tests: enable Groovy extension, don't wait for daemon death 2018-10-17 16:33:49 +03:00
Mikhail Glukhikh
02e6fb348d MPP wizard tests: check no empty files are generated 2018-10-17 16:33:47 +03:00
Mikhail Glukhikh
853d90d906 MPP wizard tests: extract test functions into separate class 2018-10-17 16:33:21 +03:00
Mikhail Glukhikh
35d4b7dfd9 MPP wizard tests: temporary fix for "failed to delete" problem 2018-10-17 16:33:19 +03:00
Mikhail Glukhikh
63146b98bb MPP wizard tests: add tests run #KT-27492 Fixed 2018-10-17 16:33:18 +03:00
Mikhail Glukhikh
855e2707e3 MPP wizard test: add project import (KT-27492) 2018-10-17 16:33:17 +03:00
Mikhail Glukhikh
43c8c44441 Add MPP wizard general test (KT-27492) 2018-10-17 16:33:15 +03:00
Mikhail Glukhikh
8281416dfa Introduce explicit plugin versions for MPP builder testing 2018-10-17 16:33:09 +03:00
Mikhail Glukhikh
a16318624b MPP wizards: remove unused module parameter from createProjectSkeleton 2018-10-17 16:33:06 +03:00
Sergey Igushkin
a88bfb726d Fix uninitialized lateinit compilerPluginOptionsTask in non-MPP
When a non-MPP is imported into the IDE, the importer anyway tries to
build the MPP source sets model, so it tries to access the
`compilerPluginArguments` and `compilerPluginClasspath`, resulting in
an import error.

Issue #KT-27646 Fixed
2018-10-17 16:19:16 +03:00
Alexander Udalov
5d040c459b Regenerate tests 2018-10-17 14:05:31 +02:00
romanart
71f109387a Update tests 2018-10-17 14:10:37 +03:00
romanart
6a66663739 Update IR Runtime 2018-10-17 14:10:37 +03:00
romanart
eb2a33ebee [JS IR BE] Implement lowering to connect kotlin Throwable with JS Error 2018-10-17 14:10:37 +03:00
Roman Elizarov
1a86411139 Removed todo from Continuation.context
The design decision was the we would not provide its default impl
2018-10-17 11:59:26 +03:00
Mikhail Zarechenskiy
fe233de825 Report error for Result as an extension receiver with safe call
#KT-27620 Fixed
2018-10-16 19:03:05 +03:00
Dmitriy Dolovov
249bdb969c Fix: K/N interop libs are not read by IDEA in certain cases
Issue #KT-27579 Fixed
2018-10-16 21:32:08 +07:00
Mikhail Glukhikh
2dd8b526fb Live templates test: fix typo & cleanup 2018-10-16 17:17:22 +03:00
Mikhail Glukhikh
0f94c0901f Introduce live templates for main without arguments #KT-27461 Fixed 2018-10-16 17:17:21 +03:00
Pavel V. Talanov
1c761c7864 KotlinJUnitRunConfigurationProducer: do not manually override sdk
Should be correct if the module is correct
Manually setting sdk led to problem in case of android SDK
2018-10-16 15:27:59 +02:00
Pavel V. Talanov
3c3e7b617b KotlinMultiplatformRunLocationsProvider: fix tests in android modules
Android modules are considered to be 'production' but can contain tests
    and test roots

 #KT-27371 In progress
2018-10-16 15:27:58 +02:00
victor.petukhov
a2b7912db9 Add expect and actual modifiers to the grammar (KT-25477) 2018-10-16 16:18:32 +03:00
victor.petukhov
205bd3f829 Replace the invalid rule name element to expression in the collectionLiteral grammar rule 2018-10-16 16:16:18 +03:00
Sergey Igushkin
c25cdb4264 Fix resourcesDir that cannot be imported due to not being a File 2018-10-16 14:30:25 +03:00
Sergey Igushkin
e103bea211 Import compiler plugin options from new MPP into IDE
Issue #KT-27499 Fixed
2018-10-16 14:30:25 +03:00
Sergey Igushkin
7075509b1e Import experimental annotations from new MPP into IDE
Issue #KT-26840 Fixed
2018-10-16 14:30:25 +03:00
Sergey Igushkin
9f2e5cdc4d Propagate the subplugin options from the tasks to the source sets
If a source set is used in only one compilation, take the options from
its compile task.

If a source set is used by multiple compilations of a single target,
either choose the 'main' compilation or choose any (this will happen
for Android, and it looks OK for the first time). If there are multiple
compilations of different targets, use the metadata compilation.

Issue #KT-27499 In Progress
2018-10-16 14:30:24 +03:00
Sergey Igushkin
e573911e16 Fix the format used by Kotlin/Native tasks for compiler plugin args
The correct format is "-P arg1", not "-Parg1".
2018-10-16 14:30:24 +03:00
Sergey Igushkin
ee63a6b3af Don't apply the Android Extensions subplugin to non-Android JVM tasks
In a multiplatform project with both Android and non-Android JVM targets
the subplugin should only affect the tasks of the Android target
2018-10-16 14:30:24 +03:00
Sergey Igushkin
5db23f1a81 Support -Xuse-experimental in the new MPP languageSettings { ... } DSL
Add the corresponding Gradle plugin DSL, consistency checks, and logic
for propagating these settings to the compiler during build.

Issue #KT-26840 In Progress
2018-10-16 14:30:24 +03:00
Sergey Rostov
bde6d841c1 IC: move CacheVersionManager from build_common to jps plugin, tests 2018-10-16 13:33:24 +03:00
Sergey Rostov
0d1f7965d4 JPS, CacheAttributesManager: remove unused methods 2018-10-16 12:29:58 +03:00
Sergey Rostov
d91f6f8c43 IC: move CacheVersionManager from build_common to jps plugin 2018-10-16 12:29:58 +03:00
Sergey Rostov
940861c245 IC: remove CacheVersionManager usages from build_common.
They are kept up to date but was never used.
2018-10-16 12:29:58 +03:00
Sergey Rostov
5232f080d6 JPS: Fix updating cache format version for rebuilt targets by removing i/o optimization
Problem: previously, format-version.txt file was deleted while cleaning
target output on rebuild. Since directory was deleted, cache
attributesDiff stored in memory was not updated. This causes that on
saveExpectedStateIfNeeded does nothing.

The right way to fix it is move cache version format diff into
AbstractIncrementalCache, and override `clean()` method. But this is
hard to do for lookup storage, since used compilers set (jvm/js) will
known only after context init. This can be done by moving `expected`
attributes out of manager, but this is huge change for small benefit.

So, the optimal way for now is to write version for each build, even if
it is not changed.

#KT-27044 Fixed
2018-10-16 12:29:58 +03:00
Alexey Sedunov
cf31e4d58c MPP: Recover content root import accidentally removed earlier 2018-10-16 12:05:19 +03:00
Alexey Sedunov
fea397a2ad MPP: Support MPP-dependent Java modules in Android projects
#KT-27265 Fixed
2018-10-16 12:05:19 +03:00
Alexey Sedunov
dcdd42ba00 MPP: Add Android tests for new MPP 2018-10-16 12:05:19 +03:00
Alexey Sedunov
da06e49b19 MPP: Merge module dependencies if one of them has COMPILE scope 2018-10-16 12:05:18 +03:00
Alexey Sedunov
d36ee02499 Gradle: Retrieve AndroidModuleModel using IdeModifiableModelsProvider
Otherwise it may be null if module is just created by the import
2018-10-16 12:05:18 +03:00
Alexey Sedunov
3a0e539eee MPP: Add MPP source roots to dependent non-MPP module
#KT-27365 Fixed
2018-10-16 12:05:18 +03:00
Alexey Sedunov
558345b057 MPP: Assign TEST scope to dependencies of test source sets
#KT-26868 Fixed
2018-10-16 12:05:17 +03:00
Alexey Sedunov
523b662680 MPP: Update Kotlin version in tests to 1.3-RC3 2018-10-16 12:05:17 +03:00
Alexey Sedunov
abec171685 Native: Register '.klib' extension through FileTypeFactory 2018-10-16 12:05:17 +03:00
Alexey Sedunov
ca2367f2b5 MPP: Rewrite ImportedModule name instead of wrapping it
Otherwise this instance is not deserialized properly
breaking import on opening project in AS

 #KT-27485 Fixed
 #KT-27473 Fixed
2018-10-16 12:05:17 +03:00
Denis Zharkov
bda1ef8d57 Do not run bytecode optimization passes for in bodyless modes
FunctionsFromAnyGeneratorImpl has been changed because previously
it didn't satisfy annotation visitor contract but it wasn't important
for MethodNode
2018-10-16 11:16:53 +03:00
Denis Zharkov
26da0b9e7e Do not call default constructor of SourceInterpreter in subclasses
It became illegal since asm-6.x

See c72a86bd5f/asm-analysis/src/main/java/org/objectweb/asm/tree/analysis/SourceInterpreter.java (L56)

 #KT-27572 Fixed
2018-10-16 11:16:53 +03:00
Valentin Kipyatkov
c63eb18b3c Fixed nested class in companion object case 2018-10-16 08:41:43 +03:00
Valentin Kipyatkov
28e2683146 One more test 2018-10-16 08:41:42 +03:00
Valentin Kipyatkov
69f74b2a51 Fixed ShortenReferences for extension on companion object 2018-10-16 08:41:42 +03:00
Valentin Kipyatkov
d4e0f53583 Fixed ShortenReferences for the case of extension for object 2018-10-16 08:41:42 +03:00
Dmitriy Dolovov
840ee66fd0 MPP Wizards: Clearer notation in generated build.gradle files
- Follow the same style as used in public documentation: https://kotlinlang.org/docs/reference/building-mpp-with-gradle.html
- Use standard methods to get link task name, don't evaluate it manually
2018-10-16 10:20:06 +07:00
Georgy Bronnikov
4942ed5e7a Clean up backend.common.ir.IrUtils.kt 2018-10-15 21:52:50 +03:00
Georgy Bronnikov
376eef05f5 JVM_IR. Accessor lowering 2018-10-15 21:52:50 +03:00
Georgy Bronnikov
a23aae590e JVM_IR. Avoid unbound symbols and declarations without parent 2018-10-15 21:52:50 +03:00
Toshiaki Kameyama
9b49c23668 Move lambda out: don't report in delegation #KT-27584 Fixed 2018-10-15 19:52:10 +03:00
Pavel Punegov
8ea8acc7f7 Set target backend to JVM for tests that have @JvmStatic annotations 2018-10-15 19:25:03 +03:00
Pavel Punegov
ed64d42d45 Regenerate JS tests 2018-10-15 19:25:02 +03:00
Pavel Punegov
eb6580acdd Return native ignore back.
K/N doesn't initialize companion objects if no methods were called from them
2018-10-15 19:25:02 +03:00
Pavel Punegov
d9a8a00069 Make tests that use jvm-annotations be targeted to jvm backend 2018-10-15 19:25:02 +03:00
Pavel V. Talanov
8be3e902a8 ResolutionFacadeWithDebugInfo: do not wrap index not ready exception
Fixes problems where `catch (IndexNotReadyException)` blocks
    in IDEA code would not work
2018-10-15 15:10:50 +02:00
Pavel Punegov
aab28e6cc7 Revert "Make coroutines test JVM-only"
This reverts commit 17b7bbce
2018-10-15 13:52:16 +03:00
Natalia Selezneva
648e8acbde Update testdata after the fix of KT-27095
(replace http with https configuring gradle project)
2018-10-15 12:28:43 +03:00
Dmitry Petrov
b6be72bb11 Add more tests for inline classes
#KT-27416
 #KT-27513
2018-10-15 12:21:14 +03:00
Dmitry Petrov
0fd68d29f4 Support @JvmStatic in inline class companion object
#KT-27107
2018-10-15 12:21:14 +03:00
Dmitry Petrov
5304754e88 Generate specialized 'toString' for inline classes when possible
#KT-25613
2018-10-15 12:21:14 +03:00
Dmitry Petrov
f68ce4b35b Support default parameter values for inline class constructors and funs
#KT-26908
 #KT-26554

Move default parameter value tests to separate directory
2018-10-15 12:21:14 +03:00
Dmitry Petrov
8ce1d09f8a Fix inline class coercion in default parameter values
#KT-27358
2018-10-15 12:21:14 +03:00
Natalia Selezneva
c2315f065a Add test for script definitions settings 2018-10-15 11:32:49 +03:00
Natalia Selezneva
71e72ec6c2 Add button to open script settings from Multiple script definition notification 2018-10-15 11:32:49 +03:00
Natalia Selezneva
6596a6ba75 Allow to switch off script definitions
^KT-24465 Fixed
2018-10-15 11:32:48 +03:00
Natalia Selezneva
7826f44180 Save ScriptDefinitions order into kotlinScripting.xml
^KT-24465 In Progress
2018-10-15 11:32:48 +03:00
Natalia Selezneva
77e687df92 Change base class for ErrorGradleScriptDefinition (migrate to new API) 2018-10-15 11:32:48 +03:00
Natalia Selezneva
3f20453ccf Do not create multiple ErrorGradleScriptDefinitions 2018-10-15 11:32:48 +03:00
Natalia Selezneva
9ab4d727e9 Provide UI for changing the order of script definitions applicability
^KT-24465 In Progress
2018-10-15 11:32:47 +03:00
Natalia Selezneva
2df8adc50b Move option for auto-reloading script dependencies to 'Kotlin Scripting' page 2018-10-15 11:32:47 +03:00
Natalia Selezneva
54f3982709 Add 'Kotlin Scripting' configuration tab
^KT-24465 In Progress
2018-10-15 11:32:47 +03:00
Natalia Selezneva
02c1ae62c3 Show notification if there are more than one script definition applicable for one script file (KT-24466)
^KT-24466 Fixed
2018-10-15 11:32:47 +03:00
Dmitry Savvinov
99e1d4ab45 Check for the presence of dispatch receiver too in isEqualsDescriptor()
Otherwise, top-level function with the name 'equals' and suitable
signature will be (erroneously) treated as true 'equals' invocation,
leading to further exception (see EA-126602)
2018-10-15 10:54:39 +03:00
Natalia Selezneva
28e43b0487 Indexes should be updated if there are new dependencies for script file
KT-26271 Fixed
2018-10-15 09:43:49 +03:00
Natalia Selezneva
c4aab8340b Do not store script definition in psiFile
This may cause problems when definitions are reordered or switched off
KT-27375 Fixed
2018-10-15 09:43:49 +03:00
Svyatoslav Kuzmich
02277d0293 [JS IR BE] ExpectDeclarationsRemoving lowering
* Copy lowering from konan to common
* Keep actual default parameters when both actual and expect default parameters are present
* Run lowering before inline in JS IR BE to fix
  box/multiplatform/defaultArguments/inlineFunctionWithDefaultLambda.kt
2018-10-15 00:03:46 +03:00
Svyatoslav Kuzmich
4c38d55f21 [JS IR BE] Unmute tests 2018-10-15 00:03:45 +03:00
Svyatoslav Kuzmich
5a057f8ca6 [JS IR BE] Support 'is Number' and 'is Comparable<>' 2018-10-14 23:53:03 +03:00
Svyatoslav Kuzmich
783f27c554 [JS IR BE] Support Number.to(Byte|Short|Int|Float|Double|Long) 2018-10-14 23:53:03 +03:00
Svyatoslav Kuzmich
bad9534abd [JS IR BE] Support integer operation overflow 2018-10-14 23:53:02 +03:00
Zalim Bashorov
8013a56286 [JS IR BE] process empty loops correctly in BlockDecomposerLowering 2018-10-13 01:51:59 +03:00
Zalim Bashorov
6d592ae66b Unmute tests 2018-10-13 01:51:59 +03:00
Zalim Bashorov
dfc3bda3b4 Minor: remove forgotten "TODO" 2018-10-13 01:51:58 +03:00
Nikolay Krasko
ea9d4037e6 Minor: cleanup KotlinLightCodeInsightFixtureTestCase.kt 2018-10-12 18:50:06 +03:00
Nikolay Krasko
d8fda8b153 Tests for navigation to stdlib multiplatform sources (KT-26004)
#KT-26004 Fixed
2018-10-12 18:50:05 +03:00
Nikolay Krasko
e3d930a6a1 Build maven-like stdlib sources artifacts during dist
This is needed to emulate gradle and maven like projects in plugin tests.
2018-10-12 18:50:04 +03:00
Nikolay Krasko
ac2bc22f54 Use information from stub for contracts presence 2018-10-12 18:21:39 +03:00
Nikolay Krasko
d3ec145f13 Fixes for ReplaceArraysCopyOfWithCopyOfInspection
- Reduce applicability range
- Don't fix reporting level, otherwise it won't be possible to change
  it in settings
- Using isCalling utility
2018-10-12 18:21:38 +03:00
kenji tomita
e6de8e9cd3 Inspection to convert Arrays.copyOf(a, size) to a.copyOf(size) 2018-10-12 18:21:36 +03:00
Nikolay Krasko
fc4f7303d3 Disable highlighting for decompiled Kotlin files (KT-27284)
#KT-27284 Fixed
2018-10-12 18:21:35 +03:00
victor.petukhov
b86211b434 Add spec tests for integer literals 2018-10-12 17:31:24 +03:00
Natalia Selezneva
4f04d4503a Highlight files in diff view (KT-17892)
KT-17892 Fixed
2018-10-12 15:27:46 +03:00
Natalia Selezneva
db0021718f Set since-build for Idea 182 and AS 3.3 to 182.4323.46 2018-10-12 15:27:46 +03:00
Natalia Selezneva
605396f9e2 Update idea to 2018.2.3 (182.4323.46) 2018-10-12 15:27:46 +03:00
Natalia Selezneva
6bddf36725 Update as33 branch to AS3.3 canary 12 2018-10-12 15:27:46 +03:00
Natalia Selezneva
3744a00f77 Run Kotlin Scratch in the background cancelable task (KT-25032)
KT-25032 Fixed
2018-10-12 15:27:46 +03:00
Natalia Selezneva
00e0f430ac Add shortcut and menu item for Run Scratch Action (KT-24180)
KT-24180 Fixed
2018-10-12 15:27:45 +03:00
Natalia Selezneva
af2235fd1d Fix compatibility with anko plugin 2018-10-12 15:27:45 +03:00
Natalia Selezneva
c73885142a Do not access stubs in dumb mode finding script definition 2018-10-12 15:27:45 +03:00
Natalia Selezneva
daa6e9b562 Minor: reformat and rearrange code 2018-10-12 15:27:45 +03:00
Ilmir Usmanov
a5bcd3495e Simplify tail-call optimisation check
Check, that all suspension points are immediately followed by ARETURN
and do not check that all these ARETURNs are immediately preceded by
suspension points.
 #KT-27190 Fixed
2018-10-12 15:10:12 +03:00
Vyacheslav Gerasimov
d11fbac511 Build: Use cache-redirector.jetbrains.com to prevent connection timeouts 2018-10-12 14:57:37 +03:00
Yan Zhulanow
a8aab3fbe5 as33: Remove declaration of the KotlinAndroidGradleOrderEnumerationHandler extension from as33 (KT-26975)
'idea-android' module is not put into the plugin made for Android Studio 3.3 as it has its own copy of 'idea-android'.
2018-10-12 14:50:53 +03:00
Ilmir Usmanov
e21159c28f Report suspension point in monitor error on crossinline lambdas
#KT-27258: Fixed
2018-10-12 14:21:42 +03:00
Zalim Bashorov
3f0bd20235 Add an ability to run/debug ir tests inside node.js (even from IDEA) 2018-10-12 13:57:03 +03:00
Mikhail Zarechenskiy
b7d7d1eb01 Fix inline class type coercion in == with generic call
#KT-27393 Fixed
2018-10-12 12:50:49 +03:00
Mikhail Zarechenskiy
0201694f84 Propagate KotlinType into create method for coroutines
#KT-27526 Fixed
2018-10-12 12:50:47 +03:00
Mikhail Zarechenskiy
a8abd8cceb Fix boxing/unboxing for generic functions on index expressions
Unsubstituted type should be used for coercion to box value of
 inline class type if it's needed. For the substituted value it's not
 known if it was a generic parameter or not.

 #KT-27502 Fixed
2018-10-12 11:58:56 +03:00
Nikolay Krasko
882a12d916 Exit if it's impossible to create file during copy/past (KT-26210)
#KT-26210 Fixed
2018-10-12 11:48:49 +03:00
Toshiaki Kameyama
749fd5dd80 "Convert property to function" intention: don't suggest if property has @JvmField annotation #KT-27157 Fixed 2018-10-11 21:01:27 +03:00
Toshiaki Kameyama
487b1e96be "Introduce backing property" intention: don't suggest if property has @JvmField annotation #KT-27156 Fixed 2018-10-11 21:00:44 +03:00
Toshiaki Kameyama
ca335880eb "Convert property initializer to getter" intention: don't suggest if property has @JvmField annotation #KT-27139 Fixed 2018-10-11 20:59:33 +03:00
Toshiaki Kameyama
3866c85a34 Add accessor intention: don't suggest if property has @JvmField annotation #KT-27139 Fixed 2018-10-11 20:59:33 +03:00
Ilya Gorbunov
27dc160aef Rename Random companion object to Default
#KT-27508
2018-10-11 19:06:12 +03:00
Sergey Igushkin
81b4031a35 Remove internal Gradle API usage for stale output cleanup
BuildOutputCleanupRegistry tracks the all of the outputs that belong to
the Gradle build, so when Gradle runs in an unknown state (e.g. without
any history), it can detect stale outputs in the output directories and
delete them.

Since this is an internal API, its usage is removed. Instead, another
way to tell Gradle that a set of directories belongs to the build is to
add them to the `delete` task targets.
2018-10-11 19:01:53 +03:00
Sergey Igushkin
a0f4d5a637 Get rid of FileCollectionInternal usage that breaks with Gradle 5.0+
Remove the implementation of the `FileCollectionInternal` interface in
`KotlinCompilationOutput`. This interface may change unexpectedly (and
does between Gradle 4.10 and 5.0) so we need to get rid of its
implementation.

On the other hand, we can't just implement `FileCollection` instead
because Gradle internally assumes that all `FileCollection` instances
are also `FileCollectionInternal`. So the way to fix this is to remove
`SourceSetOutput` from superinterfaces of `KotlinCompilationOutput`
altogether.

Instead, to work with `SourceSetOutput` and `KotlinCompilationOutput`
in a uniform way, provide a wrapper for `SourceSetOutput`:
`KotlinWithJavaCompilationOutput` that is basically a proxy
class.
2018-10-11 19:01:52 +03:00
Alexey Sedunov
174fd41564 Rename: Restore project scope (fixing failing tests)
It fixes search of usages for some cases where element's useScope()
is not enough (like parameter references in named arguments)
2018-10-11 17:56:27 +03:00
Alexey Sedunov
84d9f8250c Configuration: Ensure facet UI is initialized in apply() call
#KT-27187 Fixed
2018-10-11 17:56:27 +03:00
Alexey Sedunov
3fcf6e7719 Change Signature: Clear callback after the call
Retaining the callback leads to the leak of obsolete resolve data
2018-10-11 17:56:27 +03:00
Alexey Sedunov
c3af3cc482 Configuration: Do not use read action during conpiler settings loading
It may lead to deadlock (see KT-27298)

 #KT-27298 Fixed
2018-10-11 17:56:27 +03:00
Alexey Sedunov
26d77183df Misc: Update repository URLs in importer test data 2018-10-11 17:56:27 +03:00
Alexey Sedunov
7553fd2766 Misc: Disable some tests for recent Gradle versions
Old-style MPP doesn't work there due to ExternalProject not being built
2018-10-11 17:56:26 +03:00
Toshiaki Kameyama
061aa63a73 "Make private" intention: fix some false positive cases 2018-10-11 17:20:46 +03:00
Mikhail Glukhikh
7488056249 Use 'canBeInternal' in ChangeVisibilityFix (related to KT-27138) 2018-10-11 17:20:30 +03:00
Toshiaki Kameyama
c65e246e02 Make private: don't suggest if property has @JvmField annotation
#KT-27138 Fixed
2018-10-11 17:20:13 +03:00
Mikhail Glukhikh
248e09ff2c Refactoring: ConstantConditionIfInspection
Transform collectFixesAndRegisterProblem to just collectFixes
2018-10-11 17:19:55 +03:00
Toshiaki Kameyama
5c83c247d7 "Simplify comparison": remove if when possible after applying quickfix
#KT-25995 Fixed
2018-10-11 17:19:10 +03:00
Mikhail Glukhikh
688fc386b6 Refactoring: introduce resolve to property descriptor 2018-10-11 17:14:17 +03:00
Mikhail Glukhikh
b08f966428 Use kotlin-stdlib instead of kotlin-stdlib-jdk8 in MPP mobile wizard
#KT-27356 Fixed
2018-10-11 17:12:31 +03:00
Mikhail Glukhikh
42888572cb MPP wizards: generate different file names to avoid KT-21186
#KT-27456 Fixed
2018-10-11 17:11:44 +03:00
Anton Bannykh
8852ef9e75 [JS IR BE] fix multimodule 2018-10-11 16:02:21 +03:00
Zalim Bashorov
9041d717a2 [JS IR BE] add IrType.asString that return stable string representation to use it for stringified signatures
`IrType.render` was used before, but it's written for debugging purpose and generates unstable string representation.
2018-10-11 14:54:55 +03:00
Ilmir Usmanov
c4d0b5493a Fix NPE in suspension point in monitor call checker
#KT-27484 Fixed
2018-10-11 14:38:34 +03:00
Denis Zharkov
36c73eedbf Minor. Move DslMarkerOnFunctionTypeReceiver entry closer to 1.4 features 2018-10-11 10:23:02 +03:00
Denis Zharkov
75dc8ce1c3 Fix exception in light classes when type alias in MultifileClass
#KT-27355 Fixed
2018-10-11 10:22:09 +03:00
Toshiaki Kameyama
dc750cdbb3 Call chain into sequence: add 'unzip' to conversion targets #KT-27486 Fixed 2018-10-11 09:18:30 +03:00
Toshiaki Kameyama
3f252b15e1 Call chain into sequence: add 'flatten' to conversion targets #KT-26969 Fixed 2018-10-11 09:17:23 +03:00
Nikolay Krasko
bd27460694 Prevent IDEA attach debugger to serialize task
Workaround for IDEA-200192

IDEA patches JavaExec tasks and adds
agentlib:jdwp= jvm parameter when running under debug.

Replace parameters after IDEA has finished patching parameters.
2018-10-10 20:58:00 +03:00
Svyatoslav Kuzmich
7074909230 [JS IR BE] Support enumValues<T>() and enumValueOf<T>(name) 2018-10-10 19:35:17 +03:00
Svyatoslav Kuzmich
bdc3daf972 [JS IR BE] Support Enum::values 2018-10-10 19:35:17 +03:00
Svyatoslav Kuzmich
0210ec3114 [JS BE] Fix KT-26787: handle JsSwitch in LabeledBlockToDoWhileTransformation 2018-10-10 19:35:16 +03:00
Pavel Punegov
f543170998 Increase tolerance for Float asin test 2018-10-10 19:05:44 +03:00
Sergey Bogolepov
2f1f32bbf4 Replace random val in companion object with top level val 2018-10-10 19:04:55 +03:00
Pavel Punegov
17b7bbce8c Make coroutines test JVM-only 2018-10-10 19:04:31 +03:00
Pavel Punegov
3dd16da315 Fix vararg test for native that assigns named argument.
Ignore test that uses nested class in enum in native
2018-10-10 19:03:56 +03:00
Pavel Punegov
dd1c9fa9f0 Native: Ignore tests that use reflection not implemented in native 2018-10-10 19:01:35 +03:00
Pavel Punegov
82b59c5044 Native: Ignore tests that use jvm or full reflect 2018-10-10 19:00:50 +03:00
Svyatoslav Kuzmich
89f7ced0d4 [JS IR BE] Unmute tests 2018-10-10 17:27:37 +03:00
Svyatoslav Kuzmich
e73ff16b35 [JS IR BE] Refactor: split IntrinsicifyCallsLowering into multiple classes 2018-10-10 17:27:37 +03:00
Svyatoslav Kuzmich
749556f565 [JS IR BE] Support Long coercion 2018-10-10 17:27:37 +03:00
Svyatoslav Kuzmich
c7bde6a5e6 [JS IR BE] Fix runtime compareTo(Number, Long) 2018-10-10 17:27:36 +03:00
Anton Bannykh
44d56cb278 JS: fix val with backing field initialization in secondary constructors
This change reverts the AssignmentTranslator logic to a previous state
of "if we assign to a val, tranlate to backing field". Previously a
check whether or not we are inside of a constructor was added. The
check didn't detect secondary constructors, hence initializing of
val's with backing field started to work incorrectly.

The check itself was added in an attempt to prevent augmented assignment
operators to reference the backing field. The check seems to have been
wrong, because an augmented assignment could happen inside a construcotr.
A more correct fix was added later. It seems that it is safe now to
revert the logic back and rely on the frontend to only allow assignment
to a val property during initilization.
2018-10-10 17:25:55 +03:00
Mikhail Glukhikh
6be65e7d1a Replace equals with == involving FP types: handle possible smart casts
This fixes two relevant tests with smart casts
#KT-25933 Fixed
2018-10-10 15:02:47 +03:00
Mikhail Glukhikh
04cadf3f58 Reformat ReplaceCallWithBinaryOperator 2018-10-10 15:02:45 +03:00
kenji tomita
1aa9d5673b Do not highlight replacement of equals involving floating-point types
Two tests with smart casts do not work yet
Part of KT-25933
2018-10-10 15:02:43 +03:00
Anton Bannykh
8c6337f3f6 [JS IR BE]: support dynamic_var["foo"] = "bar"
Used EQ origin to detect. Added a test to check dynamic_var = "bar" case
is not affected
2018-10-10 13:43:22 +03:00
Anton Bannykh
7afb81a7df JVM_IR: fix ranges' test generator 2018-10-10 13:13:36 +03:00
Ilya Chernikov
7fbfad814e Fix default host configuration property - make it not shared:
Shared instance is incorrect here and causes clashes when many
definitions are loaded in the same process.
Also make the diagnostics in case of clashes more verbose.
2018-10-10 10:53:57 +02:00
John Eismeier
ac69fa14d5 Is the Interface with out the f a type? 2018-10-10 09:44:10 +03:00
Ilmir Usmanov
9af7316845 Add call checker to report error more granulary if possible
This, however, works only for calls of 'synchronized' only. Thus, it
does not support inline functions of any kind.
2018-10-09 22:55:51 +03:00
Ilmir Usmanov
281f09f077 Rework check of suspension point inside critical section
There is a trade-off between robustness of check and accuracy of the
diagnostic: the previous version, which works on generation, was too
fragile and lead to false-positives. Now we check on state machine
generation. However, since we do not have PSI for call, we can only
report diagnostic on whole suspend function or suspend lambda.
Additionally, the state machine is generated on crossinline suspend
lambdas regeneration and thus we do not have the PSI for the lambda as
well!

 #KT-27130 Fixed
 #KT-27258 Open
2018-10-09 22:55:48 +03:00
Ilmir Usmanov
1b04945625 Revert: Forbid suspension points in critical sections 2018-10-09 22:55:43 +03:00
Vyacheslav Gerasimov
37a88fda78 Build: Remove shadow jar task from custom-deps/intellij-sdk project 2018-10-09 20:48:27 +03:00
Vyacheslav Gerasimov
78d4abf954 Build: set version for build-scan plugin to 1.15 since 1.16 fails with NPE 2018-10-09 20:27:15 +03:00
Sergey Igushkin
294bd8c7fa Fix resolution of Java Usage artifacts for configurations with no usage
When Gradle resolves a dependency on a publication with no metadata
(or with metadata disabled), it represents it as two variants, one with
Usage `java-api`, the other with `java-runtime`. It turns out that the
`java-api` one does not contain transitive dependencies with Maven scope
`runtime`.

This commit makes the Kotlin Gradle plugin disambiguation rules behave
the same way as those defined in the JavaBasePlugin: when no Usage is
requested, prefer the runtime usages as they are more complete.
2018-10-09 19:17:36 +03:00
Sergey Igushkin
748dc203e5 Fix unresolved library with 'java-api' and 'java-runtime' usages 2018-10-09 19:17:36 +03:00
romanart
d77a0f109b Update tests 2018-10-09 15:33:04 +03:00
romanart
5af114da07 Add unit into compilation 2018-10-09 15:33:03 +03:00
romanart
9b40981368 [JS IR BE] Unit Materialization lowering
Fix unit-related things across backend
2018-10-09 15:32:52 +03:00
Toshiaki Kameyama
57ae60e9dc "Add else branch" on when quickfix: don't add braces #KT-5088 Fixed 2018-10-09 12:28:08 +03:00
Toshiaki Kameyama
f22133be7e Call chain into sequence refactoring: introduce & use isIterable
Related to KT-26650
2018-10-09 12:22:19 +03:00
Toshiaki Kameyama
416d33fc92 Refactoring: extract KtCallExpression.isCall(FqName) function 2018-10-09 12:22:18 +03:00
Toshiaki Kameyama
9a725b99b2 Call chain into sequence: fix false negative on Iterable
#KT-26650 Fixed
2018-10-09 12:22:17 +03:00
Mikhail Glukhikh
2e5ee242c7 Minor refactoring: implicitVisibility 2018-10-09 11:50:21 +03:00
Toshiaki Kameyama
3be5f2b843 "Redundant visibility": Fix false positive for overridden setter
#KT-26051 Fixed
2018-10-09 11:48:00 +03:00
Toshiaki Kameyama
1c8e75eb34 if then to elvis: propose transformation to 'let' #KT-26653 Fixed 2018-10-09 11:41:06 +03:00
Toshiaki Kameyama
539c55c5b2 Call chain into sequence: fix false negative on implicit receiver
Part of KT-26650
2018-10-09 11:33:55 +03:00
Mikhail Glukhikh
0285cae2fd Minor: introduce 'lazyTerminations' in Call chain --> Sequence
Related to KT-27104
2018-10-09 11:32:25 +03:00
Toshiaki Kameyama
8fc5fefc7f Call chain --> Sequence: don't report if first call is 'groupingBy'
#KT-27104 Fixed
2018-10-09 11:26:50 +03:00
Mikhail Glukhikh
b500239bd1 Call chain -> sequence: minor style fix 2018-10-09 11:09:58 +03:00
Toshiaki Kameyama
3c75dd7b5a Fix inspection message 2018-10-09 11:09:43 +03:00
Toshiaki Kameyama
920c200693 Call chain --> Sequence: introduce "call chain length" parameter
#KT-26571 Fixed
2018-10-09 11:09:28 +03:00
Mikhail Glukhikh
a43be4cbe8 Fix testNotPossible (no more conversion to secondary constructor) 2018-10-09 11:08:37 +03:00
victor.petukhov
c01362a943 Fix path separators for Windows in spec test validator 2018-10-09 10:00:07 +03:00
victor.petukhov
4ee0a666cb Temporary mute test with FrontEndException (KT-26386) 2018-10-09 09:59:56 +03:00
victor.petukhov
f61980732b Mute tests with unexpected behaviour 2018-10-09 09:59:46 +03:00
victor.petukhov
e90cf4b955 Actualize test with return expression in contract description (implies) 2018-10-09 09:59:35 +03:00
victor.petukhov
4a372458d6 Include part of the spec tests to the compiler dist tests 2018-10-09 09:59:20 +03:00
Ilya Matveev
85ba5f11d6 Add configuration methods for kotlinOptions in K/N tasks
Issue #KT-26758 fixed.
2018-10-08 17:44:32 +03:00
Ilya Matveev
ee5bc95da5 Fix up-to-date checks for framework compilation 2018-10-08 17:44:32 +03:00
Ilya Matveev
73138073f1 Take K/N version into account in UP-TO-DATE checks for cinterop tasks 2018-10-08 17:44:32 +03:00
Alex Saveau
524ae9df7d Fix bugs causing early task evaluation (#1812)
* Fix bugs causing early task evaluation

Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>

* Fix merge mistakes

Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>

* Fix another call forcing tasks evaluation  Add a test for lazy tasks
2018-10-08 14:07:22 +03:00
James Wald
b7d0d20739 Fix typo in expression precedence table 2018-10-08 14:00:51 +03:00
Nikolay Krasko
1aab3c890c Minor: fix typo 2018-10-08 13:40:29 +03:00
Alexey Belkov
f3bb952148 Remove useless code to determine default visibility 2018-10-08 13:40:28 +03:00
Nikolay Krasko
daf6036bc0 Update Android Studio 3.3 dependency to 3.3.0.10 2018-10-08 13:40:27 +03:00
Nikolay Krasko
76a3f23df0 Test for stubs of extension/non-extension properties with same name (KT-27274)
An issue was probably fixed in 98232265d7

 #KT-27274 Fixed
2018-10-08 13:40:25 +03:00
Toshiaki Kameyama
b0c3461eab Add quickfix for ASSIGN_OPERATOR_AMBIGUITY on mutable collection '+=', '-='
KT-26236 Fixed
2018-10-05 15:58:39 +03:00
Toshiaki Kameyama
725cb88f41 Add quick-fix to "Unlabeled return inside lambda" inspection #KT-27007 Fixed 2018-10-05 10:01:31 +02:00
Vyacheslav Gerasimov
d7b885159e Revert Workaround IndexOuOfBoundsException on configuration with gradle 4.7 2018-10-04 18:28:16 +03:00
Toshiaki Kameyama
f4a637a72e "Convert object literal to lambda" inspection: report at INFORMATION level if object literal has 'return' #KT-27116 Fixed 2018-10-04 13:13:52 +02:00
Toshiaki Kameyama
23734bae3e Add quickfix for DECLARATION_CANT_BE_INLINED #KT-9983 Fixed 2018-10-04 13:11:36 +02:00
Toshiaki Kameyama
c44d3a8d68 Show lambda parameter info #KT-13118 Fixed 2018-10-03 19:08:56 +03:00
victor.petukhov
30fc76a602 Remove redundant directives to contracts use 2018-10-03 13:49:32 +03:00
victor.petukhov
4819223b74 Add generated codegen box tests for Boolean literals as identifiers 2018-10-03 13:49:31 +03:00
victor.petukhov
1bc0c4092c Add codegen box test templates for identifiers 2018-10-03 13:49:30 +03:00
victor.petukhov
dd91727a78 Add generated PSI tests for Boolean literals as identifiers 2018-10-03 13:49:22 +03:00
victor.petukhov
ed73513d48 Add PSI test templates for identifiers 2018-10-03 13:49:20 +03:00
victor.petukhov
4bfa90dc25 Refactor files in the 'spec' package 2018-10-03 13:49:11 +03:00
victor.petukhov
45c5a168a3 Implement feature interaction tests generator based on templates 2018-10-03 13:48:22 +03:00
victor.petukhov
6f95e4ae3b Add codegen box spec tests support 2018-10-03 13:29:25 +03:00
victor.petukhov
8538866778 Add few tests for contracts
- Contracts in getter/setter (unexpected behaviour)
- Check smartcasts when non-null assertion for a contract function is used
- Check work of contracts when type parameter of the callsInPlace is specify explicitly
- Check smartcasts working if type checking for contract function is used
2018-10-03 13:29:13 +03:00
victor.petukhov
ecb3f10e47 Add 'mute' concept: move tests with unexpected behaviour to the corresponding folder 2018-10-03 13:26:37 +03:00
victor.petukhov
84dc28374c Add multilevel sections support and corresponding renaming 2018-10-03 13:26:29 +03:00
Ilya Gorbunov
2c313e12e5 Rewrite builtin serialization task as JavaExec
Add standard clean, assemble, build tasks by applying base plugin.
Clean outputs in dist/builtins on clean.
2018-10-03 11:51:30 +03:00
Dmitry Petrov
b55b0c1ff1 Support local property delegation to inline class values
Also, add extra test on property delegation.
2018-10-03 11:09:48 +03:00
Dmitry Petrov
6fa436911a Support interface delegation to inline class values (KT-27318) 2018-10-03 11:09:47 +03:00
Dmitry Petrov
5480bf69e8 Support property delegation to inline class values (KT-27070) 2018-10-03 11:09:46 +03:00
Dmitry Petrov
70e60ea9bc Fix inline class coercion in string template with StringBuilder.append
Inline class values with array as a carrier type were not boxed.

 #KT-27113
2018-10-03 11:09:41 +03:00
kenji tomita
6532916dd2 Change necessary labels in "Call on collection type may be reduced"
#KT-24492 Fixed
2018-10-03 08:00:40 +02:00
Toshiaki Kameyama
5e7d974767 "Make open": Fix false positive for data class inheritance #KT-27354 Fixed 2018-10-03 08:53:03 +03:00
Yan Zhulanow
6d73aa29e0 Pill: Understand dependencies with the 'apiElements' configuration name as module dependencies 2018-10-02 20:03:01 +03:00
Dmitry Petrov
813e4c966a Update testData for constant initializers in IR 2018-10-02 17:08:55 +03:00
Dmitry Petrov
189b05f8a4 Update testData for public API: companion field visibility in 1.3 2018-10-02 16:20:09 +03:00
Nikolay Krasko
02fbb03d6a Show migration when changes are in kts files or inside buildSrc dir (KT-27329)
#KT-27329 Fixed
2018-10-02 16:05:18 +03:00
Nikolay Krasko
d756d93af1 Better coroutines versions update (KT-27351)
- It was decided to update coroutines to 1.0.0 not to 0.30.0 for 1.3
- Always update to 0.27.0-eap13 coroutines for versions before 0.27.0

 #KT-27351 Fixed
2018-10-02 15:54:10 +03:00
Dmitry Petrov
8891733074 Generate const val initializers as IrConst expressions 2018-10-02 13:46:37 +03:00
Mikhail Glukhikh
75b27f890a Fix tests in mobile shared library wizard #KT-27335 Fixed 2018-10-02 13:08:45 +03:00
Mikhael Bogdanov
4fb434c0de Move out jvm-specific part from ir-common
#KT-27005 Fixed
2018-10-02 11:12:21 +02:00
victor.petukhov
023e4e3a0e Actualize tests after KT-27260 fix 2018-10-02 11:49:10 +03:00
Alexey Sedunov
b5d3520db9 MPP: Add MPP sources roots to dependent Android module
#KT-27331 Fixed
2018-10-02 11:18:09 +03:00
Dmitry Savvinov
62edf29cbf Use DataFlowValue instead of Descriptor for equality of ESDataFlowValue
Equality of those values is crucial for intersecting data-flow info
coming from expressions like: 'this.x != null || other.x != null'.

Using 'ValueDescriptor' for equality is obviously wrong, because then 'this.x'
and 'other.x' will be treated as equal, leading to unsound smartcasts.

This commit adds proper overload of 'equals' to 'ESDataFlowValue' that
will compare them based on underlying 'DataFlowValue' (which already
distinguish those values)

^KT-27260 Fixed
2018-10-02 11:05:06 +03:00
Dmitry Savvinov
dd682bd37d Add test on data-flow
Idea is to intersect similar smartcasts on similar properties coming
from *different* instances (something like
'this.x == null && other.x == null' ).

It checks that we distinguish subjects of such smartcasts properly.

Currently behavior is undesired, see KT-27260
2018-10-02 11:05:06 +03:00
Mikhail Zarechenskiy
e74469fdfc Use mutable lists before deserialization of project structure
The problem is that we perform xml deserialization using intellij
 mechanism which tries to clear target object if it isn't unmodifiable
 (see CollectionBinding.isMutableCollection). This check fails for
 kotlin.EmptyList (emptyList()) which then cause exception

 #KT-27321 Fixed
2018-10-01 19:43:03 +03:00
Ilya Chernikov
da9c486a70 Fix gradle support for non-kts scripts for inter-project dependencies 2018-10-01 18:34:15 +02:00
Ilya Chernikov
c50e880173 Implement more precise diagnostic when a standard script template is missing
adapt quickfix accordingly
#KT-26505 fixed
2018-10-01 18:34:15 +02:00
Ilya Gorbunov
b1c4590537 Override docs of MutableList.add/addAll methods
#KT-25632
2018-10-01 18:09:09 +03:00
Ilya Gorbunov
d6beddaac5 Document the requirement for 'minus(elements)' to have stable hashCode
#KT-24536
2018-10-01 18:09:09 +03:00
Ilya Gorbunov
27beadad18 Summary for new packages: kotlin.coroutines, kotlin.contracts, kotlin.random 2018-10-01 18:03:28 +03:00
Ilya Gorbunov
08822ff14b Document that lines and lineSequence do not preserve line separators 2018-10-01 18:03:23 +03:00
Ilya Gorbunov
21b71f3bb1 Clarify the purpose of the message parameter of assertFailsWith
#KT-22869 Fixed
2018-10-01 18:03:23 +03:00
Ilya Gorbunov
9f9033870c Add a note about non-atomic behavior of MutableMap.getOrPut
#KT-13821
2018-10-01 18:03:23 +03:00
Ilya Gorbunov
bb9e9ac1ee Seeded random docs: add a note about repeatability not being preserved
We're not ready to give a guarantee that the seeded generator
implementation will never change in future versions.
2018-10-01 18:03:23 +03:00
Ilmir Usmanov
896913907b Update bootstap 2018-10-01 17:30:06 +03:00
Alexander Udalov
712c9cbfe6 Minor, mute legacyModOperator.kt for JVM_IR 2018-10-01 16:17:14 +02:00
Alexander Udalov
04ba1cff05 Minor, unmute bothInExpectAndActual.kt for JS_IR 2018-10-01 16:17:14 +02:00
Alexander Udalov
6a6a28f8cd Fix ComponentContainerTest 2018-10-01 16:17:14 +02:00
Vyacheslav Gerasimov
f871e9dc79 Update gradle version to 4.10.2 2018-10-01 16:38:58 +03:00
Vyacheslav Gerasimov
f9cefdaa44 Add to kotlin-plugin.jar js.translator module referenced by serialization 2018-10-01 16:27:23 +03:00
Vyacheslav Gerasimov
28c84d0e00 183: Make 183 plugin compatible with upcoming Idea 191 2018-10-01 15:35:50 +03:00
Mikhail Glukhikh
6dbb51d7a7 MPP wizards: remove AS bunches (anyway they aren't accessible for AS) 2018-10-01 15:07:44 +03:00
Alexey Sedunov
a24e58f5a0 Configuration: Update repository URLs to use HTTPS instead of HTTP
#KT-27095 Fixed
2018-10-01 14:46:52 +03:00
Alexey Sedunov
03b289b899 Configuration: Do not save default values of sourceMapEmbedSources 2018-10-01 14:46:52 +03:00
Alexey Sedunov
0765cb9c62 Minor: Fix model access 2018-10-01 14:46:52 +03:00
Alexander Udalov
55c8b35eee Remove unneeded default imports in stdlib and tests 2018-10-01 13:39:02 +02:00
Mikhail Glukhikh
199ae3bac8 Forbid all MPP wizards in IDEA 173, but leave them in AS 3.1
Related to KT-27267
2018-10-01 14:36:52 +03:00
Mikhail Glukhikh
4c85616ee3 Forbid all MPP native-related wizards in IDEA 181, but leave in AS 3.2
Related to KT-27267
2018-10-01 14:36:51 +03:00
Alexander Udalov
009f18f1f4 Split AnalysisFlag values to AnalysisFlags and JvmAnalysisFlags
Declare AnalysisFlags in module 'frontend', and JvmAnalysisFlags in
module 'frontend.java', to avoid leaking Java-related logic to common
compiler code
2018-10-01 13:31:00 +02:00
Alexey Sedunov
c59779f5b9 MPP: Retain KotlinSourceSetInfo for Android in data nodes
User data is not serialized which leads to broken import on reopening

 #KT-27213 Fixed
2018-10-01 13:55:35 +03:00
Alexey Sedunov
c183c5b36a MPP: Add dependencies for all source sets for a given Android variant 2018-10-01 13:55:31 +03:00
Alexey Sedunov
63500216f0 MPP: Fix recognition of test source sets in Android projects
#KT-27212 Fixed
2018-10-01 13:55:26 +03:00
Alexey Sedunov
5b8208c751 MPP: Fix import failure in the case unresolved dependency is found
Instead report unresolved dependencies in Gradle build results

 #KT-27029 Fixed
2018-10-01 13:55:22 +03:00
Alexey Sedunov
99f63f2ebd Configuration: Use model provider to access facets
Otherwise newly created Android project may get invalid SDK
until the reimport is performed

 #KT-27193 Fixed
2018-10-01 13:55:16 +03:00
Mikhail Glukhikh
eb528c3d65 MPP mobile wizard: generate also Xcode (r) project for iOS
#KT-27178 Fixed
2018-10-01 13:46:37 +03:00
Dmitriy Dolovov
21952960f6 [K/N] Allow common source sets in projects created with wizard
Issue #KT-27232 Fixed
2018-10-01 16:36:32 +07:00
Georgy Bronnikov
ade640eadb JVM_IR. Support compile time constants 2018-10-01 12:25:55 +03:00
Denis Zharkov
623c6803d6 Fix regression on smart casts in when on a sealed class
See the comment in PatternMatchingTypingVisitor

 #KT-27221 Fixed
2018-10-01 09:59:28 +03:00
Dmitry Petrov
729da29e49 Update command-line options help for '-Xnormalize-constructor-calls'
Default value depends on language version.
2018-10-01 09:42:13 +03:00
Ilya Matveev
d2740db88f Update Kotlin/Native: 0.9.3 2018-09-30 11:27:13 +03:00
Ilya Matveev
7a5c05b72d Filter java.endorsed.dirs property in K/N runner 2018-09-30 11:27:13 +03:00
Nikolay Krasko
b09ec3cbb3 Shortcut quick fix for migrating all coroutines in the project (KT-27164)
#KT-27164 Fixed
2018-09-29 16:27:45 +03:00
Nikolay Krasko
282407c4a7 Minor: register problems through holder function 2018-09-29 16:27:43 +03:00
Nikolay Krasko
0efb4cc5f6 Refactoring: extract fun in ObsoleteExperimentalCoroutinesInspection.kt 2018-09-29 16:27:42 +03:00
Sergey Igushkin
58a8411575 Fix KNPE due to publications processing order in Gradle 4.7
A KNPE happened because Gradle 4.7 (but not 4.8+) requested a
publication's dependencies before all other publications were created.

Issue #KT-27231 Fixed
2018-09-28 21:57:09 +03:00
Svyatoslav Kuzmich
334c776b92 [JS IR BE] Fix @DoNotIntrinsify processing. Reuse it for compareTo 2018-09-28 20:27:01 +03:00
Ilya Gorbunov
12a31637d1 Improve groupingBy samples 2018-09-28 19:59:30 +03:00
Ilya Gorbunov
3a40e3f041 Move groupingByEachCount together with the new Grouping samples 2018-09-28 19:51:07 +03:00
Itsuki Aoyagi
039d41679e Add samples for groupingBy operations 2018-09-28 19:51:07 +03:00
Toshiaki Kameyama
d89947bd5a "Convert put to assignment": don't report on 'super' #KT-27146 Fixed 2018-09-28 19:43:05 +03:00
Leonid Startsev
b611facd71 Check if serialization plugin presents in the facet compiler classpath before applying extensions logic
#KT-27166 Fixed
2018-09-28 18:31:03 +03:00
Alexander Udalov
088cd4b5e3 Stop parsing argument in argfile when quote ends
There are two visible effects of this change:
1) If an empty argument is passed in quotes, it will be parsed as an
   empty string and handled by the compiler, which will report an error
   later. The specific error is not very important because it's an edge
   case anyway; at the moment, "source file or directory not found:" is
   reported which is no better than the "invalid flag:" error reported
   by javac in the similar case
2) It's no longer possible to split an argument into several parts and
   quote them separately, such as:

       "-langu"ag"e-"ver'sio'n 1.2

   No test added for this change in behavior since it's an even edgier
   case. Note that javac also prohibits this.

 #KT-27226 Fixed
2018-09-28 16:02:40 +02:00
Alexander Udalov
16dd6ebe61 Handle whitespaces in argfiles correctly
#KT-27218 Fixed
2018-09-28 16:02:40 +02:00
Mikhail Glukhikh
ab05f17d1d Fix ifThenToSafeAccess inspection test 2018-09-28 15:11:40 +03:00
Pavel Punegov
fedb9ad035 Merge branch 'ignore-defaultArgs-mpp' 2018-09-28 14:27:12 +03:00
Pavel Punegov
7c2c4e68ce Ignore 2 tests in Native: default arguments got from expect declarations there 2018-09-28 14:22:27 +03:00
Ilya Matveev
5140e674b4 Use compileClasspath configuration for native standard libraries 2018-09-28 14:15:11 +03:00
Ilya Matveev
5c4adc1100 Don't add dependency on a klib task for binary tasks 2018-09-28 14:15:11 +03:00
Dmitry Petrov
7b7cf39388 Fix inline classes coercion in 'if' expression
#KT-27132
2018-09-28 10:46:42 +03:00
Dmitry Petrov
ab90b2b901 Fix nullability propagation in inline class type mapping
#KT-27096

See https://jetbrains.slack.com/archives/C06E082M6/p1537949572000100
2018-09-28 10:46:42 +03:00
Dmitry Petrov
0b23ddb947 Add test for KT-27140 2018-09-28 10:46:42 +03:00
Nikolay Krasko
1901331ee5 Remove NotificationAction.createSimple to fix compilation in 173 2018-09-28 10:37:43 +03:00
Ilmir Usmanov
e7bed58ebe Fix bootstrap 2018-09-27 21:59:38 +03:00
Ilmir Usmanov
6e0391f9ec Use release coroutines in script-runtime 2018-09-27 21:59:35 +03:00
Dmitry Petrov
0191e3d1cf Migrate to release coroutines 2018-09-27 21:59:31 +03:00
Yan Zhulanow
bbc73ec0e5 MPP: Fix JPS tests
Move back the application check as only the class presence check is not sufficient.
2018-09-27 21:31:30 +03:00
Mikhail Glukhikh
ca4547c40a Add Maven Publish to MPP library wizards (in progress) #KT-27201 Fixed 2018-09-27 20:16:05 +03:00
Mikhail Glukhikh
e7100838d0 Introduce MPP wizard for mobile (Android / iOS) libraries
#KT-27200 Fixed
2018-09-27 19:43:04 +03:00
Nikolay Krasko
41bd29c3e9 Replace migration dialog with sticky popup (KT-27163)
#KT-27163 Fixed
2018-09-27 18:48:54 +03:00
Pavel V. Talanov
ce9028e367 Prefer data from facet settings when computing module js output root
#KT-26872 Fixed
2018-09-27 17:21:09 +02:00
Sergey Igushkin
2441df820b Support Kotlin/JS DCE in new MPP
Issue #KT-27196 Fixed
2018-09-27 17:54:38 +03:00
Ilya Chernikov
499146db0e Fix pill problem with main-kts-test, reenabling pill for main-kts modules 2018-09-27 16:27:55 +02:00
Ilya Chernikov
0303fc036c Fix gradle support for non-kts scripts when daemon is used 2018-09-27 16:27:17 +02:00
Dmitriy Dolovov
bfa6d57e34 [K/N] Improvements in new application wizard in IDEA
Issue #KT-27210 Fixed
2018-09-27 18:37:46 +07:00
Ilya Chernikov
7b7f87a3b7 Move ivy resolver to the main-kts to avoid classloading issues...
e.g. when main-kts is loaded in IDEA
#KT-26828 fixed
2018-09-27 12:56:19 +02:00
Dmitry Savvinov
6065095e24 Fix too aggressive data-flow clearing of loop-assigned vars
This is effectively a revert of
447c127036, which was an (incorrect) fix
for KT-22379.

The bug was that we've cleared data-flow info for assigned variables
*after* knowledge that loop condition if 'false' was applied (we can
claim that if loop has no jump-outs). Therefore, we broke smartcasts in
the innocent code like that:

  var x: Int? = null
  while (x == null) {
      x = readPotentiallyNullableInt()
  }
  // x should be non-null here

Commit reverts that "fix" for 1.3.0 and postpones deprecation until 1.4

KT-22379 Open
KT-27084 Fixed
2018-09-27 12:09:22 +03:00
Dmitry Savvinov
99454aa78d Add test on smartcast from while-assigned var
Currently behavior is undesired, it will be fixed in the next commit
(see KT-27084)
2018-09-27 12:09:21 +03:00
Nikolay Krasko
056c61090d Ignore non-kotlin modules during building migration information (KT-27100)
Otherwise maximum settings might be always obtained from project compiler
settings and thus stay unchanged during migration process.

 #KT-27100 Fixed
2018-09-27 11:59:49 +03:00
Pavel V. Talanov
2d52865415 Default to plain 'Run' icon when calculating icons for common code
#KT-26942 Fixed
2018-09-27 10:51:43 +02:00
Alexey Sedunov
8d3e997a82 Configuration: Do not configure SDK for Android modules
This is already done by the Android plugin itself

 #KT-27193 Fixed
2018-09-27 10:46:44 +02:00
Alexander Udalov
9f6575c57f Add file name to exception on invalid module-info.class in dependencies
This will help users in working around KT-23025
2018-09-27 10:16:15 +02:00
Dmitry Petrov
7624dbbb20 Fix subject variable handling in specialized enum codegen
#KT-27161
2018-09-27 10:48:35 +03:00
Mikhail Glukhikh
258999fa9e Always use Gradle wrapper 4.7 in MPP projects #KT-27177 Fixed 2018-09-27 10:45:00 +03:00
Dmitry Petrov
0dd04c3424 Postpone companion object field visibility
Have to reconsider this issue because of interface companion objects.
2018-09-27 10:35:23 +03:00
Dmitry Petrov
792ff3c39e Generate private interface companion object as package-private synthetic 2018-09-27 10:35:23 +03:00
Dmitry Petrov
7949ac1080 Use common instance receiver generation logic for 'this' expression
Otherwise it would skip private companion object accessor generation.
2018-09-27 10:35:23 +03:00
Denis Zharkov
c4337f753e Restore binary compatibility for IDE plugins
Caused by 341f7c348a
2018-09-27 10:16:20 +03:00
Ilya Gorbunov
0c81e30d46 Make a more correct implementation of unsigned arrays copyInto
Return the destination array instead of the destination storage array
wrapped in a new unsigned array. The difference should be
indistinguishable, however in JS, where inline classes are not inlined yet,
it had resulted in an extra wrapper.
2018-09-26 22:57:14 +03:00
ymnder
1a20b1f357 Add sample for 'repeat' function
Co-authored-by: Ilya Gorbunov <ilya.gorbunov@jetbrains.com>
2018-09-26 22:39:56 +03:00
shiraji
0c97d99d77 KT-20357 Add sample code for Regex.find
Co-authored-by: Ilya Gorbunov <ilya.gorbunov@jetbrains.com>
2018-09-26 22:24:53 +03:00
takattata
f06ea6fddd KT-20357 Add sample code for Char extensions 2018-09-26 21:58:50 +03:00
Takayuki Matsubara
d26c0f777b KT-20357 Add samples for Map.containsValue
Co-authored-by: Ilya Gorbunov <ilya.gorbunov@jetbrains.com>
2018-09-26 21:03:57 +03:00
Keita Watanabe
12ec4fdce0 KT-20357 Add sample for mutableSet function 2018-09-26 20:44:40 +03:00
Ilya Gorbunov
df6ccbca49 KT-20357 Add samples for elementAtOrElse
Move samples to Elements nested class.
2018-09-26 20:44:40 +03:00
Takayuki Matsubara
7d5efe7f51 KT-20357 Add samples for elementAtOrNull 2018-09-26 20:44:40 +03:00
Takayuki Matsubara
ad9b700ec4 KT-20357 Add samples for elementAt 2018-09-26 20:44:40 +03:00
Leonid Startsev
40b3514a47 Include serialization config in IDE for IDEA 183, AS 3.2 and 3.3 2018-09-26 19:47:07 +03:00
Alexander Udalov
5713298108 Fix FQ name usage of experimental marker in UseExperimental
#KT-26366 Fixed
2018-09-26 18:36:01 +02:00
Vyacheslav Gerasimov
cb398ea6b1 Fix compilation of kotlin-gradle-plugin broken after migration to gradle 4.10 2018-09-26 18:56:35 +03:00
Ilya Gorbunov
7b66a4d295 Remove links to contract samples as these samples are not supported by Dokka 2018-09-26 18:15:52 +03:00
Ilya Gorbunov
b2b23ac282 Improve contract API documentation 2018-09-26 18:15:52 +03:00
Ilya Gorbunov
f2a51f96a5 Improve documentation of experimental annotations 2018-09-26 18:15:52 +03:00
Ilya Gorbunov
04f1f6086b Fix doc build script after removing taks distJar from stdlib project 2018-09-26 18:15:52 +03:00
Mikhael Bogdanov
29568d2f48 Add test configuration for JDK_11 2018-09-26 17:05:55 +02:00
Mikhail Zarechenskiy
d0ed76ebc8 183: Fix exception about unmapped lambda argument from IDE inspection
Intention: obtain lambda argument for some parent call,
 then get that call (for the lambda argument) and map
 the argument to the parameter.

 Before the fix, we were getting call for inner element,
 not for the lambda argument and as a result, there were exceptions.

 #KT-26873 Fixed
2018-09-26 18:03:34 +03:00
Alexey Sedunov
c1b3e72ae8 Gradle: Inherit project SDK when no explicit one is specified
#KT-27145 Fixed
2018-09-26 16:59:46 +03:00
Vyacheslav Gerasimov
60758b86ee as33: Delete unnecessary bunch for itellij-sdk build.gradle.kts 2018-09-26 16:19:09 +03:00
Vyacheslav Gerasimov
666b660f79 Restore noDefaultJar() in kotlin-compiler project 2018-09-26 16:19:09 +03:00
Vyacheslav Gerasimov
1f0e9f24c5 Fix noDefaultJar helper for gradle 4.10
artifacts don't implement ArchivePublishArtifact in gradle 4.10
2018-09-26 16:19:09 +03:00
Vyacheslav Gerasimov
1109b795da Build: upgrade gradle to 4.10 2018-09-26 16:19:09 +03:00
Vyacheslav Gerasimov
8338a0dd85 Build: upgrade gradle to 4.9 2018-09-26 16:19:09 +03:00
Vyacheslav Gerasimov
10810aa90f Build: upgrade gradle to 4.8, fix ivy artifacts publication
Fix kotlin gradle plugin compilation against gradle 4.8 api
Internal ivy artifacts api has been changed, there is no longer DefaultIvyArtifact
2018-09-26 16:19:09 +03:00
Sergey Igushkin
44f87e4951 Revert "(minor) Transform KotlinPlatformType attribute to String, rename entries"
This reverts commit 3f24f8bd
2018-09-26 15:58:14 +03:00
Sergey Igushkin
8d054ba346 Revert "Build source sets hierarchy in Android projects"
This reverts commit 269410d7

The change causes errors in AS 3.2 import.
2018-09-26 15:58:14 +03:00
Ilya Matveev
3f452b2af2 Fix native test working directory 2018-09-26 15:49:47 +03:00
Ilya Matveev
6741a550d9 Add implementation dependencies into publication for native 2018-09-26 15:49:47 +03:00
Ilya Matveev
ac24bb0433 Update Kotlin/Native: 0.9.2 2018-09-26 15:49:47 +03:00
Ilya Matveev
da1fcb008b Fix -Xcommon-sources in native args 2018-09-26 15:49:47 +03:00
Mikhail Glukhikh
a97f2bb992 Introduce MPP wizard for mobile (Android / iOS) applications
This mobile wizard already contains skeleton
Finally #KT-25952 Fixed
Also #KT-26786 Fixed
2018-09-26 15:41:24 +03:00
Pavel V. Talanov
a258908fbb Create ModuleInfos for newmpp modules with missing roots accurately
#KT-27010 Fixed
 #KT-27133 Fixed
2018-09-26 13:46:45 +02:00
Pavel V. Talanov
cc1be5f559 Introduce SourceType and use KotlinFacetSettings.isTestModule
Refactor dealing with production/test roots
Remove ad-hoc code in KotlinMultiplatformRunLocationsProvider
2018-09-26 13:46:45 +02:00
Nikolay Krasko
1be491504a Fix formatting for when with subjects (KT-27027)
#KT-27027 Fixed
2018-09-26 13:35:36 +03:00
Nikolay Krasko
0833f23d02 Make ReplaceWith work for objects (KT-16211, KT-14929)
#KT-16211 Fixed
2018-09-26 13:35:35 +03:00
Nikolay Krasko
18c181641f Return updated element after reference shortening
Fresh new expression obtained after qualified expression binding is
invalidated after shortening.
2018-09-26 13:35:34 +03:00
Sergey Igushkin
c4283de9cb Mark deprecated Gradle configurations with the Kotlin platform attribute
The traditional Gradle/Java model assumes several configurations, which
are now deprecated, which are both `canBeConsumed = true` and
`canBeResolved = true`.

* compile, testCompile, etc.
* runtime, testRuntime, etc.
* default

These configurations need to somehow resolve correctly to an appropriate
platform-specific artifact when they contain an MPP library or project
dependency.

However, simply marking them with the Kotlin platform type attribute
would put these configurations under considerations during Gradle
variant aware depdendency resolution of project dependencies, which
in order would lead to ambiguity (e.g. `compile` vs `runtime` vs
`testCompile` vs ... vs `apiElements`).

To deprioritize these configurations during dependency resolution, we
mark them with a special attribute with a unique value in each project.
Given that the values are different in different projects, Gradle will
not choose a configuration marked by this attribute.

But we still need 'project(path: '...', configuration: '...')`
dependencies to work, and so, instead of rejecting those different
values of the attribute, we say that all values are compatible, but
when an ambiguity arises, choose the configurations not marked by this
attribute, so effectively eliminating them from resolution.

Issue #KT-27111 Fixed
2018-09-26 13:02:32 +03:00
Sergey Igushkin
3f24f8bd8d (minor) Transform KotlinPlatformType attribute to String, rename entries
* To avoid unexpected effects from the Gradle instantiation mechanisms
  for attribute values, use a safer String attribute type for the
  KotlinPlatformType attribute

* Rename its entries to keep enum entries naming consistent
2018-09-26 13:02:32 +03:00
Sergey Igushkin
65e3559c09 Fix resources processing configuration
* Add resources processing to the K/N compilations

* Use a proper resources output path (composed from target + compilation
  rather than just compilation name)

* Fix incorrect reassignment of the resources directory
2018-09-26 13:02:32 +03:00
Sergey Igushkin
fef61eca51 Add tests for variant-aware dependency resolution between projects 2018-09-26 13:02:32 +03:00
Sergey Igushkin
81ae54c05b Show warnings for disabled targets on current host
Issue #KT-26647 Fixed
2018-09-26 13:02:32 +03:00
Sergey Igushkin
4f650bb056 Add an experimental feature warnings on MPP usage & metadata publishing
Issue #KT-25200 Fixed
2018-09-26 13:02:31 +03:00
Sergey Igushkin
54988932a3 Ensure that kapt configurations are not exposed for consumption 2018-09-26 13:02:31 +03:00
Sergey Igushkin
7c05f77cb7 Add tools for testing dependencies resolution by resolving all configs 2018-09-26 13:02:31 +03:00
Sergey Igushkin
c3dd24e9b2 Rewrite project dependencies when publishing a multimodule MPP
When a new MPP is published without Gradle metadata, the project
dependencies should be replaced with specific module dependencies,
e.g. `sample-lib` with `sample-lib-jvm`, because a consumer won't be
able to resolve `sample-lib` in a variant-aware way.
2018-09-26 13:02:31 +03:00
Sergey Igushkin
05301e37d8 Fallback for publishing with no Gradle metadata
The following parts of the publications are affected:

* root publication
  * with Gradle metadata, it is published and references the
    other publications using the `available-at` mechanism
  * without metadata opt-in, it is not published

* Kotlin metadata variant
  * with Gradle metadata, it is added as an additional variant to the
    platform-specific publications to allow the IDE to discover it
  * without metadata opt-in, it is added as a dependency to the platform-
    specific modules (like in old MPP)
2018-09-26 13:02:31 +03:00
Sergey Igushkin
b388f7fde0 Introduce Kotlin variants with metadata variant and metadata dependency
These two will be needed when we publish a platform-specific part of a
MPP library in order to help the consumers of that single module
(rather than the whole MPP library) find the Kotlin metadata.

`KotlinVariantWithMetadataVariant` will be used for publishing with
Gradle metadata enabled, `KotlinVariantWithMetadataDependency` for
publishing without Gradle metadata, instead adding the Kotlin metadata
as a dependency, just like we did in old MPP.
2018-09-26 13:02:31 +03:00
Sergey Igushkin
1abcfc76df Add Kotlin-specific Usage attribute values
When a non-Kotlin (JVM) project resolves an MPP library dependency,
it expects only one variant per Java Usage value ('java-api',
'java-runtime-jars'). If there's more than one, it will report
ambiguity and fail.

So we need to avoid creating non-JVM variants with Java Usage values
to ensure that non-Kotlin consumers can resolve the dependencies on
an MPP library with a single JVM target (if there's more than one
JVM target, there will still be ambiguity, but that's quite what one
would expect and what can be solved with custom attributes).

Instead, we define two Kotlin-specific Usage values, 'kotlin-api' and
'kotlin-runtime', so that:

* input configurations with these Usage values can consume plain Java
  artifacts, for compatibility with plain old Kotlin modules

* if a consumer does not request a Kotlin usage and receives the two,
  let it use the runtime one as it is more complete

We then use the two Usage values on those Kotlin input and output
configurations which are not JVM-related, and leave the Java Usages
for the JVM targets.
2018-09-26 13:02:31 +03:00
Sergey Igushkin
76b51b1058 Allow the common platform type consumers to consume platform artifacts
When a Kotlin metadata input configuration tries to resolve a module
with no Kotlin metadata (such as: plain old Maven module, a non-MPP
Kotlin project with a single platform), it should be able to resolve
successfully.

Given that the input metadata configurations extend from source set
dependencies configurations, where platform-specific dependencies may
occur, allowing the metadata configuration to resolve such dependencies
into platform artifacts seems to achieve successful dependency
resolution.

Issue #KT-26834 Fixed
2018-09-26 13:02:31 +03:00
Sergey Igushkin
269410d7aa Build source sets hierarchy in Android projects
Instead of simply adding all Kotlin source sets participating in an
Android compilation, as was appropriate until we introduced the
dependsOn relation, we should now build a proper source sets hierarchy.
2018-09-26 13:02:30 +03:00
Ilya Chernikov
43a4b84b44 Make script resolving annotations repeatable, fix multiple repos usage
Also avoid "unknown resolver central" errors on ivy resolving
#KT-27050 fixed
2018-09-26 11:49:45 +02:00
Mikhail Zarechenskiy
0d103e7f0c Allow using extensions with trivial-constraints in builder-inference
#KT-27079 Fixed
2018-09-26 11:52:23 +03:00
Mikhail Zarechenskiy
0da1b9b80f Revert "Migration change: temporarily specify type explicitly"
This reverts commit bc6e091004.

 This commit was needed to avoid bootstraping, now we can revert it
2018-09-26 11:51:57 +03:00
Mikhail Zarechenskiy
7c1d374ed5 Fix diagnostic tests about coroutine-inference 2018-09-26 11:51:55 +03:00
Alexander Podkhalyuzin
3142627269 Removed extra spaces in new MPP project template
#KT-26952  Fixed
2018-09-26 10:21:10 +03:00
Toshiaki Kameyama
c1013cc198 "Convert to secondary constructor": Fix false positive with delegation #KT-27061 Fixed 2018-09-26 09:31:12 +03:00
Yuki Miida
af1fc5b668 Add sample for orEmpty method 2018-09-26 05:54:40 +03:00
Mikhail Glukhikh
64b23812c0 Move CliArgumentStringBuilder: cli -> idea-jvm 2018-09-25 19:14:12 +03:00
Mikhail Glukhikh
1f4d91da1c Has actual marker: distinguish Android and JVM modules #KT-25055 Fixed 2018-09-25 19:11:30 +03:00
Dmitry Petrov
fd57a43665 Update testData for ClassFileToSourceStubConverterTestGenerated 2018-09-25 17:25:02 +03:00
Simon Ogorodnik
189fe95d8a Fix type-aliases by expansion search loop
Compare type-aliases by it's fqNames instead of identity, as
multiple runs of resolveToDescriptorIfAny produces different descriptors
for one declaration
2018-09-25 16:40:03 +03:00
Nikolay Krasko
1ff12d00e4 Allow return value hint for lambda expressions (KT-26689)
#KT-26689 Fixed
2018-09-25 15:52:22 +03:00
Nikolay Krasko
07e305e5f4 Update dictionary: +infos, -kompiler 2018-09-25 15:52:21 +03:00
Nikolay Krasko
80c3e59dd5 Minor: cleanup testUtils.kt 2018-09-25 15:52:19 +03:00
Nikolay Krasko
e1f746f23c Resolve "key is not found in bundle" exception from tests in AS
Android Studio idea.jar is taken from clion projects and has
IdeSpecificFeatures.xml and ProductivityFeaturesRegistry.xml files that
mention function that have to be found in ProductivityFeaturesRegistry.

Unfortunately, correspondent CLion bundle is not registered in tests, and
this causes a lot of tests fail.
2018-09-25 15:52:18 +03:00
Ilya Chernikov
127451e1d9 Add kotlin-main-kts.jar to the dist 2018-09-25 14:13:28 +02:00
Alexey Sedunov
22c77ffbb2 MPP: Do not populate content roots in the absence of ExternalProject
#KT-26900 Fixed
2018-09-25 15:05:46 +03:00
Alexey Sedunov
4f01a438c4 MPP: Add all android-targeted compilation source roots to the module 2018-09-25 15:05:43 +03:00
Alexey Sedunov
3a973973ce MPP: Create android source roots automatically when requested
#KT-26764 Fixed
2018-09-25 14:54:27 +03:00
Alexey Sedunov
391e4c2ad1 Configuration: Fix JVM target detection in the absence of Kotlin facet
#KT-27021 Fixed
2018-09-25 14:54:26 +03:00
Alexey Sedunov
bd3adbd457 MPP: Reset JDK for JVM modules
#KT-26937 Fixed
2018-09-25 14:54:26 +03:00
Alexey Sedunov
6d4f927f7e Configuraion: Defer initialization of facets UI
#KT-25410 Fixed
2018-09-25 14:54:25 +03:00
Dmitriy Dolovov
5e33860652 [K/N] Stand-alone Native Application wizard in IDEA
Issue #KT-27076 Fixed
2018-09-25 17:24:59 +07:00
Dmitriy Dolovov
8e455f5a14 Merge pull request #1893 from JetBrains/rr/ddol/KT-27072
[K/N] Friendly displaying of Kotlin/Native default libraries in IDEA
2018-09-25 16:03:28 +07:00
Toshiaki Kameyama
7d89205618 Add "Remove inline modifier" quick fix for NOTHING_TO_INLINE #KT-5187 Fixed 2018-09-25 11:48:20 +03:00
Toshiaki Kameyama
65f23f3c4e Fix false positive in class literal #KT-16338 Fixed 2018-09-25 11:27:27 +03:00
Toshiaki Kameyama
6cd13341ee Add inspection for unlabeled return inside lambda #KT-26511 Fixed 2018-09-25 11:24:56 +03:00
Dmitry Petrov
ba32ed7404 Test: @JvmField in inline class companion 2018-09-25 11:15:29 +03:00
Dmitry Petrov
bffe9e45e8 Add accessor tests: inline class <-> companion
KT-26858 was fixed somewhere in the middle.

 #KT26858
2018-09-25 11:15:29 +03:00
Dmitry Petrov
850d72f13f Fix accessor generation for inline class members
TODO 'generateMethodCallTo' is a bloody mess that deserves rewriting.
2018-09-25 11:15:29 +03:00
Dmitry Petrov
edc8cf3ed0 Use proper type for context 'this'
Bug in 'generateThisOrOuterFromContext', it worked while instance of a
class was always an object.

 #KT-27078
2018-09-25 11:15:29 +03:00
Dmitry Petrov
c1bb3479df More tests on casts on receiver of inline class type 2018-09-25 11:15:29 +03:00
Dmitry Petrov
88cc900dc7 Add test for private inline class method call from inline lambda 2018-09-25 11:15:29 +03:00
Dmitry Petrov
2e6d53a43f Fix extension receiver coercion for inline classes
#KT-27031
2018-09-25 11:15:29 +03:00
Dmitry Petrov
20d7210239 Fix outer class mapping for closures in inline class
#KT-27030
 #KT-27033
2018-09-25 11:15:29 +03:00
Dmitry Petrov
26602c8443 Minor: move tests 2018-09-25 11:15:29 +03:00
Dmitry Petrov
f9a419f940 Fix companion method access from inline class
#KT-27025
2018-09-25 11:15:29 +03:00
Dmitry Petrov
1869ed09bc Fix companion field access from inline class
#KT-26858
2018-09-25 11:15:29 +03:00
Toshiaki Kameyama
3e4d8eba76 Add braces: Remove new line between '}' and 'else' #KT-26839 Fixed 2018-09-25 11:08:49 +03:00
Alexey Tsvetkov
de261df6f5 Use separate configuration for resolving native compiler plugin artifacts
Kotlin/JVM and Kotlin/JS use shaded compiler, but
Kotlin/Native uses non-shaded one.
Serialization plugin was configured to use either shaded or non-shaded
plugin version, because we used one configuration for resolving
compiler plugins.
This change introduces 'kotlinNativeCompilerPluginClasspath' configuration
for resolving Kotlin/Native compiler plugins.
2018-09-25 11:08:39 +03:00
Toshiaki Kameyama
affa881421 "Redundant SAM constructor": Fix highlighting range #KT-27034 Fixed 2018-09-25 11:06:45 +03:00
Dmitriy Dolovov
405bd91597 [K/N] User friendly displaying of Kotlin/Native default libraries in IDEA
Issue #KT-27072 Fixed
2018-09-25 11:50:39 +07:00
Georgy Bronnikov
487f500f85 Revert "JVM_IR. Support compile time constants"
This reverts commit 055215c54f.
2018-09-25 05:24:48 +03:00
Georgy Bronnikov
055215c54f JVM_IR. Support compile time constants 2018-09-25 01:38:51 +03:00
Pavel V. Talanov
985934a40a Prefer kotlin JUnit config to any pattern based config
Specifically that means that Kotlin JUnit configurations will be created
    for JUnit classes and methods instead of AS pattern configurations
2018-09-24 18:29:04 +02:00
Pavel V. Talanov
71d640f3f8 Improve kotlin jvm run config producers for 181 and as32 branches
Drop KotlinJUnitRunConfigurationProducer, KotlinRunConfigurationProducer
    bunch files
Extract differences in behaviour to 'jvmMppUtils.kt'
Improve 'isConfigurationFromContext' checks for 181 and as32
    (this prevents duplicate configurations being created)
KotlinRunConfigurationProducer chooses corresponding jvm module
    for common code

 #KT-26886 Fixed
2018-09-24 18:08:06 +02:00
Pavel V. Talanov
f34f306d90 IdeaModuleInfos: consider newMpp modules to always have relevant roots
Make sure implementing(ed)Descriptors always return a relevant module
    regardless of whether the module has physical directories configured
2018-09-24 18:08:06 +02:00
Vyacheslav Gerasimov
7eb8123d26 Add changelog for 1.2.71 2018-09-24 18:37:39 +03:00
Nikolay Krasko
dda1673096 Don't choose navigation target only by index (KT-26004)
There might be situation when platform code has a declaration with
another signature and the same fqname, but navigating to common
declaration is expected.

 #KT-26004 Fixed
2018-09-24 18:26:34 +03:00
Svyatoslav Kuzmich
b79dcbe8e6 [JS IR BE] Refactor equals and compareTo lowering 2018-09-24 18:21:57 +03:00
Yan Zhulanow
005955326f Pill: Exclude kotlin-main-kts module from JPS 2018-09-24 17:54:24 +03:00
Yan Zhulanow
ff0b051a64 MPP: Rewrite work-around for JPS in a more safe way 2018-09-24 17:54:24 +03:00
Yan Zhulanow
bc27cabb1a Call 'GradleProjectImportHandler's in MPP Gradle importer (KT-27006) 2018-09-24 17:54:23 +03:00
Nikolay Krasko
bbd15db308 Remove old buildIterator import (KT-26679) 2018-09-24 15:57:06 +03:00
Mikhail Zarechenskiy
6a860dd042 Fix blackbox codegen tests that use coroutine inference
Note that previously we implicitly ignored JS_IR backend when directive
 COMMON_COROUTINES_TEST was enabled, see kotlin/generators/util/coroutines.kt#L57
2018-09-24 12:10:56 +03:00
Ilya Gorbunov
974837654e Remove workaround for complex default value in Array.copyInto
#KT-22818
2018-09-22 18:24:00 +03:00
Ilya Gorbunov
a5f1ed9a5d Advance bootstrap to 1.3.20-dev-384 2018-09-22 18:23:52 +03:00
Alexey Tsvetkov
cd2ff41ef5 Validate Gradle task properties on test run
By default `validateTaskProperties` is added only to `check` task's
dependencies, so doesn't run on our CI.
We can run `check` instead of `test` on CI, but since developers are
not used to it, I believe it's better to make `test` tasks depend on
`validateTaskProperties`
2018-09-22 00:10:45 +03:00
Natalia Selezneva
a078526c4d Scratch tests: check that highlighting is enabled for scratch 2018-09-21 22:58:14 +03:00
Natalia Selezneva
8f8c431524 Fix Optimize import for scripts not under source roots
KT-17231 Fixed
KT-21981 Fixed
2018-09-21 22:58:14 +03:00
Natalia Selezneva
eb597fbf22 Fix unused import inspection for scripts not under source roots (including build.gradle.kts and scratches)
KT-20040 Fixed
2018-09-21 22:58:14 +03:00
Natalia Selezneva
43027d0581 Check scriptDefinition expected location for scripts when use ProjectRootUtil.isInContent 2018-09-21 22:58:14 +03:00
Natalia Selezneva
074aa47dc0 Use ProjectRootUtil.isInContent instead of checking script expected location manually 2018-09-21 22:58:14 +03:00
Natalia Selezneva
d3ee14c5d2 Check scriptDefinition expected location for scripts when use ProjectRootUtil.isInContent 2018-09-21 22:58:06 +03:00
Ivan Gavrilovic
2d425d4e0a Fix null checks in the flow 2018-09-21 20:23:44 +03:00
Ivan Gavrilovic
bb53a1c3d2 Use new API from AGP to get JavaCompile task
New API for getting the JavaCompile task has been
added to AGP, and the old one is deprecated. It is
now returning TaskProvider<JavaCompile>, which allows
API users to avoid configuring tasks unnecessarily.

This commit does not change anything functionally, it
is only to avoid the warning message, as reporter in
https://issuetracker.google.com/116198439.
2018-09-21 20:23:44 +03:00
Ilya Gorbunov
358e64fdb0 Remove dead code for builtins uninvalidation in tests 2018-09-21 18:35:02 +03:00
Ilya Gorbunov
4423ef9087 Minor: remove unused template for Map.random() 2018-09-21 18:28:44 +03:00
Anton Bannykh
8e347f9f39 [JS IR BE] lateinit support
* Functions with IrExpressionBody are lowered to IrBlockBody
* Implemented throwUninitializedPropertyAccessException function
2018-09-21 18:20:11 +03:00
Anton Bannykh
beaf6df8c5 [JS IR BE] support CharSequence and String methods 2018-09-21 18:16:03 +03:00
Alexander Udalov
3e90d367f2 Do not report experimental usage errors in import statements
#KT-25545 Fixed
2018-09-21 17:35:50 +03:00
Alexander Udalov
9d27771f86 Fix instance parameter type of inherited declaration in reflection
Both for callables obtained via reflection API (KClass.members etc) and
for callables obtained via ::-references, the instance parameter is now
the class which was used to construct the type at the left-hand side of
the reference, NOT the class where the callable is originally declared
as is known at compile-time. The reason is to reduce the difference in
behavior of KCallable.call vs FunctionN.invoke: the latter always
required the subclass instance for a fake override, and it's reasonable
that the former would require it as well.

Note that in Java reflection, behavior could differ in a similar case.
For a simple fake override, Class.getMethod would return the method
declared in the base class and that method will accept instances of the
base class in invoke. However, it's difficult to rely on this behavior
because if there's a bridge for a fake override in the derived class
(e.g. when overridden members have different signatures), the returned
Method object is accepting the derived class as the receiver. This just
confirms the fact that Java reflection operates on a different level of
abstraction, namely JVM methods in .class files, which is not applicable
to our use cases directly. Another reason not to replicate Java
reflection's behavior is the uncertainty as to which member is returned
in case there are several in the hierarchy for a given fake override:
see the "otherwise one of the methods is chosen arbitrarily" note in
javadoc on Class.getMethod.

 #KT-24170 Fixed
2018-09-21 17:32:43 +03:00
Alexander Udalov
3ca81b95c2 Use non-allowed actual defaults in backends to workaround compiler exception
It's difficult to fix KT-22818 until the IR comes along, so we're
providing a workaround where one can disable the
ACTUAL_FUNCTION_WITH_DEFAULT_ARGUMENTS error and provide default values
in the actual function, to avoid exception from the backend.

 #KT-22818
2018-09-21 17:30:05 +03:00
Ilya Chernikov
18b53f331a Fix proguarding of the main-kts 2018-09-21 15:12:53 +02:00
Simon Ogorodnik
68dfe9bf14 Fix missing NativeLibraryType
#KT-27009 fixed
2018-09-21 15:32:56 +03:00
Simon Ogorodnik
3aee3dfdd9 Remove JPS KotlinNativeConfigurator 2018-09-21 15:32:55 +03:00
Simon Ogorodnik
9a79254f7e Make possible to have no libraryDescription for 'Configure Kotlin' 2018-09-21 15:32:54 +03:00
Simon Ogorodnik
faf09a2aac Add KotlinNativeGradleConfigurator to avoid 'Configure Kotlin' for K/N 2018-09-21 15:32:53 +03:00
Simon Ogorodnik
cff648a505 Don't show 'Configure Kotlin' panel when module already configured 2018-09-21 15:32:53 +03:00
Roman Artemev
a807397f65 [JS_IR] Add inlineBox tests 2018-09-21 14:02:53 +03:00
Alexander Podkhalyuzin
aa56c50218 Fixed update copyright action with no package and imports
#KT-23864 Fixed
2018-09-21 12:56:11 +03:00
Dmitry Petrov
d03237bebc Generate backing fields and initializers for external constants 2018-09-21 09:50:21 +03:00
Dmitry Petrov
ec8bdff5c7 Working infrastructure for external dependencies testing
(not really, but at least something)
2018-09-21 09:50:21 +03:00
Dmitry Petrov
6022fb4ec3 Fix default impl for suspend fun
We have an extra parameter in the mapped signature, and don't care about
Kotlin types there (so far). Might be a better idea to obtain the actual
descriptor for a suspend function (with extra parameter), and pass
arguments accordingly.
2018-09-21 09:48:11 +03:00
Dmitry Petrov
0f898dc6dc Fix default interface generic extension fun call with inline class type
When we've determined that we are going to invoke an erased inline class
method ('static foo-impl(this, ...)' in inline class), keep track of it
so that the remaining type mapping logic proceeds correctly.

 #KT-26998 Fixed Target versions 1.3.20
2018-09-21 09:48:11 +03:00
Dmitry Petrov
95010de32e Minor: renaming 2018-09-21 09:48:11 +03:00
Dmitry Petrov
8d2b1950e6 Fix Kotlin default interface methods calls for inline classes
When mapping callable method signature for erased inline class methods,
use original function descriptor instead of super declaration
(otherwise it would map to a default interface method with mismatching
signature).

When generating delegates to Kotlin default interface methods, keep
track of the original Kotlin types for delegating method arguments and
interface method arguments.

'original' for value parameters of fake overrides points to the
overridden function value parameters instead of the value parameter of
the unsubstituted function. This causes inconsistent type mapping for
inline classes implementing generic interfaces with default methods.

 #KT-25295 Fixed Target versions 1.3.20
 #KT-26931 Fixed Target versions 1.3.20
2018-09-21 09:48:11 +03:00
Dmitry Petrov
8536ef5b43 Minor: reformat 2018-09-21 09:48:11 +03:00
Dmitry Petrov
947ea88d5e Refactor: pull up and extract method 2018-09-21 09:48:11 +03:00
Dmitry Petrov
d9593c7a34 Add tests for inline class variables captured in closure 2018-09-21 09:48:11 +03:00
aleksZubakov
7e49005bab Add LazyTopDownAnalyzer in LazyResolve container 2018-09-20 22:24:07 +03:00
Ilya Gorbunov
0ca59b3a40 Use modern API of Kotlin 1.3 in JS canvas examples 2018-09-20 22:08:56 +03:00
Roman Artemev
24e7bafa7d Port test from K/N 2018-09-20 19:59:12 +03:00
Ilya Matveev
a6f2af03e7 Pass absolute library paths to native compiler 2018-09-20 19:10:27 +03:00
Mikhail Zarechenskiy
09cd038e4b Fix test about version requirement
We began to write version requirement on declarations with `Result` and
 now (after bootstrap) we are getting error in this test because of that
 version requirement.

 see 908be10bf4
2018-09-20 17:58:56 +03:00
Mikhail Zarechenskiy
a4f5cced47 Support coroutine inference under version <= 1.2
Follow-up #KT-26958
2018-09-20 17:42:24 +03:00
Mikhail Glukhikh
de36d919aa Fix testJvmStaticUsagesRuntime from PSI checker, messages updated to 1.3 2018-09-20 17:28:07 +03:00
Mikhail Glukhikh
83faba6424 MPP wizard: add skeleton for shared JVM/JS/iOS project
Part of KT-26786
2018-09-20 16:21:43 +03:00
Mikhail Glukhikh
47baaf10c6 MPP wizard: add skeleton for JVM/JS project
Part of KT-26786
2018-09-20 16:21:26 +03:00
Mikhail Glukhikh
625ff00f62 Fix testEnableCoroutinesFacet from update configuration group 2018-09-20 16:19:10 +03:00
Mikhail Glukhikh
6850d7be0c Enable feature: add test for JPS case 2018-09-20 16:19:03 +03:00
Mikhail Glukhikh
c5a81c4e8b Extract shouldConfigureInProject to AbstractChangeFeatureSupportLevelFix 2018-09-20 16:18:06 +03:00
Mikhail Glukhikh
7030a485be Enable / disable feature: update Gradle build script bunch for 173 2018-09-20 16:18:05 +03:00
Mikhail Glukhikh
f6b805a973 Add enable / disable feature in JPS
#KT-26775 Fixed
#KT-26774 Fixed
2018-09-20 15:56:37 +03:00
Mikhail Glukhikh
8a7ff4cd24 Add enable / disable feature in Maven project
Part of KT-26775
2018-09-20 15:56:32 +03:00
Mikhail Glukhikh
106db57975 Add enable / disable feature in Gradle (Kotlin DSL) project
Part of KT-26775
2018-09-20 15:56:31 +03:00
Mikhail Glukhikh
43e4616fdf Add enable / disable feature in Gradle (Groovy) project, forTests option
Part of KT-26775
2018-09-20 15:56:29 +03:00
Mikhail Glukhikh
b194be7665 Introduce skeleton for ChangeGeneralLanguageFeatureSupportFix
Part of KT-26775 and KT-26774
2018-09-20 15:56:27 +03:00
Mikhail Glukhikh
fd3dfe0710 Extract AbstractChangeFeature...Fix from ChangeCoroutineSupportFix
Part of KT-26775 implementation
2018-09-20 15:56:26 +03:00
Mikhail Glukhikh
125a136663 Delete unnecessary bunches for KotlinMavenConfigurator
One private fun (instead of public) is the only difference here
2018-09-20 15:56:25 +03:00
Mikhail Glukhikh
a0ae4dd387 Fix Maven enable coroutines test (language version) 2018-09-20 15:56:23 +03:00
Ilya Chernikov
a6c7f4294c Annotate DiscoverScriptExtensionsTask properly
KT-26978 fixed
2018-09-20 09:44:58 +02:00
Yan Zhulanow
1008adaf02 Do not discover script extensions for Kapt stub generation tasks (KT-26974) 2018-09-19 22:50:31 +03:00
Ilmir Usmanov
7b1c564b87 Replace ALOAD 0 with fake continuation if suspension point is default
method

 #KT-25922 Fixed
 #KT-26608 Fixed
 #KT-26658 Fixed
2018-09-19 22:14:29 +03:00
Pavel V. Talanov
85bdb8b787 Do not show run gutters for native
#KT-26851 Fixed
2018-09-19 19:25:24 +02:00
Anton Bannykh
06ecca4144 [JS IR BE] unsigned literal support 2018-09-19 17:45:07 +03:00
Nikolay Krasko
9f16e4f709 Report jre deprecated warning when version is set implicitly (KT-26933)
#KT-26933 Fixed
2018-09-19 17:31:10 +03:00
Toshiaki Kameyama
3f2c73b4a9 if-then to safe access: fix for qualified 'this' condition #KT-26662 Fixed 2018-09-19 16:16:15 +03:00
Toshiaki Kameyama
b5f73ebd0f if-then to safe access: report even if condition in parentheses #KT-26662 Fixed 2018-09-19 16:16:15 +03:00
kenji tomita
6d9fb4f382 Fix #KT-26902 Bad quickfix name for "Call on non-null type may be reduced" 2018-09-19 15:56:26 +03:00
Stanislav Erokhin
4ca0c60066 Temporary specify type explicitly for sequence method in debugger tests. 2018-09-19 15:46:24 +03:00
Stanislav Erokhin
95633b6027 Advance bootstrap to 1.3.20-dev-258 2018-09-19 15:46:22 +03:00
Anton Bannykh
6736987239 JS: fix unsigned literal inlining 2018-09-19 15:04:36 +03:00
Dmitry Petrov
7ff72e9d90 Fix inline class recursion through type parameters
Note that inline class such as
  inline class Id<T>(val x: T)
is prohibited in 1.3.0.
2018-09-19 14:51:50 +03:00
Anton Bannykh
66b5dd92d9 JS: fix line number data 2018-09-19 13:57:43 +03:00
Mikhael Bogdanov
1face1c334 Don't generate annotations on synthetic accessor parameters 2018-09-19 12:14:09 +02:00
Mikhael Bogdanov
38652372ce Generate private constructors for Enums
#KT-2680 Fixed
  #KT-16867 Fixed
2018-09-19 12:14:08 +02:00
Mikhael Bogdanov
c753a98d02 Use section constants to generate smap data 2018-09-19 12:14:07 +02:00
Mikhael Bogdanov
a789fd92fe Properly parse smap information
#KT-23369 Fixed
2018-09-19 12:14:07 +02:00
Ilya Gorbunov
86ba5ebf29 Mix kotlin-annotations-jvm with kotlin-reflect into proguard
So it can strip these annotations from the resulting jar.

#KT-26929 Fixed
2018-09-19 12:40:47 +03:00
Nikolay Krasko
64d2cdf0c2 Migrate for moved and renamed buildSequence/buildIterator (KT-26679)
#KT-26679 Fixed
2018-09-19 12:38:35 +03:00
Nikolay Krasko
082801efb4 Refactoring: move each problem to a separate class 2018-09-19 12:38:33 +03:00
Mikhail Zarechenskiy
86141be61f Add inference annotations to the dumped declarations 2018-09-18 23:28:54 +03:00
Alexander Udalov
8c01cd48a5 Report warning instead of error on usages of Experimental/UseExperimental
#KT-26936 Fixed
2018-09-18 22:50:26 +03:00
Ilya Gorbunov
1d7ee22bdc Simplify comparisons for small unsigned types that can fit in Int
UByte and UShort can be extended to Int exactly and then compared as ints
2018-09-18 22:25:36 +03:00
Ilya Gorbunov
af29dced98 Make overridden compareTo in unsigned types inline only 2018-09-18 22:25:36 +03:00
Ilya Gorbunov
9e0708e85a Make most of unsigned operations inline only 2018-09-18 22:25:36 +03:00
Ilya Gorbunov
d793221a7b Extract unsigned type related extensions to separate classes
- Rename class with unsigned number to string conversions to UStringsKt
- Extract Random unsigned extensions to URandomKt
2018-09-18 22:25:36 +03:00
Ilya Matveev
b469afdfcb Use argument file to run Kotlin/Native compiler 2018-09-18 21:39:44 +03:00
Ilya Matveev
7d6adbd088 Serialize native compiler args 2018-09-18 21:39:44 +03:00
Ilmir Usmanov
5dea245a37 Fix linenumbers written to debug metadata
#KT-26848 Fixed
2018-09-18 20:06:25 +03:00
Ilya Chernikov
c0f4933356 Make ivy resolver quiet 2018-09-18 18:39:30 +02:00
Mikhail Zarechenskiy
d7f2eeb6e8 Add BuildInference annotation onto stdlib coroutine builders 2018-09-18 18:55:26 +03:00
Mikhail Zarechenskiy
bc6e091004 Migration change: temporarily specify type explicitly
Because of introduction of `BuilderInference` annotation.
 Change it back after bootstrap
2018-09-18 18:55:26 +03:00
Mikhail Zarechenskiy
a293aded5d Introduce builder-like inference with an explicit opt-in for it
- Add marker for the experimental type inference features
 - Add annotation that will control builder-like inference
 - Require that annotation on corresponding parameters and extensions
 - Allow to use builder inference without suspendability

 Changes in tests and refactorings (rename mainly) are going to be
 introduced in further commits
2018-09-18 18:55:25 +03:00
Mikhail Zarechenskiy
5e9b31ca2c Minor: invert logic of function 2018-09-18 18:55:25 +03:00
Vyacheslav Gerasimov
5229ed0217 Add compatibility artifact with Mutable and ReadOnly annotations into dist
#KT-26916 Fixed
2018-09-18 18:52:32 +03:00
Denis Zharkov
ed7dd6fccb Minor. Move serialization annotation fq-names to IDE light-classes
They are a kind of a hack applied in light-classes and it'd be nice
to prevent them being used in irrelevant contexts

kotlin-serialization-compiler module should not depend on idea,
thus we can't use annotations directly there.

So, we copy-paste them and add a test on names consistency
2018-09-18 18:37:11 +03:00
Nikolay Krasko
b31de355db Fix compilation error in MavenMigrateTest.kt 2018-09-18 18:12:58 +03:00
Simon Ogorodnik
818171108e [K/N] Hack to enable exporting interop libraries 2018-09-18 17:54:57 +03:00
Dmitriy Dolovov
ab07377200 [K/N] Fix: Obsolete text stubs after updating K/N library
Issue #KT-26736 Fixed
2018-09-18 17:43:20 +03:00
Dmitriy Dolovov
db418123d4 [K/N] Proper invalidation of metadata cache in IDEA by VFS events 2018-09-18 17:43:19 +03:00
Simon Ogorodnik
35a0b42796 Support forward declarations for Native via hack-ing into built-ins 2018-09-18 17:43:15 +03:00
Simon Ogorodnik
69f5cf7095 Create Native specific LibraryInfo
This LibraryInfo contains KonanLibrary and provides correct
capabilities to ModuleDescriptor
2018-09-18 17:41:39 +03:00
Simon Ogorodnik
a2cdb14610 Add function to get typed capability from ModuleInfo 2018-09-18 17:33:10 +03:00
Simon Ogorodnik
d90cda65a1 Add factory function to create platform specific LibraryInfo's 2018-09-18 17:33:09 +03:00
Simon Ogorodnik
0cc3625dc1 Do not throw exception on not-found serialized class from knm 2018-09-18 17:33:08 +03:00
Simon Ogorodnik
ca742b1552 Support free-form .knm package part names 2018-09-18 17:33:07 +03:00
Simon Ogorodnik
7166c011bf Support for split-packages in Kotlin Native
See JetBrains/kotlin-native#2034
2018-09-18 17:33:06 +03:00
Ilya Matveev
a2c5c515de Support OptionalExpectation in native 2018-09-18 15:55:49 +03:00
Anton Bannykh
7d5a304cf6 [JS IR BE] support Char.rangeTo() 2018-09-18 15:43:55 +03:00
Roman Artemev
89bec8ec59 Update tests 2018-09-18 15:30:17 +03:00
Roman Artemev
084071e2e5 [JS IR BE] Fix callable reference lowering
* more precisely handle implicit receiver arguments
2018-09-18 14:59:21 +03:00
Ilmir Usmanov
14818a4fc1 Minor. Remove tests with suspend delegates 2018-09-18 14:56:11 +03:00
Ilmir Usmanov
c4038729ea Minor. Split tests with buildSequence into LV 1.2 and LV 1.3 versions 2018-09-18 14:56:08 +03:00
Nikolay Krasko
50deac7a26 Update test data in migration tests 2018-09-18 14:38:26 +03:00
Nikolay Krasko
6ef6fe4a47 Don't show migration dialog if no actual migrations are available (KT-26889)
#KT-26889 Fixed
2018-09-18 14:38:26 +03:00
Nikolay Krasko
11b948f004 Postpone migration till indexes are ready (KT-26428)
#KT-26428 Fixed
2018-09-18 14:38:26 +03:00
Anton Bannykh
0660e4d616 [JS IR BE] support multimodule tests 2018-09-18 14:36:20 +03:00
Anton Bannykh
2e709a81fa [JS IR BE] Arrays, varargs 2018-09-18 14:36:20 +03:00
Mikhail Glukhikh
e24f68c357 Remove erroneous suspend delegate tests (not supported in 1.3) 2018-09-18 12:00:12 +03:00
Mikhail Glukhikh
65ee837bfe Fix testAddArrayOfTypeForJavaAnnotation (named arguments in 1.3) 2018-09-18 11:50:48 +03:00
Mikhail Glukhikh
140c5d7689 Fix AddAnnotationTarget.testWithJava from multi-file quick fix 2018-09-18 11:50:47 +03:00
Mikhail Glukhikh
b7da2ad675 RedundantSamConstructor: remove reformatting in inspection visitor
This fixes testNestedInterface
2018-09-18 11:50:45 +03:00
Mikhail Glukhikh
6cb1ba9d41 Switch off ResultIsResultInspection as no more necessary for 1.3 2018-09-18 11:50:44 +03:00
Mikhail Glukhikh
94789c50b9 Do not suggest adding 'name =' before single vararg argument
This fixes two named argument intention tests
2018-09-18 11:50:43 +03:00
Mikhail Glukhikh
9694882db6 Fix testEnumClass (implementAsConstructorParameter) 2018-09-18 11:50:42 +03:00
Mikhail Glukhikh
b6c4bd270c Switch testCoroutineContext to release coroutines thus fixing it 2018-09-18 11:50:41 +03:00
Mikhail Glukhikh
2e2b15853e Suppress RESULT_CLASS_IN_RETURN_TYPE in ResultIsResultInspection tests
This fixes four relevant inspection tests
2018-09-18 11:50:40 +03:00
Mikhail Glukhikh
54e7fe6c52 Add language version 1.2 to mod-related inspection test thus fixing it
This does not work in 1.3 because mod is no more supported
2018-09-18 11:50:39 +03:00
Mikhail Glukhikh
2473362373 ArrayInDataClass test: replace Arrays functions with Kotlin ones
This fixes relevant inspection test
2018-09-18 11:50:38 +03:00
Mikhail Glukhikh
4a3af36909 Remove SHOULD_FAIL_WITH from testQuotesName thus fixing it 2018-09-18 11:50:37 +03:00
Mikhail Glukhikh
3014c3b33b Add new error from 1.3 into testIncorrectArgs thus fixing it 2018-09-18 11:50:36 +03:00
Mikhail Glukhikh
362ee126d1 Add language version 1.2 to quick-fix tests for companion in interface
In 1.3, companion members in interface can be annotated with JvmField,
so fix replacing JvmField with const is no more actual.
This fixes testCompanionInInterface.
2018-09-18 11:50:35 +03:00
Mikhail Glukhikh
81406a2bac Change .hashCode() to .bar() for some nullability fixes tests
Hash code can be no more used because in 1.3 we have nullable extension.
This fixes two wrap with safe let call tests and
one surround with null check test.
2018-09-18 11:50:34 +03:00
Mikhail Glukhikh
0f8b46b7d7 Add language version 1.2 to quick-fix tests for add explicit import
This fixes tests for KT-21515
2018-09-18 11:50:33 +03:00
Mikhail Glukhikh
39d28f1c92 AddAnnotationTargetTest: replace retention annotation if needed
This fixes testExpression3 from this test group
2018-09-18 11:50:32 +03:00
Mikhail Glukhikh
2bba4f5aa8 Fix two obsoleteCoroutines tests 2018-09-18 11:50:30 +03:00
Ilya Chernikov
7dd168d4ef [minor] remove dumping of the proguard config to the wrong file 2018-09-18 08:36:47 +02:00
Ilmir Usmanov
3bb405bee4 Minor. Move SUSPENSION_POINT_INSIDE_MONITOR to ErrorsJvm 2018-09-17 20:22:49 +03:00
Yan Zhulanow
139c582ce2 Minor: Fix missing 'ifEmpty()' 2018-09-17 20:08:28 +03:00
Yan Zhulanow
8db5fd4b9b Add missing empty bunches for AS 3.3 2018-09-17 20:08:27 +03:00
Yan Zhulanow
373ddcf55d Fix compatibility with JPS-standalone (KT-26777) 2018-09-17 20:08:27 +03:00
Yan Zhulanow
d5f203a978 Add a missing write action to KotlinNativeApplicationComponent 2018-09-17 20:08:27 +03:00
Yan Zhulanow
b38e9b6b05 Make all intellij-core dependencies non-transitive 2018-09-17 20:08:27 +03:00
Yan Zhulanow
39f5418c01 Update Android Studio 3.2 version 2018-09-17 20:08:27 +03:00
Ilmir Usmanov
35056543a2 Fix LVT entries of 'this' and parameters in coroutine code
#KT-24510 Fixed
2018-09-17 20:03:51 +03:00
Ilmir Usmanov
2dd5b8fa70 Forbid suspension points in critical sections
#KT-26480: Fixed
2018-09-17 19:29:51 +03:00
Denis Zharkov
a4b2e5964a Do not build dummy light classes for serialization-related classes
Otherwise, whether LazyLightClassMemberMatchingError happens
or other type of errors because serialization plugin expects
full resolution in the correct module

Currently, only @Serializable annotation leads to exceptions,
but just in case we consider both of them as potentially problematic

 #KT-26895 Fixed
2018-09-17 19:09:40 +03:00
Leonid Startsev
fe9ce45e1d Add initialization of constantValueGenerator for correct work
Exception was thrown from serialization plugin after compiler
refactoring
2018-09-17 19:07:10 +03:00
Ilya Gorbunov
cb47b0cde1 Fix sourcemap of stdlib/js to include new source sets 2018-09-17 17:58:28 +03:00
Ilya Gorbunov
f4af656e20 Remove entire stdlib opt-in for unsigned types to control precisely where they are exposed 2018-09-17 17:58:27 +03:00
Dmitry Petrov
97999a6415 Update testData for public API tests
Internal constructors for UIntProgression and ULongProgression are now
correctly detected as non-public API (because of proper metadata).
2018-09-17 17:28:52 +03:00
Mikhail Zarechenskiy
ea69d26bac Don't throw exception on error types in light classes mode
#KT-26829 Fixed
 #KT-26827 Fixed
2018-09-17 16:21:07 +03:00
Mikhail Zarechenskiy
fa9a3868b7 Make generation of assertions for platform types aware of kotlin types
#KT-26859 Fixed
2018-09-17 16:21:06 +03:00
Mikhail Zarechenskiy
03ea8603ce Do not try building light classes for inline classes in dumb mode
Generation of inline classes is quite complicated: we mangle methods,
 add stubs and synthesized methods. So, for simplicity, to avoid
 logic duplication in dummy resolve and in the backend, currently we
 will use only the latter for light classes generation

 #KT-26843 Fixed
2018-09-17 16:21:04 +03:00
Mikhail Zarechenskiy
7d2bc5c0f6 Properly load top-level constant initializers from multifile classes
Before Kotlin 1.3-M2 we didn't write `has_field` flag for constants
 inside multifile classes. Now we write and rely on this when
 trying to load constant initializers, which is totally fine for
 binaries that were compiled with the 1.3-M2 or newer version.
 Unfortunately, constant initializers will not be loaded for old binaries.

 One way is to avoid relying on this flag, but then we'll get other
 problems (e.g. 3345dc81fd).

 Therefore, for binaries that were compiled with at least 1.3-M2 version,
 we'll rely on the flag, otherwise, we won't.
2018-09-17 16:21:02 +03:00
Mikhail Zarechenskiy
8e66dadb47 Add regression test for KT-26806
#KT-26806
2018-09-17 16:21:01 +03:00
Roman Artemev
e242a8b08b Unmute tests 2018-09-17 15:29:19 +03:00
Roman Artemev
affc827998 [JS IR BE] Support 1.3 coroutines in backend 2018-09-17 15:29:18 +03:00
Roman Artemev
c0ef1311ba [JS IR BE] Fix runtime for Release coroutines 2018-09-17 15:29:16 +03:00
Roman Artemev
c4ddf2e9ae Enable release coroutine tests in JS IR 2018-09-17 14:52:44 +03:00
Roman Artemev
323602eb5f Skip expect declaration 2018-09-17 14:52:44 +03:00
Roman Artemev
a8b44c9e18 [JS IR BE] Fix Ir Copier
* use symbol table to allocate classifier for IrType
2018-09-17 14:52:44 +03:00
Roman Artemev
6bb77ba51d [JS IR BE] Get rid of parameters in doResume method. Make its signature similar for both 1.2 and 1.3 coroutines 2018-09-17 14:52:44 +03:00
Pavel V. Talanov
e66f3fa59e Remove as33 bunches specific to mpp run configs
It is now compatible with 182 branch
2018-09-17 13:51:17 +02:00
Pavel V. Talanov
20b86d85c3 as33 branch 'since-build' is 182.4129.33 2018-09-17 13:51:15 +02:00
Pavel V. Talanov
9cbc87ce57 Update as33 branch to AS3.3 canary 10 release 2018-09-17 13:51:14 +02:00
Ilya Matveev
e1e02b072b Use Kotlin/Native 0.9.1 (#1872) 2018-09-17 14:30:14 +03:00
Ilya Matveev
82baf6cbb1 Don't add cinterop libraries in compilation output (#1871) 2018-09-17 14:29:10 +03:00
Denis Zharkov
956f8ad5e9 Support deserialized contracts in common code
#KT-26687 Fixed
2018-09-17 12:48:42 +03:00
Alexander Podkhalyuzin
ed8aad6149 Override completion right after override modifier
#KT-25312 Fixed
2018-09-17 12:23:59 +03:00
Nikolay Krasko
073f4f51fd Clean accidentally committed temporary code 2018-09-17 11:28:22 +03:00
Ilya Matveev
ea1abb0680 Provide a DSL for publication settings (#1869)
* Provide a DSL for publication settings
* Rename DSL method publication -> mavenPublication
* Fix gradle task input/output validation

 #KT-26771 fixed.
2018-09-17 11:04:55 +03:00
Ilya Gorbunov
1b889c976a Use new sequence builders in tests
Coroutine tests will fail when LV=1.2 because there're no such builders
in kotlin.coroutines.experimental.

#KT-26678
2018-09-16 23:30:36 +03:00
Ilya Gorbunov
7a7fa56d74 [JS IR BE] New sequence builder mocks for building stdlib
#KT-26678
2018-09-16 23:30:36 +03:00
Ilya Gorbunov
aac96c476a Rename sequence and iterator builder functions and their scope class
This introduces new functions instead of the existing sequence builders:
- `sequence` instead of `buildSequence`
- `iterator` instead of `buildIterator`
- `SequenceScope` instead of `SequenceBuilder`

The old functions were deprecated with error and made inline-only, and `SequenceBuilder` has been
made a deprecated typealias to `SequenceScope`.

Move sequence builders to `SequencesKt` facade class.

Replace sequence builder usages in stdlib and samples.

#KT-26678
2018-09-16 23:30:35 +03:00
Ilya Gorbunov
9c812c6e2b Use new coroutines in samples 2018-09-16 23:30:32 +03:00
Roman Elizarov
4d3d376db8 InlineOnly Result.getOrNull method 2018-09-16 23:27:46 +03:00
Roman Elizarov
feb7239189 Removed SuccessOrFailure.
Left deprecated/error typealias to Result for 1.3-Mx users.
2018-09-16 23:27:45 +03:00
Roman Elizarov
1f675c8a74 Fixed unused exceptionOrNull result in map/mapCatching
(replaced with isSuccess check)
2018-09-16 23:27:45 +03:00
Ilya Chernikov
73907106e9 Fix script util tests after moving context utils to scripting-jvm 2018-09-16 22:24:59 +02:00
Nikolay Krasko
94e6f986e7 Mover to AS 3.2 RC 3 2018-09-16 15:52:35 +03:00
Nikolay Krasko
782aa94513 Bad indentation after annotation in incomplete declaration (KT-22322)
Same behavior is for any modifier in incomplete declaration.

 #KT-22322 Fixed
2018-09-16 15:52:34 +03:00
Nikolay Krasko
94531f992d Do not show incompatible error for *-rc13 coroutines (KT-26810)
#KT-26810 Fixed
2018-09-16 15:52:32 +03:00
Ilya Chernikov
d760299dc1 Implement context classpath extraction using particular class,...
Use it in the main-kts.
Also improve diagnoistics related to the definition loading.

#KT-26828 fixed (after this commit - finally, see also another related commit)
2018-09-15 15:44:53 +02:00
Ilya Chernikov
d9760f00f6 Move context classpath utils from script-util to scripting-jvm
since it is the right place to have it in the new structure.
Solves the problem that script-util classes not found then script
definition with context classpath is loaded by the scripting compiler
plugin, since script-util is not packed into embeddable plugin.
The old context utils are deprecated and in fact wrap the new utils.
#KT-26828 fixed (in fact - partially, see another related commit)
2018-09-15 15:43:53 +02:00
Alexey Sedunov
7b3973db52 MPP: Enable Android-specific content root logic for Android Studio
#KT-26813 Fixed
2018-09-14 21:27:10 +03:00
Anton Bannykh
082c44cb5c JS: add a flag for more convenient investigation of failing IR tests 2018-09-14 20:34:34 +03:00
Mikhail Glukhikh
382379d785 MPP wizard: remove kotlin-stdlib-native & kotlin-test-native deps
Related to KT-25952
2018-09-14 18:58:50 +03:00
Pavel V. Talanov
d3540a01a7 Jest/Mocha run config producers: fix searching for test runner package
#KT-26793 Fixed
2018-09-14 17:36:29 +02:00
Pavel V. Talanov
cbe3c69457 Gradle method/class configurations: support only jvm modules
Fixes a problem where invalid run configuration could be created
    for common module when 'Gradle Test Runner' option is selected
2018-09-14 17:36:29 +02:00
Alexey Sedunov
619e2bc0db MPP: Allow 'implements' relation only within the same Gradle project
Also allow COMMON modules on the "implementer" side
2018-09-14 17:33:59 +03:00
Mikhael Bogdanov
9e6637dced Don't generate additional annotations on synthetic accessors 2018-09-14 16:23:57 +02:00
Mikhael Bogdanov
b7afb4a58e Generate enum entries classes with package private visibility
#KT-6574 Fixed
2018-09-14 16:23:57 +02:00
Raluca Sauciuc
de989c4050 Expand the fix from commit 6c274cecff to cover AndroidX
Android Studio users who migrated to AndroidX are running into the
databinding deadlock again: https://issuetracker.google.com/111788726
2018-09-14 17:09:16 +03:00
Dmitriy Dolovov
0059fcceb9 [K/N] Safe determining Kotlin/Native meta version 2018-09-14 17:08:08 +03:00
Dmitry Petrov
88fb76bffc Fix annotations loading for inline class constructors 2018-09-14 16:09:41 +03:00
Alexey Sedunov
d5b3dc8a2a MPP: Exclude non-COMMON modules from 'implemented' list 2018-09-14 15:56:04 +03:00
Ilya Gorbunov
6bfb5c59a3 Make ResultTest common
Use custom exception type to avoid platform differences in toString implementation.
2018-09-14 15:32:25 +03:00
Ilya Gorbunov
b1c2daf1fe Stdlib: fix name shadowing and names of overridden method parameters 2018-09-14 15:32:25 +03:00
Ilya Gorbunov
bf4be12239 Stdlib: review and suppress warnings 2018-09-14 15:32:25 +03:00
Ilya Gorbunov
6786b9ece2 Stdlib tests: cleanup warnings 2018-09-14 15:32:08 +03:00
Ilya Gorbunov
7e0a658de7 Change nextInt/Long with range parameters from members to extensions
We'd like to fix the implementation of these methods, so we could intrinsify them later
or perform other optimizations that are not possible when these methods are open.
2018-09-14 15:15:52 +03:00
Ilya Gorbunov
928fe19801 Rename Random.next* parameters: remaining renames
- Correct docs after parameter renaming
- Rename parameters in Random inheritors
- Rename local variables

#KT-26596
2018-09-14 15:15:52 +03:00
kenji tomita
ffb83bbdf0 Rename Random.next* parameters from "origin, bound" to "from, until"
Rename Random test methods

#KT-26596
2018-09-14 15:15:52 +03:00
Ilya Matveev
ccd4bc1bff Add a project property for Kotlin/Native version overriding 2018-09-14 14:58:03 +03:00
Ilya Matveev
80bec0898f Download native compiler in configuration stage 2018-09-14 14:58:03 +03:00
Alexey Sedunov
5a64067601 MPP: Update gradle plugin version in new MPP tests 2018-09-14 14:51:02 +03:00
Alexey Sedunov
14d8425e27 MPP: Fix import of dependencies on Android modules 2018-09-14 14:51:01 +03:00
Alexey Sedunov
1de0dbd67d MPP: Configure Kotlin facets for Android modules
#KT-26770 Fixed
2018-09-14 14:51:01 +03:00
Alexey Sedunov
9253f88220 MPP: Exclude COMMON modules from implementation list 2018-09-14 14:51:01 +03:00
Alexey Sedunov
4970e90412 MPP: Add commonMain as a part of inter-project dependency
#KT-26383 Fixed
2018-09-14 14:51:01 +03:00
Alexey Sedunov
469b11e0aa MPP: Drop duplicating library produced by file collection dependency
#KT-26675 Fixed
2018-09-14 14:51:01 +03:00
Alexey Sedunov
5ac64bcc1d MPP: Match project dependencies by target elements task 2018-09-14 14:51:00 +03:00
Alexey Sedunov
a417630c24 MPP: Force COMMON platform for commonMain/commonTest source sets
Follow-up for 172/AS3.1 bunches
2018-09-14 14:51:00 +03:00
Alexander Udalov
863c0051ce Do not report deprecation on readBytes with API version < 1.3
#KT-26667 Fixed
2018-09-14 14:43:24 +03:00
Alexander Udalov
044419eda5 Minor, refactor DeprecationResolver.getOwnDeprecations
Make local function a member, inline another utility function
2018-09-14 14:43:23 +03:00
Alexander Udalov
5dc563a9af Split deprecationUtil.kt to several files, move to subpackage
Also move interface Deprecation to subpackage "deprecation"
2018-09-14 14:43:23 +03:00
Nikolay Krasko
c268dcecd2 Better parsing for external library name (KT-26794)
- Migration notification fixed
- Make fix for replacing old coroutines libraries applicable

 #KT-26794
2018-09-14 10:52:57 +03:00
Sergey Rostov
5fc2267665 JPS, Tests: Encapsulate libraries root paths used in JPS tests 2018-09-14 10:34:30 +03:00
Sergey Rostov
f1b97bb9be JPS: code cleanup 2018-09-14 10:34:30 +03:00
Sergey Rostov
39c76c7b11 JPS: fix daemon RPC serialization
#KT-26809 Fixed
2018-09-14 10:34:30 +03:00
Georgy Bronnikov
e712007904 Restore a test 2018-09-14 09:41:39 +03:00
Georgy Bronnikov
433afcd669 JVM_IR. Mute failing tests 2018-09-14 03:12:23 +03:00
Ilya Chernikov
a03bfb3561 Implement support for non-kts scripts in gradle
#KT-26784 fixed
2018-09-13 20:47:21 +02:00
Sergey Rostov
9ae478e4fc JPS, Tests: migrate to master 2018-09-13 20:40:21 +03:00
Sergey Rostov
81cf3fbc28 JPS, minor: rename KotlinModuleBuildTarget.updateSourcesList to computeSourcesList 2018-09-13 20:30:35 +03:00
Sergey Rostov
9e6d6ad9da JPS, native: skip and report native modules as not supported
#KT-26648 Fixed
2018-09-13 20:30:35 +03:00
Dmitriy Dolovov
0c94aefb87 Move NativeIdePlatformKind to idea-jps-common
Issue #KT-26714 Fixed
2018-09-13 20:30:34 +03:00
Sergey Rostov
c8351c3da0 JPS, -Xcommon-sources: write tests 2018-09-13 20:30:34 +03:00
Sergey Rostov
313c27859a JPS tests: support _dependencies.txt and _steps.txt for better files sorting 2018-09-13 20:30:34 +03:00
Sergey Rostov
1b93f07a76 JPS tests: support custom mpp multi module tests, rearrange test data files for more consistency, configure js modules with facet (not with stdlib dependency which should be deprecated), temporary mute some complex mpp tests 2018-09-13 20:30:33 +03:00
Sergey Rostov
8cd3b46f05 JPS, -Xcommon-sources: don't iterate on all sources, use root info from DirtySourceFilesHolder. Cleanup code.
Also:
- Pass `-Xcommon-sources` argument to JS compiler.
- Calculate all sources list only when needed (after change it is not required to calculate common-sources)
- Remove `chunk: ModuleChunk` parameter from some `KotlinModuleBuildTarget` functions.
2018-09-13 20:30:33 +03:00
Sergey Rostov
359909dcff JPS MPP tests: Don't do anything for common modules, enable js ic, fix test data 2018-09-13 20:30:33 +03:00
Sergey Rostov
4975ef7db5 JPS tests: restore MPP tests runner, support new MPP model 2018-09-13 20:30:32 +03:00
Sergey Rostov
808e83a01e JPS tests: switch to new dependencies.txt parser
Order of modules changed because new parser preserve order, while previously modules are accidentally sorted by hashCode().
2018-09-13 20:30:32 +03:00
Sergey Rostov
0b5a6f61bb JPS tests: move MockJavaConstantSearch to separate file to got rid of AbstractIncrementalJpsTest.kt.173 bunch file 2018-09-13 20:30:32 +03:00
Sergey Rostov
b8c982bb72 JPS: support -Xcommon-sources for multiplatform projects
#KT-26489 Fixed
2018-09-13 20:30:31 +03:00
Vyacheslav Gerasimov
9e701f96de Add changelog for 1.2.70 2018-09-13 20:18:09 +03:00
NikitaKatkov
d2536f207c 183: CoroutineNonBlockingContextChecker for warning on blocking calls in coroutines (KT-15525) 2018-09-13 19:36:51 +03:00
Denis Zharkov
341f7c348a Fix memory leak in KotlinBuiltins related to unsigned types
Having a map from ModuleDescriptor leads to modules leakage
Especially, it's critical for DefaultBuiltins which is used in JS

ModuleDescriptor's instances were leaked there forever until the daemon dies
(up to 350M while compiling Kotlin project itself)
2018-09-13 18:49:42 +03:00
Georgy Bronnikov
f04733ef33 JVM_IR. support big arity 2018-09-13 18:44:47 +03:00
Mikhael Bogdanov
03f092fd39 Revert "Generate private constructors for Enums" cause of bootstrap problem
This reverts commit 81435c9
2018-09-13 17:07:56 +02:00
Mikhail Glukhikh
76d1d6ff12 Allow to move suspend lambda out of parentheses
#KT-26674 Fixed
#KT-26676 Fixed
2018-09-13 16:38:29 +03:00
Alexander Udalov
3a5de13dd4 Support inline classes in function signatures in call/callBy
#KT-25664 Fixed
 #KT-26748 Open
 #KT-26765 Open
2018-09-13 16:04:20 +03:00
Alexander Udalov
3e79bd2b0e Make CallerImpl with subclasses a sealed hierarchy 2018-09-13 15:54:20 +03:00
Alexander Udalov
8c8f0639f8 Remove unneeded CallerImpl implementations
Also fix a bug where nullability of the assigned value was not checked
in ClassCompanionFieldSetter because it wasn't a subclass of FieldSetter
where this check occurred
2018-09-13 15:54:20 +03:00
Alexander Udalov
356b02cb91 Extract Caller interface out of FunctionCaller, move to subpackage
Also rename FunctionCaller to CallerImpl and extract irrelevant
declarations out of it
2018-09-13 15:40:38 +03:00
Alexander Udalov
43dcbbcce1 Minor, use arrayOf to simplify code in FunctionCaller 2018-09-13 15:40:38 +03:00
Natalia Selezneva
4b138ae2b8 Do not use async script dependencies resolver in tests 2018-09-13 14:50:22 +03:00
Nikolay Krasko
8be1929634 Title and description unification for coroutines migration inspection (KT-26472) 2018-09-13 11:26:59 +03:00
Nikolay Krasko
9bfbe8a90a Enable Maven fix for coroutines in migration (KT-26472)
#KT-26472 Fixed
2018-09-13 11:26:57 +03:00
Nikolay Krasko
504c9c02d7 Remove detection of new projects from the list of modules 2018-09-13 11:26:55 +03:00
Nikolay Krasko
a58f7b5599 Remove unneeded bunch file 2018-09-13 11:26:53 +03:00
Mikhael Bogdanov
81435c98fa Generate private constructors for Enums
#KT-2680 Fixed
  #KT-16867 Fixed
2018-09-13 10:09:58 +02:00
Mikhail Glukhikh
941e5ae1b2 Introduce MPP wizard for shared (JVM / JS / iOS) libraries
This implements second part of KT-25952
2018-09-13 10:52:46 +03:00
Mikhail Glukhikh
84587eb0f9 Kotlin JVM/JS multiplatform builder: change description 2018-09-13 10:52:23 +03:00
Mikhail Glukhikh
03820245eb Change KonanPlatform platform name: Konan -> Native #KT-26691 Fixed 2018-09-13 09:09:47 +03:00
Mikhail Glukhikh
6c49c1eabd NativeIdePlatformKind: remove redundant 2018-09-13 09:09:46 +03:00
Mikhail Glukhikh
e7a6ce3626 NativeIdePlatformKind: remove unused 2018-09-13 09:09:44 +03:00
Mikhail Glukhikh
df0d91ef9e Style fix: KotlinNativeModuleConfigurator 2018-09-13 09:09:43 +03:00
Ilya Gorbunov
9353cfb526 contentDeepToString: use list instead of set for infinite recursion tracking
#KT-26388
2018-09-13 06:10:10 +03:00
Ilya Gorbunov
2d356b89b5 Specialize contentDeepEquals/HashCode/ToString for arrays of unsigned types
#KT-26388
2018-09-13 06:10:10 +03:00
Ilya Gorbunov
3cc606577c Add annotations-13.0 in classpath of those tests where the annotations from stdlib were used 2018-09-13 02:41:19 +03:00
Ilya Gorbunov
f340bc9f91 Do not use deprecated org.junit.Test in gradle js integration tests 2018-09-12 21:42:48 +03:00
Denis Zharkov
e213dc261e Fix bunch files for test RunConfigurationTest 2018-09-12 19:48:03 +03:00
Alexander Podkhalyuzin
85ba637796 Light classes should reuse language versions settings during generation
#KT-26732 Fixed
2018-09-12 16:02:07 +03:00
Vyacheslav Gerasimov
c768130f89 Remove gradle/ext-releases-local repo, native platform is now available on jcenter 2018-09-12 15:52:15 +03:00
Ilmir Usmanov
e9fc65c7ae Use our own primitive boxing methods in coroutines codegen
#KT-26490 Fixed
2018-09-12 15:36:17 +03:00
Ilmir Usmanov
273889d1a9 Add our own primitive boxing methods to stdlib
These methods are very thin wrappers around primitive wrapper classes
constructors.
They are used by coroutines code which returns primitives and this way
HotSpot is able to throw the allocations away completely.
 #KT-26591 Fixed
2018-09-12 15:36:11 +03:00
Dmitry Petrov
792c5f8b3f Generate metadata and annotations for hidden constructor
Reflection expects to see a callable method for a hidden constructor,
thus, it should be a synthetic accessor.
JVM method signature in metadata should point to the synthetic accessor.
Annotations for hidden constructor should be written on the synthetic
accessor.
2018-09-12 15:33:11 +03:00
Ilmir Usmanov
3e3ffd14a9 Exclude kotlin.coroutines.intrinsics and kotlin.coroutines.jvm.internal
from default imports.
2018-09-12 15:22:51 +03:00
Alexander Udalov
f63cf9d506 Use JvmName on kotlin.Metadata parameters to improve public API
#KT-26359 Fixed
2018-09-12 14:37:11 +03:00
Denis Zharkov
8365836753 Fix as33-bunch for KotlinRunConfigurationProducer.kt after 38be1f6947 2018-09-12 14:03:07 +03:00
Alexander Udalov
6b2a1497e2 Advance bootstrap to 1.3.0-dev-496 2018-09-12 13:34:23 +03:00
victor.petukhov
50d9dbbfc1 Fix inheritance in stdlib contracts code (KT-26409) 2018-09-12 12:34:15 +03:00
victor.petukhov
cba99a1e67 Move test to negatives after fix KT-26382 2018-09-12 12:32:57 +03:00
Denis Zharkov
9bc5b753aa Fix 181-bunch for KotlinRunConfigurationProducer.kt after 38be1f6947 2018-09-12 11:47:33 +03:00
Anton Bannykh
b389e29db5 JS: update DCE testdata 2018-09-12 09:49:25 +03:00
Anton Bannykh
ead9b31e03 JS: support [suspend] fun main([args: Array<String>]) (KT-26628, KT-26572 fixed) 2018-09-12 09:49:25 +03:00
Denis Zharkov
7e9704e50d Prohibit inheritance of Java members containing FunctionN types
#KT-25855 Fixed
2018-09-12 09:49:25 +03:00
Denis Zharkov
24a905293f Load Java declarations which reference FunctionN as Deprecated.Error
#KT-25855 Fixed
2018-09-12 09:49:25 +03:00
Denis Zharkov
bcf1b9c804 Minor. Reformat SignatureEnhancement 2018-09-12 09:49:25 +03:00
Denis Zharkov
7f4f07659c Minor. Move Deprecation and DeprecationLevel interfaces to core 2018-09-12 09:49:25 +03:00
Denis Zharkov
9cb8a35275 Minor. Pull user-data related things to CallableDescriptor
Currently, we assume user data for all non-FunctionDescriptor
declarations is empty
2018-09-12 09:49:25 +03:00
Denis Zharkov
c1cc722ac4 Turn off incorrect switch-optimization for when by enums
#KT-24708 Fixed
2018-09-12 09:49:25 +03:00
Denis Zharkov
fc3c4ad883 Support parameterless and suspend main functions in multifile classes
#KT-26574 Fixed
2018-09-12 09:49:25 +03:00
Denis Zharkov
b53194ef1a Minor. Drop unused method in FunctionCodegen 2018-09-12 09:49:25 +03:00
Denis Zharkov
aa74511378 Fix UnusedSymbolInspection for parameterless and suspend main functions
#KT-26574 Fixed
2018-09-12 09:49:25 +03:00
Denis Zharkov
1cc0c12f87 Add language feature for extended main convention
- suspend
- parameterless

 #KT-17679 Fixed
 #KT-26574 Fixed
2018-09-12 09:49:25 +03:00
Denis Zharkov
f79fbe778f Minor. Extract KtElement::isMainFunction in the IDE context 2018-09-12 09:49:25 +03:00
Denis Zharkov
38be1f6947 Minor. Parametrize MainFunctionDetector with LanguageVersionSettings 2018-09-12 09:49:25 +03:00
Denis Zharkov
bc722f9c5f Support main entry-point without arguments in JVM
#KT-26574 In Progress
2018-09-12 09:48:13 +03:00
Denis Zharkov
2c920b732c Support main entry-point without arguments in frontend
#KT-26574 In Progress
2018-09-12 09:48:13 +03:00
Denis Zharkov
3cf1c56794 Minor. Get rid of static public parts in MainFunctionDetector
In further commits, MainFunctionDetector::isMain will use
getFunctionDescriptor property
2018-09-12 09:48:13 +03:00
Denis Zharkov
c3f6ba3302 Support suspend fun main in JVM
#KT-17679 Fixed
2018-09-12 09:48:13 +03:00
Denis Zharkov
272ee252d8 Report warning on "suspend {}"-like calls based on variable
#KT-22892 Fixed
2018-09-12 09:48:13 +03:00
Denis Zharkov
b9f141d4aa Forbid suspend functions annotated with @kotlin.test.Test
#KT-26200 Fixed
2018-09-12 09:48:13 +03:00
Ilya Gorbunov
a18770fbbb Remove projectDist dependency helper usages
Use default configuration dependencies instead of projectDist ones.
2018-09-12 06:05:05 +03:00
Ilya Gorbunov
03340d770b Replace remaining distJar dependencies with default configuration dependencies 2018-09-12 06:05:05 +03:00
Pavel V. Talanov
ef915096a5 Common tests are discoverable via platform modules test classpath
Introduce KotlinGradleOrderEnumerationHandler
    and patch KotlinAndroidGradleOrderEnumerationHandler:
    - If 'Android Support' plugin is off KAndroidGradleOEH will not be available and KGOEH will be used
    - Make KAndroidGOEH implement a different EP so it replaces KGOEH when it is available
2018-09-12 04:13:32 +02:00
Pavel V. Talanov
4b0bc4a438 Try to distinguish between test/production compilations 2018-09-12 04:13:32 +02:00
Pavel V. Talanov
ee1ec22e4c Implement MultipleRunLocationsProvider EP
Provide run locations corresponding to platform modules when invoked from common code
2018-09-12 04:13:32 +02:00
Pavel V. Talanov
3da9d79fc2 KtFile.getClasses() returns empty array for non-jvm files 2018-09-12 04:13:32 +02:00
Pavel V. Talanov
3a2d25a422 Js run configuration producers: get module from ConfigurationContext
Delegate mpp concerns to MultipleRunLocationsProvider EP
Restore old behaviour via bunch files
2018-09-12 04:13:31 +02:00
Pavel V. Talanov
456bf9808d Configuration providers don't create configurations for common code
Remove special code that creates configurations
    and patches them for common modules
This should be done via MultipleRunLocationsProvider EP
2018-09-12 04:13:31 +02:00
Pavel V. Talanov
25882c5b46 Minor: add is(New)MPPModule utils 2018-09-12 04:13:31 +02:00
Pavel V. Talanov
472be61356 182 branch since-build is 182.4129.33
To allow use of the latest API
2018-09-12 04:13:31 +02:00
Ilya Gorbunov
c4e794b21f Add nullability annotations jar to debugger test application compile classpath 2018-09-12 00:58:55 +03:00
Ilya Gorbunov
41a8678b95 Remove mutability and nullability annotations from stdlib in kotlinc/lib
#KT-21784
2018-09-12 00:58:55 +03:00
Ilya Gorbunov
584410b14b Advance bootstrap to 1.3.0-dev-485 2018-09-12 00:55:14 +03:00
Alexander Udalov
e7807cc168 Skip prerelease check when building kotlin-stdlib-js-merger 2018-09-11 21:10:04 +03:00
Ilya Gorbunov
c1829782b7 Turn off compiler prerelease flag #KT-26643 2018-09-11 21:10:04 +03:00
Yan Zhulanow
59241a9c1f Minor: Remove unneeded import 2018-09-11 21:07:27 +03:00
Ilya Gorbunov
000e7493a1 Introduce common KCallable and K(Mutable)Property(ø,0,1,2) interfaces
#KT-25935
2018-09-11 19:21:15 +03:00
Ilya Gorbunov
7b46d22877 Introduce common KClass interface #KT-25935 2018-09-11 18:45:55 +03:00
4965 changed files with 86859 additions and 44720 deletions

2
.bunch
View File

@@ -4,4 +4,6 @@
as31_173_181
as32_181
as33
as34_as33
183
191_183

View File

@@ -3,6 +3,7 @@
<words>
<w>cidr</w>
<w>foldable</w>
<w>redirector</w>
</words>
</dictionary>
</component>

View File

@@ -7,9 +7,9 @@
<w>fqname</w>
<w>goto</w>
<w>gradle</w>
<w>infos</w>
<w>intrinsics</w>
<w>kdoc</w>
<w>kompiler</w>
<w>memoize</w>
<w>memoized</w>
<w>multiline</w>

View File

@@ -7,6 +7,7 @@
<w>experimentality</w>
<w>insn</w>
<w>liveness</w>
<w>parameterless</w>
</words>
</dictionary>
</component>
</component>

View File

@@ -105,6 +105,12 @@
<Problem reference="org.jetbrains.java.decompiler.main.decompiler.BaseDecompiler#addSpace" reason="Method was replaced with outher methods in 182. Use addSpaceEx instead." />
<Problem reference="com.intellij.psi.codeStyle.CommonCodeStyleSettings#copyFrom" reason="Absent in 173. Use CompatibilityKt.copyFromEx instead." />
<Problem reference="com.intellij.psi.codeStyle.CommonCodeStyleSettingsManager#copy" reason="Removed since 181. Use CompatibilityKt.copyFromEx instead." />
<Problem reference="com.intellij.notification.NotificationAction#createSimple" reason="Absent in 173." />
<Problem reference="com.intellij.notification.NotificationAction#create" reason="Absent in 173." />
<Problem reference="com.intellij.util.JdomKt#element" reason="Removed in 191" />
<Problem reference="com.intellij.execution.JavaRunConfigurationExtensionManager#getInstance" reason="Can't be used in Kotlin, because method was replaced with property after J2K in 191. Use JavaRunConfigurationExtensionManagerUtil instead." />
<Problem reference="com.intellij.execution.configurations.RunConfigurationBase" reason="Generalized in 191. Use RunConfigurationBaseAny instead in signatures." />
<Problem reference="com.intellij.execution.configurations.ModuleBasedConfiguration" reason="Generalized in 191. Use ModuleBasedConfigurationElement instead." />
</list>
</option>
</inspection_tool>

View File

@@ -0,0 +1,13 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="run IR test in node.js" type="js.build_tools.npm">
<package-json value="$PROJECT_DIR$/js/js.translator/testData/package.json" />
<command value="run" />
<scripts>
<script value="runIrTestInNode" />
</scripts>
<arguments value="$FilePath$" />
<node-interpreter value="project" />
<envs />
<method v="2" />
</configuration>
</component>

View File

@@ -292,7 +292,220 @@
- [`KT-25541`](https://youtrack.jetbrains.com/issue/KT-25541) Incorrect parameter names in reflection for inner class constructor from Java class compiled with "-parameters"
## 1.2.71
### Compiler
- [`KT-26806`](https://youtrack.jetbrains.com/issue/KT-26806) Defining constants using kotlin.math is broken in 1.2.70
### IDE
- [`KT-26399`](https://youtrack.jetbrains.com/issue/KT-26399) Kotlin Migration: NPE at KotlinMigrationProjectComponent$onImportFinished$1.run()
- [`KT-26794`](https://youtrack.jetbrains.com/issue/KT-26794) Bad version detection during migration in Android Studio 3.2
- [`KT-26823`](https://youtrack.jetbrains.com/issue/KT-26823) Fix deadlock in databinding with AndroidX which led to Android Studio hanging
- [`KT-26889`](https://youtrack.jetbrains.com/issue/KT-26889) Don't show migration dialog if no actual migrations are available
- [`KT-25177`](https://youtrack.jetbrains.com/issue/KT-25177) Report asDynamic on dynamic type as a warning
- [`KT-25454`](https://youtrack.jetbrains.com/issue/KT-25454) Extract function: make default visibility private
### JavaScript
- [`KT-26466`](https://youtrack.jetbrains.com/issue/KT-26466) Uncaught ReferenceError: println is not defined
### Tools. Gradle
- [`KT-26208`](https://youtrack.jetbrains.com/issue/KT-26208) inspectClassesForKotlinIC slows down continuous mode in Gradle
### Libraries
- [`KT-26929`](https://youtrack.jetbrains.com/issue/KT-26929) Kotlin Reflect and Proguard: cant find referenced class kotlin.annotations.jvm.ReadOnly/Mutable
## 1.2.70
### Compiler
- [`KT-13860`](https://youtrack.jetbrains.com/issue/KT-13860) Avoid creating KtImportDirective PSI elements for default imports in LazyImportScope
- [`KT-22201`](https://youtrack.jetbrains.com/issue/KT-22201) Generate nullability annotations for data class toString and equals methods.
- [`KT-23870`](https://youtrack.jetbrains.com/issue/KT-23870) SAM adapter method returns null-values for "genericParameterTypes"
- [`KT-24597`](https://youtrack.jetbrains.com/issue/KT-24597) IDE doesn't report missing constructor on inheritance of an expected class in common module
- [`KT-25120`](https://youtrack.jetbrains.com/issue/KT-25120) RequireKotlin on nested class and its members is not loaded correctly
- [`KT-25193`](https://youtrack.jetbrains.com/issue/KT-25193) Names of parameters from Java interface methods implemented by delegation are lost
- [`KT-25405`](https://youtrack.jetbrains.com/issue/KT-25405) Mismatching descriptor type parameters on inner types
- [`KT-25604`](https://youtrack.jetbrains.com/issue/KT-25604) Disable callable references to exprerimental suspend functions
- [`KT-25665`](https://youtrack.jetbrains.com/issue/KT-25665) Add a warning for annotations which target non-existent accessors
- [`KT-25894`](https://youtrack.jetbrains.com/issue/KT-25894) Do not generate body for functions from Any in light class builder mode
- [`KT-20772`](https://youtrack.jetbrains.com/issue/KT-20772) Incorrect smart cast on enum members
- [`KT-24657`](https://youtrack.jetbrains.com/issue/KT-24657) Compiler performance issues with big files
- [`KT-25745`](https://youtrack.jetbrains.com/issue/KT-25745) Do not report warning about annotations on non-existing accessors for JvmStatic properties
- [`KT-25746`](https://youtrack.jetbrains.com/issue/KT-25746) Improve message for warning about annotations that have target to non-existing accessors
- [`KT-25810`](https://youtrack.jetbrains.com/issue/KT-25810) New Inference: Overload resolution ambiguity on method 'provideDelegate(Nothing?, KProperty<*>)' when there's more than one `provideDelegate` operator in scope
- [`KT-25973`](https://youtrack.jetbrains.com/issue/KT-25973) Report metadata version mismatch upon discovering a .kotlin_module file in the dependencies with an incompatible metadata version
- [`KT-22281`](https://youtrack.jetbrains.com/issue/KT-22281) JVM: Incorrect comparison of Double and Float when types are derived from smart-casts
- [`KT-22649`](https://youtrack.jetbrains.com/issue/KT-22649) Compiler: wrong code generated / Couldn't transform method node - using inline extension property inside lambda
### IDE
- [`KT-18301`](https://youtrack.jetbrains.com/issue/KT-18301) kotlin needs crazy amount of memory
- [`KT-23668`](https://youtrack.jetbrains.com/issue/KT-23668) Methods with internal visibility have different mangling names in IDE and in compiler
- [`KT-24892`](https://youtrack.jetbrains.com/issue/KT-24892) please remove usages of com.intellij.util.containers.ConcurrentFactoryMap#ConcurrentFactoryMap deprecated long ago
- [`KT-25144`](https://youtrack.jetbrains.com/issue/KT-25144) Quick fix “Change signature” changes class of argument when applied for descendant classes with enabled -Xnew-inference option
- [`KT-25356`](https://youtrack.jetbrains.com/issue/KT-25356) Update Gradle Kotlin-DSL icon according to new IDEA 2018.2 icons style
- [`KT-20056`](https://youtrack.jetbrains.com/issue/KT-20056) TCE on creating object of an anonymous class in Kotlin script
- [`KT-25092`](https://youtrack.jetbrains.com/issue/KT-25092) SourcePsi should be physical leaf element but got OPERATION_REFERENCE
- [`KT-25249`](https://youtrack.jetbrains.com/issue/KT-25249) Uast operates "Unit" type instead of "void"
- [`KT-25255`](https://youtrack.jetbrains.com/issue/KT-25255) Preferences | Languages & Frameworks | Kotlin Updates: show currently installed version
- [`KT-25297`](https://youtrack.jetbrains.com/issue/KT-25297) Inconsistency in `KotlinULambdaExpression` and `KotlinLocalFunctionULambdaExpression`
- [`KT-25515`](https://youtrack.jetbrains.com/issue/KT-25515) Add/remove analysis-related compiler setting does not update IDE project model immediately
- [`KT-25524`](https://youtrack.jetbrains.com/issue/KT-25524) UAST: proper resolve for function variable call
- [`KT-25640`](https://youtrack.jetbrains.com/issue/KT-25640) "Configure Kotlin" action changes values of language and API version in project settings
### IDE. Debugger
- [`KT-25147`](https://youtrack.jetbrains.com/issue/KT-25147) Conditional breakpoints doesn't work in `common` code of MPP
- [`KT-25152`](https://youtrack.jetbrains.com/issue/KT-25152) MPP debug doesn't navigate to `common` code if there are same named files in `common` and `platform` parts
### IDE. Gradle
- [`KT-22732`](https://youtrack.jetbrains.com/issue/KT-22732) TestNG runner is always used for TestNG tests even when Use Gradle runner is selected
- [`KT-25913`](https://youtrack.jetbrains.com/issue/KT-25913) Honor 'store generated project files externally option' for Kotlin facets imported from Gradle
- [`KT-25955`](https://youtrack.jetbrains.com/issue/KT-25955) Support expect/actual in new MPP imported into IDEA
### IDE. Inspections and Intentions
#### New Features
- [`KT-6633`](https://youtrack.jetbrains.com/issue/KT-6633) Inspection to detect unnecessary "with" calls
- [`KT-25146`](https://youtrack.jetbrains.com/issue/KT-25146) Add quick-fix for default parameter value removal
- [`KT-7675`](https://youtrack.jetbrains.com/issue/KT-7675) Create inspection to replace if with let
- [`KT-13515`](https://youtrack.jetbrains.com/issue/KT-13515) Add intention to replace '?.let' with null check
- [`KT-13854`](https://youtrack.jetbrains.com/issue/KT-13854) Need intention actions: to convert property with getter to initializer
- [`KT-15476`](https://youtrack.jetbrains.com/issue/KT-15476) Inspection to convert non-lazy chains of collection functions into sequences
- [`KT-22068`](https://youtrack.jetbrains.com/issue/KT-22068) Force usage of “it” in .forEach{} calls
- [`KT-23445`](https://youtrack.jetbrains.com/issue/KT-23445) Inspection and quickfix to replace `assertTrue(a == b)` with `assertEquals(a, b)`
- [`KT-25270`](https://youtrack.jetbrains.com/issue/KT-25270) "return@foo" outside of lambda should have quickfix to remove "@foo" label
#### Fixes
- [`KT-11154`](https://youtrack.jetbrains.com/issue/KT-11154) Spell checking inspection is not suppressable
- [`KT-18681`](https://youtrack.jetbrains.com/issue/KT-18681) "Replace 'if' with 'when'" generates unnecessary else block
- [`KT-24001`](https://youtrack.jetbrains.com/issue/KT-24001) "Suspicious combination of == and ===" false positive
- [`KT-24385`](https://youtrack.jetbrains.com/issue/KT-24385) Convert lambda to reference refactor produces red code with companion object
- [`KT-24694`](https://youtrack.jetbrains.com/issue/KT-24694) Move lambda out of parentheses should not be applied for multiple functional parameters
- [`KT-25089`](https://youtrack.jetbrains.com/issue/KT-25089) False-positive "Call chain on collection type can be simplified" for `map` and `joinToString` on a `HashMap`
- [`KT-25169`](https://youtrack.jetbrains.com/issue/KT-25169) Impossible to suppress UAST/JVM inspections
- [`KT-25321`](https://youtrack.jetbrains.com/issue/KT-25321) Safe delete of a class property implementing constructor parameter at the platform side doesn't remove all the related declarations
- [`KT-25539`](https://youtrack.jetbrains.com/issue/KT-25539) `Make class open` quick fix doesn't update all the related implementations of a multiplatform class
- [`KT-25608`](https://youtrack.jetbrains.com/issue/KT-25608) Confusing "Redundant override" inspection message
- [`KT-16422`](https://youtrack.jetbrains.com/issue/KT-16422) Replace lambda with method reference inspections fails
- [`KT-21999`](https://youtrack.jetbrains.com/issue/KT-21999) Convert lambda to reference adds this with incorrect label
- [`KT-23467`](https://youtrack.jetbrains.com/issue/KT-23467) False positive `suspicious callable reference` on scoping function called on another lambda
- [`KT-25044`](https://youtrack.jetbrains.com/issue/KT-25044) "Implement member" quick-fix should not generate 'actual' modifier with expect declaration in interface only
- [`KT-25579`](https://youtrack.jetbrains.com/issue/KT-25579) Redundant semicolon erroneously reported during local var modifier ambiguity
- [`KT-25633`](https://youtrack.jetbrains.com/issue/KT-25633) “Add kotlin-XXX.jar to the classpath” quick fix adds dependency with invalid version in Gradle-based projects
- [`KT-25739`](https://youtrack.jetbrains.com/issue/KT-25739) "Convert to run" / "Convert to with" intentions incorrectly process references to Java static members
- [`KT-25928`](https://youtrack.jetbrains.com/issue/KT-25928) "Let extend" quick fix is suggested in case of nullable/non-null TYPE_MISMATCH collision
- [`KT-26042`](https://youtrack.jetbrains.com/issue/KT-26042) False positive "Remove redundant '.let' call" for lambda with destructured arguments
### IDE. KDoc
- [`KT-22815`](https://youtrack.jetbrains.com/issue/KT-22815) Update quick documentation
- [`KT-22648`](https://youtrack.jetbrains.com/issue/KT-22648) Quick Doc popup: break (long?) declarations into several lines
### IDE. Libraries
- [`KT-25129`](https://youtrack.jetbrains.com/issue/KT-25129) Idea freezes when Kotlin plugin tries to determine if jar is js lib in jvm module
### IDE. Navigation
- [`KT-25317`](https://youtrack.jetbrains.com/issue/KT-25317) `Go to actual declaration` keyboard shortcut doesn't work for `expect object`, showing "No implementations found" message
- [`KT-25492`](https://youtrack.jetbrains.com/issue/KT-25492) Find usages: keep `Expected functions` option state while searching for usages of a regular function
- [`KT-25498`](https://youtrack.jetbrains.com/issue/KT-25498) `Find Usages` doesn't show `Supertype` usages of `actual` declarations with constructor
### IDE. Project View
- [`KT-22823`](https://youtrack.jetbrains.com/issue/KT-22823) Text pasted into package is parsed as Kotlin before Java
### IDE. Refactorings
- [`KT-22072`](https://youtrack.jetbrains.com/issue/KT-22072) "Convert MutableMap.put to assignment" should not be applicable when put is used as expression
- [`KT-23590`](https://youtrack.jetbrains.com/issue/KT-23590) Incorrect conflict warning "Internal function will not be accessible" when moving class from jvm to common module
- [`KT-23594`](https://youtrack.jetbrains.com/issue/KT-23594) Incorrect conflict warning about IllegalStateException when moving class from jvm to common module
- [`KT-23772`](https://youtrack.jetbrains.com/issue/KT-23772) MPP: Refactor / Rename class does not update name of file containing related expect/actual class
- [`KT-23914`](https://youtrack.jetbrains.com/issue/KT-23914) Safe search false positives during moves between common and actual modules
- [`KT-25326`](https://youtrack.jetbrains.com/issue/KT-25326) Refactor/Safe Delete doesn't report `actual object` usages
- [`KT-25438`](https://youtrack.jetbrains.com/issue/KT-25438) Refactor/Safe delete of a multiplatform companion object: usage is not reported
- [`KT-25857`](https://youtrack.jetbrains.com/issue/KT-25857) Refactoring → Move moves whole file in case of moving class from Kotlin script
- [`KT-25858`](https://youtrack.jetbrains.com/issue/KT-25858) Refactoring → Move can be called only for class declarations in Kotlin script
### IDE. Script
- [`KT-25814`](https://youtrack.jetbrains.com/issue/KT-25814) IDE scripting console -> kotlin (JSR-223) - compilation errors - unresolved IDEA classes
- [`KT-25822`](https://youtrack.jetbrains.com/issue/KT-25822) jvmTarget from the script compiler options is ignored in the IDE
### IDE. Multiplatform
- [`KT-23368`](https://youtrack.jetbrains.com/issue/KT-23368) IDE: Build: JPS errors are reported for valid non-multiplatform module depending on multiplatform one
### IDE. Ultimate
- [`KT-25595`](https://youtrack.jetbrains.com/issue/KT-25595) Rename Kotlin-specific "Protractor" run configuration to distinguish it from the one provided by NodeJS plugin
- [`KT-19309`](https://youtrack.jetbrains.com/issue/KT-19309) Spring JPA Repository IntelliJ tooling with Kotlin
### IDE. Tests Support
- [`KT-26228`](https://youtrack.jetbrains.com/issue/KT-26228) NoClassDefFoundError: org/jetbrains/kotlin/idea/run/KotlinTestNgConfigurationProducer on running a JUnit test with TestNG plugin disabled
### Reflection
- [`KT-25541`](https://youtrack.jetbrains.com/issue/KT-25541) Incorrect parameter names in reflection for inner class constructor from Java class compiled with "-parameters"
### Tools. CLI
- [`KT-21910`](https://youtrack.jetbrains.com/issue/KT-21910) Add `-Xfriend-paths` compiler argument to support internal visibility checks in production/test sources from external build systems
- [`KT-25554`](https://youtrack.jetbrains.com/issue/KT-25554) Do not report warnings when `-XXLanguage` was used to turn on deprecation
- [`KT-25196`](https://youtrack.jetbrains.com/issue/KT-25196) Optional expected annotation is visible in platforms where it doesn't have actual
### Tools. JPS
- [`KT-25540`](https://youtrack.jetbrains.com/issue/KT-25540) JPS JS IC does not recompile usages from other modules when package is different
### Tools. kapt
- [`KT-25396`](https://youtrack.jetbrains.com/issue/KT-25396) KAPT Error: Unknown option: infoAsWarnings
- [`KT-26211`](https://youtrack.jetbrains.com/issue/KT-26211) Kotlin plugin 1.2.60+ breaks IDEA source/resource/test roots in a Maven project with Kapt
### Tools. Gradle
- [`KT-25025`](https://youtrack.jetbrains.com/issue/KT-25025) Inter-project IC for JS in Gradle
- [`KT-25455`](https://youtrack.jetbrains.com/issue/KT-25455) Gradle IC: when class signature is changed its indirect subclasses in different module are not recompiled
### Tools. JPS
- [`KT-25998`](https://youtrack.jetbrains.com/issue/KT-25998) Build process starts compiling w/o any changes (on release version)
- [`KT-25977`](https://youtrack.jetbrains.com/issue/KT-25977) Can not run a Kotlin test
- [`KT-26072`](https://youtrack.jetbrains.com/issue/KT-26072) MPP compilation issue
- [`KT-26113`](https://youtrack.jetbrains.com/issue/KT-26113) Build takes around 20 seconds in already fully built IDEA project
### Tools. Scripts
- [`KT-26142`](https://youtrack.jetbrains.com/issue/KT-26142) update maven-central remote repository url
### Tools. Incremental Compile
- [`KT-26528`](https://youtrack.jetbrains.com/issue/KT-26528) ISE “To save disabled cache status [delete] should be called (this behavior is kept for compatibility)” on compiling project with enabled IC in Maven
### JavaScript
- [`KT-22053`](https://youtrack.jetbrains.com/issue/KT-22053) JS: Secondary constructor of Throwable inheritor doesn't call to primary one
- [`KT-26064`](https://youtrack.jetbrains.com/issue/KT-26064) JS inliner calls wrong constructor in incremental build
- [`KT-26117`](https://youtrack.jetbrains.com/issue/KT-26117) JS runtime error: ArrayList_init instead of ArrayList_init_0
### Libraries
- [`KT-18067`](https://youtrack.jetbrains.com/issue/KT-18067) KotlinJS - String.compareTo(other: String, ignoreCase: Boolean = false): Int
- [`KT-19507`](https://youtrack.jetbrains.com/issue/KT-19507) Using @JvmName from stdlib-common fails to compile in JS module.
- [`KT-19508`](https://youtrack.jetbrains.com/issue/KT-19508) Add @JsName to stdlib-common for controlling JS implementation
- [`KT-24478`](https://youtrack.jetbrains.com/issue/KT-24478) Annotate relevant standard library annotations with @OptionalExpectation
- [`KT-25980`](https://youtrack.jetbrains.com/issue/KT-25980) JvmSynthetic annotation has no description in the docs
## 1.2.60

View File

@@ -8,7 +8,7 @@ plugins {
dependencies {
compile(commonDep("org.apache.ant", "ant"))
compile(project(":kotlin-preloader"))
compile(projectDist(":kotlin-stdlib"))
compile(project(":kotlin-stdlib"))
}
sourceSets {

View File

@@ -14,17 +14,17 @@ dependencies {
compileOnly(project(":js:js.serializer"))
compileOnly(project(":js:js.frontend"))
compileOnly(intellijCoreDep()) { includeJars("intellij-core") }
compileOnly(intellijDep()) { includeJars("annotations", "asm-all", "trove4j", "util") }
compileOnly(intellijDep()) { includeJars("annotations", "asm-all", "trove4j", "util", rootProject = rootProject) }
compileOnly(project(":kotlin-reflect-api"))
testCompileOnly(project(":compiler:cli-common"))
testCompile(projectTests(":compiler:tests-common"))
testCompile(commonDep("junit:junit"))
testCompile(protobufFull())
testCompile(projectDist(":kotlin-stdlib"))
testCompile(project(":kotlin-stdlib"))
testCompileOnly(intellijDep()) { includeJars("openapi") }
testRuntime(projectDist(":kotlin-reflect"))
testRuntime(project(":kotlin-reflect"))
}
sourceSets {

View File

@@ -0,0 +1,9 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.build
val DEFAULT_KOTLIN_SOURCE_FILES_EXTENSIONS = listOf("kt", "kts")

View File

@@ -23,10 +23,7 @@ import com.intellij.util.io.EnumeratorStringDescriptor
import gnu.trove.THashSet
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.build.GeneratedJvmClass
import org.jetbrains.kotlin.config.IncrementalCompilation
import org.jetbrains.kotlin.incremental.storage.*
import org.jetbrains.kotlin.incremental.storage.version.clean
import org.jetbrains.kotlin.incremental.storage.version.localCacheVersionManager
import org.jetbrains.kotlin.inline.inlineFunctionsJvmNames
import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader
import org.jetbrains.kotlin.load.kotlin.incremental.components.IncrementalCache
@@ -264,11 +261,6 @@ open class IncrementalJvmCache(
return protoMap[JvmClassName.byInternalName(MODULE_MAPPING_FILE_NAME)]?.bytes
}
override fun clean() {
super.clean()
localCacheVersionManager(targetDataRoot, IncrementalCompilation.isEnabledForJvm()).clean()
}
private inner class ProtoMap(storageFile: File) : BasicStringMap<ProtoMapValue>(storageFile, ProtoMapValueExternalizer) {
fun process(kotlinClass: LocalFileKotlinClass, changesCollector: ChangesCollector) {

View File

@@ -21,11 +21,8 @@ import java.io.File
fun File.isJavaFile() =
extension.equals("java", ignoreCase = true)
fun File.isKotlinFile(): Boolean =
extension.let {
"kt".equals(it, ignoreCase = true) ||
"kts".equals(it, ignoreCase = true)
}
fun File.isKotlinFile(sourceFilesExtensions: List<String>): Boolean =
!isJavaFile() && sourceFilesExtensions.any { it.equals(extension, ignoreCase = true) }
fun File.isClassFile(): Boolean =
extension.equals("class", ignoreCase = true)

View File

@@ -67,12 +67,18 @@ fun getModificationsToPerform(
val underscore = fileName.indexOf("_")
if (underscore != -1) {
val module = fileName.substring(0, underscore)
var moduleName = fileName.substring(0, underscore)
var moduleFileName = fileName.substring(underscore + 1)
if (moduleName.all { it.isDigit() }) {
val (moduleName1, moduleFileName1) = moduleFileName.split("_")
moduleName = moduleName1
moduleFileName = moduleFileName1
}
assert(moduleNames != null) { "File name has module prefix, but multi-module environment is absent" }
assert(module in moduleNames!!) { "Module not found for file with prefix: $fileName" }
assert(moduleName in moduleNames!!) { "Module not found for file with prefix: $fileName" }
return Pair(module, fileName.substring(underscore + 1))
return Pair(moduleName, moduleFileName)
}
assert(moduleNames == null) { "Test is multi-module, but file has no module prefix: $fileName" }

View File

@@ -13,12 +13,12 @@ import proguard.gradle.ProGuardTask
buildscript {
extra["defaultSnapshotVersion"] = "1.3-SNAPSHOT"
kotlinBootstrapFrom(BootstrapOption.TeamCity("1.3.0-dev-322", onlySuccessBootstrap = false))
kotlinBootstrapFrom(BootstrapOption.TeamCity("1.3.20-dev-564", onlySuccessBootstrap = false))
repositories {
repositories.withRedirector(project) {
bootstrapKotlinRepo?.let(::maven)
maven("https://plugins.gradle.org/m2")
}
}
// a workaround for kotlin compiler classpath in kotlin project: sometimes gradle substitutes
// kotlin-stdlib external dependency with local project :kotlin-stdlib in kotlinCompilerClasspath configuration.
@@ -35,7 +35,7 @@ buildscript {
}
plugins {
`build-scan`
`build-scan` version "1.15"
idea
id("jps-compatible")
}
@@ -107,6 +107,7 @@ extra["JDK_17"] = jdkPath("1.7")
extra["JDK_18"] = jdkPath("1.8")
extra["JDK_9"] = jdkPath("9")
extra["JDK_10"] = jdkPathIfFound("10")
extra["JDK_11"] = jdkPathIfFound("11")
rootProject.apply {
from(rootProject.file("versions.gradle.kts"))
@@ -122,8 +123,8 @@ extra["versions.junit"] = "4.12"
extra["versions.javaslang"] = "2.0.6"
extra["versions.ant"] = "1.8.2"
extra["versions.android"] = "2.3.1"
extra["versions.kotlinx-coroutines-core"] = "0.20"
extra["versions.kotlinx-coroutines-jdk8"] = "0.20"
extra["versions.kotlinx-coroutines-core"] = "0.26.1-eap13"
extra["versions.kotlinx-coroutines-jdk8"] = "0.26.1-eap13"
extra["versions.json"] = "20160807"
extra["versions.native-platform"] = "0.14"
extra["versions.ant-launcher"] = "1.8.0"
@@ -161,6 +162,8 @@ extra["compilerModules"] = arrayOf(
":compiler:resolution",
":compiler:serialization",
":compiler:psi",
":compiler:fir:tree",
":compiler:fir:psi2fir",
":compiler:frontend",
":compiler:frontend.java",
":compiler:frontend.script",
@@ -260,21 +263,20 @@ allprojects {
val mirrorRepo: String? = findProperty("maven.repository.mirror")?.toString()
repositories {
repositories.withRedirector(project) {
intellijSdkRepo(project)
androidDxJarRepo(project)
mirrorRepo?.let(::maven)
bootstrapKotlinRepo?.let(::maven)
jcenter()
}
}
configureJvmProject(javaHome!!, jvmTarget!!)
val commonCompilerArgs = listOfNotNull(
"-Xallow-kotlin-package",
"-Xread-deserialized-contracts",
"-Xprogressive".takeIf { hasProperty("test.progressive.mode") }, // TODO: change to "-progressive" after bootstrap
"-XXLanguage:-ReleaseCoroutines"
"-Xprogressive".takeIf { hasProperty("test.progressive.mode") } // TODO: change to "-progressive" after bootstrap
)
tasks.withType<org.jetbrains.kotlin.gradle.dsl.KotlinCompile<*>> {
@@ -383,14 +385,14 @@ val ideaPlugin by task<Task> {
}
tasks {
"clean" {
create("clean") {
doLast {
delete("$buildDir/repo")
delete(distDir)
}
}
"cleanupArtifacts" {
create("cleanupArtifacts") {
doLast {
delete(ideaPluginDir)
delete(ideaUltimatePluginDir)
@@ -398,7 +400,7 @@ tasks {
}
}
"coreLibsTest" {
create("coreLibsTest") {
(coreLibProjects + listOf(
":kotlin-stdlib:samples",
":kotlin-test:kotlin-test-js:kotlin-test-js-it",
@@ -409,34 +411,35 @@ tasks {
}
}
"gradlePluginTest" {
create("gradlePluginTest") {
gradlePluginProjects.forEach {
dependsOn(it + ":check")
}
}
"gradlePluginIntegrationTest" {
create("gradlePluginIntegrationTest") {
dependsOn(":kotlin-gradle-plugin-integration-tests:check")
}
"jvmCompilerTest" {
create("jvmCompilerTest") {
dependsOn("dist")
dependsOn(":compiler:test",
":compiler:container:test",
":compiler:tests-java8:test")
":compiler:tests-java8:test",
":compiler:tests-spec:remoteRunTests")
}
"jsCompilerTest" {
create("jsCompilerTest") {
dependsOn(":js:js.tests:test")
dependsOn(":js:js.tests:runMocha")
}
"scriptingTest" {
create("scriptingTest") {
dependsOn("dist")
dependsOn(":kotlin-script-util:test")
}
"compilerTest" {
create("compilerTest") {
dependsOn("jvmCompilerTest")
dependsOn("jsCompilerTest")
@@ -445,44 +448,44 @@ tasks {
dependsOn(":compiler:incremental-compilation-impl:test")
}
"toolsTest" {
create("toolsTest") {
dependsOn(":tools:kotlinp:test")
}
"examplesTest" {
create("examplesTest") {
dependsOn("dist")
(project(":examples").subprojects + project(":kotlin-gradle-subplugin-example")).forEach { p ->
dependsOn("${p.path}:check")
}
}
"distTest" {
create("distTest") {
dependsOn("compilerTest")
dependsOn("toolsTest")
dependsOn("gradlePluginTest")
dependsOn("examplesTest")
}
"specTest" {
create("specTest") {
dependsOn("dist")
dependsOn(":compiler:tests-spec:test")
}
"androidCodegenTest" {
create("androidCodegenTest") {
dependsOn(":compiler:android-tests:test")
}
"jps-tests" {
create("jps-tests") {
dependsOn("dist")
dependsOn(":jps-plugin:test")
}
"idea-plugin-main-tests" {
create("idea-plugin-main-tests") {
dependsOn("dist")
dependsOn(":idea:test")
}
"idea-plugin-additional-tests" {
create("idea-plugin-additional-tests") {
dependsOn("dist")
dependsOn(":idea:idea-gradle:test",
":idea:idea-maven:test",
@@ -490,20 +493,20 @@ tasks {
":eval4j:test")
}
"idea-plugin-tests" {
create("idea-plugin-tests") {
dependsOn("dist")
dependsOn("idea-plugin-main-tests",
"idea-plugin-additional-tests")
}
"android-ide-tests" {
create("android-ide-tests") {
dependsOn("dist")
dependsOn(":plugins:android-extensions-ide:test",
":idea:idea-android:test",
":kotlin-annotation-processing:test")
}
"plugins-tests" {
create("plugins-tests") {
dependsOn("dist")
dependsOn(":kotlin-annotation-processing:test",
":kotlin-source-sections-compiler-plugin:test",
@@ -511,11 +514,12 @@ tasks {
":kotlin-noarg-compiler-plugin:test",
":kotlin-sam-with-receiver-compiler-plugin:test",
":plugins:uast-kotlin:test",
":kotlin-annotation-processing-gradle:test")
":kotlin-annotation-processing-gradle:test",
":kotlinx-serialization-ide-plugin:test")
}
"ideaPluginTest" {
create("ideaPluginTest") {
dependsOn(
"idea-plugin-tests",
"jps-tests",
@@ -526,12 +530,15 @@ tasks {
}
"test" {
create("test") {
doLast {
throw GradleException("Don't use directly, use aggregate tasks *-check instead")
}
}
"check" { dependsOn("test") }
create("check") {
dependsOn("test")
}
}
fun CopySpec.setExecutablePermissions() {

712
build.gradle.kts.191 Normal file
View File

@@ -0,0 +1,712 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.api.Project
import java.util.*
import java.io.File
import org.gradle.api.tasks.bundling.Jar
import org.gradle.plugins.ide.idea.model.IdeaModel
import org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import org.jetbrains.kotlin.gradle.tasks.Kotlin2JsCompile
import proguard.gradle.ProGuardTask
buildscript {
extra["defaultSnapshotVersion"] = "1.3-SNAPSHOT"
kotlinBootstrapFrom(BootstrapOption.TeamCity("1.3.20-dev-564", onlySuccessBootstrap = false))
repositories.withRedirector(project) {
bootstrapKotlinRepo?.let(::maven)
maven("https://plugins.gradle.org/m2")
}
// a workaround for kotlin compiler classpath in kotlin project: sometimes gradle substitutes
// kotlin-stdlib external dependency with local project :kotlin-stdlib in kotlinCompilerClasspath configuration.
// see also configureCompilerClasspath@
val bootstrapCompilerClasspath by configurations.creating
dependencies {
bootstrapCompilerClasspath(kotlin("compiler-embeddable", bootstrapKotlinVersion))
classpath("com.gradle.publish:plugin-publish-plugin:0.9.7")
classpath(kotlin("gradle-plugin", bootstrapKotlinVersion))
classpath("net.sf.proguard:proguard-gradle:5.3.3")
}
}
plugins {
`build-scan` version "1.15"
idea
id("jps-compatible")
}
pill {
excludedDirs(
"out",
"buildSrc/build",
"buildSrc/prepare-deps/android-dx/build",
"buildSrc/prepare-deps/intellij-sdk/build"
)
}
buildScan {
setTermsOfServiceUrl("https://gradle.com/terms-of-service")
setTermsOfServiceAgree("yes")
}
val configuredJdks: List<JdkId> =
getConfiguredJdks().also {
it.forEach {
logger.info("Using ${it.majorVersion} home: ${it.homeDir}")
}
}
val defaultSnapshotVersion: String by extra
val buildNumber by extra(findProperty("build.number")?.toString() ?: defaultSnapshotVersion)
val kotlinVersion by extra(findProperty("deployVersion")?.toString() ?: buildNumber)
val kotlinLanguageVersion by extra("1.3")
allprojects {
group = "org.jetbrains.kotlin"
version = kotlinVersion
}
extra["kotlin_root"] = rootDir
val cidrKotlinPlugin by configurations.creating
dependencies {
cidrKotlinPlugin(project(":prepare:cidr-plugin", "runtimeJar"))
}
val commonBuildDir = File(rootDir, "build")
val distDir by extra("$rootDir/dist")
val distKotlinHomeDir by extra("$distDir/kotlinc")
val distLibDir = "$distKotlinHomeDir/lib"
val commonLocalDataDir = "$rootDir/local"
val ideaSandboxDir = "$commonLocalDataDir/ideaSandbox"
val ideaUltimateSandboxDir = "$commonLocalDataDir/ideaUltimateSandbox"
val ideaPluginDir = "$distDir/artifacts/ideaPlugin/Kotlin"
val ideaUltimatePluginDir = "$distDir/artifacts/ideaUltimatePlugin/Kotlin"
val cidrPluginDir = "$distDir/artifacts/cidrPlugin/Kotlin"
// TODO: use "by extra()" syntax where possible
extra["distLibDir"] = project.file(distLibDir)
extra["libsDir"] = project.file(distLibDir)
extra["commonLocalDataDir"] = project.file(commonLocalDataDir)
extra["ideaSandboxDir"] = project.file(ideaSandboxDir)
extra["ideaUltimateSandboxDir"] = project.file(ideaUltimateSandboxDir)
extra["ideaPluginDir"] = project.file(ideaPluginDir)
extra["ideaUltimatePluginDir"] = project.file(ideaUltimatePluginDir)
extra["cidrPluginDir"] = project.file(cidrPluginDir)
extra["isSonatypeRelease"] = false
extra["JDK_16"] = jdkPath("1.6")
extra["JDK_17"] = jdkPath("1.7")
extra["JDK_18"] = jdkPath("1.8")
extra["JDK_9"] = jdkPath("9")
extra["JDK_10"] = jdkPathIfFound("10")
extra["JDK_11"] = jdkPathIfFound("11")
rootProject.apply {
from(rootProject.file("versions.gradle.kts"))
from(rootProject.file("report.gradle.kts"))
}
extra["versions.protobuf-java"] = "2.6.1"
extra["versions.javax.inject"] = "1"
extra["versions.jsr305"] = "1.3.9"
extra["versions.jansi"] = "1.16"
extra["versions.jline"] = "3.3.1"
extra["versions.junit"] = "4.12"
extra["versions.javaslang"] = "2.0.6"
extra["versions.ant"] = "1.8.2"
extra["versions.android"] = "2.3.1"
extra["versions.kotlinx-coroutines-core"] = "0.26.1-eap13"
extra["versions.kotlinx-coroutines-jdk8"] = "0.26.1-eap13"
extra["versions.json"] = "20160807"
extra["versions.native-platform"] = "0.14"
extra["versions.ant-launcher"] = "1.8.0"
extra["versions.robolectric"] = "3.1"
extra["versions.org.springframework"] = "4.2.0.RELEASE"
extra["versions.jflex"] = "1.7.0"
extra["versions.markdown"] = "0.1.25"
val isTeamcityBuild = project.hasProperty("teamcity") || System.getenv("TEAMCITY_VERSION") != null
val intellijUltimateEnabled = project.getBooleanProperty("intellijUltimateEnabled") ?: isTeamcityBuild
val effectSystemEnabled by extra(project.getBooleanProperty("kotlin.compiler.effectSystemEnabled") ?: false)
val newInferenceEnabled by extra(project.getBooleanProperty("kotlin.compiler.newInferenceEnabled") ?: false)
val intellijSeparateSdks = project.getBooleanProperty("intellijSeparateSdks") ?: false
extra["intellijUltimateEnabled"] = intellijUltimateEnabled
extra["intellijSeparateSdks"] = intellijSeparateSdks
extra["IntellijCoreDependencies"] =
listOf("annotations",
"asm-all-7.0-beta",
"guava",
"jdom",
"jna",
"log4j",
"picocontainer",
"snappy-in-java",
"streamex",
"trove4j")
extra["compilerModules"] = arrayOf(
":compiler:util",
":compiler:container",
":compiler:resolution",
":compiler:serialization",
":compiler:psi",
":compiler:frontend",
":compiler:frontend.java",
":compiler:frontend.script",
":compiler:cli-common",
":compiler:daemon-common",
":compiler:daemon",
":compiler:ir.tree",
":compiler:ir.psi2ir",
":compiler:ir.backend.common",
":compiler:backend.js",
":compiler:backend-common",
":compiler:backend",
":compiler:plugin-api",
":compiler:light-classes",
":compiler:cli",
":compiler:incremental-compilation-impl",
":js:js.ast",
":js:js.serializer",
":js:js.parser",
":js:js.frontend",
":js:js.translator",
":js:js.dce",
":compiler",
":kotlin-build-common",
":core:metadata",
":core:metadata.jvm",
":core:descriptors",
":core:descriptors.jvm",
":core:deserialization",
":core:util.runtime"
)
val coreLibProjects = listOf(
":kotlin-stdlib",
":kotlin-stdlib-common",
":kotlin-stdlib-js",
":kotlin-stdlib-jre7",
":kotlin-stdlib-jre8",
":kotlin-stdlib-jdk7",
":kotlin-stdlib-jdk8",
":kotlin-test:kotlin-test-common",
":kotlin-test:kotlin-test-jvm",
":kotlin-test:kotlin-test-junit",
":kotlin-test:kotlin-test-junit5",
":kotlin-test:kotlin-test-testng",
":kotlin-test:kotlin-test-js",
":kotlin-reflect"
)
val gradlePluginProjects = listOf(
":kotlin-gradle-plugin",
":kotlin-gradle-plugin:plugin-marker",
":kotlin-gradle-plugin-api",
// ":kotlin-gradle-plugin-integration-tests", // TODO: build fails
":kotlin-allopen",
":kotlin-allopen:plugin-marker",
":kotlin-annotation-processing-gradle",
":kotlin-noarg",
":kotlin-noarg:plugin-marker",
":kotlin-sam-with-receiver"
)
apply {
from("libraries/commonConfiguration.gradle")
from("libraries/configureGradleTools.gradle")
}
apply {
if (extra["isSonatypeRelease"] as? Boolean == true) {
logger.info("Applying configuration for sonatype release")
from("libraries/prepareSonatypeStaging.gradle")
}
}
fun Task.listConfigurationContents(configName: String) {
doFirst {
project.configurations.findByName(configName)?.let {
println("$configName configuration files:\n${it.allArtifacts.files.files.joinToString("\n ", " ")}")
}
}
}
val defaultJvmTarget = "1.8"
val defaultJavaHome = jdkPath(defaultJvmTarget!!)
val ignoreTestFailures by extra(project.findProperty("ignoreTestFailures")?.toString()?.toBoolean() ?: project.hasProperty("teamcity"))
allprojects {
jvmTarget = defaultJvmTarget
javaHome = defaultJavaHome
// There are problems with common build dir:
// - some tests (in particular js and binary-compatibility-validator depend on the fixed (default) location
// - idea seems unable to exclude common builddir from indexing
// therefore it is disabled by default
// buildDir = File(commonBuildDir, project.name)
val mirrorRepo: String? = findProperty("maven.repository.mirror")?.toString()
repositories.withRedirector(project) {
intellijSdkRepo(project)
androidDxJarRepo(project)
mirrorRepo?.let(::maven)
bootstrapKotlinRepo?.let(::maven)
jcenter()
}
configureJvmProject(javaHome!!, jvmTarget!!)
val commonCompilerArgs = listOfNotNull(
"-Xallow-kotlin-package",
"-Xread-deserialized-contracts",
"-Xprogressive".takeIf { hasProperty("test.progressive.mode") } // TODO: change to "-progressive" after bootstrap
)
tasks.withType<org.jetbrains.kotlin.gradle.dsl.KotlinCompile<*>> {
kotlinOptions {
languageVersion = kotlinLanguageVersion
apiVersion = kotlinLanguageVersion
freeCompilerArgs = commonCompilerArgs
}
}
tasks.withType<org.jetbrains.kotlin.gradle.dsl.KotlinJvmCompile> {
kotlinOptions {
freeCompilerArgs = commonCompilerArgs + listOf("-Xnormalize-constructor-calls=enable")
}
}
tasks.withType(VerificationTask::class.java as Class<Task>) {
(this as VerificationTask).ignoreFailures = ignoreTestFailures
}
tasks.withType<Javadoc> {
enabled = false
}
task<Jar>("javadocJar") {
classifier = "javadoc"
}
tasks.withType<Jar> {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
task("listArchives") { listConfigurationContents("archives") }
task("listRuntimeJar") { listConfigurationContents("runtimeJar") }
task("listDistJar") { listConfigurationContents("distJar") }
afterEvaluate {
logger.info("configuring project $name to compile to the target jvm version $jvmTarget using jdk: $javaHome")
if (javaHome != defaultJavaHome || jvmTarget != defaultJvmTarget) {
configureJvmProject(javaHome!!, jvmTarget!!)
}
fun File.toProjectRootRelativePathOrSelf() = (relativeToOrNull(rootDir)?.takeUnless { it.startsWith("..") } ?: this).path
fun FileCollection.printClassPath(role: String) =
println("${project.path} $role classpath:\n ${joinToString("\n ") { it.toProjectRootRelativePathOrSelf() } }")
try { javaPluginConvention() } catch (_: UnknownDomainObjectException) { null }?.let { javaConvention ->
task("printCompileClasspath") { doFirst { javaConvention.sourceSets["main"].compileClasspath.printClassPath("compile") } }
task("printRuntimeClasspath") { doFirst { javaConvention.sourceSets["main"].runtimeClasspath.printClassPath("runtime") } }
task("printTestCompileClasspath") { doFirst { javaConvention.sourceSets["test"].compileClasspath.printClassPath("test compile") } }
task("printTestRuntimeClasspath") { doFirst { javaConvention.sourceSets["test"].runtimeClasspath.printClassPath("test runtime") } }
}
run configureCompilerClasspath@ {
val bootstrapCompilerClasspath by rootProject.buildscript.configurations
configurations.findByName("kotlinCompilerClasspath")?.let {
dependencies.add(it.name, files(bootstrapCompilerClasspath))
}
}
}
}
gradle.taskGraph.whenReady {
if (isTeamcityBuild) {
logger.warn("CI build profile is active (IC is off, proguard is on). Use -Pteamcity=false to reproduce local build")
for (task in allTasks) {
when (task) {
is AbstractKotlinCompile<*> -> task.incremental = false
is JavaCompile -> task.options.isIncremental = false
}
}
} else {
logger.warn("Local build profile is active (IC is on, proguard is off). Use -Pteamcity=true to reproduce TC build")
for (task in allTasks) {
when (task) {
// todo: remove when Gradle 4.10+ is used (Java IC on by default)
is JavaCompile -> task.options.isIncremental = true
is org.gradle.jvm.tasks.Jar -> task.entryCompression = ZipEntryCompression.STORED
}
}
}
}
val dist by task<Copy> {
val childDistTasks = getTasksByName("dist", true) - this@task
dependsOn(childDistTasks)
into(distDir)
from(files("compiler/cli/bin")) { into("kotlinc/bin") }
from(files("license")) { into("kotlinc/license") }
}
val copyCompilerToIdeaPlugin by task<Copy> {
dependsOn(dist)
into(ideaPluginDir)
from(distDir) { include("kotlinc/**") }
}
val ideaPlugin by task<Task> {
dependsOn(copyCompilerToIdeaPlugin)
val childIdeaPluginTasks = getTasksByName("ideaPlugin", true) - this@task
dependsOn(childIdeaPluginTasks)
}
tasks {
create("clean") {
doLast {
delete("$buildDir/repo")
delete(distDir)
}
}
create("cleanupArtifacts") {
doLast {
delete(ideaPluginDir)
delete(ideaUltimatePluginDir)
delete(cidrPluginDir)
}
}
create("coreLibsTest") {
(coreLibProjects + listOf(
":kotlin-stdlib:samples",
":kotlin-test:kotlin-test-js:kotlin-test-js-it",
":kotlinx-metadata-jvm",
":tools:binary-compatibility-validator"
)).forEach {
dependsOn(it + ":check")
}
}
create("gradlePluginTest") {
gradlePluginProjects.forEach {
dependsOn(it + ":check")
}
}
create("gradlePluginIntegrationTest") {
dependsOn(":kotlin-gradle-plugin-integration-tests:check")
}
create("jvmCompilerTest") {
dependsOn("dist")
dependsOn(":compiler:test",
":compiler:container:test",
":compiler:tests-java8:test",
":compiler:tests-spec:remoteRunTests")
}
create("jsCompilerTest") {
dependsOn(":js:js.tests:test")
dependsOn(":js:js.tests:runMocha")
}
create("scriptingTest") {
dependsOn("dist")
dependsOn(":kotlin-script-util:test")
}
create("compilerTest") {
dependsOn("jvmCompilerTest")
dependsOn("jsCompilerTest")
dependsOn("scriptingTest")
dependsOn(":kotlin-build-common:test")
dependsOn(":compiler:incremental-compilation-impl:test")
}
create("toolsTest") {
dependsOn(":tools:kotlinp:test")
}
create("examplesTest") {
dependsOn("dist")
(project(":examples").subprojects + project(":kotlin-gradle-subplugin-example")).forEach { p ->
dependsOn("${p.path}:check")
}
}
create("distTest") {
dependsOn("compilerTest")
dependsOn("toolsTest")
dependsOn("gradlePluginTest")
dependsOn("examplesTest")
}
create("specTest") {
dependsOn("dist")
dependsOn(":compiler:tests-spec:test")
}
create("androidCodegenTest") {
dependsOn(":compiler:android-tests:test")
}
create("jps-tests") {
dependsOn("dist")
dependsOn(":jps-plugin:test")
}
create("idea-plugin-main-tests") {
dependsOn("dist")
dependsOn(":idea:test")
}
create("idea-plugin-additional-tests") {
dependsOn("dist")
dependsOn(":idea:idea-gradle:test",
":idea:idea-maven:test",
":j2k:test",
":eval4j:test")
}
create("idea-plugin-tests") {
dependsOn("dist")
dependsOn("idea-plugin-main-tests",
"idea-plugin-additional-tests")
}
create("android-ide-tests") {
dependsOn("dist")
dependsOn(":plugins:android-extensions-ide:test",
":idea:idea-android:test",
":kotlin-annotation-processing:test")
}
create("plugins-tests") {
dependsOn("dist")
dependsOn(":kotlin-annotation-processing:test",
":kotlin-source-sections-compiler-plugin:test",
":kotlin-allopen-compiler-plugin:test",
":kotlin-noarg-compiler-plugin:test",
":kotlin-sam-with-receiver-compiler-plugin:test",
":plugins:uast-kotlin:test",
":kotlin-annotation-processing-gradle:test",
":kotlinx-serialization-ide-plugin:test")
}
create("ideaPluginTest") {
dependsOn(
"idea-plugin-tests",
"jps-tests",
"plugins-tests",
"android-ide-tests",
":generators:test"
)
}
create("test") {
doLast {
throw GradleException("Don't use directly, use aggregate tasks *-check instead")
}
}
create("check") {
dependsOn("test")
}
}
fun CopySpec.setExecutablePermissions() {
filesMatching("**/bin/*") { mode = 0b111101101 }
filesMatching("**/bin/*.bat") { mode = 0b110100100 }
}
val zipCompiler by task<Zip> {
dependsOn(dist)
destinationDir = file(distDir)
archiveName = "kotlin-compiler-$kotlinVersion.zip"
from(distKotlinHomeDir)
into("kotlinc")
setExecutablePermissions()
doLast {
logger.lifecycle("Compiler artifacts packed to $archivePath")
}
}
val zipTestData by task<Zip> {
destinationDir = file(distDir)
archiveName = "kotlin-test-data.zip"
from("compiler/testData") { into("compiler") }
from("idea/testData") { into("ide") }
from("idea/idea-completion/testData") { into("ide/completion") }
from("libraries/stdlib/common/test") { into("stdlib/common") }
from("libraries/stdlib/test") { into("stdlib/test") }
doLast {
logger.lifecycle("Test data packed to $archivePath")
}
}
val zipPlugin by task<Zip> {
val src = when (project.findProperty("pluginArtifactDir") as String?) {
"Kotlin" -> ideaPluginDir
"KotlinUltimate" -> ideaUltimatePluginDir
null -> if (project.hasProperty("ultimate")) ideaUltimatePluginDir else ideaPluginDir
else -> error("Unsupported plugin artifact dir")
}
val destPath = project.findProperty("pluginZipPath") as String?
val dest = File(destPath ?: "$buildDir/kotlin-plugin.zip")
destinationDir = dest.parentFile
archiveName = dest.name
doFirst {
if (destPath == null) throw GradleException("Specify target zip path with 'pluginZipPath' property")
}
from(src)
into("Kotlin")
setExecutablePermissions()
doLast {
logger.lifecycle("Plugin artifacts packed to $archivePath")
}
}
val cidrPlugin by task<Copy> {
dependsOn(ideaPlugin)
into(cidrPluginDir)
from(ideaPluginDir) {
exclude("lib/kotlin-plugin.jar")
exclude("lib/android-lint.jar")
exclude("lib/android-ide.jar")
exclude("lib/android-output-parser-ide.jar")
exclude("lib/android-extensions-ide.jar")
exclude("lib/android-extensions-compiler.jar")
exclude("lib/kapt3-idea.jar")
exclude("lib/jps-ide.jar")
exclude("lib/jps/**")
exclude("kotlinc/**")
exclude("lib/maven-ide.jar")
}
from(cidrKotlinPlugin) { into("lib") }
}
val zipCidrPlugin by task<Zip> {
val destPath = project.findProperty("pluginZipPath") as String?
?: "$distDir/artifacts/kotlin-plugin-$kotlinVersion-CIDR.zip"
val destFile = File(destPath)
destinationDir = destFile.parentFile
archiveName = destFile.name
from(cidrPlugin)
into("Kotlin")
setExecutablePermissions()
doLast {
logger.lifecycle("Plugin artifacts packed to $archivePath")
}
}
configure<IdeaModel> {
module {
excludeDirs = files(
project.buildDir,
commonLocalDataDir,
".gradle",
"dependencies",
"dist"
).toSet()
}
}
fun jdkPathIfFound(version: String): String? {
val jdkName = "JDK_${version.replace(".", "")}"
val jdkMajorVersion = JdkMajorVersion.valueOf(jdkName)
return configuredJdks.find { it.majorVersion == jdkMajorVersion }?.homeDir?.canonicalPath
}
fun jdkPath(version: String): String = jdkPathIfFound(version)
?: throw GradleException ("Please set environment variable JDK_${version.replace(".", "")} to point to JDK $version installation")
fun Project.configureJvmProject(javaHome: String, javaVersion: String) {
tasks.withType<JavaCompile> {
if (name != "compileJava9Java") {
options.isFork = true
options.forkOptions.javaHome = file(javaHome)
options.compilerArgs.add("-proc:none")
options.encoding = "UTF-8"
}
}
tasks.withType<KotlinCompile> {
kotlinOptions.jdkHome = javaHome
kotlinOptions.jvmTarget = javaVersion
}
tasks.withType<Test> {
executable = File(javaHome, "bin/java").canonicalPath
}
}
tasks.create("findShadowJarsInClasspath").doLast {
fun Collection<File>.printSorted(indent: String = " ") {
sortedBy { it.path }.forEach { println(indent + it.relativeTo(rootProject.projectDir)) }
}
val shadowJars = hashSetOf<File>()
for (project in rootProject.allprojects) {
for (task in project.tasks) {
when (task) {
is ShadowJar -> {
shadowJars.add(fileFrom(task.archivePath))
}
is ProGuardTask -> {
shadowJars.addAll(task.outputs.files.toList())
}
}
}
}
println("Shadow jars:")
shadowJars.printSorted()
fun Project.checkConfig(configName: String) {
val config = configurations.findByName(configName) ?: return
val shadowJarsInConfig = config.resolvedConfiguration.files.filter { it in shadowJars }
if (shadowJarsInConfig.isNotEmpty()) {
println()
println("Project $project contains shadow jars in configuration '$configName':")
shadowJarsInConfig.printSorted()
}
}
for (project in rootProject.allprojects) {
project.checkConfig("compileClasspath")
project.checkConfig("testCompileClasspath")
}
}

View File

@@ -1,11 +1,17 @@
buildscript {
val cacheRedirectorEnabled = findProperty("cacheRedirectorEnabled")?.toString()?.toBoolean() == true
val buildSrcKotlinVersion: String by extra(findProperty("buildSrc.kotlin.version")?.toString() ?: embeddedKotlinVersion)
val buildSrcKotlinRepo: String? by extra(findProperty("buildSrc.kotlin.repo") as String?)
extra["versions.shadow"] = "2.0.2"
extra["versions.native-platform"] = "0.14"
repositories {
if (cacheRedirectorEnabled) {
maven("https://cache-redirector.jetbrains.com/jcenter.bintray.com")
}
buildSrcKotlinRepo?.let {
maven(url = it)
}
@@ -17,6 +23,8 @@ buildscript {
}
}
val cacheRedirectorEnabled = findProperty("cacheRedirectorEnabled")?.toString()?.toBoolean() == true
logger.info("buildSrcKotlinVersion: " + extra["buildSrcKotlinVersion"])
logger.info("buildSrc kotlin compiler version: " + org.jetbrains.kotlin.config.KotlinCompilerVersion.VERSION)
logger.info("buildSrc stdlib version: " + KotlinVersion.CURRENT)
@@ -32,12 +40,12 @@ plugins {
}
gradlePlugin {
(plugins) {
"pill-configurable" {
plugins {
register("pill-configurable") {
id = "pill-configurable"
implementationClass = "org.jetbrains.kotlin.pill.PillConfigurablePlugin"
}
"jps-compatible" {
register("jps-compatible") {
id = "jps-compatible"
implementationClass = "org.jetbrains.kotlin.pill.JpsCompatiblePlugin"
}
@@ -58,8 +66,6 @@ val isTeamcityBuild = project.hasProperty("teamcity") || System.getenv("TEAMCITY
val intellijUltimateEnabled by extra(project.getBooleanProperty("intellijUltimateEnabled") ?: isTeamcityBuild)
val intellijSeparateSdks by extra(project.getBooleanProperty("intellijSeparateSdks") ?: false)
extra["intellijRepo"] = "https://www.jetbrains.com/intellij-repository"
extra["intellijReleaseType"] = if (extra["versions.intellijSdk"]?.toString()?.endsWith("SNAPSHOT") == true)
"snapshots"
else
@@ -70,10 +76,14 @@ extra["versions.androidDxSources"] = "5.0.0_r2"
extra["customDepsOrg"] = "kotlin.build.custom.deps"
repositories {
if (cacheRedirectorEnabled) {
maven("https://cache-redirector.jetbrains.com/jcenter.bintray.com")
}
extra["buildSrcKotlinRepo"]?.let {
maven(url = it)
}
maven(url = "https://repo.gradle.org/gradle/ext-releases-local") // for native-platform
jcenter()
}
@@ -82,9 +92,7 @@ dependencies {
compile("net.rubygrapefruit:native-platform-windows-amd64:${property("versions.native-platform")}")
compile("net.rubygrapefruit:native-platform-windows-i386:${property("versions.native-platform")}")
compile("com.jakewharton.dex:dex-method-list:3.0.0")
// TODO: adding the dep to the plugin breaks the build unexpectedly, resolve and uncomment
// compile("org.jetbrains.kotlin:kotlin-gradle-plugin:${rootProject.extra["bootstrap_kotlin_version"]}")
// Shadow plugin is used in many projects of the main build. Once it's no longer used in buildSrc, please move this dependency to the root project
compile("com.github.jengelman.gradle.plugins:shadow:${property("versions.shadow")}")
compile("org.ow2.asm:asm-all:6.0_BETA")
}

View File

@@ -3,5 +3,7 @@ org.gradle.parallel=false
org.gradle.configureondemand=false
org.gradle.jvmargs=-Duser.country=US -Dkotlin.daemon.jvm.options=-Xmx1600m
cacheRedirectorEnabled=true
#buildSrc.kotlin.repo=https://jcenter.bintray.com
#buildSrc.kotlin.version=1.1.50

View File

@@ -3,6 +3,8 @@ org.gradle.parallel=false
org.gradle.configureondemand=false
org.gradle.jvmargs=-Duser.country=US -Dkotlin.daemon.jvm.options=-Xmx1600m
cacheRedirectorEnabled=true
#buildSrc.kotlin.repo=https://jcenter.bintray.com
#buildSrc.kotlin.version=1.1.50

View File

@@ -3,6 +3,8 @@ org.gradle.parallel=false
org.gradle.configureondemand=false
org.gradle.jvmargs=-Duser.country=US -Dkotlin.daemon.jvm.options=-Xmx1600m
cacheRedirectorEnabled=true
#buildSrc.kotlin.repo=https://jcenter.bintray.com
#buildSrc.kotlin.version=1.1.50

View File

@@ -3,6 +3,8 @@ org.gradle.parallel=false
org.gradle.configureondemand=false
org.gradle.jvmargs=-Duser.country=US -Dkotlin.daemon.jvm.options=-Xmx1600m
cacheRedirectorEnabled=true
#buildSrc.kotlin.repo=https://jcenter.bintray.com
#buildSrc.kotlin.version=1.1.50

View File

@@ -0,0 +1,11 @@
org.gradle.daemon=true
org.gradle.parallel=false
org.gradle.configureondemand=false
org.gradle.jvmargs=-Duser.country=US -Dkotlin.daemon.jvm.options=-Xmx1600m
cacheRedirectorEnabled=true
#buildSrc.kotlin.repo=https://jcenter.bintray.com
#buildSrc.kotlin.version=1.1.50
intellijUltimateEnabled=false

View File

@@ -1,5 +1,5 @@
import org.gradle.api.publish.ivy.internal.artifact.DefaultIvyArtifact
import org.gradle.api.publish.ivy.internal.artifact.FileBasedIvyArtifact
import org.gradle.api.publish.ivy.internal.publication.DefaultIvyConfiguration
import org.gradle.api.publish.ivy.internal.publication.DefaultIvyPublicationIdentity
import org.gradle.api.publish.ivy.internal.publisher.IvyDescriptorFileGenerator
@@ -92,8 +92,8 @@ val prepareIvyXml by tasks.creating {
with(IvyDescriptorFileGenerator(DefaultIvyPublicationIdentity(customDepsOrg, dxModuleName, dxRevision))) {
addConfiguration(DefaultIvyConfiguration("default"))
addConfiguration(DefaultIvyConfiguration("sources"))
addArtifact(DefaultIvyArtifact(File(dxRepoModuleDir, "dx.jar"), "dx", "jar", "jar", null).also { it.conf = "default" })
addArtifact(DefaultIvyArtifact(File(dxRepoModuleDir, "dx-sources.jar"), "dx", "jar", "sources", "sources").also { it.conf = "sources" })
addArtifact(FileBasedIvyArtifact(File(dxRepoModuleDir, "dx.jar"), DefaultIvyPublicationIdentity(customDepsOrg, "dx", dxRevision)).also { it.conf = "default" })
addArtifact(FileBasedIvyArtifact(File(dxRepoModuleDir, "dx-sources.jar"), DefaultIvyPublicationIdentity(customDepsOrg, "dx", dxRevision)).also { it.conf = "sources" })
writeTo(ivyFile)
}
}

View File

@@ -1,25 +1,15 @@
@file:Suppress("PropertyName")
import org.gradle.api.publish.ivy.internal.artifact.DefaultIvyArtifact
import org.gradle.api.publish.ivy.internal.artifact.FileBasedIvyArtifact
import org.gradle.api.publish.ivy.internal.publication.DefaultIvyConfiguration
import org.gradle.api.publish.ivy.internal.publication.DefaultIvyPublicationIdentity
import org.gradle.api.publish.ivy.internal.publisher.IvyDescriptorFileGenerator
import java.io.File
import org.gradle.internal.os.OperatingSystem
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
buildscript {
repositories {
jcenter()
}
dependencies {
classpath("com.github.jengelman.gradle.plugins:shadow:${property("versions.shadow")}")
}
}
val cacheRedirectorEnabled = findProperty("cacheRedirectorEnabled")?.toString()?.toBoolean() == true
val intellijUltimateEnabled: Boolean by rootProject.extra
val intellijRepo: String by rootProject.extra
val intellijReleaseType: String by rootProject.extra
val intellijVersion = rootProject.extra["versions.intellijSdk"] as String
val androidStudioRelease = rootProject.findProperty("versions.androidStudioRelease") as String?
@@ -66,8 +56,14 @@ repositories {
}
}
}
maven { setUrl("$intellijRepo/$intellijReleaseType") }
maven { setUrl("https://plugins.jetbrains.com/maven") }
if (cacheRedirectorEnabled) {
maven("https://cache-redirector.jetbrains.com/www.jetbrains.com/intellij-repository/$intellijReleaseType")
maven("https://cache-redirector.jetbrains.com/plugins.jetbrains.com/maven")
}
maven("https://www.jetbrains.com/intellij-repository/$intellijReleaseType")
maven("https://plugins.jetbrains.com/maven")
}
val intellij by configurations.creating
@@ -152,12 +148,9 @@ val unzipIntellijCore by tasks.creating { configureExtractFromConfigurationTask(
val unzipJpsStandalone by tasks.creating { configureExtractFromConfigurationTask(`jps-standalone`) { zipTree(it.singleFile) } }
val copyIntellijSdkSources by tasks.creating(ShadowJar::class.java) {
val copyIntellijSdkSources by tasks.creating(Copy::class.java) {
from(sources)
baseName = "ideaIC"
version = intellijVersion
classifier = "sources"
destinationDir = File(repoDir, sources.name)
into(File(repoDir, sources.name))
}
val copyJpsBuildTest by tasks.creating { configureExtractFromConfigurationTask(`jps-build-test`) { it.singleFile } }
@@ -171,12 +164,12 @@ fun writeIvyXml(moduleName: String, fileName: String, jarFiles: FileCollection,
jarFiles.asFileTree.files.forEach {
if (it.isFile && it.extension == "jar") {
val relativeName = it.toRelativeString(baseDir).removeSuffix(".jar")
addArtifact(DefaultIvyArtifact(it, relativeName, "jar", "jar", null).also { it.conf = "default" })
addArtifact(FileBasedIvyArtifact(it, DefaultIvyPublicationIdentity(customDepsOrg, relativeName, intellijVersion)).also { it.conf = "default" })
}
}
if (sourcesJar != null) {
val sourcesArtifactName = sourcesJar.name.removeSuffix(".jar").substringBefore("-")
addArtifact(DefaultIvyArtifact(sourcesJar, sourcesArtifactName, "jar", "sources", "sources").also { it.conf = "sources" })
addArtifact(FileBasedIvyArtifact(sourcesJar, DefaultIvyPublicationIdentity(customDepsOrg, sourcesArtifactName, intellijVersion)).also { it.conf = "sources" })
}
writeTo(File(customDepsRepoModulesDir, "$fileName.ivy.xml"))
}

View File

@@ -1,267 +0,0 @@
@file:Suppress("PropertyName")
import org.gradle.api.publish.ivy.internal.artifact.DefaultIvyArtifact
import org.gradle.api.publish.ivy.internal.publication.DefaultIvyConfiguration
import org.gradle.api.publish.ivy.internal.publication.DefaultIvyPublicationIdentity
import org.gradle.api.publish.ivy.internal.publisher.IvyDescriptorFileGenerator
import java.io.File
import org.gradle.internal.os.OperatingSystem
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
buildscript {
repositories {
jcenter()
}
dependencies {
classpath("com.github.jengelman.gradle.plugins:shadow:${property("versions.shadow")}")
}
}
val intellijUltimateEnabled: Boolean by rootProject.extra
val intellijRepo: String by rootProject.extra
val intellijReleaseType: String by rootProject.extra
val intellijVersion = rootProject.extra["versions.intellijSdk"] as String
val androidStudioRelease = rootProject.findProperty("versions.androidStudioRelease") as String?
val androidStudioBuild = rootProject.findProperty("versions.androidStudioBuild") as String?
val intellijSeparateSdks: Boolean by rootProject.extra
val installIntellijCommunity = !intellijUltimateEnabled || intellijSeparateSdks
val installIntellijUltimate = intellijUltimateEnabled
val intellijVersionDelimiterIndex = intellijVersion.indexOfAny(charArrayOf('.', '-'))
if (intellijVersionDelimiterIndex == -1) {
error("Invalid IDEA version $intellijVersion")
}
val platformBaseVersion = intellijVersion.substring(0, intellijVersionDelimiterIndex)
logger.info("intellijUltimateEnabled: $intellijUltimateEnabled")
logger.info("intellijVersion: $intellijVersion")
logger.info("androidStudioRelease: $androidStudioRelease")
logger.info("androidStudioBuild: $androidStudioBuild")
logger.info("intellijSeparateSdks: $intellijSeparateSdks")
logger.info("installIntellijCommunity: $installIntellijCommunity")
logger.info("installIntellijUltimate: $installIntellijUltimate")
val studioOs by lazy {
when {
OperatingSystem.current().isWindows -> "windows"
OperatingSystem.current().isMacOsX -> "mac"
OperatingSystem.current().isLinux -> "linux"
else -> {
logger.error("Unknown operating system for android tools: ${OperatingSystem.current().name}")
""
}
}
}
repositories {
if (androidStudioRelease != null) {
ivy {
artifactPattern("https://dl.google.com/dl/android/studio/ide-zips/$androidStudioRelease/[artifact]-[revision]-$studioOs.zip")
metadataSources {
artifact()
}
}
}
maven { setUrl("$intellijRepo/$intellijReleaseType") }
maven { setUrl("https://plugins.jetbrains.com/maven") }
}
val intellij by configurations.creating
val intellijUltimate by configurations.creating
val sources by configurations.creating
val `jps-standalone` by configurations.creating
val `jps-build-test` by configurations.creating
val `intellij-core` by configurations.creating
val `plugins-NodeJS` by configurations.creating
val customDepsRepoDir = File(buildDir, "repo")
val customDepsOrg: String by rootProject.extra
val customDepsRevision = intellijVersion
val customDepsRepoModulesDir = File(customDepsRepoDir, "$customDepsOrg/$customDepsRevision")
val repoDir = customDepsRepoModulesDir
dependencies {
if (androidStudioRelease != null) {
intellij("google:android-studio-ide:$androidStudioBuild")
} else {
if (installIntellijCommunity) {
intellij("com.jetbrains.intellij.idea:ideaIC:$intellijVersion")
}
if (installIntellijUltimate) {
intellijUltimate("com.jetbrains.intellij.idea:ideaIU:$intellijVersion")
}
}
sources("com.jetbrains.intellij.idea:ideaIC:$intellijVersion:sources@jar")
`jps-standalone`("com.jetbrains.intellij.idea:jps-standalone:$intellijVersion")
`jps-build-test`("com.jetbrains.intellij.idea:jps-build-test:$intellijVersion")
`intellij-core`("com.jetbrains.intellij.idea:intellij-core:$intellijVersion")
if (intellijUltimateEnabled) {
`plugins-NodeJS`("com.jetbrains.plugins:NodeJS:${rootProject.extra["versions.idea.NodeJS"]}@zip")
}
}
fun Task.configureExtractFromConfigurationTask(sourceConfig: Configuration,
pathRemap: (String) -> String = { it },
extractor: (Configuration) -> Any) {
dependsOn(sourceConfig)
inputs.files(sourceConfig)
val targetDir = File(repoDir, sourceConfig.name)
outputs.dirs(targetDir)
doFirst {
project.copy {
from(extractor(sourceConfig))
into(targetDir)
eachFile {
path = pathRemap(path)
}
}
}
}
fun removePathPrefix(path: String): String {
if (androidStudioRelease == null) return path
val slashes = if (studioOs == "mac") 2 else 1
var result = path
repeat(slashes) {
result = result.substringAfter('/')
}
return result
}
val unzipIntellijSdk by tasks.creating {
configureExtractFromConfigurationTask(intellij, pathRemap = { removePathPrefix(it) }) {
zipTree(it.singleFile).matching {
exclude("**/plugins/Kotlin/**")
}
}
}
val unzipIntellijUltimateSdk by tasks.creating {
configureExtractFromConfigurationTask(intellijUltimate) {
zipTree(it.singleFile).matching {
exclude("plugins/Kotlin/**")
}
}
}
val unzipIntellijCore by tasks.creating { configureExtractFromConfigurationTask(`intellij-core`) { zipTree(it.singleFile) } }
val unzipJpsStandalone by tasks.creating { configureExtractFromConfigurationTask(`jps-standalone`) { zipTree(it.singleFile) } }
val copyIntellijSdkSources by tasks.creating(ShadowJar::class.java) {
from(sources)
baseName = "ideaIC"
version = intellijVersion
classifier = "sources"
destinationDir = File(repoDir, sources.name)
}
val copyJpsBuildTest by tasks.creating { configureExtractFromConfigurationTask(`jps-build-test`) { it.singleFile } }
val unzipNodeJSPlugin by tasks.creating { configureExtractFromConfigurationTask(`plugins-NodeJS`) { zipTree(it.singleFile) } }
fun writeIvyXml(moduleName: String, fileName: String, jarFiles: FileCollection, baseDir: File, sourcesJar: File?) {
with(IvyDescriptorFileGenerator(DefaultIvyPublicationIdentity(customDepsOrg, moduleName, intellijVersion))) {
addConfiguration(DefaultIvyConfiguration("default"))
addConfiguration(DefaultIvyConfiguration("sources"))
jarFiles.asFileTree.files.forEach {
if (it.isFile && it.extension == "jar") {
val relativeName = it.toRelativeString(baseDir).removeSuffix(".jar")
addArtifact(DefaultIvyArtifact(it, relativeName, "jar", "jar", null).also { it.conf = "default" })
}
}
if (sourcesJar != null) {
val sourcesArtifactName = sourcesJar.name.removeSuffix(".jar").substringBefore("-")
addArtifact(DefaultIvyArtifact(sourcesJar, sourcesArtifactName, "jar", "sources", "sources").also { it.conf = "sources" })
}
writeTo(File(customDepsRepoModulesDir, "$fileName.ivy.xml"))
}
}
val prepareIvyXmls by tasks.creating {
dependsOn(unzipIntellijCore, unzipJpsStandalone, copyIntellijSdkSources, copyJpsBuildTest)
val intellijSdkDir = File(repoDir, intellij.name)
val intellijUltimateSdkDir = File(repoDir, intellijUltimate.name)
if (installIntellijCommunity) {
dependsOn(unzipIntellijSdk)
inputs.dir(intellijSdkDir)
outputs.file(File(repoDir, "${intellij.name}.ivy.xml"))
}
if (installIntellijUltimate) {
dependsOn(unzipIntellijUltimateSdk)
inputs.dir(intellijUltimateSdkDir)
outputs.file(File(repoDir, "${intellijUltimate.name}.ivy.xml"))
}
val flatDeps = listOf(`intellij-core`, `jps-standalone`, `jps-build-test`)
flatDeps.forEach {
inputs.dir(File(repoDir, it.name))
outputs.file(File(repoDir, "${it.name}.ivy.xml"))
}
inputs.dir(File(repoDir, sources.name))
if (intellijUltimateEnabled) {
dependsOn(unzipNodeJSPlugin)
inputs.dir(File(repoDir, `plugins-NodeJS`.name))
outputs.file(File(repoDir, "${`plugins-NodeJS`.name}.ivy.xml"))
}
doFirst {
val sourcesFile = if (sources.isEmpty) null else File(repoDir, "${sources.name}/${sources.singleFile.name}")
if (installIntellijCommunity) {
val libDir = File(intellijSdkDir, "lib")
writeIvyXml(intellij.name,
intellij.name,
fileTree(libDir).filter {
it.parentFile == libDir && !it.name.startsWith("kotlin-")
},
libDir,
sourcesFile)
File(intellijSdkDir, "plugins").listFiles { it: File -> it.isDirectory }.forEach {
writeIvyXml(it.name, "intellij.plugin.${it.name}", files("$it/lib/"), File(it, "lib"), sourcesFile)
}
}
if (installIntellijUltimate) {
val libDir = File(intellijUltimateSdkDir, "lib")
writeIvyXml(intellij.name, // important! the module name should be "intellij"
intellijUltimate.name,
fileTree(libDir).filter {
it.parentFile == libDir && !it.name.startsWith("kotlin-")
},
libDir,
sourcesFile)
File(intellijUltimateSdkDir, "plugins").listFiles { it: File -> it.isDirectory }.forEach {
writeIvyXml(it.name, "intellijUltimate.plugin.${it.name}", files("$it/lib/"), File(it, "lib"), sourcesFile)
}
}
flatDeps.forEach {
writeIvyXml(it.name, it.name, files("$repoDir/${it.name}"), File(repoDir, it.name), sourcesFile)
}
if (intellijUltimateEnabled) {
val nodeJsBaseDir = "${`plugins-NodeJS`.name}/NodeJS/lib"
writeIvyXml("NodeJS", `plugins-NodeJS`.name, files("$repoDir/$nodeJsBaseDir"), File(repoDir, nodeJsBaseDir), sourcesFile)
}
}
}
val build by tasks.creating {
dependsOn(prepareIvyXmls)
}
val clean by tasks.creating(Delete::class) {
delete(customDepsRepoModulesDir)
delete(buildDir)
}

View File

@@ -1,3 +1,15 @@
pluginManagement {
repositories {
if (cacheRedirectorEnabled == 'true') {
maven {
url "https://cache-redirector.jetbrains.com/plugins.gradle.org/m2"
}
}
gradlePluginPortal()
}
}
include "prepare-deps:android-dx",
"prepare-deps:intellij-sdk"

View File

@@ -8,7 +8,6 @@ import org.gradle.api.file.DuplicatesStrategy
import org.gradle.api.file.FileCollection
import org.gradle.api.internal.artifacts.publish.ArchivePublishArtifact
import org.gradle.api.plugins.BasePluginConvention
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.javadoc.Javadoc
import org.gradle.jvm.tasks.Jar
import java.io.File
@@ -57,15 +56,14 @@ fun Project.noDefaultJar() {
defaultJarTask.enabled = false
defaultJarTask.actions = emptyList()
configurations.forEach { cfg ->
cfg.artifacts.removeAll {
(it as? ArchivePublishArtifact)?.archiveTask?.let { it == defaultJarTask } ?: false
cfg.artifacts.removeAll { artifact ->
artifact.file in defaultJarTask.outputs.files
}
}
}
}
fun<T> Project.runtimeJarArtifactBy(task: Task, artifactRef: T, body: ConfigurablePublishArtifact.() -> Unit = {}) {
fun Project.runtimeJarArtifactBy(task: Task, artifactRef: Any, body: ConfigurablePublishArtifact.() -> Unit = {}) {
addArtifact("archives", task, artifactRef, body)
addArtifact("runtimeJar", task, artifactRef, body)
configurations.findByName("runtime")?.let {
@@ -80,17 +78,17 @@ fun<T: Jar> Project.runtimeJar(task: T, body: T.() -> Unit = {}): T {
}
return task.apply {
setupPublicJar(project.the<BasePluginConvention>().archivesBaseName)
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
setDuplicatesStrategy(DuplicatesStrategy.EXCLUDE)
body()
project.runtimeJarArtifactBy(this, this)
}
}
fun Project.runtimeJar(taskName: String = "jar", body: Jar.() -> Unit = {}): Jar = runtimeJar(getOrCreateTask(taskName, body))
fun Project.runtimeJar(body: Jar.() -> Unit = {}): Jar = runtimeJar(getOrCreateTask("jar", body), { })
fun Project.sourcesJar(sourceSet: String? = "main", body: Jar.() -> Unit = {}): Jar =
getOrCreateTask("sourcesJar") {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
setDuplicatesStrategy(DuplicatesStrategy.EXCLUDE)
classifier = "sources"
try {
if (sourceSet != null) {
@@ -107,7 +105,7 @@ fun Project.sourcesJar(sourceSet: String? = "main", body: Jar.() -> Unit = {}):
fun Project.javadocJar(body: Jar.() -> Unit = {}): Jar =
getOrCreateTask("javadocJar") {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
setDuplicatesStrategy(DuplicatesStrategy.EXCLUDE)
classifier = "javadoc"
tasks.findByName("javadoc")?.let{ it as Javadoc }?.takeIf { it.enabled }?.let {
dependsOn(it)
@@ -202,14 +200,14 @@ fun Jar.setupPublicJar(baseName: String, classifier: String = "") {
}
fun<T> Project.addArtifact(configuration: Configuration, task: Task, artifactRef: T, body: ConfigurablePublishArtifact.() -> Unit = {}) {
fun Project.addArtifact(configuration: Configuration, task: Task, artifactRef: Any, body: ConfigurablePublishArtifact.() -> Unit = {}) {
artifacts.add(configuration.name, artifactRef) {
builtBy(task)
body()
}
}
fun<T> Project.addArtifact(configurationName: String, task: Task, artifactRef: T, body: ConfigurablePublishArtifact.() -> Unit = {}) =
fun Project.addArtifact(configurationName: String, task: Task, artifactRef: Any, body: ConfigurablePublishArtifact.() -> Unit = {}) =
addArtifact(configurations.getOrCreate(configurationName), task, artifactRef, body)
fun Project.cleanArtifacts() {

View File

@@ -0,0 +1,65 @@
/*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package tasks
import groovy.util.Node
import groovy.util.XmlParser
import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import java.io.File
import java.util.*
open class WriteCopyrightToFile : DefaultTask() {
@InputFile
var path = project.file("${project.rootDir}/.idea/copyright/apache.xml")
@OutputFile
var outputFile: File? = null
@Input
var commented: Boolean = true
@TaskAction
fun write() {
if (commented) {
outputFile!!.writeText(project.readCopyrightCommented())
} else {
outputFile!!.writeText(project.readCopyright())
}
}
fun Project.readCopyright(): String {
val file = rootDir.resolve(".idea/copyright/apache.xml")
assert(file.exists()) {
"File $file with copyright not found"
}
val xmlParser = XmlParser()
val node = xmlParser.parse(file)
assert(node.attribute("name") == "CopyrightManager") {
"Copyright format changed occasionally?"
}
val copyrightBlock = node.children().filterIsInstance<Node>().single()
val noticeNode = copyrightBlock.children().filterIsInstance<Node>().single { it.attribute("name") == "notice" }
return noticeNode.attribute("value").toString().replace("&#36;today.year", GregorianCalendar()[Calendar.YEAR].toString())
}
fun Project.readCopyrightCommented(): String {
return "/*\n" + readCopyright().prependIndent(" * ") + "\n */"
}
}

View File

@@ -65,7 +65,7 @@ private fun Project.compilerShadowJar(taskName: String, body: ShadowJar.() -> Un
return task<ShadowJar>(taskName) {
destinationDir = File(buildDir, "libs")
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
setDuplicatesStrategy(DuplicatesStrategy.EXCLUDE)
from(compilerJar)
body()
}
@@ -97,7 +97,7 @@ fun Project.embeddableCompilerDummyForDependenciesRewriting(taskName: String = "
return task<ShadowJar>(taskName) {
destinationDir = File(buildDir, "libs")
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
setDuplicatesStrategy(DuplicatesStrategy.EXCLUDE)
from(compilerDummyJar)
configureEmbeddableCompilerRelocation(withJavaxInject = false)
body()
@@ -119,7 +119,7 @@ fun Project.rewriteDepsToShadedJar(originalJarTask: Jar, shadowJarTask: Jar, bod
// which leads to the content of that JAR being excluded as well:
exclude { it.file == compilerDummyJarFile }
classifier = null
classifier = ""
body()
}
}

View File

@@ -54,7 +54,7 @@ fun Project.configureInstrumentation() {
val instrumentationClasspathCfg = configurations.create("instrumentationClasspath")
dependencies {
instrumentationClasspathCfg(intellijDep()) { includeJars("javac2", "jdom", "asm-all") }
instrumentationClasspathCfg(intellijDep()) { includeJars("javac2", "jdom", "asm-all", rootProject = rootProject) }
}
afterEvaluate {
@@ -105,12 +105,12 @@ open class IntelliJInstrumentCodeTask : ConventionTask() {
get() = project.files(sourceSet!!.allSource.srcDirs.filter { !sourceSet!!.resources.contains(it) && it.exists() })
@get:OutputDirectory
var output: File? = null
lateinit var output: File
@TaskAction
fun instrumentClasses() {
logger.info("input files are: ${originalClassesDirs?.joinToString("; ", transform = { "'${it.name}'${if (it.exists()) "" else " (does not exists)" }"})}")
output?.deleteRecursively()
output.deleteRecursively()
copyOriginalClasses()
val classpath = instrumentationClasspath!!

View File

@@ -54,7 +54,7 @@ fun Project.configureInstrumentation() {
val instrumentationClasspathCfg = configurations.create("instrumentationClasspath")
dependencies {
instrumentationClasspathCfg(intellijDep()) { includeJars("javac2", "jdom", "asm-all", "jgoodies-forms") }
instrumentationClasspathCfg(intellijDep()) { includeJars("javac2", "jdom", "asm-all", "jgoodies-forms", rootProject = rootProject) }
}
afterEvaluate {
@@ -105,12 +105,12 @@ open class IntelliJInstrumentCodeTask : ConventionTask() {
get() = project.files(sourceSet!!.allSource.srcDirs.filter { !sourceSet!!.resources.contains(it) && it.exists() })
@get:OutputDirectory
var output: File? = null
lateinit var output: File
@TaskAction
fun instrumentClasses() {
logger.info("input files are: ${originalClassesDirs?.joinToString("; ", transform = { "'${it.name}'${if (it.exists()) "" else " (does not exists)" }"})}")
output?.deleteRecursively()
output.deleteRecursively()
copyOriginalClasses()
val classpath = instrumentationClasspath!!

View File

@@ -0,0 +1,57 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
import org.gradle.api.Project
import org.gradle.api.artifacts.dsl.RepositoryHandler
import org.gradle.api.artifacts.repositories.MavenArtifactRepository
import java.net.URI
// https://youtrack.jetbrains.com/issue/ADM-23180
val mirroredUrls = listOf(
"https://dl.bintray.com/groovy/maven",
"https://dl.bintray.com/kotlin/kotlin-dev",
"https://dl.bintray.com/kotlin/kotlin-eap",
"https://dl.google.com/dl/android/maven2",
"https://dl.google.com/go",
"https://download.jetbrains.com",
"https://jcenter.bintray.com",
"https://jetbrains.bintray.com/dekaf",
"https://jetbrains.bintray.com/intellij-jdk",
"https://jetbrains.bintray.com/intellij-plugin-service",
"https://jetbrains.bintray.com/intellij-third-party-dependencies",
"https://jetbrains.bintray.com/markdown",
"https://jetbrains.bintray.com/teamcity-rest-client",
"https://jetbrains.bintray.com/test-discovery",
"https://jitpack.io",
"https://maven.exasol.com/artifactory/exasol-releases",
"https://plugins.gradle.org/m2",
"https://plugins.jetbrains.com/maven",
"https://repo.grails.org/grails/core",
"https://repo.jenkins-ci.org/releases",
"https://repo.spring.io/milestone",
"https://repo1.maven.org/maven2",
"https://services.gradle.org",
"https://www.jetbrains.com/intellij-repository",
"https://www.myget.org/F/intellij-go-snapshots/maven",
"https://www.myget.org/F/rd-snapshots/maven"
)
fun URI.toCacheRedirectorUri() = URI("https://cache-redirector.jetbrains.com/$host/$path")
fun RepositoryHandler.redirect() = filterIsInstance<MavenArtifactRepository>().forEach { repository ->
val uri = repository.url
if (uri.toString().trimEnd('/') in mirroredUrls) {
repository.url = uri.toCacheRedirectorUri()
}
}
fun Project.cacheRedirectorEnabled(): Boolean = findProperty("cacheRedirectorEnabled")?.toString()?.toBoolean() == true
fun RepositoryHandler.withRedirector(project: Project, configuration: RepositoryHandler.() -> Unit) {
configuration()
if (project.cacheRedirectorEnabled()) {
redirect()
}
}

View File

@@ -9,7 +9,7 @@ import net.rubygrapefruit.platform.WindowsRegistry.Key.HKEY_LOCAL_MACHINE
import org.gradle.internal.os.OperatingSystem
enum class JdkMajorVersion {
JDK_16, JDK_17, JDK_18, JDK_9, JDK_10
JDK_16, JDK_17, JDK_18, JDK_9, JDK_10, JDK_11
}
val jdkAlternativeVarNames = mapOf(JdkMajorVersion.JDK_9 to listOf("JDK_19"))

View File

@@ -173,7 +173,7 @@ fun generateKotlinPluginArtifactFile(rootProject: Project): PFile {
for (dependencyInfo in listOf(configuration).collectDependencies()) {
val dependency = (dependencyInfo as? DependencyInfo.ResolvedDependencyInfo)?.dependency ?: continue
if (dependency.configuration == "runtimeElements") {
if (dependency.isModuleDependency) {
archiveForJar.add(ModuleOutput(dependency.moduleName + ".src"))
} else if (dependency.configuration == "tests-jar" || dependency.configuration == "jpsTest") {
error("Test configurations are not allowed here")

View File

@@ -235,8 +235,9 @@ private fun parseSourceRoots(project: Project): List<PSourceRoot> {
return emptyList()
}
val kotlinTasksBySourceSet = project.tasks
.filter { it.name.startsWith("compile") && it.name.endsWith("Kotlin") }
val kotlinTasksBySourceSet = project.tasks.names
.filter { it.startsWith("compile") && it.endsWith("Kotlin") }
.map { project.tasks.getByName(it) }
.associateBy { it.invokeInternal("getSourceSetName") }
val sourceRoots = mutableListOf<PSourceRoot>()
@@ -413,7 +414,7 @@ private fun ParserContext.parseDependencies(project: Project, forTests: Boolean)
}
}
mainRoots += if (dependency.configuration == "runtimeElements" && scope != Scope.TEST) {
mainRoots += if (dependency.isModuleDependency && scope != Scope.TEST) {
POrderRoot(PDependency.Module(dependency.moduleName + ".src"), scope)
} else if (dependency.configuration == "tests-jar" || dependency.configuration == "jpsTest") {
POrderRoot(
@@ -489,6 +490,9 @@ sealed class DependencyInfo(val scope: Scope) {
class CustomDependencyInfo(scope: Scope, val files: List<File>) : DependencyInfo(scope)
}
val ResolvedDependency.isModuleDependency
get() = configuration in JpsCompatiblePlugin.MODULE_CONFIGURATIONS
fun List<CollectedConfiguration>.collectDependencies(): List<DependencyInfo> {
val dependencies = mutableListOf<DependencyInfo>()
@@ -531,4 +535,4 @@ private val Project.sourceSets: SourceSetContainer
lateinit var result: SourceSetContainer
project.configure<JavaPluginConvention> { result = sourceSets }
return result
}
}

View File

@@ -20,6 +20,8 @@ class PillConfigurablePlugin : Plugin<Project> {
class JpsCompatiblePlugin : Plugin<Project> {
companion object {
val MODULE_CONFIGURATIONS = arrayOf("apiElements", "runtimeElements")
private fun mapper(module: String, vararg configurations: String): DependencyMapper {
return DependencyMapper("org.jetbrains.kotlin", module, *configurations) { MappedDependency(PDependency.Library(module)) }
}
@@ -27,10 +29,10 @@ class JpsCompatiblePlugin : Plugin<Project> {
private fun getDependencyMappers(projectLibraries: List<PLibrary>): List<DependencyMapper> {
val mappersForKotlinLibrariesExeptStdlib = projectLibraries
.filter { it.name != "kotlin-stdlib" }
.mapTo(mutableListOf()) { mapper(it.name, "default", "distJar", "runtimeElements") }
.mapTo(mutableListOf()) { mapper(it.name, "default", "distJar", *MODULE_CONFIGURATIONS) }
return mappersForKotlinLibrariesExeptStdlib + listOf(
DependencyMapper("org.jetbrains.kotlin", "kotlin-stdlib", "distJar", "runtimeElements") {
DependencyMapper("org.jetbrains.kotlin", "kotlin-stdlib", "distJar", *MODULE_CONFIGURATIONS) {
MappedDependency(
PDependency.Library("kotlin-stdlib"),
listOf(PDependency.Library("annotations-13.0"))
@@ -42,13 +44,13 @@ class JpsCompatiblePlugin : Plugin<Project> {
listOf(PDependency.Library("annotations-13.0"))
)
},
DependencyMapper("org.jetbrains.kotlin", "kotlin-reflect-api", "runtimeElements") {
DependencyMapper("org.jetbrains.kotlin", "kotlin-reflect-api", *MODULE_CONFIGURATIONS) {
MappedDependency(PDependency.Library("kotlin-reflect"))
},
DependencyMapper("org.jetbrains.kotlin", "kotlin-compiler-embeddable", "runtimeJar") { null },
DependencyMapper("org.jetbrains.kotlin", "kotlin-stdlib-js", "distJar") { null },
DependencyMapper("org.jetbrains.kotlin", "kotlin-compiler", "runtimeJar") { null },
DependencyMapper("org.jetbrains.kotlin", "compiler", "runtimeElements") { null },
DependencyMapper("org.jetbrains.kotlin", "compiler", *MODULE_CONFIGURATIONS) { null },
DependencyMapper("kotlin.build.custom.deps", "android", "default") { dep ->
val (sdkCommon, otherJars) = dep.moduleArtifacts.map { it.file }.partition { it.name == "sdk-common.jar" }
val mainLibrary = PDependency.ModuleLibrary(PLibrary(dep.moduleName, otherJars))

View File

@@ -108,7 +108,7 @@ open class PublishedKotlinModule : Plugin<Project> {
val password: String? by preparePublication.extra
val repoUrl: String by preparePublication.extra
var repository: MavenRemoteRepository by Delegates.notNull()
var repository by Delegates.notNull<MavenRemoteRepository>()
repositories {
withConvention(MavenRepositoryHandlerConvention::class) {

View File

@@ -137,7 +137,11 @@ class CodegenTestsOnAndroidGenerator private constructor(private val pathManager
writeFiles(
rawFiles.map {
CodegenTestFiles.create(it.first, it.second, environment.project).psiFile
try {
CodegenTestFiles.create(it.first, it.second, environment.project).psiFile
} catch (e: Throwable) {
throw RuntimeException("Error on processing ${it.first}:\n${it.second}", e)
}
}, environment
)
Disposer.dispose(disposable)
@@ -202,6 +206,10 @@ class CodegenTestsOnAndroidGenerator private constructor(private val pathManager
if (fullFileText.contains("// WITH_COROUTINES")) continue
// TODO: Support jvm assertions
if (fullFileText.contains("// KOTLIN_CONFIGURATION_FLAGS: ASSERTIONS_MODE=jvm")) continue
// TODO: support JVM 8 test with D8
if (fullFileText.contains("// JVM_TARGET")) continue
// TODO: support SKIP_JDK6 on new platforms
if (fullFileText.contains("// SKIP_JDK6")) continue
if (hasBoxMethod(fullFileText)) {
val testFiles = createTestFiles(file, fullFileText)

View File

@@ -23,6 +23,7 @@ import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.checkers.ExpectedActualDeclarationChecker
import org.jetbrains.kotlin.resolve.multiplatform.ExpectedActualResolver
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.DFS
object CodegenUtil {
@JvmStatic
@@ -200,16 +201,25 @@ object CodegenUtil {
trace: DiagnosticSink?
): List<ValueParameterDescriptor> {
if (descriptor.isActual) {
val actualParameters = descriptor.valueParameters
if (actualParameters.any { it.declaresOrInheritsDefaultValue() }) {
// This is incorrect code: actual function cannot have default values, they should be declared in the expected function.
// But until KT-22818 is fixed, we need to provide a workaround for the exception that happens on complex default values
// in the expected function. One may suppress the error then, and declare default values _both_ in expect and actual.
// With this code, we'll generate actual default values if they're present, and expected default values otherwise.
return actualParameters
}
val expected = CodegenUtil.findExpectedFunctionForActual(descriptor)
if (expected != null && expected.valueParameters.any(ValueParameterDescriptor::declaresDefaultValue)) {
val element = DescriptorToSourceUtils.descriptorToDeclaration(expected)
if (element == null) {
if (trace != null) {
val actualDeclaration = DescriptorToSourceUtils.descriptorToDeclaration(descriptor)
?: error("Not a source declaration: $descriptor")
?: error("Not a source declaration: $descriptor")
trace.report(Errors.EXPECTED_FUNCTION_SOURCE_WITH_DEFAULT_ARGUMENTS_NOT_FOUND.on(actualDeclaration))
}
return descriptor.valueParameters
return actualParameters
}
return expected.valueParameters
@@ -218,12 +228,14 @@ object CodegenUtil {
return descriptor.valueParameters
}
// This function is private here because no one is supposed to use it except for the hack above.
// Please use ValueParameterDescriptor.hasDefaultValue instead.
private fun ValueParameterDescriptor.declaresOrInheritsDefaultValue(): Boolean {
return DFS.ifAny(
listOf(this),
{ current -> current.overriddenDescriptors.map(ValueParameterDescriptor::getOriginal) },
{ it.declaresDefaultValue() }
)
}
}
fun DeclarationDescriptor.isTopLevelInPackage(name: String, packageName: String): Boolean {
if (name != this.name.asString()) return false
val containingDeclaration = containingDeclaration as? PackageFragmentDescriptor ?: return false
val packageFqName = containingDeclaration.fqName.asString()
return packageName == packageFqName
}

View File

@@ -9,6 +9,7 @@ import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.config.coroutinesIntrinsicsPackageFqName
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.isTopLevelInPackage
import org.jetbrains.kotlin.name.Name
val COROUTINE_SUSPENDED_NAME = Name.identifier("COROUTINE_SUSPENDED")

View File

@@ -48,7 +48,7 @@ class AccessorForFunctionDescriptor(
isSuspend = calleeDescriptor.isSuspend
if (calleeDescriptor.getUserData(INITIAL_DESCRIPTOR_FOR_SUSPEND_FUNCTION) != null) {
userDataMap = LinkedHashMap<FunctionDescriptor.UserDataKey<*>, Any>()
userDataMap = LinkedHashMap<CallableDescriptor.UserDataKey<*>, Any>()
userDataMap[INITIAL_DESCRIPTOR_FOR_SUSPEND_FUNCTION] =
calleeDescriptor.getUserData(INITIAL_DESCRIPTOR_FOR_SUSPEND_FUNCTION)
}

View File

@@ -181,7 +181,9 @@ public abstract class AnnotationCodegen {
}
private static boolean isInvisibleFromTheOutside(@Nullable DeclarationDescriptor descriptor) {
if (descriptor instanceof CallableMemberDescriptor && KotlinTypeMapper.isAccessor((CallableMemberDescriptor) descriptor)) return false;
if (descriptor instanceof CallableMemberDescriptor && KotlinTypeMapper.isAccessor((CallableMemberDescriptor) descriptor)) {
return true;
}
if (descriptor instanceof MemberDescriptor) {
return AsmUtil.getVisibilityAccessFlag((MemberDescriptor) descriptor) == Opcodes.ACC_PRIVATE;
}
@@ -347,7 +349,7 @@ public abstract class AnnotationCodegen {
private String getAnnotationArgumentJvmName(@Nullable ClassDescriptor annotationClass, @NotNull Name parameterName) {
if (annotationClass == null) return parameterName.asString();
Collection<PropertyDescriptor> variables =
Collection<? extends PropertyDescriptor> variables =
annotationClass.getUnsubstitutedMemberScope().getContributedVariables(parameterName, NoLookupLocation.FROM_BACKEND);
if (variables.size() != 1) return parameterName.asString();
@@ -359,7 +361,7 @@ public abstract class AnnotationCodegen {
@NotNull ConstantValue<?> value,
@NotNull AnnotationVisitor annotationVisitor
) {
AnnotationArgumentVisitor argumentVisitor = new AnnotationArgumentVisitor<Void, Void>() {
AnnotationArgumentVisitor<Void, Void> argumentVisitor = new AnnotationArgumentVisitor<Void, Void>() {
@Override
public Void visitLongValue(@NotNull LongValue value, Void data) {
return visitSimpleValue(value);

View File

@@ -26,6 +26,7 @@ import org.jetbrains.kotlin.config.JvmTarget;
import org.jetbrains.kotlin.config.LanguageFeature;
import org.jetbrains.kotlin.config.LanguageVersionSettings;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.incremental.components.NoLookupLocation;
import org.jetbrains.kotlin.lexer.KtTokens;
import org.jetbrains.kotlin.load.java.JavaVisibilities;
import org.jetbrains.kotlin.load.java.JvmAnnotationNames;
@@ -407,6 +408,9 @@ public class AsmUtil {
if (ExpectedActualDeclarationChecker.isOptionalAnnotationClass(descriptor)) {
return NO_FLAG_PACKAGE_PRIVATE;
}
if (descriptor.getKind() == ClassKind.ENUM_ENTRY) {
return NO_FLAG_PACKAGE_PRIVATE;
}
if (descriptor.getVisibility() == Visibilities.PUBLIC ||
descriptor.getVisibility() == Visibilities.PROTECTED ||
// TODO: should be package private, but for now Kotlin's reflection can't access members of such classes
@@ -479,6 +483,10 @@ public class AsmUtil {
DeclarationDescriptor containingDeclaration = memberDescriptor.getContainingDeclaration();
Visibility memberVisibility = memberDescriptor.getVisibility();
if (JvmCodegenUtil.isNonIntrinsicPrivateCompanionObjectInInterface(memberDescriptor)) {
return ACC_PUBLIC;
}
if (memberDescriptor instanceof FunctionDescriptor &&
isInlineClassWrapperConstructor((FunctionDescriptor) memberDescriptor, kind)) {
return ACC_PRIVATE;
@@ -546,16 +554,8 @@ public class AsmUtil {
return NO_FLAG_PACKAGE_PRIVATE;
}
// the following code is only for PRIVATE visibility of member
if (memberDescriptor instanceof ConstructorDescriptor) {
if (isEnumEntry(containingDeclaration)) {
return NO_FLAG_PACKAGE_PRIVATE;
}
if (isEnumClass(containingDeclaration)) {
//TODO: should be ACC_PRIVATE
// see http://youtrack.jetbrains.com/issue/KT-2680
return ACC_PROTECTED;
}
if (memberDescriptor instanceof ConstructorDescriptor && isEnumEntry(containingDeclaration)) {
return NO_FLAG_PACKAGE_PRIVATE;
}
return null;
@@ -639,10 +639,18 @@ public class AsmUtil {
) {
assert !info.isStatic();
Type fieldType = info.getFieldType();
KotlinType fieldKotlinType = info.getFieldKotlinType();
KotlinType nullableAny;
if (fieldKotlinType != null) {
nullableAny = fieldKotlinType.getConstructor().getBuiltIns().getNullableAnyType();
} else {
nullableAny = null;
}
iv.load(ownerIndex, info.getOwnerType());//this
if (cast) {
iv.load(index, AsmTypes.OBJECT_TYPE); //param
StackValue.coerce(AsmTypes.OBJECT_TYPE, fieldType, iv);
StackValue.coerce(AsmTypes.OBJECT_TYPE, nullableAny, fieldType, fieldKotlinType, iv);
} else {
iv.load(index, fieldType); //param
}
@@ -658,8 +666,23 @@ public class AsmUtil {
}
public static void genInvokeAppendMethod(@NotNull InstructionAdapter v, @NotNull Type type, @Nullable KotlinType kotlinType) {
genInvokeAppendMethod(v, type, kotlinType, null);
}
public static void genInvokeAppendMethod(
@NotNull InstructionAdapter v,
@NotNull Type type,
@Nullable KotlinType kotlinType,
@Nullable KotlinTypeMapper typeMapper
) {
Type appendParameterType;
if (kotlinType != null && InlineClassesUtilsKt.isInlineClassType(kotlinType)) {
CallableMethod specializedToString = getSpecializedToStringCallableMethodOrNull(kotlinType, typeMapper);
if (specializedToString != null) {
specializedToString.genInvokeInstruction(v);
appendParameterType = AsmTypes.JAVA_STRING_TYPE;
}
else if (kotlinType != null && InlineClassesUtilsKt.isInlineClassType(kotlinType)) {
appendParameterType = OBJECT_TYPE;
SimpleType nullableAnyType = kotlinType.getConstructor().getBuiltIns().getNullableAnyType();
StackValue.coerce(type, kotlinType, appendParameterType, nullableAnyType, v);
@@ -674,9 +697,17 @@ public class AsmUtil {
public static StackValue genToString(
@NotNull StackValue receiver,
@NotNull Type receiverType,
@Nullable KotlinType receiverKotlinType
@Nullable KotlinType receiverKotlinType,
@Nullable KotlinTypeMapper typeMapper
) {
return StackValue.operation(JAVA_STRING_TYPE, v -> {
CallableMethod specializedToString = getSpecializedToStringCallableMethodOrNull(receiverKotlinType, typeMapper);
if (specializedToString != null) {
receiver.put(receiverType, receiverKotlinType, v);
specializedToString.genInvokeInstruction(v);
return null;
}
Type type;
KotlinType kotlinType;
if (receiverKotlinType != null && InlineClassesUtilsKt.isInlineClassType(receiverKotlinType)) {
@@ -694,6 +725,36 @@ public class AsmUtil {
});
}
@Nullable
private static CallableMethod getSpecializedToStringCallableMethodOrNull(
@Nullable KotlinType receiverKotlinType,
@Nullable KotlinTypeMapper typeMapper
) {
if (typeMapper == null) return null;
if (receiverKotlinType == null) return null;
if (!InlineClassesUtilsKt.isInlineClassType(receiverKotlinType)) return null;
if (receiverKotlinType.isMarkedNullable()) return null;
DeclarationDescriptor receiverTypeDescriptor = receiverKotlinType.getConstructor().getDeclarationDescriptor();
assert receiverTypeDescriptor instanceof ClassDescriptor && ((ClassDescriptor) receiverTypeDescriptor).isInline() :
"Inline class type expected: " + receiverKotlinType;
ClassDescriptor receiverClassDescriptor = (ClassDescriptor) receiverTypeDescriptor;
FunctionDescriptor toStringDescriptor = receiverClassDescriptor.getUnsubstitutedMemberScope()
.getContributedFunctions(Name.identifier("toString"), NoLookupLocation.FROM_BACKEND)
.stream()
.filter(
f -> f.getValueParameters().size() == 0
&& KotlinBuiltIns.isString(f.getReturnType())
&& f.getDispatchReceiverParameter() != null
&& f.getExtensionReceiverParameter() == null
)
.findFirst()
.orElseThrow(() -> new AssertionError("'toString' not found in member scope of " + receiverClassDescriptor));
return typeMapper.mapToCallableMethod(toStringDescriptor, false, OwnerKind.ERASED_INLINE_CLASS);
}
static void genHashCode(MethodVisitor mv, InstructionAdapter iv, Type type, JvmTarget jvmTarget) {
if (type.getSort() == Type.ARRAY) {
Type elementType = correctElementType(type);
@@ -907,19 +968,20 @@ public class AsmUtil {
if (state.isCallAssertionsDisabled()) return stackValue;
if (runtimeAssertionInfo == null || !runtimeAssertionInfo.getNeedNotNullAssertion()) return stackValue;
return new StackValue(stackValue.type) {
return new StackValue(stackValue.type, stackValue.kotlinType) {
@Override
public void putSelector(@NotNull Type type, @Nullable KotlinType kotlinType, @NotNull InstructionAdapter v) {
Type innerType = stackValue.type;
stackValue.put(innerType, v);
KotlinType innerKotlinType = stackValue.kotlinType;
stackValue.put(innerType, innerKotlinType, v);
if (innerType.getSort() == Type.OBJECT || innerType.getSort() == Type.ARRAY) {
v.dup();
v.visitLdcInsn(runtimeAssertionInfo.getMessage());
v.invokestatic(IntrinsicMethods.INTRINSICS_CLASS_NAME, "checkExpressionValueIsNotNull",
"(Ljava/lang/Object;Ljava/lang/String;)V", false);
}
StackValue.coerce(innerType, type, v);
StackValue.coerce(innerType, innerKotlinType, type, kotlinType, v);
}
};
}

View File

@@ -5,11 +5,11 @@
package org.jetbrains.kotlin.codegen
import org.jetbrains.kotlin.backend.common.isTopLevelInPackage
import org.jetbrains.kotlin.codegen.coroutines.createCustomCopy
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper
import org.jetbrains.kotlin.config.JVMAssertionsMode
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.isTopLevelInPackage
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.BindingTraceContext
import org.jetbrains.kotlin.resolve.DelegatingBindingTrace

View File

@@ -26,14 +26,14 @@ interface CallGenerator {
class DefaultCallGenerator(private val codegen: ExpressionCodegen) : CallGenerator {
override fun genCallInner(
callableMethod: Callable,
resolvedCall: ResolvedCall<*>?,
callDefault: Boolean,
codegen: ExpressionCodegen) {
callableMethod: Callable,
resolvedCall: ResolvedCall<*>?,
callDefault: Boolean,
codegen: ExpressionCodegen
) {
if (!callDefault) {
callableMethod.genInvokeInstruction(codegen.v)
}
else {
} else {
(callableMethod as CallableMethod).genInvokeDefaultInstruction(codegen.v)
}
}
@@ -66,15 +66,17 @@ interface CallGenerator {
}
val value = codegen.gen(argumentExpression)
value.put(parameterType, valueParameterDescriptor.original.type, v)
value.put(parameterType, valueParameterDescriptor.unsubstitutedType, v)
if (isVarargInvoke) {
v.astore(OBJECT_TYPE)
}
}
override fun putCapturedValueOnStack(
stackValue: StackValue, valueType: Type, paramIndex: Int) {
private val ValueParameterDescriptor.unsubstitutedType
get() = containingDeclaration.original.valueParameters[index].type
override fun putCapturedValueOnStack(stackValue: StackValue, valueType: Type, paramIndex: Int) {
stackValue.put(stackValue.type, stackValue.kotlinType, codegen.v)
}
@@ -117,26 +119,28 @@ interface CallGenerator {
fun genCallInner(callableMethod: Callable, resolvedCall: ResolvedCall<*>?, callDefault: Boolean, codegen: ExpressionCodegen)
fun genValueAndPut(
valueParameterDescriptor: ValueParameterDescriptor,
argumentExpression: KtExpression,
parameterType: Type,
parameterIndex: Int)
valueParameterDescriptor: ValueParameterDescriptor,
argumentExpression: KtExpression,
parameterType: Type,
parameterIndex: Int
)
fun putValueIfNeeded(
parameterType: JvmKotlinType,
value: StackValue) {
fun putValueIfNeeded(parameterType: JvmKotlinType, value: StackValue) {
putValueIfNeeded(parameterType, value, ValueKind.GENERAL)
}
fun putValueIfNeeded(
parameterType: JvmKotlinType,
value: StackValue,
kind: ValueKind = ValueKind.GENERAL,
parameterIndex: Int = -1)
parameterType: JvmKotlinType,
value: StackValue,
kind: ValueKind = ValueKind.GENERAL,
parameterIndex: Int = -1
)
fun putCapturedValueOnStack(
stackValue: StackValue,
valueType: Type, paramIndex: Int)
stackValue: StackValue,
valueType: Type,
paramIndex: Int
)
fun processAndPutHiddenParameters(justProcess: Boolean)

View File

@@ -5,11 +5,13 @@
package org.jetbrains.kotlin.codegen;
import com.intellij.psi.PsiElement;
import kotlin.collections.CollectionsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.backend.common.CodegenUtil;
import org.jetbrains.kotlin.backend.common.bridges.ImplKt;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.codegen.context.ClassContext;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.descriptors.*;
@@ -18,15 +20,24 @@ import org.jetbrains.kotlin.psi.synthetics.SyntheticClassOrObjectDescriptor;
import org.jetbrains.kotlin.psi.synthetics.SyntheticClassOrObjectDescriptorKt;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.resolve.InlineClassesUtilsKt;
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin;
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature;
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter;
import org.jetbrains.kotlin.resolve.scopes.MemberScope;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.org.objectweb.asm.Type;
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
import org.jetbrains.org.objectweb.asm.commons.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.*;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isJvmInterface;
import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.enumEntryNeedSubclass;
import static org.jetbrains.kotlin.resolve.DescriptorToSourceUtils.descriptorToDeclaration;
import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.OBJECT_TYPE;
import static org.jetbrains.kotlin.resolve.jvm.annotations.JvmAnnotationUtilKt.hasJvmDefaultAnnotation;
import static org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKind.CLASS_MEMBER_DELEGATION_TO_DEFAULT_IMPL;
public abstract class ClassBodyCodegen extends MemberCodegen<KtPureClassOrObject> {
@NotNull
@@ -204,4 +215,121 @@ public abstract class ClassBodyCodegen extends MemberCodegen<KtPureClassOrObject
protected ClassDescriptor classForInnerClassRecord() {
return InnerClassConsumer.Companion.classForInnerClassRecord(descriptor, false);
}
protected void generateDelegatesToDefaultImpl() {
if (isJvmInterface(descriptor)) return;
for (Map.Entry<FunctionDescriptor, FunctionDescriptor> entry : CodegenUtil.getNonPrivateTraitMethods(descriptor).entrySet()) {
FunctionDescriptor interfaceFun = entry.getKey();
//skip java 8 default methods
if (!CodegenUtilKt.isDefinitelyNotDefaultImplsMethod(interfaceFun) && !hasJvmDefaultAnnotation(interfaceFun)) {
generateDelegationToDefaultImpl(interfaceFun, entry.getValue());
}
}
}
private void generateDelegationToDefaultImpl(@NotNull FunctionDescriptor interfaceFun, @NotNull FunctionDescriptor inheritedFun) {
functionCodegen.generateMethod(
new JvmDeclarationOrigin(CLASS_MEMBER_DELEGATION_TO_DEFAULT_IMPL, descriptorToDeclaration(interfaceFun), interfaceFun),
inheritedFun,
new FunctionGenerationStrategy.CodegenBased(state) {
@Override
public void doGenerateBody(@NotNull ExpressionCodegen codegen, @NotNull JvmMethodSignature signature) {
DeclarationDescriptor containingDeclaration = interfaceFun.getContainingDeclaration();
if (!DescriptorUtils.isInterface(containingDeclaration)) return;
DeclarationDescriptor declarationInheritedFun = inheritedFun.getContainingDeclaration();
PsiElement classForInheritedFun = descriptorToDeclaration(declarationInheritedFun);
if (classForInheritedFun instanceof KtDeclaration) {
codegen.markLineNumber((KtElement) classForInheritedFun, false);
}
ClassDescriptor containingTrait = (ClassDescriptor) containingDeclaration;
Type traitImplType = typeMapper.mapDefaultImpls(containingTrait);
FunctionDescriptor originalInterfaceFun = interfaceFun.getOriginal();
Method traitMethod = typeMapper.mapAsmMethod(originalInterfaceFun, OwnerKind.DEFAULT_IMPLS);
putArgumentsOnStack(codegen, signature, traitMethod);
InstructionAdapter iv = codegen.v;
if (KotlinBuiltIns.isCloneable(containingTrait) && traitMethod.getName().equals("clone")) {
// A special hack for Cloneable: there's no kotlin/Cloneable$DefaultImpls class at runtime,
// and its 'clone' method is actually located in java/lang/Object
iv.invokespecial("java/lang/Object", "clone", "()Ljava/lang/Object;", false);
}
else {
iv.invokestatic(traitImplType.getInternalName(), traitMethod.getName(), traitMethod.getDescriptor(), false);
}
Type returnType = signature.getReturnType();
StackValue.onStack(traitMethod.getReturnType(), originalInterfaceFun.getReturnType()).put(returnType, iv);
iv.areturn(returnType);
}
private void putArgumentsOnStack(
@NotNull ExpressionCodegen codegen,
@NotNull JvmMethodSignature signature,
@NotNull Method defaultImplsMethod
) {
InstructionAdapter iv = codegen.v;
Type[] myArgTypes = signature.getAsmMethod().getArgumentTypes();
Type[] toArgTypes = defaultImplsMethod.getArgumentTypes();
boolean isErasedInlineClass =
InlineClassesUtilsKt.isInlineClass(descriptor) && kind == OwnerKind.ERASED_INLINE_CLASS;
int myArgI = 0;
int argVar = 0;
Type receiverType = typeMapper.mapType(descriptor);
KotlinType interfaceKotlinType = ((ClassDescriptor) inheritedFun.getContainingDeclaration()).getDefaultType();
StackValue.local(argVar, receiverType, descriptor.getDefaultType())
.put(OBJECT_TYPE, interfaceKotlinType, iv);
if (isErasedInlineClass) myArgI++;
argVar += receiverType.getSize();
int toArgI = 1;
List<ParameterDescriptor> myParameters = getParameters(inheritedFun);
List<ParameterDescriptor> toParameters = getParameters(interfaceFun);
assert myParameters.size() == toParameters.size() :
"Inconsistent value parameters between delegating fun " + inheritedFun +
"and interface fun " + interfaceFun;
Iterator<ParameterDescriptor> myParametersIterator = myParameters.iterator();
Iterator<ParameterDescriptor> toParametersIterator = toParameters.iterator();
for (; myArgI < myArgTypes.length; myArgI++, toArgI++) {
Type myArgType = myArgTypes[myArgI];
Type toArgType = toArgTypes[toArgI];
KotlinType myArgKotlinType = myParametersIterator.hasNext() ? myParametersIterator.next().getType() : null;
KotlinType toArgKotlinType = toParametersIterator.hasNext() ? toParametersIterator.next().getType() : null;
StackValue.local(argVar, myArgType, myArgKotlinType)
.put(toArgType, toArgKotlinType, iv);
argVar += myArgType.getSize();
}
assert toArgI == toArgTypes.length :
"Invalid trait implementation signature: " + signature +
" vs " + defaultImplsMethod + " for " + interfaceFun;
}
private List<ParameterDescriptor> getParameters(FunctionDescriptor functionDescriptor) {
List<ParameterDescriptor> valueParameterDescriptors =
new ArrayList<>(functionDescriptor.getValueParameters().size() + 1);
ReceiverParameterDescriptor extensionReceiverParameter = functionDescriptor.getExtensionReceiverParameter();
if (extensionReceiverParameter != null) {
valueParameterDescriptors.add(extensionReceiverParameter);
}
valueParameterDescriptors.addAll(functionDescriptor.getValueParameters());
return valueParameterDescriptors;
}
}
);
}
}

View File

@@ -27,7 +27,8 @@ import org.jetbrains.annotations.TestOnly;
import org.jetbrains.kotlin.backend.common.output.OutputFile;
import org.jetbrains.kotlin.backend.common.output.OutputFileCollection;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.config.AnalysisFlag;
import org.jetbrains.kotlin.config.AnalysisFlags;
import org.jetbrains.kotlin.config.JvmAnalysisFlags;
import org.jetbrains.kotlin.descriptors.ClassDescriptor;
import org.jetbrains.kotlin.descriptors.DescriptorUtilKt;
import org.jetbrains.kotlin.descriptors.ModuleDescriptor;
@@ -113,7 +114,7 @@ public class ClassFileFactory implements OutputFileCollection {
part.addTo(builder);
}
List<String> experimental = state.getLanguageVersionSettings().getFlag(AnalysisFlag.getExperimental());
List<String> experimental = state.getLanguageVersionSettings().getFlag(AnalysisFlags.getExperimental());
if (!experimental.isEmpty()) {
writeExperimentalMarkers(state.getModule(), builder, experimental);
}
@@ -124,7 +125,7 @@ public class ClassFileFactory implements OutputFileCollection {
@Override
public byte[] asBytes(ClassBuilderFactory factory) {
int flags = 0;
if (state.getLanguageVersionSettings().getFlag(AnalysisFlag.getStrictMetadataVersionSemantics())) {
if (state.getLanguageVersionSettings().getFlag(JvmAnalysisFlags.getStrictMetadataVersionSemantics())) {
flags |= ModuleMapping.STRICT_METADATA_VERSION_SEMANTICS_FLAG;
}
return ModuleMappingKt.serializeToByteArray(moduleProto, state.getMetadataVersion(), flags);

View File

@@ -37,6 +37,7 @@ import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKt;
import org.jetbrains.kotlin.resolve.scopes.MemberScope;
import org.jetbrains.kotlin.serialization.DescriptorSerializer;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.kotlin.types.SimpleType;
import org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils;
import org.jetbrains.kotlin.util.OperatorNameConventions;
import org.jetbrains.org.objectweb.asm.MethodVisitor;
@@ -390,8 +391,8 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
DeclarationDescriptor container = descriptor.getContainingDeclaration();
if (container instanceof ClassDescriptor) {
// TODO: getDefaultType() here is wrong and won't work for arrays
putJavaLangClassInstance(iv, state.getTypeMapper().mapType(((ClassDescriptor) container).getDefaultType()));
// TODO: would it work for arrays?
putJavaLangClassInstance(iv, state.getTypeMapper().mapClass((ClassDescriptor) container));
}
else if (container instanceof PackageFragmentDescriptor) {
iv.aconst(state.getTypeMapper().mapOwner(descriptor));
@@ -437,13 +438,25 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
mv.visitCode();
InstructionAdapter iv = new InstructionAdapter(mv);
Pair<Integer, Type> receiverIndexAndType =
Pair<Integer, FieldInfo> receiverIndexAndFieldInfo =
CallableReferenceUtilKt.generateClosureFieldsInitializationFromParameters(iv, closure, args);
if (shouldHaveBoundReferenceReceiver && receiverIndexAndType == null) {
if (shouldHaveBoundReferenceReceiver && receiverIndexAndFieldInfo == null) {
throw new AssertionError("No bound reference receiver in constructor parameters: " + args);
}
int boundReferenceReceiverParameterIndex = shouldHaveBoundReferenceReceiver ? receiverIndexAndType.getFirst() : -1;
Type boundReferenceReceiverType = shouldHaveBoundReferenceReceiver ? receiverIndexAndType.getSecond() : null;
int boundReceiverParameterIndex;
Type boundReceiverType;
KotlinType boundReceiverKotlinType;
if (shouldHaveBoundReferenceReceiver) {
boundReceiverParameterIndex = receiverIndexAndFieldInfo.getFirst();
boundReceiverType = receiverIndexAndFieldInfo.getSecond().getFieldType();
boundReceiverKotlinType = receiverIndexAndFieldInfo.getSecond().getFieldKotlinType();
}
else {
boundReceiverParameterIndex = -1;
boundReceiverType = null;
boundReceiverKotlinType = null;
}
iv.load(0, superClassAsmType);
@@ -453,7 +466,7 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
int arity = calculateArity();
iv.iconst(arity);
if (shouldHaveBoundReferenceReceiver) {
CallableReferenceUtilKt.loadBoundReferenceReceiverParameter(iv, boundReferenceReceiverParameterIndex, boundReferenceReceiverType);
CallableReferenceUtilKt.loadBoundReferenceReceiverParameter(iv, boundReceiverParameterIndex, boundReceiverType, boundReceiverKotlinType);
superClassConstructorDescriptor = "(ILjava/lang/Object;)V";
}
else {
@@ -490,13 +503,14 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
List<FieldInfo> args = Lists.newArrayList();
ClassDescriptor captureThis = closure.getCapturedOuterClassDescriptor();
if (captureThis != null) {
Type type = typeMapper.mapType(captureThis);
args.add(FieldInfo.createForHiddenField(ownerType, type, CAPTURED_THIS_FIELD));
SimpleType thisType = captureThis.getDefaultType();
Type type = typeMapper.mapType(thisType);
args.add(FieldInfo.createForHiddenField(ownerType, type, thisType, CAPTURED_THIS_FIELD));
}
KotlinType captureReceiverType = closure.getCapturedReceiverFromOuterContext();
if (captureReceiverType != null) {
String fieldName = closure.getCapturedReceiverFieldName(typeMapper.getBindingContext(), languageVersionSettings);
args.add(FieldInfo.createForHiddenField(ownerType, typeMapper.mapType(captureReceiverType), fieldName));
args.add(FieldInfo.createForHiddenField(ownerType, typeMapper.mapType(captureReceiverType), captureReceiverType, fieldName));
}
for (EnclosedValueDescriptor enclosedValueDescriptor : closure.getCaptureVariables().values()) {
@@ -505,7 +519,10 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
ExpressionTypingUtils.isLocalFunction(descriptor)) {
args.add(
FieldInfo.createForHiddenField(
ownerType, enclosedValueDescriptor.getType(), enclosedValueDescriptor.getFieldName()
ownerType,
enclosedValueDescriptor.getType(),
enclosedValueDescriptor.getKotlinType(),
enclosedValueDescriptor.getFieldName()
)
);
}

View File

@@ -106,8 +106,10 @@ public class ConstructorCodegen {
}
);
functionCodegen.generateDefaultIfNeeded(constructorContext, constructorDescriptor, OwnerKind.IMPLEMENTATION,
DefaultParameterValueLoader.DEFAULT, null);
OwnerKind ownerKindForDefault = context.getContextKind() == OwnerKind.ERASED_INLINE_CLASS
? OwnerKind.ERASED_INLINE_CLASS
: OwnerKind.IMPLEMENTATION;
functionCodegen.generateDefaultIfNeeded(constructorContext, constructorDescriptor, ownerKindForDefault, DefaultParameterValueLoader.DEFAULT, null);
registerAccessorForHiddenConstructorIfNeeded(constructorDescriptor);
@@ -140,7 +142,10 @@ public class ConstructorCodegen {
}
);
functionCodegen.generateDefaultIfNeeded(constructorContext, constructorDescriptor, OwnerKind.IMPLEMENTATION,
OwnerKind ownerKindForDefault = context.getContextKind() == OwnerKind.ERASED_INLINE_CLASS
? OwnerKind.ERASED_INLINE_CLASS
: OwnerKind.IMPLEMENTATION;
functionCodegen.generateDefaultIfNeeded(constructorContext, constructorDescriptor, ownerKindForDefault,
DefaultParameterValueLoader.DEFAULT, null);
new DefaultParameterValueSubstitutor(state).generateOverloadsIfNeeded(

View File

@@ -24,6 +24,7 @@ import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtPureClassOrObject
import org.jetbrains.kotlin.psi.KtPureElement
import org.jetbrains.kotlin.resolve.calls.components.hasDefaultValue
import org.jetbrains.kotlin.resolve.isInlineClass
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.resolve.jvm.annotations.findJvmOverloadsAnnotation
import org.jetbrains.kotlin.resolve.jvm.diagnostics.OtherOriginFromPure
@@ -223,7 +224,7 @@ class DefaultParameterValueSubstitutor(val state: GenerationState) {
v.aconst(null)
val defaultMethod = typeMapper.mapDefaultMethod(delegateFunctionDescriptor, contextKind)
if (functionDescriptor is ConstructorDescriptor) {
if (functionDescriptor is ConstructorDescriptor && !functionDescriptor.containingDeclaration.isInlineClass()) {
v.invokespecial(methodOwner.internalName, defaultMethod.name, defaultMethod.descriptor, false)
} else {
v.invokestatic(methodOwner.internalName, defaultMethod.name, defaultMethod.descriptor, false)
@@ -250,6 +251,7 @@ class DefaultParameterValueSubstitutor(val state: GenerationState) {
if (classDescriptor.kind != ClassKind.CLASS) return false
if (classOrObject.isLocal) return false
if (classDescriptor.isInline) return false
if (CodegenBinding.canHaveOuter(state.bindingContext, classDescriptor)) return false

View File

@@ -49,6 +49,7 @@ class ErasedInlineClassBodyCodegen(
override fun generateSyntheticPartsAfterBody() {
super.generateSyntheticPartsAfterBody()
generateDelegatesToDefaultImpl()
generateUnboxMethod()
generateFunctionsFromAny()
generateSpecializedEqualsStub()

View File

@@ -513,7 +513,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
}
return StackValue.operation(asmType, v -> {
return StackValue.operation(asmType, kotlinType, v -> {
Label elseLabel = new Label();
BranchedValue.Companion.condJump(condition, elseLabel, true, v);
@@ -833,7 +833,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
StringTemplateEntry entry = entries.get(0);
if (entry instanceof StringTemplateEntry.Expression) {
KtExpression expr = ((StringTemplateEntry.Expression) entry).expression;
return genToString(gen(expr), expressionType(expr), kotlinType(expr));
return genToString(gen(expr), expressionType(expr), kotlinType(expr), typeMapper);
}
else {
return StackValue.constant(((StringTemplateEntry.Constant) entry).value, type);
@@ -1105,7 +1105,8 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
ClassDescriptor captureThis = closure.getCapturedOuterClassDescriptor();
if (captureThis != null) {
StackValue thisOrOuter = generateThisOrOuter(captureThis, false);
assert !isPrimitive(thisOrOuter.type) : "This or outer should be non primitive: " + thisOrOuter.type;
assert !isPrimitive(thisOrOuter.type) || captureThis.isInline() :
"This or outer for " + captureThis + " should be non-primitive: " + thisOrOuter.type;
callGenerator.putCapturedValueOnStack(thisOrOuter, thisOrOuter.type, paramIndex++);
}
}
@@ -1938,11 +1939,15 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
Type sharedVarType = typeMapper.getSharedVarType(descriptor);
Type varType = getVariableTypeNoSharing(variableDescriptor);
KotlinType delegateKotlinType =
isDelegatedLocalVariable(descriptor)
? JvmCodegenUtil.getPropertyDelegateType((VariableDescriptorWithAccessors) descriptor, bindingContext)
: null;
if (sharedVarType != null) {
return StackValue.shared(index, varType, variableDescriptor);
return StackValue.shared(index, varType, variableDescriptor, delegateKotlinType);
}
else {
return adjustVariableValue(StackValue.local(index, varType, variableDescriptor), variableDescriptor);
return adjustVariableValue(StackValue.local(index, varType, variableDescriptor, delegateKotlinType), variableDescriptor);
}
}
else {
@@ -2064,7 +2069,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
CallableMethod callableGetter = null;
CallableMethod callableSetter = null;
CodegenContext backingFieldContext = getBackingFieldContext(fieldAccessorKind, containingDeclaration);
CodegenContext<?> backingFieldContext = getBackingFieldContext(fieldAccessorKind, containingDeclaration);
boolean isPrivateProperty =
fieldAccessorKind != AccessorKind.NORMAL &&
(AsmUtil.getVisibilityForBackingField(propertyDescriptor, isDelegatedProperty) & ACC_PRIVATE) != 0;
@@ -2152,7 +2157,8 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
return StackValue.property(
propertyDescriptor, backingFieldOwner,
typeMapper.mapType(isDelegatedProperty && forceField ? delegateType : propertyDescriptor.getOriginal().getType()),
isStaticBackingField, fieldName, callableGetter, callableSetter, receiver, this, resolvedCall, skipLateinitAssertion
isStaticBackingField, fieldName, callableGetter, callableSetter, receiver, this, resolvedCall, skipLateinitAssertion,
isDelegatedProperty && forceField ? delegateType : null
);
}
@@ -2168,7 +2174,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
CallableMethod callableSetter =
setMethod != null ? typeMapper.mapToCallableMethod(context.accessibleDescriptor(setMethod, null), false) : null;
return StackValue.property(propertyDescriptor, null, type, false, null, callableGetter, callableSetter, receiver, this,
null, false);
null, false, null);
}
@Override
@@ -2667,28 +2673,8 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
public StackValue generateReceiverValue(@Nullable ReceiverValue receiverValue, boolean isSuper) {
if (receiverValue instanceof ImplicitClassReceiver) {
ClassDescriptor receiverDescriptor = ((ImplicitClassReceiver) receiverValue).getDeclarationDescriptor();
if (DescriptorUtils.isCompanionObject(receiverDescriptor)) {
CallableMemberDescriptor contextDescriptor = context.getContextDescriptor();
if (contextDescriptor instanceof FunctionDescriptor && receiverDescriptor == contextDescriptor.getContainingDeclaration()) {
return StackValue.LOCAL_0;
}
else if (isPossiblyUninitializedSingleton(receiverDescriptor) && isInsideSingleton(receiverDescriptor)) {
return generateThisOrOuterFromContext(receiverDescriptor, false, false);
}
else if (couldUseDirectAccessToCompanionObject(receiverDescriptor, context)) {
return StackValue.singleton(receiverDescriptor, typeMapper);
}
else {
return generateAccessorCallForCompanionObject(receiverDescriptor);
}
}
else if (receiverDescriptor instanceof ScriptDescriptor) {
return generateScriptReceiver((ScriptDescriptor) receiverDescriptor);
}
else {
return StackValue.thisOrOuter(this, receiverDescriptor, isSuper,
receiverValue instanceof CastImplicitClassReceiver || isEnumEntry(receiverDescriptor));
}
return generateInstanceReceiver(receiverDescriptor, isSuper,
receiverValue instanceof CastImplicitClassReceiver || isEnumEntry(receiverDescriptor));
}
else if (receiverValue instanceof ExtensionReceiver) {
return generateExtensionReceiver(((ExtensionReceiver) receiverValue).getDeclarationDescriptor());
@@ -2708,6 +2694,35 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
}
private StackValue generateInstanceReceiver(
@NotNull ClassDescriptor receiverDescriptor,
boolean isSuper,
boolean castReceiver
) {
if (DescriptorUtils.isCompanionObject(receiverDescriptor)) {
CallableMemberDescriptor contextDescriptor = context.getContextDescriptor();
if (contextDescriptor instanceof FunctionDescriptor && receiverDescriptor == contextDescriptor.getContainingDeclaration()) {
return StackValue.LOCAL_0;
}
else if (isPossiblyUninitializedSingleton(receiverDescriptor) && isInsideSingleton(receiverDescriptor)) {
return generateThisOrOuterFromContext(receiverDescriptor, false, false);
}
else if (couldUseDirectAccessToCompanionObject(receiverDescriptor, context)) {
return StackValue.singleton(receiverDescriptor, typeMapper);
}
else {
return generateAccessorCallForCompanionObject(receiverDescriptor);
}
}
else if (receiverDescriptor instanceof ScriptDescriptor) {
return generateScriptReceiver((ScriptDescriptor) receiverDescriptor);
}
else {
return StackValue.thisOrOuter(this, receiverDescriptor, isSuper, castReceiver);
}
}
@NotNull
private StackValue generateAccessorCallForCompanionObject(@NotNull ClassDescriptor companionObjectDescriptor) {
DeclarationDescriptor hostClassDescriptor = companionObjectDescriptor.getContainingDeclaration();
@@ -2839,8 +2854,8 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
private StackValue generateThisOrOuterFromContext(@NotNull ClassDescriptor thisOrOuterClass, boolean isSuper, boolean forceOuter) {
CodegenContext cur = context;
SimpleType thisType = thisOrOuterClass.getDefaultType();
StackValue result = StackValue.local(0, asmType(thisType), thisType);
SimpleType contextType = cur.getThisDescriptor().getDefaultType();
StackValue result = StackValue.local(0, asmType(contextType), contextType);
boolean inStartConstructorContext = cur instanceof ConstructorContext;
while (cur != null) {
ClassDescriptor thisDescriptor = cur.getThisDescriptor();
@@ -3038,7 +3053,9 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
FunctionDescriptor functionDescriptor = bindingContext.get(FUNCTION, expression);
if (functionDescriptor != null) {
FunctionReferenceGenerationStrategy strategy = new FunctionReferenceGenerationStrategy(
state, functionDescriptor, resolvedCall, receiver != null ? receiver.type : null, null, false
state, functionDescriptor, resolvedCall,
receiver != null ? new JvmKotlinType(receiver.type, receiver.kotlinType) : null,
null, false
);
return genClosure(
@@ -3077,10 +3094,10 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
element.getContainingFile()
);
Type receiverAsmType = receiverValue != null ? receiverValue.type : null;
PropertyReferenceCodegen codegen = new PropertyReferenceCodegen(
state, parentCodegen, context.intoAnonymousClass(classDescriptor, this, OwnerKind.IMPLEMENTATION),
element, classBuilder, variableDescriptor, target, receiverAsmType
element, classBuilder, variableDescriptor, target,
receiverValue != null ? new JvmKotlinType(receiverValue.type, receiverValue.kotlinType) : null
);
codegen.generate();
@@ -3239,7 +3256,16 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
private StackValue genLazyUnlessProvided(@Nullable StackValue pregenerated, @NotNull KtExpression expr, @NotNull Type type) {
return pregenerated != null ? StackValue.coercion(pregenerated, type, null) : genLazy(expr, type);
return genLazyUnlessProvided(pregenerated, expr, type, null);
}
private StackValue genLazyUnlessProvided(
@Nullable StackValue pregenerated,
@NotNull KtExpression expr,
@NotNull Type type,
@Nullable KotlinType kotlinType
) {
return pregenerated != null ? StackValue.coercion(pregenerated, type, kotlinType) : genLazy(expr, type, kotlinType);
}
private StackValue genUnlessProvided(@Nullable StackValue pregenerated, @NotNull KtExpression expr, @NotNull Type type) {
@@ -3384,8 +3410,8 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
KotlinType leftKotlinType = kotlinType(left);
KotlinType rightKotlinType = kotlinType(right);
StackValue leftValue = genLazyUnlessProvided(pregeneratedSubject, left, leftType);
StackValue rightValue = genLazy(right, rightType);
StackValue leftValue = genLazyUnlessProvided(pregeneratedSubject, left, leftType, leftKotlinType);
StackValue rightValue = genLazy(right, rightType, rightKotlinType);
return StackValue.operation(Type.BOOLEAN_TYPE, v -> {
KotlinType nullableAnyType = state.getModule().getBuiltIns().getNullableAnyType();
@@ -3855,7 +3881,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
gen(expr, exprType, exprKotlinType);
}
genInvokeAppendMethod(v, exprType.getSort() == Type.ARRAY ? OBJECT_TYPE : exprType, exprKotlinType);
genInvokeAppendMethod(v, exprType, exprKotlinType, typeMapper);
}
@Nullable
@@ -4108,9 +4134,10 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
Type varType = getVariableTypeNoSharing(variableDescriptor);
KotlinType delegateKotlinType = JvmCodegenUtil.getPropertyDelegateType(variableDescriptor, bindingContext);
StackValue storeTo = sharedVarType == null ?
StackValue.local(index, varType, variableDescriptor) :
StackValue.shared(index, varType, variableDescriptor);
StackValue.local(index, varType, variableDescriptor, delegateKotlinType) :
StackValue.shared(index, varType, variableDescriptor, delegateKotlinType);
storeTo.putReceiver(v, false);
if (variableDescriptor.isLateInit()) {
@@ -4354,8 +4381,8 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
Type elementType = isGetter ? callableMethod.getReturnType() : ArrayUtil.getLastElement(argumentTypes);
KotlinType elementKotlinType = isGetter ?
operationDescriptor.getReturnType() :
CollectionsKt.last(operationDescriptor.getValueParameters()).getType();
operationDescriptor.getOriginal().getReturnType() :
CollectionsKt.last(operationDescriptor.getOriginal().getValueParameters()).getType();
return StackValue.collectionElement(
collectionElementReceiver, elementType, elementKotlinType, resolvedGetCall, resolvedSetCall, this
);
@@ -4402,8 +4429,9 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
public StackValue visitThisExpression(@NotNull KtThisExpression expression, StackValue receiver) {
DeclarationDescriptor descriptor = bindingContext.get(REFERENCE_TARGET, expression.getInstanceReference());
if (descriptor instanceof ClassDescriptor) {
return generateInstanceReceiver((ClassDescriptor) descriptor, false, true);
//TODO rewrite with context.lookupInContext()
return StackValue.thisOrOuter(this, (ClassDescriptor) descriptor, false, true);
//return StackValue.thisOrOuter(this, (ClassDescriptor) descriptor, false, true);
}
if (descriptor instanceof CallableDescriptor) {
return generateExtensionReceiver((CallableDescriptor) descriptor);
@@ -4901,7 +4929,7 @@ The "returned" value of try expression with no finally is either the last expres
@NotNull VariableDescriptorWithAccessors variableDescriptor,
@NotNull KotlinTypeMapper typeMapper
) {
return StackValue.delegate(typeMapper.mapType(variableDescriptor.getType()), delegateValue, metadataValue, variableDescriptor, this);
return StackValue.localDelegate(typeMapper.mapType(variableDescriptor.getType()), delegateValue, metadataValue, variableDescriptor, this);
}
@NotNull

View File

@@ -6,11 +6,13 @@
package org.jetbrains.kotlin.codegen;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.CompanionObjectMapping;
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
import org.jetbrains.kotlin.descriptors.ClassDescriptor;
import org.jetbrains.kotlin.load.java.JvmAbi;
import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.org.objectweb.asm.Type;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.isNonCompanionObject;
@@ -29,7 +31,9 @@ public class FieldInfo {
ClassDescriptor ownerDescriptor = DescriptorUtils.getParentOfType(classDescriptor, ClassDescriptor.class);
assert ownerDescriptor != null : "Owner not found for class: " + classDescriptor;
Type ownerType = typeMapper.mapClass(ownerDescriptor);
return new FieldInfo(ownerType, typeMapper.mapType(classDescriptor), classDescriptor.getName().asString(), true);
KotlinType fieldKotlinType = classDescriptor.getDefaultType();
Type fieldType = typeMapper.mapType(fieldKotlinType);
return new FieldInfo(ownerType, fieldType, fieldKotlinType, classDescriptor.getName().asString(), true);
}
@NotNull
@@ -38,23 +42,43 @@ public class FieldInfo {
@NotNull KotlinTypeMapper typeMapper,
@NotNull String name
) {
Type type = typeMapper.mapType(classDescriptor);
return new FieldInfo(type, type, name, true);
Type owner = typeMapper.mapClass(classDescriptor);
KotlinType fieldKotlinType = classDescriptor.getDefaultType();
Type fieldType = typeMapper.mapType(fieldKotlinType);
return new FieldInfo(owner, fieldType, fieldKotlinType, name, true);
}
@NotNull
public static FieldInfo createForHiddenField(@NotNull Type owner, @NotNull Type fieldType, @NotNull String fieldName) {
return new FieldInfo(owner, fieldType, fieldName, false);
return createForHiddenField(owner, fieldType, null, fieldName);
}
@NotNull
public static FieldInfo createForHiddenField(
@NotNull Type owner,
@NotNull Type fieldType,
@Nullable KotlinType fieldKotlinType,
@NotNull String fieldName
) {
return new FieldInfo(owner, fieldType, fieldKotlinType, fieldName, false);
}
private final Type fieldType;
private final KotlinType fieldKotlinType;
private final Type ownerType;
private final String fieldName;
private final boolean isStatic;
private FieldInfo(@NotNull Type ownerType, @NotNull Type fieldType, @NotNull String fieldName, boolean isStatic) {
private FieldInfo(
@NotNull Type ownerType,
@NotNull Type fieldType,
@Nullable KotlinType fieldKotlinType,
@NotNull String fieldName,
boolean isStatic
) {
this.ownerType = ownerType;
this.fieldType = fieldType;
this.fieldKotlinType = fieldKotlinType;
this.fieldName = fieldName;
this.isStatic = isStatic;
}
@@ -64,6 +88,11 @@ public class FieldInfo {
return fieldType;
}
@Nullable
public KotlinType getFieldKotlinType() {
return fieldKotlinType;
}
@NotNull
public Type getOwnerType() {
return ownerType;

View File

@@ -68,13 +68,16 @@ import java.util.*;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isNullableAny;
import static org.jetbrains.kotlin.codegen.AsmUtil.*;
import static org.jetbrains.kotlin.codegen.CodegenUtilKt.generateBridgeForMainFunctionIfNecessary;
import static org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings.METHOD_FOR_FUNCTION;
import static org.jetbrains.kotlin.codegen.state.KotlinTypeMapper.isAccessor;
import static org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.DECLARATION;
import static org.jetbrains.kotlin.descriptors.ModalityKt.isOverridable;
import static org.jetbrains.kotlin.descriptors.annotations.AnnotationUtilKt.isEffectivelyInlineOnly;
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;
import static org.jetbrains.kotlin.resolve.jvm.InlineClassManglingRulesKt.shouldHideConstructorDueToInlineClassTypeValueParameters;
import static org.jetbrains.kotlin.resolve.jvm.annotations.JvmAnnotationUtilKt.hasJvmDefaultAnnotation;
import static org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils.*;
import static org.jetbrains.org.objectweb.asm.Opcodes.*;
@@ -225,13 +228,10 @@ public class FunctionCodegen {
asmMethod.getDescriptor()
);
if (CodegenContextUtil.isImplementationOwner(owner, functionDescriptor)) {
v.getSerializationBindings().put(METHOD_FOR_FUNCTION, CodegenUtilKt.unwrapFrontendVersion(functionDescriptor), asmMethod);
}
recordMethodForFunctionIfAppropriate(functionDescriptor, asmMethod);
AnnotationCodegen.forMethod(mv, memberCodegen, typeMapper).genAnnotations(functionDescriptor, asmMethod.getReturnType());
generateMethodAnnotationsIfRequired(functionDescriptor, asmMethod, jvmSignature, mv);
generateParameterAnnotations(functionDescriptor, mv, jvmSignature, memberCodegen, state);
GenerateJava8ParameterNamesKt.generateParameterNames(functionDescriptor, mv, jvmSignature, state, (flags & ACC_SYNTHETIC) != 0);
if (contextKind != OwnerKind.ERASED_INLINE_CLASS) {
@@ -244,6 +244,8 @@ public class FunctionCodegen {
parentBodyCodegen.addAdditionalTask(new JvmStaticInCompanionObjectGenerator(functionDescriptor, origin, state, parentBodyCodegen));
}
generateBridgeForMainFunctionIfNecessary(state, v, functionDescriptor, jvmSignature, origin, methodContext.getParentContext());
boolean isOpenSuspendInClass =
functionDescriptor.isSuspend() &&
functionDescriptor.getModality() != Modality.ABSTRACT && isOverridable(functionDescriptor) &&
@@ -266,6 +268,49 @@ public class FunctionCodegen {
}
}
private void recordMethodForFunctionIfAppropriate(
@NotNull FunctionDescriptor functionDescriptor,
Method asmMethod
) {
if (functionDescriptor instanceof AccessorForConstructorDescriptor) {
ConstructorDescriptor originalConstructor = ((AccessorForConstructorDescriptor) functionDescriptor).getCalleeDescriptor();
if (shouldHideConstructorDueToInlineClassTypeValueParameters(originalConstructor)) {
functionDescriptor = originalConstructor;
}
}
else if (shouldHideConstructorDueToInlineClassTypeValueParameters(functionDescriptor)) {
return;
}
functionDescriptor = CodegenUtilKt.unwrapFrontendVersion(functionDescriptor);
if (!CodegenContextUtil.isImplementationOwner(owner, functionDescriptor)) return;
v.getSerializationBindings().put(METHOD_FOR_FUNCTION, functionDescriptor, asmMethod);
}
private void generateMethodAnnotationsIfRequired(
@NotNull FunctionDescriptor functionDescriptor,
@NotNull Method asmMethod,
@NotNull JvmMethodGenericSignature jvmSignature,
@NotNull MethodVisitor mv
) {
FunctionDescriptor annotationsOwner;
if (shouldHideConstructorDueToInlineClassTypeValueParameters(functionDescriptor)) {
if (functionDescriptor instanceof AccessorForConstructorDescriptor) {
annotationsOwner = ((AccessorForConstructorDescriptor) functionDescriptor).getCalleeDescriptor();
}
else {
return;
}
}
else {
annotationsOwner = functionDescriptor;
}
AnnotationCodegen.forMethod(mv, memberCodegen, typeMapper).genAnnotations(annotationsOwner, asmMethod.getReturnType());
generateParameterAnnotations(annotationsOwner, mv, jvmSignature, memberCodegen, state);
}
@NotNull
public MethodVisitor newMethod(
@NotNull JvmDeclarationOrigin origin,
@@ -285,7 +330,8 @@ public class FunctionCodegen {
@NotNull DeclarationDescriptor containingDeclaration
) {
return !canDelegateMethodBodyToInlineClass(origin, functionDescriptor, contextKind, containingDeclaration) ||
!functionDescriptor.getOverriddenDescriptors().isEmpty();
!functionDescriptor.getOverriddenDescriptors().isEmpty() ||
CodegenUtilKt.isJvmStaticInInlineClass(functionDescriptor);
}
private static boolean canDelegateMethodBodyToInlineClass(
@@ -298,6 +344,9 @@ public class FunctionCodegen {
if (contextKind == OwnerKind.ERASED_INLINE_CLASS) return false;
if (origin.getOriginKind() == JvmDeclarationOriginKind.UNBOX_METHOD_OF_INLINE_CLASS) return false;
// Synthesized class member descriptors corresponding to JvmStatic members of companion object
if (CodegenUtilKt.isJvmStaticInInlineClass(functionDescriptor)) return false;
// descriptor corresponds to the underlying value
if (functionDescriptor instanceof PropertyAccessorDescriptor) {
PropertyDescriptor property = ((PropertyAccessorDescriptor) functionDescriptor).getCorrespondingProperty();
@@ -309,7 +358,7 @@ public class FunctionCodegen {
// base check
boolean isInlineClass = InlineClassesUtilsKt.isInlineClass(containingDeclaration);
boolean simpleFunctionOrProperty =
!(functionDescriptor instanceof ConstructorDescriptor) && !KotlinTypeMapper.isAccessor(functionDescriptor);
!(functionDescriptor instanceof ConstructorDescriptor) && !isAccessor(functionDescriptor);
return isInlineClass && simpleFunctionOrProperty;
}
@@ -444,31 +493,6 @@ public class FunctionCodegen {
endVisit(mv, null, origin.getElement());
}
private void generateDelegateForDefaultImpl(
@NotNull FunctionDescriptor functionDescriptor,
@Nullable PsiElement element
) {
Method defaultImplMethod = typeMapper.mapAsmMethod(functionDescriptor, OwnerKind.DEFAULT_IMPLS);
CodegenUtilKt.generateMethod(
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;
}
);
}
public static void generateParameterAnnotations(
@NotNull FunctionDescriptor functionDescriptor,
@NotNull MethodVisitor mv,
@@ -489,6 +513,7 @@ public class FunctionCodegen {
@NotNull InnerClassConsumer innerClassConsumer,
@NotNull GenerationState state
) {
if (isAccessor(functionDescriptor)) return;
KotlinTypeMapper typeMapper = state.getTypeMapper();
Iterator<ValueParameterDescriptor> iterator = valueParameters.iterator();
List<JvmMethodParameterSignature> kotlinParameterTypes = jvmSignature.getValueParameters();
@@ -870,7 +895,7 @@ public class FunctionCodegen {
return parameter.getName().asString();
}
private static void generateFacadeDelegateMethodBody(
public static void generateFacadeDelegateMethodBody(
@NotNull MethodVisitor mv,
@NotNull Method asmMethod,
@NotNull MultifileClassFacadeContext context
@@ -1130,6 +1155,10 @@ public class FunctionCodegen {
return;
}
if (InlineClassesUtilsKt.isInlineClass(contextClass) && kind != OwnerKind.ERASED_INLINE_CLASS) {
return;
}
if (!isDefaultNeeded(functionDescriptor, function)) {
return;
}
@@ -1140,7 +1169,9 @@ public class FunctionCodegen {
isEffectivelyInlineOnly(functionDescriptor) ?
AsmUtil.NO_FLAG_PACKAGE_PRIVATE : Opcodes.ACC_PUBLIC;
int flags = visibilityFlag | getDeprecatedAccessFlag(functionDescriptor) | ACC_SYNTHETIC;
if (!(functionDescriptor instanceof ConstructorDescriptor)) {
if (!(functionDescriptor instanceof ConstructorDescriptor &&
!InlineClassesUtilsKt.isInlineClass(functionDescriptor.getContainingDeclaration()))
) {
flags |= ACC_STATIC;
}
@@ -1245,7 +1276,8 @@ public class FunctionCodegen {
Label loadArg = new Label();
iv.ifeq(loadArg);
StackValue.local(parameterIndex, type).store(loadStrategy.genValue(parameterDescriptor, codegen), iv);
StackValue.local(parameterIndex, type, parameterDescriptor.getType())
.store(loadStrategy.genValue(parameterDescriptor, codegen), iv);
iv.mark(loadArg);
}
@@ -1261,7 +1293,7 @@ public class FunctionCodegen {
generator.putValueIfNeeded(new JvmKotlinType(type, null), StackValue.local(parameterIndex, type));
}
CallableMethod method = state.getTypeMapper().mapToCallableMethod(functionDescriptor, false);
CallableMethod method = state.getTypeMapper().mapToCallableMethod(functionDescriptor, false, methodContext.getContextKind());
generator.genCall(method, null, false, codegen);
@@ -1561,10 +1593,13 @@ public class FunctionCodegen {
reg += argTypes[i].getSize();
}
String internalName = typeMapper.mapType(toClass).getInternalName();
String internalName = typeMapper.mapClass(toClass).getInternalName();
if (toClass.getKind() == ClassKind.INTERFACE) {
iv.invokeinterface(internalName, delegateToMethod.getName(), delegateToMethod.getDescriptor());
}
else if (toClass.isInline()) {
iv.invokestatic(internalName, delegateToMethod.getName(), delegateToMethod.getDescriptor(), false);
}
else {
iv.invokevirtual(internalName, delegateToMethod.getName(), delegateToMethod.getDescriptor(), false);
}

View File

@@ -20,6 +20,7 @@ import org.jetbrains.kotlin.resolve.calls.util.CallMaker;
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature;
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 org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
@@ -51,6 +52,7 @@ public class FunctionReferenceGenerationStrategy extends FunctionGenerationStrat
private final FunctionDescriptor referencedFunction;
private final FunctionDescriptor functionDescriptor;
private final Type receiverType; // non-null for bound references
private final KotlinType receiverKotlinType;
private final StackValue receiverValue;
private final boolean isInliningStrategy;
@@ -58,7 +60,7 @@ public class FunctionReferenceGenerationStrategy extends FunctionGenerationStrat
@NotNull GenerationState state,
@NotNull FunctionDescriptor functionDescriptor,
@NotNull ResolvedCall<?> resolvedCall,
@Nullable Type receiverType,
@Nullable JvmKotlinType receiverJvmKotlinType,
@Nullable StackValue receiverValue,
boolean isInliningStrategy
) {
@@ -73,7 +75,8 @@ public class FunctionReferenceGenerationStrategy extends FunctionGenerationStrat
this.referencedFunction = referencedFunction;
this.functionDescriptor = functionDescriptor;
}
this.receiverType = receiverType;
this.receiverType = receiverJvmKotlinType != null ? receiverJvmKotlinType.getType() : null;
this.receiverKotlinType = receiverJvmKotlinType != null ? receiverJvmKotlinType.getKotlinType() : null;
this.receiverValue = receiverValue;
this.isInliningStrategy = isInliningStrategy;
assert receiverType != null || receiverValue == null
@@ -240,7 +243,7 @@ public class FunctionReferenceGenerationStrategy extends FunctionGenerationStrat
if (receiverType != null) {
ClassDescriptor classDescriptor = (ClassDescriptor) codegen.getContext().getParentContext().getContextDescriptor();
Type asmType = codegen.getState().getTypeMapper().mapClass(classDescriptor);
return CallableReferenceUtilKt.capturedBoundReferenceReceiver(asmType, receiverType, isInliningStrategy);
return CallableReferenceUtilKt.capturedBoundReferenceReceiver(asmType, receiverType, receiverKotlinType, isInliningStrategy);
}
// 0 is this (the callable reference class), 1 is the invoke() method's first parameter

View File

@@ -16,7 +16,6 @@ import org.jetbrains.kotlin.descriptors.ClassDescriptor;
import org.jetbrains.kotlin.descriptors.FunctionDescriptor;
import org.jetbrains.kotlin.descriptors.PropertyDescriptor;
import org.jetbrains.kotlin.lexer.KtTokens;
import org.jetbrains.kotlin.load.java.JvmAbi;
import org.jetbrains.kotlin.psi.KtClassOrObject;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.InlineClassesUtilsKt;
@@ -24,6 +23,7 @@ import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin;
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKt;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.kotlin.types.SimpleType;
import org.jetbrains.org.objectweb.asm.AnnotationVisitor;
import org.jetbrains.org.objectweb.asm.Label;
import org.jetbrains.org.objectweb.asm.MethodVisitor;
import org.jetbrains.org.objectweb.asm.Type;
@@ -34,9 +34,7 @@ import java.util.List;
import static org.jetbrains.kotlin.codegen.AsmUtil.*;
import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.JAVA_STRING_TYPE;
import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.OBJECT_TYPE;
import static org.jetbrains.org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.jetbrains.org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.jetbrains.org.objectweb.asm.Opcodes.IRETURN;
import static org.jetbrains.org.objectweb.asm.Opcodes.*;
public class FunctionsFromAnyGeneratorImpl extends FunctionsFromAnyGenerator {
private final ClassDescriptor classDescriptor;
@@ -83,7 +81,7 @@ public class FunctionsFromAnyGeneratorImpl extends FunctionsFromAnyGenerator {
return;
}
mv.visitAnnotation(Type.getDescriptor(NotNull.class), false);
visitEndForAnnotationVisitor(mv.visitAnnotation(Type.getDescriptor(NotNull.class), false));
if (!generationState.getClassBuilderMode().generateBodies) {
FunctionCodegen.endVisit(mv, toStringMethodName, getDeclaration());
@@ -122,7 +120,7 @@ public class FunctionsFromAnyGeneratorImpl extends FunctionsFromAnyGenerator {
}
}
}
genInvokeAppendMethod(iv, asmType, type.getKotlinType());
genInvokeAppendMethod(iv, asmType, type.getKotlinType(), typeMapper);
}
iv.aconst(")");
@@ -218,7 +216,9 @@ public class FunctionsFromAnyGeneratorImpl extends FunctionsFromAnyGenerator {
return;
}
mv.visitParameterAnnotation(isErasedInlineClassKind ? 1 : 0, Type.getDescriptor(Nullable.class), false);
visitEndForAnnotationVisitor(
mv.visitParameterAnnotation(isErasedInlineClassKind ? 1 : 0, Type.getDescriptor(Nullable.class), false)
);
if (!generationState.getClassBuilderMode().generateBodies) {
FunctionCodegen.endVisit(mv, equalsMethodName, getDeclaration());
@@ -271,6 +271,12 @@ public class FunctionsFromAnyGeneratorImpl extends FunctionsFromAnyGenerator {
FunctionCodegen.endVisit(mv, equalsMethodName, getDeclaration());
}
private static void visitEndForAnnotationVisitor(@Nullable AnnotationVisitor annotation) {
if (annotation != null) {
annotation.visitEnd();
}
}
private int generateBasicChecksAndStoreTarget(InstructionAdapter iv, Label eq, Label ne) {
if (fieldOwnerContext.getContextKind() == OwnerKind.ERASED_INLINE_CLASS) {
SimpleType wrapperKotlinType = classDescriptor.getDefaultType();

View File

@@ -13,7 +13,6 @@ import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function2;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.backend.common.CodegenUtil;
import org.jetbrains.kotlin.backend.common.DataClassMethodGenerator;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMap;
@@ -73,9 +72,7 @@ import static org.jetbrains.kotlin.resolve.BindingContextUtils.getNotNull;
import static org.jetbrains.kotlin.resolve.DescriptorToSourceUtils.descriptorToDeclaration;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.*;
import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.OBJECT_TYPE;
import static org.jetbrains.kotlin.resolve.jvm.annotations.JvmAnnotationUtilKt.hasJvmDefaultAnnotation;
import static org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin.NO_ORIGIN;
import static org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKind.CLASS_MEMBER_DELEGATION_TO_DEFAULT_IMPL;
import static org.jetbrains.kotlin.types.Variance.INVARIANT;
import static org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils.isLocalFunction;
import static org.jetbrains.org.objectweb.asm.Opcodes.*;
@@ -256,10 +253,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
if (!(myClass instanceof KtClass)) return;
if (!descriptor.isInline()) return;
CodegenContext parentContext = context.getParentContext();
assert parentContext != null : "Parent context of inline class declaration should not be null";
ClassContext erasedInlineClassContext = parentContext.intoWrapperForErasedInlineClass(descriptor, state);
ClassContext erasedInlineClassContext = context.intoWrapperForErasedInlineClass(descriptor, state);
new ErasedInlineClassBodyCodegen((KtClass) myClass, erasedInlineClassContext, v, state, this).generate();
}
@@ -273,7 +267,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
if (inlinedValue == null) return;
Type valueType = typeMapper.mapType(inlinedValue.getType());
SimpleFunctionDescriptor functionDescriptor = InlineClassDescriptorResolver.INSTANCE.createUnboxFunctionDescriptor(this.descriptor);
SimpleFunctionDescriptor functionDescriptor = InlineClassDescriptorResolver.createUnboxFunctionDescriptor(this.descriptor);
assert functionDescriptor != null : "FunctionDescriptor for unbox method should be not null during codegen";
functionCodegen.generateMethod(
@@ -411,7 +405,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
generateCompanionObjectBackingFieldCopies();
generateTraitMethods();
generateDelegatesToDefaultImpl();
generateDelegates(delegationFieldsInfo);
@@ -473,7 +467,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
return;
}
Collection<SimpleFunctionDescriptor> functions = descriptor.getDefaultType().getMemberScope().getContributedFunctions(
Collection<? extends SimpleFunctionDescriptor> functions = descriptor.getDefaultType().getMemberScope().getContributedFunctions(
Name.identifier("toArray"), NoLookupLocation.FROM_BACKEND
);
boolean hasGenericToArray = false;
@@ -792,12 +786,15 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
state.getLanguageVersionSettings().supportsFeature(LanguageFeature.DeprecatedFieldForInvisibleCompanionObject);
boolean properVisibilityForCompanionObjectInstanceField =
state.getLanguageVersionSettings().supportsFeature(LanguageFeature.ProperVisibilityForCompanionObjectInstanceField);
boolean hasPrivateOrProtectedProperVisibility = (properFieldVisibilityFlag & (ACC_PRIVATE | ACC_PROTECTED)) != 0;
boolean hasPackagePrivateProperVisibility = (properFieldVisibilityFlag & (ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED)) == 0;
boolean fieldShouldBeDeprecated =
deprecatedFieldForInvisibleCompanionObject &&
!properVisibilityForCompanionObjectInstanceField &&
(properFieldVisibilityFlag & (ACC_PRIVATE | ACC_PROTECTED)) != 0;
(hasPrivateOrProtectedProperVisibility || hasPackagePrivateProperVisibility ||
isNonIntrinsicPrivateCompanionObjectInInterface(companionObjectDescriptor));
boolean doNotGeneratePublic =
properVisibilityForCompanionObjectInstanceField && (properFieldVisibilityFlag & (ACC_PRIVATE | ACC_PROTECTED)) != 0;
properVisibilityForCompanionObjectInstanceField && hasPrivateOrProtectedProperVisibility;
int fieldAccessFlags;
if (doNotGeneratePublic) {
fieldAccessFlags = ACC_STATIC | ACC_FINAL;
@@ -811,6 +808,11 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
if (fieldShouldBeDeprecated) {
fieldAccessFlags |= ACC_DEPRECATED;
}
if (properVisibilityForCompanionObjectInstanceField &&
JvmCodegenUtil.isCompanionObjectInInterfaceNotIntrinsic(companionObjectDescriptor) &&
Visibilities.isPrivate(companionObjectDescriptor.getVisibility())) {
fieldAccessFlags |= ACC_SYNTHETIC;
}
StackValue.Field field = StackValue.singleton(companionObjectDescriptor, typeMapper);
FieldVisitor fv = v.newField(JvmDeclarationOriginKt.OtherOrigin(companionObject == null ? myClass.getPsiOrParent() : companionObject),
fieldAccessFlags, field.name, field.type.getDescriptor(), null, null);
@@ -1051,71 +1053,6 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
}
private void generateTraitMethods() {
if (isJvmInterface(descriptor)) return;
for (Map.Entry<FunctionDescriptor, FunctionDescriptor> entry : CodegenUtil.getNonPrivateTraitMethods(descriptor).entrySet()) {
FunctionDescriptor interfaceFun = entry.getKey();
//skip java 8 default methods
if (!CodegenUtilKt.isDefinitelyNotDefaultImplsMethod(interfaceFun) && !hasJvmDefaultAnnotation(interfaceFun)) {
generateDelegationToDefaultImpl(interfaceFun, entry.getValue());
}
}
}
private void generateDelegationToDefaultImpl(@NotNull FunctionDescriptor interfaceFun, @NotNull FunctionDescriptor inheritedFun) {
functionCodegen.generateMethod(
new JvmDeclarationOrigin(CLASS_MEMBER_DELEGATION_TO_DEFAULT_IMPL, descriptorToDeclaration(interfaceFun), interfaceFun),
inheritedFun,
new FunctionGenerationStrategy.CodegenBased(state) {
@Override
public void doGenerateBody(@NotNull ExpressionCodegen codegen, @NotNull JvmMethodSignature signature) {
DeclarationDescriptor containingDeclaration = interfaceFun.getContainingDeclaration();
if (!DescriptorUtils.isInterface(containingDeclaration)) return;
DeclarationDescriptor declarationInheritedFun = inheritedFun.getContainingDeclaration();
PsiElement classForInheritedFun = descriptorToDeclaration(declarationInheritedFun);
if (classForInheritedFun instanceof KtDeclaration) {
codegen.markLineNumber((KtElement) classForInheritedFun, false);
}
ClassDescriptor containingTrait = (ClassDescriptor) containingDeclaration;
Type traitImplType = typeMapper.mapDefaultImpls(containingTrait);
FunctionDescriptor originalInterfaceFun = interfaceFun.getOriginal();
Method traitMethod = typeMapper.mapAsmMethod(originalInterfaceFun, OwnerKind.DEFAULT_IMPLS);
Type[] argTypes = signature.getAsmMethod().getArgumentTypes();
Type[] originalArgTypes = traitMethod.getArgumentTypes();
assert originalArgTypes.length == argTypes.length + 1 :
"Invalid trait implementation signature: " + signature + " vs " + traitMethod + " for " + interfaceFun;
InstructionAdapter iv = codegen.v;
iv.load(0, OBJECT_TYPE);
for (int i = 0, reg = 1; i < argTypes.length; i++) {
StackValue.local(reg, argTypes[i]).put(originalArgTypes[i + 1], iv);
//noinspection AssignmentToForLoopParameter
reg += argTypes[i].getSize();
}
if (KotlinBuiltIns.isCloneable(containingTrait) && traitMethod.getName().equals("clone")) {
// A special hack for Cloneable: there's no kotlin/Cloneable$DefaultImpls class at runtime,
// and its 'clone' method is actually located in java/lang/Object
iv.invokespecial("java/lang/Object", "clone", "()Ljava/lang/Object;", false);
}
else {
iv.invokestatic(traitImplType.getInternalName(), traitMethod.getName(), traitMethod.getDescriptor(), false);
}
Type returnType = signature.getReturnType();
StackValue.onStack(traitMethod.getReturnType(), originalInterfaceFun.getReturnType()).put(returnType, iv);
iv.areturn(returnType);
}
}
);
}
private void generateEnumEntries() {
if (descriptor.getKind() != ClassKind.ENUM_CLASS) return;

View File

@@ -197,8 +197,8 @@ public class JvmCodegenUtil {
if (KotlinTypeMapper.isAccessor(property)) return false;
CodegenContext context = contextBeforeInline.getFirstCrossInlineOrNonInlineContext();
// Inline functions or inline classes can't use direct access because a field may not be visible at the call site
if (context.isInlineMethodContext() || (context.getEnclosingClass() != null && context.getEnclosingClass().isInline())) {
// Inline functions can't use direct access because a field may not be visible at the call site
if (context.isInlineMethodContext()) {
return false;
}
@@ -348,6 +348,11 @@ public class JvmCodegenUtil {
!JvmAbi.isMappedIntrinsicCompanionObject((ClassDescriptor) companionObject);
}
public static boolean isNonIntrinsicPrivateCompanionObjectInInterface(@NotNull DeclarationDescriptorWithVisibility companionObject) {
return isCompanionObjectInInterfaceNotIntrinsic(companionObject) &&
Visibilities.isPrivate(companionObject.getVisibility());
}
public static boolean isDeclarationOfBigArityFunctionInvoke(@Nullable DeclarationDescriptor descriptor) {
return descriptor instanceof FunctionInvokeDescriptor && ((FunctionInvokeDescriptor) descriptor).hasBigArity();
}

View File

@@ -32,6 +32,7 @@ import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.psi.synthetics.SyntheticClassOrObjectDescriptor;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils;
import org.jetbrains.kotlin.resolve.InlineClassesUtilsKt;
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall;
import org.jetbrains.kotlin.resolve.constants.ConstantValue;
import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt;
@@ -72,7 +73,7 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
public final GenerationState state;
protected final T element;
protected final FieldOwnerContext context;
protected final FieldOwnerContext<?> context;
public final ClassBuilder v;
public final FunctionCodegen functionCodegen;
@@ -406,7 +407,7 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
return typeMapper.mapDefaultImpls(classDescriptor);
}
}
return typeMapper.mapType(classDescriptor);
return typeMapper.mapClass(classDescriptor);
}
else if (outermost instanceof MultifileClassFacadeContext || outermost instanceof DelegatingToPartContext) {
Type implementationOwnerType = CodegenContextUtil.getImplementationOwnerClassType(outermost);
@@ -509,19 +510,29 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
propertyDescriptor, true, false, null, true, StackValue.LOCAL_0, null, false
);
ResolvedCall<FunctionDescriptor> provideDelegateResolvedCall = bindingContext.get(PROVIDE_DELEGATE_RESOLVED_CALL, propertyDescriptor);
if (provideDelegateResolvedCall == null) {
if (property.getDelegateExpression() == null) {
propValue.store(codegen.gen(initializer), codegen.v);
return;
}
else {
StackValue.Property delegate = propValue.getDelegateOrNull();
assert delegate != null : "No delegate for delegated property: " + propertyDescriptor;
StackValue provideDelegateReceiver = codegen.gen(initializer);
ResolvedCall<FunctionDescriptor> provideDelegateResolvedCall =
bindingContext.get(PROVIDE_DELEGATE_RESOLVED_CALL, propertyDescriptor);
StackValue delegateValue = PropertyCodegen.invokeDelegatedPropertyConventionMethod(
codegen, provideDelegateResolvedCall, provideDelegateReceiver, propertyDescriptor
);
if (provideDelegateResolvedCall == null) {
delegate.store(codegen.gen(initializer), codegen.v);
}
else {
StackValue provideDelegateReceiver = codegen.gen(initializer);
propValue.store(delegateValue, codegen.v);
StackValue delegateValue = PropertyCodegen.invokeDelegatedPropertyConventionMethod(
codegen, provideDelegateResolvedCall, provideDelegateReceiver, propertyDescriptor
);
delegate.store(delegateValue, codegen.v);
}
}
}
// Public accessible for serialization plugin to check whether call to initializeProperty(..) is legal.
@@ -868,11 +879,15 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
boolean isJvmStaticInObjectOrClass = CodegenUtilKt.isJvmStaticInObjectOrClassOrInterface(functionDescriptor);
boolean hasDispatchReceiver = !isStaticDeclaration(functionDescriptor) &&
!isNonDefaultInterfaceMember(functionDescriptor) &&
!isJvmStaticInObjectOrClass;
!isJvmStaticInObjectOrClass &&
!InlineClassesUtilsKt.isInlineClass(functionDescriptor.getContainingDeclaration());
boolean accessorIsConstructor = accessorDescriptor instanceof AccessorForConstructorDescriptor;
ReceiverParameterDescriptor dispatchReceiver = functionDescriptor.getDispatchReceiverParameter();
Type dispatchReceiverType = dispatchReceiver != null ? typeMapper.mapType(dispatchReceiver.getType()) : AsmTypes.OBJECT_TYPE;
int accessorParam = (hasDispatchReceiver && !accessorIsConstructor) ? 1 : 0;
int reg = hasDispatchReceiver ? 1 : 0;
int reg = hasDispatchReceiver ? dispatchReceiverType.getSize() : 0;
if (!accessorIsConstructor && functionDescriptor instanceof ConstructorDescriptor) {
iv.anew(callableMethod.getOwner());
iv.dup();
@@ -881,7 +896,7 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
}
else if (KotlinTypeMapper.isAccessor(accessorDescriptor) && (hasDispatchReceiver || accessorIsConstructor)) {
if (!isJvmStaticInObjectOrClass) {
iv.load(0, OBJECT_TYPE);
iv.load(0, dispatchReceiverType);
}
}

View File

@@ -246,7 +246,7 @@ class MultifileClassCodegenImpl(
val facadeContext = state.rootContext.intoMultifileClass(packageFragment, facadeClassType, partType)
val memberCodegen = createCodegenForDelegatesInMultifileFacade(facadeContext)
for (declaration in CodegenUtil.getDeclarationsToGenerate(file, state.bindingContext)) {
if (declaration is KtNamedFunction || declaration is KtProperty || declaration is KtTypeAlias) {
if (shouldGenerateInFacade(declaration)) {
val descriptor = state.bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, declaration)
if (descriptor !is MemberDescriptor) {
throw AssertionError("Expected callable member, was " + descriptor + " for " + declaration.text)
@@ -256,6 +256,15 @@ class MultifileClassCodegenImpl(
}
}
private fun shouldGenerateInFacade(declaration: KtDeclaration): Boolean {
if (declaration is KtNamedFunction || declaration is KtProperty) return true
// In light classes, we intentionally do not analyze type aliases, since they're metadata-only
if (declaration is KtTypeAlias && state.classBuilderMode.generateMetadata) return true
return false
}
private fun shouldGenerateInFacade(descriptor: MemberDescriptor): Boolean {
if (Visibilities.isPrivate(descriptor.visibility)) return false
if (AsmUtil.getVisibilityAccessFlag(descriptor) == Opcodes.ACC_PRIVATE) return false

View File

@@ -210,6 +210,12 @@ public class PropertyCodegen {
return !isDefaultAccessor;
}
// Non-private properties with private setter should not be generated for trivial properties
// as the class will use direct field access instead
if (accessor != null && accessor.isSetter() && Visibilities.isPrivate(descriptor.getSetter().getVisibility())) {
return !isDefaultAccessor;
}
return true;
}
@@ -605,8 +611,10 @@ public class PropertyCodegen {
assert resolvedCall != null : "Resolve call should be recorded for delegate call " + signature.toString();
PropertyDescriptor propertyDescriptor = propertyAccessorDescriptor.getCorrespondingProperty();
StackValue.Property receiver = codegen.intermediateValueForProperty(propertyDescriptor, true, null, StackValue.LOCAL_0);
StackValue lastValue = invokeDelegatedPropertyConventionMethod(codegen, resolvedCall, receiver, propertyDescriptor);
StackValue.Property property = codegen.intermediateValueForProperty(propertyDescriptor, true, null, StackValue.LOCAL_0);
StackValue.Property delegate = property.getDelegateOrNull();
assert delegate != null : "No delegate for delegated property: " + propertyDescriptor;
StackValue lastValue = invokeDelegatedPropertyConventionMethod(codegen, resolvedCall, delegate, propertyDescriptor);
Type asmType = signature.getReturnType();
lastValue.put(asmType, v);
v.areturn(asmType);

View File

@@ -28,9 +28,8 @@ import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.resolve.DescriptorFactory
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.PropertyImportedFromObject
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny
import org.jetbrains.kotlin.resolve.jvm.AsmTypes.*
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
@@ -52,8 +51,11 @@ class PropertyReferenceCodegen(
classBuilder: ClassBuilder,
private val localVariableDescriptorForReference: VariableDescriptor,
private val target: VariableDescriptor,
private val receiverType: Type?
private val boundReceiverJvmKotlinType: JvmKotlinType?
) : MemberCodegen<KtElement>(state, parentCodegen, context, expression, classBuilder) {
private val boundReceiverType = boundReceiverJvmKotlinType?.type
private val classDescriptor = context.contextDescriptor
private val asmType = typeMapper.mapClass(classDescriptor)
@@ -72,9 +74,9 @@ class PropertyReferenceCodegen(
private val wrapperMethod = getWrapperMethodForPropertyReference(target, getFunction.valueParameters.size)
private val closure = bindingContext.get(CodegenBinding.CLOSURE, classDescriptor)!!.apply {
assert((capturedReceiverFromOuterContext != null) == (receiverType != null)) {
assert((capturedReceiverFromOuterContext != null) == (boundReceiverType != null)) {
"Bound property reference can only be generated with the type of the receiver. " +
"Captured type = $capturedReceiverFromOuterContext, actual type = $receiverType"
"Captured type = $capturedReceiverFromOuterContext, actual type = $boundReceiverType"
}
}
@@ -129,16 +131,16 @@ class PropertyReferenceCodegen(
private fun generateConstructor() {
generateMethod("property reference init", 0, constructor) {
val shouldHaveBoundReferenceReceiver = closure.isForBoundCallableReference()
val receiverIndexAndType = generateClosureFieldsInitializationFromParameters(closure, constructorArgs)
val receiverIndexAndFieldInfo = generateClosureFieldsInitializationFromParameters(closure, constructorArgs)
if (receiverIndexAndType == null) {
if (receiverIndexAndFieldInfo == null) {
assert(!shouldHaveBoundReferenceReceiver) { "No bound reference receiver in constructor parameters: $constructorArgs" }
load(0, OBJECT_TYPE)
invokespecial(superAsmType.internalName, "<init>", "()V", false)
} else {
val (receiverIndex, receiverType) = receiverIndexAndType
val (receiverIndex, receiverFieldInfo) = receiverIndexAndFieldInfo
load(0, OBJECT_TYPE)
loadBoundReferenceReceiverParameter(receiverIndex, receiverType)
loadBoundReferenceReceiverParameter(receiverIndex, receiverFieldInfo.fieldType, receiverFieldInfo.fieldKotlinType)
invokespecial(superAsmType.internalName, "<init>", "(Ljava/lang/Object;)V", false)
}
}
@@ -155,7 +157,7 @@ class PropertyReferenceCodegen(
getFunction,
target,
asmType,
receiverType,
boundReceiverJvmKotlinType,
element,
state,
false
@@ -176,7 +178,7 @@ class PropertyReferenceCodegen(
setFunction,
target,
asmType,
receiverType,
boundReceiverJvmKotlinType,
element,
state,
false
@@ -247,7 +249,11 @@ class PropertyReferenceCodegen(
else -> error("Unsupported callable reference: $callable")
}
val declaration = DescriptorUtils.unwrapFakeOverride(accessor).original
val method = state.typeMapper.mapAsmMethod(declaration)
val method =
if (callable.containingDeclaration.isInlineClass())
state.typeMapper.mapSignatureForInlineErasedClassSkipGeneric(declaration).asmMethod
else
state.typeMapper.mapAsmMethod(declaration)
return method.name + method.descriptor
}
@@ -284,19 +290,39 @@ class PropertyReferenceCodegen(
}
class PropertyReferenceGenerationStrategy(
val isGetter: Boolean,
private val isGetter: Boolean,
private val originalFunctionDesc: FunctionDescriptor,
val target: VariableDescriptor,
val asmType: Type,
val receiverType: Type?,
val expression: KtElement,
private val target: VariableDescriptor,
private val asmType: Type,
boundReceiverJvmKotlinType: JvmKotlinType?,
private val expression: KtElement,
state: GenerationState,
private val isInliningStrategy: Boolean
) :
FunctionGenerationStrategy.CodegenBased(state) {
private val boundReceiverType = boundReceiverJvmKotlinType?.type
private val boundReceiverKotlinType = boundReceiverJvmKotlinType?.kotlinType
private val expectedReceiverKotlinType =
target.extensionReceiverParameter?.type
?: (target.containingDeclaration as? ClassDescriptor)?.defaultType
private val expectedReceiverType =
if (expectedReceiverKotlinType != null)
state.typeMapper.mapType(expectedReceiverKotlinType)
else {
assert(boundReceiverType == null) {
"$target: no expected receiver, boundReceiverType is $boundReceiverType"
}
null
}
override fun doGenerateBody(codegen: ExpressionCodegen, signature: JvmMethodSignature) {
val v = codegen.v
val typeMapper = state.typeMapper
val targetKotlinType = target.type
if (target is PropertyImportedFromObject) {
val containingObject = target.containingObject
StackValue
@@ -304,31 +330,51 @@ class PropertyReferenceCodegen(
.put(typeMapper.mapClass(containingObject), containingObject.defaultType, v)
}
if (receiverType != null) {
val expectedReceiver =
target.extensionReceiverParameter?.type ?: (target.containingDeclaration as? ClassDescriptor)?.defaultType
val expectedReceiverType = if (expectedReceiver != null) typeMapper.mapType(expectedReceiver) else receiverType
capturedBoundReferenceReceiver(asmType, expectedReceiverType, isInliningStrategy).put(expectedReceiverType, v)
if (boundReceiverType != null) {
capturedBoundReferenceReceiver(asmType, boundReceiverType, boundReceiverKotlinType, isInliningStrategy)
.put(expectedReceiverType!!, expectedReceiverKotlinType, v)
} else {
val receivers = originalFunctionDesc.valueParameters.dropLast(if (isGetter) 0 else 1)
receivers.forEachIndexed { i, valueParameterDescriptor ->
StackValue.local(i + 1, OBJECT_TYPE).put(typeMapper.mapType(valueParameterDescriptor), valueParameterDescriptor.type, v)
val nullableAny = valueParameterDescriptor.builtIns.nullableAnyType
StackValue.local(i + 1, OBJECT_TYPE, nullableAny)
.put(typeMapper.mapType(valueParameterDescriptor), valueParameterDescriptor.type, v)
}
}
val value = if (target is LocalVariableDescriptor) {
codegen.findLocalOrCapturedValue(target)!!
} else {
codegen.intermediateValueForProperty(target as PropertyDescriptor, false, null, StackValue.none())
val value = when {
target is LocalVariableDescriptor -> codegen.findLocalOrCapturedValue(target)!!
target.isUnderlyingPropertyOfInlineClass() -> {
if (expectedReceiverType == null)
throw AssertionError("$target: boundReceiverType=$boundReceiverType, expectedReceiverType is null")
val receiver =
if (boundReceiverType != null)
StackValue.onStack(expectedReceiverType, expectedReceiverKotlinType)
else
StackValue.none()
StackValue.underlyingValueOfInlineClass(typeMapper.mapType(targetKotlinType), targetKotlinType, receiver)
}
else -> codegen.intermediateValueForProperty(target as PropertyDescriptor, false, null, StackValue.none())
}
codegen.markStartLineNumber(expression)
val type = target.type
if (isGetter) {
value.put(OBJECT_TYPE, type, v)
value.put(OBJECT_TYPE, targetKotlinType, v)
} else {
val functionDescriptor = codegen.context.functionDescriptor
value.store(StackValue.local(codegen.frameMap.getIndex(functionDescriptor.valueParameters.last()), OBJECT_TYPE, type), v)
value.store(
StackValue.local(
codegen.frameMap.getIndex(
codegen.context.functionDescriptor.valueParameters.last()
),
OBJECT_TYPE, targetKotlinType
),
v
)
}
v.areturn(signature.returnType)
}

View File

@@ -5,7 +5,6 @@
package org.jetbrains.kotlin.codegen
import org.jetbrains.kotlin.backend.common.isTopLevelInPackage
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.KotlinBuiltIns.RANGES_PACKAGE_FQ_NAME
import org.jetbrains.kotlin.builtins.PrimitiveType

View File

@@ -25,15 +25,16 @@ import org.jetbrains.kotlin.synthetic.SamAdapterExtensionFunctionDescriptor;
public class SamCodegenUtil {
@Nullable
@SuppressWarnings("unchecked")
public static FunctionDescriptor getOriginalIfSamAdapter(@NotNull FunctionDescriptor fun) {
if (fun instanceof SamAdapterDescriptor<?> || fun instanceof SamAdapterExtensionFunctionDescriptor) {
//noinspection unchecked
return ((SyntheticMemberDescriptor<FunctionDescriptor>) fun).getBaseDescriptorForSynthetic();
}
return null;
}
@SuppressWarnings("unchecked")
public static <T extends FunctionDescriptor> T resolveSamAdapter(@NotNull T descriptor) {
FunctionDescriptor original = getOriginalIfSamAdapter(descriptor);
return original != null ? (T) original : descriptor;

View File

@@ -77,7 +77,7 @@ class ScriptCodegen private constructor(
classBuilder: ClassBuilder,
methodContext: MethodContext
) {
val scriptDefinition = scriptContext.script.kotlinScriptDefinition.value
val scriptDefinition = scriptContext.script.kotlinScriptDefinition
val jvmSignature = typeMapper.mapScriptSignature(
scriptDescriptor,

View File

@@ -25,7 +25,10 @@ import org.jetbrains.kotlin.load.java.JvmAbi;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.psi.KtExpression;
import org.jetbrains.kotlin.psi.ValueArgument;
import org.jetbrains.kotlin.resolve.*;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.resolve.ImportedFromObjectCallableDescriptor;
import org.jetbrains.kotlin.resolve.InlineClassesUtilsKt;
import org.jetbrains.kotlin.resolve.calls.model.DefaultValueArgument;
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall;
import org.jetbrains.kotlin.resolve.calls.model.ResolvedValueArgument;
@@ -160,16 +163,26 @@ public abstract class StackValue {
@NotNull
public static StackValue local(int index, @NotNull Type type, @NotNull VariableDescriptor descriptor) {
return local(index, type, descriptor, null);
}
@NotNull
public static StackValue local(int index, @NotNull Type type, @NotNull VariableDescriptor descriptor, @Nullable KotlinType delegateKotlinType) {
if (descriptor.isLateInit()) {
assert delegateKotlinType == null :
"Delegated property can't be lateinit: " + descriptor + ", delegate type: " + delegateKotlinType;
return new LateinitLocal(index, type, descriptor.getType(), descriptor.getName());
}
else {
return new Local(index, type, descriptor.getType());
return new Local(
index, type,
delegateKotlinType != null ? delegateKotlinType : descriptor.getType()
);
}
}
@NotNull
public static Delegate delegate(
public static Delegate localDelegate(
@NotNull Type type,
@NotNull StackValue delegateValue,
@NotNull StackValue metadataValue,
@@ -186,7 +199,16 @@ public abstract class StackValue {
@NotNull
public static StackValue shared(int index, @NotNull Type type, @NotNull VariableDescriptor descriptor) {
return new Shared(index, type, descriptor.getType(), descriptor.isLateInit(), descriptor.getName());
return shared(index, type, descriptor, null);
}
@NotNull
public static StackValue shared(int index, @NotNull Type type, @NotNull VariableDescriptor descriptor, @Nullable KotlinType delegateKotlinType) {
return new Shared(
index, type,
delegateKotlinType != null ? delegateKotlinType : descriptor.getType(),
descriptor.isLateInit(), descriptor.getName()
);
}
@NotNull
@@ -318,7 +340,19 @@ public abstract class StackValue {
@NotNull
public static Field field(@NotNull Type type, @NotNull Type owner, @NotNull String name, boolean isStatic, @NotNull StackValue receiver) {
return field(type, null, owner, name, isStatic, receiver, null);
return field(type, null, owner, name, isStatic, receiver);
}
@NotNull
public static Field field(
@NotNull Type type,
@Nullable KotlinType kotlinType,
@NotNull Type owner,
@NotNull String name,
boolean isStatic,
@NotNull StackValue receiver
) {
return field(type, kotlinType, owner, name, isStatic, receiver, null);
}
@NotNull
@@ -341,7 +375,14 @@ public abstract class StackValue {
@NotNull
public static Field field(@NotNull FieldInfo info, @NotNull StackValue receiver) {
return field(info.getFieldType(), Type.getObjectType(info.getOwnerInternalName()), info.getFieldName(), info.isStatic(), receiver);
return field(
info.getFieldType(),
info.getFieldKotlinType(),
Type.getObjectType(info.getOwnerInternalName()),
info.getFieldName(),
info.isStatic(),
receiver
);
}
@NotNull
@@ -363,10 +404,11 @@ public abstract class StackValue {
@NotNull StackValue receiver,
@NotNull ExpressionCodegen codegen,
@Nullable ResolvedCall resolvedCall,
boolean skipLateinitAssertion
boolean skipLateinitAssertion,
@Nullable KotlinType delegateKotlinType
) {
return new Property(descriptor, backingFieldOwner, getter, setter, isStaticBackingField, fieldName, type, receiver, codegen,
resolvedCall, skipLateinitAssertion);
resolvedCall, skipLateinitAssertion, delegateKotlinType);
}
@NotNull
@@ -721,7 +763,7 @@ public abstract class StackValue {
) {
// Coerce 'this' for the case when it is smart cast.
// Do not coerce for other cases due to the 'protected' access issues (JVMS 7, 4.9.2 Structural Constraints).
boolean coerceType = descriptor.getKind() == ClassKind.INTERFACE || (castReceiver && !isSuper);
boolean coerceType = descriptor.getKind() == ClassKind.INTERFACE || descriptor.isInline() || (castReceiver && !isSuper);
return new ThisOuter(codegen, descriptor, isSuper, coerceType);
}
@@ -1426,7 +1468,7 @@ public abstract class StackValue {
Type lastParameterType = ArraysKt.last(setter.getParameterTypes());
KotlinType lastParameterKotlinType =
CollectionsKt.last(resolvedSetCall.getResultingDescriptor().getValueParameters()).getType();
CollectionsKt.last(resolvedSetCall.getResultingDescriptor().getOriginal().getValueParameters()).getType();
coerce(topOfStackType, topOfStackKotlinType, lastParameterType, lastParameterKotlinType, v);
@@ -1460,7 +1502,6 @@ public abstract class StackValue {
}
}
public static class Field extends StackValueWithSimpleReceiver {
public final Type owner;
public final String name;
@@ -1508,12 +1549,13 @@ public abstract class StackValue {
private final ExpressionCodegen codegen;
private final ResolvedCall resolvedCall;
private final boolean skipLateinitAssertion;
private final KotlinType delegateKotlinType;
public Property(
@NotNull PropertyDescriptor descriptor, @Nullable Type backingFieldOwner, @Nullable CallableMethod getter,
@Nullable CallableMethod setter, boolean isStaticBackingField, @Nullable String fieldName, @NotNull Type type,
@NotNull StackValue receiver, @NotNull ExpressionCodegen codegen, @Nullable ResolvedCall resolvedCall,
boolean skipLateinitAssertion
boolean skipLateinitAssertion, @Nullable KotlinType delegateKotlinType
) {
super(type, descriptor.getType(), isStatic(isStaticBackingField, getter), isStatic(isStaticBackingField, setter), receiver, true);
this.backingFieldOwner = backingFieldOwner;
@@ -1524,6 +1566,44 @@ public abstract class StackValue {
this.codegen = codegen;
this.resolvedCall = resolvedCall;
this.skipLateinitAssertion = skipLateinitAssertion;
this.delegateKotlinType = delegateKotlinType;
}
private static class DelegatePropertyConstructorMarker {
private DelegatePropertyConstructorMarker() {}
public static final DelegatePropertyConstructorMarker MARKER = new DelegatePropertyConstructorMarker();
}
/**
* Given a delegating property, create a "property" corresponding to the underlying delegate itself.
* This will take care of backing fields, accessors, and other such stuff.
* Note that we just replace <code>kotlinType</code> with the <code>delegateKotlinType</code>
* (so that type coercion will work properly),
* and <code>delegateKotlinType</code> with <code>null</code>
* (so that the resulting property has no underlying delegate of its own).
*
* @param delegating delegating property
* @param marker intent marker
*/
@SuppressWarnings("unused")
private Property(@NotNull Property delegating, @NotNull DelegatePropertyConstructorMarker marker) {
super(delegating.type, delegating.delegateKotlinType,
delegating.isStaticPut, delegating.isStaticStore, delegating.receiver, true);
this.backingFieldOwner = delegating.backingFieldOwner;
this.getter = delegating.getter;
this.setter = delegating.setter;
this.descriptor = delegating.descriptor;
this.fieldName = delegating.fieldName;
this.codegen = delegating.codegen;
this.resolvedCall = delegating.resolvedCall;
this.skipLateinitAssertion = delegating.skipLateinitAssertion;
this.delegateKotlinType = null;
}
public Property getDelegateOrNull() {
if (delegateKotlinType == null) return null;
return new Property(this, DelegatePropertyConstructorMarker.MARKER);
}
@Override

View File

@@ -21,10 +21,10 @@ import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
class CoercionValue(
val value: StackValue,
private val castType: Type,
private val castKotlinType: KotlinType?,
private val underlyingKotlinType: KotlinType? // type of the underlying parameter for inline class
val value: StackValue,
private val castType: Type,
private val castKotlinType: KotlinType?,
private val underlyingKotlinType: KotlinType? // type of the underlying parameter for inline class
) : StackValue(castType, castKotlinType, value.canHaveSideEffects()) {
override fun putSelector(type: Type, kotlinType: KotlinType?, v: InstructionAdapter) {
@@ -55,8 +55,8 @@ class CoercionValue(
class StackValueWithLeaveTask(
val stackValue: StackValue,
val leaveTasks: (StackValue) -> Unit
val stackValue: StackValue,
val leaveTasks: (StackValue) -> Unit
) : StackValue(stackValue.type, stackValue.kotlinType) {
override fun putReceiver(v: InstructionAdapter, isRead: Boolean) {
@@ -89,22 +89,22 @@ class FunctionCallStackValue(
fun ValueParameterDescriptor.findJavaDefaultArgumentValue(targetType: Type, typeMapper: KotlinTypeMapper): StackValue {
val descriptorWithDefaultValue = DFS.dfs(
listOf(this.original),
{ it.original.overriddenDescriptors.map(ValueParameterDescriptor::getOriginal) },
object : DFS.AbstractNodeHandler<ValueParameterDescriptor, ValueParameterDescriptor?>() {
var result: ValueParameterDescriptor? = null
listOf(this.original),
{ it.original.overriddenDescriptors.map(ValueParameterDescriptor::getOriginal) },
object : DFS.AbstractNodeHandler<ValueParameterDescriptor, ValueParameterDescriptor?>() {
var result: ValueParameterDescriptor? = null
override fun beforeChildren(current: ValueParameterDescriptor?): Boolean {
if (current?.declaresDefaultValue() == true && current.getDefaultValueFromAnnotation() != null) {
result = current
return false
}
return true
override fun beforeChildren(current: ValueParameterDescriptor?): Boolean {
if (current?.declaresDefaultValue() == true && current.getDefaultValueFromAnnotation() != null) {
result = current
return false
}
override fun result(): ValueParameterDescriptor? = result
return true
}
override fun result(): ValueParameterDescriptor? = result
}
) ?: error("Should be at least one descriptor with default value: $this")
val defaultValue = descriptorWithDefaultValue.getDefaultValueFromAnnotation()

View File

@@ -959,11 +959,18 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
}
private boolean isWhenWithEnums(@NotNull KtWhenExpression expression) {
return WhenChecker.isWhenByEnum(expression, bindingContext) &&
switchCodegenProvider.checkAllItemsAreConstantsSatisfying(
expression,
constant -> constant instanceof EnumValue || constant instanceof NullValue
);
ClassId enumClassId = WhenChecker.getClassIdForEnumSubject(expression, bindingContext);
if (enumClassId == null) return false;
return switchCodegenProvider.checkAllItemsAreConstantsSatisfying(
expression,
constant -> isEnumEntryOrNull(enumClassId, constant)
);
}
private static boolean isEnumEntryOrNull(ClassId enumClassId, ConstantValue<?> constant) {
return (constant instanceof EnumValue && ((EnumValue) constant).getEnumClassId().equals(enumClassId)) ||
constant instanceof NullValue;
}
@NotNull

View File

@@ -24,69 +24,77 @@ import org.jetbrains.kotlin.psi.KtCallableReferenceExpression
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.resolve.source.KotlinSourceElement
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.builtIns
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
fun capturedBoundReferenceReceiver(ownerType: Type, expectedReceiverType: Type, isInliningStrategy: Boolean): StackValue =
StackValue.operation(expectedReceiverType) { iv ->
iv.load(0, ownerType)
iv.getfield(
ownerType.internalName,
//HACK for inliner - it should recognize field as captured receiver
if (isInliningStrategy) AsmUtil.CAPTURED_RECEIVER_FIELD else AsmUtil.BOUND_REFERENCE_RECEIVER,
AsmTypes.OBJECT_TYPE.descriptor
)
StackValue.coerce(AsmTypes.OBJECT_TYPE, expectedReceiverType, iv)
}
fun capturedBoundReferenceReceiver(
ownerType: Type,
expectedReceiverType: Type,
expectedReceiverKotlinType: KotlinType?,
isInliningStrategy: Boolean
): StackValue =
StackValue.operation(expectedReceiverType) { iv ->
iv.load(0, ownerType)
iv.getfield(
ownerType.internalName,
//HACK for inliner - it should recognize field as captured receiver
if (isInliningStrategy) AsmUtil.CAPTURED_RECEIVER_FIELD else AsmUtil.BOUND_REFERENCE_RECEIVER,
AsmTypes.OBJECT_TYPE.descriptor
)
val nullableAny = expectedReceiverKotlinType?.run { builtIns.nullableAnyType }
StackValue.coerce(AsmTypes.OBJECT_TYPE, nullableAny, expectedReceiverType, expectedReceiverKotlinType, iv)
}
fun ClassDescriptor.isSyntheticClassForCallableReference(): Boolean =
this is SyntheticClassDescriptorForLambda &&
(this.source as? KotlinSourceElement)?.psi is KtCallableReferenceExpression
this is SyntheticClassDescriptorForLambda &&
(this.source as? KotlinSourceElement)?.psi is KtCallableReferenceExpression
fun CalculatedClosure.isForCallableReference(): Boolean =
closureClass.isSyntheticClassForCallableReference()
closureClass.isSyntheticClassForCallableReference()
fun CalculatedClosure.isForBoundCallableReference(): Boolean =
isForCallableReference() && capturedReceiverFromOuterContext != null
isForCallableReference() && capturedReceiverFromOuterContext != null
fun InstructionAdapter.loadBoundReferenceReceiverParameter(index: Int, type: Type) {
fun InstructionAdapter.loadBoundReferenceReceiverParameter(index: Int, type: Type, kotlinType: KotlinType?) {
load(index, type)
StackValue.coerce(type, AsmTypes.OBJECT_TYPE, this)
val nullableAny = kotlinType?.run { builtIns.nullableAnyType }
StackValue.coerce(type, kotlinType, AsmTypes.OBJECT_TYPE, nullableAny, this)
}
fun CalculatedClosure.isBoundReferenceReceiverField(fieldInfo: FieldInfo): Boolean =
isForBoundCallableReference() &&
fieldInfo.fieldName == AsmUtil.CAPTURED_RECEIVER_FIELD
isForBoundCallableReference() &&
fieldInfo.fieldName == AsmUtil.CAPTURED_RECEIVER_FIELD
fun InstructionAdapter.generateClosureFieldsInitializationFromParameters(closure: CalculatedClosure, args: List<FieldInfo>): Pair<Int, Type>? {
fun InstructionAdapter.generateClosureFieldsInitializationFromParameters(
closure: CalculatedClosure,
args: List<FieldInfo>
): Pair<Int, FieldInfo>? {
var k = 1
var boundReferenceReceiverParameterIndex = -1
var boundReferenceReceiverType: Type? = null
var boundReferenceReceiverFieldInfo: FieldInfo? = null
for (fieldInfo in args) {
if (closure.isBoundReferenceReceiverField(fieldInfo)) {
boundReferenceReceiverParameterIndex = k
boundReferenceReceiverType = fieldInfo.fieldType
boundReferenceReceiverFieldInfo = fieldInfo
k += fieldInfo.fieldType.size
continue
}
k = AsmUtil.genAssignInstanceFieldFromParam(fieldInfo, k, this)
}
return when {
boundReferenceReceiverType != null ->
Pair(boundReferenceReceiverParameterIndex, boundReferenceReceiverType)
else ->
null
}
return boundReferenceReceiverFieldInfo?.let { Pair(boundReferenceReceiverParameterIndex, it) }
}
fun computeExpectedNumberOfReceivers(referencedFunction: FunctionDescriptor, isBound: Boolean): Int {
val receivers = (if (referencedFunction.dispatchReceiverParameter != null) 1 else 0) +
(if (referencedFunction.extensionReceiverParameter != null) 1 else 0) -
(if (isBound) 1 else 0)
(if (referencedFunction.extensionReceiverParameter != null) 1 else 0) -
(if (isBound) 1 else 0)
if (receivers < 0 && referencedFunction is ConstructorDescriptor &&
DescriptorUtils.isObject(referencedFunction.containingDeclaration.containingDeclaration)) {
DescriptorUtils.isObject(referencedFunction.containingDeclaration.containingDeclaration)
) {
//reference to object nested class
//TODO: seems problem should be fixed on frontend side (note that object instance are captured by generated class)
return 0

View File

@@ -12,8 +12,11 @@ import org.jetbrains.kotlin.codegen.binding.CodegenBinding
import org.jetbrains.kotlin.builtins.UnsignedTypes
import org.jetbrains.kotlin.codegen.context.CodegenContext
import org.jetbrains.kotlin.codegen.context.FieldOwnerContext
import org.jetbrains.kotlin.codegen.context.MultifileClassFacadeContext
import org.jetbrains.kotlin.codegen.context.PackageContext
import org.jetbrains.kotlin.codegen.coroutines.continuationAsmType
import org.jetbrains.kotlin.codegen.coroutines.unwrapInitialDescriptorForSuspendFunction
import org.jetbrains.kotlin.codegen.inline.NUMBERED_FUNCTION_PREFIX
import org.jetbrains.kotlin.codegen.inline.ReificationArgument
import org.jetbrains.kotlin.codegen.intrinsics.TypeIntrinsics
import org.jetbrains.kotlin.codegen.optimization.common.asSequence
@@ -30,19 +33,18 @@ import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.BindingTrace
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.DescriptorUtils.isSubclass
import org.jetbrains.kotlin.resolve.annotations.hasJvmStaticAnnotation
import org.jetbrains.kotlin.resolve.calls.callUtil.getFirstArgumentExpression
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.isInlineClassType
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import org.jetbrains.kotlin.resolve.jvm.diagnostics.Synthetic
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodGenericSignature
import org.jetbrains.kotlin.resolve.scopes.receivers.TransientReceiver
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberDescriptor
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberDescriptor.CoroutinesCompatibilityMode
@@ -52,6 +54,7 @@ import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.utils.DFS
import org.jetbrains.org.objectweb.asm.Label
import org.jetbrains.org.objectweb.asm.Opcodes.*
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
import org.jetbrains.org.objectweb.asm.commons.Method
@@ -250,6 +253,9 @@ fun CallableDescriptor.isJvmStaticInObjectOrClassOrInterface(): Boolean =
fun CallableDescriptor.isJvmStaticInCompanionObject(): Boolean =
isJvmStaticIn { DescriptorUtils.isCompanionObject(it) }
fun CallableDescriptor.isJvmStaticInInlineClass(): Boolean =
isJvmStaticIn { it.isInlineClass() }
private fun CallableDescriptor.isJvmStaticIn(predicate: (DeclarationDescriptor) -> Boolean): Boolean =
when (this) {
is PropertyAccessorDescriptor -> {
@@ -464,4 +470,197 @@ fun recordCallLabelForLambdaArgument(declaration: KtFunctionLiteral, bindingTrac
val call = callExpression.getResolvedCall(bindingTrace.bindingContext) ?: return
storeLabelName(call.resultingDescriptor.name.asString())
}
}
private val ARRAY_OF_STRINGS_TYPE = Type.getType("[Ljava/lang/String;")
private val METHOD_DESCRIPTOR_FOR_MAIN = Type.getMethodDescriptor(Type.VOID_TYPE, ARRAY_OF_STRINGS_TYPE)
fun generateBridgeForMainFunctionIfNecessary(
state: GenerationState,
packagePartClassBuilder: ClassBuilder,
functionDescriptor: FunctionDescriptor,
signatureOfRealDeclaration: JvmMethodGenericSignature,
origin: JvmDeclarationOrigin,
parentContext: CodegenContext<*>
) {
val originElement = origin.element ?: return
if (functionDescriptor.name.asString() != "main" || !DescriptorUtils.isTopLevelDeclaration(functionDescriptor)) return
val unwrappedFunctionDescriptor = functionDescriptor.unwrapInitialDescriptorForSuspendFunction()
val isParameterless =
unwrappedFunctionDescriptor.extensionReceiverParameter == null && unwrappedFunctionDescriptor.valueParameters.isEmpty()
if (!functionDescriptor.isSuspend && !isParameterless) return
if (!state.mainFunctionDetector.isMain(unwrappedFunctionDescriptor, false, true)) return
val bridgeMethodVisitor = packagePartClassBuilder.newMethod(
Synthetic(originElement, functionDescriptor),
ACC_PUBLIC or ACC_STATIC or ACC_SYNTHETIC,
"main",
METHOD_DESCRIPTOR_FOR_MAIN, null, null
)
if (parentContext is MultifileClassFacadeContext) {
bridgeMethodVisitor.visitCode()
FunctionCodegen.generateFacadeDelegateMethodBody(
bridgeMethodVisitor,
Method("main", METHOD_DESCRIPTOR_FOR_MAIN),
parentContext
)
bridgeMethodVisitor.visitEnd()
return
}
val lambdaInternalName =
if (functionDescriptor.isSuspend)
generateLambdaForRunSuspend(
state,
originElement,
packagePartClassBuilder.thisName,
signatureOfRealDeclaration,
isParameterless
)
else
null
bridgeMethodVisitor.apply {
visitCode()
if (lambdaInternalName != null) {
visitTypeInsn(NEW, lambdaInternalName)
visitInsn(DUP)
visitVarInsn(ALOAD, 0)
visitMethodInsn(
INVOKESPECIAL,
lambdaInternalName,
"<init>",
METHOD_DESCRIPTOR_FOR_MAIN,
false
)
visitMethodInsn(
INVOKESTATIC,
"kotlin/coroutines/jvm/internal/RunSuspendKt", "runSuspend",
Type.getMethodDescriptor(
Type.VOID_TYPE,
Type.getObjectType(NUMBERED_FUNCTION_PREFIX + "1")
),
false
)
} else {
visitMethodInsn(
INVOKESTATIC,
packagePartClassBuilder.thisName, "main",
Type.getMethodDescriptor(
Type.VOID_TYPE
),
false
)
}
visitInsn(RETURN)
visitEnd()
}
}
private fun generateLambdaForRunSuspend(
state: GenerationState,
originElement: PsiElement,
packagePartClassInternalName: String,
signatureOfRealDeclaration: JvmMethodGenericSignature,
parameterless: Boolean
): String {
val internalName = "$packagePartClassInternalName$$\$main"
val lambdaBuilder = state.factory.newVisitor(
JvmDeclarationOrigin.NO_ORIGIN,
Type.getObjectType(internalName),
originElement.containingFile
)
lambdaBuilder.defineClass(
originElement, state.classFileVersion,
ACC_FINAL or ACC_SUPER or ACC_SYNTHETIC,
internalName, null,
AsmTypes.LAMBDA.internalName,
arrayOf(NUMBERED_FUNCTION_PREFIX + "1")
)
lambdaBuilder.newField(
JvmDeclarationOrigin.NO_ORIGIN,
ACC_PRIVATE or ACC_FINAL,
"args",
ARRAY_OF_STRINGS_TYPE.descriptor, null, null
)
lambdaBuilder.newMethod(
JvmDeclarationOrigin.NO_ORIGIN,
AsmUtil.NO_FLAG_PACKAGE_PRIVATE or ACC_SYNTHETIC,
"<init>",
METHOD_DESCRIPTOR_FOR_MAIN, null, null
).apply {
visitCode()
visitVarInsn(ALOAD, 0)
visitVarInsn(ALOAD, 1)
visitFieldInsn(
PUTFIELD,
lambdaBuilder.thisName,
"args",
ARRAY_OF_STRINGS_TYPE.descriptor
)
visitVarInsn(ALOAD, 0)
visitInsn(ICONST_1)
visitMethodInsn(
INVOKESPECIAL,
AsmTypes.LAMBDA.internalName,
"<init>",
Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE),
false
)
visitInsn(RETURN)
visitEnd()
}
lambdaBuilder.newMethod(
JvmDeclarationOrigin.NO_ORIGIN,
ACC_PUBLIC or ACC_FINAL or ACC_SYNTHETIC,
"invoke",
Type.getMethodDescriptor(AsmTypes.OBJECT_TYPE, AsmTypes.OBJECT_TYPE), null, null
).apply {
visitCode()
if (!parameterless) {
// Actually, the field for arguments may also be removed in case of parameterless main,
// but probably it'd much easier when IR is ready
visitVarInsn(ALOAD, 0)
visitFieldInsn(
GETFIELD,
lambdaBuilder.thisName,
"args",
ARRAY_OF_STRINGS_TYPE.descriptor
)
}
visitVarInsn(ALOAD, 1)
val continuationInternalName = state.languageVersionSettings.continuationAsmType().internalName
visitTypeInsn(
CHECKCAST,
continuationInternalName
)
visitMethodInsn(
INVOKESTATIC,
packagePartClassInternalName,
signatureOfRealDeclaration.asmMethod.name,
signatureOfRealDeclaration.asmMethod.descriptor,
false
)
visitInsn(ARETURN)
visitEnd()
}
writeSyntheticClassMetadata(lambdaBuilder, state)
lambdaBuilder.done()
return lambdaBuilder.thisName
}

View File

@@ -393,12 +393,16 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
public CodegenContext findParentContextWithDescriptor(DeclarationDescriptor descriptor) {
CodegenContext c = this;
while (c != null) {
if (c.getContextDescriptor() == descriptor) break;
if (!c.shouldSkipThisContextInHierarchy() && c.getContextDescriptor() == descriptor) break;
c = c.getParentContext();
}
return c;
}
private boolean shouldSkipThisContextInHierarchy() {
return getContextKind() == OwnerKind.ERASED_INLINE_CLASS;
}
@NotNull
private PropertyDescriptor getPropertyAccessor(
@NotNull PropertyDescriptor propertyDescriptor,
@@ -409,7 +413,7 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
return getAccessor(propertyDescriptor, AccessorKind.NORMAL, null, superCallTarget, getterAccessorRequired, setterAccessorRequired);
}
@SuppressWarnings("unchecked")
public <D extends CallableMemberDescriptor> D getAccessorForJvmDefaultCompatibility(@NotNull D descriptor) {
if (descriptor instanceof PropertyAccessorDescriptor) {
PropertyDescriptor propertyAccessor = getAccessor(((PropertyAccessorDescriptor) descriptor).getCorrespondingProperty(),

View File

@@ -21,6 +21,7 @@ import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.codegen.ExpressionCodegen;
import org.jetbrains.kotlin.codegen.StackValue;
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.org.objectweb.asm.Type;
public final class EnclosedValueDescriptor {
@@ -29,18 +30,21 @@ public final class EnclosedValueDescriptor {
private final StackValue.StackValueWithSimpleReceiver innerValue;
private final StackValue instanceValue;
private final Type type;
private final KotlinType kotlinType;
public EnclosedValueDescriptor(
@NotNull String fieldName,
@Nullable DeclarationDescriptor descriptor,
@NotNull StackValue.StackValueWithSimpleReceiver innerValue,
@NotNull Type type
@NotNull Type type,
@Nullable KotlinType kotlinType
) {
this.fieldName = fieldName;
this.descriptor = descriptor;
this.innerValue = innerValue;
this.instanceValue = innerValue;
this.type = type;
this.kotlinType = kotlinType;
}
public EnclosedValueDescriptor(
@@ -48,13 +52,15 @@ public final class EnclosedValueDescriptor {
@Nullable DeclarationDescriptor descriptor,
@NotNull StackValue.StackValueWithSimpleReceiver innerValue,
@NotNull StackValue.Field instanceValue,
@NotNull Type type
@NotNull Type type,
@Nullable KotlinType kotlinType
) {
this.fieldName = name;
this.descriptor = descriptor;
this.innerValue = innerValue;
this.instanceValue = instanceValue;
this.type = type;
this.kotlinType = kotlinType;
}
@NotNull
@@ -82,6 +88,11 @@ public final class EnclosedValueDescriptor {
return type;
}
@Nullable
public KotlinType getKotlinType() {
return kotlinType;
}
@Override
public String toString() {
return fieldName + " " + type + " -> " + descriptor;

View File

@@ -63,11 +63,11 @@ public interface LocalLookup {
if (sharedVarType != null) {
StackValue.Field wrapperValue = StackValue.receiverWithRefWrapper(localType, classType, fieldName, thiz, vd);
innerValue = StackValue.fieldForSharedVar(localType, classType, fieldName, wrapperValue, vd);
enclosedValueDescriptor = new EnclosedValueDescriptor(fieldName, d, innerValue, wrapperValue, type);
enclosedValueDescriptor = new EnclosedValueDescriptor(fieldName, d, innerValue, wrapperValue, type, kotlinType);
}
else {
innerValue = StackValue.field(type, kotlinType, classType, fieldName, false, thiz, vd);
enclosedValueDescriptor = new EnclosedValueDescriptor(fieldName, d, innerValue, type);
enclosedValueDescriptor = new EnclosedValueDescriptor(fieldName, d, innerValue, type, kotlinType);
}
closure.captureVariable(enclosedValueDescriptor);
@@ -118,7 +118,7 @@ public interface LocalLookup {
localType, null, classType, fieldName, false, StackValue.LOCAL_0, vd
);
closure.captureVariable(new EnclosedValueDescriptor(fieldName, d, innerValue, localType));
closure.captureVariable(new EnclosedValueDescriptor(fieldName, d, innerValue, localType, null));
return innerValue;
}

View File

@@ -29,6 +29,7 @@ import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.impl.SyntheticFieldDescriptor;
import org.jetbrains.kotlin.resolve.inline.InlineUtil;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.org.objectweb.asm.Label;
import org.jetbrains.org.objectweb.asm.Type;
@@ -64,8 +65,9 @@ public class MethodContext extends CodegenContext<CallableMemberDescriptor> {
public StackValue getReceiverExpression(KotlinTypeMapper typeMapper) {
assert getCallableDescriptorWithReceiver() != null;
@SuppressWarnings("ConstantConditions")
Type asmType = typeMapper.mapType(getCallableDescriptorWithReceiver().getExtensionReceiverParameter().getType());
return StackValue.local(AsmUtil.getReceiverIndex(this, getContextDescriptor()), asmType);
KotlinType kotlinType = getCallableDescriptorWithReceiver().getExtensionReceiverParameter().getType();
Type asmType = typeMapper.mapType(kotlinType);
return StackValue.local(AsmUtil.getReceiverIndex(this, getContextDescriptor()), asmType, kotlinType);
}
@Override

View File

@@ -77,7 +77,7 @@ class ScriptContext(
scriptDescriptor.unsubstitutedPrimaryConstructor.valueParameters[ctorImplicitReceiversParametersStart + index].name.identifier
fun getImplicitReceiverType(index: Int): Type? {
val receivers = script.kotlinScriptDefinition.value.implicitReceivers
val receivers = script.kotlinScriptDefinition.implicitReceivers
val kClass = receivers.getOrNull(index)?.classifier as? KClass<*>
return kClass?.java?.classId?.let(AsmUtil::asmTypeByClassId)
}

View File

@@ -0,0 +1,49 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.codegen.coroutines
import org.jetbrains.kotlin.codegen.optimization.boxing.isPrimitiveBoxing
import org.jetbrains.kotlin.codegen.optimization.common.asSequence
import org.jetbrains.kotlin.codegen.optimization.transformer.MethodTransformer
import org.jetbrains.kotlin.codegen.topLevelClassInternalName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.jvm.JvmPrimitiveType
import org.jetbrains.kotlin.utils.sure
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.tree.MethodInsnNode
import org.jetbrains.org.objectweb.asm.tree.MethodNode
private val BOXING_CLASS_INTERNAL_NAME =
RELEASE_COROUTINES_VERSION_SETTINGS.coroutinesJvmInternalPackageFqName().child(Name.identifier("Boxing")).topLevelClassInternalName()
object ChangeBoxingMethodTransformer : MethodTransformer() {
private val wrapperToInternalBoxing: Map<String, String>
init {
val map = hashMapOf<String, String>()
for (primitiveType in JvmPrimitiveType.values()) {
val name = primitiveType.wrapperFqName.topLevelClassInternalName()
map[name] = "box${primitiveType.javaKeywordName.capitalize()}"
}
wrapperToInternalBoxing = map
}
override fun transform(internalClassName: String, methodNode: MethodNode) {
for (boxing in methodNode.instructions.asSequence().filter { it.isPrimitiveBoxing() }) {
assert(boxing.opcode == Opcodes.INVOKESTATIC) {
"boxing shall be INVOKESTATIC wrapper.valueOf"
}
boxing as MethodInsnNode
val methodName = wrapperToInternalBoxing[boxing.owner].sure {
"expected primitive wrapper, but got ${boxing.owner}"
}
methodNode.instructions.set(
boxing,
MethodInsnNode(boxing.opcode, BOXING_CLASS_INTERNAL_NAME, methodName, boxing.desc, false)
)
}
}
}

View File

@@ -50,7 +50,7 @@ abstract class AbstractCoroutineCodegen(
element: KtElement,
closureContext: ClosureContext,
classBuilder: ClassBuilder,
private val userDataForDoResume: Map<out FunctionDescriptor.UserDataKey<*>, *>? = null
private val userDataForDoResume: Map<out CallableDescriptor.UserDataKey<*>, *>? = null
) : ClosureCodegen(
outerExpressionCodegen.state,
element, null, closureContext, null,
@@ -347,7 +347,7 @@ class CoroutineCodegenForLambda private constructor(
// pass captured closure to constructor
val constructorParameters = calculateConstructorParameters(typeMapper, languageVersionSettings, closure, owner)
for (parameter in constructorParameters) {
StackValue.field(parameter, thisInstance).put(parameter.fieldType, this)
StackValue.field(parameter, thisInstance).put(parameter.fieldType, parameter.fieldKotlinType, this)
}
// load resultContinuation
@@ -377,7 +377,11 @@ class CoroutineCodegenForLambda private constructor(
load(1, AsmTypes.OBJECT_TYPE)
iconst(index - 1)
aload(AsmTypes.OBJECT_TYPE)
StackValue.coerce(AsmTypes.OBJECT_TYPE, fieldInfoForCoroutineLambdaParameter.fieldType, this)
StackValue.coerce(
AsmTypes.OBJECT_TYPE, builtIns.nullableAnyType,
fieldInfoForCoroutineLambdaParameter.fieldType, fieldInfoForCoroutineLambdaParameter.fieldKotlinType,
this
)
putfield(
fieldInfoForCoroutineLambdaParameter.ownerInternalName,
fieldInfoForCoroutineLambdaParameter.fieldName,
@@ -386,7 +390,11 @@ class CoroutineCodegenForLambda private constructor(
} else {
if (generateErasedCreate) {
load(index, AsmTypes.OBJECT_TYPE)
StackValue.coerce(AsmTypes.OBJECT_TYPE, fieldInfoForCoroutineLambdaParameter.fieldType, this)
StackValue.coerce(
AsmTypes.OBJECT_TYPE, builtIns.nullableAnyType,
fieldInfoForCoroutineLambdaParameter.fieldType, fieldInfoForCoroutineLambdaParameter.fieldKotlinType,
this
)
} else {
load(index, fieldInfoForCoroutineLambdaParameter.fieldType)
}
@@ -434,6 +442,7 @@ class CoroutineCodegenForLambda private constructor(
FieldInfo.createForHiddenField(
typeMapper.mapClass(closureContext.thisDescriptor),
typeMapper.mapType(type),
type,
name
)
@@ -448,7 +457,8 @@ class CoroutineCodegenForLambda private constructor(
return CoroutineTransformerMethodVisitor(
mv, access, name, desc, null, null,
obtainClassBuilderForCoroutineState = { v },
lineNumber = CodegenUtil.getLineNumberForElement(element, false) ?: 0,
element = element,
diagnostics = state.diagnostics,
shouldPreserveClassInitialization = constructorCallNormalizationMode.shouldPreserveClassInitialization,
containingClassInternalName = v.thisName,
isForNamedFunction = false,

View File

@@ -6,6 +6,7 @@
package org.jetbrains.kotlin.codegen.coroutines
import com.intellij.util.containers.Stack
import org.jetbrains.kotlin.backend.common.CodegenUtil
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.codegen.ClassBuilder
import org.jetbrains.kotlin.codegen.StackValue
@@ -19,7 +20,10 @@ import org.jetbrains.kotlin.codegen.optimization.fixStack.top
import org.jetbrains.kotlin.codegen.optimization.transformer.MethodTransformer
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.config.isReleaseCoroutines
import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import org.jetbrains.kotlin.utils.addToStdlib.cast
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
@@ -56,9 +60,11 @@ class CoroutineTransformerMethodVisitor(
obtainClassBuilderForCoroutineState: () -> ClassBuilder,
private val isForNamedFunction: Boolean,
private val shouldPreserveClassInitialization: Boolean,
private val lineNumber: Int,
private val languageVersionSettings: LanguageVersionSettings,
private val sourceFile: String,
// These two are needed to report diagnostics about suspension points inside critical section
private val element: KtElement,
private val diagnostics: DiagnosticSink,
// It's only matters for named functions, may differ from '!isStatic(access)' in case of DefaultImpls
private val needDispatchReceiver: Boolean = false,
// May differ from containingClassInternalName in case of DefaultImpls
@@ -68,6 +74,7 @@ class CoroutineTransformerMethodVisitor(
) : TransformationMethodVisitor(delegate, access, name, desc, signature, exceptions) {
private val classBuilderForCoroutineState: ClassBuilder by lazy(obtainClassBuilderForCoroutineState)
private val lineNumber = element?.let { CodegenUtil.getLineNumberForElement(it, false) } ?: 0
private var continuationIndex = if (isForNamedFunction) -1 else 0
private var dataIndex = if (isForNamedFunction) -1 else 1
@@ -83,14 +90,18 @@ class CoroutineTransformerMethodVisitor(
FixStackMethodTransformer().transform(containingClassInternalName, methodNode)
RedundantLocalsEliminationMethodTransformer(languageVersionSettings).transform(containingClassInternalName, methodNode)
if (languageVersionSettings.isReleaseCoroutines()) {
ChangeBoxingMethodTransformer.transform(containingClassInternalName, methodNode)
}
updateMaxStack(methodNode)
val suspensionPoints = collectSuspensionPoints(methodNode)
checkForSuspensionPointInsideMonitor(methodNode, suspensionPoints)
// First instruction in the method node may change in case of named function
val actualCoroutineStart = methodNode.instructions.first
var startLabelNode: LabelNode? = null
if (isForNamedFunction) {
ReturnUnitMethodTransformer.transform(containingClassInternalName, methodNode)
@@ -105,7 +116,7 @@ class CoroutineTransformerMethodVisitor(
}
continuationIndex = methodNode.maxLocals++
startLabelNode = prepareMethodNodePreludeForNamedFunction(methodNode)
prepareMethodNodePreludeForNamedFunction(methodNode)
} else {
ReturnUnitMethodTransformer.cleanUpReturnsUnitMarkers(methodNode, ReturnUnitMethodTransformer.findReturnsUnitMarks(methodNode))
}
@@ -127,14 +138,16 @@ class CoroutineTransformerMethodVisitor(
val suspendMarkerVarIndex = methodNode.maxLocals++
val suspensionPointLabels = suspensionPoints.withIndex().map {
val suspensionPointLineNumbers = suspensionPoints.map { findSuspensionPointLineNumber(it) }
val continuationLabels = suspensionPoints.withIndex().map {
transformCallAndReturnContinuationLabel(it.index + 1, it.value, methodNode, suspendMarkerVarIndex)
}
val defaultLabel = LabelNode()
val tableSwitchLabel = LabelNode()
methodNode.instructions.apply {
val startLabel = LabelNode()
val tableSwitchLabel = LabelNode()
val firstStateLabel = LabelNode()
val defaultLabel = LabelNode()
// tableswitch(this.label)
insertBefore(
@@ -151,13 +164,13 @@ class CoroutineTransformerMethodVisitor(
0,
suspensionPoints.size,
defaultLabel,
startLabel, *suspensionPointLabels.toTypedArray()
firstStateLabel, *continuationLabels.toTypedArray()
),
startLabel
firstStateLabel
)
)
insert(startLabel, withInstructionAdapter {
insert(firstStateLabel, withInstructionAdapter {
generateResumeWithExceptionCheck(languageVersionSettings.isReleaseCoroutines(), dataIndex, exceptionIndex)
})
insert(last, defaultLabel)
@@ -171,31 +184,90 @@ class CoroutineTransformerMethodVisitor(
dropSuspensionMarkers(methodNode, suspensionPoints)
methodNode.removeEmptyCatchBlocks()
if (isForNamedFunction) {
addContinuationToLvt(
methodNode,
startLabelNode.sure { "start label has not been initialized during prelude generation" },
defaultLabel
)
}
// The parameters (and 'this') shall live throughout the method, otherwise, d8 emits warning about invalid debug info
val startLabel = LabelNode()
val endLabel = LabelNode()
methodNode.instructions.insertBefore(methodNode.instructions.first, startLabel)
methodNode.instructions.insert(methodNode.instructions.last, endLabel)
fixLvtForParameters(methodNode, startLabel, endLabel)
if (languageVersionSettings.isReleaseCoroutines() && !isCrossinlineLambda) {
val suspensionPointLabelNodes = listOf(tableSwitchLabel) + suspensionPointLabels.map {
it.label.info.safeAs<LabelNode>()
.sure { "suspensionPointLabel shall have valid info. Check state-machine generation." }
writeDebugMetadata(methodNode, suspensionPointLineNumbers, spilledToVariableMapping)
}
}
private fun findSuspensionPointLineNumber(suspensionPoint: SuspensionPoint) =
suspensionPoint.suspensionCallBegin.findPreviousOrNull { it is LineNumberNode } as LineNumberNode?
private fun checkForSuspensionPointInsideMonitor(methodNode: MethodNode, suspensionPoints: List<SuspensionPoint>) {
if (methodNode.instructions.asSequence().none { it.opcode == Opcodes.MONITORENTER }) return
val cfg = ControlFlowGraph.build(methodNode)
val monitorDepthMap = hashMapOf<AbstractInsnNode, Int>()
fun addMonitorDepthToSuccs(index: Int, depth: Int) {
val insn = methodNode.instructions[index]
monitorDepthMap[insn] = depth
val newDepth = when (insn.opcode) {
Opcodes.MONITORENTER -> depth + 1
Opcodes.MONITOREXIT -> depth - 1
else -> depth
}
writeDebugMetadata(methodNode, suspensionPointLabelNodes, spilledToVariableMapping)
for (succIndex in cfg.getSuccessorsIndices(index)) {
if (monitorDepthMap[methodNode.instructions[succIndex]] == null) {
addMonitorDepthToSuccs(succIndex, newDepth)
}
}
}
addMonitorDepthToSuccs(0, 0)
for (suspensionPoint in suspensionPoints) {
if (monitorDepthMap[suspensionPoint.suspensionCallBegin]?.let { it > 0 } == true) {
// TODO: Support crossinline suspend lambdas
val stackTraceElement = StackTraceElement(
containingClassInternalName,
methodNode.name,
sourceFile,
findSuspensionPointLineNumber(suspensionPoint)?.line ?: -1
)
diagnostics.report(ErrorsJvm.SUSPENSION_POINT_INSIDE_MONITOR.on(element, "$stackTraceElement"))
return
}
}
}
private fun fixLvtForParameters(methodNode: MethodNode, startLabel: LabelNode, endLabel: LabelNode) {
// We need to skip continuation, since the inliner likes to remap variables there.
// But this is not a problem, since we have separate $continuation LVT entry
val paramsNum =
/* this */ (if (internalNameForDispatchReceiver != null) 1 else 0) +
/* real params */ Type.getArgumentTypes(methodNode.desc).size -
/* no continuation */ if (isForNamedFunction) 1 else 0
for (i in 0..paramsNum) {
fixRangeOfLvtRecord(methodNode, i, startLabel, endLabel)
}
}
private fun fixRangeOfLvtRecord(methodNode: MethodNode, index: Int, startLabel: LabelNode, endLabel: LabelNode) {
val vars = methodNode.localVariables.filter { it.index == index }
assert(vars.size <= 1) {
"Someone else occupies parameter's slot at $index"
}
vars.firstOrNull()?.let {
it.start = startLabel
it.end = endLabel
}
}
private fun writeDebugMetadata(
methodNode: MethodNode,
suspensionPointLabels: List<LabelNode>,
suspensionPointLineNumbers: List<LineNumberNode?>,
spilledToLocalMapping: List<List<SpilledVariableDescriptor>>
) {
val lines = suspensionPointLabels.map { label ->
label.safeAs<AbstractInsnNode>()?.findNextOrNull { it is LineNumberNode }.safeAs<LineNumberNode>()?.line ?: -1
}
val lines = suspensionPointLineNumbers.map { it?.line ?: -1 }
val metadata = classBuilderForCoroutineState.newAnnotation(DEBUG_METADATA_ANNOTATION_ASM_TYPE.descriptor, true)
metadata.visit(COROUTINES_METADATA_SOURCE_FILE_JVM_NAME, sourceFile)
metadata.visit(COROUTINES_METADATA_LINE_NUMBERS_JVM_NAME, lines.toIntArray())
@@ -220,7 +292,11 @@ class CoroutineTransformerMethodVisitor(
metadata.visitEnd()
}
private fun addContinuationToLvt(methodNode: MethodNode, startLabel: LabelNode, endLabel: LabelNode) {
// Warning! This is _continuation_, not _completion_, it can be allocated inside the method, thus, it is incorrect to treat it
// as a parameter
private fun addContinuationToLvt(methodNode: MethodNode, startLabel: LabelNode) {
val endLabel = LabelNode()
methodNode.instructions.insert(methodNode.instructions.last, endLabel)
methodNode.localVariables.add(
LocalVariableNode(
"\$continuation",
@@ -288,7 +364,7 @@ class CoroutineTransformerMethodVisitor(
)
}
private fun prepareMethodNodePreludeForNamedFunction(methodNode: MethodNode): LabelNode {
private fun prepareMethodNodePreludeForNamedFunction(methodNode: MethodNode) {
val objectTypeForState = Type.getObjectType(classBuilderForCoroutineState.thisName)
val continuationArgumentIndex = getLastParameterIndex(methodNode.desc, methodNode.access)
methodNode.instructions.asSequence().filterIsInstance<VarInsnNode>().forEach {
@@ -297,8 +373,6 @@ class CoroutineTransformerMethodVisitor(
it.`var` = continuationIndex
}
val startLabel = LabelNode()
methodNode.instructions.insert(withInstructionAdapter {
val createStateInstance = Label()
val afterCoroutineStateCreated = Label()
@@ -318,7 +392,6 @@ class CoroutineTransformerMethodVisitor(
// `doResume` just before calling the suspend function (see kotlin.coroutines.experimental.jvm.internal.CoroutineImplForNamedFunction).
// So, if it's set we're in continuation.
visitLabel(startLabel.label)
visitVarInsn(Opcodes.ALOAD, continuationArgumentIndex)
instanceOf(objectTypeForState)
ifeq(createStateInstance)
@@ -360,6 +433,8 @@ class CoroutineTransformerMethodVisitor(
visitLabel(afterCoroutineStateCreated)
addContinuationToLvt(methodNode, LabelNode(afterCoroutineStateCreated))
visitVarInsn(Opcodes.ALOAD, continuationIndex)
getfield(classBuilderForCoroutineState.thisName, languageVersionSettings.dataFieldName(), AsmTypes.OBJECT_TYPE.descriptor)
visitVarInsn(Opcodes.ASTORE, dataIndex)
@@ -370,7 +445,6 @@ class CoroutineTransformerMethodVisitor(
visitVarInsn(Opcodes.ASTORE, exceptionIndex)
}
})
return startLabel
}
private fun removeUnreachableSuspensionPointsAndExitPoints(methodNode: MethodNode, suspensionPoints: MutableList<SuspensionPoint>) {
@@ -870,17 +944,11 @@ private fun allSuspensionPointsAreTailCalls(
}
if (insideTryBlock) return@all false
safelyReachableReturns[endIndex + 1]?.all { returnIndex ->
sourceFrames[returnIndex].top().sure {
"There must be some value on stack to return"
}.insns.all { sourceInsn ->
sourceInsn?.let(instructions::indexOf) in beginIndex..endIndex
}
} ?: false
safelyReachableReturns[endIndex + 1] != null
}
}
internal class IgnoringCopyOperationSourceInterpreter : SourceInterpreter() {
internal class IgnoringCopyOperationSourceInterpreter : SourceInterpreter(OPTIMIZATION_ASM_API_VERSION) {
override fun copyOperation(insn: AbstractInsnNode?, value: SourceValue?) = value
}

View File

@@ -66,7 +66,8 @@ open class SuspendFunctionGenerationStrategy(
return CoroutineTransformerMethodVisitor(
mv, access, name, desc, null, null, containingClassInternalName, this::classBuilderForCoroutineState,
isForNamedFunction = true,
lineNumber = CodegenUtil.getLineNumberForElement(declaration, false) ?: 0,
element = declaration,
diagnostics = state.diagnostics,
shouldPreserveClassInitialization = constructorCallNormalizationMode.shouldPreserveClassInitialization,
needDispatchReceiver = originalSuspendDescriptor.dispatchReceiverParameter != null,
internalNameForDispatchReceiver = containingClassInternalNameOrNull(),

View File

@@ -56,7 +56,7 @@ const val DO_RESUME_METHOD_NAME = "doResume"
const val INVOKE_SUSPEND_METHOD_NAME = "invokeSuspend"
const val EXCEPTION_FIELD_NAME = "exception"
private val RELEASE_COROUTINES_VERSION_SETTINGS = LanguageVersionSettingsImpl(LanguageVersion.KOTLIN_1_3, ApiVersion.KOTLIN_1_3)
val RELEASE_COROUTINES_VERSION_SETTINGS = LanguageVersionSettingsImpl(LanguageVersion.KOTLIN_1_3, ApiVersion.KOTLIN_1_3)
fun LanguageVersionSettings.isResumeImplMethodName(name: String) =
if (isReleaseCoroutines())
@@ -117,10 +117,10 @@ private val GET_CONTEXT_METHOD_NAME = "getContext"
data class ResolvedCallWithRealDescriptor(val resolvedCall: ResolvedCall<*>, val fakeContinuationExpression: KtExpression)
@JvmField
val INITIAL_DESCRIPTOR_FOR_SUSPEND_FUNCTION = object : FunctionDescriptor.UserDataKey<FunctionDescriptor> {}
val INITIAL_DESCRIPTOR_FOR_SUSPEND_FUNCTION = object : CallableDescriptor.UserDataKey<FunctionDescriptor> {}
@JvmField
val INITIAL_SUSPEND_DESCRIPTOR_FOR_DO_RESUME = object : FunctionDescriptor.UserDataKey<FunctionDescriptor> {}
val INITIAL_SUSPEND_DESCRIPTOR_FOR_DO_RESUME = object : CallableDescriptor.UserDataKey<FunctionDescriptor> {}
// Resolved calls to suspension function contain descriptors as they visible within coroutines:
// E.g. `fun <V> await(f: CompletableFuture<V>): V` instead of `fun <V> await(f: CompletableFuture<V>, machine: Continuation<V>): Unit`

View File

@@ -169,7 +169,7 @@ private fun checkUpdatedExpectedType(was: Type?, new: Type) {
}
}
private class MySourceInterpreter : SourceInterpreter() {
private class MySourceInterpreter : SourceInterpreter(OPTIMIZATION_ASM_API_VERSION) {
override fun copyOperation(insn: AbstractInsnNode, value: SourceValue) =
when {
insn.isStoreOperation() || insn.isLoadOperation() -> SourceValue(value.size, insn)

View File

@@ -10,13 +10,12 @@ import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactoryImpl
import org.jetbrains.kotlin.resolve.calls.smartcasts.getKotlinTypeForComparison
import org.jetbrains.kotlin.resolve.calls.smartcasts.getKotlinTypeWithPossibleSmartCastToFP
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
import org.jetbrains.org.objectweb.asm.Type
class TypeAndNullability(@JvmField val type: Type, @JvmField val isNullable: Boolean)
@@ -35,60 +34,31 @@ fun calcProperTypeForIeee754ArithmeticIfNeeded(
return TypeAndNullability(asmType, isNullable)
}
private fun KotlinType.isFloatingPointOrNullable() =
KotlinBuiltIns.isDoubleOrNullableDouble(this) || KotlinBuiltIns.isFloatOrNullableFloat(this)
private fun KtExpression.getKotlinTypeForComparison(bindingContext: BindingContext): KotlinType? =
when {
this is KtProperty -> bindingContext[BindingContext.VARIABLE, this]?.type
else -> kotlinType(bindingContext)
}
fun legacyCalcTypeForIeee754ArithmeticIfNeeded(
expression: KtExpression?,
bindingContext: BindingContext,
descriptor: DeclarationDescriptor,
languageVersionSettings: LanguageVersionSettings
): TypeAndNullability? {
val ktType = expression?.getKotlinTypeForComparison(bindingContext) ?: return null
if (KotlinBuiltIns.isDoubleOrNullableDouble(ktType)) {
return TypeAndNullability(
Type.DOUBLE_TYPE,
TypeUtils.isNullableType(ktType)
)
}
if (KotlinBuiltIns.isFloatOrNullableFloat(ktType)) {
return TypeAndNullability(
Type.FLOAT_TYPE,
TypeUtils.isNullableType(ktType)
)
}
// NB. Using DataFlowValueFactoryImpl is a hack, but it is ok for 'legacy'
val dataFlow = DataFlowValueFactoryImpl(languageVersionSettings).createDataFlowValue(
expression,
ktType,
bindingContext,
descriptor
val ktType = expression.getKotlinTypeWithPossibleSmartCastToFP(
// NB. Using DataFlowValueFactoryImpl is a hack, but it is ok for 'legacy'
bindingContext, descriptor, languageVersionSettings, DataFlowValueFactoryImpl(languageVersionSettings)
)
val stableTypes = bindingContext.getDataFlowInfoBefore(expression).getStableTypes(dataFlow, languageVersionSettings)
return stableTypes.firstNotNullResult {
when {
KotlinBuiltIns.isDoubleOrNullableDouble(it) -> TypeAndNullability(
if (ktType != null) {
if (KotlinBuiltIns.isDoubleOrNullableDouble(ktType)) {
return TypeAndNullability(
Type.DOUBLE_TYPE,
TypeUtils.isNullableType(
it
)
TypeUtils.isNullableType(ktType)
)
KotlinBuiltIns.isFloatOrNullableFloat(it) -> TypeAndNullability(
}
if (KotlinBuiltIns.isFloatOrNullableFloat(ktType)) {
return TypeAndNullability(
Type.FLOAT_TYPE,
TypeUtils.isNullableType(
it
)
TypeUtils.isNullableType(ktType)
)
else -> null
}
}
return null
}

View File

@@ -21,8 +21,10 @@ import org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf
import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmProtoBufUtil
import org.jetbrains.kotlin.metadata.jvm.serialization.JvmStringTable
import org.jetbrains.kotlin.protobuf.MessageLite
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin.Companion.NO_ORIGIN
import org.jetbrains.kotlin.utils.addToStdlib.cast
import org.jetbrains.org.objectweb.asm.*
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
import org.jetbrains.org.objectweb.asm.tree.*
@@ -131,10 +133,9 @@ class AnonymousObjectTransformer(
constructor!!, allCapturedParamBuilder, constructorParamBuilder,transformationInfo, parentRemapper
)
val crossinlineSuspendElement = capturedCrossinlineSuspendElement()
val capturesCrossinlineSuspend = (!inliningContext.isInliningLambda || inliningContext.isContinuation) &&
inliningContext.expressionMap.values.any { lambda ->
lambda is PsiExpressionLambda && lambda.isCrossInline && lambda.invokeMethodDescriptor.isSuspend
}
crossinlineSuspendElement != null
val deferringMethods = ArrayList<DeferredMethodVisitor>()
@@ -158,11 +159,18 @@ class AnonymousObjectTransformer(
capturesCrossinlineSuspend && !inliningContext.isContinuation && continuationClassName != null
val deferringVisitor =
when {
generateStateMachineForLambda -> newStateMachineForLambda(classBuilder, next)
generateStateMachineForNamedFunction -> newStateMachineForNamedFunction(classBuilder, next, continuationClassName!!)
else -> newMethod(classBuilder, next)
}
if (crossinlineSuspendElement != null) {
when {
generateStateMachineForLambda -> newStateMachineForLambda(classBuilder, next, crossinlineSuspendElement)
generateStateMachineForNamedFunction -> newStateMachineForNamedFunction(
classBuilder,
next,
continuationClassName!!,
crossinlineSuspendElement
)
else -> newMethod(classBuilder, next)
}
} else newMethod(classBuilder, next)
val funResult = inlineMethodAndUpdateGlobalResult(parentRemapper, deferringVisitor, next, allCapturedParamBuilder, false)
val returnType = Type.getReturnType(next.desc)
@@ -227,6 +235,10 @@ class AnonymousObjectTransformer(
return transformationResult
}
private fun capturedCrossinlineSuspendElement(): KtExpression? = inliningContext.expressionMap.values.find { lambda ->
lambda is PsiExpressionLambda && lambda.isCrossInline && lambda.invokeMethodDescriptor.isSuspend
}?.cast<PsiExpressionLambda>()?.functionWithBodyOrCallableReference
private fun writeTransformedMetadata(header: KotlinClassHeader, classBuilder: ClassBuilder) {
writeKotlinMetadata(classBuilder, state, header.kind, header.extraInt) action@ { av ->
val (newProto, newStringTable) = transformMetadata(header) ?: run {
@@ -435,7 +447,7 @@ class AnonymousObjectTransformer(
}
}
private fun newStateMachineForLambda(builder: ClassBuilder, original: MethodNode): DeferredMethodVisitor {
private fun newStateMachineForLambda(builder: ClassBuilder, original: MethodNode, element: KtExpression): DeferredMethodVisitor {
return DeferredMethodVisitor(
MethodNode(
original.access, original.name, original.desc, original.signature,
@@ -448,7 +460,8 @@ class AnonymousObjectTransformer(
ArrayUtil.toStringArray(original.exceptions)
), original.access, original.name, original.desc, null, null,
obtainClassBuilderForCoroutineState = { builder },
lineNumber = 0, // <- TODO
element = element,
diagnostics = state.diagnostics,
languageVersionSettings = languageVersionSettings,
shouldPreserveClassInitialization = state.constructorCallNormalizationMode.shouldPreserveClassInitialization,
containingClassInternalName = builder.thisName,
@@ -462,7 +475,8 @@ class AnonymousObjectTransformer(
private fun newStateMachineForNamedFunction(
builder: ClassBuilder,
original: MethodNode,
continuationClassName: String
continuationClassName: String,
element: KtExpression
): DeferredMethodVisitor {
assert(inliningContext is RegeneratedClassContext)
return DeferredMethodVisitor(
@@ -477,7 +491,8 @@ class AnonymousObjectTransformer(
ArrayUtil.toStringArray(original.exceptions)
), original.access, original.name, original.desc, null, null,
obtainClassBuilderForCoroutineState = { (inliningContext as RegeneratedClassContext).continuationBuilders[continuationClassName]!! },
lineNumber = 0, // <- TODO
element = element,
diagnostics = state.diagnostics,
languageVersionSettings = languageVersionSettings,
shouldPreserveClassInitialization = state.constructorCallNormalizationMode.shouldPreserveClassInitialization,
containingClassInternalName = builder.thisName,

View File

@@ -255,25 +255,27 @@ class PsiExpressionLambda(
arrayListOf<CapturedParamDesc>().apply {
val captureThis = closure.capturedOuterClassDescriptor
if (captureThis != null) {
val type = typeMapper.mapType(captureThis)
val kotlinType = captureThis.defaultType
val type = typeMapper.mapType(kotlinType)
val descriptor = EnclosedValueDescriptor(
AsmUtil.CAPTURED_THIS_FIELD, null,
StackValue.field(type, lambdaClassType, AsmUtil.CAPTURED_THIS_FIELD, false, StackValue.LOCAL_0),
type
type, kotlinType
)
add(getCapturedParamInfo(descriptor))
}
if (closure.capturedReceiverFromOuterContext != null) {
val type = typeMapper.mapType(closure.capturedReceiverFromOuterContext!!).let {
val capturedReceiver = closure.capturedReceiverFromOuterContext
if (capturedReceiver != null) {
val type = typeMapper.mapType(capturedReceiver).let {
if (isBoundCallableReference) it.boxReceiverForBoundReference() else it
}
val fieldName = closure.getCapturedReceiverFieldName(typeMapper.bindingContext, languageVersionSettings)
val descriptor = EnclosedValueDescriptor(
fieldName, null,
StackValue.field(type, lambdaClassType, fieldName, false, StackValue.LOCAL_0),
type
StackValue.field(type, capturedReceiver, lambdaClassType, fieldName, false, StackValue.LOCAL_0),
type, capturedReceiver
)
add(getCapturedParamInfo(descriptor))
}

View File

@@ -15,6 +15,7 @@ import org.jetbrains.kotlin.codegen.inline.FieldRemapper.Companion.foldName
import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicMethods
import org.jetbrains.kotlin.codegen.optimization.ApiVersionCallsPreprocessingMethodTransformer
import org.jetbrains.kotlin.codegen.optimization.FixStackWithLabelNormalizationMethodTransformer
import org.jetbrains.kotlin.codegen.optimization.common.ControlFlowGraph
import org.jetbrains.kotlin.codegen.optimization.common.InsnSequence
import org.jetbrains.kotlin.codegen.optimization.common.asSequence
import org.jetbrains.kotlin.codegen.optimization.common.isMeaningful
@@ -23,7 +24,7 @@ import org.jetbrains.kotlin.codegen.optimization.fixStack.top
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ParameterDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.resolve.isInlineClassType
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.resolve.jvm.AsmTypes.OBJECT_TYPE
import org.jetbrains.kotlin.types.KotlinType
@@ -640,26 +641,78 @@ class MethodInliner(
private fun replaceContinuationAccessesWithFakeContinuationsIfNeeded(processingNode: MethodNode) {
val lambdaInfo = inliningContext.lambdaInfo ?: return
if (!lambdaInfo.invokeMethodDescriptor.isSuspend) return
val sources = analyzeMethodNodeBeforeInline(processingNode)
val cfg = ControlFlowGraph.build(processingNode)
val aload0s = processingNode.instructions.asSequence().filter { it.opcode == Opcodes.ALOAD && it.safeAs<VarInsnNode>()?.`var` == 0 }
// Expected pattern here:
// ALOAD 0
// ICONST_0
// INVOKESTATIC InlineMarker.mark
// INVOKE* suspendingFunction(..., Continuation;)Ljava/lang/Object;
val continuationAsParameterAload0s =
aload0s.filter { it.next?.next?.let(::isBeforeSuspendMarker) == true && isSuspendCall(it.next?.next?.next) }
replaceContinuationsWithFakeOnes(continuationAsParameterAload0s, processingNode)
val visited = hashSetOf<AbstractInsnNode>()
fun findMeaningfulSuccs(insn: AbstractInsnNode): Collection<AbstractInsnNode> {
if (!visited.add(insn)) return emptySet()
val res = hashSetOf<AbstractInsnNode>()
for (succIndex in cfg.getSuccessorsIndices(insn)) {
val succ = processingNode.instructions[succIndex]
if (succ.isMeaningful) res.add(succ)
else res.addAll(findMeaningfulSuccs(succ))
}
return res
}
// After inlining suspendCoroutineUninterceptedOrReturn there will be suspension point, which is not a MethodInsnNode.
// So, it is incorrect to expect MethodInsnNodes only
val suspensionPoints = processingNode.instructions.asSequence()
.filter { isBeforeSuspendMarker(it) }
.flatMap { findMeaningfulSuccs(it).asSequence() }
.filter { it is MethodInsnNode }
val toReplace = hashSetOf<AbstractInsnNode>()
for (suspensionPoint in suspensionPoints) {
assert(suspensionPoint is MethodInsnNode) {
"suspensionPoint shall be MethodInsnNode, but instead $suspensionPoint"
}
suspensionPoint as MethodInsnNode
assert(Type.getReturnType(suspensionPoint.desc) == OBJECT_TYPE) {
"suspensionPoint shall return $OBJECT_TYPE, but returns ${Type.getReturnType(suspensionPoint.desc)}"
}
val frame = sources[processingNode.instructions.indexOf(suspensionPoint)] ?: continue
val paramTypes = Type.getArgumentTypes(suspensionPoint.desc)
if (suspensionPoint.name.endsWith(JvmAbi.DEFAULT_PARAMS_IMPL_SUFFIX)) {
// Expected pattern here:
// ALOAD 0
// (ICONST or other integers creating instruction)
// (ACONST_NULL or ALOAD)
// ICONST_0
// INVOKESTATIC InlineMarker.mark
// INVOKE* suspendingFunction$default(..., Continuation;ILjava/lang/Object)Ljava/lang/Object;
assert(paramTypes.size >= 3) {
"${suspensionPoint.name}${suspensionPoint.desc} shall have 3+ parameters"
}
} else {
// Expected pattern here:
// ALOAD 0
// ICONST_0
// INVOKESTATIC InlineMarker.mark
// INVOKE* suspendingFunction(..., Continuation;)Ljava/lang/Object;
assert(paramTypes.isNotEmpty()) {
"${suspensionPoint.name}${suspensionPoint.desc} shall have 1+ parameters"
}
}
paramTypes.reversed().asSequence().withIndex()
.filter { it.value == languageVersionSettings.continuationAsmType() || it.value == OBJECT_TYPE }
.flatMap { frame.getStack(frame.stackSize - it.index - 1).insns.asSequence() }
.filter { it in aload0s }.let { toReplace.addAll(it) }
}
// Expected pattern here:
// ALOAD 0
// ASTORE N
// This pattern may occur after multiple inlines
val continuationToStoreAload0s = aload0s.filter { it.next?.opcode == Opcodes.ASTORE }
replaceContinuationsWithFakeOnes(continuationToStoreAload0s, processingNode)
// Note, that this is not a suspension point, thus we check it separately
toReplace.addAll(aload0s.filter { it.next?.opcode == Opcodes.ASTORE })
// Expected pattern here:
// ALOAD 0
// INVOKEINTERFACE kotlin/jvm/functions/FunctionN.invoke (...,Ljava/lang/Object;)Ljava/lang/Object;
val continuationAsLambdaParameterAload0s = aload0s.filter { isLambdaCall(it.next) }
replaceContinuationsWithFakeOnes(continuationAsLambdaParameterAload0s, processingNode)
toReplace.addAll(aload0s.filter { isLambdaCall(it.next) })
replaceContinuationsWithFakeOnes(toReplace, processingNode)
}
private fun isLambdaCall(invoke: AbstractInsnNode?): Boolean {
@@ -672,7 +725,7 @@ class MethodInliner(
}
private fun replaceContinuationsWithFakeOnes(
continuations: Sequence<AbstractInsnNode>,
continuations: Collection<AbstractInsnNode>,
node: MethodNode
) {
for (toReplace in continuations) {

View File

@@ -27,6 +27,7 @@ import org.jetbrains.org.objectweb.asm.ClassVisitor;
import org.jetbrains.org.objectweb.asm.FieldVisitor;
import org.jetbrains.org.objectweb.asm.MethodVisitor;
import org.jetbrains.org.objectweb.asm.commons.*;
import org.jetbrains.org.objectweb.asm.commons.FieldRemapper;
public class RemappingClassBuilder extends DelegatingClassBuilder {
private final ClassBuilder builder;
@@ -66,9 +67,8 @@ public class RemappingClassBuilder extends DelegatingClassBuilder {
@Nullable String signature,
@Nullable Object value
) {
return new RemappingFieldAdapter(
builder.newField(origin, access, name, remapper.mapDesc(desc), remapper.mapSignature(signature, true), value),
remapper
return new FieldRemapper(
builder.newField(origin, access, name, remapper.mapDesc(desc), remapper.mapSignature(signature, true), value), remapper
);
}
@@ -82,8 +82,7 @@ public class RemappingClassBuilder extends DelegatingClassBuilder {
@Nullable String signature,
@Nullable String[] exceptions
) {
return new RemappingMethodAdapter(
access, desc,
return new MethodRemapper(
builder.newMethod(origin, access, name, remapper.mapMethodDesc(desc), remapper.mapSignature(signature, false), exceptions),
remapper
);
@@ -92,12 +91,12 @@ public class RemappingClassBuilder extends DelegatingClassBuilder {
@Override
@NotNull
public AnnotationVisitor newAnnotation(@NotNull String desc, boolean visible) {
return new RemappingAnnotationAdapter(builder.newAnnotation(remapper.mapDesc(desc), visible), remapper);
return new AnnotationRemapper(builder.newAnnotation(remapper.mapDesc(desc), visible), remapper);
}
@Override
@NotNull
public ClassVisitor getVisitor() {
return new RemappingClassAdapter(builder.getVisitor(), remapper);
return new ClassRemapper(builder.getVisitor(), remapper);
}
}

View File

@@ -19,6 +19,10 @@ package org.jetbrains.kotlin.codegen.inline
import gnu.trove.TIntIntHashMap
import org.jetbrains.kotlin.codegen.ClassBuilder
import org.jetbrains.kotlin.codegen.SourceInfo
import org.jetbrains.kotlin.codegen.inline.SMAP.Companion.END
import org.jetbrains.kotlin.codegen.inline.SMAP.Companion.FILE_SECTION
import org.jetbrains.kotlin.codegen.inline.SMAP.Companion.LINE_SECTION
import org.jetbrains.kotlin.codegen.inline.SMAP.Companion.STRATA_SECTION
import java.util.*
const val KOTLIN_STRATA_NAME = "Kotlin"
@@ -49,9 +53,9 @@ class SMAPBuilder(
}
private fun generateDefaultStrata(realMappings: List<FileMapping>): String {
val fileIds = "*F" + realMappings.mapIndexed { id, file -> "\n${file.toSMAPFile(id + 1)}" }.joinToString("")
val lineMappings = "*L" + realMappings.joinToString("") { it.toSMAPMapping() }
return "*S $KOTLIN_STRATA_NAME\n$fileIds\n$lineMappings\n*E\n"
val fileIds = FILE_SECTION + realMappings.mapIndexed { id, file -> "\n${file.toSMAPFile(id + 1)}" }.joinToString("")
val lineMappings = LINE_SECTION + realMappings.joinToString("") { it.toSMAPMapping() }
return "$STRATA_SECTION $KOTLIN_STRATA_NAME\n$fileIds\n$lineMappings\n$END\n"
}
private fun generateDebugStrata(realMappings: List<FileMapping>): String {
@@ -69,9 +73,9 @@ class SMAPBuilder(
if (combinedMapping.lineMappings.isEmpty()) return ""
val newMappings = listOf(combinedMapping)
val fileIds = "*F" + newMappings.mapIndexed { id, file -> "\n${file.toSMAPFile(id + 1)}" }.joinToString("")
val lineMappings = "*L" + newMappings.joinToString("") { it.toSMAPMapping() }
return "*S $KOTLIN_DEBUG_STRATA_NAME\n$fileIds\n$lineMappings\n*E\n"
val fileIds = FILE_SECTION + newMappings.mapIndexed { id, file -> "\n${file.toSMAPFile(id + 1)}" }.joinToString("")
val lineMappings = LINE_SECTION + newMappings.joinToString("") { it.toSMAPMapping() }
return "$STRATA_SECTION $KOTLIN_DEBUG_STRATA_NAME\n$fileIds\n$lineMappings\n$END\n"
}
private fun RangeMapping.toSMAP(fileId: Int): String {
@@ -271,6 +275,7 @@ class SMAP(val fileMappings: List<FileMapping>) {
companion object {
const val FILE_SECTION = "*F"
const val LINE_SECTION = "*L"
const val STRATA_SECTION = "*S"
const val END = "*E"
}
}

View File

@@ -42,25 +42,24 @@ object SMAPParser {
fun parse(mappingInfo: String): SMAP {
val fileMappings = linkedMapOf<Int, FileMapping>()
val fileSectionStart = mappingInfo.indexOf(SMAP.FILE_SECTION) + SMAP.FILE_SECTION.length
val lineSectionAnchor = mappingInfo.indexOf(SMAP.LINE_SECTION)
val files = mappingInfo.substring(fileSectionStart, lineSectionAnchor)
val iterator = mappingInfo.lineSequence().dropWhile { it.trim() != SMAP.FILE_SECTION }.drop(1).iterator()
while (iterator.hasNext()) {
val fileDeclaration = iterator.next().trim()
if (fileDeclaration == SMAP.LINE_SECTION) break
val fileEntries = files.trim().split('+')
if (!fileDeclaration.startsWith('+')) {
throw AssertionError("File declaration should be in extended form, but: $fileDeclaration in $mappingInfo")
}
for (fileDeclaration in fileEntries) {
if (fileDeclaration == "") continue
val fileInternalName = fileDeclaration.trim()
val indexEnd = fileInternalName.indexOf(' ')
val fileIndex = fileInternalName.substring(0, indexEnd).toInt()
val newLine = fileInternalName.indexOf('\n')
val fileName = fileInternalName.substring(indexEnd + 1, newLine)
fileMappings[fileIndex] = FileMapping(fileName, fileInternalName.substring(newLine + 1).trim())
val indexAndFileInternalName = fileDeclaration.substringAfter("+ ").trim()
val fileIndex = indexAndFileInternalName.substringBefore(' ').toInt()
val fileName = indexAndFileInternalName.substringAfter(' ')
val path = iterator.next().trim()
fileMappings[fileIndex] = FileMapping(fileName, path)
}
val lines = mappingInfo.substring(lineSectionAnchor + SMAP.LINE_SECTION.length, mappingInfo.indexOf(SMAP.END)).trim().split('\n')
for (lineMapping in lines) {
for (lineMapping in iterator) {
if (lineMapping.trim() == SMAP.END) break
/*only simple mapping now*/
val targetSplit = lineMapping.indexOf(':')
val originalPart = lineMapping.substring(0, targetSplit)

View File

@@ -172,17 +172,20 @@ class PsiSourceCompilerForInline(private val codegen: ExpressionCodegen, overrid
val strategy = when (expression) {
is KtCallableReferenceExpression -> {
val resolvedCall = expression.callableReference.getResolvedCallWithAssert(state.bindingContext)
val receiverType = JvmCodegenUtil.getBoundCallableReferenceReceiver(resolvedCall)?.type?.let(state.typeMapper::mapType)
val receiverKotlinType = JvmCodegenUtil.getBoundCallableReferenceReceiver(resolvedCall)?.type
val receiverType = receiverKotlinType?.let(state.typeMapper::mapType)
val boundReceiverJvmKotlinType = receiverType?.let { JvmKotlinType(receiverType, receiverKotlinType) }
if (isLambda && lambdaInfo!!.isPropertyReference) {
val asmType = state.typeMapper.mapClass(lambdaInfo.classDescriptor)
val info = lambdaInfo.propertyReferenceInfo
PropertyReferenceCodegen.PropertyReferenceGenerationStrategy(
true, info!!.getFunction, info.target, asmType, receiverType,
true, info!!.getFunction, info.target, asmType,
boundReceiverJvmKotlinType,
lambdaInfo.functionWithBodyOrCallableReference, state, true
)
} else {
FunctionReferenceGenerationStrategy(state, descriptor, resolvedCall, receiverType, null, true)
FunctionReferenceGenerationStrategy(state, descriptor, resolvedCall, boundReceiverJvmKotlinType, null, true)
}
}
is KtFunctionLiteral -> ClosureGenerationStrategy(state, expression as KtDeclarationWithBody)

View File

@@ -17,6 +17,7 @@
package org.jetbrains.kotlin.codegen.optimization.boxing
import org.jetbrains.kotlin.codegen.optimization.OptimizationMethodVisitor
import org.jetbrains.kotlin.codegen.optimization.common.OPTIMIZATION_ASM_API_VERSION
import org.jetbrains.kotlin.codegen.optimization.common.debugText
import org.jetbrains.kotlin.codegen.optimization.common.isLoadOperation
import org.jetbrains.kotlin.codegen.optimization.common.isMeaningful
@@ -119,7 +120,7 @@ class PopBackwardPropagationTransformer : MethodTransformer() {
throw AssertionError("Incorrect bytecode at ${methodNode.instructions.indexOf(insn)}: ${insn.debugText} $frame")
}
private inner class HazardsTrackingInterpreter : SourceInterpreter() {
private inner class HazardsTrackingInterpreter : SourceInterpreter(OPTIMIZATION_ASM_API_VERSION) {
override fun naryOperation(insn: AbstractInsnNode, values: MutableList<out SourceValue>): SourceValue {
for (value in values) {
value.insns.markAsDontTouch()
@@ -313,4 +314,4 @@ fun AbstractInsnNode.isUnitInstance() =
this is FieldInsnNode && owner == "kotlin/Unit" && name == "INSTANCE"
fun AbstractInsnNode.isPrimitiveTypeConversion() =
opcode in Opcodes.I2L..Opcodes.I2S
opcode in Opcodes.I2L..Opcodes.I2S

View File

@@ -27,6 +27,8 @@ import org.jetbrains.org.objectweb.asm.Opcodes.*
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.tree.*
const val OPTIMIZATION_ASM_API_VERSION = Opcodes.ASM5
val AbstractInsnNode.isMeaningful: Boolean
get() =
when (this.type) {
@@ -221,4 +223,4 @@ internal inline fun <reified T : AbstractInsnNode> AbstractInsnNode.takeInsnIf(o
fun InsnList.removeAll(nodes: Collection<AbstractInsnNode>) {
for (node in nodes) remove(node)
}
}

View File

@@ -23,6 +23,7 @@ import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.ScriptDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.idea.MainFunctionDetector
import org.jetbrains.kotlin.load.kotlin.incremental.components.IncrementalCache
import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmMetadataVersion
import org.jetbrains.kotlin.modules.TargetId
@@ -31,6 +32,8 @@ import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtScript
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.deprecation.CoroutineCompatibilitySupport
import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver
import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
@@ -138,7 +141,8 @@ class GenerationState private constructor(
val deserializationConfiguration: DeserializationConfiguration =
CompilerDeserializationConfiguration(configuration.languageVersionSettings)
val deprecationProvider = DeprecationResolver(LockBasedStorageManager.NO_LOCKS, configuration.languageVersionSettings, CoroutineCompatibilitySupport.ENABLED)
val deprecationProvider =
DeprecationResolver(LockBasedStorageManager.NO_LOCKS, configuration.languageVersionSettings, CoroutineCompatibilitySupport.ENABLED)
init {
val icComponents = configuration.get(JVMConfigurationKeys.INCREMENTAL_COMPILATION_COMPONENTS)
@@ -180,6 +184,7 @@ class GenerationState private constructor(
filter = if (wantsDiagnostics) BindingTraceFilter.ACCEPT_ALL else BindingTraceFilter.NO_DIAGNOSTICS
)
val bindingContext: BindingContext = bindingTrace.bindingContext
val mainFunctionDetector = MainFunctionDetector(bindingContext, languageVersionSettings)
private val isIrBackend = configuration.get(JVMConfigurationKeys.IR) ?: false
val typeMapper: KotlinTypeMapper = KotlinTypeMapper(
this.bindingContext,
@@ -238,7 +243,7 @@ class GenerationState private constructor(
JVMConstructorCallNormalizationMode.DISABLE
}
val jvmDefaultMode = languageVersionSettings.getFlag(AnalysisFlag.jvmDefaultMode)
val jvmDefaultMode = languageVersionSettings.getFlag(JvmAnalysisFlags.jvmDefaultMode)
val disableOptimization = configuration.get(JVMConfigurationKeys.DISABLE_OPTIMIZATION, false)
@@ -247,7 +252,12 @@ class GenerationState private constructor(
init {
this.interceptedBuilderFactory = builderFactory
.wrapWith(
{ OptimizationClassBuilderFactory(it, this) },
{
if (classBuilderMode.generateBodies)
OptimizationClassBuilderFactory(it, this)
else
it
},
{
BuilderFactoryForDuplicateSignatureDiagnostics(
it, this.bindingContext, diagnostics, this.moduleName,

View File

@@ -509,31 +509,35 @@ public class KotlinTypeMapper {
);
}
// Make sure this method is called only from back-end
// It uses staticTypeMappingConfiguration that throws exception on error types
@NotNull
public static Type mapInlineClassTypeAsDeclaration(@NotNull KotlinType kotlinType) {
return mapInlineClassType(kotlinType, TypeMappingMode.CLASS_DECLARATION);
return mapInlineClassType(kotlinType, TypeMappingMode.CLASS_DECLARATION, staticTypeMappingConfiguration);
}
// Make sure this method is called only from back-end
// It uses staticTypeMappingConfiguration that throws exception on error types
@NotNull
public static Type mapUnderlyingTypeOfInlineClassType(@NotNull KotlinType kotlinType) {
KotlinType underlyingType = InlineClassesUtilsKt.unsubstitutedUnderlyingType(kotlinType);
if (underlyingType == null) {
throw new IllegalStateException("There should be underlying type for inline class type: " + kotlinType);
}
return mapInlineClassType(underlyingType, TypeMappingMode.DEFAULT);
return mapInlineClassType(underlyingType, TypeMappingMode.DEFAULT, staticTypeMappingConfiguration);
}
@NotNull
public static Type mapInlineClassType(@NotNull KotlinType kotlinType) {
return mapInlineClassType(kotlinType, TypeMappingMode.DEFAULT);
private Type mapInlineClassType(@NotNull KotlinType kotlinType) {
return mapInlineClassType(kotlinType, TypeMappingMode.DEFAULT, typeMappingConfiguration);
}
private static Type mapInlineClassType(
@NotNull KotlinType kotlinType,
@NotNull TypeMappingMode mode
@NotNull TypeMappingMode mode,
@NotNull TypeMappingConfiguration<Type> configuration
) {
return TypeSignatureMappingKt.mapType(
kotlinType, AsmTypeFactory.INSTANCE, mode, staticTypeMappingConfiguration, null,
kotlinType, AsmTypeFactory.INSTANCE, mode, configuration, null,
(ktType, asmType, typeMappingMode) -> Unit.INSTANCE,
false
);
@@ -858,6 +862,9 @@ public class KotlinTypeMapper {
}
else {
boolean toInlinedErasedClass = currentOwner.isInline() && !isAccessor(functionDescriptor);
if (toInlinedErasedClass) {
functionDescriptor = descriptor;
}
boolean isStaticInvocation = (isStaticDeclaration(functionDescriptor) &&
!(functionDescriptor instanceof ImportedFromObjectCallableDescriptor)) ||
@@ -1040,6 +1047,9 @@ public class KotlinTypeMapper {
else if (isInterface(containingDeclaration)) {
return OwnerKind.DEFAULT_IMPLS;
}
else if (InlineClassesUtilsKt.isInlineClass(containingDeclaration)) {
return OwnerKind.ERASED_INLINE_CLASS;
}
return OwnerKind.IMPLEMENTATION;
}
@@ -1361,8 +1371,12 @@ public class KotlinTypeMapper {
) {
String descriptor = method.getDescriptor();
int maskArgumentsCount = (callableDescriptor.getValueParameters().size() + Integer.SIZE - 1) / Integer.SIZE;
String additionalArgs = StringUtil.repeat(Type.INT_TYPE.getDescriptor(), maskArgumentsCount);
additionalArgs += (isConstructor(method) ? DEFAULT_CONSTRUCTOR_MARKER : OBJECT_TYPE).getDescriptor();
Type defaultConstructorMarkerType =
isConstructor(method) || isInlineClassConstructor(callableDescriptor)
? DEFAULT_CONSTRUCTOR_MARKER
: OBJECT_TYPE;
String additionalArgs = StringUtil.repeat(Type.INT_TYPE.getDescriptor(), maskArgumentsCount)
+ defaultConstructorMarkerType.getDescriptor();
String result = descriptor.replace(")", additionalArgs + ")");
if (dispatchReceiverDescriptor != null && !isConstructor(method)) {
return result.replace("(", "(" + dispatchReceiverDescriptor);
@@ -1378,6 +1392,11 @@ public class KotlinTypeMapper {
return "<init>".equals(method.getName());
}
private static boolean isInlineClassConstructor(@NotNull CallableDescriptor callableDescriptor) {
return callableDescriptor instanceof ClassConstructorDescriptor
&& InlineClassesUtilsKt.isInlineClass(callableDescriptor.getContainingDeclaration());
}
@NotNull
public Method mapDefaultMethod(@NotNull FunctionDescriptor functionDescriptor, @NotNull OwnerKind kind) {
Method jvmSignature = mapAsmMethod(functionDescriptor, kind);
@@ -1400,7 +1419,7 @@ public class KotlinTypeMapper {
* In that case the generated method's return type should be boxed: otherwise it's not possible to use
* this class from Java since javac issues errors when loading the class (incompatible return types)
*/
private static boolean forceBoxedReturnType(@NotNull FunctionDescriptor descriptor) {
private boolean forceBoxedReturnType(@NotNull FunctionDescriptor descriptor) {
if (isBoxMethodForInlineClass(descriptor)) return true;
//noinspection ConstantConditions
@@ -1414,7 +1433,7 @@ public class KotlinTypeMapper {
return false;
}
private static boolean isJvmPrimitive(@NotNull KotlinType kotlinType) {
private boolean isJvmPrimitive(@NotNull KotlinType kotlinType) {
if (KotlinBuiltIns.isPrimitiveType(kotlinType)) return true;
if (InlineClassesUtilsKt.isInlineClassType(kotlinType) && !KotlinTypeKt.isError(kotlinType)) {

View File

@@ -91,6 +91,7 @@ abstract class SwitchCodegen(
v.mark(endLabel)
subjectVariableDescriptor?.let {
codegen.frameMap.leave(it)
v.visitLocalVariable(
it.name.asString(), subjectType.descriptor, null,
beginLabel, endLabel, subjectLocal

View File

@@ -17,7 +17,7 @@
package org.jetbrains.kotlin.codegen
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.config.AnalysisFlag
import org.jetbrains.kotlin.config.JvmAnalysisFlags
import org.jetbrains.kotlin.load.java.JvmAnnotationNames
import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader
import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmBytecodeBinaryVersion
@@ -38,7 +38,7 @@ fun writeKotlinMetadata(
if (state.languageVersionSettings.isPreRelease()) {
flags = flags or JvmAnnotationNames.METADATA_PRE_RELEASE_FLAG
}
if (state.languageVersionSettings.getFlag(AnalysisFlag.strictMetadataVersionSemantics)) {
if (state.languageVersionSettings.getFlag(JvmAnalysisFlags.strictMetadataVersionSemantics)) {
flags = flags or JvmAnnotationNames.METADATA_STRICT_VERSION_SEMANTICS_FLAG
}
if (flags != 0) {

View File

@@ -67,11 +67,11 @@ dependencies {
testRuntime(intellijDep()) // Should come before compiler, because of "progarded" stuff needed for tests
depDistProjects.forEach {
testCompile(projectDist(it))
testCompile(project(it))
}
testCompile(commonDep("junit:junit"))
testCompileOnly(projectDist(":kotlin-test:kotlin-test-jvm"))
testCompileOnly(projectDist(":kotlin-test:kotlin-test-junit"))
testCompileOnly(project(":kotlin-test:kotlin-test-jvm"))
testCompileOnly(project(":kotlin-test:kotlin-test-junit"))
testCompile(projectTests(":compiler:tests-common"))
testCompile(projectTests(":generators:test-generator"))
testCompile(project(":compiler:ir.ir2cfg"))
@@ -84,10 +84,10 @@ dependencies {
testCompileOnly(project(it))
}
testCompileOnly(intellijCoreDep()) { includeJars("intellij-core") }
testCompileOnly(intellijDep()) { includeJars("openapi", "idea", "idea_rt", "util", "asm-all") }
testCompileOnly(intellijDep()) { includeJars("openapi", "idea", "idea_rt", "util", "asm-all", rootProject = rootProject) }
testRuntime(projectDist(":kotlin-reflect"))
testRuntime(projectDist(":kotlin-daemon-client"))
testRuntime(project(":kotlin-reflect"))
testRuntime(project(":kotlin-daemon-client"))
testRuntime(androidDxJar())
testRuntime(files(toolsJar()))
@@ -117,6 +117,7 @@ projectTest {
systemProperty("kotlin.ant.classpath", antLauncherJar.asPath)
systemProperty("kotlin.ant.launcher.class", "org.apache.tools.ant.Main")
}
exclude("org/jetbrains/kotlin/codegen/jdk/JvmTarget*")
}
fun Project.codegenTest(target: Int, jvm: Int,
@@ -125,15 +126,8 @@ fun Project.codegenTest(target: Int, jvm: Int,
dependsOn(*testDistProjects.map { "$it:dist" }.toTypedArray())
workingDir = rootDir
filter.includeTestsMatching("org.jetbrains.kotlin.codegen.BlackBoxCodegenTestGenerated*")
filter.includeTestsMatching("org.jetbrains.kotlin.codegen.BlackBoxInlineCodegenTestGenerated*")
filter.includeTestsMatching("org.jetbrains.kotlin.codegen.CompileKotlinAgainstInlineKotlinTestGenerated*")
filter.includeTestsMatching("org.jetbrains.kotlin.codegen.CompileKotlinAgainstKotlinTestGenerated*")
filter.includeTestsMatching("org.jetbrains.kotlin.codegen.BlackBoxAgainstJavaCodegenTestGenerated*")
filter.includeTestsMatching("org.jetbrains.kotlin.codegen.jdk.JvmTarget${target}OnJvm${jvm}")
if (jdk == "JDK_9") {
jvmArgs = listOf("--add-opens", "java.desktop/javax.swing=ALL-UNNAMED", "--add-opens", "java.base/java.io=ALL-UNNAMED")
}
body()
doFirst {
val jdkPath = project.findProperty(jdk) ?: error("$jdk is not optional to run this test")
@@ -200,6 +194,11 @@ codegenTest(target = 10, jvm = 10) {
systemProperty("kotlin.test.substitute.bytecode.1.8.to.10", "true")
}
codegenTest(target = 8, jvm = 11) {
systemProperty("kotlin.test.default.jvm.target", "1.8")
jvmArgs!!.add( "-XX:-FailOverToOldVerifier")
}
val generateTests by generator("org.jetbrains.kotlin.generators.tests.GenerateCompilerTestsKt")
testsJar()

View File

@@ -198,13 +198,13 @@ abstract class CommonCompilerArguments : CommonToolArguments() {
open fun configureAnalysisFlags(collector: MessageCollector): MutableMap<AnalysisFlag<*>, Any> {
return HashMap<AnalysisFlag<*>, Any>().apply {
put(AnalysisFlag.skipMetadataVersionCheck, skipMetadataVersionCheck)
put(AnalysisFlag.multiPlatformDoNotCheckActual, noCheckActual)
put(AnalysisFlag.allowKotlinPackage, allowKotlinPackage)
put(AnalysisFlag.experimental, experimental?.toList().orEmpty())
put(AnalysisFlag.useExperimental, useExperimental?.toList().orEmpty())
put(AnalysisFlag.explicitApiVersion, apiVersion != null)
put(AnalysisFlag.allowResultReturnType, allowResultReturnType)
put(AnalysisFlags.skipMetadataVersionCheck, skipMetadataVersionCheck)
put(AnalysisFlags.multiPlatformDoNotCheckActual, noCheckActual)
put(AnalysisFlags.allowKotlinPackage, allowKotlinPackage)
put(AnalysisFlags.experimental, experimental?.toList().orEmpty())
put(AnalysisFlags.useExperimental, useExperimental?.toList().orEmpty())
put(AnalysisFlags.explicitApiVersion, apiVersion != null)
put(AnalysisFlags.allowResultReturnType, allowResultReturnType)
}
}

View File

@@ -16,11 +16,12 @@
package org.jetbrains.kotlin.cli.common.arguments
import java.io.Serializable
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
abstract class Freezable {
protected open inner class FreezableVar<T>(private var value: T) : ReadWriteProperty<Any, T> {
protected open inner class FreezableVar<T>(private var value: T) : ReadWriteProperty<Any, T>, Serializable {
override fun getValue(thisRef: Any, property: KProperty<*>) = value
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {

View File

@@ -110,7 +110,9 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
@Argument(
value = "-Xnormalize-constructor-calls",
valueDescription = "{disable|enable}",
description = "Normalize constructor calls (disable: don't normalize; enable: normalize), default is disable"
description = "Normalize constructor calls (disable: don't normalize; enable: normalize),\n" +
"default is 'disable' in language version 1.2 and below,\n" +
"'enable' since language version 1.3"
)
var constructorCallNormalizationMode: String? by NullableStringFreezableVar(null)
@@ -259,13 +261,13 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
override fun configureAnalysisFlags(collector: MessageCollector): MutableMap<AnalysisFlag<*>, Any> {
val result = super.configureAnalysisFlags(collector)
result.put(AnalysisFlag.strictMetadataVersionSemantics, strictMetadataVersionSemantics)
result[AnalysisFlag.jsr305] = Jsr305Parser(collector).parse(
result[JvmAnalysisFlags.strictMetadataVersionSemantics] = strictMetadataVersionSemantics
result[JvmAnalysisFlags.jsr305] = Jsr305Parser(collector).parse(
jsr305,
supportCompatqualCheckerFrameworkAnnotations
)
result[AnalysisFlag.ignoreDataFlowInAssert] = JVMAssertionsMode.fromString(assertionsMode) != JVMAssertionsMode.LEGACY
JvmDefaultMode.fromStringOrNull(jvmDefault)?.let { result[AnalysisFlag.jvmDefaultMode] = it }
result[AnalysisFlags.ignoreDataFlowInAssert] = JVMAssertionsMode.fromString(assertionsMode) != JVMAssertionsMode.LEGACY
JvmDefaultMode.fromStringOrNull(jvmDefault)?.let { result[JvmAnalysisFlags.jvmDefaultMode] = it }
?: collector.report(
CompilerMessageSeverity.ERROR,
"Unknown @JvmDefault mode: $jvmDefault, " +

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