Compare commits

...

430 Commits

Author SHA1 Message Date
Alexander Podkhalyuzin
84f2ff12e2 Implemented KotlinResolveScopeEnlarger for modules
Before that we had dependency to iml file, which is incorrect
2018-12-14 19:50:53 +03:00
Roman Artemev
96bf749d4d Add changelog for 1.3.11 2018-12-06 12:40:32 +03:00
Simon Ogorodnik
1870487ce6 Support overriding module/library/sdk for particular light PsiClass
To support light R classes
2018-12-03 15:22:10 +03:00
Nikolay Krasko
54c0000332 Enlarge scope for auto-import and completion with extensions (KT-27944)
Android R classes provided with scope enlarger and they can be found
during resolve, but ignored during auto-import search.

(cherry picked from commit 5ab812e29e)
2018-12-03 15:21:54 +03:00
Mikhail Glukhikh
31ac07d6e2 Fix "redundant async" for coroutines 1.*, forbid explicit scopes case
Related to KT-28504
#KT-28445 Fixed

(cherry picked from commit 05b1a99022)
2018-12-01 11:02:52 +03:00
Mikhail Glukhikh
0b9bbe02f1 Extract stub library file from "Redundant async" inspection tests
(cherry picked from commit 6b60d49e09)
2018-12-01 11:02:13 +03:00
Ilya Gorbunov
b5bbbc6450 Update selenium version to 2.53.1
This change is required to fix failing tests of browser-example and browser-example-with-library.
Tests began to fail recently because `htmlunit-driver` had a dependency on `selenium-support`
constrained to [2.53.0,4.0.0) range. Apparently the recently released 3.141.0 version of that artifact
became incompatible with the rest of selenium 2.52.

This fix advances the version of selenium to 2.53.1. This version has a dependency on
`selenium-support:2.53.1`. Since it goes earlier in dependency tree and satisfies the range constraint,
it is used for `htmlunit-driver` too.
2018-11-30 19:00:02 +03:00
Ilya Matveev
a5422b159e Update Kotlin/Native: 1.0.3 2018-11-30 18:25:51 +07:00
Denis Zharkov
a72f820893 Fix message text for INCOMPATIBLE_ENUM_COMPARISON
^KT-28516 Fixed
2018-11-30 10:34:50 +03:00
Andrey Uskov
57361fd6dc Fixed dependency resolution of root project
#KT-28389 Fixed

(cherry picked from commit 620969652a)
2018-11-29 17:13:13 +03:00
Alexey Sedunov
514e825e95 MPP: Fix adjustment of transitive project dependencies
#KT-27632 Fixed

(cherry picked from commit af5d4b3156)
2018-11-29 17:11:51 +03:00
Leonid Startsev
878482fe8f Replace imported serialization-ide.jar with serialization-compiler.jar so JPS build also start working
(cherry picked from commit baf8cb6e9b)
2018-11-27 15:13:53 +03:00
Denis Zharkov
a5df656f52 Report a warning when comparing incompatible enums
I've put `isIncompatibleEnums` to TypeIntersector because I placed
all of its usages after all of the TypeIntersector::isIntersectionEmpty ones

^KT-28225 Fixed
2018-11-20 11:23:57 +03:00
Roman Artemev
5d26297999 [JS BE] Support contracts in JS Fix KT-27946
(cherry picked from commit 8f2117685f)
2018-11-14 17:17:34 +03:00
Mikhail Zarechenskiy
ac908715bb Fix mapping for inline classes when JvmSuppressWildcards mode is using
#KT-28097 Fixed
2018-11-14 14:39:59 +03:00
Ilya Gorbunov
a32e69a699 Actualize Deprecated annotation and DeprecationLevel enum docs
...to clear some confusion from KT-25643.
Describe level property usage scenario in detail.

(cherry picked from commit ea0030f324)
2018-11-14 14:31:40 +03:00
Denis Zharkov
caeec04816 Add changelog for 1.3.10 2018-11-14 14:12:45 +03:00
Anton Bannykh
72e2bbd2e0 JS: report inline suspend functions to IC
* Also inline suspend lambda'a
* Also use correct JsName's in exported suspend inline fun's
* Also use less unused imports
2018-11-08 14:37:18 +03:00
Andrey Uskov
5f61ecdd8d Fix dependency resolution on model post-processing
#KT-27265 Fixed

(cherry picked from commit b9753164c9)
2018-11-08 13:14:06 +03:00
Alexey Sedunov
58046aead2 MPP: Support MPP-dependent Java modules in Android projects
#KT-27265 Fixed

(cherry picked from commit fea397a2ad)
2018-11-08 13:13:36 +03:00
Andrey Uskov
615d801bc9 Fix NPE in KotlinJavaMPPSourceSetDataService.postProcess
#KT-28051 Fixed
(cherry picked from commit 080681ea2f)
2018-11-08 13:13:11 +03:00
Alexander Udalov
17010d98be Do not try computing return type in OverloadChecker
Return type is not needed for checking overloads, but querying it may
involve resolving function bodies, which usually happens after overload
checking (see LazyTopDownAnalyzer.analyzeDeclarations) and at this point
can lead to incorrect BACKING_FIELD_REQUIRED value being computed for
some properties (see KT-27895)

 #KT-27895 Fixed
2018-11-08 13:01:03 +03:00
Yan Zhulanow
e4e1dbfd96 Kapt: Use correct type mapping mode while mapping super types (KT-27126) 2018-11-08 18:58:28 +09:00
Yan Zhulanow
6f6a30dfc8 Kapt: Fix error type correction for super class constructor calls 2018-11-08 18:58:27 +09:00
Ilya Matveev
0132c53055 Update Kotlin/Native: 1.0.2 2018-11-08 11:07:34 +03:00
Sergey Rostov
37dfa2498d JPS: support -Xcommon-sources for JVM multiplatform projects
#KT-26489 Fixed

(cherry picked from commit b8c982bb72)
2018-11-08 08:28:40 +03:00
Anton Bannykh
97682e8e01 JS: fix concurrent access to NameSuggestion.cache (KT-27230 fixed)
(cherry picked from commit 82268cd95d)
2018-11-07 18:59:28 +03:00
Alexey Tsvetkov
0d21a52b46 Revert usage of lazy task API
We want to be compatible with Gradle 4.0+
where the API is not available.
Use eager task creation API for now.
Lazy API support should be added later with
proper Gradle versions checks.
2018-11-07 18:28:15 +03:00
Alexey Tsvetkov
60ef74a78d Do not resolve configuration for scripting Gradle plugin
Avoid resolving kotlinScriptDef configurations during
configuration phase. Also, make task creation lazy.

   #KT-27160 fixed

# Conflicts:
#	libraries/tools/kotlin-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/scripting/internal/ScriptingGradleSubplugin.kt
2018-11-07 18:28:03 +03:00
Alexander Udalov
0749cff2dd Fix loading class literal value void.class in reflection
#KT-27878 Fixed

(cherry picked from commit 2f72f68e1a)
2018-11-06 13:03:31 +01:00
Alexander Udalov
4c937703a0 Fix loading of class literal constant values in reflection
(cherry picked from commit 902d414d39)
2018-11-06 13:01:13 +01:00
Mikhail Glukhikh
cb9ed57682 AndroidViewConstructorFix: add white space after annotation explicitly
This fixes Android formatter-related issue
#KT-27945 Fixed

(cherry picked from commit 22fa9b6b92)
2018-11-06 12:22:32 +03:00
Dmitry Savvinov
13801c4cea 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-11-06 10:54:37 +03:00
Vyacheslav Gerasimov
82b1f44e13 Register stream-debugger for AS 3.2, 3.3, 3.4 2018-11-01 19:45:22 +03:00
Vyacheslav Gerasimov
7f67c1f4a5 as34: Update idea-version 2018-11-01 19:33:01 +03:00
Vyacheslav Gerasimov
a19baa9c73 as34: Apply AS 3.3 related changes 2018-11-01 19:33:01 +03:00
Vyacheslav Gerasimov
70669f26f6 as34: Add bunch for AS 3.4 deriving from 183 2018-11-01 19:33:00 +03:00
Pavel V. Talanov
eae271fe9e multiplatformUtil: Do not fail on non-physical classes from java
#KT-27907 Fixed
2018-11-01 15:50:56 +01:00
Mikhail Glukhikh
8b7143c931 Unused symbol: fix false positives on inline class constructors
#KT-27434 Fixed

(cherry picked from commit 700bcb5984)
2018-11-01 09:26:09 +03:00
Mikhail Glukhikh
1694e73f24 Unused symbol: handle functions with inline class parameters correctly
#KT-27357 Fixed

(cherry picked from commit a5e508a083)
2018-11-01 09:24:36 +03:00
Mikhael Bogdanov
164838d72b Remove 'override' to compile against ASM 6 2018-10-31 20:02:07 +01:00
Ilya Gorbunov
3ba932ea62 Minor: fix doc formatting that caused summary differ in JVM and Native
(cherry picked from commit c3237f416f)
2018-10-31 20:40:14 +03:00
Ilya Gorbunov
5745ee3cf6 Minor: fix sample references in MatchResult
(cherry picked from commit 18f9b9a022)
2018-10-31 20:40:13 +03:00
Sergey Igushkin
82e5574634 Fix runtime elements configuration resolved for compile classpath
The existing disambiguation rule for the Usage attribute lead to
runtime variants being resolved even for compile-scoped input
configurations, because Gradle runs disambiguation rules even if the
consumer value is present in the candidates list.

For example, an `app` project's `jvmCompileClasspath` configuration
would get its `project('lib')` dependency resolved to the
`jvmLibRuntimeElements` instead of `jvmLibApiElements`.

Fix this by:
1) running the part of the disambiguation rule only with Gradle 4.1+, so
  as to use the consumer value for proper disambiguation;
2) choosing the JAVA_API usage when the consumer is JAVA_API or
  KOTLIN_API, and choosing one of the JAVA_RUNTIME usages if the
  consumer is either KOTLIN_RUNTIME, one of the JAVA_RUNTIME usages, or
  does not specify its usage.

Issue #KT-27849 Fixed

(cherry picked from commit f995afd50d)
2018-10-31 20:17:21 +03:00
Yan Zhulanow
7791003b7c Fix sporadic false-positive "Receiver parameter is never used" for local functions (KT-26481)
(cherry picked from commit 9dd6efe)
2018-10-31 19:37:29 +03:00
Yan Zhulanow
96193111e6 Add a missing write action to KotlinNativeApplicationComponent
(cherry picked from commit d5f203a)
2018-10-31 18:12:02 +03:00
Mikhael Bogdanov
bbb0795904 Use proper type constructor in eval4j
ASM 7 changes default behavior for 'getTypeInternal' (was 'getType') method.
 Now it's throwing exception instead of create 'METHOD' Type.
 Old behavior was equals to 'Type.getMethodType("<invalid>")'

 #KT-27833 Fixed

(cherry picked from commit 98fa26c2d8)
2018-10-31 17:54:06 +03:00
Mikhail Zarechenskiy
cef6c71154 Don't try parsing contract-like function not from kotlin package
Returning `null` from `doCheckContract` functions means that we
have failed to parse contract function and should report an error, but
if the called function isn't true contract, we shouldn't evaluate that code
at all.

 #KT-27758 Fixed
2018-10-31 17:54:06 +03:00
Mikhael Bogdanov
235ba4864f Fix method inlining problems in 183 branch related to asm upgrade to 7.0
'visitAnnotableParameterCount' is propagating copying node state to
    destination one that corrupts its state

 #KT-27774 In Progress
2018-10-31 17:54:06 +03:00
Ilya Matveev
a2818a876d Use KOTLIN_API usage in cinterop dependencies.
Issue #KT-27803 fixed.
2018-10-31 17:54:06 +03:00
Sergey Rostov
3e86fe940d JPS: Don't catch BuildDataCorruptedException as internal error.
BuildDataCorruptedException should be thrown up to `IncProjectBuilder`
to be handled by TeamCity.

#KT-27037 Fixed

(cherry picked from commit cce125b982)
2018-10-31 17:54:06 +03:00
Sergey Rostov
57726d2cde JPS: Fix initialization order for case when all kotlin rebuild.
#KT-27792 Fixed

(cherry picked from commit 0b8d94a6b1)
2018-10-31 17:54:06 +03:00
Ilya Gorbunov
f3a3b37452 Duplicate MutableList.add docs in AbstractMutableList.add
Because the documentation inheritance doesn't work as desired here.

(cherry picked from commit c8caed5b6f)
2018-10-31 17:54:06 +03:00
Ilya Gorbunov
d4a4c62b90 Unify kotlin.test docs
(cherry picked from commit efa7bf0c37)
2018-10-31 17:54:06 +03:00
Piotr Krzeminski
d3b8b9297f kotlin-test: Add documentation for value returned by assertFailsWith
A follow-up after https://youtrack.jetbrains.com/issue/KT-27418

Co-authored-by: Ilya Gorbunov <ilya.gorbunov@jetbrains.com>
(cherry picked from commit 3c46bb9d03)
2018-10-31 17:54:06 +03:00
Mikhail Levchenko
74e61b071c Remove confusing samples from SequenceBuilder docs
Problem:
SequenceBuilder is experimental and deprecated in 1.3 in favor of
SequenceScope. Usage of experimental package is discouraged in 1.3.
The documentation for SequenceBuilder refers to SequnceScope sample code,
which might be confusing.

Solution:
Remove samples for SequenceBuilder completely to discourage its usage,
but provide a note about it having deprecated in favor of SequenceScope.
Provide links to modern version of outdated SequenceBuilder.

(cherry picked from commit 16918fa25e)
2018-10-31 17:54:06 +03:00
Denis Zharkov
90a20f95ad Update ChangeLog.md 2018-10-29 19:21:11 +03:00
Denis Zharkov
9e03b75f8e Add changelog notes for 1.3-RC4 and 1.3.0 2018-10-29 18:31:30 +03:00
Yan Zhulanow
12e41557b5 Fix Android Extension imports resolution after project reopening (KT-27793) 2018-10-25 21:23:49 +03:00
Ilya Matveev
3d3fce65f9 Update Kotlin/Native: 1.0.1 2018-10-23 15:31:09 +03:00
Denis Zharkov
abe6693af7 Do not set version to buildNumber
They might be different in case of releases:
1.3.0 != 1.3.0-release-N
2018-10-23 14:21:20 +03:00
Nikolay Krasko
22222c8fd0 Update channels list in update Kotlin dropdown (KT-25429)
#KT-25429 Fixed
2018-10-22 20:42:22 +03:00
Ilya Matveev
cc035f7f41 Update Kotlin/Native: 1.0.0 2018-10-22 23:50:36 +07:00
Ilya Gorbunov
c7bc74291d Unify and improve Regex docs
(cherry picked from commit 4a10d954fc)
2018-10-22 17:50:10 +03:00
Ilya Gorbunov
dd62c1ebfd Unify coroutine intrinsic docs
(cherry picked from commit 709a28060f)
2018-10-22 17:50:08 +03:00
Ilya Gorbunov
2d4807f90a capitalize/decapitalize docs in stdlib/js
(cherry picked from commit 63c5e18149)
2018-10-22 17:50:06 +03:00
Ilya Gorbunov
87becfd470 Common String.toNumber: clarify thrown exception types
(cherry picked from commit a1c0c679ee)
2018-10-22 17:50:05 +03:00
Ilya Gorbunov
2a895ed273 kotlin.system docs improvements
- Rewrite exitProcess docs in a more common way
- Add [block] parameter reference

(cherry picked from commit 1ed136a621)
2018-10-22 17:50:03 +03:00
Ilya Gorbunov
1329624481 Minor: code formatting in Unit docs
(cherry picked from commit 3aff7112e0)
2018-10-22 17:50:01 +03:00
Ilya Gorbunov
6aea25b08f Unify AbstractMutableMap JS docs
(cherry picked from commit ac5eeb885f)
2018-10-22 17:50:00 +03:00
Ilya Gorbunov
8041879ae9 Correct parameter reference in copyInto docs
(cherry picked from commit 7fc6f06b70)
2018-10-22 17:49:58 +03:00
Ilya Gorbunov
ef082199b0 Unify print/println/readLine docs
(cherry picked from commit ebe9d59df7)
2018-10-22 17:49:56 +03:00
Alexey Sedunov
6f135248dc Inspections: Report "unresolved property" only if reference is soft
#KT-27619 Fixed
2018-10-22 12:59:26 +03:00
Denis Zharkov
9a6a6c427a Use https when publishing to sonatype
Otherwise, NoHttpResponseException may happen sporadically
2018-10-22 12:05:21 +03:00
Ilya Matveev
0495864483 Specify K/N default libs directory more precisely (#1934) 2018-10-22 15:29:16 +07:00
Ilya Gorbunov
5e41d261df Update line numbers in JS test data after changing Result source file 2018-10-19 23:02:24 +03:00
Ilya Gorbunov
69c3714d88 Add more missing SinceKotlin("1.3") annotations
(cherry picked from commit c72cf02e6c)
2018-10-19 22:37:48 +03:00
Lukas Welte
7659eb1405 Mark Result, its extensions and runCatching as available since 1.3
(cherry picked from commit 70d0c1a0ae)
2018-10-19 22:37:47 +03:00
Roman Elizarov
8cd22016e7 Broken doc link to suspendCoroutineOrReturn fixed 2018-10-19 14:52:12 +03:00
Sergey Igushkin
8f6bbcf2ee 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

(cherry picked from commit a88bfb726d)
2018-10-17 19:02:18 +03:00
Alexey Sedunov
9c9da4a7d8 Gradle: Retrieve AndroidModuleModel using IdeModifiableModelsProvider
Otherwise it may be null if module is just created by the import

 #KT-27643 Fixed
2018-10-17 13:57:35 +03:00
Mikhail Zarechenskiy
16c74fbfe5 Use unsubstituted type when putting values to coerce them correctly
This commit fixes `testUnboxParameterOfSuspendLambdaBeforeInvoke` and
 relevant behaviour, it's part of more complex commit 8d2b1950e6 which isn't in 1.3.0
2018-10-17 12:06:24 +03:00
Yan Zhulanow
737fb0fe81 Kapt: Update test data (reflects old non-'const' property behavior in 1.3) 2018-10-16 23:35:12 +03:00
Yan Zhulanow
77c5791c4d Kapt: Fix anonymous type transformer, do not use ClassDescriptor.defaultType as a replacement (KT-27119) 2018-10-16 23:35:11 +03:00
Sergey Igushkin
4a12f0e3a1 Import compiler plugin options from new MPP into IDE
Issue #KT-27499 Fixed

(cherry picked from commit e103bea211)
2018-10-16 19:08:53 +03:00
Sergey Igushkin
c1fb928b34 Import experimental annotations from new MPP into IDE
Issue #KT-26840 Fixed

(cherry picked from commit 7075509b1e)
2018-10-16 19:08:53 +03:00
Sergey Igushkin
1475f6b110 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

(cherry picked from commit 9f2e5cdc4d)
2018-10-16 19:08:53 +03:00
Sergey Igushkin
02b02b9c92 Fix the format used by Kotlin/Native tasks for compiler plugin args
The correct format is "-P arg1", not "-Parg1".

(cherry picked from commit e573911e16)
2018-10-16 19:08:53 +03:00
Sergey Igushkin
4087c8dd66 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

(cherry picked from commit ee63a6b3af)
2018-10-16 19:08:53 +03:00
Sergey Igushkin
edcbdb813d 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

(cherry picked from commit 5db23f1a81)
2018-10-16 19:08:53 +03:00
Mikhail Zarechenskiy
2e0e8b6c0d Report error for Result as an extension receiver with safe call
#KT-27620 Fixed
2018-10-16 19:04:39 +03:00
Natalia Selezneva
79fa7d8c5d Add shortcut and menu item for Run Scratch Action (KT-24180)
KT-24180 Fixed

(cherry picked from commit 00e0f430ac)
2018-10-16 19:02:45 +03:00
Pavel V. Talanov
44537f9dfc 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:36:32 +02:00
Pavel V. Talanov
ed224224dc KotlinMultiplatformRunLocationsProvider: fix tests in android modules
Android modules are considered to be 'production' but can contain tests
    and test roots

 #KT-27451 Fixed
2018-10-16 15:35:58 +02:00
Sergey Igushkin
9c31b291c9 Fix resourcesDir that cannot be imported due to not being a File
(cherry picked from commit c25cdb4264)
2018-10-16 14:33:21 +03:00
Denis Zharkov
0b509f7a1b Restore test-data accidentally removed in 76c0691e9e 2018-10-16 14:15:12 +03:00
Sergey Rostov
c678d7aa6a JPS: Fix updating cache format version for rebuilt targets by removing i/o optimization
This is safe version special for 1.3.0 branch.

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 13:17:57 +03:00
Sergey Igushkin
fba163cec0 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.

(cherry picked from commit 81b4031a35)
2018-10-16 13:12:48 +03:00
Sergey Igushkin
3164cfd963 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.

(cherry picked from commit a0f4d5a637)
2018-10-16 13:12:37 +03:00
Denis Zharkov
2e0383eeb3 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:18:37 +03:00
Dmitry Petrov
0c8bd72deb Generate tests after cherry-picking some fixes 2018-10-16 01:56:26 +03:00
Dmitry Petrov
8d0bdd16b4 Fix inline classes coercion in 'if' expression
#KT-27132

(cherry picked from commit 7b7cf39388)
2018-10-16 01:56:25 +03:00
Dmitry Petrov
d646a543f2 Fix nullability propagation in inline class type mapping
#KT-27096

See https://jetbrains.slack.com/archives/C06E082M6/p1537949572000100

(cherry picked from commit ab90b2b901)
2018-10-16 01:56:23 +03:00
Dmitry Petrov
3cd0c5a8f7 Fix extension receiver coercion for inline classes
#KT-27031

(cherry picked from commit 2e6d53a43f)
2018-10-16 01:56:22 +03:00
Dmitry Petrov
27b8c4e097 Fix outer class mapping for closures in inline class
#KT-27030
 #KT-27033

(cherry picked from commit 20d7210239)
2018-10-16 01:56:20 +03:00
Dmitry Petrov
2249a95a81 Fix companion field access from inline class
#KT-26858

(cherry picked from commit 1869ed09bc)
2018-10-16 01:56:19 +03:00
Alexey Sedunov
3d729fa7d0 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-15 20:51:05 +03:00
Pavel V. Talanov
d31ec51ecc ResolutionFacadeWithDebugInfo: do not wrap index not ready exception
Fixes problems where `catch (IndexNotReadyException)` blocks
    in IDEA code would not work
2018-10-15 15:19:34 +02:00
Ilya Gorbunov
9b1a39bff8 Rename Random companion object to Default
#KT-27508

(cherry picked from commit 27dc160aef)
2018-10-15 16:02:36 +03:00
Alexey Sedunov
94df721eb9 MPP: Add MPP sources roots to dependent non-MPP module
#KT-27365 Fixed
2018-10-15 14:30:51 +03:00
Mikhail Zarechenskiy
40e0f4df67 Fix inline class type coercion in == with generic call
#KT-27393 Fixed
2018-10-15 14:06:42 +03:00
Mikhail Zarechenskiy
3a122ce8cd Propagate KotlinType into create method for coroutines
#KT-27526 Fixed
2018-10-15 14:06:41 +03:00
Mikhail Zarechenskiy
3856afec0a 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-15 12:35:23 +03:00
Denis Zharkov
c7fbc42440 Add changelog notes for 1.3-RC2 and 1.3-RC3 2018-10-12 18:38:55 +03:00
Nikolay Krasko
37ef5f8142 Show migration when changes are in kts files or inside buildSrc dir (KT-27329)
#KT-27329 Fixed
2018-10-12 18:00:49 +03:00
Leonid Startsev
f10d78514c Call Gradle import handlers when importing Gradle modules from new mpp plugin
This enables serialization and other plugins in IDE with new mpp
2018-10-12 17:33:07 +03:00
Ilmir Usmanov
a6d4de60b3 Report suspension point in monitor error on crossinline lambdas
#KT-27258: Fixed
2018-10-12 16:50:38 +03:00
Ilmir Usmanov
348e68eb5e Fix NPE in suspension point in monitor call checker
#KT-27484 Fixed
2018-10-12 16:50:36 +03:00
Ilmir Usmanov
76c0691e9e 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-12 16:50:33 +03:00
Ilmir Usmanov
1ac9183044 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-12 16:50:30 +03:00
Ilmir Usmanov
42ca4a00e9 Revert: Forbid suspension points in critical sections 2018-10-12 16:50:27 +03:00
Denis Zharkov
211d7056cd Fix exception in light classes when type alias in MultifileClass
#KT-27355 Fixed
2018-10-12 15:44:01 +03:00
Svyatoslav Kuzmich
caf6e2b444 [JS BE] Fix KT-26787: handle JsSwitch in LabeledBlockToDoWhileTransformation 2018-10-12 15:20:47 +03:00
Ivan Gavrilovic
e204b002f7 Fix null checks in the flow
(cherry picked from commit 2d425d4e0a)
2018-10-12 15:02:27 +03:00
Ivan Gavrilovic
e186ea7e84 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.

(cherry picked from commit bb53a1c3d2)
2018-10-12 15:01:48 +03:00
Yan Zhulanow
cea006ab4b 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:47:53 +03:00
Mikhail Glukhikh
370f4e045d Use kotlin-stdlib instead of kotlin-stdlib-jdk8 in MPP mobile wizard
#KT-27356 Fixed

(cherry picked from commit b08f966428)
2018-10-11 21:20:54 +03:00
Mikhail Glukhikh
facf20b68c MPP wizards: generate different file names to avoid KT-21186
#KT-27456 Fixed

(cherry picked from commit 42888572cb)
2018-10-11 21:20:39 +03:00
Alexey Sedunov
8c63dabe3d Change Signature: Clear callback after the call
Retaining the callback leads to the leak of obsolete resolve data

(cherry picked from commit 3fcf6e7719)
2018-10-11 21:02:16 +03:00
Alexey Sedunov
b68e759e16 Configuration: Do not use read action during conpiler settings loading
It may lead to deadlock (see KT-27298)

 #KT-27298 Fixed

(cherry picked from commit c3af3cc482)
2018-10-11 21:02:15 +03:00
Ilya Chernikov
5e7b7dccd3 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-11 19:11:59 +02:00
Sergey Igushkin
500b13e605 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.

(cherry picked from commit 294bd8c7fa)
2018-10-11 14:52:16 +03:00
Ilya Matveev
ffbb468870 Add configuration methods for kotlinOptions in K/N tasks
Issue #KT-26758 fixed.
2018-10-11 14:29:40 +03:00
Ilya Matveev
14f253de70 Fix up-to-date checks for framework compilation 2018-10-11 14:29:40 +03:00
Ilya Matveev
9df3ee986a Take K/N version into account in UP-TO-DATE checks for cinterop tasks 2018-10-11 14:29:40 +03:00
Vyacheslav Gerasimov
7a25bf8aa0 Add to kotlin-plugin.jar js.translator module referenced by serialization
(cherry picked from commit f9cefdaa44)
2018-10-08 14:56:06 +03:00
Pavel Punegov
be5b8371f0 Ignore 2 tests in Native: default arguments got from expect declarations there
(cherry picked from commit 7c2c4e68ce)
2018-10-04 16:41:41 +03:00
Nikolay Krasko
60903a8534 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:10:16 +02:00
Mikhail Glukhikh
57b93904ed Fix tests in mobile shared library wizard #KT-27335 Fixed
(cherry picked from commit 75b27f890a)
2018-10-02 12:31:26 +02:00
Dmitry Savvinov
2900cddc40 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

(cherry picked from commit 62edf29cbf)
2018-10-02 12:14:43 +02:00
Dmitry Savvinov
4558aed787 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

(cherry picked from commit dd682bd37d)
2018-10-02 12:14:40 +02:00
Ilya Gorbunov
9020e1c233 Override docs of MutableList.add/addAll methods
#KT-25632

(cherry picked from commit b1c4590537)
2018-10-02 12:10:40 +02:00
Ilya Gorbunov
5357f0871f Document the requirement for 'minus(elements)' to have stable hashCode
#KT-24536

(cherry picked from commit d6beddaac5)
2018-10-02 12:10:36 +02:00
Ilya Gorbunov
515ccb672e Summary for new packages: kotlin.coroutines, kotlin.contracts, kotlin.random
(cherry picked from commit 27beadad18)
2018-10-02 12:10:32 +02:00
Ilya Gorbunov
4e4c99bc39 Document that lines and lineSequence do not preserve line separators
(cherry picked from commit 08822ff14b)
2018-10-02 12:10:28 +02:00
Ilya Gorbunov
c35011eb13 Clarify the purpose of the message parameter of assertFailsWith
#KT-22869 Fixed

(cherry picked from commit 21b71f3bb1)
2018-10-02 12:10:24 +02:00
Ilya Gorbunov
7755f11b97 Add a note about non-atomic behavior of MutableMap.getOrPut
#KT-13821

(cherry picked from commit 9f9033870c)
2018-10-02 12:10:20 +02:00
Ilya Gorbunov
f5acebd50b 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.

(cherry picked from commit bb9e9ac1ee)
2018-10-02 12:10:15 +02:00
Yan Zhulanow
fa92420aaa MPP: Fix JPS tests
Move back the application check as only the class presence check is not sufficient.

(cherry picked from commit bbc73ec0e5)
2018-10-02 12:02:33 +02:00
Alexander Udalov
6f776c1b68 Handle whitespaces in argfiles correctly
#KT-27218 Fixed

(cherry picked from commit 16dd6ebe61)
2018-10-02 12:00:34 +02:00
Nikolay Krasko
3f8f80df02 Shortcut quick fix for migrating all coroutines in the project (KT-27164)
#KT-27164 Fixed
2018-10-02 12:56:56 +03:00
Nikolay Krasko
fbf983bbc1 Remove NotificationAction.createSimple to fix compilation in 173
(cherry picked from commit 1901331ee5)
2018-10-02 12:56:55 +03:00
Nikolay Krasko
941dd26df8 Replace migration dialog with sticky popup (KT-27163)
#KT-27163 Fixed

(cherry picked from commit 41bd29c3e9)
2018-10-02 12:56:54 +03:00
Alexey Sedunov
58b96f8c60 MPP: Add MPP sources roots to dependent Android module
#KT-27331 Fixed
2018-10-02 02:50:40 +03:00
Alexey Sedunov
742058ea80 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 20:25:28 +03:00
Alexey Sedunov
fb9a329972 MPP: Add dependencies for all source sets for a given Android variant 2018-10-01 20:25:27 +03:00
Alexey Sedunov
532a215829 MPP: Fix recognition of test source sets in Android projects
#KT-27212 Fixed
2018-10-01 20:25:27 +03:00
Alexey Sedunov
12fc174182 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 20:25:27 +03:00
Alexey Sedunov
a3b07758a5 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 20:25:27 +03:00
Vyacheslav Gerasimov
9dd1a0ef1e 183: Make 183 plugin compatible with upcoming Idea 191
(cherry picked from commit 28c84d0e00)
2018-10-01 18:42:55 +03:00
Mikhail Glukhikh
7b4cddef64 MPP wizards: remove AS bunches (anyway they aren't accessible for AS)
(cherry picked from commit 6dbb51d7a7)
2018-10-01 18:18:20 +03:00
Mikhail Glukhikh
6906c2ea5d Forbid all MPP wizards in IDEA 173, but leave them in AS 3.1
Related to KT-27267

(cherry picked from commit 199ae3bac8)
2018-10-01 18:18:20 +03:00
Mikhail Glukhikh
7da062d780 Forbid all MPP native-related wizards in IDEA 181, but leave in AS 3.2
Related to KT-27267

(cherry picked from commit 4c85616ee3)
2018-10-01 18:18:19 +03:00
Mikhail Glukhikh
f4ef085d1d MPP mobile wizard: generate also Xcode (r) project for iOS
#KT-27178 Fixed

(cherry picked from commit eb528c3d65)
2018-10-01 18:18:19 +03:00
Ilya Gorbunov
36b1672da9 Improve groupingBy samples
(cherry picked from commit 12a31637d1)
2018-10-01 14:42:00 +03:00
Ilya Gorbunov
57d0c4538c Move groupingByEachCount together with the new Grouping samples
(cherry picked from commit 3a40e3f041)
2018-10-01 14:42:00 +03:00
Itsuki Aoyagi
b6e107ef2a Add samples for groupingBy operations
(cherry picked from commit 039d41679e)
2018-10-01 14:42:00 +03:00
ymnder
453680d050 Add sample for 'repeat' function
Co-authored-by: Ilya Gorbunov <ilya.gorbunov@jetbrains.com>
(cherry picked from commit 1a20b1f357)
2018-10-01 14:42:00 +03:00
shiraji
62ad8fd760 KT-20357 Add sample code for Regex.find
Co-authored-by: Ilya Gorbunov <ilya.gorbunov@jetbrains.com>
(cherry picked from commit 0c97d99d77)
2018-10-01 14:42:00 +03:00
takattata
4eeb5558aa KT-20357 Add sample code for Char extensions
(cherry picked from commit f06ea6fddd)
2018-10-01 14:42:00 +03:00
Takayuki Matsubara
c40dea86cc KT-20357 Add samples for Map.containsValue
Co-authored-by: Ilya Gorbunov <ilya.gorbunov@jetbrains.com>
(cherry picked from commit d26c0f777b)
2018-10-01 14:42:00 +03:00
Keita Watanabe
ef93784b48 KT-20357 Add sample for mutableSet function
(cherry picked from commit 12ec4fdce0)
2018-10-01 14:42:00 +03:00
Ilya Gorbunov
f500a6fd94 KT-20357 Add samples for elementAtOrElse
Move samples to Elements nested class.

(cherry picked from commit df6ccbca49)
2018-10-01 14:42:00 +03:00
Takayuki Matsubara
a66f8ff100 KT-20357 Add samples for elementAtOrNull
(cherry picked from commit 7d5efe7f51)
2018-10-01 14:42:00 +03:00
Takayuki Matsubara
23f5083a20 KT-20357 Add samples for elementAt
(cherry picked from commit ad9b700ec4)
2018-10-01 14:42:00 +03:00
Yuki Miida
02147f6f2e Add sample for orEmpty method
(cherry picked from commit af1fc5b668)
2018-10-01 14:42:00 +03:00
Dmitriy Dolovov
a1f87da48a [K/N] Allow common source sets in projects created with wizard
Issue #KT-27232 Fixed
2018-10-01 16:28:09 +07:00
Denis Zharkov
2f77419fa2 Fix regression on smart casts in when on a sealed class
See the comment in PatternMatchingTypingVisitor

 #KT-27221 Fixed
2018-10-01 10:00:38 +03:00
Dmitry Petrov
96c68e530b Update command-line options help for '-Xnormalize-constructor-calls'
Default value depends on language version.

(cherry picked from commit 729da29e49)
2018-10-01 09:42:59 +03:00
Ilya Matveev
9d38ac9665 Update Kotlin/Native: 0.9.3 2018-09-30 10:00:53 +03:00
Ilya Matveev
3cd03a380a Filter java.endorsed.dirs property in K/N runner 2018-09-30 10:00:53 +03:00
Sergey Igushkin
e983a884de Fix unresolved library with 'java-api' and 'java-runtime' usages 2018-09-29 19:18:21 +03:00
Sergey Igushkin
244e077432 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

(cherry picked from commit 58a8411575)
2018-09-29 16:04:28 +03:00
Leonid Startsev
21c6bfc3db Check if serialization plugin presents in the facet compiler classpath before applying extensions logic
#KT-27166 Fixed

(cherry picked from commit b611facd71)
2018-09-29 14:51:10 +03:00
Mikhail Glukhikh
bef5636ce5 Add Maven Publish to MPP library wizards (in progress) #KT-27201 Fixed
(cherry picked from commit ca4547c40a)
2018-09-29 12:41:02 +03:00
Mikhail Glukhikh
9044f3b57d Introduce MPP wizard for mobile (Android / iOS) libraries
#KT-27200 Fixed

(cherry picked from commit e7100838d0)
2018-09-29 12:40:26 +03:00
Ilmir Usmanov
bc8943bfce Fix bootstrap
(cherry picked from commit e7bed58)
2018-09-28 12:32:23 +03:00
Ilmir Usmanov
792ac45b19 Use release coroutines in script-runtime
(cherry picked from commit 6e0391f)
2018-09-28 12:32:04 +03:00
Dmitry Petrov
c84324070b Migrate to release coroutines
(cherry picked from commit 0191e3d)
2018-09-28 12:31:39 +03:00
Sergey Igushkin
c796643434 Support Kotlin/JS DCE in new MPP
Issue #KT-27196 Fixed

(cherry picked from commit 2441df820b)
2018-09-27 18:02:47 +03:00
Pavel V. Talanov
fe20d025ed Prefer data from facet settings when computing module js output root
#KT-26872 Fixed
2018-09-27 17:01:56 +02:00
Ilya Matveev
9bc3dafb02 Use compileClasspath configuration for native standard libraries 2018-09-27 16:49:42 +02:00
Dmitriy Dolovov
e8a9a44c25 [K/N] Improvements in new application wizard in IDEA
Issue #KT-27210 Fixed

(cherry picked from commit bfa6d57e34)
2018-09-27 16:48:49 +02:00
Ilya Matveev
9e0dacf53c Don't add dependency on a klib task for binary tasks 2018-09-27 16:47:26 +02:00
Ilya Chernikov
60be62d021 Fix gradle support for non-kts scripts when daemon is used 2018-09-27 16:45:36 +02:00
Ilya Chernikov
0659c5f54b 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 16:45:14 +02:00
Pavel V. Talanov
679bc7a6af Default to plain 'Run' icon when calculating icons for common code
#KT-26942 Fixed
2018-09-27 10:56:38 +02:00
Nikolay Krasko
3c9ef4ab4d 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:52:25 +03:00
Alexey Sedunov
6b71029755 Configuration: Do not configure SDK for Android modules
This is already done by the Android plugin itself

 #KT-27193 Fixed

(cherry picked from commit 8d3e997a82)
2018-09-27 10:47:00 +02:00
Mikhail Zarechenskiy
1b19ba6374 Fix debugger tests because of lack of BuilderInference annotation 2018-09-27 11:40:59 +03:00
Ilmir Usmanov
24762a4e93 Fix LVT entries of 'this' and parameters in coroutine code
#KT-24510 Fixed

(cherry picked from commit 35056543a2)
2018-09-27 10:33:51 +02:00
Ilya Gorbunov
53f6967992 Remove links to contract samples as these samples are not supported by Dokka
(cherry picked from commit 7b66a4d295)
2018-09-27 10:28:18 +02:00
Ilya Gorbunov
a545675a63 Improve contract API documentation
(cherry picked from commit b2b23ac282)
2018-09-27 10:28:14 +02:00
Ilya Gorbunov
0a2d49b986 Improve documentation of experimental annotations
(cherry picked from commit f2a51f96a5)
2018-09-27 10:28:07 +02:00
Dmitry Petrov
104c160e01 Fix subject variable handling in specialized enum codegen
#KT-27161

(cherry picked from commit 7624dbbb20)
2018-09-27 10:23:59 +02:00
Denis Zharkov
ddae613557 Restore binary compatibility for IDE plugins
Caused by 341f7c348a

(cherry picked from commit c4337f753e)
2018-09-27 10:23:13 +02:00
Mikhail Glukhikh
eda10360a7 Always use Gradle wrapper 4.7 in MPP projects #KT-27177 Fixed
(cherry picked from commit 258999fa9e)
2018-09-27 11:13:22 +03:00
Yan Zhulanow
117d552931 Call 'GradleProjectImportHandler's in MPP Gradle importer (KT-27006) 2018-09-26 22:37:41 +03:00
Pavel V. Talanov
1cc313dfc3 Create ModuleInfos for newmpp modules with missing roots accurately
#KT-27010 Fixed
 #KT-27133 Fixed
2018-09-26 19:21:25 +02:00
Pavel V. Talanov
7a02615d78 Introduce SourceType and use KotlinFacetSettings.isTestModule
Refactor dealing with production/test roots
Remove ad-hoc code in KotlinMultiplatformRunLocationsProvider
2018-09-26 19:21:25 +02:00
Pavel V. Talanov
526d073e66 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-26 19:21:25 +02:00
Leonid Startsev
99367595e6 Include serialization config in IDE for IDEA 183, AS 3.2 and 3.3 2018-09-26 19:50:44 +03:00
Nikolay Krasko
66ca7c06cb Fix formatting for when with subjects (KT-27027)
#KT-27027 Fixed
2018-09-26 19:42:52 +03:00
Nikolay Krasko
422625e0cf Make ReplaceWith work for objects (KT-16211, KT-14929)
#KT-16211 Fixed
2018-09-26 19:42:52 +03:00
Nikolay Krasko
225d112388 Return updated element after reference shortening
Fresh new expression obtained after qualified expression binding is
invalidated after shortening.
2018-09-26 19:42:52 +03:00
Sergey Igushkin
720f3061eb 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

(cherry picked from commit c4283de9cb)
2018-09-26 19:33:55 +03:00
Sergey Igushkin
93f47c0947 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

(cherry picked from commit 65e3559c09)
2018-09-26 19:33:54 +03:00
Sergey Igushkin
b9ae5d3eba Add tests for variant-aware dependency resolution between projects
(cherry picked from commit fef61eca51)
2018-09-26 19:33:54 +03:00
Sergey Igushkin
5900dd739e Show warnings for disabled targets on current host
Issue #KT-26647 Fixed

(cherry picked from commit 81ae54c05b)
2018-09-26 19:33:54 +03:00
Sergey Igushkin
dbb91694fe Add an experimental feature warnings on MPP usage & metadata publishing
Issue #KT-25200 Fixed

(cherry picked from commit 4f650bb056)
2018-09-26 19:33:54 +03:00
Sergey Igushkin
fd3ea84bb2 Ensure that kapt configurations are not exposed for consumption
(cherry picked from commit 54988932a3)
2018-09-26 19:33:53 +03:00
Sergey Igushkin
259939ff41 Add tools for testing dependencies resolution by resolving all configs
(cherry picked from commit 7c05f77cb7)
2018-09-26 19:33:53 +03:00
Sergey Igushkin
a9a099401f 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.

(cherry picked from commit c3dd24e9b2)
2018-09-26 19:33:53 +03:00
Sergey Igushkin
dd21f357cc 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)

(cherry picked from commit 05301e37d8)
2018-09-26 19:33:53 +03:00
Sergey Igushkin
fc54152b81 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.

(cherry picked from commit b388f7fde0)
2018-09-26 19:33:53 +03:00
Sergey Igushkin
f2247509c4 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.

(cherry picked from commit 1abcfc76df)
2018-09-26 19:33:53 +03:00
Sergey Igushkin
cafb01ad47 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

(cherry picked from commit 76b51b1058)
2018-09-26 19:33:52 +03:00
Ilya Gorbunov
fe1eb542d8 Regenerate public API after advancing bootstrap
Unsigned progression internal synthetic constructors
are correctly detected as internal.
2018-09-26 17:15:59 +03:00
Mikhail Zarechenskiy
38f425731b Allow using extensions with trivial-constraints in builder-inference
#KT-27079 Fixed
2018-09-26 17:07:25 +03:00
Mikhail Zarechenskiy
107eef020c Fix diagnostic tests about coroutine-inference 2018-09-26 17:07:25 +03:00
Mikhail Zarechenskiy
3f022feff1 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-26 17:07:24 +03:00
Simon Ogorodnik
09ef8ddd98 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

(cherry picked from commit 189fe95d8a)
2018-09-26 17:02:38 +03:00
Simon Ogorodnik
49274d8bbf Fix missing NativeLibraryType
#KT-27009 fixed

(cherry picked from commit 68dfe9bf14)
2018-09-26 17:02:38 +03:00
Simon Ogorodnik
5a53b0ca92 Remove JPS KotlinNativeConfigurator
(cherry picked from commit 3aee3dfdd9)
2018-09-26 17:02:37 +03:00
Simon Ogorodnik
fb6f7b2353 Make possible to have no libraryDescription for 'Configure Kotlin'
(cherry picked from commit 9a79254f7e)
2018-09-26 17:02:37 +03:00
Simon Ogorodnik
ff549574c8 Add KotlinNativeGradleConfigurator to avoid 'Configure Kotlin' for K/N
(cherry picked from commit faf09a2aac)
2018-09-26 17:02:36 +03:00
Simon Ogorodnik
0e020965a6 Don't show 'Configure Kotlin' panel when module already configured
(cherry picked from commit cff648a505)
2018-09-26 17:02:36 +03:00
Ilya Matveev
e8f3c78232 Fix native test working directory 2018-09-26 16:59:11 +03:00
Ilya Matveev
49f431b033 Add implementation dependencies into publication for native 2018-09-26 16:59:10 +03:00
Ilya Matveev
4fae55661e Fix -Xcommon-sources in native args 2018-09-26 16:59:10 +03:00
Alexander Podkhalyuzin
ea5e656b86 Removed extra spaces in new MPP project template
#KT-26952  Fixed

(cherry picked from commit 3142627269)
2018-09-26 16:22:34 +03:00
Mikhail Glukhikh
194a11ecb7 Introduce MPP wizard for mobile (Android / iOS) applications
This mobile wizard already contains skeleton
Finally #KT-25952 Fixed
Also #KT-26786 Fixed

(cherry picked from commit a97f2bb992)
2018-09-26 16:21:51 +03:00
Pavel Punegov
4bbdee8dfd Increase tolerance for Float asin test 2018-09-26 16:18:06 +03:00
Pavel Punegov
f8c36e47b2 Remove unnecessary language version setting in tests 2018-09-26 16:18:05 +03:00
Sergey Bogolepov
ea13b30f82 Replace random val in companion object with top level val 2018-09-26 16:18:05 +03:00
Pavel Punegov
4afe6e01cb Make coroutines test JVM-only 2018-09-26 16:18:05 +03:00
Pavel Punegov
11a07e9705 Fix vararg test for native that assigns named argument.
Remove duplicate ignore
2018-09-26 16:18:05 +03:00
Pavel Punegov
3d03b8d43e Native: Ignore tests that use reflection not implemented in native 2018-09-26 16:18:05 +03:00
Pavel Punegov
8b2f311135 Native: Ignore tests that use jvm or full reflect 2018-09-26 16:18:04 +03:00
Pavel Punegov
2160d4ad81 Set language version to 1.2 for tests that use deprecated in 1.3 behaviour 2018-09-26 16:18:04 +03:00
Pavel Punegov
33693dcab4 Replace min with coerceAtMost in test 2018-09-26 16:18:04 +03:00
Pavel Punegov
f7890bd2c0 Disable JVM tests in native 2018-09-26 16:18:04 +03:00
Pavel Punegov
0e639ef7e8 Update ignore tag for Native backend 2018-09-26 16:18:04 +03:00
Alexey Tsvetkov
d8c4cc84ef 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-26 15:45:19 +03:00
Dmitry Savvinov
74ed159cb0 Turn off SoundSmartCastFromLoopConditionForLoopAssignedVariables
Due to KT-27084
2018-09-26 14:58:17 +03:00
Dmitry Savvinov
0ed3b58cac 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-26 14:56:30 +03:00
Alexander Udalov
c350177a19 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

(cherry picked from commit 9d27771f86)
2018-09-26 13:41:58 +02:00
Pavel V. Talanov
ef38a193bd 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-26 13:39:41 +02:00
Pavel V. Talanov
22ad7533dc 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-26 13:39:09 +02:00
Pavel V. Talanov
e140128cbb Do not show run gutters for native
#KT-26851 Fixed
2018-09-26 13:38:48 +02:00
Mikhail Glukhikh
29d75c74a6 Has actual marker: distinguish Android and JVM modules #KT-25055 Fixed
(cherry picked from commit 1f4d91da1c)
2018-09-26 14:34:03 +03:00
Mikhail Glukhikh
adc8d769fd Fix testJvmStaticUsagesRuntime from PSI checker, messages updated to 1.3
(cherry picked from commit de36d919aa)
2018-09-26 14:33:21 +03:00
Mikhail Glukhikh
3df74e3090 Fix testEnableCoroutinesFacet from update configuration group
(cherry picked from commit 625ff00f62)
2018-09-26 14:33:21 +03:00
Mikhail Glukhikh
0888aa9571 Fix Maven enable coroutines test (language version)
(cherry picked from commit a0ae4dd387)
2018-09-26 14:33:21 +03:00
Mikhail Glukhikh
a9faccd921 Remove erroneous suspend delegate tests (not supported in 1.3)
(cherry picked from commit e24f68c357)
2018-09-26 14:33:20 +03:00
Mikhail Glukhikh
a7da318836 Fix AddAnnotationTarget.testWithJava from multi-file quick fix
(cherry picked from commit 140c5d7689)
2018-09-26 14:33:20 +03:00
Mikhail Glukhikh
5b3e86df68 Fix testEnumClass (implementAsConstructorParameter)
(cherry picked from commit 9694882db6)
2018-09-26 14:33:20 +03:00
Mikhail Glukhikh
ffdfc5fd87 Switch testCoroutineContext to release coroutines thus fixing it
(cherry picked from commit b6c4bd270c)
2018-09-26 14:33:19 +03:00
Mikhail Glukhikh
081214f087 Suppress RESULT_CLASS_IN_RETURN_TYPE in ResultIsResultInspection tests
This fixes four relevant inspection tests

(cherry picked from commit 2e2b15853e)
2018-09-26 14:33:19 +03:00
Mikhail Glukhikh
96dd293734 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

(cherry picked from commit 54e7fe6c52)
2018-09-26 14:33:19 +03:00
Mikhail Glukhikh
0bec2cc7f8 ArrayInDataClass test: replace Arrays functions with Kotlin ones
This fixes relevant inspection test

(cherry picked from commit 2473362373)
2018-09-26 14:33:18 +03:00
Mikhail Glukhikh
7282c0d319 Remove SHOULD_FAIL_WITH from testQuotesName thus fixing it
(cherry picked from commit 4a3af36909)
2018-09-26 14:33:18 +03:00
Mikhail Glukhikh
3f8f5b91a5 Add new error from 1.3 into testIncorrectArgs thus fixing it
(cherry picked from commit 3014c3b33b)
2018-09-26 14:33:18 +03:00
Mikhail Glukhikh
aa37d002a2 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.

(cherry picked from commit 362ee126d1)
2018-09-26 14:33:18 +03:00
Mikhail Glukhikh
7513c41ecf 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.

(cherry picked from commit 81406a2bac)
2018-09-26 14:33:17 +03:00
Mikhail Glukhikh
296efbdb10 Add language version 1.2 to quick-fix tests for add explicit import
This fixes tests for KT-21515

(cherry picked from commit 0f8b46b7d7)
2018-09-26 14:33:17 +03:00
Mikhail Glukhikh
c2c39abc24 Fix two obsoleteCoroutines tests
(cherry picked from commit 2bba4f5aa8)
2018-09-26 14:33:17 +03:00
Ilya Chernikov
4bd548eb20 Annotate DiscoverScriptExtensionsTask properly
KT-26978 fixed
2018-09-26 13:27:49 +02:00
Alexey Sedunov
7b6f1654e0 Gradle: Inherit project SDK when no explicit one is specified
#KT-27145 Fixed
2018-09-26 13:53:42 +03:00
Dmitriy Dolovov
9c899a3e11 [K/N] User friendly displaying of Kotlin/Native default libraries in IDEA
Issue #KT-27072 Fixed

(cherry picked from commit 405bd91597)
2018-09-26 16:55:13 +07:00
Dmitriy Dolovov
7652ef0b99 [K/N] Stand-alone Native Application wizard in IDEA
Issue #KT-27076 Fixed

(cherry picked from commit 5e33860652)
2018-09-26 16:55:13 +07:00
Ilya Chernikov
ee342d5e5c 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:47:26 +02:00
Nikolay Krasko
412611acd6 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-26 11:01:00 +03:00
Nikolay Krasko
9b01b5ad59 Remove old buildIterator import (KT-26679) 2018-09-26 11:01:00 +03:00
Nikolay Krasko
a422759e54 Report jre deprecated warning when version is set implicitly (KT-26933)
#KT-26933 Fixed
2018-09-26 11:01:00 +03:00
Dmitry Petrov
64f3540c89 Postpone companion object field visibility
Have to reconsider this issue because of interface companion objects.
2018-09-26 09:20:35 +03:00
Alexey Sedunov
1f4a0fe5ae MPP: Do not populate content roots in the absence of ExternalProject
#KT-26900 Fixed
2018-09-25 18:01:09 +03:00
Alexey Sedunov
f969403405 MPP: Reset JDK for JVM modules
#KT-26937 Fixed
2018-09-25 18:01:09 +03:00
Ilya Gorbunov
e258fde2af Remove workaround for complex default value in Array.copyInto
#KT-22818

(cherry picked from commit 974837654e)
2018-09-25 17:49:01 +03:00
Ilya Gorbunov
5829437933 Advance bootstrap to 1.3.0-rc-74 2018-09-25 17:49:01 +03:00
Mikhail Zarechenskiy
d576348990 Add inference annotations to the dumped declarations 2018-09-25 17:48:39 +03:00
Ilya Chernikov
9fa62d7b3c Add kotlin-main-kts.jar to the dist 2018-09-25 14:07:17 +02:00
Ilya Chernikov
31a389d317 Fix proguarding of the main-kts 2018-09-25 13:42:24 +02:00
Alexey Sedunov
99b0352d86 Configuration: Fix JVM target detection in the absence of Kotlin facet
#KT-27021 Fixed
2018-09-25 13:38:22 +03:00
Yan Zhulanow
09cc8d0e2b Fix compatibility with JPS-standalone (KT-26777) 2018-09-25 13:35:18 +03:00
Mikhail Glukhikh
1983570688 MPP wizard: add skeleton for shared JVM/JS/iOS project
Part of KT-26786

(cherry picked from commit 83faba6424)
2018-09-25 13:11:43 +03:00
Mikhail Glukhikh
65c164892f MPP wizard: add skeleton for JVM/JS project
Part of KT-26786

(cherry picked from commit 47baaf10c6)
2018-09-25 13:11:28 +03:00
Mikhail Glukhikh
bd1eefc432 Enable feature: add test for JPS case
(cherry picked from commit 6850d7be0c)
2018-09-25 13:09:41 +03:00
Mikhail Glukhikh
06f73005ad Extract shouldConfigureInProject to AbstractChangeFeatureSupportLevelFix
(cherry picked from commit c5a81c4e8b)
2018-09-25 13:09:41 +03:00
Mikhail Glukhikh
b2dc504504 Enable / disable feature: update Gradle build script bunch for 173
(cherry picked from commit 7030a485be)
2018-09-25 13:09:41 +03:00
Mikhail Glukhikh
0fdae44562 Add enable / disable feature in JPS
#KT-26775 Fixed
#KT-26774 Fixed

(cherry picked from commit f6b805a973)
2018-09-25 13:09:41 +03:00
Mikhail Glukhikh
7ba48146fc Add enable / disable feature in Maven project
Part of KT-26775

(cherry picked from commit 8a7ff4cd24)
2018-09-25 13:09:40 +03:00
Mikhail Glukhikh
cb4068ba6c Add enable / disable feature in Gradle (Kotlin DSL) project
Part of KT-26775

(cherry picked from commit 106db57975)
2018-09-25 13:09:40 +03:00
Mikhail Glukhikh
0a2e0ef406 Add enable / disable feature in Gradle (Groovy) project, forTests option
Part of KT-26775

(cherry picked from commit 43e4616fdf)
2018-09-25 13:09:40 +03:00
Mikhail Glukhikh
789b2db7b5 Introduce skeleton for ChangeGeneralLanguageFeatureSupportFix
Part of KT-26775 and KT-26774

(cherry picked from commit b194be7665)
2018-09-25 13:09:40 +03:00
Mikhail Glukhikh
edbc1ac405 Extract AbstractChangeFeature...Fix from ChangeCoroutineSupportFix
Part of KT-26775 implementation

(cherry picked from commit fd3dfe0710)
2018-09-25 13:09:39 +03:00
Mikhail Glukhikh
2355ea791a Delete unnecessary bunches for KotlinMavenConfigurator
One private fun (instead of public) is the only difference here

(cherry picked from commit 125a136663)
2018-09-25 13:09:39 +03:00
Ilmir Usmanov
ca3bec732e Minor. Split tests with buildSequence into LV 1.2 and LV 1.3 versions
(cherry picked from commit c4038729ea)
2018-09-25 02:03:10 +03:00
Anton Bannykh
fd64b50c54 JS: fix line number data
(cherry picked from commit 66b5dd92d9)
2018-09-25 02:03:10 +03:00
Mikhail Zarechenskiy
0e4e1b6941 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

(cherry picked from commit 09cd038e4b)
2018-09-25 02:03:10 +03:00
Ilya Gorbunov
8b5c5fb16a Use modern API of Kotlin 1.3 in JS canvas examples
(cherry picked from commit 0ca59b3a40)
2018-09-25 02:03:10 +03:00
Alexander Udalov
51b848c67f Do not report experimental usage errors in import statements
#KT-25545 Fixed

(cherry picked from commit 3e90d367f2)
2018-09-24 17:59:50 +02:00
Alexander Udalov
969828bf81 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

(cherry picked from commit 3ca81b95c2)
2018-09-24 17:59:43 +02:00
Ilya Matveev
1bd837007e Update Kotlin/Native: 0.9.2 2018-09-24 18:50:06 +03:00
Ilya Matveev
3dfba8272f Pass absolute library paths to native compiler 2018-09-24 18:49:57 +03:00
Ilya Chernikov
076ccca14f Fix script util tests after moving context utils to scripting-jvm 2018-09-21 19:21:08 +02:00
Denis Zharkov
e8e73bce15 Fix bunch files for test RunConfigurationTest 2018-09-21 18:32:12 +03:00
Anton Bannykh
b6b01dd4c5 JS: fix unsigned literal inlining
(cherry picked from commit 6736987239)
2018-09-21 16:08:40 +03:00
Ilya Matveev
2a24d9cb5a Update Kotlin/Native: 0.9.2-dev-4008 2018-09-20 14:19:26 +03:00
Mikhail Zarechenskiy
4e51cef541 Support coroutine inference under version <= 1.2
Follow-up #KT-26958
2018-09-20 13:56:03 +03:00
Yan Zhulanow
67bb952df9 Do not discover script extensions for Kapt stub generation tasks (KT-26974) 2018-09-19 22:51:30 +03:00
Alexander Udalov
0969f95dfa Add ChangeLog for 1.3-RC 2018-09-19 20:39:57 +03:00
Nikolay Krasko
f0eb72ad6b Migrate for moved and renamed buildSequence/buildIterator (KT-26679)
#KT-26679 Fixed

(cherry picked from commit 64d2cdf0c2)
2018-09-19 12:48:58 +03:00
Nikolay Krasko
85e0a1b7bc Refactoring: move each problem to a separate class
(cherry picked from commit 082801efb4)
2018-09-19 12:48:58 +03:00
Ilya Gorbunov
02e276ce30 Mix kotlin-annotations-jvm with kotlin-reflect into proguard
So it can strip these annotations from the resulting jar.

#KT-26929 Fixed

(cherry picked from commit 86ba5ebf29)
2018-09-19 12:41:24 +03:00
Alexander Udalov
c029a34e0d Report warning instead of error on usages of Experimental/UseExperimental
#KT-26936 Fixed

(cherry picked from commit 8c01cd4)
2018-09-18 22:52:24 +03:00
Ilya Gorbunov
c008822d9f 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

(cherry picked from commit 1d7ee22bdc)
2018-09-18 22:42:55 +03:00
Ilya Gorbunov
1af800a07f Make overridden compareTo in unsigned types inline only
(cherry picked from commit af29dced98)
2018-09-18 22:42:52 +03:00
Ilya Gorbunov
0484a51a50 Make most of unsigned operations inline only
(cherry picked from commit 9e0708e85a)
2018-09-18 22:42:50 +03:00
Ilya Gorbunov
76e5e84a56 Extract unsigned type related extensions to separate classes
- Rename class with unsigned number to string conversions to UStringsKt
- Extract Random unsigned extensions to URandomKt

(cherry picked from commit d793221a7b)
2018-09-18 22:42:47 +03:00
Ilya Matveev
29be9d447a Serialize native compiler args
(cherry picked from commit 7d6adbd)
2018-09-18 21:52:47 +03:00
Ilya Chernikov
2cd5354c22 Make ivy resolver quiet 2018-09-18 18:37:02 +02:00
Mikhail Zarechenskiy
5c266ba184 Add BuildInference annotation onto stdlib coroutine builders 2018-09-18 19:24:45 +03:00
Mikhail Zarechenskiy
7cdc9612f7 Migration change: temporarily specify type explicitly
Because of introduction of `BuilderInference` annotation.
 Change it back after bootstrap
2018-09-18 19:24:44 +03:00
Mikhail Zarechenskiy
c169610b57 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 19:24:42 +03:00
Mikhail Zarechenskiy
181fb81473 Minor: invert logic of function 2018-09-18 19:24:41 +03:00
Nikolay Krasko
e980c75cab Fix compilation error in MavenMigrateTest.kt 2018-09-18 18:21:46 +03:00
Simon Ogorodnik
ab1f8af88b [K/N] Hack to enable exporting interop libraries 2018-09-18 17:59:15 +03:00
Dmitriy Dolovov
1655c3a7ca [K/N] Fix: Obsolete text stubs after updating K/N library
Issue #KT-26736 Fixed
2018-09-18 17:59:14 +03:00
Dmitriy Dolovov
76ebec5d37 [K/N] Proper invalidation of metadata cache in IDEA by VFS events 2018-09-18 17:59:13 +03:00
Simon Ogorodnik
5e54f84ecd Support forward declarations for Native via hack-ing into built-ins 2018-09-18 17:59:12 +03:00
Simon Ogorodnik
a847efdef7 Create Native specific LibraryInfo
This LibraryInfo contains KonanLibrary and provides correct
capabilities to ModuleDescriptor
2018-09-18 17:59:12 +03:00
Simon Ogorodnik
40607b14a9 Add function to get typed capability from ModuleInfo 2018-09-18 17:59:11 +03:00
Simon Ogorodnik
a5074a91ab Add factory function to create platform specific LibraryInfo's 2018-09-18 17:59:10 +03:00
Simon Ogorodnik
943259dfcb Do not throw exception on not-found serialized class from knm 2018-09-18 17:59:10 +03:00
Simon Ogorodnik
0fa3c9b338 Support free-form .knm package part names 2018-09-18 17:59:09 +03:00
Simon Ogorodnik
f832890360 Support for split-packages in Kotlin Native
See JetBrains/kotlin-native#2034
2018-09-18 17:59:08 +03:00
Nikolay Krasko
986f999206 Don't show migration dialog if no actual migrations are available (KT-26889)
#KT-26889 Fixed
2018-09-18 17:46:12 +03:00
Nikolay Krasko
44c07154a2 Postpone migration till indexes are ready (KT-26428)
#KT-26428 Fixed
2018-09-18 17:46:12 +03:00
Ilya Gorbunov
7aa291076d Fix sourcemap of stdlib/js to include new source sets
(cherry picked from commit cb47b0cde1)
2018-09-18 16:19:38 +03:00
Ilya Matveev
b9b94c4fe3 Support OptionalExpectation in native 2018-09-18 15:58:25 +03:00
Ilmir Usmanov
4add819658 Forbid suspension points in critical sections
#KT-26480: Fixed
2018-09-18 13:53:16 +03:00
Vyacheslav Gerasimov
30df42743d Add compatibility artifact with Mutable and ReadOnly annotations into dist
#KT-26916 Fixed
2018-09-18 13:35:07 +03:00
Ilya Matveev
09467ddc9d Use Kotlin/Native 0.9.1 (#1872) 2018-09-17 19:38:54 +03:00
Ilya Matveev
f9ef065c7b Don't add cinterop libraries in compilation output (#1871) 2018-09-17 19:38:46 +03:00
Ilya Matveev
ecc384fbfc 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 19:38:25 +03:00
Denis Zharkov
fd31e28903 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:10:26 +03:00
Alexander Podkhalyuzin
3d89a08022 JPS, native: skip and report native modules as not supported
#KT-26648 Fixed

(cherry picked from commit 9e6d6ad9da)
2018-09-17 18:55:14 +03:00
Sergey Rostov
8f07ea2348 JPS: fix daemon RPC serialization
#KT-26809 Fixed

(cherry picked from commit 39c76c7b11)
2018-09-17 18:55:12 +03:00
Dmitriy Dolovov
d52c49cf59 Move NativeIdePlatformKind to idea-jps-common
Issue #KT-26714 Fixed

(cherry picked from commit 0c94aefb87)
2018-09-17 18:55:11 +03:00
Mikhail Zarechenskiy
3dc3ce4c6e Don't throw exception on error types in light classes mode
#KT-26829 Fixed
 #KT-26827 Fixed
2018-09-17 18:50:05 +03:00
Mikhail Zarechenskiy
0702d33970 Make generation of assertions for platform types aware of kotlin types
#KT-26859 Fixed
2018-09-17 18:50:03 +03:00
Mikhail Zarechenskiy
6e0ba8bd8a 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 18:50:01 +03:00
Mikhail Zarechenskiy
6c7d062cd7 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 18:49:59 +03:00
Mikhail Zarechenskiy
d6e4309b39 Add regression test for KT-26806
#KT-26806
2018-09-17 18:49:58 +03:00
Ilya Chernikov
184742e779 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-17 14:28:39 +02:00
Ilya Chernikov
aed19965c0 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-17 14:28:22 +02:00
Nikolay Krasko
f7d5f989aa Clean accidentally committed temporary code
(cherry picked from commit 073f4f51fd)
2018-09-17 15:23:25 +03:00
Nikolay Krasko
38e661295e Bad indentation after annotation in incomplete declaration (KT-22322)
Same behavior is for any modifier in incomplete declaration.

 #KT-22322 Fixed

(cherry picked from commit 782aa94513)
2018-09-17 15:23:24 +03:00
Nikolay Krasko
88abe52633 Do not show incompatible error for *-rc13 coroutines (KT-26810)
#KT-26810 Fixed

(cherry picked from commit 94531f992d)
2018-09-17 15:23:24 +03:00
Nikolay Krasko
16b272a7cf Title and description unification for coroutines migration inspection (KT-26472)
(cherry picked from commit 8be1929634)
2018-09-17 15:23:24 +03:00
Nikolay Krasko
b270e19786 Enable Maven fix for coroutines in migration (KT-26472)
#KT-26472 Fixed

(cherry picked from commit 9bfbe8a90a)
2018-09-17 15:23:24 +03:00
Pavel V. Talanov
2763dd068d Remove as33 bunches specific to mpp run configs
It is now compatible with 182 branch
2018-09-17 13:54:43 +02:00
Pavel V. Talanov
7fd19555fc as33 branch 'since-build' is 182.4129.33 2018-09-17 13:54:22 +02:00
Pavel V. Talanov
ba3cdb7fb6 Update as33 branch to AS3.3 canary 10 release 2018-09-17 13:54:06 +02:00
Pavel V. Talanov
2ece6f579e Jest/Mocha run config producers: fix searching for test runner package
#KT-26793 Fixed
2018-09-17 13:53:45 +02:00
Pavel V. Talanov
c9010f2756 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-17 13:53:23 +02:00
Ilya Gorbunov
fab69d2f22 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

(cherry picked from commit 1b889c976a)
2018-09-17 14:38:48 +03:00
Ilya Gorbunov
b8d9f8dadd [JS IR BE] New sequence builder mocks for building stdlib
#KT-26678

(cherry picked from commit 7a7fa56d74)
2018-09-17 14:38:47 +03:00
Ilya Gorbunov
ea0cf43cec 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

(cherry picked from commit aac96c476a)
2018-09-17 14:38:47 +03:00
Ilya Gorbunov
13394a4669 Use new coroutines in samples
(cherry picked from commit 9c812c6e2b)
2018-09-17 14:38:47 +03:00
Denis Zharkov
94368f1afb Support deserialized contracts in common code
#KT-26687 Fixed
2018-09-17 12:58:50 +03:00
Alexey Sedunov
1ff86abdce MPP: Enable Android-specific content root logic for Android Studio
#KT-26813 Fixed

(cherry picked from commit 7b3973db52)
2018-09-17 11:47:32 +03:00
Alexey Sedunov
f87d2b2feb MPP: Allow 'implements' relation only within the same Gradle project
Also allow COMMON modules on the "implementer" side

(cherry picked from commit 619e2bc0db)
2018-09-17 11:47:32 +03:00
Alexey Sedunov
b20749e259 MPP: Exclude non-COMMON modules from 'implemented' list
(cherry picked from commit d5b3dc8a2a)
2018-09-17 11:47:32 +03:00
Alexey Sedunov
9e91cf2bf1 MPP: Update gradle plugin version in new MPP tests
(cherry picked from commit 5a64067601)
2018-09-17 11:47:32 +03:00
Alexey Sedunov
f17fe0bf0e MPP: Fix import of dependencies on Android modules
(cherry picked from commit 14d8425e27)
2018-09-17 11:47:32 +03:00
Alexey Sedunov
310a46ee73 MPP: Configure Kotlin facets for Android modules
#KT-26770 Fixed

(cherry picked from commit 1de0dbd67d)
2018-09-17 11:47:31 +03:00
Alexey Sedunov
56300b4ef7 MPP: Exclude COMMON modules from implementation list
(cherry picked from commit 9253f88220)
2018-09-17 11:47:31 +03:00
Alexey Sedunov
a0286c533f MPP: Add commonMain as a part of inter-project dependency
#KT-26383 Fixed

(cherry picked from commit 4970e90412)
2018-09-17 11:47:31 +03:00
Alexey Sedunov
7674acb45c MPP: Drop duplicating library produced by file collection dependency
#KT-26675 Fixed

(cherry picked from commit 469b11e0aa)
2018-09-17 11:47:31 +03:00
Alexey Sedunov
67114fcfdc MPP: Match project dependencies by target elements task
(cherry picked from commit 5ac64bcc1d)
2018-09-17 11:47:31 +03:00
Alexey Sedunov
64081b71f0 MPP: Force COMMON platform for commonMain/commonTest source sets
Follow-up for 172/AS3.1 bunches

(cherry picked from commit a417630c24)
2018-09-17 11:47:30 +03:00
Roman Elizarov
10032ee259 InlineOnly Result.getOrNull method 2018-09-16 23:16:24 +03:00
Roman Elizarov
a6ab49bf9d Removed SuccessOrFailure.
Left deprecated/error typealias to Result for 1.3-Mx users.
2018-09-16 23:16:24 +03:00
Roman Elizarov
4ec1ca807f Fixed unused exceptionOrNull result in map/mapCatching
(replaced with isSuccess check)
2018-09-16 23:16:23 +03:00
Nikolay Krasko
3b24b74340 Better parsing for external library name (KT-26794)
- Migration notification fixed
- Make fix for replacing old coroutines libraries applicable

 #KT-26794
2018-09-16 15:42:29 +03:00
Ilya Gorbunov
92c481cadf Stdlib: fix name shadowing and names of overridden method parameters
(cherry picked from commit b1c2daf1fe)
2018-09-15 00:22:44 +03:00
Ilya Gorbunov
dc4eb1e6c0 Stdlib: review and suppress warnings
(cherry picked from commit bf4be12239)
2018-09-15 00:22:42 +03:00
Ilya Gorbunov
b506b4d91a Stdlib tests: cleanup warnings
(cherry picked from commit 6786b9ece2)
2018-09-15 00:22:41 +03:00
Ilya Gorbunov
afb6552618 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.

(cherry picked from commit 7e0a658de7)
2018-09-15 00:22:39 +03:00
Ilya Gorbunov
42ea253765 Rename Random.next* parameters: remaining renames
- Correct docs after parameter renaming
- Rename parameters in Random inheritors
- Rename local variables

#KT-26596

(cherry picked from commit 928fe19801)
2018-09-15 00:22:38 +03:00
kenji tomita
e2561cb091 Rename Random.next* parameters from "origin, bound" to "from, until"
Rename Random test methods

#KT-26596

(cherry picked from commit ffb83bbdf0)
2018-09-15 00:22:36 +03:00
Leonid Startsev
4b6fa98c09 Add initialization of constantValueGenerator for correct work
Exception was thrown from serialization plugin after compiler
refactoring
2018-09-14 20:24:47 +03:00
Mikhail Glukhikh
f36e35070e MPP wizard: remove kotlin-stdlib-native & kotlin-test-native deps
Related to KT-25952

(cherry picked from commit 382379d785)
2018-09-14 19:49:03 +03:00
Raluca Sauciuc
4cbdaebb36 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

(cherry picked from commit de989c4050)
2018-09-14 18:19:58 +03:00
Alexander Udalov
dac967d804 Do not report deprecation on readBytes with API version < 1.3
#KT-26667 Fixed

(cherry picked from commit 863c0051ce)
2018-09-14 16:21:37 +03:00
Dmitry Petrov
b930e6e8e8 Fix annotations loading for inline class constructors 2018-09-14 16:11:09 +03:00
Ilya Matveev
7c99348051 Add a project property for Kotlin/Native version overriding 2018-09-14 15:32:12 +03:00
Ilya Matveev
47f1ff8a36 Download native compiler in configuration stage 2018-09-14 15:31:11 +03:00
Alexander Udalov
c5fc729297 Support inline classes in function signatures in call/callBy
#KT-25664 Fixed
 #KT-26748 Open
 #KT-26765 Open

(cherry picked from commit 3a5de13dd4)
2018-09-14 14:42:49 +03:00
Alexander Udalov
da0fb1cbb0 Make CallerImpl with subclasses a sealed hierarchy
(cherry picked from commit 3e79bd2b0e)
2018-09-14 14:42:44 +03:00
Alexander Udalov
24a22fe127 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

(cherry picked from commit 8c8f0639f8)
2018-09-14 14:42:39 +03:00
Alexander Udalov
32c03876f2 Extract Caller interface out of FunctionCaller, move to subpackage
Also rename FunctionCaller to CallerImpl and extract irrelevant
declarations out of it

(cherry picked from commit 356b02cb91)
2018-09-14 14:42:35 +03:00
Alexander Udalov
6daa43895a Minor, use arrayOf to simplify code in FunctionCaller
(cherry picked from commit 43dcbbcce1)
2018-09-14 14:42:30 +03:00
Ilya Chernikov
82cc6ba1e3 Implement support for non-kts scripts in gradle
#KT-26784 fixed
2018-09-13 20:52:50 +02:00
Denis Zharkov
9fff156d6c 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:50:37 +03:00
Ilya Gorbunov
6129012d4f contentDeepToString: use list instead of set for infinite recursion tracking
#KT-26388

(cherry picked from commit 9353cfb526)
2018-09-13 17:22:25 +03:00
Ilya Gorbunov
dd4b0d7296 Specialize contentDeepEquals/HashCode/ToString for arrays of unsigned types
#KT-26388

(cherry picked from commit 2d356b89b5)
2018-09-13 17:22:23 +03:00
Ilya Gorbunov
f2bc5da814 Add annotations-13.0 in classpath of those tests where the annotations from stdlib were used
(cherry picked from commit 3cc606577c)
2018-09-13 17:20:13 +03:00
Ilya Gorbunov
5470b9a7a8 Do not use deprecated org.junit.Test in gradle js integration tests
(cherry picked from commit f340bc9f91)
2018-09-13 17:20:11 +03:00
Mikhail Glukhikh
36b84247b1 Allow to move suspend lambda out of parentheses
#KT-26674 Fixed
#KT-26676 Fixed

(cherry picked from commit 76d1d6ff12)
2018-09-13 17:08:42 +03:00
Mikhail Glukhikh
66352155df Introduce MPP wizard for shared (JVM / JS / iOS) libraries
This implements second part of KT-25952

(cherry picked from commit 941e5ae1b2)
2018-09-13 12:52:40 +03:00
Mikhail Glukhikh
7405c31d18 Kotlin JVM/JS multiplatform builder: change description
(cherry picked from commit 84587eb0f9)
2018-09-13 12:52:14 +03:00
Mikhail Glukhikh
f44b85b326 Change KonanPlatform platform name: Konan -> Native #KT-26691 Fixed
(cherry picked from commit 03820245eb)
2018-09-13 09:59:58 +03:00
Ilmir Usmanov
02d1d832f1 Use our own primitive boxing methods in coroutines codegen
#KT-26490 Fixed
2018-09-12 17:01:19 +03:00
Ilmir Usmanov
8e696bcbf1 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 17:01:19 +03:00
Ilmir Usmanov
929957e963 Exclude kotlin.coroutines.intrinsics and kotlin.coroutines.jvm.internal
from default imports.
2018-09-12 17:01:18 +03:00
Alexander Podkhalyuzin
9f428daad9 Light classes should reuse language versions settings during generation
#KT-26732 Fixed

(cherry picked from commit 85ba637796)
2018-09-12 16:16:39 +03:00
Dmitry Petrov
1b519b340e 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:37:20 +03:00
973 changed files with 28906 additions and 13061 deletions

1
.bunch
View File

@@ -5,3 +5,4 @@ as31_173_181
as32_181
as33
183
as34_183

View File

@@ -105,6 +105,8 @@
<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." />
</list>
</option>
</inspection_tool>

File diff suppressed because it is too large Load Diff

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

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

@@ -13,7 +13,7 @@ import proguard.gradle.ProGuardTask
buildscript {
extra["defaultSnapshotVersion"] = "1.3-SNAPSHOT"
kotlinBootstrapFrom(BootstrapOption.TeamCity("1.3.0-dev-496", onlySuccessBootstrap = false))
kotlinBootstrapFrom(BootstrapOption.TeamCity("1.3.0-rc-74", projectExtId = "Kotlin_130_Compiler", onlySuccessBootstrap = false))
repositories {
bootstrapKotlinRepo?.let(::maven)
@@ -122,8 +122,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"
@@ -273,8 +273,7 @@ allprojects {
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<*>> {
@@ -511,7 +510,8 @@ 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")
}

View File

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

View File

@@ -191,7 +191,6 @@ fun ConfigurationContainer.getOrCreate(name: String): Configuration = findByName
fun Jar.setupPublicJar(baseName: String, classifier: String = "") {
val buildNumber = project.rootProject.extra["buildNumber"] as String
this.baseName = baseName
this.version = buildNumber
this.classifier = classifier
manifest.attributes.apply {
put("Implementation-Vendor", "JetBrains")

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

@@ -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
}
@@ -907,19 +915,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

@@ -66,13 +66,16 @@ 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)
}
}
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)

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;
@@ -490,13 +491,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 +507,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

@@ -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);
@@ -3239,7 +3239,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 +3393,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();
@@ -4354,8 +4363,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
);

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

@@ -76,6 +76,7 @@ import static org.jetbrains.kotlin.descriptors.annotations.AnnotationUtilKt.isEf
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.*;
@@ -226,13 +227,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) {
@@ -269,6 +267,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,

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;
}

View File

@@ -406,7 +406,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);

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

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

@@ -318,7 +318,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 +353,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
@@ -721,7 +740,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 +1445,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);

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

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

@@ -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))
}
@@ -131,10 +142,10 @@ class CoroutineTransformerMethodVisitor(
transformCallAndReturnContinuationLabel(it.index + 1, it.value, methodNode, suspendMarkerVarIndex)
}
val defaultLabel = LabelNode()
val tableSwitchLabel = LabelNode()
methodNode.instructions.apply {
val startLabel = LabelNode()
val firstStateLabel = LabelNode()
val defaultLabel = LabelNode()
// tableswitch(this.label)
insertBefore(
@@ -151,13 +162,13 @@ class CoroutineTransformerMethodVisitor(
0,
suspensionPoints.size,
defaultLabel,
startLabel, *suspensionPointLabels.toTypedArray()
firstStateLabel, *suspensionPointLabels.toTypedArray()
),
startLabel
firstStateLabel
)
)
insert(startLabel, withInstructionAdapter {
insert(firstStateLabel, withInstructionAdapter {
generateResumeWithExceptionCheck(languageVersionSettings.isReleaseCoroutines(), dataIndex, exceptionIndex)
})
insert(last, defaultLabel)
@@ -171,13 +182,13 @@ 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 {
@@ -188,6 +199,71 @@ class CoroutineTransformerMethodVisitor(
}
}
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
}
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>,
@@ -220,7 +296,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 +368,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 +377,6 @@ class CoroutineTransformerMethodVisitor(
it.`var` = continuationIndex
}
val startLabel = LabelNode()
methodNode.instructions.insert(withInstructionAdapter {
val createStateInstance = Label()
val afterCoroutineStateCreated = Label()
@@ -318,7 +396,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 +437,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 +449,6 @@ class CoroutineTransformerMethodVisitor(
visitVarInsn(Opcodes.ASTORE, exceptionIndex)
}
})
return startLabel
}
private fun removeUnreachableSuspensionPointsAndExitPoints(methodNode: MethodNode, suspensionPoints: MutableList<SuspensionPoint>) {
@@ -880,7 +958,7 @@ private fun allSuspensionPointsAreTailCalls(
}
}
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())

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

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

File diff suppressed because it is too large Load Diff

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

@@ -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
);
@@ -1400,7 +1404,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 +1418,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

@@ -27,6 +27,7 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.firstOverridden
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.descriptorUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.descriptorUtil.propertyIfAccessor
import org.jetbrains.kotlin.resolve.isInlineClassType
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.getEffectiveVariance
@@ -78,12 +79,19 @@ private val METHODS_WITH_DECLARATION_SITE_WILDCARDS = setOf(
fun TypeMappingMode.updateArgumentModeFromAnnotations(type: KotlinType): TypeMappingMode {
type.suppressWildcardsMode()?.let {
return TypeMappingMode.createWithConstantDeclarationSiteWildcardsMode(
skipDeclarationSiteWildcards = it, isForAnnotationParameter = isForAnnotationParameter)
skipDeclarationSiteWildcards = it,
isForAnnotationParameter = isForAnnotationParameter,
needInlineClassWrapping = needInlineClassWrapping
)
}
if (type.annotations.hasAnnotation(JVM_WILDCARD_ANNOTATION_FQ_NAME)) {
return TypeMappingMode.createWithConstantDeclarationSiteWildcardsMode(
skipDeclarationSiteWildcards = false, isForAnnotationParameter = isForAnnotationParameter, fallbackMode = this)
skipDeclarationSiteWildcards = false,
isForAnnotationParameter = isForAnnotationParameter,
fallbackMode = this,
needInlineClassWrapping = needInlineClassWrapping
)
}
return this
@@ -97,7 +105,10 @@ internal fun extractTypeMappingModeFromAnnotation(
(outerType.suppressWildcardsMode() ?: callableDescriptor?.suppressWildcardsMode())?.let {
if (outerType.arguments.isNotEmpty())
TypeMappingMode.createWithConstantDeclarationSiteWildcardsMode(
skipDeclarationSiteWildcards = it, isForAnnotationParameter = isForAnnotationParameter)
skipDeclarationSiteWildcards = it,
isForAnnotationParameter = isForAnnotationParameter,
needInlineClassWrapping = !outerType.isInlineClassType()
)
else
TypeMappingMode.DEFAULT
}

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

@@ -0,0 +1,50 @@
/*
* 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.cli.common.arguments
import org.jetbrains.kotlin.config.LanguageFeature
object CliArgumentStringBuilder {
private const val languagePrefix = "-XXLanguage:"
private val LanguageFeature.State.sign: String
get() = when (this) {
LanguageFeature.State.ENABLED -> "+"
LanguageFeature.State.DISABLED -> "-"
LanguageFeature.State.ENABLED_WITH_WARNING -> "+" // not supported normally
LanguageFeature.State.ENABLED_WITH_ERROR -> "-" // not supported normally
}
fun LanguageFeature.buildArgumentString(state: LanguageFeature.State): String {
return "$languagePrefix${state.sign}$name"
}
fun String.replaceLanguageFeature(
feature: LanguageFeature,
state: LanguageFeature.State,
prefix: String = "",
postfix: String = "",
separator: String = ", ",
quoted: Boolean = true
): String {
val existingFeatureIndex = indexOf(feature.name)
val languagePrefixIndex = lastIndexOf(languagePrefix, existingFeatureIndex)
val featureArgumentString = feature.buildArgumentString(state)
val quote = if (quoted) "\"" else ""
return if (languagePrefixIndex != -1) {
replaceRange(languagePrefixIndex, existingFeatureIndex + feature.name.length, featureArgumentString)
} else {
val splitText = if (postfix.isNotEmpty()) split(postfix) else listOf(this, "")
if (splitText.size != 2) {
"$prefix$quote$featureArgumentString$quote$postfix"
} else {
val (mainPart, commentPart) = splitText
// In Groovy / Kotlin DSL, we can have comment after [...] or listOf(...)
mainPart + "$separator$quote$featureArgumentString$quote$postfix" + commentPart
}
}
}
}

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)

View File

@@ -16,8 +16,6 @@ private const val EXPERIMENTAL_ARGFILE_ARGUMENT = "-Xargfile="
private const val SINGLE_QUOTE = '\''
private const val DOUBLE_QUOTE = '"'
private const val BACKSLASH = '\\'
private const val WHITESPACE = ' '
private const val NEWLINE = '\n'
/**
* Performs initial preprocessing of arguments, passed to the compiler.
@@ -56,13 +54,14 @@ private fun Reader.parseNextArgument(): String? {
val sb = StringBuilder()
var r = nextChar()
while (r != null && (r == WHITESPACE || r == NEWLINE)) {
while (r != null && r.isWhitespace()) {
r = nextChar()
}
loop@ while (r != null) {
while (r != null) {
if (r.isWhitespace()) break
when (r) {
WHITESPACE, NEWLINE -> break@loop
DOUBLE_QUOTE, SINGLE_QUOTE -> consumeRestOfEscapedSequence(sb, r)
BACKSLASH -> nextChar()?.apply(sb::append)
else -> sb.append(r)

View File

@@ -20,6 +20,7 @@ import com.intellij.openapi.Disposable
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.impl.ZipHandler
import com.intellij.openapi.vfs.impl.jar.CoreJarFileSystem
import org.jetbrains.kotlin.build.DEFAULT_KOTLIN_SOURCE_FILES_EXTENSIONS
import org.jetbrains.kotlin.build.JvmSourceRoot
import org.jetbrains.kotlin.cli.common.CLICompiler
import org.jetbrains.kotlin.cli.common.ExitCode
@@ -559,6 +560,13 @@ class CompileServiceImpl(
k2jvmArgs.commonSources = parsedModule.modules.flatMap { it.getCommonSourceFiles() }.toTypedArray().takeUnless { it.isEmpty() }
val allKotlinFiles = parsedModule.modules.flatMap { it.getSourceFiles().map(::File) }
val allKotlinExtensions = (
DEFAULT_KOTLIN_SOURCE_FILES_EXTENSIONS +
allKotlinFiles.asSequence()
.map { it.extension }
.filter { !it.equals("java", ignoreCase = true) }
.asIterable()
).distinct()
k2jvmArgs.friendPaths = parsedModule.modules.flatMap(Module::getFriendPaths).toTypedArray()
val changedFiles = if (incrementalCompilationOptions.areFileChangesKnown) {
@@ -592,7 +600,8 @@ class CompileServiceImpl(
buildHistoryFile = incrementalCompilationOptions.multiModuleICSettings.buildHistoryFile,
localStateDirs = incrementalCompilationOptions.localStateDirs,
usePreciseJavaTracking = incrementalCompilationOptions.usePreciseJavaTracking,
modulesApiHistory = modulesApiHistory
modulesApiHistory = modulesApiHistory,
kotlinSourceFilesExtensions = allKotlinExtensions
)
return compiler.compile(allKotlinFiles, k2jvmArgs, compilerMessageCollector, changedFiles)
}

View File

@@ -148,7 +148,7 @@ public class SingleAbstractMethodUtils {
// Otherwise android data binding can cause resolve re-entrance
// For details see KT-18687, KT-16149
// TODO: prevent resolve re-entrance on architecture level, or (alternatively) ask data binding owners not to do it
if (DescriptorUtilsKt.getFqNameSafe(klass).asString().equals("android.databinding.DataBindingComponent")) {
if (DescriptorUtilsKt.getFqNameSafe(klass).asString().endsWith(".databinding.DataBindingComponent")) {
return null;
}

View File

@@ -281,18 +281,19 @@ public abstract class FileBasedKotlinClass implements KotlinJvmBinaryClass {
return resolveNameByInternalName(name, innerClasses);
}
// See ReflectKotlinStructure.classLiteralValue
@NotNull
private static ClassLiteralId resolveKotlinNameByType(@NotNull Type type, @NotNull InnerClassesInfo innerClasses) {
String typeDesc = type.getDescriptor();
int nestedness = typeDesc.charAt(0) == '[' ? type.getDimensions() : 0;
String elementDesc = nestedness == 0 ? typeDesc : type.getElementType().getDescriptor();
int dimensions = typeDesc.charAt(0) == '[' ? type.getDimensions() : 0;
String elementDesc = dimensions == 0 ? typeDesc : type.getElementType().getDescriptor();
JvmPrimitiveType primType = JvmPrimitiveType.getByDesc(elementDesc);
if (primType != null) {
return new ClassLiteralId(ClassId.topLevel(primType.getPrimitiveType().getTypeFqName()), nestedness);
return new ClassLiteralId(ClassId.topLevel(primType.getPrimitiveType().getTypeFqName()), dimensions);
}
ClassId javaClassId = resolveNameByDesc(elementDesc, innerClasses);
ClassId kotlinClassId = JavaToKotlinClassMap.INSTANCE.mapJavaToKotlin(javaClassId.asSingleFqName());
return new ClassLiteralId(kotlinClassId != null ? kotlinClassId : javaClassId, nestedness);
return new ClassLiteralId(kotlinClassId != null ? kotlinClassId : javaClassId, dimensions);
}
@NotNull

View File

@@ -0,0 +1,70 @@
/*
* 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.resolve.jvm.checkers
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.isTopLevelInPackage
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtValueArgumentList
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.checkers.CallChecker
import org.jetbrains.kotlin.resolve.calls.checkers.CallCheckerContext
import org.jetbrains.kotlin.resolve.calls.checkers.findEnclosingSuspendFunction
import org.jetbrains.kotlin.resolve.calls.model.ExpressionValueArgument
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
import org.jetbrains.kotlin.resolve.source.getPsi
class SuspensionPointInSynchronizedCallChecker : CallChecker {
override fun check(resolvedCall: ResolvedCall<*>, reportOn: PsiElement, context: CallCheckerContext) {
val descriptor = resolvedCall.candidateDescriptor
if (descriptor !is FunctionDescriptor || !descriptor.isSuspend) return
val enclosingSuspendFunctionSource = findEnclosingSuspendFunction(context)?.source?.getPsi() ?: return
// Search for `synchronized` call
var parent = reportOn
var child = reportOn
var insideLambda = false
while (parent != enclosingSuspendFunctionSource) {
if (parent is KtCallExpression) {
if (checkCall(context, parent, child, insideLambda, reportOn, resolvedCall)) break
}
if (parent is KtLambdaExpression) {
insideLambda = true
}
// The lambda is inside parentheses -> keep the child the same to check whether it is the second argument
if (parent !is KtValueArgumentList) {
child = parent
}
// parent.parent can be null if we edit the file, see EA-2158254 and KT-27484
parent = parent.parent ?: return
}
}
private fun checkCall(
context: CallCheckerContext,
parent: KtCallExpression,
child: PsiElement,
insideLambda: Boolean,
reportOn: PsiElement,
resolvedCall: ResolvedCall<*>
): Boolean {
val call = context.trace[BindingContext.CALL, parent.calleeExpression] ?: return false
val resolved = context.trace[BindingContext.RESOLVED_CALL, call] ?: return false
val isSynchronized = resolved.resultingDescriptor.isTopLevelInPackage("synchronized", "kotlin")
if (isSynchronized) {
val isSecondArgument = (resolved.valueArgumentsByIndex?.get(1) as? ExpressionValueArgument)?.valueArgument == child
if (insideLambda && isSecondArgument) {
context.trace.report(ErrorsJvm.SUSPENSION_POINT_INSIDE_SYNCHRONIZED.on(reportOn, resolvedCall.resultingDescriptor))
}
return true
}
return false
}
}

View File

@@ -1,17 +1,6 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* 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.resolve.jvm.diagnostics;
@@ -147,6 +136,8 @@ public class DefaultErrorMessagesJvm implements DefaultErrorMessages.Extension {
MAP.put(USAGE_OF_JVM_DEFAULT_THROUGH_SUPER_CALL, "Super calls of '@JvmDefault' members are only allowed with -Xjvm-default option");
MAP.put(NON_JVM_DEFAULT_OVERRIDES_JAVA_DEFAULT, "Non-@JvmDefault interface method cannot override default Java method. Please annotate this method with @JvmDefault");
MAP.put(EXPLICIT_METADATA_IS_DISALLOWED, "Explicit @Metadata is disallowed");
MAP.put(SUSPENSION_POINT_INSIDE_MONITOR, "A suspension point at {0} is inside a critical section", STRING);
MAP.put(SUSPENSION_POINT_INSIDE_SYNCHRONIZED, "The ''{0}'' suspension point is inside a synchronized block", NAME);
}
@NotNull

View File

@@ -1,22 +1,12 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* 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.resolve.jvm.diagnostics;
import com.intellij.psi.PsiElement;
import org.jetbrains.kotlin.descriptors.CallableDescriptor;
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor;
import org.jetbrains.kotlin.diagnostics.*;
import org.jetbrains.kotlin.name.FqName;
@@ -132,6 +122,9 @@ public interface ErrorsJvm {
DiagnosticFactory1<KtAnnotationEntry, String> ANNOTATION_TARGETS_NON_EXISTENT_ACCESSOR = DiagnosticFactory1.create(WARNING);
DiagnosticFactory1<PsiElement, String> SUSPENSION_POINT_INSIDE_MONITOR = DiagnosticFactory1.create(ERROR);
DiagnosticFactory1<PsiElement, CallableDescriptor> SUSPENSION_POINT_INSIDE_SYNCHRONIZED = DiagnosticFactory1.create(ERROR);
@SuppressWarnings("UnusedDeclaration")
Object _initializer = new Object() {
{

View File

@@ -1,17 +1,6 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* 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.resolve.jvm.platform
@@ -52,6 +41,7 @@ object JvmPlatformConfigurator : PlatformConfigurator(
additionalCallCheckers = listOf(
JavaAnnotationCallChecker(),
SuspensionPointInSynchronizedCallChecker(),
JavaClassOnCompanionChecker(),
ProtectedInSuperClassCompanionCallChecker(),
UnsupportedSyntheticCallableReferenceChecker(),

View File

@@ -16,7 +16,7 @@
package org.jetbrains.kotlin.script
import kotlinx.coroutines.experimental.runBlocking
import kotlinx.coroutines.runBlocking
import kotlin.script.experimental.dependencies.DependenciesResolver
import kotlin.script.dependencies.Environment
import kotlin.script.dependencies.ScriptContents

View File

@@ -45,7 +45,6 @@ import org.jetbrains.kotlin.resolve.TargetPlatform
import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.storage.getValue
import java.util.*
import kotlin.coroutines.experimental.buildSequence
class ResolverForModule(
val packageFragmentProvider: PackageFragmentProvider,
@@ -346,7 +345,7 @@ class LazyModuleDependencies<M : ModuleInfo>(
) : ModuleDependencies {
private val dependencies = storageManager.createLazyValue {
val moduleDescriptor = resolverForProject.descriptorForModule(module)
buildSequence {
sequence {
if (firstDependency != null) {
yield(resolverForProject.descriptorForModule(firstDependency))
}
@@ -502,4 +501,7 @@ private object DiagnoseUnknownModuleInfoReporter {
private fun errorInSpecialModuleInfoResolver(message: String): Nothing = throw AssertionError(message)
private fun otherError(message: String): Nothing = throw AssertionError(message)
}
}
@Suppress("UNCHECKED_CAST")
fun <T> ModuleInfo.getCapability(capability: ModuleDescriptor.Capability<T>) = capabilities[capability] as? T

View File

@@ -29,6 +29,7 @@ import org.jetbrains.kotlin.container.useImpl
import org.jetbrains.kotlin.container.useInstance
import org.jetbrains.kotlin.context.ModuleContext
import org.jetbrains.kotlin.context.ProjectContext
import org.jetbrains.kotlin.contracts.ContractDeserializerImpl
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.impl.CompositePackageFragmentProvider
import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl
@@ -165,6 +166,7 @@ object CommonAnalyzerFacade : ResolverForModuleFactory() {
useInstance(metadataPartProvider)
useInstance(declarationProviderFactory)
useImpl<MetadataPackageFragmentProvider>()
useImpl<ContractDeserializerImpl>()
val metadataFinderFactory = ServiceManager.getService(moduleContext.project, MetadataFinderFactory::class.java)
?: error("No MetadataFinderFactory in project")

View File

@@ -23,7 +23,22 @@ import org.jetbrains.kotlin.descriptors.ValueDescriptor
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValue
class ESDataFlowValue(descriptor: ValueDescriptor, val dataFlowValue: DataFlowValue) : ESVariable(descriptor)
class ESDataFlowValue(descriptor: ValueDescriptor, val dataFlowValue: DataFlowValue) : ESVariable(descriptor) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ESDataFlowValue
if (dataFlowValue != other.dataFlowValue) return false
return true
}
override fun hashCode(): Int {
return dataFlowValue.hashCode()
}
}
class ESLambda(val lambda: KtLambdaExpression) : ESValue(null) {
override fun <T> accept(visitor: ESExpressionVisitor<T>): T {

View File

@@ -34,29 +34,43 @@ import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.resolve.scopes.LexicalScopeKind
class ContractParsingServices(val languageVersionSettings: LanguageVersionSettings) {
/**
* ! IMPORTANT NOTICE !
*
* This function has very important non-obvious implicit contract:
* it *must* call [org.jetbrains.kotlin.contracts.description.LazyContractProvider.setContractDescription]
* if FunctionDescriptor had [LazyContractProvider] in the user data.
*
* Otherwise, it may lead to inconsistent resolve state and failed assertions
*/
fun checkContractAndRecordIfPresent(expression: KtExpression, trace: BindingTrace, scope: LexicalScope, isFirstStatement: Boolean) {
if (!expression.isContractDescriptionCallPsiCheck()) return // fastpath
// Fastpath. Note that it doesn't violates invariant described in KDoc, because 'isContractDescriptionCallPsiCheck'
// is a *necessary* (but not sufficient, actually) condition for presence of 'LazyContractProvider'
if (!expression.isContractDescriptionCallPsiCheck()) return
val collector = TraceBasedCollector(trace, expression)
val callContext = ContractCallContext(expression, isFirstStatement, scope, trace.bindingContext)
val contractProviderIfAny = (scope.ownerDescriptor as? FunctionDescriptor)?.getUserData(ContractProviderKey)
if (!callContext.isContractDescriptionCallPreciseCheck()) {
contractProviderIfAny?.setContractDescription(null)
return
}
val parsedContract = doCheckContract(collector, callContext)
collector.flushDiagnostics(parsingFailed = parsedContract == null)
val contractProviderIfAny = (scope.ownerDescriptor as? FunctionDescriptor)?.getUserData(ContractProviderKey)
if (collector.hasErrors())
contractProviderIfAny?.setContractDescription(null)
else
contractProviderIfAny?.setContractDescription(parsedContract)
}
private fun ContractCallContext.isContractDescriptionCallPreciseCheck(): Boolean =
contractCallExpression.isContractDescriptionCallPreciseCheck(bindingContext)
private fun doCheckContract(collector: ContractParsingDiagnosticsCollector, callContext: ContractCallContext): ContractDescription? {
val expression = callContext.contractCallExpression
val bindingContext = callContext.bindingContext
if (!expression.isContractDescriptionCallPreciseCheck(bindingContext)) return null
checkFeatureEnabled(collector)
checkContractAllowedHere(collector, callContext)

View File

@@ -87,7 +87,7 @@ fun DeclarationDescriptor.isCallsInPlaceEffectDescriptor(): Boolean = equalsDslD
fun DeclarationDescriptor.isInvocationKindEnum(): Boolean = equalsDslDescriptor(INVOCATION_KIND_ENUM)
fun DeclarationDescriptor.isEqualsDescriptor(): Boolean =
this is FunctionDescriptor && this.name == Name.identifier("equals") && // fast checks
this is FunctionDescriptor && this.name == Name.identifier("equals") && dispatchReceiverParameter != null && // fast checks
this.returnType?.isBoolean() == true && this.valueParameters.singleOrNull()?.type?.isNullableAny() == true // signature matches
internal fun ResolvedCall<*>.firstArgumentAsExpressionOrNull(): KtExpression? =

View File

@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.coroutines
import org.jetbrains.kotlin.builtins.isFunctionOrSuspendFunctionType
import org.jetbrains.kotlin.builtins.isSuspendFunctionType
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
@@ -24,3 +25,5 @@ import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor
val CallableDescriptor.isSuspendLambda get() = this is AnonymousFunctionDescriptor && this.isSuspend
val ValueParameterDescriptor.hasSuspendFunctionType get() = returnType?.isSuspendFunctionType == true
val ValueParameterDescriptor.hasFunctionOrSuspendFunctionType get() = returnType?.isFunctionOrSuspendFunctionType == true

View File

@@ -244,7 +244,7 @@ public interface Errors {
DiagnosticFactory2<PsiElement, FqName, DeclarationDescriptor> EXPERIMENTAL_OVERRIDE = DiagnosticFactory2.create(WARNING);
DiagnosticFactory2<PsiElement, FqName, DeclarationDescriptor> EXPERIMENTAL_OVERRIDE_ERROR = DiagnosticFactory2.create(ERROR);
DiagnosticFactory0<PsiElement> EXPERIMENTAL_IS_NOT_ENABLED = DiagnosticFactory0.create(ERROR);
DiagnosticFactory0<PsiElement> EXPERIMENTAL_IS_NOT_ENABLED = DiagnosticFactory0.create(WARNING);
DiagnosticFactory0<PsiElement> EXPERIMENTAL_CAN_ONLY_BE_USED_AS_ANNOTATION = DiagnosticFactory0.create(ERROR);
DiagnosticFactory0<PsiElement>
EXPERIMENTAL_MARKER_CAN_ONLY_BE_USED_AS_ANNOTATION_OR_ARGUMENT_IN_USE_EXPERIMENTAL = DiagnosticFactory0.create(ERROR);
@@ -788,6 +788,8 @@ public interface Errors {
DiagnosticFactory3<KtBinaryExpression, KtSimpleNameExpression, KotlinType, KotlinType> EQUALITY_NOT_APPLICABLE =
DiagnosticFactory3.create(ERROR);
DiagnosticFactory2<KtElement, KotlinType, KotlinType> INCOMPATIBLE_ENUM_COMPARISON =
DiagnosticFactory2.create(WARNING);
DiagnosticFactory1<KtExpression, KotlinType> HAS_NEXT_MISSING = DiagnosticFactory1.create(ERROR);
DiagnosticFactory1<KtExpression, KotlinType> HAS_NEXT_FUNCTION_AMBIGUITY = DiagnosticFactory1.create(ERROR);
@@ -1037,6 +1039,7 @@ public interface Errors {
DiagnosticFactory0<KtDeclaration> OVERRIDE_BY_INLINE = DiagnosticFactory0.create(WARNING, DECLARATION_SIGNATURE);
DiagnosticFactory0<PsiElement> REIFIED_TYPE_PARAMETER_IN_OVERRIDE = DiagnosticFactory0.create(ERROR);
DiagnosticFactory1<PsiElement, CallableDescriptor> INLINE_CALL_CYCLE = DiagnosticFactory1.create(ERROR, DEFAULT);
DiagnosticFactory1<PsiElement, CallableDescriptor> SUSPENSION_POINT_INSIDE_MONITOR = DiagnosticFactory1.create(ERROR, DEFAULT);
DiagnosticFactory0<PsiElement> NON_LOCAL_RETURN_IN_DISABLED_INLINE = DiagnosticFactory0.create(ERROR);
DiagnosticFactory0<KtDeclaration> INLINE_PROPERTY_WITH_BACKING_FIELD = DiagnosticFactory0.create(ERROR, DECLARATION_SIGNATURE);
DiagnosticFactory0<KtAnnotationEntry> NON_INTERNAL_PUBLISHED_API = DiagnosticFactory0.create(ERROR);

View File

@@ -729,6 +729,8 @@ public class DefaultErrorMessages {
return nameExpression.getReferencedName();
}, RENDER_TYPE, RENDER_TYPE);
MAP.put(INCOMPATIBLE_ENUM_COMPARISON, "Comparison of incompatible enums ''{0}'' and ''{1}'' is always unsuccessful", RENDER_TYPE, RENDER_TYPE);
MAP.put(SENSELESS_COMPARISON, "Condition ''{0}'' is always ''{1}''", ELEMENT_TEXT, TO_STRING);
MAP.put(SENSELESS_NULL_IN_WHEN, "Expression under 'when' is never equal to null");
@@ -934,6 +936,7 @@ public class DefaultErrorMessages {
//Inline non locals
MAP.put(NON_LOCAL_RETURN_NOT_ALLOWED, "Can''t inline ''{0}'' here: it may contain non-local returns. Add ''crossinline'' modifier to parameter declaration ''{0}''", ELEMENT_TEXT);
MAP.put(INLINE_CALL_CYCLE, "The ''{0}'' invocation is a part of inline cycle", NAME);
MAP.put(SUSPENSION_POINT_INSIDE_MONITOR, "The ''{0}'' suspension point is inside a critical section", NAME);
MAP.put(NON_LOCAL_RETURN_IN_DISABLED_INLINE, "Non-local returns are not allowed with inlining disabled");
MAP.put(NON_LOCAL_SUSPENSION_POINT, "Suspension functions can be called only within coroutine body");
MAP.put(ILLEGAL_SUSPEND_FUNCTION_CALL, "Suspend function ''{0}'' should be called only from a coroutine or another suspend function", NAME);

View File

@@ -42,3 +42,6 @@ fun AnnotationDescriptor.argumentValue(parameterName: String): ConstantValue<*>?
DeprecationLevel.ERROR
)
val JVM_FIELD_ANNOTATION_FQ_NAME = FqName("kotlin.jvm.JvmField")
val KOTLINX_SERIALIZABLE_FQ_NAME = FqName("kotlinx.serialization.Serializable")
val KOTLINX_SERIALIZER_FQ_NAME = FqName("kotlinx.serialization.Serializer")

View File

@@ -198,10 +198,14 @@ public class BindingContextUtils {
return expression instanceof KtReferenceExpression;
}
public static boolean isVarCapturedInClosure(BindingContext bindingContext, DeclarationDescriptor descriptor) {
public static boolean isCapturedInClosure(BindingContext bindingContext, DeclarationDescriptor descriptor) {
if (!(descriptor instanceof VariableDescriptor) || descriptor instanceof PropertyDescriptor) return false;
VariableDescriptor variableDescriptor = (VariableDescriptor) descriptor;
return bindingContext.get(CAPTURED_IN_CLOSURE, variableDescriptor) != null && variableDescriptor.isVar();
return bindingContext.get(CAPTURED_IN_CLOSURE, variableDescriptor) != null;
}
public static boolean isVarCapturedInClosure(BindingContext bindingContext, DeclarationDescriptor descriptor) {
return isCapturedInClosure(bindingContext, descriptor) && ((VariableDescriptor) descriptor).isVar();
}
@NotNull

View File

@@ -55,7 +55,9 @@ class OverloadChecker(val specificityComparator: TypeSpecificityComparator) {
// They can be disambiguated by providing explicit type parameters.
if (a.typeParameters.isEmpty() != b.typeParameters.isEmpty()) return true
if (ErrorUtils.containsErrorType(a) || ErrorUtils.containsErrorType(b)) return true
if (a is FunctionDescriptor && ErrorUtils.containsErrorTypeInParameters(a) ||
b is FunctionDescriptor && ErrorUtils.containsErrorTypeInParameters(b)
) return true
if (a.varargParameterPosition() != b.varargParameterPosition()) return true
val aSignature = FlatSignature.createFromCallableDescriptor(a)

View File

@@ -414,7 +414,7 @@ class GenericCandidateResolver(
val effectiveExpectedType = getEffectiveExpectedType(valueParameterDescriptor, valueArgument, context)
if (isCoroutineCallWithAdditionalInference(valueParameterDescriptor, valueArgument)) {
if (isCoroutineCallWithAdditionalInference(valueParameterDescriptor, valueArgument, languageVersionSettings)) {
coroutineInferenceSupport.analyzeCoroutine(functionLiteral, valueArgument, constraintSystem, context, effectiveExpectedType)
}

View File

@@ -21,7 +21,8 @@ class ResultTypeWithNullableOperatorsChecker : CallChecker {
when {
operationNode?.elementType == KtTokens.SAFE_ACCESS -> {
val receiver = resolvedCall.resultingDescriptor.dispatchReceiverParameter ?: return
val resultingDescriptor = resolvedCall.resultingDescriptor
val receiver = resultingDescriptor.extensionReceiverParameter ?: resultingDescriptor.dispatchReceiverParameter ?: return
if (receiver.type.isResultType()) {
context.trace.report(Errors.RESULT_CLASS_WITH_NULLABLE_OPERATOR.on(operationNode!!.psi, "?."))
}

View File

@@ -46,9 +46,15 @@ fun FunctionDescriptor.isBuiltInCoroutineContext(languageVersionSettings: Langua
fun PropertyDescriptor.isBuiltInCoroutineContext(languageVersionSettings: LanguageVersionSettings) =
this.fqNameSafe.isBuiltInCoroutineContext(languageVersionSettings)
object CoroutineSuspendCallChecker : CallChecker {
private val ALLOWED_SCOPE_KINDS = setOf(LexicalScopeKind.FUNCTION_INNER_SCOPE, LexicalScopeKind.FUNCTION_HEADER_FOR_DESTRUCTURING)
private val ALLOWED_SCOPE_KINDS = setOf(LexicalScopeKind.FUNCTION_INNER_SCOPE, LexicalScopeKind.FUNCTION_HEADER_FOR_DESTRUCTURING)
fun findEnclosingSuspendFunction(context: CallCheckerContext): FunctionDescriptor? = context.scope
.parentsWithSelf.firstOrNull {
it is LexicalScope && it.kind in ALLOWED_SCOPE_KINDS &&
it.ownerDescriptor.safeAs<FunctionDescriptor>()?.isSuspend == true
}?.cast<LexicalScope>()?.ownerDescriptor?.cast()
object CoroutineSuspendCallChecker : CallChecker {
override fun check(resolvedCall: ResolvedCall<*>, reportOn: PsiElement, context: CallCheckerContext) {
val descriptor = resolvedCall.candidateDescriptor
when (descriptor) {
@@ -61,11 +67,7 @@ object CoroutineSuspendCallChecker : CallChecker {
else -> return
}
val enclosingSuspendFunction = context.scope
.parentsWithSelf.firstOrNull {
it is LexicalScope && it.kind in ALLOWED_SCOPE_KINDS &&
it.ownerDescriptor.safeAs<FunctionDescriptor>()?.isSuspend == true
}?.cast<LexicalScope>()?.ownerDescriptor?.cast<FunctionDescriptor>()
val enclosingSuspendFunction = findEnclosingSuspendFunction(context)
when {
enclosingSuspendFunction != null -> {

View File

@@ -6,6 +6,9 @@
package org.jetbrains.kotlin.resolve.calls.inference
import org.jetbrains.kotlin.builtins.*
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.coroutines.hasFunctionOrSuspendFunctionType
import org.jetbrains.kotlin.coroutines.hasSuspendFunctionType
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
@@ -31,6 +34,8 @@ import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess
import org.jetbrains.kotlin.resolve.calls.results.OverloadResolutionResultsImpl
import org.jetbrains.kotlin.resolve.calls.tasks.TracingStrategy
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.descriptorUtil.hasBuilderInferenceAnnotation
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.TypeUtils.NO_EXPECTED_TYPE
@@ -38,9 +43,7 @@ import org.jetbrains.kotlin.types.checker.NewKotlinTypeChecker
import org.jetbrains.kotlin.types.checker.TypeCheckerContext
import org.jetbrains.kotlin.types.expressions.ExpressionTypingServices
import org.jetbrains.kotlin.types.expressions.KotlinTypeInfo
import org.jetbrains.kotlin.types.typeUtil.asTypeProjection
import org.jetbrains.kotlin.types.typeUtil.builtIns
import org.jetbrains.kotlin.types.typeUtil.contains
import org.jetbrains.kotlin.types.typeUtil.*
import javax.inject.Inject
class TypeTemplate(
@@ -82,8 +85,28 @@ class CoroutineInferenceData {
} ?: type
}
fun addConstraint(subType: KotlinType, superType: KotlinType) {
csBuilder.addSubtypeConstraint(toNewVariableType(subType), toNewVariableType(superType), ConstraintPositionKind.SPECIAL.position())
internal fun addConstraint(subType: KotlinType, superType: KotlinType, allowOnlyTrivialConstraints: Boolean) {
val newSubType = toNewVariableType(subType)
val newSuperType = toNewVariableType(superType)
if (allowOnlyTrivialConstraints) {
if (isTrivialConstraint(subType, superType)) {
// It's important to avoid adding even trivial constraints from extensions,
// because we allow only calls that don't matter at all and here we can get
// into a situation when type is inferred from only trivial constraints to Any?, for example.
// Actually, this is a more general problem about inferring type without constraints (KT-5464)
return
} else {
badCallHappened()
}
}
csBuilder.addSubtypeConstraint(newSubType, newSuperType, ConstraintPositionKind.SPECIAL.position())
}
private fun isTrivialConstraint(subType: KotlinType, superType: KotlinType): Boolean {
return subType is SimpleType && subType.isNothing() || superType is SimpleType && superType.isNullableAny()
}
fun reportInferenceResult(externalCSBuilder: ConstraintSystem.Builder) {
@@ -110,6 +133,8 @@ class CoroutineInferenceSupport(
@set:Inject
lateinit var callCompleter: CallCompleter
private val languageVersionSettings get() = expressionTypingServices.languageVersionSettings
fun analyzeCoroutine(
functionLiteral: KtFunction,
valueArgument: ValueArgument,
@@ -118,7 +143,8 @@ class CoroutineInferenceSupport(
lambdaExpectedType: KotlinType
) {
val argumentExpression = valueArgument.getArgumentExpression() ?: return
if (!lambdaExpectedType.isSuspendFunctionType) return
if (!checkExpectedTypeForArgument(lambdaExpectedType)) return
val lambdaReceiverType = lambdaExpectedType.getReceiverTypeFromFunctionType() ?: return
val inferenceData = CoroutineInferenceData()
@@ -172,6 +198,13 @@ class CoroutineInferenceSupport(
inferenceData.reportInferenceResult(csBuilder)
}
private fun checkExpectedTypeForArgument(expectedType: KotlinType): Boolean {
return if (languageVersionSettings.supportsFeature(LanguageFeature.ExperimentalBuilderInference))
expectedType.isFunctionOrSuspendFunctionType
else
expectedType.isSuspendFunctionType
}
fun checkCoroutineCalls(
context: BasicCallResolutionContext,
tracingStrategy: TracingStrategy,
@@ -186,45 +219,69 @@ class CoroutineInferenceSupport(
callCompleter.completeCall(context, overloadResults, tracingStrategy)
if (!resultingCall.isReallySuccess()) return
if (isBadCall(resultingCall.resultingDescriptor)) {
val resultingDescriptor = resultingCall.resultingDescriptor
if (!isGoodCall(resultingDescriptor)) {
inferenceData.badCallHappened()
}
forceInferenceForArguments(context) { valueArgument: ValueArgument, kotlinType: KotlinType ->
val argumentMatch = resultingCall.getArgumentMapping(valueArgument) as? ArgumentMatch
?: return@forceInferenceForArguments
val argumentMatch = resultingCall.getArgumentMapping(valueArgument) as? ArgumentMatch ?: return@forceInferenceForArguments
with(NewKotlinTypeChecker) {
val parameterType = getEffectiveExpectedType(argumentMatch.valueParameter, valueArgument, context)
CoroutineTypeCheckerContext().isSubtypeOf(kotlinType.unwrap(), parameterType.unwrap())
CoroutineTypeCheckerContext(allowOnlyTrivialConstraints = false).isSubtypeOf(kotlinType.unwrap(), parameterType.unwrap())
}
}
val extensionReceiver = resultingCall.resultingDescriptor.extensionReceiverParameter ?: return
val extensionReceiver = resultingDescriptor.extensionReceiverParameter ?: return
val allowOnlyTrivialConstraintsForReceiver =
if (languageVersionSettings.supportsFeature(LanguageFeature.ExperimentalBuilderInference))
!resultingDescriptor.hasBuilderInferenceAnnotation()
else
false
resultingCall.extensionReceiver?.let { actualReceiver ->
with(NewKotlinTypeChecker) {
CoroutineTypeCheckerContext().isSubtypeOf(actualReceiver.type.unwrap(), extensionReceiver.value.type.unwrap())
CoroutineTypeCheckerContext(allowOnlyTrivialConstraints = allowOnlyTrivialConstraintsForReceiver).isSubtypeOf(
actualReceiver.type.unwrap(), extensionReceiver.value.type.unwrap()
)
}
}
}
private fun isBadCall(resultingDescriptor: CallableDescriptor): Boolean {
fun KotlinType.containsTypeTemplate() = contains { it is TypeTemplate }
private fun KotlinType.containsTypeTemplate() = contains { it is TypeTemplate }
val returnType = resultingDescriptor.returnType ?: return true
if (returnType.containsTypeTemplate()) return true
if (resultingDescriptor !is FunctionDescriptor || resultingDescriptor.isSuspend) return false
for (valueParameter in resultingDescriptor.valueParameters) {
if (valueParameter.type.containsTypeTemplate()) return true
private fun isGoodCall(resultingDescriptor: CallableDescriptor): Boolean {
if (!languageVersionSettings.supportsFeature(LanguageFeature.ExperimentalBuilderInference)) {
return isGoodCallForOldCoroutines(resultingDescriptor)
}
return false
if (resultingDescriptor.isExtension && !resultingDescriptor.hasBuilderInferenceAnnotation()) {
return resultingDescriptor.extensionReceiverParameter?.type?.containsTypeTemplate() == false
}
val returnType = resultingDescriptor.returnType ?: return false
return !returnType.containsTypeTemplate()
}
private class CoroutineTypeCheckerContext : TypeCheckerContext(errorTypeEqualsToAnything = true) {
private fun isGoodCallForOldCoroutines(resultingDescriptor: CallableDescriptor): Boolean {
val returnType = resultingDescriptor.returnType ?: return false
if (returnType.containsTypeTemplate()) return false
if (resultingDescriptor !is FunctionDescriptor || resultingDescriptor.isSuspend) return true
if (resultingDescriptor.valueParameters.any { it.type.containsTypeTemplate() }) return false
return true
}
private class CoroutineTypeCheckerContext(
private val allowOnlyTrivialConstraints: Boolean
) : TypeCheckerContext(errorTypeEqualsToAnything = true) {
override fun addSubtypeConstraint(subType: UnwrappedType, superType: UnwrappedType): Boolean? {
(subType as? TypeTemplate ?: superType as? TypeTemplate)?.coroutineInferenceData?.addConstraint(subType, superType)
val typeTemplate = subType as? TypeTemplate ?: superType as? TypeTemplate
typeTemplate?.coroutineInferenceData?.addConstraint(subType, superType, allowOnlyTrivialConstraints)
return null
}
}
@@ -260,11 +317,20 @@ class CoroutineInferenceSupport(
}
}
fun isCoroutineCallWithAdditionalInference(parameterDescriptor: ValueParameterDescriptor, argument: ValueArgument) =
parameterDescriptor.hasSuspendFunctionType &&
fun isCoroutineCallWithAdditionalInference(
parameterDescriptor: ValueParameterDescriptor,
argument: ValueArgument,
languageVersionSettings: LanguageVersionSettings
): Boolean {
val parameterHasOptIn = if (languageVersionSettings.supportsFeature(LanguageFeature.ExperimentalBuilderInference))
parameterDescriptor.hasBuilderInferenceAnnotation() && parameterDescriptor.hasFunctionOrSuspendFunctionType
else
parameterDescriptor.hasSuspendFunctionType
return parameterHasOptIn &&
argument.getArgumentExpression() is KtLambdaExpression &&
parameterDescriptor.type.let { it.isBuiltinFunctionalType && it.getReceiverTypeFromFunctionType() != null }
}
fun OverloadResolutionResultsImpl<*>.isResultWithCoroutineInference() = getCoroutineInferenceData() != null

View File

@@ -86,7 +86,7 @@ internal fun VariableDescriptor.variableKind(
}
private fun hasNoWritersInClosures(
fun hasNoWritersInClosures(
variableContainingDeclaration: DeclarationDescriptor,
writers: Set<AssignedVariablesSearcher.Writer>,
bindingContext: BindingContext

View File

@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.resolve.calls.tower
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.builtins.getReceiverTypeFromFunctionType
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
@@ -37,7 +38,8 @@ import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class KotlinResolutionStatelessCallbacksImpl(
private val deprecationResolver: DeprecationResolver
private val deprecationResolver: DeprecationResolver,
private val languageVersionSettings: LanguageVersionSettings
) : KotlinResolutionStatelessCallbacks {
override fun isDescriptorFromSource(descriptor: CallableDescriptor) =
DescriptorToSourceUtils.descriptorToDeclaration(descriptor) != null
@@ -72,5 +74,5 @@ class KotlinResolutionStatelessCallbacksImpl(
functionCall.safeAs<PSIKotlinCallForInvoke>()?.variableCall
override fun isCoroutineCall(argument: KotlinCallArgument, parameter: ValueParameterDescriptor): Boolean =
isCoroutineCallWithAdditionalInference(parameter, argument.psiCallArgument.valueArgument)
isCoroutineCallWithAdditionalInference(parameter, argument.psiCallArgument.valueArgument, languageVersionSettings)
}

View File

@@ -28,6 +28,7 @@ import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getTopmostParentQualifiedExpressionForSelector
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.calls.checkers.CallChecker
@@ -259,9 +260,6 @@ class ExperimentalUsageChecker(project: Project) : CallChecker {
}
}
val experimentalities = targetDescriptor.loadExperimentalities(moduleAnnotationsResolver, context.languageVersionSettings)
reportNotAcceptedExperimentalities(experimentalities, element, context)
val targetClass = when (targetDescriptor) {
is ClassDescriptor -> targetDescriptor
is TypeAliasDescriptor -> targetDescriptor.classDescriptor
@@ -276,6 +274,11 @@ class ExperimentalUsageChecker(project: Project) : CallChecker {
)
}
}
if (element.getParentOfType<KtImportDirective>(false) == null) {
val experimentalities = targetDescriptor.loadExperimentalities(moduleAnnotationsResolver, context.languageVersionSettings)
reportNotAcceptedExperimentalities(experimentalities, element, context)
}
}
private fun checkUsageOfKotlinExperimentalOrUseExperimental(element: PsiElement, context: CheckerContext) {

View File

@@ -322,6 +322,11 @@ class DeprecationResolver(
return emptyList()
}
// This is a temporary workaround before @DeprecatedSinceKotlin is introduced, see KT-23575
if (shouldSkipDeprecationOnKotlinIoReadBytes(this, languageVersionSettings)) {
return emptyList()
}
val result = SmartList<Deprecation>()
fun addDeprecationIfPresent(target: DeclarationDescriptor) {
@@ -365,6 +370,15 @@ class DeprecationResolver(
return result.distinct()
}
private fun shouldSkipDeprecationOnKotlinIoReadBytes(
descriptor: DeclarationDescriptor, languageVersionSettings: LanguageVersionSettings
): Boolean =
descriptor.name.asString() == "readBytes" &&
(descriptor.containingDeclaration as? PackageFragmentDescriptor)?.fqName?.asString() == "kotlin.io" &&
descriptor is FunctionDescriptor &&
descriptor.valueParameters.singleOrNull()?.type?.let(KotlinBuiltIns::isInt) == true &&
languageVersionSettings.apiVersion < ApiVersion.KOTLIN_1_3
private fun getDeprecationByCoroutinesVersion(target: DeclarationDescriptor): DeprecatedExperimentalCoroutine? {
if (target !is DeserializedMemberDescriptor) return null

View File

@@ -28,6 +28,7 @@ import org.jetbrains.kotlin.resolve.calls.inference.CallHandle;
import org.jetbrains.kotlin.resolve.calls.inference.ConstraintSystem;
import org.jetbrains.kotlin.resolve.calls.inference.ConstraintSystemBuilderImpl;
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker;
import org.jetbrains.kotlin.types.typeUtil.TypeUtilsKt;
import java.util.*;
@@ -40,6 +41,11 @@ public class TypeIntersector {
return intersectTypes(new LinkedHashSet<>(Arrays.asList(typeA, typeB))) == null;
}
public static boolean isIncompatibleEnums(@NotNull KotlinType typeA, @NotNull KotlinType typeB) {
if (!TypeUtilsKt.isEnum(typeA) || !TypeUtilsKt.isEnum(typeB)) return false;
return !typeA.getConstructor().equals(typeB.getConstructor());
}
@Nullable
public static KotlinType intersectTypes(@NotNull Collection<KotlinType> types) {
assert !types.isEmpty() : "Attempting to intersect empty collection of types, this case should be dealt with on the call site.";

View File

@@ -1429,6 +1429,10 @@ public class BasicExpressionTypingVisitor extends ExpressionTypingVisitor {
if (TypeIntersector.isIntersectionEmpty(leftType, rightType)) {
context.trace.report(EQUALITY_NOT_APPLICABLE.on(expression, expression.getOperationReference(), leftType, rightType));
}
else if (TypeIntersector.isIncompatibleEnums(leftType, rightType)) {
context.trace.report(INCOMPATIBLE_ENUM_COMPARISON.on(expression, leftType, rightType));
}
SenselessComparisonChecker.checkSenselessComparisonWithNull(
expression, left, right, context,
expr -> facade.getTypeInfo(expr, context).getType(),

View File

@@ -53,7 +53,6 @@ import org.jetbrains.kotlin.types.typeUtil.makeNullable
import org.jetbrains.kotlin.utils.yieldIfNotNull
import java.util.*
import javax.inject.Inject
import kotlin.coroutines.experimental.buildSequence
sealed class DoubleColonLHS(val type: KotlinType) {
/**
@@ -715,13 +714,13 @@ class DoubleColonExpressionResolver(
?.apply { commitTrace() }?.results
}
val resultSequence = buildSequence {
val resultSequence = sequence {
when (lhs) {
is DoubleColonLHS.Type -> {
val classifier = lhsType.constructor.declarationDescriptor
if (classifier !is ClassDescriptor) {
c.trace.report(CALLABLE_REFERENCE_LHS_NOT_A_CLASS.on(expression))
return@buildSequence
return@sequence
}
val qualifier = c.trace.get(BindingContext.QUALIFIER, expression.receiverExpression!!)

View File

@@ -410,7 +410,13 @@ class PatternMatchingTypingVisitor internal constructor(facade: ExpressionTyping
possibleTypesForSubject: Set<KotlinType>
) {
val subjectExpression = expression.subjectExpression ?: return
for (possibleCastType in possibleTypesForSubject) {
// Using "reversed()" here is a kind of hack to fix KT-27221
// KT-27221 was a breaking change introduced after DataFlowImpl optimization that changed the order of possible types to reversed,
// and it led to the wrong sealed class being chosen.
// But it seems that order of collected types shouldn't matter at all
// (at least because the order of relevant checks might change the behavior, see KT-27252)
// TODO: Read the comment above, wait for resolution in KT-27252 and get rid of "reversed" call here
for (possibleCastType in possibleTypesForSubject.reversed()) {
val possibleCastClass = possibleCastType.constructor.declarationDescriptor as? ClassDescriptor ?: continue
if (possibleCastClass.kind == ClassKind.ENUM_CLASS || possibleCastClass.modality == Modality.SEALED) {
if (checkSmartCastToExpectedTypeInSubject(
@@ -678,6 +684,10 @@ class PatternMatchingTypingVisitor internal constructor(facade: ExpressionTyping
return
}
if (TypeIntersector.isIncompatibleEnums(type, subjectType)) {
context.trace.report(INCOMPATIBLE_ENUM_COMPARISON.on(reportErrorOn, subjectType, type))
}
// check if the pattern is essentially a 'null' expression
if (KotlinBuiltIns.isNullableNothing(type) && !TypeUtils.isNullableType(subjectType)) {
context.trace.report(SENSELESS_NULL_IN_WHEN.on(reportErrorOn))

View File

@@ -10,7 +10,8 @@ import java.io.File
class DirtyFilesContainer(
private val caches: IncrementalCachesManager<*>,
private val reporter: ICReporter
private val reporter: ICReporter,
private val sourceFilesExtensions: List<String>
) {
private val myDirtyFiles = HashSet<File>()
@@ -18,7 +19,7 @@ class DirtyFilesContainer(
ArrayList(myDirtyFiles)
fun add(files: Iterable<File>) {
val existingKotlinFiles = files.filter { it.isKotlinFile() }
val existingKotlinFiles = files.filter { it.isKotlinFile(sourceFilesExtensions) }
if (existingKotlinFiles.isNotEmpty()) {
myDirtyFiles.addAll(existingKotlinFiles)
}

View File

@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.incremental
import org.jetbrains.kotlin.build.DEFAULT_KOTLIN_SOURCE_FILES_EXTENSIONS
import org.jetbrains.kotlin.build.GeneratedFile
import org.jetbrains.kotlin.cli.common.ExitCode
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
@@ -50,6 +51,7 @@ abstract class IncrementalCompilerRunner<
protected val cacheDirectory = File(workingDir, cacheDirName)
protected val dirtySourcesSinceLastTimeFile = File(workingDir, DIRTY_SOURCES_FILE_NAME)
protected val lastBuildInfoFile = File(workingDir, LAST_BUILD_INFO_FILE_NAME)
protected open val kotlinSourceFilesExtensions: List<String> = DEFAULT_KOTLIN_SOURCE_FILES_EXTENSIONS
protected abstract fun isICEnabled(): Boolean
protected abstract fun createCacheManager(args: Args): CacheManager
@@ -85,7 +87,7 @@ abstract class IncrementalCompilerRunner<
if (providedChangedFiles == null) {
caches.inputsCache.sourceSnapshotMap.compareAndUpdate(allSourceFiles)
}
val allKotlinFiles = allSourceFiles.filter { it.isKotlinFile() }
val allKotlinFiles = allSourceFiles.filter { it.isKotlinFile(kotlinSourceFilesExtensions) }
return compileIncrementally(args, caches, allKotlinFiles, CompilationMode.Rebuild(), messageCollector)
}
@@ -281,8 +283,8 @@ abstract class IncrementalCompilerRunner<
changedFiles: ChangedFiles.Known
): DirtyData {
val removedClasses = HashSet<String>()
val dirtyFiles = changedFiles.modified.filterTo(HashSet()) { it.isKotlinFile() }
val removedFiles = changedFiles.removed.filterTo(HashSet()) { it.isKotlinFile() }
val dirtyFiles = changedFiles.modified.filterTo(HashSet()) { it.isKotlinFile(kotlinSourceFilesExtensions) }
val removedFiles = changedFiles.removed.filterTo(HashSet()) { it.isKotlinFile(kotlinSourceFilesExtensions) }
val existingClasses = classesFqNames(dirtyFiles)
val previousClasses = caches.platformCache

View File

@@ -90,7 +90,7 @@ class IncrementalJsCompilerRunner(
val lastBuildInfo = BuildInfo.read(lastBuildInfoFile)
?: return CompilationMode.Rebuild { "No information on previous build" }
val dirtyFiles = DirtyFilesContainer(caches, reporter)
val dirtyFiles = DirtyFilesContainer(caches, reporter, kotlinSourceFilesExtensions)
initDirtyFiles(dirtyFiles, changedFiles)
val libs = (args.libraries ?: "").split(File.pathSeparator).map { File(it) }

View File

@@ -22,6 +22,7 @@ import com.intellij.psi.PsiClass
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiFileFactory
import com.intellij.psi.PsiJavaFile
import org.jetbrains.kotlin.build.DEFAULT_KOTLIN_SOURCE_FILES_EXTENSIONS
import org.jetbrains.kotlin.build.GeneratedFile
import org.jetbrains.kotlin.build.GeneratedJvmClass
import org.jetbrains.kotlin.build.JvmSourceRoot
@@ -40,7 +41,6 @@ import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.incremental.multiproject.EmptyModulesApiHistory
import org.jetbrains.kotlin.incremental.multiproject.ModulesApiHistory
import org.jetbrains.kotlin.incremental.storage.version.CacheVersionManager
import org.jetbrains.kotlin.incremental.util.Either
import org.jetbrains.kotlin.load.java.JavaClassesTracker
import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader
import org.jetbrains.kotlin.load.kotlin.incremental.components.IncrementalCompilationComponents
@@ -57,8 +57,8 @@ fun makeIncrementally(
messageCollector: MessageCollector = MessageCollector.NONE,
reporter: ICReporter = EmptyICReporter
) {
val kotlinExtensions = listOf("kt", "kts")
val allExtensions = kotlinExtensions + listOf("java")
val kotlinExtensions = DEFAULT_KOTLIN_SOURCE_FILES_EXTENSIONS
val allExtensions = kotlinExtensions + "java"
val rootsWalk = sourceRoots.asSequence().flatMap { it.walk() }
val files = rootsWalk.filter(File::isFile)
val sourceFiles = files.filter { it.extension.toLowerCase() in allExtensions }.toList()
@@ -75,7 +75,8 @@ fun makeIncrementally(
usePreciseJavaTracking = true,
localStateDirs = emptyList(),
buildHistoryFile = buildHistoryFile,
modulesApiHistory = EmptyModulesApiHistory
modulesApiHistory = EmptyModulesApiHistory,
kotlinSourceFilesExtensions = kotlinExtensions
)
compiler.compile(sourceFiles, args, messageCollector, providedChangedFiles = null)
}
@@ -104,9 +105,10 @@ class IncrementalJvmCompilerRunner(
cachesVersionManagers: List<CacheVersionManager>,
reporter: ICReporter,
private val usePreciseJavaTracking: Boolean,
buildHistoryFile: File,
buildHistoryFile: File,
localStateDirs: Collection<File>,
private val modulesApiHistory: ModulesApiHistory
private val modulesApiHistory: ModulesApiHistory,
override val kotlinSourceFilesExtensions: List<String> = DEFAULT_KOTLIN_SOURCE_FILES_EXTENSIONS
) : IncrementalCompilerRunner<K2JVMCompilerArguments, IncrementalJvmCachesManager>(
workingDir,
"caches-jvm",
@@ -145,7 +147,7 @@ class IncrementalJvmCompilerRunner(
changedFiles: ChangedFiles.Known,
args: K2JVMCompilerArguments
): CompilationMode {
val dirtyFiles = DirtyFilesContainer(caches, reporter)
val dirtyFiles = DirtyFilesContainer(caches, reporter, kotlinSourceFilesExtensions)
initDirtyFiles(dirtyFiles, changedFiles)
val lastBuildInfo = BuildInfo.read(lastBuildInfoFile) ?: return CompilationMode.Rebuild { "No information on previous build" }

View File

@@ -291,6 +291,11 @@ public class IncrementalJsCompilerRunnerTestGenerated extends AbstractIncrementa
runTest("jps-plugin/testData/incremental/pureKotlin/inlinePropertyOnTopLevel/");
}
@TestMetadata("inlineSuspendFunctionChanged")
public void testInlineSuspendFunctionChanged() throws Exception {
runTest("jps-plugin/testData/incremental/pureKotlin/inlineSuspendFunctionChanged/");
}
@TestMetadata("inlineTwoFunctionsOneChanged")
public void testInlineTwoFunctionsOneChanged() throws Exception {
runTest("jps-plugin/testData/incremental/pureKotlin/inlineTwoFunctionsOneChanged/");

View File

@@ -291,6 +291,11 @@ public class IncrementalJvmCompilerRunnerTestGenerated extends AbstractIncrement
runTest("jps-plugin/testData/incremental/pureKotlin/inlinePropertyOnTopLevel/");
}
@TestMetadata("inlineSuspendFunctionChanged")
public void testInlineSuspendFunctionChanged() throws Exception {
runTest("jps-plugin/testData/incremental/pureKotlin/inlineSuspendFunctionChanged/");
}
@TestMetadata("inlineTwoFunctionsOneChanged")
public void testInlineTwoFunctionsOneChanged() throws Exception {
runTest("jps-plugin/testData/incremental/pureKotlin/inlineTwoFunctionsOneChanged/");

View File

@@ -28,7 +28,7 @@ import com.intellij.psi.impl.java.stubs.PsiJavaFileStub
import com.intellij.psi.impl.java.stubs.impl.PsiJavaFileStubImpl
import com.intellij.psi.impl.source.tree.TreeElement
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.BindingContext
@@ -54,7 +54,13 @@ fun buildLightClass(
context.module,
context.bindingContext,
files.toList(),
CompilerConfiguration.EMPTY
context.languageVersionSettings?.let {
CompilerConfiguration().apply {
languageVersionSettings = it
isReadOnly = true
}
} ?: CompilerConfiguration.EMPTY
).generateDeclaredClassFilter(generateClassFilter).wantsDiagnostics(false).build()
state.beforeCompile()

View File

@@ -30,7 +30,7 @@ import com.intellij.psi.impl.java.stubs.PsiJavaFileStub
import com.intellij.psi.impl.java.stubs.impl.PsiJavaFileStubImpl
import com.intellij.psi.impl.source.tree.TreeElement
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.BindingContext
@@ -56,7 +56,12 @@ fun buildLightClass(
context.module,
context.bindingContext,
files.toList(),
CompilerConfiguration.EMPTY
context.languageVersionSettings?.let {
CompilerConfiguration().apply {
languageVersionSettings = it
isReadOnly = true
}
} ?: CompilerConfiguration.EMPTY
).generateDeclaredClassFilter(generateClassFilter).wantsDiagnostics(false).build()
state.beforeCompile()

View File

@@ -16,10 +16,12 @@
package org.jetbrains.kotlin.asJava.builder
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.resolve.BindingContext
open class LightClassConstructionContext(
val bindingContext: BindingContext,
val module: ModuleDescriptor
val module: ModuleDescriptor,
val languageVersionSettings: LanguageVersionSettings? = null
)

View File

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

View File

@@ -6,3 +6,5 @@
package test
val foo = 42
typealias A = String

View File

@@ -13,7 +13,9 @@ where advanced options include:
-Xbuild-file=<path> Path to the .xml build file to compile
-Xcompile-java Reuse javac analysis and compile Java source files
-Xnormalize-constructor-calls={disable|enable}
Normalize constructor calls (disable: don't normalize; enable: normalize), default is disable
Normalize constructor calls (disable: don't normalize; enable: normalize),
default is 'disable' in language version 1.2 and below,
'enable' since language version 1.3
-Xdump-declarations-to=<path> Path to JSON file to dump Java to Kotlin declaration mappings
-Xdisable-default-scripting-plugin
Do not enable scripting plugin by default

View File

@@ -0,0 +1,3 @@
$TESTDATA_DIR$/suspensionPointInMonitor.kt
-d
$TEMP_DIR$

View File

@@ -0,0 +1,68 @@
fun builder(c: suspend () -> Unit) {}
private val lock = Any()
suspend fun suspensionPoint() {}
private inline fun inlineMe(c: () -> Unit) {
synchronized(lock) {
c()
}
}
private inline fun monitorInFinally(a: () -> Unit, b: () -> Unit) {
try {
a()
} finally {
synchronized(lock) {
b()
}
}
}
fun test() {
builder {
synchronized(lock) {
suspensionPoint()
}
}
builder {
inlineMe {
suspensionPoint()
}
}
builder {
monitorInFinally(
{},
{ suspensionPoint() }
)
}
synchronized(lock) {
builder {
suspensionPoint()
}
}
synchronized(lock) {
object : SuspendRunnable {
override suspend fun run() {
suspensionPoint()
}
}
}
object : SuspendRunnable {
override suspend fun run() {
synchronized(lock) {
suspensionPoint()
}
}
}
}
interface SuspendRunnable {
suspend fun run()
}

View File

@@ -0,0 +1,7 @@
compiler/testData/cli/jvm/suspensionPointInMonitor.kt:26:13: error: the 'suspensionPoint' suspension point is inside a synchronized block
suspensionPoint()
^
compiler/testData/cli/jvm/suspensionPointInMonitor.kt:60:17: error: the 'suspensionPoint' suspension point is inside a synchronized block
suspensionPoint()
^
COMPILATION_ERROR

View File

@@ -25,7 +25,7 @@ fun box(): String {
result = ""
invokeOrder = ""
result = inlineFun(constraints = { invokeOrder += "constraints";A("C") }(),
result = inlineFun(constraints = *arrayOf({ invokeOrder += "constraints";A("C") }()),
receiver = { invokeOrder += " receiver"; "R" }(),
init = { invokeOrder += " init"; "I" }())
if (result != "C, R, I") return "fail 1: $result"
@@ -35,7 +35,7 @@ fun box(): String {
result = ""
invokeOrder = ""
result = inlineFun(init = { invokeOrder += "init"; "I" }(),
constraints = { invokeOrder += "constraints";A("C") }(),
constraints = *arrayOf({ invokeOrder += "constraints";A("C") }()),
receiver = { invokeOrder += " receiver"; "R" }()
)
if (result != "C, R, I") return "fail 3: $result"
@@ -45,7 +45,7 @@ fun box(): String {
result = ""
invokeOrder = ""
result = inlineFun(init = { invokeOrder += "init"; "I" }(),
constraints = { invokeOrder += " constraints";A("C") }())
constraints = *arrayOf({ invokeOrder += " constraints";A("C") }()))
if (result != "C, DEFAULT, I") return "fail 5: $result"
if (invokeOrder != "init constraints default receiver") return "fail 6: $invokeOrder"

View File

@@ -1,10 +1,11 @@
// IGNORE_BACKEND: JVM_IR
// !LANGUAGE: -ReleaseCoroutines -ExperimentalBuilderInference
// IGNORE_BACKEND: JVM_IR, JS_IR
// WITH_RUNTIME
// WITH_COROUTINES
// COMMON_COROUTINES_TEST
import helpers.*
import COROUTINES_PACKAGE.*
import COROUTINES_PACKAGE.intrinsics.*
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
interface AsyncGenerator<in T> {
suspend fun yield(value: T)

View File

@@ -0,0 +1,141 @@
// !LANGUAGE: +ReleaseCoroutines +ExperimentalBuilderInference
// IGNORE_BACKEND: JVM_IR
// WITH_RUNTIME
// WITH_COROUTINES
import helpers.*
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*
import kotlin.experimental.ExperimentalTypeInference
interface AsyncGenerator<in T> {
suspend fun yield(value: T)
}
interface AsyncSequence<out T> {
operator fun iterator(): AsyncIterator<T>
}
interface AsyncIterator<out T> {
operator suspend fun hasNext(): Boolean
operator suspend fun next(): T
}
@UseExperimental(ExperimentalTypeInference::class)
fun <T> asyncGenerate(@BuilderInference block: suspend AsyncGenerator<T>.() -> Unit): AsyncSequence<T> = object : AsyncSequence<T> {
override fun iterator(): AsyncIterator<T> {
val iterator = AsyncGeneratorIterator<T>()
iterator.nextStep = block.createCoroutine(receiver = iterator, completion = iterator)
return iterator
}
}
class AsyncGeneratorIterator<T>: AsyncIterator<T>, AsyncGenerator<T>, ContinuationAdapter<Unit>() {
var computedNext = false
var nextValue: T? = null
var nextStep: Continuation<Unit>? = null
// if (computesNext) computeContinuation is Continuation<T>
// if (!computesNext) computeContinuation is Continuation<Boolean>
var computesNext = false
var computeContinuation: Continuation<*>? = null
override val context = EmptyCoroutineContext
suspend fun computeHasNext(): Boolean = suspendCoroutineUninterceptedOrReturn { c ->
computesNext = false
computeContinuation = c
nextStep!!.resume(Unit)
COROUTINE_SUSPENDED
}
suspend fun computeNext(): T = suspendCoroutineUninterceptedOrReturn { c ->
computesNext = true
computeContinuation = c
nextStep!!.resume(Unit)
COROUTINE_SUSPENDED
}
@Suppress("UNCHECKED_CAST")
fun resumeIterator(exception: Throwable?) {
if (exception != null) {
done()
computeContinuation!!.resumeWithException(exception)
return
}
if (computesNext) {
computedNext = false
(computeContinuation as Continuation<T>).resume(nextValue as T)
} else {
(computeContinuation as Continuation<Boolean>).resume(nextStep != null)
}
}
override suspend fun hasNext(): Boolean {
if (!computedNext) return computeHasNext()
return nextStep != null
}
override suspend fun next(): T {
if (!computedNext) return computeNext()
computedNext = false
return nextValue as T
}
private fun done() {
computedNext = true
nextStep = null
}
// Completion continuation implementation
override fun resume(value: Unit) {
done()
resumeIterator(null)
}
override fun resumeWithException(exception: Throwable) {
done()
resumeIterator(exception)
}
// Generator implementation
override suspend fun yield(value: T): Unit = suspendCoroutineUninterceptedOrReturn { c ->
computedNext = true
nextValue = value
nextStep = c
resumeIterator(null)
COROUTINE_SUSPENDED
}
}
fun builder(c: suspend () -> Unit) {
c.startCoroutine(EmptyContinuation)
}
fun cst(a: Any?): String? = a as String?
fun any(a: Any?): Any? = a
fun box(): String {
val seq = asyncGenerate {
yield("O")
yield("K")
}
var res = ""
builder {
// type of `prev` should be j/l/Object everywhere (even in a expected type position)
var prev: Any? = null
for (i in seq) {
res += i
prev = any(res)
// merge of NULL_VALUE and j/l/Object should result in common j/l/Object value
// but it was NULL_VALUE and we do not spill null values, we just put
// ACONST_NULL after suspension point instead
}
res = cst(prev) ?: "fail 1"
}
return res
}

View File

@@ -1,11 +1,11 @@
// IGNORE_BACKEND: JS_IR
// IGNORE_BACKEND: JVM_IR
// !LANGUAGE: -ReleaseCoroutines -ExperimentalBuilderInference
// IGNORE_BACKEND: JVM_IR, JS_IR
// WITH_RUNTIME
// WITH_COROUTINES
// COMMON_COROUTINES_TEST
import helpers.*
import COROUTINES_PACKAGE.*
import COROUTINES_PACKAGE.intrinsics.*
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
interface AsyncGenerator<in T> {
suspend fun yield(value: T)

View File

@@ -0,0 +1,136 @@
// !LANGUAGE: +ReleaseCoroutines +ExperimentalBuilderInference
// IGNORE_BACKEND: JVM_IR
// WITH_RUNTIME
// WITH_COROUTINES
import helpers.*
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*
import kotlin.experimental.ExperimentalTypeInference
interface AsyncGenerator<in T> {
suspend fun yield(value: T)
}
interface AsyncSequence<out T> {
operator fun iterator(): AsyncIterator<T>
}
interface AsyncIterator<out T> {
operator suspend fun hasNext(): Boolean
operator suspend fun next(): T
}
@UseExperimental(ExperimentalTypeInference::class)
fun <T> asyncGenerate(@BuilderInference block: suspend AsyncGenerator<T>.() -> Unit): AsyncSequence<T> = object : AsyncSequence<T> {
override fun iterator(): AsyncIterator<T> {
val iterator = AsyncGeneratorIterator<T>()
iterator.nextStep = block.createCoroutine(receiver = iterator, completion = iterator)
return iterator
}
}
class AsyncGeneratorIterator<T>: AsyncIterator<T>, AsyncGenerator<T>, ContinuationAdapter<Unit>() {
var computedNext = false
var nextValue: T? = null
var nextStep: Continuation<Unit>? = null
// if (computesNext) computeContinuation is Continuation<T>
// if (!computesNext) computeContinuation is Continuation<Boolean>
var computesNext = false
var computeContinuation: Continuation<*>? = null
override val context = EmptyCoroutineContext
suspend fun computeHasNext(): Boolean = suspendCoroutineUninterceptedOrReturn { c ->
computesNext = false
computeContinuation = c
nextStep!!.resume(Unit)
COROUTINE_SUSPENDED
}
suspend fun computeNext(): T = suspendCoroutineUninterceptedOrReturn { c ->
computesNext = true
computeContinuation = c
nextStep!!.resume(Unit)
COROUTINE_SUSPENDED
}
@Suppress("UNCHECKED_CAST")
fun resumeIterator(exception: Throwable?) {
if (exception != null) {
done()
computeContinuation!!.resumeWithException(exception)
return
}
if (computesNext) {
computedNext = false
(computeContinuation as Continuation<T>).resume(nextValue as T)
} else {
(computeContinuation as Continuation<Boolean>).resume(nextStep != null)
}
}
override suspend fun hasNext(): Boolean {
if (!computedNext) return computeHasNext()
return nextStep != null
}
override suspend fun next(): T {
if (!computedNext) return computeNext()
computedNext = false
return nextValue as T
}
private fun done() {
computedNext = true
nextStep = null
}
// Completion continuation implementation
override fun resume(value: Unit) {
done()
resumeIterator(null)
}
override fun resumeWithException(exception: Throwable) {
done()
resumeIterator(exception)
}
// Generator implementation
override suspend fun yield(value: T): Unit = suspendCoroutineUninterceptedOrReturn { c ->
computedNext = true
nextValue = value
nextStep = c
resumeIterator(null)
COROUTINE_SUSPENDED
}
}
suspend fun <T> AsyncSequence<T>.toList(): List<T> {
val out = arrayListOf<T>()
for (e in this@toList) out += e // fails at this line
return out
}
fun builder(c: suspend () -> Unit) {
c.startCoroutine(EmptyContinuation)
}
fun box(): String {
val seq = asyncGenerate {
yield("O")
yield("K")
}
var res = listOf<String>()
builder {
res = seq.toList()
}
if (res.size > 2) return "fail 1: ${res.size}"
return res[0] + res[1]
}

View File

@@ -1,10 +1,11 @@
// IGNORE_BACKEND: JVM_IR
// !LANGUAGE: -ReleaseCoroutines -ExperimentalBuilderInference
// IGNORE_BACKEND: JVM_IR, JS_IR
// WITH_RUNTIME
// WITH_COROUTINES
// COMMON_COROUTINES_TEST
import helpers.*
import COROUTINES_PACKAGE.*
import COROUTINES_PACKAGE.intrinsics.*
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
interface AsyncGenerator<in T> {
suspend fun yield(value: T)

View File

@@ -0,0 +1,130 @@
// !LANGUAGE: +ReleaseCoroutines +ExperimentalBuilderInference
// IGNORE_BACKEND: JVM_IR
// WITH_RUNTIME
// WITH_COROUTINES
import helpers.*
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*
import kotlin.experimental.ExperimentalTypeInference
interface AsyncGenerator<in T> {
suspend fun yield(value: T)
}
interface AsyncSequence<out T> {
operator fun iterator(): AsyncIterator<T>
}
interface AsyncIterator<out T> {
operator suspend fun hasNext(): Boolean
operator suspend fun next(): T
}
@UseExperimental(ExperimentalTypeInference::class)
fun <T> asyncGenerate(@BuilderInference block: suspend AsyncGenerator<T>.() -> Unit): AsyncSequence<T> = object : AsyncSequence<T> {
override fun iterator(): AsyncIterator<T> {
val iterator = AsyncGeneratorIterator<T>()
iterator.nextStep = block.createCoroutine(receiver = iterator, completion = iterator)
return iterator
}
}
class AsyncGeneratorIterator<T>: AsyncIterator<T>, AsyncGenerator<T>, ContinuationAdapter<Unit>() {
var computedNext = false
var nextValue: T? = null
var nextStep: Continuation<Unit>? = null
// if (computesNext) computeContinuation is Continuation<T>
// if (!computesNext) computeContinuation is Continuation<Boolean>
var computesNext = false
var computeContinuation: Continuation<*>? = null
override val context = EmptyCoroutineContext
suspend fun computeHasNext(): Boolean = suspendCoroutineUninterceptedOrReturn { c ->
computesNext = false
computeContinuation = c
nextStep!!.resume(Unit)
COROUTINE_SUSPENDED
}
suspend fun computeNext(): T = suspendCoroutineUninterceptedOrReturn { c ->
computesNext = true
computeContinuation = c
nextStep!!.resume(Unit)
COROUTINE_SUSPENDED
}
@Suppress("UNCHECKED_CAST")
fun resumeIterator(exception: Throwable?) {
if (exception != null) {
done()
computeContinuation!!.resumeWithException(exception)
return
}
if (computesNext) {
computedNext = false
(computeContinuation as Continuation<T>).resume(nextValue as T)
} else {
(computeContinuation as Continuation<Boolean>).resume(nextStep != null)
}
}
override suspend fun hasNext(): Boolean {
if (!computedNext) return computeHasNext()
return nextStep != null
}
override suspend fun next(): T {
if (!computedNext) return computeNext()
computedNext = false
return nextValue as T
}
private fun done() {
computedNext = true
nextStep = null
}
// Completion continuation implementation
override fun resume(value: Unit) {
done()
resumeIterator(null)
}
override fun resumeWithException(exception: Throwable) {
done()
resumeIterator(exception)
}
// Generator implementation
override suspend fun yield(value: T): Unit = suspendCoroutineUninterceptedOrReturn { c ->
computedNext = true
nextValue = value
nextStep = c
resumeIterator(null)
COROUTINE_SUSPENDED
}
}
fun builder(c: suspend () -> Unit) {
c.startCoroutine(EmptyContinuation)
}
fun box(): String {
val seq = asyncGenerate {
yield("O")
yield("K")
}
var res = ""
builder {
for (i in seq) {
res += i
}
}
return res
}

View File

@@ -2,10 +2,9 @@
// IGNORE_BACKEND: JVM_IR
// WITH_RUNTIME
// WITH_COROUTINES
// COMMON_COROUTINES_TEST
// LANGUAGE_VERSION: 1.2
import helpers.*
import COROUTINES_PACKAGE.*
import COROUTINES_PACKAGE.intrinsics.*
import kotlin.coroutines.experimental.*
enum class Foo(vararg expected: String) {
A("start", "A", "end"),

View File

@@ -0,0 +1,48 @@
// IGNORE_BACKEND: JS_IR
// IGNORE_BACKEND: JVM_IR
// WITH_RUNTIME
// WITH_COROUTINES
// LANGUAGE_VERSION: 1.3
import helpers.*
import kotlin.coroutines.*
enum class Foo(vararg expected: String) {
A("start", "A", "end"),
B("start", "BCD", "end"),
C("start", "BCD", "end"),
D("start", "BCD", "end"),
E("start", "E", "end"),
F("start", "end");
val expected = expected.toList()
}
fun box(): String {
for (c in Foo.values()) {
val actual = getSequence(c).toList()
if (actual != c.expected) {
return "FAIL: -- ${c.expected} != $actual"
}
}
return "OK"
}
fun getSequence(a: Foo) =
sequence {
yield("start")
when (a) {
Foo.A -> {
yield("A")
}
Foo.B,
Foo.C,
Foo.D-> {
yield("BCD")
}
Foo.E-> {
yield("E")
}
}
yield("end")
}

View File

@@ -1,5 +1,5 @@
// LANGUAGE_VERSION: 1.3
// IGNORE_BACKEND: JS_IR
// TARGET_BACKEND: JVM
// IGNORE_BACKEND: JVM_IR
// WITH_RUNTIME
// WITH_COROUTINES

View File

@@ -1,3 +1,4 @@
// IGNORE_BACKEND: NATIVE
// IGNORE_BACKEND: JS_IR, JS
// IGNORE_BACKEND: JVM_IR
// WITH_RUNTIME

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