Compare commits

...

345 Commits

Author SHA1 Message Date
Ilya Gorbunov
a3b14561c4 Revert using regex Pattern in String.replace
Use String.indexOf(..., ignoreCase) instead in all branches to preserve
compatibility with behavior before 1.4.20 that used String.split which
essentially relied on that String.indexOf

#KT-43745 Fixed

(cherry picked from commit 149bcc2d22)
2020-12-04 17:57:31 +03:00
Vyacheslav Gerasimov
cb93152fed Build: Set file access rights explicitly in kotlin-stdlib-js jar
Workaround for #KTI-401. Since gradle 6.6 ant.replaceregexp call sets
incorrect access rights `-rw-------` instead of `-rw-r--r--`
2020-12-04 17:08:45 +03:00
Igor Chevdar
4c44045e9d Bumped K/N version 2020-12-02 09:47:48 +05:00
Ilya Goncharov
40abf82dd4 [Gradle, JS] Add filter on file on fileCollectionDependencies because Gradle can't hash directory
^KT-43668 fixed

(cherry picked from commit e7789d2e30)
2020-12-01 11:52:22 +03:00
Andrei Klunnyi
166ce6a2ea KTIJ-585 [Gradle Runner]: main() cannot be launched from AS 4.1
Android gradle-project model differs from what we have for pure Java
and MPP. It's the reason why application classpath cannot be collected
correctly.
Until universal solution is provided delegation to gradle is put under
the registry flag. If disable platform runner is used as before.

(cherry picked from commit 4817d5e01d)
2020-11-30 16:54:48 +01:00
Ilmir Usmanov
5e23440a2a IC & Coroutines: Do not box suspend operator fun invoke receiver
if it is called using parens and not by calling 'invoke' method.

Use underlying type when calling continuation constructor if suspend
function is method inside inline class.

 #KT-43505 Fixed
 #KT-39437 Fixed
2020-11-27 19:32:46 +01:00
Ilmir Usmanov
0b495c1531 IC & Coroutines: Unbox inline class parameter of suspend lambda
inside 'create' if 'create' overrides 'create' from
BaseContinuationImpl. In other words, unbox the parameter if 'create'
accepts only one parameter.

 #KT-43249 Fixed
 #KT-43533 Fixed
2020-11-27 19:32:43 +01:00
Ilmir Usmanov
a48f76d4d9 IC & Coroutines: Unbox inline classes of suspend lambdas
inside 'invoke' if 'create' does not override 'create' from
BaseContinuationImpl. In other words, when suspend lambda accepts more
than one parameter (including receiver).

Do that only if we do not generate bridge 'invoke' method, since
inline classes are unboxed in the bridge.

Use mangled name for 'create' function in this case inside 'invoke'.

 #KT-43249 In progress
 #KT-39847 Fixed
 #KT-38937 Fixed
2020-11-27 19:32:40 +01:00
Ilya Gorbunov
a173e0e631 Fix annotation spelling in docs
KT-43586

(cherry picked from commit 7fd96f5773)
2020-11-26 16:59:54 +03:00
Ilya Gorbunov
02d925a73b Qualify replacement expression with receiver to workaround KT-42874
(cherry picked from commit 4767696840)
2020-11-26 16:59:44 +03:00
Ilya Gorbunov
be704622cb Use NIO Files for creating temp files: idea plugin
(cherry picked from commit dce3e57685)
2020-11-26 16:56:21 +03:00
Ilya Gorbunov
0c5c194c17 Use NIO Files for creating temp files: scripting, daemon, main-kts
(cherry picked from commit 090b562db7)
2020-11-26 16:56:21 +03:00
Ilya Gorbunov
39ca1b45b5 Use NIO Files for creating temp files: build tools
(cherry picked from commit c9bbdf6575)
2020-11-26 16:56:21 +03:00
Dmitriy Dolovov
219c200627 Native: Use NIO Files.createTemp*() in favor of File.createTemp*() extension functions
(cherry picked from commit ee7f3b1bfe)
2020-11-26 16:56:21 +03:00
Ilya Goncharov
fd2fd51b3d [JS IR] webpackConfigAppliers as internal to not break Gradle lambda serialization in some cases
[JS IR] Add synthetic config and webpack config is nested object

^KT-43535 fixed
2020-11-26 11:15:47 +03:00
Andrei Klunnyi
7a55c9dd51 KT-43511 [Gradle Runner]: run task is not created for top level modules
(cherry picked from commit c13650fd79)
2020-11-25 14:59:15 +01:00
Leonid Startsev
3e803a5f18 Directly search in IrClass for declarations to fill bodies with plugin
because some other compiler plugins (Compose) copy/rewrite IR declarations
completely, and in the end, functions that are present in the final IR tree
do not have bodies.

Correctly create IrProperty and IrField when they were absent from the
descriptors (in case for private serializer properties)

Do not use symbol table because 'declare' API is not available in plugins.

Fixes https://github.com/JetBrains/compose-jb/issues/46
2020-11-24 21:48:49 +03:00
Andrei Klunnyi
2a25f07c77 KT-42561 [Gradle Runner]: run task is created for extra modules
Approach to take classpath from 'project.sourceSets' failed because it
was applied to extra modules - those without java like plugins
(extending project model with 'sourceSets').

This commit specifies criterion of gradle-project selection - the one to
create run task for.

^KT-42561 fixed

(cherry picked from commit 05ddbeab0a)
2020-11-24 15:57:44 +01:00
Vyacheslav Gerasimov
e9ce4a22c4 Build: Fix ide plugin maven artifacts publication 2020-11-24 00:31:10 +03:00
Yan Zhulanow
4bceb0d5a1 IDE dependencies: Publish kotlin-coroutines-experimental-compat library
(cherry picked from commit d376585821)
2020-11-23 16:52:11 +03:00
Yan Zhulanow
e30fc4b00c Don't publish kotlin-dist-for-ide in publishIdeArtifacts as it's now published alone
(cherry picked from commit 65d8e5a615)
2020-11-23 16:52:10 +03:00
Nikolay Krasko
45c957becd Make a longer description for Kotlin Android plugin
Try to overcome `Plugin description must not be generic, please
elaborate.` from the Gradle plugin portal.
2020-11-19 17:41:17 +03:00
woainikk
d0c005400b Update changelog for 1.4.20 release 2020-11-19 11:47:29 +03:00
Vladimir Dolzhenko
49a7e00685 Run tests AS42 under JDK 11
Due to built dependency with java9
2020-11-17 15:26:16 +00:00
Vladimir Dolzhenko
0e75999ce1 Clean up non failed tests in AS42 2020-11-17 15:26:15 +00:00
Vladimir Dolzhenko
995df014e3 Don't set KOTLIN_BUNDLED in unit tests in AS42 2020-11-17 15:26:14 +00:00
Stanislav Erokhin
90305141cd Use absolute path to the project in test in AS 4.2
It seems like sometimes by some reason here used relative path, but
also seems like corresponding function prefer absolute path.
Without it tests failing (for example ConfigureKotlinTest)
2020-11-17 15:26:14 +00:00
Yan Zhulanow
8aea0139b0 Fix ClassNotFoundException: org.w3c.dom.ElementTraversal 2020-11-17 15:26:13 +00:00
Stanislav Erokhin
c37d269225 Fix compilation 2020-11-17 15:26:12 +00:00
Stanislav Erokhin
53e74af304 Register DumpUtil if it has not been registered yet in AS42 2020-11-17 15:26:12 +00:00
Stanislav Erokhin
5cc229cfb3 Fix compilation in AS 4.2
Previous method was deprecated, replaced to the new one based on the
implementation of deprecated `openExistingProject`
2020-11-17 15:26:11 +00:00
Konstantin Tskhovrebov
be71a871ae Fix tests for as42.
(cherry picked from commit 0ce6d694b7)
2020-11-17 15:26:11 +00:00
Nikolay Krasko
3d0e7d4d77 Clean .bunch file
No need to pass base branch in the rule

(cherry picked from commit 6d2647c681)
2020-11-17 15:26:10 +00:00
Igor Chevdar
d29d387518 Bumped K/N version 2020-11-17 10:37:24 +05:00
Yan Zhulanow
5e43889164 Parcelize: Fix typo in diagnostic message (KT-43290)
(cherry picked from commit 7b98876475)
2020-11-13 17:43:19 +09:00
Yan Zhulanow
5ad87a15f0 Parcelize: Activate checkers only when the plugin is enabled for module (KT-43291) 2020-11-12 05:40:28 +09:00
Sam Wang
95964be449 Restore KotlinExplicitMovementProvider in as41 and as42
(cherry picked from commit d1ba2f3d46)
2020-11-11 11:55:30 +01:00
Kris
cb2ca2279d Add samples for Random.nextX() functions
(cherry picked from commit 173954b3b3)
2020-11-11 12:55:16 +03:00
Kris
5da0af56ee Add samples for last() and lastOrNull() functions
(cherry picked from commit ebdd023633)
2020-11-11 12:55:15 +03:00
Dominik Wuttke
6d43560f84 Add a link to scope functions overview for takeIf and takeUnless
Co-authored-by: Dominik Wuttke <Dominik.wu@gmx.net>
(cherry picked from commit 3acb468d48)
2020-11-11 12:55:15 +03:00
Uzi Landsmann
af2c46724e Added samples for the kotlin.system package (measureTime* functions)
Co-authored-by: Ilya Gorbunov <ilya.gorbunov@jetbrains.com>
(cherry picked from commit f48f7c6dca)
2020-11-11 12:55:15 +03:00
Uzi Landsmann
4245d2ad4e Added samples for the kotlin.streams package
Co-authored-by: Uzi Landsmann <uzi.landsmann@bisnode.com>
(cherry picked from commit 15381c4662)
2020-11-11 12:55:15 +03:00
Yuya Urano
e97fe906f1 KT-20357: Add a sample for requireNotNull
(cherry picked from commit 18672c99ca)
2020-11-11 12:55:15 +03:00
Derek Bodin
baa11aaf1e Update example for default buildList to not use capacity KT-41136 (#3688)
(cherry picked from commit 96834d6f4c)
2020-11-11 12:55:14 +03:00
Igor Chevdar
b2d3570030 Bumped K/N version 2020-11-11 14:53:31 +05:00
Nikolay Krasko
77500761d0 as41: Fix compile error in :compiler:tests-common:compileTestJava
(cherry picked from commit 646e6446f7)
2020-11-11 10:55:31 +03:00
Ilmir Usmanov
9a7c8f086e Use non-local return target instead of inline site in suspend function
return type coercion.
 #KT-43226 Fixed
2020-11-11 05:49:52 +01:00
Ilya Gorbunov
06a614f3f7 Deprecate createTempFile/createTempDir functions
Document their potential permission problems.
Suppress this deprecation in tests.

(cherry picked from commit 66f5c98505)
2020-11-11 00:35:56 +03:00
Yan Zhulanow
a262dba9e3 Parcelize: Use @Parcelize annotations from Android Extensions instead of the copied&deprecated ones (KT-42342, KT-43150)
Dex can't merge class files from both android-extensions-runtime and parcelize-runtime, so we have to keep only one copy of each class.
Instead of @Deprecated annotations, there are new diagnostics (without quick-fixes yet).
The goal is to allow simple usages (@Parcelize alone) but forbid kotlinx.android.synthetic.Parceler usage.

(cherry picked from commit e83a3c3f27)
2020-11-11 04:41:43 +09:00
Stanislav Erokhin
a6d0af82d7 KT-43202 Fix isEap function: support RC version
Since 1.4.20 we changed rc suffix to RC.
Old variant (rc) kept just in case
#KT-43202 Fixed

(cherry picked from commit f6df624c6b)
2020-11-09 11:11:00 +03:00
Igor Chevdar
e7a07673f8 [IR] Fixed https://youtrack.jetbrains.com/issue/KT-43159 2020-11-09 12:16:09 +05:00
Andrei Klunnyi
796f1fdf21 [KT-40688] Inlay Hints: lambda hints removal on editing
Due to the platform API limitation lambda related hints are treated
separately to all others. Hints removal on editing is not an exclusion
and is now supported as well.

(cherry picked from commit 7859287337)
2020-11-05 11:21:12 +01:00
Victor Petukhov
8c08502e90 Don't report warning about changing execution order for varargs if it's inside an annotation
^KT-43110 Fixed
2020-11-05 13:19:21 +03:00
Victor Petukhov
4cde8c425c Don't report warning about implicitly inferred Nothing for call arguments if there is non-Nothing return type
^KT-43108 Fixed
2020-11-05 13:19:21 +03:00
Andrei Klunnyi
c17c6a28ee Disable "Incomplete destructuring declaration"
^KT-43037 fixed

(cherry picked from commit 55048f40ab)
2020-11-05 11:03:11 +01:00
Anton Yalyshev
bdae207060 Add change-notes for 1.4.20
(cherry picked from commit d4d93b7091)
2020-11-03 14:07:51 +03:00
Mikhael Bogdanov
68a82fdbf6 Don't generate final modifier on static interface methods produced by @JvmStatic+@JvmOverloads from interface companion
#KT-35716 Fixed

(cherry picked from commit 7ec2d036ae)
2020-11-03 11:10:42 +01:00
anastasiia.spaseeva
93a1b34c95 Add changelog for 1.4.20-RC 2020-11-02 12:23:13 +03:00
Jake Wharton
267aab87c0 Update ExperimentalPathApi annotation's SinceKotlin value to 1.4
(cherry picked from commit 3a693e112b)
2020-10-28 18:21:36 +03:00
Roman Golyshev
1dcecec0b7 KT-42274 Update SOURCE_STUB_VERSION
This update should have been done in
4b7d34b537 commit, as it is stated in the
`KtTokens.MODIFIER_KEYWORDS_ARRAY` docs.

Shifting all modifiers by one have led resulted in incorrect modifiers
when stubs were read from the disk. Updating `SOURCE_STUB_VERSION` will
make IDEA recreate all stubs from scratch

(cherry-picked from commit 82984089f0)

^KT-42274 Fixed
2020-10-28 14:57:45 +00:00
Igor Chevdar
c138aef990 Bumped K/N version 2020-10-28 19:32:23 +05:00
Yan Zhulanow
0e1b529f62 Kapt: Never mark static methods 'default' (KT-42915) 2020-10-28 21:04:25 +09:00
Ilya Gorbunov
3ae3694991 Cleanup more test files and directories after tests
#KT-19192

(cherry picked from commit 0fa2cc15de)
2020-10-28 14:42:26 +03:00
Ilya Gorbunov
78058f7713 Revise functions in PathReadWrite
- Adjust implementations to avoid excessive vararg copies
- Remove options from forEachLine, it doesn't make much sense and
isn't consistent with the other read* functions.
- Revise inlineness of functions in PathReadWrite
- Compact implementations of those that are remained inline.
- Clarify docs of functions for reading the entire file

#KT-19192

(cherry picked from commit fe098ec821)
2020-10-28 14:42:25 +03:00
Ilya Gorbunov
7da8ab6e30 Implement additional Path extensions
#KT-19192

(cherry picked from commit a43cc0d1f9)
2020-10-28 14:42:25 +03:00
Ilya Gorbunov
0b2022aa2b Add glob filtering when listing directory entries
#KT-19192

(cherry picked from commit 038f1cbd1e)
2020-10-28 14:42:25 +03:00
Ilya Gorbunov
433be3bc7d Avoid introducing Path.printWriter
#KT-19192

(cherry picked from commit e7c888a2e6)
2020-10-28 14:42:25 +03:00
Ilya Gorbunov
489735e51f Introduce dedicated experimental annotation for Path extensions
#KT-19192

(cherry picked from commit 9f659d74df)
2020-10-28 14:42:25 +03:00
Ilya Gorbunov
b1950b2511 Move Path extensions to the new package kotlin.io.path
This avoids the conflict with the existing top-level functions in
kotlin.io package.

#KT-19192

(cherry picked from commit 997cd35e06)
2020-10-28 14:42:24 +03:00
Ilya Gorbunov
1025e0b1c5 Simplify Path.copyTo implementation
Delegate most checks to the platform Files.copy.
This changes the exception type thrown in one case,
so document when it happens. Also 'copyTo' no longer
creates target parent directory if it doesn't exist.

#KT-19192

(cherry picked from commit 7d58a5e2f2)
2020-10-28 14:42:24 +03:00
Ilya Gorbunov
fea02daedb Workaround bugs in Path.relativize
Also add actual paths to the relativeTo error message.

#KT-19192

(cherry picked from commit f6d2400208)
2020-10-28 14:42:24 +03:00
AJ
c3e73a1e86 Add java.nio.Path extensions to stdlib-jdk7: part 2
- Add notExists
- Rename isFile to isRegularFile
- Remove forEachBlock
- Rename listFiles
- Add relativeTo extensions
- Remove extra overloads
- Update doc comments
- Address review comments

#KT-19192

(cherry picked from commit b3a87356bd)
2020-10-28 14:42:24 +03:00
AJ
1e3e7e91d2 Add java.nio.Path extensions to stdlib-jdk7
This PR adds most extensions on `java.io.File` in `kotlin.io` to `java.nio.Path`. This includes extensions from `FileReadWrite.kt`, `Utils.kt`, and `FileTreeWalk.kt`.

I attempted to keep the implementations, documentation, and tests as similar as possible to the existing implementations.

I am happy to add, remove, or move to separate PRs any of the functions of this PR.

### `File` extensions that were not added to `Path`

##### `createTempDir`, `createTempFile`

These functions have no `File` parameters, so can't be overloaded. Equivalents exist as `Files.createTempFile()` and `Files.createTempDirectory()`.

##### `startsWith`, `endsWith`, `normalize`, `resolve`, `resolveSibling`

These exist as member functions on `Path`

##### `relativeTo`, `relativeToOrNull`, `relativeToOrSelf`, `toRelativeString`, `toRelativeStringOrNull`

This functionality exists as the `Path.relativize` member function, which is equivalent to `relativeTo`, but with the receiver and parameter flipped. `foo.relativeTo(bar)` is equivalent to `bar.relativize(foo)`. We could potentially add a `relativizeOrNull` extension to make that pattern simpler.

##### `isRooted`

`Path` has a `root` method, so `isRooted` is equivalent to `root != null`

### New extensions

All of the simple boolean attribute checks from `java.nio.Files` were added as extensions on `Path`. These extensions are used commonly enough that it seems worth supporting them. This functionality for `File` is implemented as member methods.

The following `Path` extensions were added:

- `exists`
- `isDirectory`
- `isExecutable`
- `isFile`
- `isHidden`
- `isReadable`
- `isSameFile`
- `isSymbolicLink`
- `isWritable`

Some of these extensions take options that are forwarded to their `Files` method, so all of the extensions were implemented as functions rather than properties for consistency.

Additionally, `Path.listFiles` was added to match the `File.listFiles` method. One motivation for its addition was that it's used several times in the implementation of other file extensions. The way to list directory contents with `java.nio` is via `Files.newDirectoryStream()`, which returns an iterable object that must be closed to avoid leaking resources. It's difficult to use correctly with functions like `map` and `filter`, so this extension was added as a simpler, less error-prone alternative.

### Other changes

I added overloads of several of the read-write that take `OpenOptions` to expose the greater control that `java.nio` introduces. For example, you can use `printWriter(APPEND)` to create a `PrintWriter` that doesn't delete the contents of an existing file.

All the new extensions throw exceptions (such as `NoSuchFileException`) from `java.nio` rather than the copies from `kotlin.io`. The `kotlin.io` copies take `File` objects as parameters, and so aren't compatible with `Path`s.

### Address review comments

- Move varargs parameters to the last position
- Remove PathTreeWalk

#KT-19192

(cherry picked from commit 03cc0bf6aa)
2020-10-28 14:42:24 +03:00
Vladimir Ilmov
030c2daa4d Incorrect package name for multipart classes
(cherry picked from commit 51a37bffff)

^KT-42883 Fixed
2020-10-28 09:15:25 +01:00
Yaroslav Chernyshev
43023f001a [Gradle, Cocoapods] Added useLibraries() to allow static library pods
#KT-42531 fixed

(cherry picked from commit 3386b93009)
2020-10-27 19:28:04 +03:00
Abduqodiri Qurbonzoda
3f1eb1c105 Promote CancellationException to stable #KT-41837
(cherry picked from commit 2fd7d64db0)
2020-10-27 18:59:24 +03:00
Ilya Goncharov
43c8dc174d [Gradle, JS] Fix for IDEA import with dukat binaries
^KT-42954 fixed

(cherry picked from commit e6edb62911)
2020-10-27 18:53:57 +03:00
Yan Zhulanow
4452b2a0fd Minor: Update Android Extensions deprecation message in relevant test
(cherry picked from commit 008da87160)
2020-10-28 00:47:58 +09:00
Yan Zhulanow
e2e1615f01 Fix Parcelize settings serialization (KT-42958)
(cherry picked from commit 9faf91f55d)
2020-10-28 00:47:58 +09:00
Ilya Kirillov
d863e174fa Revert accidentally changed gradle.properties 2020-10-27 16:37:04 +03:00
Ilya Kirillov
db880e5a11 Wizard: fix package for shared module
This change was accidentally made in other commit and missed in cherrypick
2020-10-27 15:10:19 +03:00
Mikhail Zarechenskiy
84b6522b96 Extract new method from the publicly used interface for compatibility
Note that we can't just use ``@JvmDefault` annotation as the main change
 is in the `core` module which targets Java 6

 #KT-42259 Fixed
2020-10-27 14:56:12 +03:00
Yan Zhulanow
beeb281c7e Update deprecation message for the Android Extensions plugin
(cherry picked from commit 994cb6f28e)
2020-10-27 18:12:46 +09:00
Konstantin Tskhovrebov
ea0ce5dbb2 Update KMM project wizard.
(cherry picked from commit ea34a588f3)
2020-10-27 12:06:27 +03:00
Ilya Kirillov
1b823f5899 Wizard: fix maven testdata 2020-10-27 12:02:58 +03:00
Ilya Kirillov
270a4f86d3 Wizard: add resolutionStrategy for mpp library template 2020-10-27 12:02:57 +03:00
Ilya Kirillov
120ae08d93 Wizard: do not create empty local.properties file 2020-10-27 12:02:56 +03:00
Ilya Kirillov
bc3119c290 Wizard: introduce mobile mpp module template & allow module templates for mpp modules 2020-10-27 12:02:56 +03:00
Ilya Kirillov
e2d4c511f6 Wizard: add android extensions plugin only by flag 2020-10-27 12:02:55 +03:00
Ilya Kirillov
ab0ec40e4b Wizard: change custom maven repositories rendering 2020-10-27 12:02:54 +03:00
Ilya Kirillov
5171ed36c5 Wizard: remove extra line break in build files 2020-10-27 12:02:53 +03:00
Ilya Kirillov
0019c30247 Wizard: add setting to hide version & groupId in gradle 2020-10-27 12:02:53 +03:00
Ilya Kirillov
cbae7004b9 Wizard: simplify custom maven repository syntax for Gradle 2020-10-27 12:02:52 +03:00
Ilya Kirillov
d90dbf5f58 Wizard: update libraries versions 2020-10-27 12:02:51 +03:00
Ilya Kirillov
80f8e8bc38 Wizard: move common repositories to the allprojects section 2020-10-27 12:02:50 +03:00
Ilya Kirillov
26d98d1adb Wizard: remove resolutionStrategy from settings.gradle 2020-10-27 12:02:50 +03:00
Ilya Kirillov
c900714114 Wizard: clean activity_main.xml & AndroidManifest.xml files 2020-10-27 12:02:49 +03:00
Ilya Kirillov
7729ee1642 Wizard: simplify android configuration 2020-10-27 12:02:48 +03:00
Yan Zhulanow
2eff78ed41 Enable Parcelize IDE plugin in Android Studio 4.2 (KT-42859)
It turned out that all extensions related to the Parcelize IDE plugin are disabled in Android Studio 4.2. The missing inclusion seemingly happened because of a rebase mistake. This commit returns the missing inclusion back.
2020-10-27 14:46:45 +09:00
Nikita Skvortsov
da041fa611 Avoid iterating over all idea modules.
Use hash table to quickly lookup idea module by gradle project path

(cherry picked from commit 02c31a711c)
2020-10-26 12:28:10 +03:00
Igor Chevdar
c53c867106 Bumped K/N version 2020-10-24 17:39:15 +05:00
Alexander Likhachev
eb98defdba [Gradle, JS] Fix K/JS project build with configuration cache (part 3)
Now configuration cache enabled builds with JS tasks does not fails but prints warning and skips execution on subsequent builds.
Relates to KT-42494

(cherry picked from commit ac7b7abcc0)
2020-10-23 16:34:10 +03:00
Alexander.Likhachev
0b414dc186 [Gradle, JS] Fix K/JS project build with configuration cache (part 2)
It is still does not support configuration cache but these changes allows build to pass with warnings
#KT-42494 Fixed

(cherry picked from commit d6e0d2a55b)
2020-10-23 16:34:05 +03:00
Victor Petukhov
85e69f4bbf Get a callable reference expression to report an error on it properly, taking into account possible wrapping
^KT-42620 Fixed
2020-10-23 15:11:17 +03:00
Andrei Klunnyi
1ba38822ee [KT-40688] Inlay Hints: inlay hints are duplicated on code editing
Code editing changes inlay hints offset.
InlayModel.getAfterLineEndElementsInRange(int, int) call didn't return
previously existed hint by its "outdated" offset. From now on hints are
taken by logical line.

(cherry picked from commit 71023cd596)
2020-10-22 19:04:26 +02:00
Mikhail Glukhikh
e543e8464a [FIR] Expand type before adding equality constraint
(cherry picked from commit ad12cc296b)
2020-10-22 18:19:10 +03:00
Victor Petukhov
a9413b3c4d Fix test after 84129098cb
(cherry picked from commit 6251568e17)
2020-10-22 12:18:52 +03:00
Victor Petukhov
6ba0f08098 Add equality constraints without subtyping
^KT-42195 Fixed
^KT-41741 Fixed
2020-10-21 21:25:10 +03:00
Mads Ager
e9dc79367d [IR] Move isAssignable to IrValueDeclaration.
(cherry picked from commit 3817aa32a1)
2020-10-21 16:00:18 +02:00
Mads Ager
5cfcddf3e3 [IR] Support isAssignable in builders and serialization.
(cherry picked from commit af0999ec6f)
2020-10-21 16:00:18 +02:00
Mads Ager
36c1f2ef40 [JS_IR] Fix exponential behavior accidentally introduced.
(cherry picked from commit 37145fb055)
2020-10-21 16:00:18 +02:00
Mads Ager
7e1fdfffc2 [IR] Add isAssignable property to IrValueParameter.
Use it to check that only the value parameters that are explicitly
marked assignable are assigned.

Currently, the only parameters marked assignable are those for
default argument stubs.

(cherry picked from commit 1f2ca606a5)
2020-10-21 16:00:18 +02:00
Mads Ager
7c4648eab8 [IR] Update naming, but not binary format for IrSetValue.
(cherry picked from commit 8d791ca98e)
2020-10-21 16:00:18 +02:00
Mads Ager
1b54421feb [IR] Fix the type of the default argument mask condition.
On JVM and JS we can get away with using an Int but it really
should be a Boolean and Native reasonably insists on that.

(cherry picked from commit 33ab2299f9)
2020-10-21 16:00:17 +02:00
Mads Ager
1545c7d1b5 [JS_IR] Use IrSetValue for default argument handling for JS backend.
Fix a couple of parameter remappings that now have to take IrSetValue
into account as well as IrGetValue.

(cherry picked from commit 87f17dec4a)
2020-10-21 16:00:17 +02:00
Mads Ager
11beda80e9 [IR] Add IR support for setting parameters.
Use it in the JVM_IR backend for default values code. The parameter
local has to be overwritten for the inliner to work.

(cherry picked from commit 9a93bb3f09)
2020-10-21 16:00:17 +02:00
Dmitry Savvinov
e3c22e500c Restore nullability after type refinement along with annotations
See the issue for details

^KT-42546 Fixed
2020-10-21 11:39:32 +03:00
Dmitry Savvinov
8b4ecf5702 Fix testdata after migrating to NewKotlinTypeCheckerImpl in OverrideResolver
- In kt10409 both 'pipe'-declarations contain error type.
NewKotlinTypeChecker in OverrideResolver considers error types as equal,
thus they are matched as bound declarations, thus 'IterablePipeline'
isn't considered to contain abstract member, thus no suggestion to add
abstract modifier.
Because initially test was covering purely technical issue of working
with error types, instead of removing it completely the additional
abstract member has been added

- in kt10808 we don't add explicit type anymore because
'noTypeInference' is false, because both expected type and actual type
are error-types, and KotlinIntroduceVariableHandler explicitly uses type
checker with 'errorTypesEqualToAnything=false'.
Also, this change might be ultimately seen as small improvement, because
if one extracts something with error type, they would certainly prefer
it to have a proper type as soon as errors are resolved (i.e. additional
code/imports written), rather than having a useless Any-type.
2020-10-21 11:39:32 +03:00
Dmitry Savvinov
bd052ee399 Drop isEqualTypeConstructor in favour of areEqualTypeConstructors 2020-10-21 11:39:32 +03:00
Dmitry Savvinov
fd824d3ce7 Use NewKotlinTypeChecker in OverridingUtil
This allows to use deep type refinement in OverridingUtil, fixing issues
with expect/actuals in composite types
2020-10-21 11:39:32 +03:00
Dmitry Savvinov
2a38b1c5b8 Add test on overriding declaration with a composite type with expect declaration 2020-10-21 11:39:32 +03:00
Dmitry Savvinov
79b4574ef4 Minor: unify error reporting for fun/properties overriding 2020-10-21 11:39:32 +03:00
Dmitry Savvinov
b6a3ba18e7 Unify code for checking return type on override for fun/property
This fixes issues with the refinement of property' return type because
for functions' return type we already perform refinement properly
2020-10-21 11:39:32 +03:00
Dmitry Savvinov
04da7b5319 Add test case on overriding property of expect-type
Current behaviour is undesired, the fix is in the next commit
2020-10-21 11:39:32 +03:00
Dmitry Savvinov
8ef411a2b3 Refine types of type parameters before checking their equality in OverridingUtil 2020-10-21 11:39:31 +03:00
Dmitry Savvinov
e39cd59a3b Add test on override with expect in return type 2020-10-21 11:39:31 +03:00
Ilya Goncharov
e81cb1ad73 [Gradle, JS] Add binary dukat mode
^KT-42339 fixed

[Gradle, JS] Prepare sources and binary modes for dukat

^KT-42339 fixed

(cherry picked from commit 500fceb438)

[Gradle, JS] Dukat descriptors

^KT-42339 fixed

(cherry picked from commit c1fe8defd2)

[Gradle, JS] Add test on compilation with dukat binaries

^KT-42339 fixed

(cherry picked from commit b37414ae0b)

[Gradle, JS] Add TaskAction on overriden method for integrated task

^KT-42339 fixed

[Gradle, JS] Temporarily used next version of dukat

^KT-42339 fixed

(cherry picked from commit 4eea52e4e7)

[Gradle, JS] Move gradle post processing after executing of dukat

^KT-42339 fixed

[Gradle, JS] Use 2 integrated tasks for dukat in both mode

^KT-42339 fixed

[Gradle, JS] Dukat into jar

^KT-42339 fixed

(cherry picked from commit af65365d6a)

[Gradle, JS] Add descriptors to dependencies in configurations phase

- Add file collection dependencies to gradle node module building

^KT-42339 fixed

(cherry picked from commit 0a86beeb64)

[Gradle, JS] Execute dukat on import in both mode

^KT-42339 fixed

[Gradle, JS] Fix tests for dukat

^KT-42339 fixed

[Gradle, JS] Add tests on binaries-both mode

^KT-42339 fixed

[Gradle, JS] Remove snapshot versions

^KT-42339 fixed

[Gradle, JS] Fix file dependency resolution into imported package

^KT-42339 fixed

(cherry picked from commit 3ad6d58153)

[Gradle, JS] Rename dukatMode to externalsOutputFormat

^KT-42339 fixed

(cherry picked from commit b1768d805f)

[Gradle, JS] Dukat change default mode onto source

- Binary only for legacy

^KT-42339 fixed
2020-10-20 15:36:52 +03:00
Victor Petukhov
17cd9dc132 Reuse built functional types for postponed arguments by expected types and paths from a top level type variable
^KT-42221 Fixed
2020-10-20 12:27:14 +03:00
Victor Petukhov
f4a1ceab57 NI: do substitution type variables during updating trace for lambda (these type variables can appear after the builder inference)
^KT-42450 Fixed

(cherry picked from commit 0685beb765)
2020-10-20 11:50:28 +03:00
Alexander Udalov
8fa8644aba Add JVM target bytecode version 15
#KT-41916 Fixed

(cherry picked from commit 48cd86b717)
2020-10-19 18:26:22 +02:00
Ilmir Usmanov
1fb1385de1 Box inline class returned from suspend lambda non-locally
All inline classes should be boxed coming in and out of lambdas,
however, if the inline class was returned non-locally, it was not boxed.
This change fixes the issue in Old JVM BE.
 #KT-41194 In progress
2020-10-19 17:31:13 +02:00
Pavel Kirpichenkov
b75f1b0829 Minor: cover negative cases with test +m
Add case without reported diagnostic on public companion.
Only report diagnostic if @JvmStatic annotation has source in code.

KT-25114
2020-10-15 18:46:24 +03:00
Pavel Kirpichenkov
dd340e99d2 Report warning on @JvmStatic in private companion objects
Deprecation cycle to prohibit in 1.5.
^KT-25114 In Progress
2020-10-15 18:46:05 +03:00
Pavel Kirpichenkov
dcfd805e46 Add test for KT-25114 2020-10-15 18:45:36 +03:00
Mikhael Bogdanov
a9e0002438 Proper check NON_JVM_DEFAULT_OVERRIDES_JAVA_DEFAULT in new jvm-default modes
#KT-42699 Fixed

(cherry picked from commit c8e84f82eb)
2020-10-15 16:35:20 +02:00
Mikhael Bogdanov
43ee55be39 Skip java defaults in EXPLICIT_OVERRIDE_REQUIRED_IN_MIXED_MODE check
#KT-42674 Fixed

(cherry picked from commit b6dc99b98e)
2020-10-15 16:35:19 +02:00
Mikhail Zarechenskiy
510e270bd1 Do not hide synthetic properties except isEmpty from Java
In order to hide synthetic property isEmpty from JDK 15, there was
 added additional logic in 5cc12b49fc but
 it also lead to the fact that now it's impossible to call synthetic
 property `declaringClass` on `Enum` as it's in the same list as method
 isEmpty(). Note that it's questionable behavior, probably we should
 also hide `declaringClass` as well but for now we turn it back to
 preserve compatibility

 #KT-42673 Fixed
2020-10-15 12:34:49 +03:00
Alexander.Likhachev
d9290c605a [Gradle, JS] Fix K/JS project build with configuration cache enabled
KT-42494 Fixed

(cherry picked from commit d3f98923dc)
2020-10-14 18:33:13 +03:00
nataliya.valtman
4838b43709 Can't use configure action from Immutable state
#KT-42413 Fixed

(cherry picked from commit 58ed1bbb64)
2020-10-13 21:03:47 +03:00
Nikolay Krasko
45179663ac Fix double publication of javadoc in kotlin-osgi-bundle (KTI-356)
There's a common place with generating empty javadoc:
635ffcd53b/libraries/pom.xml (L187)

 #KTI-356 Fixed

(cherry picked from commit 5d394528f6)
2020-10-13 20:45:18 +03:00
anastasiia.spaseeva
503a4600c9 Actualize changeLog for 1.4.20-M2 2020-10-13 17:39:01 +03:00
Vyacheslav Gerasimov
76441af482 Build: Disable plugin marker publication for sonatype 2020-10-13 14:08:56 +03:00
Nikolay Krasko
2d23aeb55d Enable signing using gpg in KotlinBuildPublishingPlugin (KTI-355)
Add skip for generated Sign task because otherwise added
 signatory is forcing task activation.

```Execution failed for task ':kotlin-allopen:signMainPublication'.
org.gradle.api.InvalidUserDataException: Cannot perform signing task
':kotlin-allopen:signMainPublication' because it has no configured
signatory```

 #KTI-355 Fixed
2020-10-13 12:29:06 +03:00
Nikolay Krasko
eb594f50e0 Revert "Enable signing using cmd in KotlinBuildPublishingPlugin (KTI-355)"
This reverts commit 8ef06005
2020-10-12 20:57:46 +03:00
Nikolay Krasko
8ef06005ee Enable signing using cmd in KotlinBuildPublishingPlugin (KTI-355)
```Execution failed for task ':kotlin-allopen:signMainPublication'.
org.gradle.api.InvalidUserDataException: Cannot perform signing task
':kotlin-allopen:signMainPublication' because it has no configured
signatory```

 #KTI-355 Fixed
2020-10-12 19:51:32 +03:00
Vladimir Dolzhenko
16cb23f321 Sync up plugin.xml AS42 with 202
Relates to #KT-42274

(cherry picked from commit 3eeaa07e0c)
2020-10-12 14:38:20 +07:00
Igor Chevdar
8a88b98cd8 Bumped K/N version 2020-10-10 10:48:58 +05:00
Ilmir Usmanov
aad01b104a Merge two consequent records in LVT
Otherwise, atomicfu will be unable to transform atomic variable usages.
2020-10-09 19:47:04 +02:00
Dmitry Gridin
c2a5779f18 Revert "Add indent before accessor for extension property (KT-33131)"
This reverts commit ab34f8c7

^KT-42560 Fixed

(cherry picked from commit 434139d986)
2020-10-09 20:40:01 +07:00
Svyatoslav Kuzmich
f1d3a71e2f [JS IR] Make JsExport not fail on companion objects (KT-37829) 2020-10-08 17:44:32 +03:00
Dmitriy Dolovov
ec95cc9d02 IDE: IndexNotReadyException while creating new Kotlin file in Dumb mode
^KT-42518
2020-10-08 15:11:30 +03:00
Igor Chevdar
9d9c0d49fb Bumped K/N version 2020-10-08 09:03:23 +05:00
Denis Zharkov
22adbc25cf Hide java.lang.CharSequence::isEmpty from Kotlin built-in class
Also, prohibit using it as a synthetic property

^KT-42467 In progress
2020-10-07 17:50:10 +03:00
Denis Zharkov
ba02083a54 Use correct naming for additional built-in member lists 2020-10-07 17:50:02 +03:00
Vladimir Dolzhenko
83446a6823 [Usages] Prepare for breaking API change in 1.4.30
KtParameter.descriptor and KtDeclaration.descriptor will be deleted - mark them as deprecated

Relates to ^KT-42406
2020-10-07 11:47:10 +02:00
KotlinIsland
3c111e1ecf Fix typo in messages: DELEGATE_SPECIAL_FUNCTION_NONE_APPLICABLE: is -> are
(cherry picked from commit 0e29f6f48b)
2020-10-07 10:49:24 +02:00
Dmitry Gridin
f8badc5a5f [inspections] fix false positive "Redundant Unit" inspection in lambda with dynamic return type
^KT-40700 Fixed

(cherry picked from commit 9a0c3c47c8)
2020-10-07 15:40:36 +07:00
Yaroslav Chernyshev
faab992f90 [Cocoapods] Remove hierarchical PodInstall dependsOn to Podspecs
#KT-41844 Fixed

(cherry picked from commit 26d03295cf)
2020-10-07 11:08:25 +03:00
Sergey Igushkin
83f3f07368 General fixes for composite builds in HMPP
* Register project structure metadata providers globally, so included
  builds can access it from the root build.

* Rework some dependency management logic so that it doesn't assume that
  dependencies resolved to projects are safe to access – it is so only
  if the project is in the same build; also, in dependency handling, use
  proper keys which distinguish project with same ID in different
  builds.

* Add a separate implementation of `MppDependencyMetadataExtractor` that
  reads the project structure metadata from the mentioned global storage
  (as we can't read it from artifacts – those are not yet build at the
  project configuration phase) but when it comes to artifacts
  processing, takes real artifacts rather than introspect the project
  structure.

* Register the Kotlin/Native host-specific metadata artifact
  configurations as consumable, so that a consumer from a different
  build can properly resolve a dependency to such a configuration and
  get the artifact.

(cherry picked from commit 3a5ffe479e)
2020-10-06 23:36:20 +03:00
Sergey Igushkin
6287a10779 Publish MPP -metadata artifact in the root module, drop separate module
Until now, there was a separate module foo-metadata that contained the
Kotlin metadata artifacts. The reasons for this were only historical,
namely the platform modules used to depend on the metadata module and
expect it to bring the common sources to the IDE.

Now we don't really need the -metadata module, and it's now more harm
from it than good, as users never need to specify it as a dependency.

We fix this by removing the -metadata module from the default publishing
layout and putting the -metadata artifact(-s) directly to the root
module.

(cherry picked from commit 7d1a3a137b)
2020-10-06 23:36:18 +03:00
Sergey Igushkin
62001be998 Simplify matching of Kotlin variant name and Gradle configuration name
Earlier, the matching was non-trivial and required the consumer to look
through all of the producer's targets to find the Kotlin variant given
the name of the configuration that Gradle chose during variant-aware
dependency resolution. This is not feasible in composite builds as we
can't look into a project model of an included build.

To fix this, simplify the matching of the Gradle configuration name and
the Kotlin variant name by just using a suffix for the published
configurations.

Namely, instead of names like `jvm-api`, use the original configuration
name `jvmApiElements` for Kotlin variant names. To avoid ambiguity with
Gradle configurations (which we might want to customize for publishing,
like by altering the attributes or the published artifacts compared to
the configuration exposed for inter-project dependencies), create
publishing configurations

(cherry picked from commit a0fbf54d11)
2020-10-06 23:36:16 +03:00
Sergey Igushkin
e6a3382fa5 HMPP resolution fixes
While we already had the associateWith relationship
that established additional visibility between such
source sets as fooMain and fooTest, this
relationship was not used properly when requested
dependencies were built for source set visibility
inference in HMPP. Instead, an old workaround was
used that just added dependencies of commonMain to
commonTest.

Fix this by using the associateWith relationship in
the preparation logic of source sets visibiltiy.

ALso, make the artifact view used in source sets visibility inference
lenient, so that a host-specific module that has not yet been published
won't lead to fail in source sets visibility and will instead be
ingored.

(cherry picked from commit 16d493558e)
2020-10-06 23:36:14 +03:00
Sergey Igushkin
5c27d7a99a Use JSON as the format for the Kotlin project structure metadata
(cherry picked from commit 5963b07987)
2020-10-06 23:36:12 +03:00
Sergey Igushkin
2abf731006 Cleanup GranularMetadataTransformation after refactoring
(cherry picked from commit f19ef0184c)
2020-10-06 23:36:10 +03:00
Ilya Chernikov
8931a5295f Implement proper script runtime exception rendering with tests
#KT-42335 fixed
2020-10-06 21:44:48 +02:00
Yan Zhulanow
f855ca7eb7 Parcelize: Don't activate both 'kotlin-parcelize' and 'kotlin-android-extensions' in IDE (KT-42267)
The actual problem is a lack of plugin activation check in ParcelableUltraLightClassModifierExtension (see how it should be done in ParcelizeUltraLightClassModifierExtension). However, ParcelableUltraLightClassModifierExtension lays inside ADT sources, and it's impossible to make an fast&easy fix from our side. However, we control the compiler plugin on which the IDE support is based, so the check is added there.

There should be no troubles if the application with 'kotlin-android-extensions' includes an Android library with 'kotlin-parcelize' or vise-versa, as runtime libraries of both plugins are attached to the 'implementation' Gradle configuration since AGP 2.5.
2020-10-07 04:07:26 +09:00
Yan Zhulanow
3288b220f4 Parcelize: Forbid applying both 'kotlin-parcelize' and 'kotlin-android-extensions' (KT-42342) 2020-10-07 04:07:26 +09:00
Yan Zhulanow
614e12eaf3 Keep class members of the ExtensionPoint interface instead of its implementation for easier usage 2020-10-07 04:07:26 +09:00
Yan Zhulanow
8d0407202e Parcelize: Don't write Parcelize model if the Parcelize plugin is disabled
(cherry picked from commit dba1b50aed)
2020-10-07 02:19:42 +09:00
Yan Zhulanow
c76621e75f Kapt: Support new @JvmDefault functionality (KT-25960)
(cherry picked from commit 9cdd6e9a8f)
2020-10-07 02:19:42 +09:00
Yan Zhulanow
5172dfea09 Kapt: Don't convert field initializers for enum fields inside companion objects (KT-37732)
For classes with companion objects, Kotlin compiler generates a 'Companion' static accessor field.
Java prioritizes fields over inner types (apparently, Scala does this as well, KT-29864), so the generated initializer doesn't compile.
As a workaround, initializer generatation is disabled for enum fields inside companion objects. Certainly, it's not a proper fix, however it does fix the regression.

(cherry picked from commit a44fd964cf)
2020-10-07 02:19:42 +09:00
Yan Zhulanow
6783b952fa Debugger: Disable "missing dependency superclass" diagnostic in evaluator (KT-38659)
(cherry picked from commit 1e9bb00744)
2020-10-07 02:19:42 +09:00
Yan Zhulanow
ec7837afe8 Parcelize: Fix NPE on availability check
(cherry picked from commit af1ed77d15)
2020-10-07 02:19:42 +09:00
Yan Zhulanow
c2270aa372 Parcelize: Add integration test for the new kotlin-parcelize plugin
(cherry picked from commit acf1a15f3e)
2020-10-07 02:19:42 +09:00
Yan Zhulanow
29fee7de8f Parcelize: Add tests for deprecated (kotlinx.android.parcel) annotations
(cherry picked from commit 2d158ffebd)
2020-10-07 02:19:41 +09:00
Yan Zhulanow
424d62aa50 Parcelize: Support old (kotlinx.android.parcel) annotations in Parcelize plugin
(cherry picked from commit 1d5ab192f5)
2020-10-07 02:19:41 +09:00
Yan Zhulanow
32ed0739e5 Parcelize: Move back annotations from kotlinx.android.parcel, deprecate them
(cherry picked from commit f0b93bf352)
2020-10-07 02:19:41 +09:00
Yan Zhulanow
2ceb4a3f9a Parcelize: Add deprecation warning to Android Extensions Gradle plugin (KT-42121)
(cherry picked from commit 75a1323974)
2020-10-07 02:19:41 +09:00
Yan Zhulanow
0b46f617ac Parcelize: Publish Parcelize compiler plugin to IDE dependencies repository
(cherry picked from commit 419c88d1f2)
2020-10-07 02:19:41 +09:00
Yan Zhulanow
c8305b346d Parcelize: Add missing dependencies to Parcelize components in tests
(cherry picked from commit 0ce9003ef7)
2020-10-07 02:19:41 +09:00
Yan Zhulanow
8e3ce8c46f Parcelize: Support the new Parcelize plugin in Gradle (KT-40030)
(cherry picked from commit 4bd8e2f78c)
2020-10-07 02:19:41 +09:00
Yan Zhulanow
3d3fe203bb Parcelize: Add IDE support for the Parcelize compiler plugin with sources extracted from Android Extensions plugin (KT-40030)
(cherry picked from commit 15b2850ee0)
2020-10-07 02:19:40 +09:00
Yan Zhulanow
380fe63da1 Parcelize: Add the Parcelize compiler plugin with sources extracted from Android Extensions plugin (KT-40030)
(cherry picked from commit b7796d63d8)
2020-10-07 02:19:40 +09:00
Mikhael Bogdanov
6588b88cbf Properly check default kind on inheriting from old DefaultImpls scheme
(cherry picked from commit 5048471835)
2020-10-06 18:13:38 +02:00
Mikhael Bogdanov
cf58e0594c Add tests for data class runtime string concatenation
#KT-35176

(cherry picked from commit ed5c2b0565)
2020-10-06 13:23:26 +02:00
Mikhael Bogdanov
6746638e7c Add test for for kt42457 wrong behaviour. Align runtime concatenation with it
#KT-42457

(cherry picked from commit eb32a6ddbd)
2020-10-06 13:23:01 +02:00
Mikhael Bogdanov
336ef6e038 Minor. Rename test folder
(cherry picked from commit 39cde978d0)
2020-10-06 07:16:16 +02:00
Mikhael Bogdanov
f6979d7b02 Rename runtime-string-concat option into 'string-concat'
(cherry picked from commit d2c4be18a0)
2020-10-06 07:16:15 +02:00
Ilya Gorbunov
2f5b895578 Do not pack source of invisible runtime helpers to stdlib-js
Use reference sources of built-in Enum and Comparable instead.

KT-42318

(cherry picked from commit 76c5d036a8)
2020-10-06 05:48:57 +03:00
Ivan Gavrilovic
406e8d5c0c Kotlin Gradle plugin - use build service to share incremental compilation info
For large projects, incremental comilation mapping information may be quite
large. With configuration caching enabled, each task gets its own copy of that
state, and for a project with 1400 subprojects, this resulted in 3.6GB of additional
state stored (once task graph is cached).

This change introduces IncrementalModuleInfoProvider which allows build service
to be used if configuration caching is enabled, and it falls back to static
constant otherwise.

(cherry picked from commit 7c360c0068)
2020-10-06 00:39:45 +03:00
Ilya Chernikov
e1fd16030f Automatically add -- after script/expression in kotlin runner
#KT-37987 fixed
2020-10-05 22:37:53 +02:00
Vladimir Dolzhenko
d14d7115e9 Clean up muted tests
Muted tests failed with `Range must be inside element being annotated` is fixed

Relates to ^KT-38959

(cherry picked from commit be84110ada)
2020-10-05 21:47:55 +02:00
Mikhael Bogdanov
0f53538665 Wrong specialization diagnostic is reported on java default inheritance
(cherry picked from commit b27955d268)
2020-10-05 20:11:47 +02:00
Yaroslav Chernyshev
827ebe38b0 [Gradle, Cocoapods] Fix false-negative testCinteropExtraOpts failing
(cherry picked from commit dcf18ec500)
2020-10-05 16:47:20 +03:00
Vladimir Dolzhenko
d0aca5b6e7 Revert "Open build tool window on Gradle DSL errors"
This reverts commit f07b8ac6
2020-10-05 13:02:25 +02:00
Vladimir Dolzhenko
457e999831 Report EXPLICIT_DELEGATION_CALL_REQUIRED on relevant element
^KT-38959 Fixed

(cherry picked from commit 5eac949b43)
2020-10-05 11:48:44 +02:00
Ilya Goncharov
44dece0da6 [Gradle, JS] Support for groovy dsl and Pair in kotlin dsl
[Gradle, JS] Use package json custom fields as inputs

^KT-42400 fixed

(cherry picked from commit de8776ec1d)
2020-10-05 12:44:22 +03:00
Ilya Goncharov
00622d652e [Gradle, JS] Small fix of nullability 2020-10-05 12:40:05 +03:00
Ilya Goncharov
4dfe84152b [Gradle, JS] Add includedRange with version only
(cherry picked from commit da16b8e527)
2020-10-05 12:40:05 +03:00
Ilya Goncharov
a4b90cc0a6 [Gradle, JS] Fix escaped characters in package.json
^KT-40202 fixed

(cherry picked from commit 31e7dd5fcc)
2020-10-05 12:40:05 +03:00
Ilya Goncharov
fb8139005c [Gradle, JS] Fix NpmRange string representation with concrete version
^KT-42222 fixed
^KT-40986 fixed
^KT-39838 fixed

(cherry picked from commit 337a66f906)
2020-10-05 12:40:05 +03:00
Ilya Goncharov
0bb1d735be [Gradle, JS] Add test for duplicated dependency with range version
^KT-42222 fixed
^KT-40986 fixed
^KT-39838 fixed

(cherry picked from commit 0fa4f0572b)
2020-10-05 12:40:05 +03:00
Ilya Goncharov
e75901302b [Gradle, JS] Fix yarn.lock resolution in case of duplicated dependencies
^KT-42222 fixed
^KT-40986 fixed
^KT-39838 fixed

(cherry picked from commit 024771028c)
2020-10-05 12:40:05 +03:00
Vladimir Dolzhenko
cdd7602406 Register EXPRESSION_CODE_FRAGMENT, BLOCK_CODE_FRAGMENT in KtStubElementTypes
Stubbed type has to be register earlier (see IStubFileElementType#checkNotInstantiatedTooLate)

Relates to ^KT-28732

(cherry picked from commit 29b23e79f3)
2020-10-05 11:20:59 +02:00
Yaroslav Chernyshev
8b05372aec [Gradle, Cocoapods] Custom packageName and extraOpts for pods cinterop
#KT-40999 Fixed
2020-10-05 12:01:17 +03:00
Ilmir Usmanov
40c66757e3 Mark implicit receiver as captured if the function is expression
#KT-40260 Fixed
 #KT-42280 Fixed
2020-10-05 09:37:34 +02:00
Dmitry Gridin
5ffbe1c674 [formatter] line indent provider: fix indent for empty braces
^KT-42411 Fixed

(cherry picked from commit 3078bd7b67)
2020-10-05 14:32:53 +07:00
Ilya Gorbunov
53c13c1ec2 Use regex for case-insensitive String.replace
KT-41799

(cherry picked from commit fafb4a7914)
2020-10-03 23:41:58 +03:00
Francesco Vasco
d4cb539e7f Use StringBuilder in String.replace (2x faster)
KT-41799

(cherry picked from commit 4a0109cf44)
2020-10-03 23:41:55 +03:00
Ilya Chernikov
b67bfc1416 Import scope of the imported script
#KT-34178

(cherry picked from commit 5ab822be36)
2020-10-02 21:50:21 +02:00
Ilya Chernikov
22342206bc Remove unused code...
left after "Optimize scopes handling inside LexicalChainedScope"
refactoring commit.

(cherry picked from commit a71eab89e7)
2020-10-02 21:50:19 +02:00
Ilya Chernikov
5c4d863e64 Fix restoring script configuration from file attributes
#KT-41622 fixed

(cherry picked from commit 2828f0a814)
2020-10-02 21:50:18 +02:00
Ilya Chernikov
ec3d113be3 Fix ScriptDefinition subtyping after earlier refactorings
#KT-41905 fixed
(may also fix other yet undetected or not analyzed problems with script
definitions)

(cherry picked from commit d88e87aaac)
2020-10-02 21:50:17 +02:00
Ilya Chernikov
b97a5892cb Treat classpath extraction problems on script definition loading as warnings
#KT-44206 fixed

(cherry picked from commit adcfca3f98)
2020-10-02 21:50:16 +02:00
Mikhael Bogdanov
f06986d557 JVM_IR. Support runtime string concatenation
(cherry picked from commit cf5bd38bec)
2020-10-02 18:25:40 +02:00
Mikhael Bogdanov
057c0737cd Support indy concatenation
(cherry picked from commit 1938f9459f)
2020-10-02 18:25:40 +02:00
Mikhael Bogdanov
9c56160e7a Properly process constants
(cherry picked from commit 942e1962d9)
2020-10-02 18:25:40 +02:00
Mikhael Bogdanov
1d8881991b Add TODO
(cherry picked from commit 8a1f7c5859)
2020-10-02 18:25:40 +02:00
Mikhael Bogdanov
9839368159 Add runtime string concat options. Some renaming
(cherry picked from commit c329c22630)
2020-10-02 18:25:40 +02:00
Mikhael Bogdanov
1e9ccf9059 Basic invokedynamic string concatenation support
(cherry picked from commit 04012951c1)
2020-10-02 18:25:40 +02:00
Mikhael Bogdanov
52c29f1062 Introduce StringAppendGenerator
(cherry picked from commit 88892ec65d)
2020-10-02 18:25:39 +02:00
Mikhael Bogdanov
6d88bfbf09 Minor. Reformat
(cherry picked from commit bf35818438)
2020-10-02 18:25:39 +02:00
Alexander Udalov
f04290289c Minor, mute new test for FIR
(cherry picked from commit ae6d89b100)
2020-10-02 18:25:39 +02:00
pyos
68211ce62b JVM_IR: check for null when converting unboxed inline classes to strings
`C?` can be unboxed into `T?` if if wraps a reference type `T!!`, but in
this case `null` is not a valid value to pass to `toString-impl`.

 #KT-42005 Fixed

(cherry picked from commit bd6ead0467)
2020-10-02 18:25:39 +02:00
Leonid Startsev
851ea9fb85 Use correct class type when creating class references
(for e.g. PolymorphicSerializer)

Former class reference may had type arguments in it, which lead to bugs
in JS IR.

Fixes https://github.com/Kotlin/kotlinx.serialization/issues/1072

(cherry picked from commit bdbf8d7980)
2020-10-02 19:13:28 +03:00
Leonid Startsev
9b7eba77b8 Remove requirement on 'Serializable class must have single primary constructor'
#KT-38868 Fixed
 #KT-41627 Fixed
 Fixes https://github.com/Kotlin/kotlinx.serialization/issues/396
 Fixes https://github.com/Kotlin/kotlinx.serialization/issues/1049

(cherry picked from commit d4bdb0eedc)
2020-10-02 19:13:23 +03:00
Victor Petukhov
a9cf0df01e Add check already fixed variables in PostponedArgumentInputTypesResolver during adding constraints on them and using inside a functional type
^KT-42374 Fixed
2020-10-02 18:33:04 +03:00
Ilya Goncharov
da190a895e [Gradle, JS] Test: Add yarn resolution by version shortcut
^KT-42420 fixed

(cherry picked from commit 96ccf03794)
2020-10-02 18:18:57 +03:00
Ilya Goncharov
a11fe3eac0 [Gradle, JS] Add yarn resolution by version shortcut
^KT-42420 fixed

(cherry picked from commit 18ec9f10f9)
2020-10-02 18:18:56 +03:00
Vladimir Dolzhenko
f7ad2d3fa5 Store kotlin-script-cache-dependencies as project file attribute
To avoid extra root project scan we need to store already processed script cache dependencies

^KT-41640 Fixed

(cherry picked from commit abc4aef403)
2020-10-02 15:26:16 +02:00
Vladimir Dolzhenko
f07b8ac612 Open build tool window on Gradle DSL errors
^EA-236697 Fixed

(cherry picked from commit 741df42c18)
2020-10-02 15:21:46 +02:00
Leonid Startsev
a1ddf68885 Adapt serialization exceptions constructor calls to signature change
(see https://github.com/Kotlin/kotlinx.serialization/pull/1054)

(cherry picked from commit eea4ff33a0)
2020-10-02 14:53:07 +03:00
Leonid Startsev
66225dd449 Add diagnostic to check whether provided custom serializer matches
type of the property.

Check for serializer type mismatch only when custom serializer is present

Otherwise, there are too many false positives on e.g. PolymorphicSerializer

#KT-36329 Fixed

Fixes https://github.com/Kotlin/kotlinx.serialization/issues/830

(cherry picked from commit fe5dbf75fa)
2020-10-02 14:53:04 +03:00
Leonid Startsev
13a2a35299 Improve remove/specify type intentions in Explicit API mode
Do not suggest to remove type for public declarations

 #KT-38915 Fixed

Do not show intention to specify type when corresponding quickfix is available

 #KT-39026 Fixed

(cherry picked from commit bc432ecb85)
2020-10-02 14:52:52 +03:00
Leonid Startsev
117bad1b6a Check return type of internal @PublishedApi functions in Explicit API mode
#KT-38981 Fixed

(cherry picked from commit 5f0e7c3c3f)
2020-10-02 14:52:51 +03:00
Yan Zhulanow
578e52a970 Keep all variants of ExtensionPointImpl.registerExtension() in the pro-guarded compiler (KT-42103) 2020-10-02 17:52:04 +09:00
Yaroslav Chernyshev
596da430ca [Gradle, Cocoapods] Add Podfile missing info to podInstall error report
#KT-42243 Fixed

(cherry picked from commit 4c9d3b4668)
2020-10-01 14:31:52 +03:00
Roman Golyshev
6456d16675 KT-41859 Place classes after typealiases in DeserializedMemberScope
This way, the order in stubs and in deserialized text would be the same

On the next stub version bump, this fix should be reworked: the order
in the `DeserializedMemberScope` should be restored, and the order in
the stubs should be fixed to match the order in `MemberComparator`

^KT-41859 Fixed

(cherry picked from commit 945edfe987)
2020-10-01 11:16:29 +00:00
Roman Golyshev
251e6cc97f KT-41346 Implement NoReorderImplementation without reordering
- See the documentation for `Implementation` for the full
info about the fix and the issue
- Add `preserveDeclarationsOrdering` setting to
`DeserializationConfiguration`
- Enable this setting in `DeserializerForClassfileDecompiler`
- Also, use `List` instead of `Collection` to pass members to
`DeserializedMemberScope`. It is done to emphasize that the order of
the members is important and may be used
- Review: https://jetbrains.team/p/kt/review/1627
- ^KT-41346 Fixed

(cherry picked from commit 6d0a5a0bb2)
2020-10-01 11:16:28 +00:00
Roman Golyshev
ff70f8fbea KT-41346 Refactor computeNonDeclared*
Change the signature of the `computeNonDeclared*` methods so they expect
mutable lists - it better suits their contracts. Also, add a little
documentations about the contract

Also, change `Collection` to `List` for incoming protos to `emphasize`
that their order might be used

(cherry picked from commit bf371ff98a)
2020-10-01 11:16:28 +00:00
Roman Golyshev
0101c3e208 KT-41346 Move Implementation to DeserializedMemberScope
(cherry picked from commit b1097c49d3)
2020-10-01 11:16:27 +00:00
Roman Golyshev
cf4abb4210 KT-41346 Move related code to OptimizedImplementation
This does not change any semantics, only moves the code around

(cherry picked from commit 5596bf33d8)
2020-10-01 11:16:27 +00:00
Roman Golyshev
db2c0856f1 KT-41346 Introduce inner OptimizedImplementation class
Make it implement `Implementation` and move definitions
there

(cherry picked from commit c8878f862d)
2020-10-01 11:16:26 +00:00
Roman Golyshev
f8c74e30ec KT-41346 Extract Implementation interface
This is a temporary interface to make refactoring easier

(cherry picked from commit 683dd57f24)
2020-10-01 11:16:25 +00:00
Roman Golyshev
8900e2dde1 KT-41346 Move removing non-available functions to protected method
This would allow to stricten contract on `computeNonDeclaredFunctions`

(cherry picked from commit 341a7478ed)
2020-10-01 11:16:25 +00:00
Roman Golyshev
733f009b5d KT-41346 Cleanup DeserializedMemberScope
(cherry picked from commit 4f4c25ca5e)
2020-10-01 11:16:24 +00:00
Victor Petukhov
82a3a2ebe6 Introduce warning for the changing arguments execution order for named varargs (KT-17691)
(cherry picked from commit d02432cf93)
2020-10-01 12:17:03 +03:00
Victor Petukhov
7954517ef7 Introduce language feature to enable the correct arguments execution order for named varargs (KT-17691)
(cherry picked from commit d62c665e99)
2020-10-01 12:16:58 +03:00
Kirill Shmakov
7c5eeebb45 Refactor build settings: directly use AppCode artifacts
Modification of 4f51367196

Remaining part of #KT-42065.
2020-10-01 11:08:16 +03:00
Victor Petukhov
62784f1f1a Fix failing spec test
(cherry picked from commit 986ee11aab)
2020-09-30 22:15:17 +03:00
Victor Petukhov
5db84fb293 Fix failing test after fcfabb70d5
(cherry picked from commit d0a1f18c7d)
2020-09-30 17:40:06 +03:00
Victor Petukhov
301df24d90 Report invisible setter error if it's resolved to synthetic property of base class with public getter and protected setter
^KT-11713 Fixed
2020-09-30 14:38:15 +03:00
Denis Zharkov
b4cf209bf5 Fix incorrect NULLABLE_TYPE_PARAMETER_AGAINST_NOT_NULL_TYPE_PARAMETER
^KT-42257 Fixed
2020-09-30 14:35:02 +03:00
Vladimir Dolzhenko
3105b96f39 Add registry key kotlin.resolve.forceFullResolveOnHighlighting
Relates to ^KT-41195
Relates to ^KT-38687

(cherry picked from commit ce1b388668)
2020-09-30 10:42:55 +02:00
Konstantin Tskhovrebov
58feedc741 Revert "as42: Fix override."
This reverts commit d33391f4
2020-09-30 09:41:31 +03:00
Vladimir Dolzhenko
2036b31a9b Added deprecated PackageFragmentProvider#getPackageFragments for BWC
Relates to ^KT-33394
^KT-42259 Fixed

(cherry picked from commit 3c380faeb5)
2020-09-29 21:20:52 +02:00
Alexander Udalov
ac09c60863 JVM IR: do not copy type parameters into suspend lambda classes
Declarations inside that class are referencing the type parameters of
the containing function anyway, since we don't do any remapping. So the
resulting IR is slightly more correct, and doesn't lead to type
parameter/argument size mismatch error on IrBased/Wrapped-descriptors.

This reverts a part of 01da7f289b, which looks like it was no longer
necessary after 8d0ffa1444.

 #KT-42028 Fixed

(cherry picked from commit d48307ec34)
2020-09-29 18:23:57 +02:00
Kirill Shmakov
93929d0bb5 Add useAndroidX property into mobile library template KT-42123
(cherry picked from commit 3075de917b)
2020-09-29 17:26:55 +03:00
Kirill Shmakov
fef425922b Clarify test names to avoid clashes in resolve
This is to workaround problem described in #KT-41342

(cherry picked from commit ac9b5dabfc)
2020-09-29 17:26:54 +03:00
Konstantin Tskhovrebov
763657bd06 as42: remove unused bunch files
(cherry picked from commit 34b6003371)
2020-09-29 15:58:42 +03:00
Konstantin Tskhovrebov
1d66108b30 Bump AS versions.
(cherry picked from commit c8def4543d)
2020-09-29 15:58:40 +03:00
Konstantin Tskhovrebov
d33391f4f8 as42: Fix override.
(cherry picked from commit 8a4aac53d8)
2020-09-29 15:58:39 +03:00
Mikhael Bogdanov
8a624cbd4e Fix nullability of typePath parameter
#KT-41484 Fixed

(cherry picked from commit 7d4a734791)
2020-09-29 14:34:36 +02:00
Konstantin Tskhovrebov
699c666459 Fix version parser for versions without status "1.4-M1-42-IJ2020.1-1".
(cherry picked from commit 8a58ada4cd)
2020-09-29 13:19:50 +03:00
Victor Petukhov
b1a5c827f1 Introduce warning about forbidden referencing to underscore named parameter of the catch block in a future release (KT-31567)
(cherry picked from commit 8f333aef3a)
2020-09-29 10:31:10 +03:00
Victor Petukhov
baa9c476e3 Introduce warning for private inline functions which return anonymous objects without specified supertypes (KT-33917)
(cherry picked from commit 09f1764f82)
2020-09-29 10:31:08 +03:00
Victor Petukhov
0b46337f40 Introduce warning for secondary constructor in enums without delegation to primary constructors (KT-35870)
(cherry picked from commit 63d825fa24)
2020-09-29 10:31:06 +03:00
Victor Petukhov
9ca8e24031 Check implicitly inferred Nothing inside special calls properly: compare constructors instead of types
^KT-41176 Open

(cherry picked from commit 076eacb3d1)
2020-09-29 10:30:58 +03:00
Victor Petukhov
7725a9000e Fix failing MPP tests after 25ea3df5ca through registering InferenceCompatibilityCheckerImpl instance
(cherry picked from commit ccc9b757c0)
2020-09-29 10:30:56 +03:00
Victor Petukhov
d5df67945f Put fix in 9123c4f73baf77f8a50dede6c890c46f5ffafd6c under the inference compatibility flag
(cherry picked from commit 25ea3df5ca)
2020-09-29 10:30:54 +03:00
Pavel Kirpichenkov
4451458014 [NI] Use compatibility mode for KT-41934
(cherry picked from commit fdc134ff66)
2020-09-29 10:30:22 +03:00
Pavel Kirpichenkov
962683caad Add language feature for inference compatibility mode
The feature is intended for updates in the inference algorithm
that change behaviour compared to the previous stable version.

(cherry picked from commit 1465e10f12)
2020-09-29 10:30:20 +03:00
Pavel Kirpichenkov
8581298145 [NI] Add extra ordering for ready-for-fixation variables
Helps fixing to more specific type in the following situations:
Type1 <: Var1
Var2 <: Var1
Var2 <: Type2

Type1 and Type2 may also be nullable and non-nullable versions of the same type.
Note that no additional constraints can be inferred from such constraints before fixation.
Resulting types for variables will always Type1 and Type2 may also be nullable and non-nullable versions of the same type.
Fixing Var1 first will make Var2's type more specific while fixing Var2 first
will make Var1's type less specific. The first is preferrable in general.

(cherry picked from commit 896fbbd1a3)
2020-09-29 10:30:19 +03:00
Victor Petukhov
2166fab0a0 Mark projection of a nullable captured type as not null during simplification constrains with it and a nullable type variable
^KT-41913 Fixed

(cherry picked from commit bfb46befa5)
2020-09-29 10:26:48 +03:00
Kirill Shmakov
5faadc659f Support rerun of MPP tests for jvm target
(cherry picked from commit ec8465859c)
2020-09-29 10:09:34 +03:00
Kirill Shmakov
60c79824a5 Support rerun of common MPP tests
This is to fix #KT-36909

(cherry picked from commit 23642d2f86)
2020-09-29 10:09:33 +03:00
Kirill Shmakov
6daa0a3e93 Use target of the test in rerun dialog
This is to fix #KT-37799

(cherry picked from commit 9008944860)
2020-09-29 10:09:32 +03:00
Vladimir Dolzhenko
f338f48dc3 Register TYPE_CODE_FRAGMENT in KtStubElementTypes
Stubbed type has to be register earlier (see IStubFileElementType#checkNotInstantiatedTooLate)

^KT-28732 Fixed

(cherry picked from commit a149d38c98)
2020-09-28 15:43:00 +02:00
Vladimir Dolzhenko
2adb9c15e7 Notify if gradle points to invalid JDK
^KT-41141 Fixed

(cherry picked from commit 4e5c61cd2f)
2020-09-28 15:43:00 +02:00
Andrei Klunnyi
acbf979587 [KTIJ-145] Memory leak detected
(cherry picked from commit 79e5177126)
2020-09-28 15:38:28 +02:00
Yaroslav Chernyshev
f717a410f3 [Gradle, Cocoapods] Complete logging for corner-case pod configurations
(cherry picked from commit 819e83b68b)
2020-09-28 16:11:29 +03:00
Yaroslav Chernyshev
6d38c7acaf [Gradle, Cocoapods] Improve logging when deprecated podspec path is used
#KT-41948 Fixed

(cherry picked from commit 5f4aa4db27)
2020-09-28 16:11:28 +03:00
Dmitriy Dolovov
ba0a48ef2c HMPP: Avoid NPE during Kotlin facet serialization
^KT-42029
2020-09-28 14:09:31 +03:00
anastasiia.spaseeva
18820cacac Fix changelog header for 1.4.20-M1 2020-09-24 19:03:41 +03:00
anastasiia.spaseeva
3e920356c7 Add changelog for 1.4.20-M1 2020-09-24 18:20:58 +03:00
Igor Chevdar
dc36d53ce1 Bumped K/N version 2020-09-24 00:33:29 +05:00
Ilya Kirillov
36369484a2 Fix binary compatibility with AS
#KT-42061 fixed
2020-09-23 18:23:12 +03:00
Vladimir Dolzhenko
acf7cb9e4d Configure modules Kotlin language settings in a background with a progress
^KT-41936 Fixed

(cherry picked from commit be20a8bd80)
2020-09-23 14:21:20 +02:00
Igor Chevdar
c902e20ff0 Bumped K/N version 2020-09-22 09:56:52 +05:00
Ilmir Usmanov
3d5bbb9ca8 Mark Unit unspillable if it is merged with unspillable Unit
#KT-42004: Fixed
2020-09-18 17:36:27 +02:00
Andrei Klunnyi
21930f040c KT-42014 ClassNotFoundException in Android Studio 4.2
KotlinCodeHintsPass was removed in 5fe1eaea but later a reference to
it appeared by accident in 50461e61.
2020-09-18 15:52:34 +02:00
rbares
9b39dd1a41 Fix JVM Parcelize use of Parceler 2020-09-18 22:46:35 +09:00
Leonid Startsev
5881eef986 Create plugin context before launching actual psi2ir process.
Because IrPluginContextImpl constructor creates new instance of
BuiltinSymbolsBase (with symbols for stdlib declarations like `arrayOf` etc),
there should be at least one pass of `declareUnboundSymbolsAsDependencies`
between creation and usage in plugin. Such pass is located between psi2ir
and compiler plugins application. If plugin context is created inside lambda,
right before plugins are applied, the symbols will remain unbound.

 #KT-41764 Fixed

(cherry picked from commit f2cf64aec7)
2020-09-18 15:45:09 +03:00
Ilya Gorbunov
28f68f8414 Pack jvm builtins into kotlin-stdlib shipped with idea plugin
This lessens the possibility that kotlin plugin will get different
variants of builtins in the classpath, thus making builtins resources
loading less order-dependent.
2020-09-18 15:27:15 +03:00
Igor Chevdar
0ca6d21670 Bumped K/N version 2020-09-18 09:47:39 +05:00
Mikhail Zarechenskiy
ac9cda0be8 as42: move plugin.xml to appropriate resource directy
#KT-41930 Fixed
2020-09-17 18:49:41 +03:00
Vladimir Dolzhenko
2142cd244a Remove 203 version from idea range for kotlin plugin 1.4.20
^KT-41976 Fixed

(cherry picked from commit dfe6c42f63)
2020-09-17 12:01:27 +02:00
Ilmir Usmanov
3d313a1ecc Ignore type parameters of inline class
when checking whether we can return unboxed inline class
from suspend function
2020-09-17 11:22:05 +02:00
Kirill Shmakov
0a2f22f711 Make watchOS test runnable on another bitness
(cherry picked from commit e6e47f8848)
2020-09-17 11:19:34 +03:00
Kirill Shmakov
62c21fcbb5 Show run test gutters only when appropriate
This is to fix KT-36370

(cherry picked from commit 12489ef1b4)
2020-09-17 11:19:30 +03:00
Toshiaki Kameyama
a21e9d034a Redundant nullable return type: fix false positive with elvis return
#KT-41878 Fixed

(cherry picked from commit 0e4bd70c29)
2020-09-17 10:04:52 +02:00
Roman Artemev
3362f15257 [IR] Skip hidden parameters in WrappedDescriptors 2020-09-17 00:56:10 +03:00
Roman Artemev
5cdf381c3e [IR] Support hidden parameters in ir builder 2020-09-17 00:56:10 +03:00
Roman Artemev
7d058cd50a [IR] Support hidden parameters in IrMangler
- make them be skipped in signature
2020-09-17 00:56:10 +03:00
Roman Artemev
1fa0dcc897 [KLIB] Support isHidden flag in deserialization 2020-09-17 00:56:10 +03:00
Roman Artemev
8042c9842c [KLIB] Support isHidden in proto flags 2020-09-17 00:56:09 +03:00
Roman Artemev
96225d92b6 [IR] Support isHidden is IrFactory API
- add API to create a hidden value parameter
2020-09-17 00:56:09 +03:00
Roman Artemev
f8cd381321 [IR] Add isHidden flag into IrValueParameter 2020-09-17 00:56:09 +03:00
Ilya Kirillov
a225d0a0fb Wizard: fix not auto-updated artifactId on project name change
#KT-41695 fixed

(cherry picked from commit be16fa76ab)
2020-09-17 00:32:41 +03:00
Ilya Kirillov
8e213c1fe4 Wizard: add missing jvm target version for tests in Groovy DSL
#KT-41958 fixed

(cherry picked from commit ca3b327592)
2020-09-17 00:32:40 +03:00
Ilya Kirillov
45d4eedf10 Wizard: ignore Kotlin repo in tests
They may differ sometimes as they depend on the latest Kotlin release

(cherry picked from commit ee2f0f45fc)
2020-09-17 00:32:39 +03:00
Alexey Tsvetkov
761feab27b Provide message collector for Java IC analysis
#KT-37446 Fixed
2020-09-16 14:06:47 +03:00
Ivan Gavrilovic
864cda198c KT-41295: Friend paths and compiler options compatible with conf caching
This change fixes serialization of friend paths and it uses
a file collection to record all friend paths. Also, when
computing the tested classpath for android projects, we now avoid
resolving the file collection until necessary.

Fixes: KT-41295
Test: ConfigurationCacheForAndroidIT
(cherry picked from commit 162dc3aa0c)
2020-09-16 10:57:11 +03:00
Steven Schäfer
e56bf12997 Android Synthetics: Resolve unbound symbols in the AndroidIrExtension
(cherry picked from commit 56c4a27887)
2020-09-15 22:37:57 +02:00
Steven Schäfer
623bab16b8 Android Synthetics: Update test infrastructure
(cherry picked from commit fe466f3dc6)
2020-09-15 22:37:56 +02:00
Ilmir Usmanov
ef7c85637d Keep DebugMetadata annotation when regenerate lambda with state-machine
When a suspend lambda does not capture crossinline lambda, it is
generated with as state-machine, since it does not inline anything.
However, when regenerating, the inliner used to remove all DebugMetadata
annotations to avoid duplication. This lead to missing annotation if
the lambda is regenerated, but state-machine is not regenerated.
This change fixes the blind spot by readding the annotation after
regeneration.
 #KT-41789 Fixed
2020-09-15 19:58:36 +02:00
Mikhail Zarechenskiy
e48bf93c67 as42: Fix test about forgotten bunches 2020-09-15 10:35:03 +03:00
Mikhail Zarechenskiy
402a2f4d51 as42: Fix compilation of tests 2020-09-15 10:28:06 +03:00
Nikolay Krasko
f2c04e94e3 as42: Fix assertEqualsToFile usage 2020-09-15 08:56:26 +03:00
Nikolay Krasko
31759df794 as42: Remove setupGradleSettings usage 2020-09-15 08:56:20 +03:00
Nikolay Krasko
ed13b7b407 as42: Remove clearing scratchesMapping in tests 2020-09-15 08:55:55 +03:00
Nikolay Krasko
2835bf7d76 as42: Fix compilation errors in AbstractJavaToKotlinConverterForWebDemoTest 2020-09-15 08:55:40 +03:00
Nikolay Krasko
03ea0b16a7 as42: Fix compilation errors caused by 202 platform 2020-09-15 08:55:19 +03:00
Nikolay Krasko
c931b57fe1 as42: Fix duplication registration for com.intellij.psi.classFileDecompiler in plugin 2020-09-15 08:54:14 +03:00
Nikolay Krasko
573715fee5 as42: Add fastutil library to dependency to make KtUsefulTestCase.<clinit> work
java.lang.NoClassDefFoundError: it/unimi/dsi/fastutil/objects/Object2FloatMap
  at com.intellij.configurationStore.MyXmlSerializer$bindingProducer$1.createRootBinding(xmlSerializer.kt:172)
  at com.intellij.configurationStore.MyXmlSerializer$bindingProducer$1.createRootBinding(xmlSerializer.kt:170)
  at com.intellij.configurationStore.OldBindingProducer.getRootBinding(xmlSerializer.kt:154)
  at com.intellij.configurationStore.MyXmlSerializer.getRootBinding(xmlSerializer.kt:186)
  at com.intellij.util.xmlb.Serializer.getRootBinding(Serializer.java:18)
  at com.intellij.configurationStore.JdomSerializerImpl.serializeObjectInto(xmlSerializer.kt:78)
  at com.intellij.configurationStore.XmlSerializer.serializeObjectInto(xmlSerializer.kt:39)
  at com.intellij.configurationStore.XmlSerializer.serializeObjectInto$default(xmlSerializer.kt:38)
  at com.intellij.configurationStore.XmlSerializer.serializeObjectInto(xmlSerializer.kt)
  at com.intellij.codeInsight.CodeInsightSettings.writeExternal(CodeInsightSettings.java:231)
  at org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase.<clinit>(KtUsefulTestCase.java:123)
  at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
  at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
  at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
  at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
  at junit.framework.TestSuite.createTest(TestSuite.java:60)
  at junit.framework.TestSuite.addTestMethod(TestSuite.java:307)
  at junit.framework.TestSuite.addTestsFromTestCase(TestSuite.java:150)
  at junit.framework.TestSuite.<init>(TestSuite.java:129)
2020-09-15 08:53:50 +03:00
Nikolay Krasko
f96b53d045 as42: Register DumbUtil service as it required in PsiElementFinderImpl 2020-09-15 08:53:05 +03:00
Nikolay Krasko
abe1485066 as42: Register classFileDecompiler through xml
It doesn't work otherwise. It's expected that extension point is registered
at the moment of ClassFileDecompilers instatiation or it fails.
2020-09-15 08:52:57 +03:00
Nikolay Krasko
e4a8aeffe6 as42: Additional fixes for AS42 and 202 platform 2020-09-15 08:52:39 +03:00
Nikolay Krasko
50461e6150 as42: Apply 201 <-> AS41 diff 2020-09-15 08:52:00 +03:00
Nikolay Krasko
57dcefc80e Introduce AS42 bunch 2020-09-15 08:51:42 +03:00
Alexander Gorshenev
19496981a3 A proper modality calculation was missing in IR fake override construction algorithm
#KT-41765 Fixed
2020-09-15 02:13:09 +03:00
Kirill Shmakov
8a10ebaa75 Update gradle tooling
In response to a766369e72

(cherry picked from commit 29f3811bab)
2020-09-14 11:32:54 +03:00
Kirill Shmakov
367d70859a Reorder arguments in KotlinNativeTest for better debug
Previously it was broken on Linux and worked poorly on macOS

(cherry picked from commit 60b812f452)
2020-09-14 11:32:52 +03:00
Toshiaki Kameyama
96cb169246 Redundant nullable return type: false negative with return expression in local function or lambda
#KT-41817 Fixed

(cherry picked from commit 370622087b)
2020-09-13 08:25:51 +02:00
Toshiaki Kameyama
30a4db4c36 Redundant nullable return type: fix false positive with non-local return
#KT-41800 Fixed

(cherry picked from commit de3907e8cc)
2020-09-13 08:25:51 +02:00
Andrey Uskov
c23385b62d Make KotlinCoreEnvironment.disposeApplicationEnvironment() public
The method disposeApplicationEnvironment should be used in Gradle
after the configuration phase. This allows not to recreate the compiler
environment after each kts file compilation and improve overall
performance the evaluation and configuration phases.

(cherry picked from commit 175a8bec9d)
2020-09-11 15:41:08 +03:00
Victor Petukhov
d0610d7ada Fix IDE test after bcd33da6f8 2020-09-11 13:49:29 +03:00
Victor Petukhov
4cb47dfd07 Don't check an argument type during passing it to vararg in the named form to avoid false positives if the argument type is type variable yet
^KT-41144 Fixed
2020-09-10 19:40:55 +03:00
Ilya Goncharov
4440675e19 [Wizard] Update versions in wizard
(cherry picked from commit 2c4c8cdf01)
2020-09-10 19:27:46 +03:00
Vladimir Dolzhenko
f75d650db1 Improve package caching in KotlinJavaPsiFacade
^KT-33394 Fixed

(cherry picked from commit 5036673187)
2020-09-10 11:43:43 +02:00
Vladimir Dolzhenko
a1005d4032 Revert back Inspection: convert initialized val to non-null type
Relates to ^KT-35757
Relates to ^KT-19321

(cherry picked from commit 6f03e42ef7)
2020-09-10 11:40:31 +02:00
Vladimir Dolzhenko
07a9f47fd4 Add warn message to ReplaceWithIgnoreCaseEquals inspection.
Relates to ^KT-40016

(cherry picked from commit a73856be66)
2020-09-10 10:57:59 +02:00
Andrey Uskov
222db66f60 Implemented collecting statistics about JS target mode 2020-09-10 00:41:03 +03:00
Ilya Goncharov
be6a7a501e Add js generate executable default collecting statistics
#KT-40462 Fixed
2020-09-10 00:40:45 +03:00
Ilya Goncharov
f24dfc654e Add js generate externals collecting statistics
#KT-39995 Fixed
2020-09-10 00:40:37 +03:00
1298 changed files with 39650 additions and 16008 deletions

2
.bunch
View File

@@ -4,4 +4,4 @@
193
as40_193
as41
as42_as41
as42_202

View File

@@ -10,7 +10,10 @@
<w>kapt</w>
<w>kotlinc</w>
<w>mutators</w>
<w>parcelable</w>
<w>parceler</w>
<w>parcelers</w>
<w>parcelize</w>
<w>repl</w>
<w>testdata</w>
<w>uast</w>

12051
ChangeLog.md

File diff suppressed because it is too large Load Diff

View File

@@ -31,6 +31,7 @@ import org.jetbrains.kotlin.progress.CompilationCanceledStatus
import org.jetbrains.kotlin.resolve.sam.SAM_LOOKUP_NAME
import org.jetbrains.kotlin.utils.addToStdlib.flattenTo
import java.io.File
import java.nio.file.Files
import java.util.*
import kotlin.collections.HashSet
import kotlin.collections.LinkedHashSet
@@ -66,7 +67,7 @@ fun makeModuleFile(
friendDirs
)
val scriptFile = File.createTempFile("kjps", sanitizeJavaIdentifier(name) + ".script.xml")
val scriptFile = Files.createTempFile("kjps", sanitizeJavaIdentifier(name) + ".script.xml").toFile()
scriptFile.writeText(builder.asText().toString())
return scriptFile
}

View File

@@ -17258,6 +17258,7 @@ public final class DebugProtoBuf {
*hasAnnotations
*Visibility
*isSecondary
*hasNonStableParameterNames
* </pre>
*/
boolean hasFlags();
@@ -17268,6 +17269,7 @@ public final class DebugProtoBuf {
*hasAnnotations
*Visibility
*isSecondary
*hasNonStableParameterNames
* </pre>
*/
int getFlags();
@@ -17463,6 +17465,7 @@ public final class DebugProtoBuf {
*hasAnnotations
*Visibility
*isSecondary
*hasNonStableParameterNames
* </pre>
*/
public boolean hasFlags() {
@@ -17475,6 +17478,7 @@ public final class DebugProtoBuf {
*hasAnnotations
*Visibility
*isSecondary
*hasNonStableParameterNames
* </pre>
*/
public int getFlags() {
@@ -17894,6 +17898,7 @@ public final class DebugProtoBuf {
*hasAnnotations
*Visibility
*isSecondary
*hasNonStableParameterNames
* </pre>
*/
public boolean hasFlags() {
@@ -17906,6 +17911,7 @@ public final class DebugProtoBuf {
*hasAnnotations
*Visibility
*isSecondary
*hasNonStableParameterNames
* </pre>
*/
public int getFlags() {
@@ -17918,6 +17924,7 @@ public final class DebugProtoBuf {
*hasAnnotations
*Visibility
*isSecondary
*hasNonStableParameterNames
* </pre>
*/
public Builder setFlags(int value) {
@@ -17933,6 +17940,7 @@ public final class DebugProtoBuf {
*hasAnnotations
*Visibility
*isSecondary
*hasNonStableParameterNames
* </pre>
*/
public Builder clearFlags() {
@@ -18307,6 +18315,7 @@ public final class DebugProtoBuf {
*isExternal
*isSuspend
*isExpect
*hasNonStableParameterNames
* </pre>
*/
boolean hasFlags();
@@ -18325,6 +18334,7 @@ public final class DebugProtoBuf {
*isExternal
*isSuspend
*isExpect
*hasNonStableParameterNames
* </pre>
*/
int getFlags();
@@ -18723,6 +18733,7 @@ public final class DebugProtoBuf {
*isExternal
*isSuspend
*isExpect
*hasNonStableParameterNames
* </pre>
*/
public boolean hasFlags() {
@@ -18743,6 +18754,7 @@ public final class DebugProtoBuf {
*isExternal
*isSuspend
*isExpect
*hasNonStableParameterNames
* </pre>
*/
public int getFlags() {
@@ -19639,6 +19651,7 @@ public final class DebugProtoBuf {
*isExternal
*isSuspend
*isExpect
*hasNonStableParameterNames
* </pre>
*/
public boolean hasFlags() {
@@ -19659,6 +19672,7 @@ public final class DebugProtoBuf {
*isExternal
*isSuspend
*isExpect
*hasNonStableParameterNames
* </pre>
*/
public int getFlags() {
@@ -19679,6 +19693,7 @@ public final class DebugProtoBuf {
*isExternal
*isSuspend
*isExpect
*hasNonStableParameterNames
* </pre>
*/
public Builder setFlags(int value) {
@@ -19702,6 +19717,7 @@ public final class DebugProtoBuf {
*isExternal
*isSuspend
*isExpect
*hasNonStableParameterNames
* </pre>
*/
public Builder clearFlags() {

View File

@@ -4656,7 +4656,8 @@ public final class DebugJvmProtoBuf {
* <code>extend .org.jetbrains.kotlin.metadata.Class { ... }</code>
*
* <pre>
* isFunctionBodyInInterface: 0 if actual body generated in DefaultImpl, 1 - otherwise (in interface default method)
* first bit: isFunctionBodyInInterface: 0 if actual body generated in DefaultImpl, 1 - otherwise (in interface default method)
* second bit: is all-compatibility mode or not, 1 - yes, 0 - no
* </pre>
*/
public static final

View File

@@ -187,7 +187,7 @@ extra["versions.kotlinx-collections-immutable-jvm"] = immutablesVersion
extra["versions.ktor-network"] = "1.0.1"
if (!project.hasProperty("versions.kotlin-native")) {
extra["versions.kotlin-native"] = "1.4.20-dev-16314"
extra["versions.kotlin-native"] = "1.4.21-release-136"
}
val intellijUltimateEnabled by extra(project.kotlinBuildProperties.intellijUltimateEnabled)
@@ -337,7 +337,8 @@ val gradlePluginProjects = listOf(
":kotlin-allopen",
":kotlin-annotation-processing-gradle",
":kotlin-noarg",
":kotlin-sam-with-receiver"
":kotlin-sam-with-receiver",
":kotlin-parcelize-compiler"
)
apply {
@@ -702,9 +703,12 @@ tasks {
dependsOn("scriptingTest")
dependsOn(":kotlin-build-common:test")
dependsOn(":compiler:incremental-compilation-impl:test")
dependsOn(":compiler:incremental-compilation-impl:testJvmICWithJdk11")
dependsOn(":core:descriptors.runtime:test")
dependsOn("jvmCompilerIntegrationTest")
dependsOn(":plugins:parcelize:parcelize-compiler:test")
}
register("toolsTest") {
@@ -777,7 +781,8 @@ tasks {
dependsOn(
":plugins:android-extensions-ide:test",
":idea:idea-android:test",
":kotlin-annotation-processing:test"
":kotlin-annotation-processing:test",
":plugins:parcelize:parcelize-ide:test"
)
}
@@ -866,12 +871,12 @@ tasks {
":prepare:ide-plugin-dependencies:incremental-compilation-impl-tests-for-ide:publish",
":prepare:ide-plugin-dependencies:kotlin-build-common-tests-for-ide:publish",
":prepare:ide-plugin-dependencies:kotlin-compiler-for-ide:publish",
":prepare:ide-plugin-dependencies:kotlin-dist-for-ide:publish",
":prepare:ide-plugin-dependencies:kotlin-gradle-statistics-for-ide:publish",
":prepare:ide-plugin-dependencies:kotlinx-serialization-compiler-plugin-for-ide:publish",
":prepare:ide-plugin-dependencies:noarg-compiler-plugin-for-ide:publish",
":prepare:ide-plugin-dependencies:sam-with-receiver-compiler-plugin-for-ide:publish",
":prepare:ide-plugin-dependencies:compiler-components-for-jps:publish",
":prepare:ide-plugin-dependencies:parcelize-compiler-plugin-for-ide:publish",
":kotlin-script-runtime:publish",
":kotlin-script-util:publish",
":kotlin-scripting-common:publish",
@@ -886,7 +891,8 @@ tasks {
":kotlin-reflect:publish",
":kotlin-main-kts:publish",
":kotlin-stdlib-js:publish",
":kotlin-test:kotlin-test-js:publish"
":kotlin-test:kotlin-test-js:publish",
":kotlin-coroutines-experimental-compat:publish"
)
}
}

View File

@@ -46,12 +46,12 @@ if (target_AppCode_Clion) {
} else if (target_AndroidStudio) {
logger.info("Including modules for AS (mobile plugin) in buildSrc/settings.gradle")
include ":prepare-deps:cocoa-common-binaries"
include ":prepare-deps:appcode-binaries"
include ":prepare-deps:lldb-framework"
include ":prepare-deps:lldb-frontend"
project(":prepare-deps:cocoa-common-binaries").projectDir =
file("${buildProperties.propertiesProvider.rootProjectDir}/kotlin-ultimate/buildSrc/prepare-deps/cocoa-common-binaries")
project(":prepare-deps:appcode-binaries").projectDir =
file("${buildProperties.propertiesProvider.rootProjectDir}/kotlin-ultimate/buildSrc/prepare-deps/appcode-binaries")
project(":prepare-deps:lldb-framework").projectDir =
file("${buildProperties.propertiesProvider.rootProjectDir}/kotlin-ultimate/buildSrc/prepare-deps/lldb-framework")
project(":prepare-deps:lldb-frontend").projectDir =

View File

@@ -54,7 +54,7 @@ enum class Ide(val platform: Platform) : CompatibilityPredicate {
AS36(Platform.P192),
AS40(Platform.P193),
AS41(Platform.P201),
AS42(Platform.P201);
AS42(Platform.P202);
val kind = Kind.values().first { it.shortName == name.take(2) }
val version = name.dropWhile { !it.isDigit() }.toInt()

View File

@@ -20,6 +20,10 @@ internal const val PLUGIN_MARKER_SUFFIX = ".gradle.plugin"
@UseExperimental(ExperimentalStdlibApi::class)
fun Project.publishPluginMarkers(withEmptyJars: Boolean = true) {
fun Project.isSonatypePublish(): Boolean =
hasProperty("isSonatypePublish") && property("isSonatypePublish") as Boolean
val pluginDevelopment = extensions.getByType<PluginBundleExtension>()
val publishingExtension = extensions.getByType<PublishingExtension>()
val mainPublication = publishingExtension.publications[KotlinBuildPublishingPlugin.PUBLICATION_NAME] as MavenPublication
@@ -32,7 +36,12 @@ fun Project.publishPluginMarkers(withEmptyJars: Boolean = true) {
tasks.named<PublishToMavenRepository>(
"publish${markerPublication.name.capitalize(Locale.ROOT)}PublicationTo${KotlinBuildPublishingPlugin.REPOSITORY_NAME}Repository"
).configureRepository()
).apply {
configureRepository()
configure {
onlyIf { !isSonatypePublish() }
}
}
}
}

View File

@@ -17,9 +17,9 @@ import org.gradle.api.publish.maven.plugins.MavenPublishPlugin
import org.gradle.api.publish.maven.tasks.PublishToMavenRepository
import org.gradle.api.tasks.TaskProvider
import org.gradle.kotlin.dsl.*
import org.gradle.plugins.signing.Sign
import org.gradle.plugins.signing.SigningExtension
import org.gradle.plugins.signing.SigningPlugin
import java.net.URI
import java.util.*
import javax.inject.Inject
@@ -108,13 +108,19 @@ class KotlinBuildPublishingPlugin @Inject constructor(
}
}
configure<SigningExtension> {
setRequired(provider {
project.findProperty("signingRequired")?.toString()?.toBoolean()
?: project.property("isSonatypeRelease") as Boolean
})
val signingRequired = provider {
project.findProperty("signingRequired")?.toString()?.toBoolean()
?: project.property("isSonatypeRelease") as Boolean
}
configure<SigningExtension> {
setRequired(signingRequired)
sign(extensions.getByType<PublishingExtension>().publications[PUBLICATION_NAME])
useGpgCmd()
}
tasks.withType<Sign>().configureEach {
setOnlyIf { signingRequired.get() }
}
tasks.register("install") {

View File

@@ -37,6 +37,7 @@ fun Task.dependsOnKotlinPluginInstall() {
":kotlin-noarg:install",
":kotlin-sam-with-receiver:install",
":kotlin-android-extensions:install",
":kotlin-parcelize-compiler:install",
":kotlin-build-common:install",
":kotlin-compiler-embeddable:install",
":native:kotlin-native-utils:install",

View File

@@ -6,7 +6,6 @@
package org.jetbrains.kotlin.codegen;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.ArrayUtil;
@@ -55,7 +54,6 @@ import org.jetbrains.org.objectweb.asm.commons.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isBoolean;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isPrimitiveClass;
@@ -72,12 +70,6 @@ import static org.jetbrains.org.objectweb.asm.Opcodes.*;
public class AsmUtil {
private static final Set<Type> STRING_BUILDER_OBJECT_APPEND_ARG_TYPES = Sets.newHashSet(
getType(String.class),
getType(StringBuffer.class),
getType(CharSequence.class)
);
private static final int NO_FLAG_LOCAL = 0;
public static final int NO_FLAG_PACKAGE_PRIVATE = 0;
@@ -598,20 +590,6 @@ public class AsmUtil {
: sort == Type.BYTE || sort == Type.SHORT ? Type.INT_TYPE : type;
}
private static Type stringBuilderAppendType(Type type) {
switch (type.getSort()) {
case Type.OBJECT:
return STRING_BUILDER_OBJECT_APPEND_ARG_TYPES.contains(type) ? type : OBJECT_TYPE;
case Type.ARRAY:
return OBJECT_TYPE;
case Type.BYTE:
case Type.SHORT:
return Type.INT_TYPE;
default:
return type;
}
}
public static void genThrow(@NotNull InstructionAdapter v, @NotNull String exception, @Nullable String message) {
v.anew(Type.getObjectType(exception));
v.dup();
@@ -688,39 +666,28 @@ public class AsmUtil {
return index;
}
public static void genStringBuilderConstructor(InstructionAdapter v) {
v.visitTypeInsn(NEW, "java/lang/StringBuilder");
v.dup();
v.invokespecial("java/lang/StringBuilder", "<init>", "()V", false);
}
public static void genInvokeAppendMethod(@NotNull InstructionAdapter v, @NotNull Type type, @Nullable KotlinType kotlinType) {
genInvokeAppendMethod(v, type, kotlinType, null);
}
public static void genInvokeAppendMethod(
@NotNull InstructionAdapter v,
@NotNull StringConcatGenerator generator,
@NotNull Type type,
@Nullable KotlinType kotlinType,
@Nullable KotlinTypeMapper typeMapper
@Nullable KotlinTypeMapper typeMapper,
@NotNull StackValue stackValue
) {
Type appendParameterType;
CallableMethod specializedToString = getSpecializedToStringCallableMethodOrNull(kotlinType, typeMapper);
if (specializedToString != null) {
specializedToString.genInvokeInstruction(v);
appendParameterType = AsmTypes.JAVA_STRING_TYPE;
stackValue.put(type, kotlinType, generator.getMv());
specializedToString.genInvokeInstruction(generator.getMv());
generator.invokeAppend(AsmTypes.JAVA_STRING_TYPE);
}
else if (kotlinType != null && InlineClassesUtilsKt.isInlineClassType(kotlinType)) {
appendParameterType = OBJECT_TYPE;
SimpleType nullableAnyType = kotlinType.getConstructor().getBuiltIns().getNullableAnyType();
StackValue.coerce(type, kotlinType, appendParameterType, nullableAnyType, v);
stackValue.put(type, kotlinType, generator.getMv());
StackValue.coerce(type, kotlinType, OBJECT_TYPE, nullableAnyType, generator.getMv());
generator.invokeAppend(OBJECT_TYPE);
}
else {
appendParameterType = stringBuilderAppendType(type);
generator.putValueOrProcessConstant(stackValue, type, kotlinType);
}
v.invokevirtual("java/lang/StringBuilder", "append", "(" + appendParameterType.getDescriptor() + ")Ljava/lang/StringBuilder;", false);
}
public static StackValue genToString(

View File

@@ -5,6 +5,7 @@
package org.jetbrains.kotlin.codegen
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.org.objectweb.asm.Type
@@ -42,7 +43,7 @@ interface Callable {
}
}
fun afterReceiverGeneration(v: InstructionAdapter, frameMap: FrameMap) {
fun afterReceiverGeneration(v: InstructionAdapter, frameMap: FrameMap, state: GenerationState) {
}
}

View File

@@ -26,6 +26,7 @@ import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtPureClassOrObject
import org.jetbrains.kotlin.psi.KtPureElement
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils.isInterface
import org.jetbrains.kotlin.resolve.calls.components.hasDefaultValue
import org.jetbrains.kotlin.resolve.isInlineClass
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
@@ -134,8 +135,9 @@ class DefaultParameterValueSubstitutor(val state: GenerationState) {
remainingParameters.map { DescriptorToSourceUtils.descriptorToDeclaration(it) as? KtParameter }
val generateAsFinal =
functionDescriptor.modality == Modality.FINAL ||
state.languageVersionSettings.supportsFeature(LanguageFeature.GenerateJvmOverloadsAsFinal)
(functionDescriptor.modality == Modality.FINAL ||
state.languageVersionSettings.supportsFeature(LanguageFeature.GenerateJvmOverloadsAsFinal)) &&
!isInterface(functionDescriptor.containingDeclaration)
val flags =
baseMethodFlags or
(if (isStatic) Opcodes.ACC_STATIC else 0) or

View File

@@ -46,6 +46,7 @@ import org.jetbrains.kotlin.config.ApiVersion;
import org.jetbrains.kotlin.config.JVMAssertionsMode;
import org.jetbrains.kotlin.config.LanguageFeature;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor;
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor;
import org.jetbrains.kotlin.descriptors.impl.SyntheticFieldDescriptor;
import org.jetbrains.kotlin.descriptors.impl.TypeAliasConstructorDescriptor;
@@ -370,22 +371,17 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
FunctionDescriptor functionDescriptor = (FunctionDescriptor) descriptor;
if (!functionDescriptor.isSuspend()) return stackValue;
// When we call suspend operator fun invoke using parens, we cannot box receiver as return type inline class
if (resolvedCall instanceof VariableAsFunctionResolvedCall &&
functionDescriptor.isOperator() && functionDescriptor.getName().getIdentifier().equals("invoke")
) return stackValue;
KotlinType unboxedInlineClass = CoroutineCodegenUtilKt
.originalReturnTypeOfSuspendFunctionReturningUnboxedInlineClass(functionDescriptor, typeMapper);
StackValue stackValueToWrap = stackValue;
KotlinType originalKotlinType;
if (unboxedInlineClass != null) {
originalKotlinType = unboxedInlineClass;
} else {
originalKotlinType = stackValueToWrap.kotlinType;
}
Type originalType;
if (unboxedInlineClass != null) {
originalType = typeMapper.mapType(unboxedInlineClass);
} else {
originalType = stackValueToWrap.type;
}
KotlinType originalKotlinType = unboxedInlineClass != null ? unboxedInlineClass : stackValueToWrap.kotlinType;
Type originalType = unboxedInlineClass != null ? typeMapper.mapType(unboxedInlineClass) : stackValueToWrap.type;
stackValue = new StackValue(originalType, originalKotlinType) {
@Override
@@ -922,28 +918,27 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
else {
return StackValue.operation(type, v -> {
genStringBuilderConstructor(v);
invokeAppendForEntries(v, entries);
v.invokevirtual("java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false);
StringConcatGenerator generator = StringConcatGenerator.Companion.create(state, v);
generator.genStringBuilderConstructorIfNeded();
invokeAppendForEntries(generator, entries);
generator.genToString();
return Unit.INSTANCE;
});
}
}
private void invokeAppendForEntries(InstructionAdapter v, List<StringTemplateEntry> entries) {
private void invokeAppendForEntries(StringConcatGenerator generator, List<StringTemplateEntry> entries) {
for (StringTemplateEntry entry : entries) {
if (entry instanceof StringTemplateEntry.Expression) {
invokeAppend(v, ((StringTemplateEntry.Expression) entry).expression);
invokeAppend(generator, ((StringTemplateEntry.Expression) entry).expression);
}
else {
String value = ((StringTemplateEntry.Constant) entry).value;
if (value.length() == 1) {
v.iconst(value.charAt(0));
genInvokeAppendMethod(v, Type.CHAR_TYPE, null);
generator.putValueOrProcessConstant(StackValue.constant(value.charAt(0), Type.CHAR_TYPE, null));
}
else {
v.aconst(value);
genInvokeAppendMethod(v, JAVA_STRING_TYPE, null);
generator.addStringConstant(value);
}
}
}
@@ -1703,20 +1698,38 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
Type returnType;
KotlinType returnKotlinType;
if (isNonLocalReturn) {
// This is inline lambda. Find inline-site and check, whether it is suspend functions returning unboxed inline class
CodegenContext<?> inlineSiteContext = this.context.getFirstCrossInlineOrNonInlineContext();
KotlinType originalInlineClass = null;
if (inlineSiteContext instanceof MethodContext) {
originalInlineClass = CoroutineCodegenUtilKt
.originalReturnTypeOfSuspendFunctionReturningUnboxedInlineClass(
((MethodContext) inlineSiteContext).getFunctionDescriptor(), typeMapper);
}
if (originalInlineClass != null) {
returnType = typeMapper.mapType(originalInlineClass);
returnKotlinType = originalInlineClass;
FunctionDescriptor returnTarget =
nonLocalReturn.descriptor instanceof FunctionDescriptor
? (FunctionDescriptor) nonLocalReturn.descriptor
: null;
if (returnTarget == null || !returnTarget.isSuspend()) {
JvmKotlinType jvmKotlinType = nonLocalReturn.getJvmKotlinType(typeMapper);
returnType = jvmKotlinType.getType();
returnKotlinType = jvmKotlinType.getKotlinType();
} else if (returnTarget instanceof AnonymousFunctionDescriptor) {
// Suspend lambdas always return Any?
returnType = OBJECT_TYPE;
returnKotlinType = state.getModule().getBuiltIns().getNullableAnyType();
} else {
returnType = nonLocalReturn.returnType.getType();
returnKotlinType = nonLocalReturn.returnType.getKotlinType();
// This is inline lambda, but return target is ordinary, yet suspend, function.
// Find inline-site and check, whether it is suspend functions returning unboxed inline class
CodegenContext<?> inlineSiteContext = this.context.getFirstCrossInlineOrNonInlineContext();
KotlinType originalInlineClass = null;
if (inlineSiteContext instanceof MethodContext) {
FunctionDescriptor view = CoroutineCodegenUtilKt.getOrCreateJvmSuspendFunctionView(returnTarget, state);
originalInlineClass =
CoroutineCodegenUtilKt.originalReturnTypeOfSuspendFunctionReturningUnboxedInlineClass(view, typeMapper);
}
if (originalInlineClass != null) {
// As an optimization, suspend functions, returning inline classes with reference underlying
// type return unboxed inline class. Save the type so the coercer will not box it.
returnType = typeMapper.mapType(originalInlineClass);
returnKotlinType = originalInlineClass;
} else {
JvmKotlinType jvmKotlinType = nonLocalReturn.getJvmKotlinType(typeMapper);
returnType = jvmKotlinType.getType();
returnKotlinType = jvmKotlinType.getKotlinType();
}
}
}
else {
@@ -1780,13 +1793,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
FunctionDescriptor containingFunction =
BindingContextUtils.getContainingFunctionSkipFunctionLiterals(descriptor, true).getFirst();
//FIRST_FUN_LABEL to prevent clashing with existing labels
return new NonLocalReturnInfo(
new JvmKotlinType(
typeMapper.mapReturnType(containingFunction),
containingFunction.getReturnType()
),
FIRST_FUN_LABEL
);
return new NonLocalReturnInfo(containingFunction, FIRST_FUN_LABEL);
} else {
//local
return null;
@@ -1799,10 +1806,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
assert element != null : "Expression should be not null " + expression.getText();
assert elementDescriptor != null : "Descriptor should be not null: " + element.getText();
CallableDescriptor function = (CallableDescriptor) elementDescriptor;
return new NonLocalReturnInfo(
new JvmKotlinType(typeMapper.mapReturnType(function), function.getReturnType()),
expression.getLabelName()
);
return new NonLocalReturnInfo(function, expression.getLabelName());
}
}
return null;
@@ -2836,7 +2840,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
myFrameMap.leaveTemp(firstReceiverType);
}
callableMethod.afterReceiverGeneration(v, myFrameMap);
callableMethod.afterReceiverGeneration(v, myFrameMap, state);
}
}
@@ -4297,7 +4301,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
}
public void invokeAppend(InstructionAdapter v, KtExpression expr) {
public void invokeAppend(StringConcatGenerator generator, KtExpression expr) {
expr = KtPsiUtil.safeDeparenthesize(expr);
ConstantValue<?> compileTimeConstant = getPrimitiveOrStringCompileTimeConstant(expr);
@@ -4311,28 +4315,29 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
Type leftType = expressionType(left);
if (leftType.equals(JAVA_STRING_TYPE)) {
invokeAppend(v, left);
invokeAppend(v, right);
invokeAppend(generator, left);
invokeAppend(generator, right);
return;
}
}
}
else if (expr instanceof KtStringTemplateExpression) {
List<StringTemplateEntry> entries = preprocessStringTemplate((KtStringTemplateExpression) expr);
invokeAppendForEntries(v, entries);
invokeAppendForEntries(generator, entries);
return;
}
}
Type exprType = expressionType(expr);
KotlinType exprKotlinType = kotlinType(expr);
StackValue value;
if (compileTimeConstant != null) {
StackValue.constant(compileTimeConstant.getValue(), exprType, exprKotlinType).put(exprType, exprKotlinType, v);
value = StackValue.constant(compileTimeConstant.getValue(), exprType, exprKotlinType);
} else {
gen(expr, exprType, exprKotlinType);
value = gen(expr);
}
genInvokeAppendMethod(v, exprType, exprKotlinType, typeMapper);
genInvokeAppendMethod(generator, exprType, exprKotlinType, typeMapper, value);
}
@Nullable
@@ -5402,14 +5407,18 @@ The "returned" value of try expression with no finally is either the last expres
private static class NonLocalReturnInfo {
private final JvmKotlinType returnType;
private final CallableDescriptor descriptor;
private final String labelName;
private NonLocalReturnInfo(@NotNull JvmKotlinType type, @NotNull String name) {
returnType = type;
private NonLocalReturnInfo(@NotNull CallableDescriptor descriptor, @NotNull String name) {
this.descriptor = descriptor;
labelName = name;
}
private JvmKotlinType getJvmKotlinType(@NotNull KotlinTypeMapper typeMapper) {
return new JvmKotlinType(typeMapper.mapReturnType(descriptor), descriptor.getReturnType());
}
}
@NotNull

View File

@@ -1677,7 +1677,8 @@ public class FunctionCodegen {
assert isInterface(containingDeclaration) : "'processInterfaceMethod' method should be called only for interfaces, but: " +
containingDeclaration;
if (JvmAnnotationUtilKt.isCompiledToJvmDefault(memberDescriptor, mode)) {
// Fake overrides in interfaces should be expanded to implementation to make proper default check
if (JvmAnnotationUtilKt.checkIsImplementationCompiledToJvmDefault(memberDescriptor, mode)) {
return (kind != OwnerKind.DEFAULT_IMPLS && !isSynthetic) ||
(kind == OwnerKind.DEFAULT_IMPLS &&
(isSynthetic || //TODO: move synthetic method generation into interface

View File

@@ -100,18 +100,19 @@ public class FunctionsFromAnyGeneratorImpl extends FunctionsFromAnyGenerator {
InstructionAdapter iv = new InstructionAdapter(mv);
mv.visitCode();
genStringBuilderConstructor(iv);
StringConcatGenerator generator = StringConcatGenerator.Companion.create(generationState, iv);
generator.genStringBuilderConstructorIfNeded();
boolean first = true;
for (PropertyDescriptor propertyDescriptor : properties) {
if (first) {
iv.aconst(classDescriptor.getName() + "(" + propertyDescriptor.getName().asString() + "=");
generator.addStringConstant(classDescriptor.getName() + "(" + propertyDescriptor.getName().asString() + "=");
first = false;
}
else {
iv.aconst(", " + propertyDescriptor.getName().asString() + "=");
generator.addStringConstant(", " + propertyDescriptor.getName().asString() + "=");
}
genInvokeAppendMethod(iv, JAVA_STRING_TYPE, null);
JvmKotlinType type = genOrLoadOnStack(iv, context, propertyDescriptor, 0);
Type asmType = type.getType();
@@ -130,13 +131,12 @@ public class FunctionsFromAnyGeneratorImpl extends FunctionsFromAnyGenerator {
kotlinType = DescriptorUtilsKt.getBuiltIns(function).getStringType();
}
}
genInvokeAppendMethod(iv, asmType, kotlinType, typeMapper);
genInvokeAppendMethod(generator, asmType, kotlinType, typeMapper, StackValue.onStack(asmType));
}
iv.aconst(")");
genInvokeAppendMethod(iv, JAVA_STRING_TYPE, null);
generator.addStringConstant(")");
iv.invokevirtual("java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false);
generator.genToString();
iv.areturn(JAVA_STRING_TYPE);
FunctionCodegen.endVisit(mv, toStringMethodName, getDeclaration());

View File

@@ -0,0 +1,152 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* 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
import com.google.common.collect.Sets
import org.jetbrains.kotlin.codegen.BranchedValue.Companion.FALSE
import org.jetbrains.kotlin.codegen.BranchedValue.Companion.TRUE
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.config.JvmStringConcat
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.resolve.jvm.AsmTypes.JAVA_STRING_TYPE
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.org.objectweb.asm.Handle
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
import java.lang.StringBuilder
class StringConcatGenerator(val mode: JvmStringConcat, val mv: InstructionAdapter) {
private val template = StringBuilder("")
private val paramTypes = arrayListOf<Type>()
private var justFlushed = false
@JvmOverloads
fun genStringBuilderConstructorIfNeded(swap: Boolean = false) {
if (mode.isDynamic) return
mv.visitTypeInsn(Opcodes.NEW, "java/lang/StringBuilder")
mv.dup()
mv.invokespecial("java/lang/StringBuilder", "<init>", "()V", false)
if (swap) {
mv.swap()
}
}
@JvmOverloads
fun putValueOrProcessConstant(stackValue: StackValue, type: Type = stackValue.type, kotlinType: KotlinType? = stackValue.kotlinType) {
justFlushed = false
if (mode == JvmStringConcat.INDY_WITH_CONSTANTS) {
when (stackValue) {
is StackValue.Constant -> {
template.append(stackValue.value)
return
}
TRUE -> {
template.append(true)
return
}
FALSE -> {
template.append(false)
return
}
}
}
stackValue.put(type, kotlinType, mv)
invokeAppend(type)
}
fun addStringConstant(value: String) {
putValueOrProcessConstant(StackValue.constant(value, JAVA_STRING_TYPE, null))
}
fun invokeAppend(type: Type) {
if (!mode.isDynamic) {
mv.invokevirtual(
"java/lang/StringBuilder",
"append",
"(" + stringBuilderAppendType(type) + ")Ljava/lang/StringBuilder;",
false
)
} else {
justFlushed = false
paramTypes.add(type)
template.append("\u0001")
if (paramTypes.size == 200) {
// Concatenate current arguments into string
// because of `StringConcatFactory` limitation add use it as new argument for further processing:
// "The number of parameter slots in {@code concatType} is less than or equal to 200"
genToString()
justFlushed = true
}
}
}
fun genToString() {
if (!mode.isDynamic) {
mv.invokevirtual("java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false)
} else {
//if state was flushed in `invokeAppend` do nothing
if (justFlushed) return
if (mode == JvmStringConcat.INDY_WITH_CONSTANTS) {
val bootstrap = Handle(
Opcodes.H_INVOKESTATIC,
"java/lang/invoke/StringConcatFactory",
"makeConcatWithConstants",
"(Ljava/lang/invoke/MethodHandles\$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;",
false
)
mv.invokedynamic(
"makeConcatWithConstants",
Type.getMethodDescriptor(JAVA_STRING_TYPE, *paramTypes.toTypedArray()),
bootstrap,
arrayOf(template.toString())
)
} else {
val bootstrap = Handle(
Opcodes.H_INVOKESTATIC,
"java/lang/invoke/StringConcatFactory",
"makeConcat",
"(Ljava/lang/invoke/MethodHandles\$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;",
false
)
mv.invokedynamic(
"makeConcat",
Type.getMethodDescriptor(JAVA_STRING_TYPE, *paramTypes.toTypedArray()),
bootstrap,
arrayOf()
)
}
template.clear()
paramTypes.clear()
paramTypes.add(JAVA_STRING_TYPE)
template.append("\u0001")
}
}
companion object {
private val STRING_BUILDER_OBJECT_APPEND_ARG_TYPES: Set<Type> = Sets.newHashSet(
AsmTypes.getType(String::class.java),
AsmTypes.getType(StringBuffer::class.java),
AsmTypes.getType(CharSequence::class.java)
)
private fun stringBuilderAppendType(type: Type): Type {
return when (type.sort) {
Type.OBJECT -> if (STRING_BUILDER_OBJECT_APPEND_ARG_TYPES.contains(type)) type else AsmTypes.OBJECT_TYPE
Type.ARRAY -> AsmTypes.OBJECT_TYPE
Type.BYTE, Type.SHORT -> Type.INT_TYPE
else -> type
}
}
fun create(state: GenerationState, mv: InstructionAdapter) =
StringConcatGenerator(state.runtimeStringConcat, mv)
}
}

View File

@@ -35,6 +35,7 @@ import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.isInlineClassType
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
@@ -294,7 +295,7 @@ class CoroutineCodegenForLambda private constructor(
functionCodegen.generateMethod(JvmDeclarationOrigin.NO_ORIGIN, funDescriptor,
object : FunctionGenerationStrategy.CodegenBased(state) {
override fun doGenerateBody(codegen: ExpressionCodegen, signature: JvmMethodSignature) {
codegen.v.generateInvokeMethod(signature)
codegen.v.generateInvokeMethod(signature, funDescriptor)
}
})
}
@@ -316,13 +317,13 @@ class CoroutineCodegenForLambda private constructor(
)
mv.visitCode()
with(InstructionAdapter(mv)) {
generateInvokeMethod(jvmMethodSignature)
generateInvokeMethod(jvmMethodSignature, untypedDescriptor)
}
FunctionCodegen.endVisit(mv, "invoke", element)
}
private fun InstructionAdapter.generateInvokeMethod(signature: JvmMethodSignature) {
private fun InstructionAdapter.generateInvokeMethod(signature: JvmMethodSignature, descriptor: FunctionDescriptor) {
// this
load(0, AsmTypes.OBJECT_TYPE)
val parameterTypes = signature.valueParameters.map { it.asmType }
@@ -348,16 +349,23 @@ class CoroutineCodegenForLambda private constructor(
load(arraySlot, AsmTypes.OBJECT_TYPE)
} else {
var index = 0
val fromKotlinTypes =
if (!generateErasedCreate && doNotGenerateInvokeBridge) funDescriptor.allValueParameterTypes()
else funDescriptor.allValueParameterTypes().map { funDescriptor.module.builtIns.nullableAnyType }
val toKotlinTypes =
if (!generateErasedCreate && doNotGenerateInvokeBridge) createCoroutineDescriptor.allValueParameterTypes()
else descriptor.allValueParameterTypes()
parameterTypes.withVariableIndices().forEach { (varIndex, type) ->
load(varIndex + 1, type)
StackValue.coerce(type, createArgumentTypes[index++], this)
StackValue.coerce(type, fromKotlinTypes[index], createArgumentTypes[index], toKotlinTypes[index], this)
index++
}
}
// this.create(..)
invokevirtual(
v.thisName,
createCoroutineDescriptor.name.identifier,
typeMapper.mapFunctionName(createCoroutineDescriptor, null),
Type.getMethodDescriptor(
languageVersionSettings.continuationAsmType(),
*createArgumentTypes.toTypedArray()
@@ -439,12 +447,24 @@ class CoroutineCodegenForLambda private constructor(
)
} else {
if (generateErasedCreate) {
load(index, AsmTypes.OBJECT_TYPE)
StackValue.coerce(
AsmTypes.OBJECT_TYPE, builtIns.nullableAnyType,
fieldInfoForCoroutineLambdaParameter.fieldType, fieldInfoForCoroutineLambdaParameter.fieldKotlinType,
this
)
if (parameter.type.isInlineClassType()) {
load(cloneIndex, fieldInfoForCoroutineLambdaParameter.ownerType)
load(index, AsmTypes.OBJECT_TYPE)
StackValue.unboxInlineClass(AsmTypes.OBJECT_TYPE, parameter.type, this)
putfield(
fieldInfoForCoroutineLambdaParameter.ownerInternalName,
fieldInfoForCoroutineLambdaParameter.fieldName,
fieldInfoForCoroutineLambdaParameter.fieldType.descriptor
)
continue
} else {
load(index, AsmTypes.OBJECT_TYPE)
StackValue.coerce(
AsmTypes.OBJECT_TYPE, builtIns.nullableAnyType,
fieldInfoForCoroutineLambdaParameter.fieldType, fieldInfoForCoroutineLambdaParameter.fieldKotlinType,
this
)
}
} else {
load(index, fieldInfoForCoroutineLambdaParameter.fieldType)
}
@@ -831,3 +851,6 @@ private object FailingFunctionGenerationStrategy : FunctionGenerationStrategy()
fun reportSuspensionPointInsideMonitor(element: KtElement, state: GenerationState, stackTraceElement: String) {
state.diagnostics.report(ErrorsJvm.SUSPENSION_POINT_INSIDE_MONITOR.on(element, stackTraceElement))
}
private fun FunctionDescriptor.allValueParameterTypes(): List<KotlinType> =
(listOfNotNull(extensionReceiverParameter?.type)) + valueParameters.map { it.type }

View File

@@ -1239,11 +1239,26 @@ private fun updateLvtAccordingToLiveness(method: MethodNode, isForNamedFunction:
val endLabel = insn as? LabelNode ?: insn.findNextOrNull { it is LabelNode } as? LabelNode ?: continue
// startLabel can be null in case of parameters
@Suppress("NAME_SHADOWING") val startLabel = startLabel ?: lvtRecord.start
// No LINENUMBER in range -> no way to put a breakpoint -> do not bother adding a record
if (InsnSequence(startLabel, endLabel).none { it is LineNumberNode }) continue
method.localVariables.add(
LocalVariableNode(lvtRecord.name, lvtRecord.desc, lvtRecord.signature, startLabel, endLabel, lvtRecord.index)
)
var recordToExtend: LocalVariableNode? = null
for (record in method.localVariables) {
if (record.name == lvtRecord.name &&
record.desc == lvtRecord.desc &&
record.signature == lvtRecord.signature &&
record.index == lvtRecord.index
) {
if (InsnSequence(record.end, startLabel).none { isBeforeSuspendMarker(it) }) {
recordToExtend = record
break
}
}
}
if (recordToExtend != null) {
recordToExtend.end = endLabel
} else {
method.localVariables.add(
LocalVariableNode(lvtRecord.name, lvtRecord.desc, lvtRecord.signature, startLabel, endLabel, lvtRecord.index)
)
}
}
}
}

View File

@@ -136,7 +136,11 @@ private class UnitSourceInterpreter(private val localVariables: Set<Int>) : Basi
override fun merge(value1: BasicValue?, value2: BasicValue?): BasicValue? =
if (value1 is UnitValue && value2 is UnitValue) {
UnitValue(value1.insns.union(value2.insns))
val newValue = UnitValue(value1.insns.union(value2.insns))
if (newValue.insns.any { it in unspillableUnitValues }) {
markUnspillable(newValue)
}
newValue
} else {
// Mark unit values as unspillable if we merge them with non-unit values here.
// This is conservative since the value could turn out to be unused.

View File

@@ -21,6 +21,7 @@ import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.resolve.inline.isEffectivelyInlineOnly
import org.jetbrains.kotlin.resolve.isInlineClass
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import org.jetbrains.kotlin.resolve.jvm.diagnostics.OtherOrigin
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature
@@ -92,7 +93,9 @@ class SuspendFunctionGenerationStrategy(
sourceFile = declaration.containingKtFile.name,
shouldPreserveClassInitialization = constructorCallNormalizationMode.shouldPreserveClassInitialization,
needDispatchReceiver = originalSuspendDescriptor.dispatchReceiverParameter != null,
internalNameForDispatchReceiver = containingClassInternalNameOrNull(),
internalNameForDispatchReceiver = (originalSuspendDescriptor.containingDeclaration as? ClassDescriptor)?.let {
if (it.isInlineClass()) state.typeMapper.mapType(it).internalName else null
} ?: containingClassInternalNameOrNull(),
languageVersionSettings = languageVersionSettings,
disableTailCallOptimizationForFunctionReturningUnit = originalSuspendDescriptor.returnType?.isUnit() == true &&
originalSuspendDescriptor.overriddenDescriptors.isNotEmpty() &&

View File

@@ -475,7 +475,8 @@ fun FunctionDescriptor.originalReturnTypeOfSuspendFunctionReturningUnboxedInline
// Force boxing if the function overrides function with different type modulo nullability
if (originalDescriptor.overriddenDescriptors.any {
(it.original.returnType?.isMarkedNullable == true && it.original.returnType?.isNullableUnderlyingType() == true) ||
it.original.returnType?.makeNotNullable() != originalReturnType.makeNotNullable()
// We do not care about type parameters, just main class type
it.original.returnType?.constructor?.declarationDescriptor != originalReturnType.constructor.declarationDescriptor
}) return null
// Don't box other inline classes
return originalReturnType
@@ -542,3 +543,12 @@ val EXPERIMENTAL_CONTINUATION_ASM_TYPE = StandardNames.CONTINUATION_INTERFACE_FQ
@JvmField
val RELEASE_CONTINUATION_ASM_TYPE = StandardNames.CONTINUATION_INTERFACE_FQ_NAME_RELEASE.topLevelClassAsmType()
fun FunctionDescriptor.isInvokeSuspendOfLambda(): Boolean {
if (this !is SimpleFunctionDescriptor) return false
if (valueParameters.size != 1 ||
valueParameters[0].name.asString() != SUSPEND_CALL_RESULT_NAME ||
name.asString() != "invokeSuspend"
) return false
return containingDeclaration is SyntheticClassDescriptorForLambda
}

View File

@@ -57,6 +57,7 @@ class AnonymousObjectTransformer(
lateinit var superClassName: String
var sourceInfo: String? = null
var debugInfo: String? = null
var debugMetadataAnnotation: AnnotationNode? = null
createClassReader().accept(object : ClassVisitor(Opcodes.API_VERSION, classBuilder.visitor) {
override fun visit(version: Int, access: Int, name: String, signature: String?, superName: String, interfaces: Array<String>) {
@@ -77,7 +78,8 @@ class AnonymousObjectTransformer(
val innerClassesInfo = FileBasedKotlinClass.InnerClassesInfo()
return FileBasedKotlinClass.convertAnnotationVisitor(metadataReader, desc, innerClassesInfo)
} else if (desc == DEBUG_METADATA_ANNOTATION_ASM_TYPE.descriptor) {
return null
debugMetadataAnnotation = AnnotationNode(desc)
return debugMetadataAnnotation
}
return super.visitAnnotation(desc, visible)
}
@@ -137,12 +139,20 @@ class AnonymousObjectTransformer(
methodsToTransform,
superClassName
)
var putDebugMetadata = false
loop@ for (next in methodsToTransform) {
val deferringVisitor =
when {
coroutineTransformer.shouldSkip(next) -> continue@loop
coroutineTransformer.shouldGenerateStateMachine(next) -> coroutineTransformer.newMethod(next)
else -> newMethod(classBuilder, next)
else -> {
// Debug metadata is not put, but we should keep, since we do not generate state-machine,
// if the lambda does not capture crossinline lambdas.
if (coroutineTransformer.suspendLambdaWithGeneratedStateMachine(next)) {
putDebugMetadata = true
}
newMethod(classBuilder, next)
}
}
if (next.name == "<clinit>") {
@@ -190,6 +200,13 @@ class AnonymousObjectTransformer(
writeTransformedMetadata(header, classBuilder)
}
// debugMetadataAnnotation can be null in LV < 1.3
if (putDebugMetadata && debugMetadataAnnotation != null) {
visitor.visitAnnotation(debugMetadataAnnotation!!.desc, true).also {
debugMetadataAnnotation!!.accept(it)
}
}
writeOuterInfo(visitor)
if (inliningContext.generateAssertField && fieldNames.none { it.key == ASSERTIONS_DISABLED_FIELD_NAME }) {

View File

@@ -37,7 +37,7 @@ open class MethodBodyVisitor(mv: MethodVisitor) : MethodVisitor(Opcodes.API_VERS
override fun visitAnnotation(desc: String, visible: Boolean): AnnotationVisitor? = null
override fun visitTypeAnnotation(typeRef: Int, typePath: TypePath, desc: String, visible: Boolean): AnnotationVisitor? = null
override fun visitTypeAnnotation(typeRef: Int, typePath: TypePath?, desc: String, visible: Boolean): AnnotationVisitor? = null
override fun visitParameterAnnotation(parameter: Int, desc: String, visible: Boolean): AnnotationVisitor? = null

View File

@@ -43,11 +43,14 @@ class CoroutineTransformer(
fun shouldGenerateStateMachine(node: MethodNode): Boolean {
// Continuations are similar to lambdas from bird's view, but we should never generate state machine for them
if (isContinuationNotLambda()) return false
// there can be suspend lambdas inside inline functions, which do not
// capture crossinline lambdas, thus, there is no need to transform them
return isSuspendFunctionWithFakeConstructorCall(node) || (isSuspendLambda(node) && !isStateMachine(node))
}
// there can be suspend lambdas inside inline functions, which do not
// capture crossinline lambdas, thus, there is no need to transform them
fun suspendLambdaWithGeneratedStateMachine(node: MethodNode): Boolean =
!isContinuationNotLambda() && isSuspendLambda(node) && isStateMachine(node)
private fun isContinuationNotLambda(): Boolean = inliningContext.isContinuation &&
if (state.languageVersionSettings.isReleaseCoroutines()) superClassName.endsWith("ContinuationImpl")
else methods.any { it.name == "getLabel" }

View File

@@ -19,7 +19,7 @@ package org.jetbrains.kotlin.codegen.intrinsics
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.AsmUtil.genInvokeAppendMethod
import org.jetbrains.kotlin.codegen.AsmUtil.genStringBuilderConstructor
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtCallableReferenceExpression
@@ -32,68 +32,73 @@ import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
class Concat : IntrinsicMethod() {
fun generateImpl(
codegen: ExpressionCodegen,
v: InstructionAdapter,
returnType: Type,
element: PsiElement?,
arguments: List<KtExpression>,
receiver: StackValue
codegen: ExpressionCodegen,
v: InstructionAdapter,
returnType: Type,
element: PsiElement?,
arguments: List<KtExpression>,
receiver: StackValue
): Type {
val generator = StringConcatGenerator.create(codegen.state, v)
if (element is KtBinaryExpression && element.operationReference.getReferencedNameElementType() == KtTokens.PLUS) {
// LHS + RHS
genStringBuilderConstructor(v)
codegen.invokeAppend(v, element.left)
codegen.invokeAppend(v, element.right)
}
else {
// LHS + RHS
generator.genStringBuilderConstructorIfNeded()
codegen.invokeAppend(generator, element.left)
codegen.invokeAppend(generator, element.right)
} else {
// Explicit plus call LHS?.plus(RHS) or LHS.plus(RHS)
receiver.put(AsmTypes.JAVA_STRING_TYPE, v)
genStringBuilderConstructor(v)
v.swap()
genInvokeAppendMethod(v, returnType, null)
codegen.invokeAppend(v, arguments[0])
generator.genStringBuilderConstructorIfNeded(true)
genInvokeAppendMethod(generator, returnType, null, null, StackValue.onStack(JAVA_STRING_TYPE))
codegen.invokeAppend(generator, arguments[0])
}
v.invokevirtual("java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false)
generator.genToString()
return JAVA_STRING_TYPE
}
override fun toCallable(method: CallableMethod): Callable =
object : IntrinsicCallable(method) {
override fun invokeMethodWithArguments(
resolvedCall: ResolvedCall<*>,
receiver: StackValue,
codegen: ExpressionCodegen
): StackValue {
if (resolvedCall.call.callElement.parent is KtCallableReferenceExpression) {
// NB we come here only in case of inlined callable reference to String::plus.
// This will map arguments properly, invoking callbacks defined in Callable.
return super.invokeMethodWithArguments(resolvedCall, receiver, codegen)
}
return StackValue.operation(returnType) {
val arguments = resolvedCall.call.valueArguments.map { it.getArgumentExpression()!! }
val actualType = generateImpl(
codegen, it, returnType,
resolvedCall.call.callElement,
arguments,
StackValue.receiver(resolvedCall, receiver, codegen, this)
)
StackValue.coerce(actualType, returnType, it)
}
object : IntrinsicCallable(method) {
lateinit var generator: StringConcatGenerator
override fun invokeMethodWithArguments(
resolvedCall: ResolvedCall<*>,
receiver: StackValue,
codegen: ExpressionCodegen
): StackValue {
if (resolvedCall.call.callElement.parent is KtCallableReferenceExpression) {
// NB we come here only in case of inlined callable reference to String::plus.
// This will map arguments properly, invoking callbacks defined in Callable.
return super.invokeMethodWithArguments(resolvedCall, receiver, codegen)
}
override fun afterReceiverGeneration(v: InstructionAdapter, frameMap: FrameMap) {
v.generateNewInstanceDupAndPlaceBeforeStackTop(frameMap, AsmTypes.JAVA_STRING_TYPE, "java/lang/StringBuilder")
v.invokespecial("java/lang/StringBuilder", "<init>", "(Ljava/lang/String;)V", false)
}
override fun invokeIntrinsic(v: InstructionAdapter) {
// String::plus has type String.(Any?) -> String, thus we have no argument type information
// in case of callable reference passed to a generic function, e.g.:
// charArrayOf('O', 'K').fold("", String::plus)
// TODO Make String::plus generic, and invoke proper StringBuilder#append.
AsmUtil.genInvokeAppendMethod(v, AsmTypes.OBJECT_TYPE, null)
v.invokevirtual("java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false)
return StackValue.operation(returnType) {
val arguments = resolvedCall.call.valueArguments.map { it.getArgumentExpression()!! }
val actualType = generateImpl(
codegen, it, returnType,
resolvedCall.call.callElement,
arguments,
StackValue.receiver(resolvedCall, receiver, codegen, this)
)
StackValue.coerce(actualType, returnType, it)
}
}
override fun afterReceiverGeneration(v: InstructionAdapter, frameMap: FrameMap, state: GenerationState) {
generator = StringConcatGenerator.create(state, v)
if (!generator.mode.isDynamic) {
v.generateNewInstanceDupAndPlaceBeforeStackTop(frameMap, JAVA_STRING_TYPE, "java/lang/StringBuilder")
v.invokespecial("java/lang/StringBuilder", "<init>", "(Ljava/lang/String;)V", false)
} else {
generator.invokeAppend(JAVA_STRING_TYPE)
}
}
override fun invokeIntrinsic(v: InstructionAdapter) {
// String::plus has type String.(Any?) -> String, thus we have no argument type information
// in case of callable reference passed to a generic function, e.g.:
// charArrayOf('O', 'K').fold("", String::plus)
// TODO Make String::plus generic, and invoke proper StringBuilder#append.
generator.invokeAppend(AsmTypes.OBJECT_TYPE)
generator.genToString()
}
}
}

View File

@@ -20,6 +20,7 @@ import org.jetbrains.kotlin.codegen.Callable
import org.jetbrains.kotlin.codegen.CallableMethod
import org.jetbrains.kotlin.codegen.FrameMap
import org.jetbrains.kotlin.codegen.generateNewInstanceDupAndPlaceBeforeStackTop
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.Type.*
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
@@ -48,7 +49,7 @@ class RangeTo : IntrinsicMethod() {
nullOr(method.dispatchReceiverType, argType),
nullOr(method.extensionReceiverType, argType)
) {
override fun afterReceiverGeneration(v: InstructionAdapter, frameMap: FrameMap) {
override fun afterReceiverGeneration(v: InstructionAdapter, frameMap: FrameMap, state: GenerationState) {
v.generateNewInstanceDupAndPlaceBeforeStackTop(frameMap, argType, returnType.internalName)
}

View File

@@ -16,13 +16,37 @@
package org.jetbrains.kotlin.codegen.intrinsics
import org.jetbrains.kotlin.codegen.Callable
import org.jetbrains.kotlin.codegen.CallableMethod
import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
class StringPlus : IntrinsicMethod() {
override fun toCallable(method: CallableMethod): Callable =
createIntrinsicCallable(method) {
it.invokestatic(IntrinsicMethods.INTRINSICS_CLASS_NAME, "stringPlus",
"(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/String;", false)
object : IntrinsicCallable(method) {
private lateinit var generator: StringConcatGenerator
override fun invokeMethodWithArguments(
resolvedCall: ResolvedCall<*>,
receiver: StackValue,
codegen: ExpressionCodegen
): StackValue {
generator = StringConcatGenerator.create(codegen.state, codegen.v)
return super.invokeMethodWithArguments(resolvedCall, receiver, codegen)
}
override fun genInvokeInstruction(v: InstructionAdapter) {
if (!generator.mode.isDynamic) {
v.invokestatic(
IntrinsicMethods.INTRINSICS_CLASS_NAME, "stringPlus",
"(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/String;", false
)
} else {
generator.invokeAppend(AsmTypes.JAVA_STRING_TYPE)
//TODO: process constants properly, do not upcast to object
generator.invokeAppend(AsmTypes.OBJECT_TYPE)
generator.genToString()
}
}
}
}

View File

@@ -191,6 +191,10 @@ class GenerationState private constructor(
val languageVersionSettings = configuration.languageVersionSettings
val target = configuration.get(JVMConfigurationKeys.JVM_TARGET) ?: JvmTarget.DEFAULT
val runtimeStringConcat =
if (target.bytecodeVersion >= JvmTarget.JVM_9.bytecodeVersion)
configuration.get(JVMConfigurationKeys.STRING_CONCAT) ?: JvmStringConcat.INLINE
else JvmStringConcat.INLINE
val moduleName: String = moduleName ?: JvmCodegenUtil.getModuleName(module)
val classBuilderMode: ClassBuilderMode = builderFactory.classBuilderMode

View File

@@ -18,3 +18,8 @@ sourceSets {
"main" { projectDefault() }
"test" {}
}
tasks.getByName<Jar>("jar") {
//excludes unused bunch files
exclude("META-INF/extensions/*.xml.**")
}

View File

@@ -0,0 +1,10 @@
<idea-plugin>
<id>org.jetbrains.kotlin</id>
<version>1.2</version>
<extensionPoints>
<extensionPoint qualifiedName="com.intellij.psi.classFileDecompiler"
interface="com.intellij.psi.compiled.ClassFileDecompilers$Decompiler"
dynamic="true"/>
</extensionPoints>
</idea-plugin>

View File

@@ -352,6 +352,12 @@ abstract class CommonCompilerArguments : CommonToolArguments() {
)
var deserializeFakeOverrides: Boolean by FreezableVar(false)
@Argument(
value = "-Xinference-compatibility",
description = "Enable compatibility changes for generic type inference algorithm"
)
var inferenceCompatibility: Boolean by FreezableVar(false)
open fun configureAnalysisFlags(collector: MessageCollector): MutableMap<AnalysisFlag<*>, Any> {
return HashMap<AnalysisFlag<*>, Any>().apply {
put(AnalysisFlags.skipMetadataVersionCheck, skipMetadataVersionCheck)
@@ -426,6 +432,10 @@ abstract class CommonCompilerArguments : CommonToolArguments() {
put(LanguageFeature.MixedNamedArgumentsInTheirOwnPosition, LanguageFeature.State.ENABLED)
}
if (inferenceCompatibility) {
put(LanguageFeature.InferenceCompatibility, LanguageFeature.State.ENABLED)
}
if (progressiveMode) {
LanguageFeature.values().filter { it.kind.enabledInProgressiveMode }.forEach {
// Don't overwrite other settings: users may want to turn off some particular

View File

@@ -70,7 +70,7 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
@Argument(
value = "-jvm-target",
valueDescription = "<version>",
description = "Target version of the generated JVM bytecode (1.6, 1.8, 9, 10, 11, 12, 13 or 14), default is 1.6"
description = "Target version of the generated JVM bytecode (1.6, 1.8, 9, 10, 11, 12, 13, 14 or 15), default is 1.6"
)
var jvmTarget: String? by NullableStringFreezableVar(JvmTarget.DEFAULT.description)
@@ -333,6 +333,16 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
)
var emitJvmTypeAnnotations: Boolean by FreezableVar(false)
@Argument(
value = "-Xstring-concat",
valueDescription = "{indy-with-constants|indy|inline}",
description = """Switch a way in which string concatenation is performed.
-Xstring-concat=indy-with-constants Performs string concatenation via `invokedynamic` 'makeConcatWithConstants'. Works only with `-jvm-target 9` or greater
-Xstring-concat=indy Performs string concatenation via `invokedynamic` 'makeConcat'. Works only with `-jvm-target 9` or greater
-Xstring-concat=inline Performs string concatenation via `StringBuilder`"""
)
var stringConcat: String? by NullableStringFreezableVar(JvmStringConcat.INLINE.description)
@Argument(
value = "-Xklib",
valueDescription = "<path>",

View File

@@ -141,6 +141,9 @@ class ScriptRunner(private val path: String) : RunnerWithCompiler() {
addClasspathArgIfNeeded(classpath)
add("-script")
add(path)
if (arguments.isNotEmpty() && arguments.first() != "--") {
add("--")
}
addAll(arguments)
}
runCompiler(compilerClasspath, compilerArgs)
@@ -153,6 +156,9 @@ class ExpressionRunner(private val code: String) : RunnerWithCompiler() {
addClasspathArgIfNeeded(classpath)
add("-expression")
add(code)
if (arguments.isNotEmpty() && arguments.first() != "--") {
add("--")
}
addAll(arguments)
}
runCompiler(compilerClasspath, compilerArgs)

View File

@@ -0,0 +1,53 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* 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.jvm.compiler;
import com.intellij.DynamicBundle;
import com.intellij.codeInsight.ContainerProvider;
import com.intellij.codeInsight.runner.JavaMainMethodProvider;
import com.intellij.core.JavaCoreApplicationEnvironment;
import com.intellij.lang.MetaLanguage;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.vfs.VirtualFileSystem;
import com.intellij.psi.FileContextProvider;
import com.intellij.psi.augment.PsiAugmentProvider;
import com.intellij.psi.meta.MetaDataContributor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.cli.jvm.modules.CoreJrtFileSystem;
public class KotlinCoreApplicationEnvironment extends JavaCoreApplicationEnvironment {
public static KotlinCoreApplicationEnvironment create(@NotNull Disposable parentDisposable, boolean unitTestMode) {
KotlinCoreApplicationEnvironment environment = new KotlinCoreApplicationEnvironment(parentDisposable, unitTestMode);
registerExtensionPoints();
return environment;
}
private KotlinCoreApplicationEnvironment(@NotNull Disposable parentDisposable, boolean unitTestMode) {
super(parentDisposable, unitTestMode);
}
private static void registerExtensionPoints() {
registerApplicationExtensionPoint(DynamicBundle.LanguageBundleEP.EP_NAME, DynamicBundle.LanguageBundleEP.class);
registerApplicationExtensionPoint(FileContextProvider.EP_NAME, FileContextProvider.class);
registerApplicationExtensionPoint(MetaDataContributor.EP_NAME, MetaDataContributor.class);
registerApplicationExtensionPoint(PsiAugmentProvider.EP_NAME, PsiAugmentProvider.class);
registerApplicationExtensionPoint(JavaMainMethodProvider.EP_NAME, JavaMainMethodProvider.class);
registerApplicationExtensionPoint(ContainerProvider.EP_NAME, ContainerProvider.class);
registerApplicationExtensionPoint(MetaLanguage.EP_NAME, MetaLanguage.class);
IdeaExtensionPoints.INSTANCE.registerVersionSpecificAppExtensionPoints(Extensions.getRootArea());
}
@Nullable
@Override
protected VirtualFileSystem createJrtFileSystem() {
return new CoreJrtFileSystem();
}
}

View File

@@ -0,0 +1,19 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* 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.jvm.compiler
import com.intellij.openapi.project.DumbUtil
@Suppress("UnstableApiUsage")
class KotlinCoreDumbUtil : DumbUtil {
override fun <T : Any?> filterByDumbAwarenessHonoringIgnoring(collection: Collection<T>): List<T> =
when (collection) {
is List<T> -> collection
else -> ArrayList(collection)
}
override fun mayUseIndices(): Boolean = false
}

View File

@@ -488,7 +488,10 @@ class KotlinCoreEnvironment private constructor(
}
}
private fun disposeApplicationEnvironment() {
/**
* This method is also used in Gradle after configuration phase finished.
*/
fun disposeApplicationEnvironment() {
synchronized(APPLICATION_LOCK) {
val environment = ourApplicationEnvironment ?: return
ourApplicationEnvironment = null

View File

@@ -0,0 +1,684 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.cli.jvm.compiler
import com.intellij.codeInsight.ExternalAnnotationsManager
import com.intellij.codeInsight.InferredAnnotationsManager
import com.intellij.core.CoreApplicationEnvironment
import com.intellij.core.CoreJavaFileManager
import com.intellij.core.JavaCoreProjectEnvironment
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.lang.java.JavaParserDefinition
import com.intellij.mock.MockProject
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.TransactionGuard
import com.intellij.openapi.application.TransactionGuardImpl
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.Extensions
import com.intellij.openapi.extensions.ExtensionsArea
import com.intellij.openapi.fileTypes.PlainTextFileType
import com.intellij.openapi.project.DumbUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.*
import com.intellij.openapi.vfs.impl.ZipHandler
import com.intellij.psi.PsiElementFinder
import com.intellij.psi.PsiManager
import com.intellij.psi.impl.JavaClassSupersImpl
import com.intellij.psi.impl.PsiElementFinderImpl
import com.intellij.psi.impl.PsiTreeChangePreprocessor
import com.intellij.psi.impl.file.impl.JavaFileManager
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.JavaClassSupers
import com.intellij.util.io.URLUtil
import com.intellij.util.lang.UrlClassLoader
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.asJava.KotlinAsJavaSupport
import org.jetbrains.kotlin.asJava.LightClassGenerationSupport
import org.jetbrains.kotlin.asJava.classes.FacadeCache
import org.jetbrains.kotlin.asJava.finder.JavaElementFinder
import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
import org.jetbrains.kotlin.cli.common.CliModuleVisibilityManagerImpl
import org.jetbrains.kotlin.cli.common.KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY
import org.jetbrains.kotlin.cli.common.config.ContentRoot
import org.jetbrains.kotlin.cli.common.config.KotlinSourceRoot
import org.jetbrains.kotlin.cli.common.config.kotlinSourceRoots
import org.jetbrains.kotlin.cli.common.extensions.ScriptEvaluationExtension
import org.jetbrains.kotlin.cli.common.extensions.ShellExtension
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.ERROR
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.STRONG_WARNING
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.toBooleanLenient
import org.jetbrains.kotlin.cli.jvm.JvmRuntimeVersionsConsistencyChecker
import org.jetbrains.kotlin.cli.jvm.config.*
import org.jetbrains.kotlin.cli.jvm.index.*
import org.jetbrains.kotlin.cli.jvm.javac.JavacWrapperRegistrar
import org.jetbrains.kotlin.cli.jvm.modules.CliJavaModuleFinder
import org.jetbrains.kotlin.cli.jvm.modules.CliJavaModuleResolver
import org.jetbrains.kotlin.cli.jvm.modules.CoreJrtFileSystem
import org.jetbrains.kotlin.codegen.extensions.ClassBuilderInterceptorExtension
import org.jetbrains.kotlin.codegen.extensions.ExpressionCodegenExtension
import org.jetbrains.kotlin.compiler.plugin.ComponentRegistrar
import org.jetbrains.kotlin.config.APPEND_JAVA_SOURCE_ROOTS_HANDLER_KEY
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.JVMConfigurationKeys
import org.jetbrains.kotlin.config.languageVersionSettings
import org.jetbrains.kotlin.extensions.*
import org.jetbrains.kotlin.extensions.internal.CandidateInterceptor
import org.jetbrains.kotlin.extensions.internal.TypeResolutionInterceptor
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.js.translate.extensions.JsSyntheticTranslateExtension
import org.jetbrains.kotlin.load.kotlin.KotlinBinaryClassCache
import org.jetbrains.kotlin.load.kotlin.MetadataFinderFactory
import org.jetbrains.kotlin.load.kotlin.ModuleVisibilityManager
import org.jetbrains.kotlin.load.kotlin.VirtualFileFinderFactory
import org.jetbrains.kotlin.parsing.KotlinParserDefinition
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.CodeAnalyzerInitializer
import org.jetbrains.kotlin.resolve.ModuleAnnotationsResolver
import org.jetbrains.kotlin.resolve.extensions.ExtraImportsProviderExtension
import org.jetbrains.kotlin.resolve.extensions.SyntheticResolveExtension
import org.jetbrains.kotlin.resolve.jvm.KotlinJavaPsiFacade
import org.jetbrains.kotlin.resolve.jvm.extensions.AnalysisHandlerExtension
import org.jetbrains.kotlin.resolve.jvm.extensions.PackageFragmentProviderExtension
import org.jetbrains.kotlin.resolve.jvm.modules.JavaModuleResolver
import org.jetbrains.kotlin.resolve.lazy.declarations.CliDeclarationProviderFactoryService
import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactoryService
import org.jetbrains.kotlin.utils.PathUtil
import java.io.File
import java.util.zip.ZipFile
class KotlinCoreEnvironment private constructor(
val projectEnvironment: JavaCoreProjectEnvironment,
initialConfiguration: CompilerConfiguration,
configFiles: EnvironmentConfigFiles
) {
class ProjectEnvironment(
disposable: Disposable, applicationEnvironment: KotlinCoreApplicationEnvironment
) :
KotlinCoreProjectEnvironment(disposable, applicationEnvironment) {
private var extensionRegistered = false
override fun preregisterServices() {
registerProjectExtensionPoints(Extensions.getArea(project))
}
fun registerExtensionsFromPlugins(configuration: CompilerConfiguration) {
if (!extensionRegistered) {
registerPluginExtensionPoints(project)
registerExtensionsFromPlugins(project, configuration)
extensionRegistered = true
}
}
override fun registerJavaPsiFacade() {
with(project) {
registerService(
CoreJavaFileManager::class.java,
ServiceManager.getService(this, JavaFileManager::class.java) as CoreJavaFileManager
)
registerKotlinLightClassSupport(project)
registerService(ExternalAnnotationsManager::class.java, MockExternalAnnotationsManager())
registerService(InferredAnnotationsManager::class.java, MockInferredAnnotationsManager())
}
super.registerJavaPsiFacade()
}
}
private val sourceFiles = mutableListOf<KtFile>()
private val rootsIndex: JvmDependenciesDynamicCompoundIndex
private val packagePartProviders = mutableListOf<JvmPackagePartProvider>()
private val classpathRootsResolver: ClasspathRootsResolver
private val initialRoots = ArrayList<JavaRoot>()
val configuration: CompilerConfiguration = initialConfiguration.apply { setupJdkClasspathRoots(configFiles) }.copy()
init {
PersistentFSConstants::class.java.getDeclaredField("ourMaxIntellisenseFileSize")
.apply { isAccessible = true }
.setInt(null, FileUtilRt.LARGE_FOR_CONTENT_LOADING)
val project = projectEnvironment.project
val messageCollector = configuration.get(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY)
(projectEnvironment as? ProjectEnvironment)?.registerExtensionsFromPlugins(configuration)
// otherwise consider that project environment is properly configured before passing to the environment
// TODO: consider some asserts to check important extension points
project.registerService(DeclarationProviderFactoryService::class.java, CliDeclarationProviderFactoryService(sourceFiles))
val isJvm = configFiles == EnvironmentConfigFiles.JVM_CONFIG_FILES
project.registerService(ModuleVisibilityManager::class.java, CliModuleVisibilityManagerImpl(isJvm))
registerProjectServicesForCLI(projectEnvironment)
registerProjectServices(projectEnvironment.project)
for (extension in CompilerConfigurationExtension.getInstances(project)) {
extension.updateConfiguration(configuration)
}
sourceFiles += createKtFiles(project)
collectAdditionalSources(project)
sourceFiles.sortBy { it.virtualFile.path }
val jdkHome = configuration.get(JVMConfigurationKeys.JDK_HOME)
val jrtFileSystem = VirtualFileManager.getInstance().getFileSystem(StandardFileSystems.JRT_PROTOCOL)
val javaModuleFinder = CliJavaModuleFinder(jdkHome?.path?.let { path ->
jrtFileSystem?.findFileByPath(path + URLUtil.JAR_SEPARATOR)
})
val outputDirectory =
configuration.get(JVMConfigurationKeys.MODULES)?.singleOrNull()?.getOutputDirectory()
?: configuration.get(JVMConfigurationKeys.OUTPUT_DIRECTORY)?.absolutePath
classpathRootsResolver = ClasspathRootsResolver(
PsiManager.getInstance(project),
messageCollector,
configuration.getList(JVMConfigurationKeys.ADDITIONAL_JAVA_MODULES),
this::contentRootToVirtualFile,
javaModuleFinder,
!configuration.getBoolean(CLIConfigurationKeys.ALLOW_KOTLIN_PACKAGE),
outputDirectory?.let(this::findLocalFile)
)
val (initialRoots, javaModules) =
classpathRootsResolver.convertClasspathRoots(configuration.getList(CLIConfigurationKeys.CONTENT_ROOTS))
this.initialRoots.addAll(initialRoots)
if (!configuration.getBoolean(JVMConfigurationKeys.SKIP_RUNTIME_VERSION_CHECK) && messageCollector != null) {
JvmRuntimeVersionsConsistencyChecker.checkCompilerClasspathConsistency(
messageCollector,
configuration,
initialRoots.mapNotNull { (file, type) -> if (type == JavaRoot.RootType.BINARY) file else null }
)
}
val (roots, singleJavaFileRoots) =
initialRoots.partition { (file) -> file.isDirectory || file.extension != JavaFileType.DEFAULT_EXTENSION }
// REPL and kapt2 update classpath dynamically
rootsIndex = JvmDependenciesDynamicCompoundIndex().apply {
addIndex(JvmDependenciesIndexImpl(roots))
updateClasspathFromRootsIndex(this)
}
(ServiceManager.getService(project, CoreJavaFileManager::class.java) as KotlinCliJavaFileManagerImpl).initialize(
rootsIndex,
packagePartProviders,
SingleJavaFileRootsIndex(singleJavaFileRoots),
configuration.getBoolean(JVMConfigurationKeys.USE_PSI_CLASS_FILES_READING)
)
project.registerService(
JavaModuleResolver::class.java,
CliJavaModuleResolver(classpathRootsResolver.javaModuleGraph, javaModules, javaModuleFinder.systemModules.toList())
)
val finderFactory = CliVirtualFileFinderFactory(rootsIndex)
project.registerService(MetadataFinderFactory::class.java, finderFactory)
project.registerService(VirtualFileFinderFactory::class.java, finderFactory)
project.putUserData(APPEND_JAVA_SOURCE_ROOTS_HANDLER_KEY, fun(roots: List<File>) {
updateClasspath(roots.map { JavaSourceRoot(it, null) })
})
}
private fun collectAdditionalSources(project: MockProject) {
var unprocessedSources: Collection<KtFile> = sourceFiles
val processedSources = HashSet<KtFile>()
val processedSourcesByExtension = HashMap<CollectAdditionalSourcesExtension, Collection<KtFile>>()
// repeat feeding extensions with sources while new sources a being added
var sourceCollectionIterations = 0
while (unprocessedSources.isNotEmpty()) {
if (sourceCollectionIterations++ > 10) { // TODO: consider using some appropriate global constant
throw IllegalStateException("Unable to collect additional sources in reasonable number of iterations")
}
processedSources.addAll(unprocessedSources)
val allNewSources = ArrayList<KtFile>()
for (extension in CollectAdditionalSourcesExtension.getInstances(project)) {
// do not feed the extension with the sources it returned on the previous iteration
val sourcesToProcess = unprocessedSources - (processedSourcesByExtension[extension] ?: emptyList())
val newSources = extension.collectAdditionalSourcesAndUpdateConfiguration(sourcesToProcess, configuration, project)
if (newSources.isNotEmpty()) {
allNewSources.addAll(newSources)
processedSourcesByExtension[extension] = newSources
}
}
unprocessedSources = allNewSources.filterNot { processedSources.contains(it) }.distinct()
sourceFiles += unprocessedSources
}
}
fun addKotlinSourceRoots(rootDirs: List<File>) {
val roots = rootDirs.map { KotlinSourceRoot(it.absolutePath, isCommon = false) }
sourceFiles += createSourceFilesFromSourceRoots(configuration, project, roots)
}
fun createPackagePartProvider(scope: GlobalSearchScope): JvmPackagePartProvider {
return JvmPackagePartProvider(configuration.languageVersionSettings, scope).apply {
addRoots(initialRoots, configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY))
packagePartProviders += this
(ModuleAnnotationsResolver.getInstance(project) as CliModuleAnnotationsResolver).addPackagePartProvider(this)
}
}
private val VirtualFile.javaFiles: List<VirtualFile>
get() = mutableListOf<VirtualFile>().apply {
VfsUtilCore.processFilesRecursively(this@javaFiles) { file ->
if (file.fileType == JavaFileType.INSTANCE) {
add(file)
}
true
}
}
private val allJavaFiles: List<File>
get() = configuration.javaSourceRoots
.mapNotNull(this::findLocalFile)
.flatMap { it.javaFiles }
.map { File(it.canonicalPath) }
fun registerJavac(
javaFiles: List<File> = allJavaFiles,
kotlinFiles: List<KtFile> = sourceFiles,
arguments: Array<String>? = null,
bootClasspath: List<File>? = null,
sourcePath: List<File>? = null
): Boolean {
return JavacWrapperRegistrar.registerJavac(
projectEnvironment.project, configuration, javaFiles, kotlinFiles, arguments, bootClasspath, sourcePath,
LightClassGenerationSupport.getInstance(project), packagePartProviders
)
}
private val applicationEnvironment: CoreApplicationEnvironment
get() = projectEnvironment.environment
val project: Project
get() = projectEnvironment.project
internal fun countLinesOfCode(sourceFiles: List<KtFile>): Int =
sourceFiles.sumBy { sourceFile ->
val text = sourceFile.text
StringUtil.getLineBreakCount(text) + (if (StringUtil.endsWithLineBreak(text)) 0 else 1)
}
private fun updateClasspathFromRootsIndex(index: JvmDependenciesIndex) {
index.indexedRoots.forEach {
projectEnvironment.addSourcesToClasspath(it.file)
}
}
fun updateClasspath(contentRoots: List<ContentRoot>): List<File>? {
// TODO: add new Java modules to CliJavaModuleResolver
val newRoots = classpathRootsResolver.convertClasspathRoots(contentRoots).roots
if (packagePartProviders.isEmpty()) {
initialRoots.addAll(newRoots)
} else {
for (packagePartProvider in packagePartProviders) {
packagePartProvider.addRoots(newRoots, configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY))
}
}
return rootsIndex.addNewIndexForRoots(newRoots)?.let { newIndex ->
updateClasspathFromRootsIndex(newIndex)
newIndex.indexedRoots.mapNotNull { (file) ->
VfsUtilCore.virtualToIoFile(VfsUtilCore.getVirtualFileForJar(file) ?: file)
}.toList()
}.orEmpty()
}
private fun contentRootToVirtualFile(root: JvmContentRoot): VirtualFile? =
when (root) {
is JvmClasspathRoot ->
if (root.file.isFile) findJarRoot(root.file) else findExistingRoot(root, "Classpath entry")
is JvmModulePathRoot ->
if (root.file.isFile) findJarRoot(root.file) else findExistingRoot(root, "Java module root")
is JavaSourceRoot ->
findExistingRoot(root, "Java source root")
else ->
throw IllegalStateException("Unexpected root: $root")
}
internal fun findLocalFile(path: String): VirtualFile? =
applicationEnvironment.localFileSystem.findFileByPath(path)
private fun findExistingRoot(root: JvmContentRoot, rootDescription: String): VirtualFile? {
return findLocalFile(root.file.absolutePath).also {
if (it == null) {
report(STRONG_WARNING, "$rootDescription points to a non-existent location: ${root.file}")
}
}
}
private fun findJarRoot(file: File): VirtualFile? =
applicationEnvironment.jarFileSystem.findFileByPath("$file${URLUtil.JAR_SEPARATOR}")
private fun getSourceRootsCheckingForDuplicates(): List<KotlinSourceRoot> {
val uniqueSourceRoots = hashSetOf<String>()
val result = mutableListOf<KotlinSourceRoot>()
for (root in configuration.kotlinSourceRoots) {
if (!uniqueSourceRoots.add(root.path)) {
report(STRONG_WARNING, "Duplicate source root: ${root.path}")
}
result.add(root)
}
return result
}
fun getSourceFiles(): List<KtFile> = sourceFiles
private fun createKtFiles(project: Project): List<KtFile> =
createSourceFilesFromSourceRoots(configuration, project, getSourceRootsCheckingForDuplicates())
internal fun report(severity: CompilerMessageSeverity, message: String) = configuration.report(severity, message)
companion object {
private val LOG = Logger.getInstance(KotlinCoreEnvironment::class.java)
private val APPLICATION_LOCK = Object()
private var ourApplicationEnvironment: KotlinCoreApplicationEnvironment? = null
private var ourProjectCount = 0
@JvmStatic
fun createForProduction(
parentDisposable: Disposable, configuration: CompilerConfiguration, configFiles: EnvironmentConfigFiles
): KotlinCoreEnvironment {
setupIdeaStandaloneExecution()
val appEnv = getOrCreateApplicationEnvironmentForProduction(parentDisposable, configuration)
val projectEnv = ProjectEnvironment(parentDisposable, appEnv)
val environment = KotlinCoreEnvironment(projectEnv, configuration, configFiles)
synchronized(APPLICATION_LOCK) {
ourProjectCount++
}
return environment
}
@JvmStatic
fun createForProduction(
projectEnvironment: JavaCoreProjectEnvironment, configuration: CompilerConfiguration, configFiles: EnvironmentConfigFiles
): KotlinCoreEnvironment {
val environment = KotlinCoreEnvironment(projectEnvironment, configuration, configFiles)
if (projectEnvironment.environment == applicationEnvironment) {
// accounting for core environment disposing
synchronized(APPLICATION_LOCK) {
ourProjectCount++
}
}
return environment
}
@TestOnly
@JvmStatic
fun createForTests(
parentDisposable: Disposable, initialConfiguration: CompilerConfiguration, extensionConfigs: EnvironmentConfigFiles
): KotlinCoreEnvironment {
val configuration = initialConfiguration.copy()
// Tests are supposed to create a single project and dispose it right after use
val appEnv = createApplicationEnvironment(parentDisposable, configuration, unitTestMode = true)
val projectEnv = ProjectEnvironment(parentDisposable, appEnv)
return KotlinCoreEnvironment(projectEnv, configuration, extensionConfigs)
}
// used in the daemon for jar cache cleanup
val applicationEnvironment: KotlinCoreApplicationEnvironment? get() = ourApplicationEnvironment
fun getOrCreateApplicationEnvironmentForProduction(
parentDisposable: Disposable, configuration: CompilerConfiguration
): KotlinCoreApplicationEnvironment {
synchronized(APPLICATION_LOCK) {
if (ourApplicationEnvironment == null) {
val disposable = Disposer.newDisposable()
ourApplicationEnvironment = createApplicationEnvironment(disposable, configuration, unitTestMode = false)
ourProjectCount = 0
Disposer.register(disposable, Disposable {
synchronized(APPLICATION_LOCK) {
ourApplicationEnvironment = null
}
})
}
// Disposing of the environment is unsafe in production then parallel builds are enabled, but turning it off universally
// breaks a lot of tests, therefore it is disabled for production and enabled for tests
if (System.getProperty(KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY).toBooleanLenient() != true) {
// JPS may run many instances of the compiler in parallel (there's an option for compiling independent modules in parallel in IntelliJ)
// All projects share the same ApplicationEnvironment, and when the last project is disposed, the ApplicationEnvironment is disposed as well
Disposer.register(parentDisposable, Disposable {
synchronized(APPLICATION_LOCK) {
if (--ourProjectCount <= 0) {
disposeApplicationEnvironment()
}
}
})
}
return ourApplicationEnvironment!!
}
}
private fun disposeApplicationEnvironment() {
synchronized(APPLICATION_LOCK) {
val environment = ourApplicationEnvironment ?: return
ourApplicationEnvironment = null
Disposer.dispose(environment.parentDisposable)
ZipHandler.clearFileAccessorCache()
}
}
private fun createApplicationEnvironment(
parentDisposable: Disposable, configuration: CompilerConfiguration, unitTestMode: Boolean
): KotlinCoreApplicationEnvironment {
val applicationEnvironment = KotlinCoreApplicationEnvironment.create(parentDisposable, unitTestMode)
registerApplicationExtensionPointsAndExtensionsFrom(configuration, "extensions/compiler.xml")
registerApplicationExtensionPointsAndExtensionsFrom(configuration, "extensions/core.xml")
registerApplicationServicesForCLI(applicationEnvironment)
registerApplicationServices(applicationEnvironment)
return applicationEnvironment
}
private fun registerApplicationExtensionPointsAndExtensionsFrom(configuration: CompilerConfiguration, configFilePath: String) {
fun File.hasConfigFile(configFile: String): Boolean =
if (isDirectory) File(this, "META-INF" + File.separator + configFile).exists()
else try {
ZipFile(this).use {
it.getEntry("META-INF/$configFile") != null
}
} catch (e: Throwable) {
false
}
val pluginRoot: File =
configuration.get(CLIConfigurationKeys.INTELLIJ_PLUGIN_ROOT)?.let(::File)
?: PathUtil.getResourcePathForClass(this::class.java).takeIf { it.hasConfigFile(configFilePath) }
// hack for load extensions when compiler run directly from project directory (e.g. in tests)
?: File("compiler/cli/cli-common/resources").takeIf { it.hasConfigFile(configFilePath) }
?: throw IllegalStateException(
"Unable to find extension point configuration $configFilePath " +
"(cp:\n ${(Thread.currentThread().contextClassLoader as? UrlClassLoader)?.urls?.joinToString("\n ") { it.file }})"
)
registerExtensionPointAndExtensionsEx(pluginRoot, configFilePath, Extensions.getRootArea())
}
@JvmStatic
@Suppress("MemberVisibilityCanPrivate") // made public for CLI Android Lint
fun registerPluginExtensionPoints(project: MockProject) {
ExpressionCodegenExtension.registerExtensionPoint(project)
SyntheticResolveExtension.registerExtensionPoint(project)
ClassBuilderInterceptorExtension.registerExtensionPoint(project)
AnalysisHandlerExtension.registerExtensionPoint(project)
PackageFragmentProviderExtension.registerExtensionPoint(project)
StorageComponentContainerContributor.registerExtensionPoint(project)
DeclarationAttributeAltererExtension.registerExtensionPoint(project)
PreprocessedVirtualFileFactoryExtension.registerExtensionPoint(project)
JsSyntheticTranslateExtension.registerExtensionPoint(project)
CompilerConfigurationExtension.registerExtensionPoint(project)
CollectAdditionalSourcesExtension.registerExtensionPoint(project)
ExtraImportsProviderExtension.registerExtensionPoint(project)
IrGenerationExtension.registerExtensionPoint(project)
ScriptEvaluationExtension.registerExtensionPoint(project)
ShellExtension.registerExtensionPoint(project)
TypeResolutionInterceptor.registerExtensionPoint(project)
CandidateInterceptor.registerExtensionPoint(project)
}
internal fun registerExtensionsFromPlugins(project: MockProject, configuration: CompilerConfiguration) {
val messageCollector = configuration.get(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY)
for (registrar in configuration.getList(ComponentRegistrar.PLUGIN_COMPONENT_REGISTRARS)) {
try {
registrar.registerProjectComponents(project, configuration)
} catch (e: AbstractMethodError) {
val message = "The provided plugin ${registrar.javaClass.name} is not compatible with this version of compiler"
// Since the scripting plugin is often discovered in the compiler environment, it is often taken from the incompatible
// location, and in many cases this is not a fatal error, therefore strong warning is generated instead of exception
if (registrar.javaClass.simpleName == "ScriptingCompilerConfigurationComponentRegistrar") {
messageCollector?.report(STRONG_WARNING, "Default scripting plugin is disabled: $message")
} else {
throw IllegalStateException(message, e)
}
}
}
}
private fun registerApplicationServicesForCLI(applicationEnvironment: KotlinCoreApplicationEnvironment) {
// ability to get text from annotations xml files
applicationEnvironment.registerFileType(PlainTextFileType.INSTANCE, "xml")
applicationEnvironment.registerParserDefinition(JavaParserDefinition())
}
// made public for Upsource
@Suppress("MemberVisibilityCanBePrivate")
@JvmStatic
fun registerApplicationServices(applicationEnvironment: KotlinCoreApplicationEnvironment) {
with(applicationEnvironment) {
registerFileType(KotlinFileType.INSTANCE, "kt")
registerFileType(KotlinFileType.INSTANCE, KotlinParserDefinition.STD_SCRIPT_SUFFIX)
registerParserDefinition(KotlinParserDefinition())
application.registerService(KotlinBinaryClassCache::class.java, KotlinBinaryClassCache())
application.registerService(JavaClassSupers::class.java, JavaClassSupersImpl::class.java)
application.registerService(TransactionGuard::class.java, TransactionGuardImpl::class.java)
}
}
@JvmStatic
fun registerProjectExtensionPoints(area: ExtensionsArea) {
CoreApplicationEnvironment.registerExtensionPoint(
area, PsiTreeChangePreprocessor.EP_NAME, PsiTreeChangePreprocessor::class.java
)
CoreApplicationEnvironment.registerExtensionPoint(area, PsiElementFinder.EP_NAME, PsiElementFinder::class.java)
IdeaExtensionPoints.registerVersionSpecificProjectExtensionPoints(area)
}
// made public for Upsource
@JvmStatic
@Deprecated("Use registerProjectServices(project) instead.", ReplaceWith("registerProjectServices(projectEnvironment.project)"))
fun registerProjectServices(projectEnvironment: JavaCoreProjectEnvironment, messageCollector: MessageCollector?) {
registerProjectServices(projectEnvironment.project)
}
// made public for Android Lint
@JvmStatic
fun registerProjectServices(project: MockProject) {
with(project) {
registerService(KotlinJavaPsiFacade::class.java, KotlinJavaPsiFacade(this))
registerService(FacadeCache::class.java, FacadeCache(this))
registerService(ModuleAnnotationsResolver::class.java, CliModuleAnnotationsResolver())
}
}
private fun registerProjectServicesForCLI(@Suppress("UNUSED_PARAMETER") projectEnvironment: JavaCoreProjectEnvironment) {
/**
* Note that Kapt may restart code analysis process, and CLI services should be aware of that.
* Use PsiManager.getModificationTracker() to ensure that all the data you cached is still valid.
*/
}
// made public for Android Lint
@JvmStatic
fun registerKotlinLightClassSupport(project: MockProject) {
with(project) {
val traceHolder = CliTraceHolder()
val cliLightClassGenerationSupport = CliLightClassGenerationSupport(traceHolder)
val kotlinAsJavaSupport = CliKotlinAsJavaSupport(this, traceHolder)
registerService(LightClassGenerationSupport::class.java, cliLightClassGenerationSupport)
registerService(CliLightClassGenerationSupport::class.java, cliLightClassGenerationSupport)
registerService(KotlinAsJavaSupport::class.java, kotlinAsJavaSupport)
registerService(CodeAnalyzerInitializer::class.java, traceHolder)
if (getService(DumbUtil::class.java) == null) {
@Suppress("UnstableApiUsage")
registerService(DumbUtil::class.java, KotlinCoreDumbUtil())
}
val area = Extensions.getArea(this)
area.getExtensionPoint(PsiElementFinder.EP_NAME).registerExtension(JavaElementFinder(this, kotlinAsJavaSupport))
area.getExtensionPoint(PsiElementFinder.EP_NAME).registerExtension(
PsiElementFinderImpl(this, ServiceManager.getService(this, JavaFileManager::class.java))
)
}
}
private fun CompilerConfiguration.setupJdkClasspathRoots(configFiles: EnvironmentConfigFiles) {
if (getBoolean(JVMConfigurationKeys.NO_JDK)) return
val jvmTarget = configFiles == EnvironmentConfigFiles.JVM_CONFIG_FILES
if (!jvmTarget) return
val jdkHome = get(JVMConfigurationKeys.JDK_HOME)
val (javaRoot, classesRoots) = if (jdkHome == null) {
val javaHome = File(System.getProperty("java.home"))
put(JVMConfigurationKeys.JDK_HOME, javaHome)
javaHome to PathUtil.getJdkClassesRootsFromCurrentJre()
} else {
jdkHome to PathUtil.getJdkClassesRoots(jdkHome)
}
if (!CoreJrtFileSystem.isModularJdk(javaRoot)) {
if (classesRoots.isEmpty()) {
report(ERROR, "No class roots are found in the JDK path: $javaRoot")
} else {
addJvmSdkRoots(classesRoots)
}
}
}
}
}

View File

@@ -49,6 +49,24 @@ fun CompilerConfiguration.setupJvmSpecificArguments(arguments: K2JVMCompilerArgu
}
}
if (arguments.stringConcat != null) {
val runtimeStringConcat = JvmStringConcat.fromString(arguments.stringConcat!!)
if (runtimeStringConcat != null) {
put(JVMConfigurationKeys.STRING_CONCAT, runtimeStringConcat)
if (jvmTarget.bytecodeVersion < JvmTarget.JVM_9.bytecodeVersion && runtimeStringConcat != JvmStringConcat.INLINE) {
messageCollector.report(
WARNING,
"`-Xstring-concat=${arguments.stringConcat}` does nothing with JVM target `${jvmTarget.description}`."
)
}
} else {
messageCollector.report(
ERROR, "Unknown `string-concat` mode: ${arguments.jvmTarget}\n" +
"Supported versions: ${JvmStringConcat.values().joinToString { it.name.toLowerCase() }}"
)
}
}
addAll(JVMConfigurationKeys.ADDITIONAL_JAVA_MODULES, arguments.additionalJavaModules?.asList())
}

View File

@@ -111,6 +111,9 @@ public class JVMConfigurationKeys {
public static final CompilerConfigurationKey<Boolean> EMIT_JVM_TYPE_ANNOTATIONS =
CompilerConfigurationKey.create("Emit JVM type annotations in bytecode");
public static final CompilerConfigurationKey<JvmStringConcat> STRING_CONCAT =
CompilerConfigurationKey.create("Specifies string concatenation scheme");
public static final CompilerConfigurationKey<List<String>> KLIB_PATHS =
CompilerConfigurationKey.create("Paths to .klib libraries");

View File

@@ -0,0 +1,20 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* 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.config
enum class JvmStringConcat(val description: String) {
INLINE("inline"),
INDY_WITH_CONSTANTS("indy-with-constants"), // makeConcatWithConstants
INDY("indy"); // makeConcat
val isDynamic
get() = this != INLINE
companion object {
@JvmStatic
fun fromString(string: String) = values().find { it.description == string }
}
}

View File

@@ -28,6 +28,7 @@ enum class JvmTarget(override val description: String) : TargetPlatformVersion {
JVM_12("12"),
JVM_13("13"),
JVM_14("14"),
JVM_15("15"),
;
val bytecodeVersion: Int by lazy {
@@ -40,6 +41,7 @@ enum class JvmTarget(override val description: String) : TargetPlatformVersion {
JVM_12 -> Opcodes.V12
JVM_13 -> Opcodes.V12 + 1
JVM_14 -> Opcodes.V12 + 2
JVM_15 -> Opcodes.V12 + 3
}
}

View File

@@ -25,6 +25,7 @@ import java.io.File
import java.io.Serializable
import java.net.SocketException
import java.nio.channels.ClosedChannelException
import java.nio.file.Files
import java.rmi.ConnectException
import java.rmi.ConnectIOException
import java.rmi.UnmarshalException
@@ -422,7 +423,7 @@ class KotlinCompilerClient : KotlinCompilerDaemonClient {
report: (DaemonReportCategory, String) -> Unit
): Deferred<Pair<CompileServiceAsync?, DaemonJVMOptions>> = GlobalScope.async {
registryDir.mkdirs()
val timestampMarker = createTempFile("kotlin-daemon-client-tsmarker", directory = registryDir)
val timestampMarker = Files.createTempFile(registryDir.toPath(), "kotlin-daemon-client-tsmarker", null).toFile()
val aliveWithMetadata = try {
walkDaemonsAsync(registryDir, compilerId, timestampMarker, report = report)
} finally {

View File

@@ -26,6 +26,7 @@ import java.io.File
import java.io.OutputStream
import java.io.PrintStream
import java.net.SocketException
import java.nio.file.Files
import java.rmi.ConnectException
import java.rmi.ConnectIOException
import java.rmi.UnmarshalException
@@ -347,7 +348,7 @@ object KotlinCompilerClient {
private fun tryFindSuitableDaemonOrNewOpts(registryDir: File, compilerId: CompilerId, daemonJVMOptions: DaemonJVMOptions, report: (DaemonReportCategory, String) -> Unit): Pair<CompileService?, DaemonJVMOptions> {
registryDir.mkdirs()
val timestampMarker = createTempFile("kotlin-daemon-client-tsmarker", directory = registryDir)
val timestampMarker = Files.createTempFile(registryDir.toPath(), "kotlin-daemon-client-tsmarker", null).toFile()
val aliveWithMetadata = try {
walkDaemons(registryDir, compilerId, timestampMarker, report = report).toList()
}

View File

@@ -17,6 +17,7 @@
package org.jetbrains.kotlin.daemon.common
import java.io.File
import java.nio.file.Files
import java.rmi.registry.LocateRegistry
@@ -106,7 +107,12 @@ private inline fun tryConnectToDaemon(port: Int, report: (DaemonReportCategory,
private const val validFlagFileKeywordChars = "abcdefghijklmnopqrstuvwxyz0123456789-_"
fun makeAutodeletingFlagFile(keyword: String = "compiler-client", baseDir: File? = null): File {
val flagFile = File.createTempFile("kotlin-${keyword.filter { validFlagFileKeywordChars.contains(it.toLowerCase()) }}-", "-is-running", baseDir?.takeIf { it.isDirectory && it.exists() })
val prefix = "kotlin-${keyword.filter { validFlagFileKeywordChars.contains(it.toLowerCase()) }}-"
val flagFile = if (baseDir?.isDirectory == true)
Files.createTempFile(baseDir.toPath(), prefix, "-is-running").toFile()
else
Files.createTempFile(prefix, "-is-running").toFile()
flagFile.deleteOnExit()
return flagFile
}

View File

@@ -920,6 +920,11 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirOldFronte
runTest("compiler/testData/diagnostics/tests/annotations/deprecatedRepeatable.kt");
}
@TestMetadata("dontReportWarningAboutChangingExecutionOrderForVararg.kt")
public void testDontReportWarningAboutChangingExecutionOrderForVararg() throws Exception {
runTest("compiler/testData/diagnostics/tests/annotations/dontReportWarningAboutChangingExecutionOrderForVararg.kt");
}
@TestMetadata("extensionFunctionType.kt")
public void testExtensionFunctionType() throws Exception {
runTest("compiler/testData/diagnostics/tests/annotations/extensionFunctionType.kt");
@@ -3369,6 +3374,16 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirOldFronte
runTest("compiler/testData/diagnostics/tests/checkArguments/booleanExpressions.kt");
}
@TestMetadata("kt17691.kt")
public void testKt17691() throws Exception {
runTest("compiler/testData/diagnostics/tests/checkArguments/kt17691.kt");
}
@TestMetadata("kt17691WithEnabledFeature.kt")
public void testKt17691WithEnabledFeature() throws Exception {
runTest("compiler/testData/diagnostics/tests/checkArguments/kt17691WithEnabledFeature.kt");
}
@TestMetadata("kt1897_diagnostic_part.kt")
public void testKt1897_diagnostic_part() throws Exception {
runTest("compiler/testData/diagnostics/tests/checkArguments/kt1897_diagnostic_part.kt");
@@ -7612,6 +7627,16 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirOldFronte
runTest("compiler/testData/diagnostics/tests/enum/SecondaryConstructorCall.kt");
}
@TestMetadata("secondaryConstructorWithoutDelegatingToPrimaryOne.kt")
public void testSecondaryConstructorWithoutDelegatingToPrimaryOne() throws Exception {
runTest("compiler/testData/diagnostics/tests/enum/secondaryConstructorWithoutDelegatingToPrimaryOne.kt");
}
@TestMetadata("secondaryConstructorWithoutDelegatingToPrimaryOneWithEnabledFeature.kt")
public void testSecondaryConstructorWithoutDelegatingToPrimaryOneWithEnabledFeature() throws Exception {
runTest("compiler/testData/diagnostics/tests/enum/secondaryConstructorWithoutDelegatingToPrimaryOneWithEnabledFeature.kt");
}
@TestMetadata("starImportNestedClassAndEntries.kt")
public void testStarImportNestedClassAndEntries() throws Exception {
runTest("compiler/testData/diagnostics/tests/enum/starImportNestedClassAndEntries.kt");
@@ -10684,6 +10709,16 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirOldFronte
runTest("compiler/testData/diagnostics/tests/inference/capturedTypes/notApproximateWhenCopyDescriptors.kt");
}
@TestMetadata("nullableCaptruredTypeAgainstNullableVariable.kt")
public void testNullableCaptruredTypeAgainstNullableVariable() throws Exception {
runTest("compiler/testData/diagnostics/tests/inference/capturedTypes/nullableCaptruredTypeAgainstNullableVariable.kt");
}
@TestMetadata("nullableCaptruredTypeAgainstNullableVariableWithDisabledComplatibilityFlag.kt")
public void testNullableCaptruredTypeAgainstNullableVariableWithDisabledComplatibilityFlag() throws Exception {
runTest("compiler/testData/diagnostics/tests/inference/capturedTypes/nullableCaptruredTypeAgainstNullableVariableWithDisabledComplatibilityFlag.kt");
}
@TestMetadata("overApproximationForInCaptured.kt")
public void testOverApproximationForInCaptured() throws Exception {
runTest("compiler/testData/diagnostics/tests/inference/capturedTypes/overApproximationForInCaptured.kt");
@@ -11055,6 +11090,11 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirOldFronte
runTest("compiler/testData/diagnostics/tests/inference/completion/postponedArgumentsAnalysis/callableReferences.kt");
}
@TestMetadata("fixingVariableDuringAddingConstraintForFirstPosponedArgument.kt")
public void testFixingVariableDuringAddingConstraintForFirstPosponedArgument() throws Exception {
runTest("compiler/testData/diagnostics/tests/inference/completion/postponedArgumentsAnalysis/fixingVariableDuringAddingConstraintForFirstPosponedArgument.kt");
}
@TestMetadata("lackOfDeepIncorporation.kt")
public void testLackOfDeepIncorporation() throws Exception {
runTest("compiler/testData/diagnostics/tests/inference/completion/postponedArgumentsAnalysis/lackOfDeepIncorporation.kt");
@@ -11965,6 +12005,11 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirOldFronte
runTest("compiler/testData/diagnostics/tests/inference/regressions/kt41386.kt");
}
@TestMetadata("kt41394.kt")
public void testKt41394() throws Exception {
runTest("compiler/testData/diagnostics/tests/inference/regressions/kt41394.kt");
}
@TestMetadata("kt4420.kt")
public void testKt4420() throws Exception {
runTest("compiler/testData/diagnostics/tests/inference/regressions/kt4420.kt");
@@ -12048,6 +12093,11 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirOldFronte
runTest("compiler/testData/diagnostics/tests/inference/reportingImprovements/inferTypeFromUnresolvedArgument.kt");
}
@TestMetadata("kt42620.kt")
public void testKt42620() throws Exception {
runTest("compiler/testData/diagnostics/tests/inference/reportingImprovements/kt42620.kt");
}
@TestMetadata("NoAmbiguityForDifferentFunctionTypes.kt")
public void testNoAmbiguityForDifferentFunctionTypes() throws Exception {
runTest("compiler/testData/diagnostics/tests/inference/reportingImprovements/NoAmbiguityForDifferentFunctionTypes.kt");
@@ -12406,6 +12456,11 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirOldFronte
runTest("compiler/testData/diagnostics/tests/inline/recursion.kt");
}
@TestMetadata("returnedAnonymousObjects.kt")
public void testReturnedAnonymousObjects() throws Exception {
runTest("compiler/testData/diagnostics/tests/inline/returnedAnonymousObjects.kt");
}
@TestMetadata("returns.kt")
public void testReturns() throws Exception {
runTest("compiler/testData/diagnostics/tests/inline/returns.kt");
@@ -19167,6 +19222,16 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirOldFronte
runTest("compiler/testData/diagnostics/tests/resolve/typeParameterInDefaultValueInLocalFunction.kt");
}
@TestMetadata("underscoreInCatchBlock.kt")
public void testUnderscoreInCatchBlock() throws Exception {
runTest("compiler/testData/diagnostics/tests/resolve/underscoreInCatchBlock.kt");
}
@TestMetadata("underscoreInCatchBlockWithEnabledFeature.kt")
public void testUnderscoreInCatchBlockWithEnabledFeature() throws Exception {
runTest("compiler/testData/diagnostics/tests/resolve/underscoreInCatchBlockWithEnabledFeature.kt");
}
@TestMetadata("wrongNumberOfTypeArguments.kt")
public void testWrongNumberOfTypeArguments() throws Exception {
runTest("compiler/testData/diagnostics/tests/resolve/wrongNumberOfTypeArguments.kt");
@@ -24205,6 +24270,11 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirOldFronte
runTest("compiler/testData/diagnostics/tests/typeParameters/implicitNothingInReturnPosition.kt");
}
@TestMetadata("implicitNothingOfJavaCallAgainstNotNothingExpectedType.kt")
public void testImplicitNothingOfJavaCallAgainstNotNothingExpectedType() throws Exception {
runTest("compiler/testData/diagnostics/tests/typeParameters/implicitNothingOfJavaCallAgainstNotNothingExpectedType.kt");
}
@TestMetadata("implicitNothingOnDelegates.kt")
public void testImplicitNothingOnDelegates() throws Exception {
runTest("compiler/testData/diagnostics/tests/typeParameters/implicitNothingOnDelegates.kt");
@@ -24860,6 +24930,11 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirOldFronte
runTest("compiler/testData/diagnostics/tests/varargs/AmbiguousVararg.kt");
}
@TestMetadata("assignArrayToVararagInNamedFormWithInference.kt")
public void testAssignArrayToVararagInNamedFormWithInference() throws Exception {
runTest("compiler/testData/diagnostics/tests/varargs/assignArrayToVararagInNamedFormWithInference.kt");
}
@TestMetadata("assignArrayToVararagInNamedForm_1_3.kt")
public void testAssignArrayToVararagInNamedForm_1_3() throws Exception {
runTest("compiler/testData/diagnostics/tests/varargs/assignArrayToVararagInNamedForm_1_3.kt");
@@ -25153,6 +25228,21 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirOldFronte
public void testAllFilesPresentInVisibility() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/diagnostics/tests/visibility"), Pattern.compile("^(.+)\\.kt$"), Pattern.compile("^(.+)\\.fir\\.kts?$"), true);
}
@TestMetadata("invisibleSetterOfJavaClass.kt")
public void testInvisibleSetterOfJavaClass() throws Exception {
runTest("compiler/testData/diagnostics/tests/visibility/invisibleSetterOfJavaClass.kt");
}
@TestMetadata("invisibleSetterOfJavaClassWithDisabledFeature.kt")
public void testInvisibleSetterOfJavaClassWithDisabledFeature() throws Exception {
runTest("compiler/testData/diagnostics/tests/visibility/invisibleSetterOfJavaClassWithDisabledFeature.kt");
}
@TestMetadata("lackOfInvisibleSetterOfJavaClassInSamePackage.kt")
public void testLackOfInvisibleSetterOfJavaClassInSamePackage() throws Exception {
runTest("compiler/testData/diagnostics/tests/visibility/lackOfInvisibleSetterOfJavaClassInSamePackage.kt");
}
}
@TestMetadata("compiler/testData/diagnostics/tests/when")

View File

@@ -493,6 +493,11 @@ public class FirOldFrontendDiagnosticsTestWithStdlibGenerated extends AbstractFi
runTest("compiler/testData/diagnostics/testsWithStdLib/annotations/jvmDefault/javaOverride.kt");
}
@TestMetadata("javaOverrideAll.kt")
public void testJavaOverrideAll() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/annotations/jvmDefault/javaOverrideAll.kt");
}
@TestMetadata("jvmDefaultInInheritance.kt")
public void testJvmDefaultInInheritance() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/annotations/jvmDefault/jvmDefaultInInheritance.kt");
@@ -799,6 +804,11 @@ public class FirOldFrontendDiagnosticsTestWithStdlibGenerated extends AbstractFi
runTest("compiler/testData/diagnostics/testsWithStdLib/annotations/jvmStatic/mainInObject.kt");
}
@TestMetadata("privateCompanionObject.kt")
public void testPrivateCompanionObject() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/annotations/jvmStatic/privateCompanionObject.kt");
}
@TestMetadata("property.kt")
public void testProperty() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/annotations/jvmStatic/property.kt");
@@ -2998,6 +3008,11 @@ public class FirOldFrontendDiagnosticsTestWithStdlibGenerated extends AbstractFi
runTest("compiler/testData/diagnostics/testsWithStdLib/inference/kt38801.kt");
}
@TestMetadata("kt42620.kt")
public void testKt42620() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/inference/kt42620.kt");
}
@TestMetadata("kt4975.kt")
public void testKt4975() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/inference/kt4975.kt");
@@ -3008,6 +3023,29 @@ public class FirOldFrontendDiagnosticsTestWithStdlibGenerated extends AbstractFi
runTest("compiler/testData/diagnostics/testsWithStdLib/inference/recursiveFlexibleAssertions.kt");
}
@TestMetadata("compiler/testData/diagnostics/testsWithStdLib/inference/addEqualityConstraintsWithoutSubtyping")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public static class AddEqualityConstraintsWithoutSubtyping extends AbstractFirOldFrontendDiagnosticsTestWithStdlib {
private void runTest(String testDataFilePath) throws Exception {
KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
}
public void testAllFilesPresentInAddEqualityConstraintsWithoutSubtyping() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/diagnostics/testsWithStdLib/inference/addEqualityConstraintsWithoutSubtyping"), Pattern.compile("^(.+)\\.kt$"), Pattern.compile("^(.+)\\.fir\\.kts?$"), true);
}
@TestMetadata("kt41741.kt")
public void testKt41741() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/inference/addEqualityConstraintsWithoutSubtyping/kt41741.kt");
}
@TestMetadata("kt42195.kt")
public void testKt42195() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/inference/addEqualityConstraintsWithoutSubtyping/kt42195.kt");
}
}
@TestMetadata("compiler/testData/diagnostics/testsWithStdLib/inference/annotationsForResolve")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
@@ -3219,6 +3257,49 @@ public class FirOldFrontendDiagnosticsTestWithStdlibGenerated extends AbstractFi
public void testSuspendFunctions() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/inference/completion/postponedArgumentsAnalysis/suspendFunctions.kt");
}
@TestMetadata("compiler/testData/diagnostics/testsWithStdLib/inference/completion/postponedArgumentsAnalysis/performance")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public static class Performance extends AbstractFirOldFrontendDiagnosticsTestWithStdlib {
private void runTest(String testDataFilePath) throws Exception {
KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
}
public void testAllFilesPresentInPerformance() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/diagnostics/testsWithStdLib/inference/completion/postponedArgumentsAnalysis/performance"), Pattern.compile("^(.+)\\.kt$"), Pattern.compile("^(.+)\\.fir\\.kts?$"), true);
}
@TestMetadata("reuseBuiltFunctionalTypesForIdLambdas.kt")
public void testReuseBuiltFunctionalTypesForIdLambdas() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/inference/completion/postponedArgumentsAnalysis/performance/reuseBuiltFunctionalTypesForIdLambdas.kt");
}
@TestMetadata("reuseBuiltFunctionalTypesForLambdas.kt")
public void testReuseBuiltFunctionalTypesForLambdas() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/inference/completion/postponedArgumentsAnalysis/performance/reuseBuiltFunctionalTypesForLambdas.kt");
}
@TestMetadata("reuseBuiltFunctionalTypesForPairOfLambdas.kt")
public void testReuseBuiltFunctionalTypesForPairOfLambdas() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/inference/completion/postponedArgumentsAnalysis/performance/reuseBuiltFunctionalTypesForPairOfLambdas.kt");
}
@TestMetadata("reuseBuiltFunctionalTypesForPairsOfDeepLambdas.kt")
public void testReuseBuiltFunctionalTypesForPairsOfDeepLambdas() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/inference/completion/postponedArgumentsAnalysis/performance/reuseBuiltFunctionalTypesForPairsOfDeepLambdas.kt");
}
@TestMetadata("reuseBuiltFunctionalTypesForPairsOfDeepMixedLambdas.kt")
public void testReuseBuiltFunctionalTypesForPairsOfDeepMixedLambdas() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/inference/completion/postponedArgumentsAnalysis/performance/reuseBuiltFunctionalTypesForPairsOfDeepMixedLambdas.kt");
}
@TestMetadata("reuseBuiltFunctionalTypesForPairsOfIdLambdas.kt")
public void testReuseBuiltFunctionalTypesForPairsOfIdLambdas() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/inference/completion/postponedArgumentsAnalysis/performance/reuseBuiltFunctionalTypesForPairsOfIdLambdas.kt");
}
}
}
}
@@ -3266,6 +3347,11 @@ public class FirOldFrontendDiagnosticsTestWithStdlibGenerated extends AbstractFi
public void testDontInferToNullableNothingInDelegates() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/inference/nothingType/dontInferToNullableNothingInDelegates.kt");
}
@TestMetadata("dontSpreadWarningToNotReturningNothingSubResolvedAtoms.kt")
public void testDontSpreadWarningToNotReturningNothingSubResolvedAtoms() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/inference/nothingType/dontSpreadWarningToNotReturningNothingSubResolvedAtoms.kt");
}
}
}

View File

@@ -421,7 +421,7 @@ internal fun IrDeclarationParent.declareThisReceiverParameter(
symbolTable.irFactory.createValueParameter(
startOffset, endOffset, thisOrigin, symbol,
Name.special("<this>"), -1, thisType,
varargElementType = null, isCrossinline = false, isNoinline = false
varargElementType = null, isCrossinline = false, isNoinline = false, isAssignable = false
).apply {
this.parent = this@declareThisReceiverParameter
receiverDescriptor.bind(this)

View File

@@ -259,7 +259,7 @@ class Fir2IrDeclarationStorage(
startOffset, endOffset, IrDeclarationOrigin.DEFINED, symbol,
Name.special("<set-?>"), 0, type,
varargElementType = null,
isCrossinline = false, isNoinline = false
isCrossinline = false, isNoinline = false, isAssignable = false
).apply {
this.parent = parent
descriptor.bind(this)

View File

@@ -608,7 +608,7 @@ class CallAndReferenceGenerator(
putValueArgument(0, assignedValue)
}
}
is IrVariableSymbol -> IrSetVariableImpl(startOffset, endOffset, type, symbol, assignedValue, origin)
is IrVariableSymbol -> IrSetValueImpl(startOffset, endOffset, type, symbol, assignedValue, origin)
else -> generateErrorCallExpression(startOffset, endOffset, calleeReference)
}
}.applyTypeArguments(variableAssignment).applyReceivers(variableAssignment, explicitReceiverExpression)

View File

@@ -270,7 +270,7 @@ class DataClassMembersGenerator(val components: Fir2IrComponents) {
) { symbol ->
components.irFactory.createValueParameter(
UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, symbol, name, index, type, null,
isCrossinline = false, isNoinline = false
isCrossinline = false, isNoinline = false, isAssignable = false
)
}.apply {
parent = irFunction

View File

@@ -276,6 +276,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/annotations/typeAnnotations/implicitReturn.kt");
}
@TestMetadata("kt41484.kt")
public void testKt41484() throws Exception {
runTest("compiler/testData/codegen/box/annotations/typeAnnotations/kt41484.kt");
}
@TestMetadata("methodParameters.kt")
public void testMethodParameters() throws Exception {
runTest("compiler/testData/codegen/box/annotations/typeAnnotations/methodParameters.kt");
@@ -345,6 +350,16 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/argumentOrder/extensionInClass.kt");
}
@TestMetadata("kt17691.kt")
public void testKt17691() throws Exception {
runTest("compiler/testData/codegen/box/argumentOrder/kt17691.kt");
}
@TestMetadata("kt17691WithEnabledFeature.kt")
public void testKt17691WithEnabledFeature() throws Exception {
runTest("compiler/testData/codegen/box/argumentOrder/kt17691WithEnabledFeature.kt");
}
@TestMetadata("kt9277.kt")
public void testKt9277() throws Exception {
runTest("compiler/testData/codegen/box/argumentOrder/kt9277.kt");
@@ -1732,6 +1747,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
public void testSubstituteStubTypeIntolambdaParameterDescriptor() throws Exception {
runTest("compiler/testData/codegen/box/builderInference/substituteStubTypeIntolambdaParameterDescriptor.kt");
}
@TestMetadata("substituteTypeVariableIntolambdaParameterDescriptor.kt")
public void testSubstituteTypeVariableIntolambdaParameterDescriptor() throws Exception {
runTest("compiler/testData/codegen/box/builderInference/substituteTypeVariableIntolambdaParameterDescriptor.kt");
}
}
@TestMetadata("compiler/testData/codegen/box/builtinStubMethods")
@@ -6443,11 +6463,21 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/coroutines/builderInferenceAndGenericArrayAcessCall.kt");
}
@TestMetadata("captureInfixFun.kt")
public void testCaptureInfixFun() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/captureInfixFun.kt");
}
@TestMetadata("captureMutableLocalVariableInsideCoroutineBlock.kt")
public void testCaptureMutableLocalVariableInsideCoroutineBlock() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/captureMutableLocalVariableInsideCoroutineBlock.kt");
}
@TestMetadata("captureUnaryOperator.kt")
public void testCaptureUnaryOperator() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/captureUnaryOperator.kt");
}
@TestMetadata("capturedVarInSuspendLambda.kt")
public void testCapturedVarInSuspendLambda_1_3() throws Exception {
runTestWithPackageReplacement("compiler/testData/codegen/box/coroutines/capturedVarInSuspendLambda.kt", "kotlin.coroutines");
@@ -6673,6 +6703,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/coroutines/kt35967.kt");
}
@TestMetadata("kt42028.kt")
public void testKt42028() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/kt42028.kt");
}
@TestMetadata("lastExpressionIsLoop.kt")
public void testLastExpressionIsLoop_1_3() throws Exception {
runTestWithPackageReplacement("compiler/testData/codegen/box/coroutines/lastExpressionIsLoop.kt", "kotlin.coroutines");
@@ -6748,6 +6783,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTestWithPackageReplacement("compiler/testData/codegen/box/coroutines/noSuspensionPoints.kt", "kotlin.coroutines");
}
@TestMetadata("nonLocalReturn.kt")
public void testNonLocalReturn() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/nonLocalReturn.kt");
}
@TestMetadata("nonLocalReturnFromInlineLambdaDeep.kt")
public void testNonLocalReturnFromInlineLambdaDeep_1_3() throws Exception {
runTestWithPackageReplacement("compiler/testData/codegen/box/coroutines/nonLocalReturnFromInlineLambdaDeep.kt", "kotlin.coroutines");
@@ -7432,6 +7472,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
KotlinTestUtils.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/codegen/box/coroutines/inlineClasses"), Pattern.compile("^(.+)\\.kt$"), null, TargetBackend.JVM_IR, true);
}
@TestMetadata("nonLocalReturn.kt")
public void testNonLocalReturn() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/inlineClasses/nonLocalReturn.kt");
}
@TestMetadata("compiler/testData/codegen/box/coroutines/inlineClasses/direct")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
@@ -7573,6 +7618,16 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/coroutines/inlineClasses/direct/covariantOverrideSuspendFun_Int.kt");
}
@TestMetadata("createMangling.kt")
public void testCreateMangling() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/inlineClasses/direct/createMangling.kt");
}
@TestMetadata("createOverride.kt")
public void testCreateOverride() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/inlineClasses/direct/createOverride.kt");
}
@TestMetadata("genericOverrideSuspendFun.kt")
public void testGenericOverrideSuspendFun() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/inlineClasses/direct/genericOverrideSuspendFun.kt");
@@ -7618,6 +7673,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTestWithPackageReplacement("compiler/testData/codegen/box/coroutines/inlineClasses/direct/interfaceDelegateWithInlineClass.kt", "kotlin.coroutines");
}
@TestMetadata("invokeOperator.kt")
public void testInvokeOperator() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/inlineClasses/direct/invokeOperator.kt");
}
@TestMetadata("overrideSuspendFun.kt")
public void testOverrideSuspendFun_1_3() throws Exception {
runTestWithPackageReplacement("compiler/testData/codegen/box/coroutines/inlineClasses/direct/overrideSuspendFun.kt", "kotlin.coroutines");
@@ -7790,6 +7850,16 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/coroutines/inlineClasses/resume/covariantOverrideSuspendFun_Int.kt");
}
@TestMetadata("createMangling.kt")
public void testCreateMangling() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/inlineClasses/resume/createMangling.kt");
}
@TestMetadata("createOverride.kt")
public void testCreateOverride() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/inlineClasses/resume/createOverride.kt");
}
@TestMetadata("genericOverrideSuspendFun.kt")
public void testGenericOverrideSuspendFun() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/inlineClasses/resume/genericOverrideSuspendFun.kt");
@@ -7835,6 +7905,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTestWithPackageReplacement("compiler/testData/codegen/box/coroutines/inlineClasses/resume/interfaceDelegateWithInlineClass.kt", "kotlin.coroutines");
}
@TestMetadata("invokeOperator.kt")
public void testInvokeOperator() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/inlineClasses/resume/invokeOperator.kt");
}
@TestMetadata("overrideSuspendFun.kt")
public void testOverrideSuspendFun_1_3() throws Exception {
runTestWithPackageReplacement("compiler/testData/codegen/box/coroutines/inlineClasses/resume/overrideSuspendFun.kt", "kotlin.coroutines");
@@ -8002,6 +8077,16 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/coroutines/inlineClasses/resumeWithException/covariantOverrideSuspendFun_Int.kt");
}
@TestMetadata("createMangling.kt")
public void testCreateMangling() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/inlineClasses/resumeWithException/createMangling.kt");
}
@TestMetadata("createOverride.kt")
public void testCreateOverride() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/inlineClasses/resumeWithException/createOverride.kt");
}
@TestMetadata("genericOverrideSuspendFun.kt")
public void testGenericOverrideSuspendFun() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/inlineClasses/resumeWithException/genericOverrideSuspendFun.kt");
@@ -8037,6 +8122,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTestWithPackageReplacement("compiler/testData/codegen/box/coroutines/inlineClasses/resumeWithException/interfaceDelegateWithInlineClass.kt", "kotlin.coroutines");
}
@TestMetadata("invokeOperator.kt")
public void testInvokeOperator() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/inlineClasses/resumeWithException/invokeOperator.kt");
}
@TestMetadata("overrideSuspendFun.kt")
public void testOverrideSuspendFun_1_3() throws Exception {
runTestWithPackageReplacement("compiler/testData/codegen/box/coroutines/inlineClasses/resumeWithException/overrideSuspendFun.kt", "kotlin.coroutines");
@@ -8729,6 +8819,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/coroutines/tailCallOptimizations/interfaceDelegation.kt");
}
@TestMetadata("returnInlineClass.kt")
public void testReturnInlineClass() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/tailCallOptimizations/returnInlineClass.kt");
}
@TestMetadata("simple.kt")
public void testSimple() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/tailCallOptimizations/simple.kt");
@@ -8967,6 +9062,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
public void testRefinedIntTypesAnalysis() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/varSpilling/refinedIntTypesAnalysis.kt");
}
@TestMetadata("safeCallElvis.kt")
public void testSafeCallElvis() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/varSpilling/safeCallElvis.kt");
}
}
}
@@ -10885,6 +10985,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/enum/constructorWithReordering.kt");
}
@TestMetadata("declaringClassOnEnumObject.kt")
public void testDeclaringClassOnEnumObject() throws Exception {
runTest("compiler/testData/codegen/box/enum/declaringClassOnEnumObject.kt");
}
@TestMetadata("deepInnerClassInEnumEntryClass.kt")
public void testDeepInnerClassInEnumEntryClass() throws Exception {
runTest("compiler/testData/codegen/box/enum/deepInnerClassInEnumEntryClass.kt");
@@ -13867,6 +13972,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/inlineClasses/toStringCallingPrivateFun.kt");
}
@TestMetadata("toStringOfUnboxedNullable.kt")
public void testToStringOfUnboxedNullable() throws Exception {
runTest("compiler/testData/codegen/box/inlineClasses/toStringOfUnboxedNullable.kt");
}
@TestMetadata("typeChecksForInlineClasses.kt")
public void testTypeChecksForInlineClasses() throws Exception {
runTest("compiler/testData/codegen/box/inlineClasses/typeChecksForInlineClasses.kt");
@@ -15345,6 +15455,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/ir/kt40083.kt");
}
@TestMetadata("kt41765.kt")
public void testKt41765() throws Exception {
runTest("compiler/testData/codegen/box/ir/kt41765.kt");
}
@TestMetadata("objectClass.kt")
public void testObjectClass() throws Exception {
runTest("compiler/testData/codegen/box/ir/objectClass.kt");
@@ -16072,6 +16187,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/jvm8/defaults/kt40920.kt");
}
@TestMetadata("kt42674.kt")
public void testKt42674() throws Exception {
runTest("compiler/testData/codegen/box/jvm8/defaults/kt42674.kt");
}
@TestMetadata("oneImplementation.kt")
public void testOneImplementation() throws Exception {
runTest("compiler/testData/codegen/box/jvm8/defaults/oneImplementation.kt");
@@ -16234,6 +16354,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/jvm8/defaults/allCompatibility/kt14243_2.kt");
}
@TestMetadata("kt42674.kt")
public void testKt42674() throws Exception {
runTest("compiler/testData/codegen/box/jvm8/defaults/allCompatibility/kt42674.kt");
}
@TestMetadata("privateFunInInterface.kt")
public void testPrivateFunInInterface() throws Exception {
runTest("compiler/testData/codegen/box/jvm8/defaults/allCompatibility/privateFunInInterface.kt");
@@ -16345,6 +16470,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/jvm8/defaults/compatibility/interfaceExtension.kt");
}
@TestMetadata("kt42674.kt")
public void testKt42674() throws Exception {
runTest("compiler/testData/codegen/box/jvm8/defaults/compatibility/kt42674.kt");
}
@TestMetadata("propertyAnnotation.kt")
public void testPropertyAnnotation() throws Exception {
runTest("compiler/testData/codegen/box/jvm8/defaults/compatibility/propertyAnnotation.kt");
@@ -16506,6 +16636,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/jvm8/defaults/noDefaultImpls/kt40920.kt");
}
@TestMetadata("kt42674.kt")
public void testKt42674() throws Exception {
runTest("compiler/testData/codegen/box/jvm8/defaults/noDefaultImpls/kt42674.kt");
}
@TestMetadata("privateFunInInterface.kt")
public void testPrivateFunInInterface() throws Exception {
runTest("compiler/testData/codegen/box/jvm8/defaults/noDefaultImpls/privateFunInInterface.kt");
@@ -17214,6 +17349,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/jvmStatic/kt21246a.kt");
}
@TestMetadata("kt35716.kt")
public void testKt35716() throws Exception {
runTest("compiler/testData/codegen/box/jvmStatic/kt35716.kt");
}
@TestMetadata("kt9897_static.kt")
public void testKt9897_static() throws Exception {
runTest("compiler/testData/codegen/box/jvmStatic/kt9897_static.kt");
@@ -21997,6 +22137,16 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
public void testKt13241_Collection() throws Exception {
runTest("compiler/testData/codegen/box/ranges/forInIndices/kt13241_Collection.kt");
}
@TestMetadata("kt43159_ArrayUpperBound.kt")
public void testKt43159_ArrayUpperBound() throws Exception {
runTest("compiler/testData/codegen/box/ranges/forInIndices/kt43159_ArrayUpperBound.kt");
}
@TestMetadata("kt43159_GenericArray.kt")
public void testKt43159_GenericArray() throws Exception {
runTest("compiler/testData/codegen/box/ranges/forInIndices/kt43159_GenericArray.kt");
}
}
@TestMetadata("compiler/testData/codegen/box/ranges/forInProgressionWithIndex")
@@ -30018,6 +30168,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/strings/kt3652.kt");
}
@TestMetadata("kt42457_old.kt")
public void testKt42457_old() throws Exception {
runTest("compiler/testData/codegen/box/strings/kt42457_old.kt");
}
@TestMetadata("kt5389_stringBuilderGet.kt")
public void testKt5389_stringBuilderGet() throws Exception {
runTest("compiler/testData/codegen/box/strings/kt5389_stringBuilderGet.kt");

View File

@@ -404,7 +404,7 @@ class JavaSymbolProvider(
private fun hasTopLevelClassOf(classId: ClassId): Boolean {
val knownNames = knownClassNamesInPackage.getOrPut(classId.packageFqName) {
facade.knownClassNamesInPackage(classId.packageFqName)
facade.knownClassNamesInPackage(classId.packageFqName, searchScope)
} ?: return true
return classId.relativeClassName.topLevelName() in knownNames
}

View File

@@ -38,7 +38,7 @@ class JavaOverrideChecker internal constructor(
}
}
return with(context) {
isEqualTypeConstructors(
areEqualTypeConstructors(
substitutor.substituteOrSelf(candidateType).typeConstructor(),
substitutor.substituteOrSelf(baseType).typeConstructor()
)

View File

@@ -19,14 +19,14 @@ class JvmMappedScope(
) : FirTypeScope() {
override fun processFunctionsByName(name: Name, processor: (FirFunctionSymbol<*>) -> Unit) {
val whiteListSignatures = signatures.whiteListSignaturesByName[name]
val visibleMethods = signatures.visibleMethodSignaturesByName[name]
?: return declaredMemberScope.processFunctionsByName(name, processor)
javaMappedClassUseSiteScope.processFunctionsByName(name) { symbol ->
val jvmSignature = symbol.fir.computeJvmDescriptor()
.replace("kotlin/Any", "java/lang/Object")
.replace("kotlin/String", "java/lang/String")
.replace("kotlin/Throwable", "java/lang/Throwable")
if (jvmSignature in whiteListSignatures) {
if (jvmSignature in visibleMethods) {
processor(symbol)
}
}
@@ -40,14 +40,14 @@ class JvmMappedScope(
) = ProcessorAction.NONE
override fun processDeclaredConstructors(processor: (FirConstructorSymbol) -> Unit) {
val constructorBlackList = signatures.constructorBlackList
if (constructorBlackList.isNotEmpty()) {
val hiddenConstructors = signatures.hiddenConstructors
if (hiddenConstructors.isNotEmpty()) {
javaMappedClassUseSiteScope.processDeclaredConstructors { symbol ->
val jvmSignature = symbol.fir.computeJvmDescriptor()
.replace("kotlin/Any", "java/lang/Object")
.replace("kotlin/String", "java/lang/String")
.replace("kotlin/Throwable", "java/lang/Throwable")
if (jvmSignature !in constructorBlackList) {
if (jvmSignature !in hiddenConstructors) {
processor(symbol)
}
}
@@ -80,14 +80,14 @@ class JvmMappedScope(
}
companion object {
data class Signatures(val whiteListSignaturesByName: Map<Name, Set<String>>, val constructorBlackList: Set<String>) {
fun isEmpty() = whiteListSignaturesByName.isEmpty() && constructorBlackList.isEmpty()
data class Signatures(val visibleMethodSignaturesByName: Map<Name, Set<String>>, val hiddenConstructors: Set<String>) {
fun isEmpty() = visibleMethodSignaturesByName.isEmpty() && hiddenConstructors.isEmpty()
fun isNotEmpty() = !isEmpty()
}
// NOTE: No-arg constructors
@OptIn(ExperimentalStdlibApi::class)
private val additionalConstructorBlackList = buildSet<String> {
private val additionalHiddenConstructors = buildSet<String> {
// kotlin.text.String pseudo-constructors should be used instead of java.lang.String constructors
listOf(
"",
@@ -113,22 +113,22 @@ class JvmMappedScope(
fun prepareSignatures(klass: FirRegularClass): Signatures {
val signaturePrefix = klass.symbol.classId.toString()
val whiteListSignaturesByName = mutableMapOf<Name, MutableSet<String>>()
JvmBuiltInsSignatures.WHITE_LIST_METHOD_SIGNATURES.filter { signature ->
val visibleMethodsByName = mutableMapOf<Name, MutableSet<String>>()
JvmBuiltInsSignatures.VISIBLE_METHOD_SIGNATURES.filter { signature ->
signature.startsWith(signaturePrefix)
}.map { signature ->
// +1 to delete dot before function name
signature.substring(signaturePrefix.length + 1)
}.forEach {
whiteListSignaturesByName.getOrPut(Name.identifier(it.substringBefore("("))) { mutableSetOf() }.add(it)
visibleMethodsByName.getOrPut(Name.identifier(it.substringBefore("("))) { mutableSetOf() }.add(it)
}
val constructorBlackList =
(JvmBuiltInsSignatures.BLACK_LIST_CONSTRUCTOR_SIGNATURES + additionalConstructorBlackList)
val hiddenConstructors =
(JvmBuiltInsSignatures.HIDDEN_CONSTRUCTOR_SIGNATURES + additionalHiddenConstructors)
.filter { it.startsWith(signaturePrefix) }
.mapTo(mutableSetOf()) { it.substring(signaturePrefix.length + 1) }
return Signatures(whiteListSignaturesByName, constructorBlackList)
return Signatures(visibleMethodsByName, hiddenConstructors)
}
}
}

View File

@@ -9,6 +9,7 @@ import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.declarations.FirTypeParameterRef
import org.jetbrains.kotlin.fir.declarations.FirTypeParameterRefsOwner
import org.jetbrains.kotlin.fir.renderWithType
import org.jetbrains.kotlin.fir.resolve.fullyExpandedType
import org.jetbrains.kotlin.fir.resolve.inference.TypeParameterBasedTypeVariable
import org.jetbrains.kotlin.fir.resolve.inference.inferenceComponents
import org.jetbrains.kotlin.fir.resolve.inference.model.ConeDeclaredUpperBoundConstraintPosition
@@ -68,7 +69,7 @@ internal object CreateFreshTypeVariableSubstitutorStage : ResolutionStage() {
typeArgument.typeRef.coneType,
typeParameter,
context.session.inferenceComponents.ctx
),
).fullyExpandedType(context.session),
SimpleConstraintSystemConstraintPosition // TODO
)
is FirStarProjection -> csBuilder.addEqualityConstraint(

View File

@@ -50,7 +50,7 @@ class ConstraintSystemCompleter(private val components: BodyResolveComponents) {
val postponedAtoms = getOrderedNotAnalyzedPostponedArguments(topLevelAtoms)
val variableForFixation =
variableFixationFinder.findFirstVariableForFixation(
c, allTypeVariables, postponedAtoms, completionMode, candidateReturnType
c, allTypeVariables, postponedAtoms, completionMode, candidateReturnType, inferenceCompatibilityMode = true
) ?: break
if (

View File

@@ -10,6 +10,7 @@ import org.jetbrains.kotlin.fir.FirSessionComponent
import org.jetbrains.kotlin.fir.NoMutableState
import org.jetbrains.kotlin.fir.types.ConeInferenceContext
import org.jetbrains.kotlin.fir.types.ConeTypeCheckerContext
import org.jetbrains.kotlin.resolve.calls.inference.InferenceCompatibilityChecker
import org.jetbrains.kotlin.resolve.calls.inference.components.ConstraintIncorporator
import org.jetbrains.kotlin.resolve.calls.inference.components.ConstraintInjector
import org.jetbrains.kotlin.resolve.calls.inference.components.ResultTypeResolver
@@ -24,7 +25,13 @@ class InferenceComponents(val session: FirSession) : FirSessionComponent {
val approximator: AbstractTypeApproximator = object : AbstractTypeApproximator(ctx) {}
val trivialConstraintTypeInferenceOracle = TrivialConstraintTypeInferenceOracle.create(ctx)
private val incorporator = ConstraintIncorporator(approximator, trivialConstraintTypeInferenceOracle, ConeConstraintSystemUtilContext)
private val injector = ConstraintInjector(incorporator, approximator)
private val injector = ConstraintInjector(
incorporator,
approximator,
object : InferenceCompatibilityChecker {
override val isCompatibilityModeEnabled = true
}
)
val resultTypeResolver = ResultTypeResolver(approximator, trivialConstraintTypeInferenceOracle)
val constraintSystemFactory = ConstraintSystemFactory()

View File

@@ -275,7 +275,7 @@ interface ConeTypeContext : TypeSystemContext, TypeSystemOptimizationContext, Ty
return this
}
override fun isEqualTypeConstructors(c1: TypeConstructorMarker, c2: TypeConstructorMarker): Boolean {
override fun areEqualTypeConstructors(c1: TypeConstructorMarker, c2: TypeConstructorMarker): Boolean {
if (c1 is ErrorTypeConstructor || c2 is ErrorTypeConstructor) return false
//assert(c1 is ConeSymbol)

View File

@@ -23,6 +23,7 @@ import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.resolve.BindingTrace
import org.jetbrains.kotlin.resolve.CodeAnalyzerInitializer
import org.jetbrains.kotlin.resolve.jvm.TopPackageNamesProvider
import org.jetbrains.kotlin.resolve.lazy.KotlinCodeAnalyzer
import javax.annotation.PostConstruct
import javax.inject.Inject
@@ -32,10 +33,14 @@ abstract class AbstractJavaClassFinder : JavaClassFinder {
protected lateinit var project: Project
protected lateinit var javaSearchScope: GlobalSearchScope
@Inject
fun setScope(scope: GlobalSearchScope) {
javaSearchScope = FilterOutKotlinSourceFilesScope(scope)
javaSearchScope =
if (scope == GlobalSearchScope.EMPTY_SCOPE) {
GlobalSearchScope.EMPTY_SCOPE
} else {
FilterOutKotlinSourceFilesScope(scope)
}
}
@Inject
@@ -48,9 +53,15 @@ abstract class AbstractJavaClassFinder : JavaClassFinder {
CodeAnalyzerInitializer.getInstance(project).initialize(trace, codeAnalyzer.moduleDescriptor, codeAnalyzer)
}
inner class FilterOutKotlinSourceFilesScope(baseScope: GlobalSearchScope) : DelegatingGlobalSearchScope(baseScope) {
inner class FilterOutKotlinSourceFilesScope(baseScope: GlobalSearchScope) : DelegatingGlobalSearchScope(baseScope),
TopPackageNamesProvider {
override fun contains(file: VirtualFile) = myBaseScope.contains(file) && (file.isDirectory || file.fileType !== KotlinFileType.INSTANCE)
override val topPackageNames: Set<String>?
get() = (myBaseScope as? TopPackageNamesProvider)?.topPackageNames
override fun contains(file: VirtualFile) =
(file.isDirectory || file.fileType !== KotlinFileType.INSTANCE) &&
myBaseScope.contains(file)
val base: GlobalSearchScope = myBaseScope

View File

@@ -18,6 +18,7 @@ package org.jetbrains.kotlin.load.java
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.load.java.structure.JavaClass
import org.jetbrains.kotlin.load.java.structure.JavaPackage
import org.jetbrains.kotlin.load.java.structure.impl.JavaPackageImpl
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.jvm.KotlinJavaPsiFacade
@@ -33,11 +34,16 @@ class JavaClassFinderImpl : AbstractJavaClassFinder() {
javaFacade = KotlinJavaPsiFacade.getInstance(project)
}
override fun findClass(request: JavaClassFinder.Request): JavaClass? = javaFacade.findClass(request, javaSearchScope)
override fun findClass(request: JavaClassFinder.Request): JavaClass? {
return javaFacade.findClass(request, javaSearchScope)
}
override fun findPackage(fqName: FqName) =
javaFacade.findPackage(fqName.asString(), javaSearchScope)?.let { JavaPackageImpl(it, javaSearchScope) }
override fun findPackage(fqName: FqName): JavaPackage? {
return javaFacade.findPackage(fqName.asString(), javaSearchScope)?.let { JavaPackageImpl(it, javaSearchScope) }
}
override fun knownClassNamesInPackage(packageFqName: FqName): Set<String>? = javaFacade.knownClassNamesInPackage(packageFqName)
override fun knownClassNamesInPackage(packageFqName: FqName): Set<String>? {
return javaFacade.knownClassNamesInPackage(packageFqName, javaSearchScope)
}
}

View File

@@ -18,7 +18,7 @@ package org.jetbrains.kotlin.load.kotlin.incremental
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentProvider
import org.jetbrains.kotlin.descriptors.PackageFragmentProviderOptimized
import org.jetbrains.kotlin.descriptors.impl.PackageFragmentDescriptorImpl
import org.jetbrains.kotlin.load.kotlin.JvmPackagePartSource
import org.jetbrains.kotlin.load.kotlin.KotlinClassFinder
@@ -38,29 +38,32 @@ import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.serialization.deserialization.DeserializationComponents
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedPackageMemberScope
import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.keysToMap
class IncrementalPackageFragmentProvider(
sourceFiles: Collection<KtFile>,
val moduleDescriptor: ModuleDescriptor,
val storageManager: StorageManager,
val deserializationComponents: DeserializationComponents,
val incrementalCache: IncrementalCache,
val target: TargetId,
private val kotlinClassFinder: KotlinClassFinder
) : PackageFragmentProvider {
sourceFiles: Collection<KtFile>,
val moduleDescriptor: ModuleDescriptor,
val storageManager: StorageManager,
val deserializationComponents: DeserializationComponents,
val incrementalCache: IncrementalCache,
val target: TargetId,
private val kotlinClassFinder: KotlinClassFinder
) : PackageFragmentProviderOptimized {
private val fqNameToPackageFragment =
PackagePartClassUtils.getFilesWithCallables(sourceFiles)
.mapTo(hashSetOf()) { it.packageFqName }
.keysToMap(this::IncrementalPackageFragment)
PackagePartClassUtils.getFilesWithCallables(sourceFiles)
.mapTo(hashSetOf()) { it.packageFqName }
.keysToMap(this::IncrementalPackageFragment)
override fun getSubPackagesOf(fqName: FqName, nameFilter: (Name) -> Boolean): Collection<FqName> = emptySet()
override fun collectPackageFragments(fqName: FqName, packageFragments: MutableCollection<PackageFragmentDescriptor>) =
packageFragments.addIfNotNull(fqNameToPackageFragment[fqName])
override fun getPackageFragments(fqName: FqName): List<PackageFragmentDescriptor> {
return listOfNotNull(fqNameToPackageFragment[fqName])
}
inner class IncrementalPackageFragment(fqName: FqName) : PackageFragmentDescriptorImpl(moduleDescriptor, fqName) {
val target: TargetId
get() = this@IncrementalPackageFragmentProvider.target
@@ -75,34 +78,34 @@ class IncrementalPackageFragmentProvider(
}
inner class IncrementalMultifileClassPackageFragment(
val facadeName: JvmClassName,
val partsInternalNames: Collection<String>,
packageFqName: FqName
val facadeName: JvmClassName,
val partsInternalNames: Collection<String>,
packageFqName: FqName
) : PackageFragmentDescriptorImpl(moduleDescriptor, packageFqName) {
private val memberScope = storageManager.createLazyValue {
ChainedMemberScope.create(
"Member scope for incremental compilation: union of multifile class parts data for $facadeName",
partsInternalNames.mapNotNull { internalName ->
incrementalCache.getPackagePartData(internalName)?.let { (data, strings) ->
val (nameResolver, packageProto) = JvmProtoBufUtil.readPackageDataFrom(data, strings)
"Member scope for incremental compilation: union of multifile class parts data for $facadeName",
partsInternalNames.mapNotNull { internalName ->
incrementalCache.getPackagePartData(internalName)?.let { (data, strings) ->
val (nameResolver, packageProto) = JvmProtoBufUtil.readPackageDataFrom(data, strings)
val partName = JvmClassName.byInternalName(internalName)
val jvmBinaryClass =
kotlinClassFinder.findKotlinClass(ClassId.topLevel(partName.fqNameForTopLevelClassMaybeWithDollars))
val partName = JvmClassName.byInternalName(internalName)
val jvmBinaryClass =
kotlinClassFinder.findKotlinClass(ClassId.topLevel(partName.fqNameForTopLevelClassMaybeWithDollars))
val metadataVersion =
jvmBinaryClass?.classHeader?.metadataVersion
val metadataVersion =
jvmBinaryClass?.classHeader?.metadataVersion
?: JvmMetadataVersion.INSTANCE
DeserializedPackageMemberScope(
this, packageProto, nameResolver, metadataVersion,
JvmPackagePartSource(
partName, facadeName, packageProto, nameResolver, knownJvmBinaryClass = jvmBinaryClass
),
deserializationComponents, classNames = { emptyList() }
)
}
DeserializedPackageMemberScope(
this, packageProto, nameResolver, metadataVersion,
JvmPackagePartSource(
partName, facadeName, packageProto, nameResolver, knownJvmBinaryClass = jvmBinaryClass
),
deserializationComponents, classNames = { emptyList() }
)
}
}
)
}

View File

@@ -61,7 +61,7 @@ fun CallableMemberDescriptor.isCompiledToJvmDefault(jvmDefault: JvmDefaultMode):
return JvmProtoBufUtil.isNewPlaceForBodyGeneration(clazz.classProto)
}
fun FunctionDescriptor.checkIsImplementationCompiledToJvmDefault(jvmDefaultMode: JvmDefaultMode): Boolean {
fun CallableMemberDescriptor.checkIsImplementationCompiledToJvmDefault(jvmDefaultMode: JvmDefaultMode): Boolean {
val actualImplementation =
(if (kind.isReal) this else findImplementationFromInterface(this))
?: error("Can't find actual implementation for $this")

View File

@@ -156,7 +156,13 @@ class JavaNullabilityChecker : AdditionalTypeChecker {
private fun isNullableTypeAgainstNotNullTypeParameter(
subType: KotlinType,
superType: KotlinType
) = superType is NotNullTypeVariable && subType.isNullable()
): Boolean {
if (superType !is NotNullTypeVariable) return false
return !AbstractNullabilityChecker.isSubtypeOfAny(
ClassicTypeCheckerContext(errorTypeEqualsToAnything = true) as AbstractTypeCheckerContext,
subType
)
}
override fun checkReceiver(
receiverParameter: ReceiverParameterDescriptor,

View File

@@ -10,6 +10,7 @@ import org.jetbrains.kotlin.config.JvmAnalysisFlags
import org.jetbrains.kotlin.config.JvmDefaultMode
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.load.java.descriptors.JavaCallableMemberDescriptor
import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor
import org.jetbrains.kotlin.load.kotlin.computeJvmDescriptor
import org.jetbrains.kotlin.psi.KtDeclaration
@@ -67,7 +68,7 @@ class JvmDefaultChecker(val jvmTarget: JvmTarget, project: Project) : Declaratio
}
if (isInterface(descriptor.containingDeclaration)) {
if (!jvmDefaultMode.forAllMethodsWithBody && isInterface(descriptor.containingDeclaration)) {
val memberDescriptor = descriptor as? CallableMemberDescriptor ?: return
if (descriptor is PropertyAccessorDescriptor) return
@@ -154,7 +155,7 @@ class JvmDefaultChecker(val jvmTarget: JvmTarget, project: Project) : Declaratio
declaration: KtDeclaration,
performSpecializationCheck: Boolean
): Boolean {
if (!performSpecializationCheck) return true
if (!performSpecializationCheck || actualImplementation is JavaMethodDescriptor) return true
val inheritedSignature = inheritedFun.computeJvmDescriptor(withReturnType = true, withName = false)
val originalImplementation = actualImplementation.original
val actualSignature = originalImplementation.computeJvmDescriptor(withReturnType = true, withName = false)
@@ -200,7 +201,11 @@ class JvmDefaultChecker(val jvmTarget: JvmTarget, project: Project) : Declaratio
val classMembers =
inheritedFun.overriddenDescriptors.filter { !isInterface(it.containingDeclaration) && !isAnnotationClass(it.containingDeclaration) }
val implicitDefaultImplsDelegate =
classMembers.firstOrNull { getNonPrivateTraitMembersForDelegation(it, true)?.isCompiledToJvmDefaultWithProperMode(jvmDefaultMode) == false }
classMembers.firstOrNull {
//TODO: additional processing for platform dependent method is required (https://youtrack.jetbrains.com/issue/KT-42697)
it !is JavaCallableMemberDescriptor &&
getNonPrivateTraitMembersForDelegation(it, true)?.isCompiledToJvmDefaultWithProperMode(jvmDefaultMode) == false
}
if (implicitDefaultImplsDelegate != null) return implicitDefaultImplsDelegate
return classMembers.firstNotNullResult { findPossibleClashMember(it, jvmDefaultMode) }
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* 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 org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.diagnostics.Errors.JVM_STATIC_IN_PRIVATE_COMPANION
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.resolve.annotations.JVM_STATIC_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.resolve.checkers.DeclarationChecker
import org.jetbrains.kotlin.resolve.checkers.DeclarationCheckerContext
import org.jetbrains.kotlin.resolve.source.KotlinSourceElement
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class JvmStaticInPrivateCompanionChecker : DeclarationChecker {
override fun check(declaration: KtDeclaration, descriptor: DeclarationDescriptor, context: DeclarationCheckerContext) {
val containingDeclaration = descriptor.containingDeclaration
if (containingDeclaration !is ClassDescriptor
|| !containingDeclaration.isCompanionObject
|| !Visibilities.isPrivate(containingDeclaration.visibility.delegate)
) return
val jvmStaticAnnotation = descriptor.annotations.findAnnotation(JVM_STATIC_ANNOTATION_FQ_NAME) ?: return
val reportTarget = jvmStaticAnnotation.source.safeAs<KotlinSourceElement>()?.psi ?: return
context.trace.report(JVM_STATIC_IN_PRIVATE_COMPANION.on(reportTarget))
}
}

View File

@@ -17,28 +17,47 @@
package org.jetbrains.kotlin.resolve.jvm.checkers
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.descriptors.DescriptorVisibility
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory3
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.resolve.calls.checkers.CallChecker
import org.jetbrains.kotlin.resolve.calls.checkers.CallCheckerContext
import org.jetbrains.kotlin.resolve.calls.context.CallPosition
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory
import org.jetbrains.kotlin.resolve.calls.smartcasts.getReceiverValueWithSmartCast
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.synthetic.SamAdapterExtensionFunctionDescriptor
import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor
object ProtectedSyntheticExtensionCallChecker : CallChecker {
fun computeSuitableDescriptorAndError(
descriptor: SyntheticJavaPropertyDescriptor,
reportOn: PsiElement,
context: CallCheckerContext
): Pair<FunctionDescriptor, DiagnosticFactory3<PsiElement, DeclarationDescriptor, DescriptorVisibility, DeclarationDescriptor>> {
val callPosition = context.resolutionContext.callPosition
val isLeftSide = callPosition is CallPosition.PropertyAssignment
&& (callPosition.leftPart as? KtDotQualifiedExpression)?.selectorExpression == reportOn
val getMethod = descriptor.getMethod
val setMethod = descriptor.setMethod
val isImprovingDiagnosticsEnabled =
context.languageVersionSettings.supportsFeature(LanguageFeature.ImproveReportingDiagnosticsOnProtectedMembersOfBaseClass)
val needToTakeSetter = isImprovingDiagnosticsEnabled && isLeftSide
val suitableDescriptor = if (needToTakeSetter && setMethod != null) setMethod else getMethod
return suitableDescriptor to if (needToTakeSetter && setMethod != null) Errors.INVISIBLE_SETTER else Errors.INVISIBLE_MEMBER
}
override fun check(resolvedCall: ResolvedCall<*>, reportOn: PsiElement, context: CallCheckerContext) {
val descriptor = resolvedCall.resultingDescriptor
val sourceFunction = when (descriptor) {
is SyntheticJavaPropertyDescriptor -> descriptor.getMethod
// TODO: this branch becomes unnecessary, because common checks are applied to SAM adapters being resolved as common members
// But this part may be still useful when we enable backward compatibility mode and SAM adapters become extensions again
is SamAdapterExtensionFunctionDescriptor -> descriptor.baseDescriptorForSynthetic
else -> return
}
if (descriptor !is SyntheticJavaPropertyDescriptor) return
val (sourceFunction, error) = computeSuitableDescriptorAndError(descriptor, reportOn, context)
val from = context.scope.ownerDescriptor
@@ -49,12 +68,14 @@ object ProtectedSyntheticExtensionCallChecker : CallChecker {
val receiverValue = resolvedCall.extensionReceiver as ReceiverValue
val receiverTypes = listOf(receiverValue.type) + context.dataFlowInfo.getStableTypes(
context.dataFlowValueFactory.createDataFlowValue(receiverValue, context.trace.bindingContext, context.scope.ownerDescriptor),
context.languageVersionSettings
context.dataFlowValueFactory.createDataFlowValue(
receiverValue, context.trace.bindingContext, context.scope.ownerDescriptor
),
context.languageVersionSettings
)
if (receiverTypes.none { DescriptorVisibilities.isVisible(getReceiverValueWithSmartCast(null, it), sourceFunction, from) }) {
context.trace.report(Errors.INVISIBLE_MEMBER.on(reportOn, descriptor, descriptor.visibility, from))
context.trace.report(error.on(reportOn, descriptor, descriptor.visibility, from))
}
}
}

View File

@@ -144,7 +144,7 @@ public class DefaultErrorMessagesJvm implements DefaultErrorMessages.Extension {
MAP.put(JVM_DEFAULT_IN_DECLARATION, "Usage of ''@{0}'' is only allowed with -Xjvm-default option", STRING);
MAP.put(JVM_DEFAULT_THROUGH_INHERITANCE, "Inheritance from an interface with '@JvmDefault' members is only allowed with -Xjvm-default option");
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(NON_JVM_DEFAULT_OVERRIDES_JAVA_DEFAULT, "Non-@JvmDefault interface method cannot override default Java method. Please annotate this method with @JvmDefault or enable `-Xjvm-default=all|all-compatibility`");
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_CRITICAL_SECTION, "The ''{0}'' suspension point is inside a critical section", NAME);

View File

@@ -25,6 +25,7 @@ import org.jetbrains.kotlin.storage.NotNullLazyValue
import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.storage.getValue
import org.jetbrains.kotlin.utils.Printer
import org.jetbrains.kotlin.utils.addIfNotNull
class OptionalAnnotationPackageFragmentProvider(
module: ModuleDescriptor,
@@ -32,7 +33,7 @@ class OptionalAnnotationPackageFragmentProvider(
notFoundClasses: NotFoundClasses,
languageVersionSettings: LanguageVersionSettings,
packagePartProvider: PackagePartProvider,
) : PackageFragmentProvider {
) : PackageFragmentProviderOptimized {
val packages: Map<FqName, PackageFragmentDescriptor> by storageManager.createLazyValue p@{
// We call getAllOptionalAnnotationClasses under lazy value only because IncrementalPackagePartProvider requires
// deserializationConfiguration to be injected.
@@ -79,6 +80,9 @@ class OptionalAnnotationPackageFragmentProvider(
}
}
override fun collectPackageFragments(fqName: FqName, packageFragments: MutableCollection<PackageFragmentDescriptor>) =
packageFragments.addIfNotNull(packages[fqName])
override fun getPackageFragments(fqName: FqName): List<PackageFragmentDescriptor> =
packages[fqName]?.let(::listOf).orEmpty()

View File

@@ -95,6 +95,7 @@ object JvmPlatformConfigurator : PlatformConfiguratorBase(
) {
override fun configureModuleComponents(container: StorageComponentContainer) {
container.useImpl<JvmStaticChecker>()
container.useImpl<JvmStaticInPrivateCompanionChecker>()
container.useImpl<JvmReflectionAPICallChecker>()
container.useImpl<JavaSyntheticScopes>()
container.useImpl<SamConversionResolverImpl>()

View File

@@ -162,6 +162,7 @@ class JavaSyntheticPropertiesScope(storageManager: StorageManager, private val l
return descriptor.valueParameters.isEmpty()
&& descriptor.typeParameters.isEmpty()
&& descriptor.visibility.isVisibleOutside()
&& !(descriptor.isHiddenForResolutionEverywhereBesideSupercalls && descriptor.name.asString() == "isEmpty") // CharSequence.isEmpty() from JDK15
}
private fun isGoodSetMethod(descriptor: FunctionDescriptor, getMethod: FunctionDescriptor): Boolean {
@@ -178,6 +179,7 @@ class JavaSyntheticPropertiesScope(storageManager: StorageManager, private val l
return parameter.varargElementType == null
&& descriptor.typeParameters.isEmpty()
&& descriptor.visibility.isVisibleOutside()
&& !(descriptor.isHiddenForResolutionEverywhereBesideSupercalls && descriptor.name.asString() == "isEmpty") // CharSequence.isEmpty() from JDK15
}
private fun FunctionDescriptor.findOverridden(condition: (FunctionDescriptor) -> Boolean): FunctionDescriptor? {

View File

@@ -8,9 +8,7 @@ package org.jetbrains.kotlin.analyzer
import com.intellij.openapi.util.ModificationTracker
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.context.ProjectContext
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentProvider
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
@@ -238,7 +236,7 @@ private class DelegatingPackageFragmentProvider<M : ModuleInfo>(
private val module: ModuleDescriptor,
moduleContent: ModuleContent<M>,
private val packageOracle: PackageOracle
) : PackageFragmentProvider {
) : PackageFragmentProviderOptimized {
private val syntheticFilePackages = moduleContent.syntheticFiles.map { it.packageFqName }.toSet()
override fun getPackageFragments(fqName: FqName): List<PackageFragmentDescriptor> {
@@ -247,6 +245,12 @@ private class DelegatingPackageFragmentProvider<M : ModuleInfo>(
return resolverForProject.resolverForModuleDescriptor(module).packageFragmentProvider.getPackageFragments(fqName)
}
override fun collectPackageFragments(fqName: FqName, packageFragments: MutableCollection<PackageFragmentDescriptor>) {
if (certainlyDoesNotExist(fqName)) return
resolverForProject.resolverForModuleDescriptor(module).packageFragmentProvider.collectPackageFragmentsOptimizedIfPossible(fqName, packageFragments)
}
override fun getSubPackagesOf(fqName: FqName, nameFilter: (Name) -> Boolean): Collection<FqName> {
if (certainlyDoesNotExist(fqName)) return emptyList()

View File

@@ -129,23 +129,28 @@ class LazyModuleDependencies<M : ModuleInfo>(
firstDependency: M? = null,
private val resolverForProject: AbstractResolverForProject<M>
) : ModuleDependencies {
private val dependencies = storageManager.createLazyValue {
val moduleDescriptors = mutableSetOf<ModuleDescriptorImpl>()
firstDependency?.let {
moduleDescriptors.add(resolverForProject.descriptorForModule(it))
}
val moduleDescriptor = resolverForProject.descriptorForModule(module)
sequence {
if (firstDependency != null) {
yield(resolverForProject.descriptorForModule(firstDependency))
}
if (module.dependencyOnBuiltIns() == ModuleInfo.DependencyOnBuiltIns.AFTER_SDK) {
yield(moduleDescriptor.builtIns.builtInsModule)
}
for (dependency in module.dependencies()) {
@Suppress("UNCHECKED_CAST")
yield(resolverForProject.descriptorForModule(dependency as M))
}
if (module.dependencyOnBuiltIns() == ModuleInfo.DependencyOnBuiltIns.LAST) {
yield(moduleDescriptor.builtIns.builtInsModule)
}
}.toList()
val dependencyOnBuiltIns = module.dependencyOnBuiltIns()
if (dependencyOnBuiltIns == ModuleInfo.DependencyOnBuiltIns.AFTER_SDK) {
moduleDescriptors.add(moduleDescriptor.builtIns.builtInsModule)
}
for (dependency in module.dependencies()) {
if (dependency == firstDependency) continue
@Suppress("UNCHECKED_CAST")
moduleDescriptors.add(resolverForProject.descriptorForModule(dependency as M))
}
if (dependencyOnBuiltIns == ModuleInfo.DependencyOnBuiltIns.LAST) {
moduleDescriptors.add(moduleDescriptor.builtIns.builtInsModule)
}
moduleDescriptors.toList()
}
override val allDependencies: List<ModuleDescriptorImpl> get() = dependencies()

View File

@@ -887,7 +887,9 @@ class ControlFlowInformationProvider private constructor(
}
instruction.next?.let { dfs(it) }
} else if (instruction.element is KtNameReferenceExpression) {
} else if (instruction.element is KtNameReferenceExpression || instruction.element is KtBinaryExpression ||
instruction.element is KtUnaryExpression
) {
val call = instruction.element.getResolvedCall(trace.bindingContext)
if (call is VariableAsFunctionResolvedCall) {
(call.variableCall.dispatchReceiver as? ExtensionReceiver)?.declarationDescriptor?.apply { markIfNeeded() }

View File

@@ -285,6 +285,7 @@ public interface Errors {
DiagnosticFactory1<PsiElement, String> EXPERIMENTAL_UNSIGNED_LITERALS_ERROR = DiagnosticFactory1.create(ERROR);
DiagnosticFactory0<PsiElement> NON_PARENTHESIZED_ANNOTATIONS_ON_FUNCTIONAL_TYPES = DiagnosticFactory0.create(ERROR);
DiagnosticFactory0<PsiElement> JVM_STATIC_IN_PRIVATE_COMPANION = DiagnosticFactory0.create(WARNING);
// Const
DiagnosticFactory0<PsiElement> CONST_VAL_NOT_TOP_LEVEL_OR_OBJECT = DiagnosticFactory0.create(ERROR);
@@ -385,14 +386,17 @@ public interface Errors {
DiagnosticFactory0<KtDeclaration> CONSTRUCTOR_IN_OBJECT = DiagnosticFactory0.create(ERROR, DECLARATION_SIGNATURE);
DiagnosticFactory0<KtSuperTypeCallEntry> SUPERTYPE_INITIALIZED_WITHOUT_PRIMARY_CONSTRUCTOR = DiagnosticFactory0.create(ERROR);
DiagnosticFactory0<KtConstructorDelegationCall> PRIMARY_CONSTRUCTOR_DELEGATION_CALL_EXPECTED =
DiagnosticFactory0<PsiElement> PRIMARY_CONSTRUCTOR_DELEGATION_CALL_EXPECTED =
DiagnosticFactory0.create(ERROR, PositioningStrategies.SECONDARY_CONSTRUCTOR_DELEGATION_CALL);
DiagnosticFactory0<PsiElement> PRIMARY_CONSTRUCTOR_DELEGATION_CALL_EXPECTED_IN_ENUM =
DiagnosticFactory0.create(WARNING, PositioningStrategies.SECONDARY_CONSTRUCTOR_DELEGATION_CALL);
DiagnosticFactory0<KtConstructorDelegationReferenceExpression> DELEGATION_SUPER_CALL_IN_ENUM_CONSTRUCTOR =
DiagnosticFactory0.create(ERROR);
DiagnosticFactory0<PsiElement> PRIMARY_CONSTRUCTOR_REQUIRED_FOR_DATA_CLASS = DiagnosticFactory0.create(ERROR);
DiagnosticFactory0<KtConstructorDelegationCall> EXPLICIT_DELEGATION_CALL_REQUIRED =
DiagnosticFactory0<PsiElement> EXPLICIT_DELEGATION_CALL_REQUIRED =
DiagnosticFactory0.create(ERROR, PositioningStrategies.SECONDARY_CONSTRUCTOR_DELEGATION_CALL);
DiagnosticFactory1<PsiElement, DeclarationDescriptor> INSTANCE_ACCESS_BEFORE_SUPER_CALL = DiagnosticFactory1.create(ERROR);
@@ -625,6 +629,8 @@ public interface Errors {
DiagnosticFactory1<KtParameter, KotlinType> FORBIDDEN_VARARG_PARAMETER_TYPE = DiagnosticFactory1.create(ERROR, PARAMETER_VARARG_MODIFIER);
DiagnosticFactory0<PsiElement> CHANGING_ARGUMENTS_EXECUTION_ORDER_FOR_NAMED_VARARGS = DiagnosticFactory0.create(WARNING);
// Named parameters
DiagnosticFactory0<KtParameter> DEFAULT_VALUE_NOT_ALLOWED_IN_OVERRIDE = DiagnosticFactory0.create(ERROR, PARAMETER_DEFAULT_VALUE);
@@ -886,6 +892,7 @@ public interface Errors {
DiagnosticFactory1<PsiElement, String> YIELD_IS_RESERVED = DiagnosticFactory1.create(ERROR);
DiagnosticFactory0<PsiElement> UNDERSCORE_IS_RESERVED = DiagnosticFactory0.create(ERROR);
DiagnosticFactory0<PsiElement> UNDERSCORE_USAGE_WITHOUT_BACKTICKS = DiagnosticFactory0.create(ERROR);
DiagnosticFactory0<PsiElement> RESOLVED_TO_UNDERSCORE_NAMED_CATCH_PARAMETER = DiagnosticFactory0.create(WARNING);
DiagnosticFactory1<PsiElement, String> INVALID_CHARACTERS = DiagnosticFactory1.create(ERROR);
DiagnosticFactory1<PsiElement, String> INAPPLICABLE_OPERATOR_MODIFIER = DiagnosticFactory1.create(ERROR);
@@ -1029,7 +1036,7 @@ public interface Errors {
DiagnosticFactory0<KtTypeParameterList> LOCAL_VARIABLE_WITH_TYPE_PARAMETERS_WARNING = DiagnosticFactory0.create(WARNING);
DiagnosticFactory0<KtTypeParameterList> LOCAL_VARIABLE_WITH_TYPE_PARAMETERS = DiagnosticFactory0.create(ERROR);
DiagnosticFactory3<KtExpression, DeclarationDescriptor, DescriptorVisibility, DeclarationDescriptor> INVISIBLE_SETTER = DiagnosticFactory3.create(ERROR);
DiagnosticFactory3<PsiElement, DeclarationDescriptor, DescriptorVisibility, DeclarationDescriptor> INVISIBLE_SETTER = DiagnosticFactory3.create(ERROR);
DiagnosticFactory1<PsiElement, KtKeywordToken> VAL_OR_VAR_ON_LOOP_PARAMETER = DiagnosticFactory1.create(ERROR);
DiagnosticFactory1<PsiElement, KtKeywordToken> VAL_OR_VAR_ON_FUN_PARAMETER = DiagnosticFactory1.create(ERROR);
@@ -1102,7 +1109,7 @@ public interface Errors {
DiagnosticFactory1<KtExpression, ClassifierDescriptorWithTypeParameters> NESTED_CLASS_ACCESSED_VIA_INSTANCE_REFERENCE = DiagnosticFactory1.create(ERROR);
DiagnosticFactory2<KtExpression, ClassDescriptor, String> NESTED_CLASS_SHOULD_BE_QUALIFIED = DiagnosticFactory2.create(ERROR);
DiagnosticFactory1<PsiElement, ClassDescriptor> INACCESSIBLE_OUTER_CLASS_EXPRESSION = DiagnosticFactory1.create(ERROR);
DiagnosticFactory1<PsiElement, ClassDescriptor> INACCESSIBLE_OUTER_CLASS_EXPRESSION = DiagnosticFactory1.create(ERROR, SECONDARY_CONSTRUCTOR_DELEGATION_CALL);
DiagnosticFactory1<KtClassOrObject, String> NESTED_CLASS_NOT_ALLOWED = DiagnosticFactory1.create(ERROR, DECLARATION_NAME);
DiagnosticFactory1<KtClassOrObject, String> NESTED_CLASS_DEPRECATED = DiagnosticFactory1.create(WARNING, DECLARATION_NAME);
@@ -1126,6 +1133,7 @@ public interface Errors {
DiagnosticFactory1<PsiElement, CallableDescriptor> PROTECTED_CALL_FROM_PUBLIC_INLINE_ERROR = DiagnosticFactory1.create(ERROR);
DiagnosticFactory2<KtElement, KtExpression, DeclarationDescriptor> INVALID_DEFAULT_FUNCTIONAL_PARAMETER_FOR_INLINE = DiagnosticFactory2.create(ERROR);
DiagnosticFactory2<KtElement, KtExpression, DeclarationDescriptor> NOT_SUPPORTED_INLINE_PARAMETER_IN_INLINE_PARAMETER_DEFAULT_VALUE = DiagnosticFactory2.create(ERROR);
DiagnosticFactory0<PsiElement> PRIVATE_INLINE_FUNCTIONS_RETURNING_ANONYMOUS_OBJECTS = DiagnosticFactory0.create(WARNING);
DiagnosticFactory0<PsiElement> NON_LOCAL_SUSPENSION_POINT = DiagnosticFactory0.create(ERROR);
DiagnosticFactory1<PsiElement, CallableDescriptor> ILLEGAL_SUSPEND_FUNCTION_CALL = DiagnosticFactory1.create(ERROR);

View File

@@ -46,10 +46,7 @@ object PositioningStrategies {
is KtObjectLiteralExpression -> {
val objectDeclaration = element.objectDeclaration
val objectKeyword = objectDeclaration.getObjectKeyword()!!
val delegationSpecifierList = objectDeclaration.getSuperTypeList()
if (delegationSpecifierList == null) {
return markElement(objectKeyword)
}
val delegationSpecifierList = objectDeclaration.getSuperTypeList() ?: return markElement(objectKeyword)
return markRange(objectKeyword, delegationSpecifierList)
}
is KtObjectDeclaration -> {
@@ -612,15 +609,26 @@ object PositioningStrategies {
}
@JvmField
val SECONDARY_CONSTRUCTOR_DELEGATION_CALL: PositioningStrategy<KtConstructorDelegationCall> =
object : PositioningStrategy<KtConstructorDelegationCall>() {
override fun mark(element: KtConstructorDelegationCall): List<TextRange> {
if (element.isImplicit) {
val constructor = element.getStrictParentOfType<KtSecondaryConstructor>()!!
val valueParameterList = constructor.valueParameterList ?: return markElement(constructor)
return markRange(constructor.getConstructorKeyword(), valueParameterList.lastChild)
val SECONDARY_CONSTRUCTOR_DELEGATION_CALL: PositioningStrategy<PsiElement> =
object : PositioningStrategy<PsiElement>() {
override fun mark(element: PsiElement): List<TextRange> {
when (element) {
is KtSecondaryConstructor -> {
val valueParameterList = element.valueParameterList ?: return markElement(element)
return markRange(element.getConstructorKeyword(), valueParameterList.lastChild)
}
is KtConstructorDelegationCall -> {
if (element.isImplicit) {
// TODO: [VD] FIR collects for some reason implicit KtConstructorDelegationCall
// check(!element.isImplicit) { "Implicit KtConstructorDelegationCall should not be collected directly" }
val constructor = element.getStrictParentOfType<KtSecondaryConstructor>()!!
val valueParameterList = constructor.valueParameterList ?: return markElement(constructor)
return markRange(constructor.getConstructorKeyword(), valueParameterList.lastChild)
}
return markElement(element.calleeExpression ?: element)
}
else -> error("unexpected element $element")
}
return markElement(element.calleeExpression ?: element)
}
}

View File

@@ -51,25 +51,23 @@ fun ResolutionContext<*>.reportTypeMismatchDueToTypeProjection(
): Boolean {
if (!TypeUtils.contains(expectedType) { it.isAnyOrNullableAny() || it.isNothing() || it.isNullableNothing() }) return false
val callPosition = this.callPosition
val (resolvedCall, correspondingNotApproximatedTypeByDescriptor: (CallableDescriptor) -> KotlinType?) = when (callPosition) {
is CallPosition.ValueArgumentPosition -> Pair(
callPosition.resolvedCall, { f: CallableDescriptor ->
is CallPosition.ValueArgumentPosition ->
callPosition.resolvedCall to { f: CallableDescriptor ->
getEffectiveExpectedType(f.valueParameters[callPosition.valueParameter.index], callPosition.valueArgument, this)
})
is CallPosition.ExtensionReceiverPosition -> Pair<ResolvedCall<*>, (CallableDescriptor) -> KotlinType?>(
callPosition.resolvedCall, { f: CallableDescriptor ->
f.extensionReceiverParameter?.type
})
is CallPosition.PropertyAssignment -> Pair<ResolvedCall<out CallableDescriptor>, (CallableDescriptor) -> KotlinType?>(
callPosition.leftPart.getResolvedCall(trace.bindingContext) ?: return false, { f: CallableDescriptor ->
(f as? PropertyDescriptor)?.setter?.valueParameters?.get(0)?.type
})
}
is CallPosition.ExtensionReceiverPosition ->
callPosition.resolvedCall to { f: CallableDescriptor -> f.extensionReceiverParameter?.type }
is CallPosition.PropertyAssignment -> {
if (callPosition.isLeft) return false
val resolvedCall = callPosition.leftPart.getResolvedCall(trace.bindingContext) ?: return false
resolvedCall to { f: CallableDescriptor -> (f as? PropertyDescriptor)?.setter?.valueParameters?.get(0)?.type }
}
is CallPosition.Unknown -> return false
}
val receiverType = resolvedCall.smartCastDispatchReceiverType
?: (resolvedCall.dispatchReceiver ?: return false).type
?: (resolvedCall.dispatchReceiver ?: return false).type
val callableDescriptor = resolvedCall.resultingDescriptor.original

View File

@@ -169,6 +169,7 @@ public class DefaultErrorMessages {
MAP.put(EXPERIMENTAL_UNSIGNED_LITERALS_ERROR, "{0}", STRING);
MAP.put(NON_PARENTHESIZED_ANNOTATIONS_ON_FUNCTIONAL_TYPES, "Non-parenthesized annotations on function types without receiver aren't yet supported (see KT-31734 for details)");
MAP.put(JVM_STATIC_IN_PRIVATE_COMPANION, "@JvmStatic is prohibited in private companion objects. This warning will become an error in the next major version");
MAP.put(REDUNDANT_MODIFIER, "Modifier ''{0}'' is redundant because ''{1}'' is present", TO_STRING, TO_STRING);
MAP.put(REDUNDANT_OPEN_IN_INTERFACE, "Modifier 'open' is redundant for abstract interface members");
@@ -269,6 +270,9 @@ public class DefaultErrorMessages {
MAP.put(USELESS_VARARG_ON_PARAMETER, "Vararg on this parameter is useless");
MAP.put(MULTIPLE_VARARG_PARAMETERS, "Multiple vararg-parameters are prohibited");
MAP.put(FORBIDDEN_VARARG_PARAMETER_TYPE, "Forbidden vararg parameter type: {0}", RENDER_TYPE);
MAP.put(CHANGING_ARGUMENTS_EXECUTION_ORDER_FOR_NAMED_VARARGS, "Arguments execution order is going to be changed in a future release." +
"The expression for named vararg argument will be executed in the order in which it was listed, not at the end." +
"See KT-17691 for more details.");
MAP.put(EXPECTED_DECLARATION_WITH_BODY, "Expected declaration must not have a body");
MAP.put(EXPECTED_CLASS_CONSTRUCTOR_DELEGATION_CALL, "Explicit delegation call for constructor of an expected class is not allowed");
@@ -509,6 +513,7 @@ public class DefaultErrorMessages {
MAP.put(UNDERSCORE_IS_RESERVED, "Names _, __, ___, ..., are reserved in Kotlin");
MAP.put(UNDERSCORE_USAGE_WITHOUT_BACKTICKS, "Names _, __, ___, ... can be used only in back-ticks (`_`, `__`, `___`, ...)");
MAP.put(RESOLVED_TO_UNDERSCORE_NAMED_CATCH_PARAMETER, "Referencing to an underscore-named parameter is deprecated. It will be an error in a future release.");
MAP.put(YIELD_IS_RESERVED, "{0}", STRING);
MAP.put(INVALID_CHARACTERS, "Name {0}", STRING);
@@ -634,6 +639,7 @@ public class DefaultErrorMessages {
MAP.put(CONSTRUCTOR_IN_OBJECT, "Constructors are not allowed for objects");
MAP.put(SUPERTYPE_INITIALIZED_WITHOUT_PRIMARY_CONSTRUCTOR, "Supertype initialization is impossible without primary constructor");
MAP.put(PRIMARY_CONSTRUCTOR_DELEGATION_CALL_EXPECTED, "Primary constructor call expected");
MAP.put(PRIMARY_CONSTRUCTOR_DELEGATION_CALL_EXPECTED_IN_ENUM, "Primary constructor call expected. It's going to be an error in 1.5.");
MAP.put(DELEGATION_SUPER_CALL_IN_ENUM_CONSTRUCTOR, "Call to super is not allowed in enum constructor");
MAP.put(PRIMARY_CONSTRUCTOR_REQUIRED_FOR_DATA_CLASS, "Primary constructor required for data class");
MAP.put(EXPLICIT_DELEGATION_CALL_REQUIRED,
@@ -1015,6 +1021,8 @@ public class DefaultErrorMessages {
MAP.put(PROTECTED_CALL_FROM_PUBLIC_INLINE_ERROR, "Protected function call from public-API inline function is prohibited", NAME);
MAP.put(INVALID_DEFAULT_FUNCTIONAL_PARAMETER_FOR_INLINE, "Invalid default value for inline parameter: ''{0}''. Only lambdas, anonymous functions, and callable references are supported", ELEMENT_TEXT, SHORT_NAMES_IN_TYPES);
MAP.put(NOT_SUPPORTED_INLINE_PARAMETER_IN_INLINE_PARAMETER_DEFAULT_VALUE, "Usage of inline parameter ''{0}'' in default value for another inline parameter is not supported", ELEMENT_TEXT, SHORT_NAMES_IN_TYPES);
MAP.put(PRIVATE_INLINE_FUNCTIONS_RETURNING_ANONYMOUS_OBJECTS, "Return type of the private inline function can't be anonymous. It will be approximated to Any in 1.5." +
"See https://youtrack.jetbrains.com/issue/KT-33917 for more details");
//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);
@@ -1024,8 +1032,8 @@ public class DefaultErrorMessages {
MAP.put(ILLEGAL_SUSPEND_PROPERTY_ACCESS, "Suspend property ''{0}'' should be accessed only from a coroutine or suspend function", NAME);
MAP.put(ILLEGAL_RESTRICTED_SUSPENDING_FUNCTION_CALL, "Restricted suspending functions can only invoke member or extension suspending functions on their restricted coroutine scope");
MAP.put(NON_MODIFIER_FORM_FOR_BUILT_IN_SUSPEND, "''suspend'' function can only be called in a form of modifier of a lambda: suspend { ... }");
MAP.put(IMPLICIT_NOTHING_TYPE_ARGUMENT_IN_RETURN_POSITION, "Returning type parameter has been inferred to Nothing implicitly. Please, specify type arguments explicitly to hide this warning. Nothing can produce an exception at runtime.");
MAP.put(IMPLICIT_NOTHING_TYPE_ARGUMENT_AGAINST_NOT_NOTHING_EXPECTED_TYPE, "Returning type parameter has been inferred to Nothing implicitly because Nothing is more specific than specified expected type. Please specify type arguments explicitly in accordance with expected type to hide this warning. Nothing can produce an exception at runtime.");
MAP.put(IMPLICIT_NOTHING_TYPE_ARGUMENT_IN_RETURN_POSITION, "Returning type parameter has been inferred to Nothing implicitly. Please specify type arguments explicitly to hide this warning. Nothing can produce an exception at runtime.");
MAP.put(IMPLICIT_NOTHING_TYPE_ARGUMENT_AGAINST_NOT_NOTHING_EXPECTED_TYPE, "Returning type parameter has been inferred to Nothing implicitly because Nothing is more specific than specified expected type. Please specify type arguments explicitly in accordance with expected type to hide this warning. Nothing can produce an exception at runtime. See KT-36776 for more details.");
MAP.put(RETURN_FOR_BUILT_IN_SUSPEND, "Using implicit label for this lambda is prohibited");
MAP.put(MODIFIER_FORM_FOR_NON_BUILT_IN_SUSPEND, "Calls having a form of ''suspend {}'' are deprecated because ''suspend'' in the context will have a meaning of a modifier. Add empty argument list to the call: ''suspend() { ... }''");

View File

@@ -42,6 +42,7 @@ import org.jetbrains.kotlin.lexer.KtTokens;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.psi.psiUtil.PsiUtilsKt;
import org.jetbrains.kotlin.resolve.calls.callResolverUtil.CallResolverUtilKt;
import org.jetbrains.kotlin.resolve.calls.components.InferenceSession;
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo;
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfoFactory;
@@ -1371,7 +1372,9 @@ public class DescriptorResolver {
}
if (isStaticNestedClass(classDescriptor)) {
trace.report(INACCESSIBLE_OUTER_CLASS_EXPRESSION.on(reportErrorsOn, classDescriptor));
PsiElement onReport = (reportErrorsOn instanceof KtConstructorDelegationCall)
? CallResolverUtilKt.reportOnElement((KtConstructorDelegationCall) reportErrorsOn) : reportErrorsOn;
trace.report(INACCESSIBLE_OUTER_CLASS_EXPRESSION.on(onReport, classDescriptor));
return false;
}
classDescriptor = getParentOfType(classDescriptor, ClassDescriptor.class, true);

View File

@@ -38,9 +38,12 @@ import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.DescriptorUtils.classCanHaveAbstractFakeOverride
import org.jetbrains.kotlin.resolve.OverridingUtil.OverrideCompatibilityInfo.Result.OVERRIDABLE
import org.jetbrains.kotlin.resolve.calls.callResolverUtil.isOrOverridesSynthesized
import org.jetbrains.kotlin.resolve.descriptorUtil.getKotlinTypeRefiner
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.types.checker.KotlinTypeRefiner
import org.jetbrains.kotlin.types.checker.NewKotlinTypeCheckerImpl
import org.jetbrains.kotlin.types.refinement.TypeRefinement
import org.jetbrains.kotlin.utils.addToStdlib.assertedCast
import java.util.*
@@ -74,7 +77,7 @@ class OverrideResolver(
val inheritedMemberErrors = CollectErrorInformationForInheritedMembersStrategy(klass, classDescriptor)
checkInheritedAndDelegatedSignatures(classDescriptor, inheritedMemberErrors, inheritedMemberErrors)
checkInheritedAndDelegatedSignatures(classDescriptor, inheritedMemberErrors, inheritedMemberErrors, kotlinTypeRefiner)
inheritedMemberErrors.doReportErrors()
}
@@ -200,17 +203,13 @@ class OverrideResolver(
overriding: CallableMemberDescriptor,
overridden: CallableMemberDescriptor
) {
reportDelegationProblemIfRequired(
RETURN_TYPE_MISMATCH_BY_DELEGATION, RETURN_TYPE_MISMATCH_ON_INHERITANCE, overriding, overridden
)
}
val (diagnosticFactory, relevantDiagnosticFromInheritance) = if (overridden is PropertyDescriptor)
PROPERTY_TYPE_MISMATCH_BY_DELEGATION to PROPERTY_TYPE_MISMATCH_ON_INHERITANCE
else
RETURN_TYPE_MISMATCH_BY_DELEGATION to RETURN_TYPE_MISMATCH_ON_INHERITANCE
override fun propertyTypeMismatchOnOverride(
overriding: PropertyDescriptor,
overridden: PropertyDescriptor
) {
reportDelegationProblemIfRequired(
PROPERTY_TYPE_MISMATCH_BY_DELEGATION, PROPERTY_TYPE_MISMATCH_ON_INHERITANCE, overriding, overridden
diagnosticFactory, relevantDiagnosticFromInheritance, overriding, overridden
)
}
@@ -263,7 +262,6 @@ class OverrideResolver(
private interface CheckOverrideReportStrategy {
fun overridingFinalMember(overriding: CallableMemberDescriptor, overridden: CallableMemberDescriptor)
fun returnTypeMismatchOnOverride(overriding: CallableMemberDescriptor, overridden: CallableMemberDescriptor)
fun propertyTypeMismatchOnOverride(overriding: PropertyDescriptor, overridden: PropertyDescriptor)
fun varOverriddenByVal(overriding: CallableMemberDescriptor, overridden: CallableMemberDescriptor)
}
@@ -310,19 +308,17 @@ class OverrideResolver(
override fun returnTypeMismatchOnOverride(overriding: CallableMemberDescriptor, overridden: CallableMemberDescriptor) {
if (!typeMismatchError) {
typeMismatchError = true
trace.report(RETURN_TYPE_MISMATCH_ON_OVERRIDE.on(
member, declared, DeclarationWithDiagnosticComponents(overridden, platformSpecificDiagnosticComponents)
))
}
}
override fun propertyTypeMismatchOnOverride(overriding: PropertyDescriptor, overridden: PropertyDescriptor) {
if (!typeMismatchError) {
typeMismatchError = true
if (overridden.isVar) {
trace.report(VAR_TYPE_MISMATCH_ON_OVERRIDE.on(member, declared, overridden))
} else {
trace.report(PROPERTY_TYPE_MISMATCH_ON_OVERRIDE.on(member, declared, overridden))
when {
overridden is PropertyDescriptor && overridden.isVar ->
trace.report(VAR_TYPE_MISMATCH_ON_OVERRIDE.on(member, declared, overridden))
overridden is PropertyDescriptor && !overridden.isVar ->
trace.report(PROPERTY_TYPE_MISMATCH_ON_OVERRIDE.on(member, declared, overridden))
else -> trace.report(RETURN_TYPE_MISMATCH_ON_OVERRIDE.on(
member, declared, DeclarationWithDiagnosticComponents(overridden, platformSpecificDiagnosticComponents)
))
}
}
}
@@ -371,14 +367,10 @@ class OverrideResolver(
}
}
override fun propertyTypeMismatchOnOverride(overriding: PropertyDescriptor, overridden: PropertyDescriptor) {
throw IllegalStateException("Component functions are not properties")
}
override fun varOverriddenByVal(overriding: CallableMemberDescriptor, overridden: CallableMemberDescriptor) {
throw IllegalStateException("Component functions are not properties")
}
})
}, kotlinTypeRefiner)
}
private fun checkOverrideForCopyFunction(copyFunction: CallableMemberDescriptor) {
@@ -561,18 +553,25 @@ class OverrideResolver(
fun getMissingImplementations(classDescriptor: ClassDescriptor): Set<CallableMemberDescriptor> {
val collector = CollectMissingImplementationsStrategy()
checkInheritedAndDelegatedSignatures(classDescriptor, collector, null)
// Note that it is fine to pass default refiner here. Reason:
// 1. We bind overrides with proper refiners and [checkInheritedAndDelegatedSignatures] skips all properly-bound overrides,
// so we would consider only unbound overrides
// 2. Using default refiner instead of proper one can only increase amount of type mismatches, not decrease it
// Putting 1 and 2 together means that using default refiner might make already unbound overrides even "more unbound", which
// isn't an issue for case of [getMissingImplementations]
checkInheritedAndDelegatedSignatures(classDescriptor, collector, null, KotlinTypeRefiner.Default)
return collector.shouldImplement
}
private fun checkInheritedAndDelegatedSignatures(
classDescriptor: ClassDescriptor,
inheritedReportStrategy: CheckInheritedSignaturesReportStrategy,
overrideReportStrategyForDelegates: CheckOverrideReportStrategy?
overrideReportStrategyForDelegates: CheckOverrideReportStrategy?,
kotlinTypeRefiner: KotlinTypeRefiner
) {
for (member in DescriptorUtils.getAllDescriptors(classDescriptor.defaultType.memberScope)) {
if (member is CallableMemberDescriptor) {
checkInheritedAndDelegatedSignatures(member, inheritedReportStrategy, overrideReportStrategyForDelegates)
checkInheritedAndDelegatedSignatures(member, inheritedReportStrategy, overrideReportStrategyForDelegates, kotlinTypeRefiner)
}
}
}
@@ -580,7 +579,8 @@ class OverrideResolver(
private fun checkInheritedAndDelegatedSignatures(
descriptor: CallableMemberDescriptor,
reportingStrategy: CheckInheritedSignaturesReportStrategy,
overrideReportStrategyForDelegates: CheckOverrideReportStrategy?
overrideReportStrategyForDelegates: CheckOverrideReportStrategy?,
kotlinTypeRefiner: KotlinTypeRefiner
) {
val kind = descriptor.kind
if (kind != FAKE_OVERRIDE && kind != DELEGATION) return
@@ -606,10 +606,10 @@ class OverrideResolver(
return
}
checkInheritedDescriptorsGroup(descriptor, relevantDirectlyOverridden, reportingStrategy)
checkInheritedDescriptorsGroup(descriptor, relevantDirectlyOverridden, reportingStrategy, kotlinTypeRefiner)
if (kind == DELEGATION && overrideReportStrategyForDelegates != null) {
checkOverridesForMember(descriptor, relevantDirectlyOverridden, overrideReportStrategyForDelegates)
checkOverridesForMember(descriptor, relevantDirectlyOverridden, overrideReportStrategyForDelegates, kotlinTypeRefiner)
}
if (kind != DELEGATION) {
@@ -632,7 +632,7 @@ class OverrideResolver(
1 ->
if (kind != DELEGATION) {
val implementation = concreteOverridden.first()
collectAbstractMethodsWithMoreSpecificReturnType(abstractOverridden, implementation).forEach {
collectAbstractMethodsWithMoreSpecificReturnType(abstractOverridden, implementation, kotlinTypeRefiner).forEach {
reportingStrategy.abstractMemberWithMoreSpecificType(it, implementation)
}
}
@@ -703,9 +703,10 @@ class OverrideResolver(
private fun collectAbstractMethodsWithMoreSpecificReturnType(
abstractOverridden: List<CallableMemberDescriptor>,
implementation: CallableMemberDescriptor
implementation: CallableMemberDescriptor,
kotlinTypeRefiner: KotlinTypeRefiner
): List<CallableMemberDescriptor> =
abstractOverridden.filter { abstractMember -> !isReturnTypeOkForOverride(abstractMember, implementation) }
abstractOverridden.filter { abstractMember -> !isReturnTypeOkForOverride(abstractMember, implementation, kotlinTypeRefiner) }
private fun getRelevantDirectlyOverridden(
overriddenByParent: MutableMap<CallableMemberDescriptor, Set<CallableMemberDescriptor>>,
@@ -778,23 +779,18 @@ class OverrideResolver(
private fun checkInheritedDescriptorsGroup(
descriptor: CallableMemberDescriptor,
overriddenDescriptors: Collection<CallableMemberDescriptor>,
reportingStrategy: CheckInheritedSignaturesReportStrategy
reportingStrategy: CheckInheritedSignaturesReportStrategy,
kotlinTypeRefiner: KotlinTypeRefiner
) {
if (overriddenDescriptors.size <= 1) return
val propertyDescriptor = descriptor as? PropertyDescriptor
for (overriddenDescriptor in overriddenDescriptors) {
if (propertyDescriptor != null) {
val overriddenPropertyDescriptor =
overriddenDescriptor.assertedCast<PropertyDescriptor> { "$overriddenDescriptor is not a property" }
if (!isPropertyTypeOkForOverride(overriddenPropertyDescriptor, propertyDescriptor)) {
reportingStrategy.typeMismatchOnInheritance(propertyDescriptor, overriddenPropertyDescriptor)
}
} else {
if (!isReturnTypeOkForOverride(overriddenDescriptor, descriptor)) {
reportingStrategy.typeMismatchOnInheritance(descriptor, overriddenDescriptor)
}
require(descriptor !is PropertyDescriptor || overriddenDescriptor is PropertyDescriptor) {
"$overriddenDescriptor is not a property"
}
if (!isReturnTypeOkForOverride(overriddenDescriptor, descriptor, kotlinTypeRefiner)) {
reportingStrategy.typeMismatchOnInheritance(descriptor, overriddenDescriptor)
}
}
}
@@ -806,7 +802,7 @@ class OverrideResolver(
) {
val overriddenDescriptors = declared.overriddenDescriptors
checkOverridesForMember(declared, overriddenDescriptors, reportError)
checkOverridesForMember(declared, overriddenDescriptors, reportError, kotlinTypeRefiner)
if (overriddenDescriptors.isEmpty()) {
val containingDeclaration = declared.containingDeclaration
@@ -829,23 +825,18 @@ class OverrideResolver(
private fun checkOverridesForMember(
memberDescriptor: CallableMemberDescriptor,
overriddenDescriptors: Collection<CallableMemberDescriptor>,
reportError: CheckOverrideReportStrategy
reportError: CheckOverrideReportStrategy,
kotlinTypeRefiner: KotlinTypeRefiner
) {
val propertyMemberDescriptor = if (memberDescriptor is PropertyDescriptor) memberDescriptor else null
for (overridden in overriddenDescriptors) {
if (overridden.modality == Modality.FINAL) {
reportError.overridingFinalMember(memberDescriptor, overridden)
}
if (propertyMemberDescriptor != null) {
val overriddenProperty = overridden.assertedCast<PropertyDescriptor> {
"$overridden is overridden by property $propertyMemberDescriptor"
if (!isReturnTypeOkForOverride(overridden, memberDescriptor, kotlinTypeRefiner)) {
require(memberDescriptor !is PropertyDescriptor || overridden is PropertyDescriptor) {
"$overridden is overridden by property $memberDescriptor"
}
if (!isPropertyTypeOkForOverride(overriddenProperty, propertyMemberDescriptor)) {
reportError.propertyTypeMismatchOnOverride(propertyMemberDescriptor, overriddenProperty)
}
} else if (!isReturnTypeOkForOverride(overridden, memberDescriptor)) {
reportError.returnTypeMismatchOnOverride(memberDescriptor, overridden)
}
@@ -857,7 +848,8 @@ class OverrideResolver(
private fun isReturnTypeOkForOverride(
superDescriptor: CallableDescriptor,
subDescriptor: CallableDescriptor
subDescriptor: CallableDescriptor,
kotlinTypeRefiner: KotlinTypeRefiner,
): Boolean {
val typeSubstitutor = prepareTypeSubstitutor(superDescriptor, subDescriptor) ?: return false
@@ -867,7 +859,11 @@ class OverrideResolver(
val substitutedSuperReturnType = typeSubstitutor.substitute(superReturnType, Variance.OUT_VARIANCE)!!
return KotlinTypeChecker.DEFAULT.isSubtypeOf(subReturnType, substitutedSuperReturnType)
val typeChecker = NewKotlinTypeCheckerImpl(kotlinTypeRefiner)
return if (superDescriptor is PropertyDescriptor && superDescriptor.isVar)
typeChecker.equalTypes(subReturnType, substitutedSuperReturnType)
else
typeChecker.isSubtypeOf(subReturnType, substitutedSuperReturnType)
}
private fun prepareTypeSubstitutor(
@@ -886,21 +882,6 @@ class OverrideResolver(
return IndexedParametersSubstitution(superTypeParameters, arguments).buildSubstitutor()
}
private fun isPropertyTypeOkForOverride(
superDescriptor: PropertyDescriptor,
subDescriptor: PropertyDescriptor
): Boolean {
val typeSubstitutor = prepareTypeSubstitutor(superDescriptor, subDescriptor) ?: return false
val substitutedSuperReturnType = typeSubstitutor.substitute(superDescriptor.type, Variance.OUT_VARIANCE)!!
return if (superDescriptor.isVar) {
KotlinTypeChecker.DEFAULT.equalTypes(subDescriptor.type, substitutedSuperReturnType)
} else {
KotlinTypeChecker.DEFAULT.isSubtypeOf(subDescriptor.type, substitutedSuperReturnType)
}
}
private fun findDataModifierForDataClass(dataClass: DeclarationDescriptor): PsiElement {
val classDeclaration = DescriptorToSourceUtils.getSourceFromDescriptor(dataClass) as KtClassOrObject?
if (classDeclaration?.modifierList != null) {

View File

@@ -8,6 +8,7 @@ package org.jetbrains.kotlin.resolve
import org.jetbrains.kotlin.builtins.PlatformToKotlinClassMapper
import org.jetbrains.kotlin.container.*
import org.jetbrains.kotlin.resolve.calls.checkers.*
import org.jetbrains.kotlin.resolve.calls.inference.InferenceCompatibilityCheckerImpl
import org.jetbrains.kotlin.resolve.calls.results.TypeSpecificityComparator
import org.jetbrains.kotlin.resolve.checkers.*
import org.jetbrains.kotlin.resolve.lazy.DelegationFilter
@@ -38,7 +39,8 @@ private val DEFAULT_DECLARATION_CHECKERS = listOf(
MissingDependencySupertypeChecker.ForDeclarations,
FunInterfaceDeclarationChecker(),
DeprecatedSinceKotlinAnnotationChecker,
ContractDescriptionBlockChecker
ContractDescriptionBlockChecker,
PrivateInlineFunctionsReturningAnonymousObjectsChecker
)
private val DEFAULT_CALL_CHECKERS = listOf(
@@ -52,7 +54,8 @@ private val DEFAULT_CALL_CHECKERS = listOf(
UselessElvisCallChecker(), ResultTypeWithNullableOperatorsChecker(), NullableVarargArgumentCallChecker,
NamedFunAsExpressionChecker, ContractNotAllowedCallChecker, ReifiedTypeParameterSubstitutionChecker(),
MissingDependencySupertypeChecker.ForCalls, AbstractClassInstantiationChecker, SuspendConversionCallChecker,
UnitConversionCallChecker, FunInterfaceConstructorReferenceChecker, NullableExtensionOperatorWithSafeCallChecker
UnitConversionCallChecker, FunInterfaceConstructorReferenceChecker, NullableExtensionOperatorWithSafeCallChecker,
ReferencingToUnderscoreNamedParameterOfCatchBlockChecker, VarargWrongExecutionOrderChecker
)
private val DEFAULT_TYPE_CHECKERS = emptyList<AdditionalTypeChecker>()
private val DEFAULT_CLASSIFIER_USAGE_CHECKERS = listOf(
@@ -107,6 +110,7 @@ abstract class PlatformConfiguratorBase(
override fun configureModuleDependentCheckers(container: StorageComponentContainer) {
container.useImpl<ExperimentalMarkerDeclarationAnnotationChecker>()
container.useImpl<InferenceCompatibilityCheckerImpl>()
}
fun configureExtensionsAndCheckers(container: StorageComponentContainer) {

View File

@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.resolve
import com.intellij.codeInsight.completion.CompletionUtilCore
import com.intellij.psi.impl.source.DummyHolder
import com.intellij.util.SmartList
import org.jetbrains.kotlin.config.AnalysisFlags
@@ -573,6 +574,9 @@ class QualifiedExpressionResolver(val languageVersionSettings: LanguageVersionSe
context: ExpressionTypingContext
): Qualifier? {
val name = expression.getReferencedNameAsName()
if (!expression.isPhysical && !name.isSpecial && name.asString().endsWith(CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED)) {
return null
}
val location = KotlinLookupLocation(expression)
val qualifierDescriptor = when (receiver) {

View File

@@ -17,6 +17,7 @@ import org.jetbrains.kotlin.config.LanguageFeature;
import org.jetbrains.kotlin.config.LanguageVersionSettings;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.annotations.Annotations;
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory0;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.progress.ProgressIndicatorAndCompilationCanceledStatus;
import org.jetbrains.kotlin.psi.*;
@@ -334,8 +335,12 @@ public class CallResolver {
KtConstructorDelegationCall delegationCall = (KtConstructorDelegationCall) context.call.getCallElement();
DeclarationDescriptor container = context.scope.getOwnerDescriptor();
assert container instanceof ConstructorDescriptor : "Trying to resolve JetConstructorDelegationCall not in constructor. scope.ownerDescriptor = " + container;
return (OverloadResolutionResults) resolveConstructorDelegationCall(context, delegationCall, (KtConstructorDelegationReferenceExpression) calleeExpression,
(ClassConstructorDescriptor) container);
return (OverloadResolutionResults) resolveConstructorDelegationCall(
context,
delegationCall,
(KtConstructorDelegationReferenceExpression) calleeExpression,
(ClassDescriptor) container.getContainingDeclaration()
);
}
else if (calleeExpression == null) {
return checkArgumentTypesAndFail(context);
@@ -433,18 +438,28 @@ public class CallResolver {
dataFlowValueFactory,
InferenceSession.Companion.getDefault());
if (call.getCalleeExpression() == null) return checkArgumentTypesAndFail(context);
KtConstructorDelegationReferenceExpression calleeExpression = call.getCalleeExpression();
if (calleeExpression == null) return checkArgumentTypesAndFail(context);
ClassDescriptor currentClassDescriptor = constructorDescriptor.getContainingDeclaration();
if (constructorDescriptor.getConstructedClass().getKind() == ClassKind.ENUM_CLASS && call.isImplicit()) {
if (currentClassDescriptor.getUnsubstitutedPrimaryConstructor() != null) {
DiagnosticFactory0<PsiElement> warningOrError;
if (languageVersionSettings.supportsFeature(LanguageFeature.RequiredPrimaryConstructorDelegationCallInEnums)) {
warningOrError = PRIMARY_CONSTRUCTOR_DELEGATION_CALL_EXPECTED; // error
} else {
warningOrError = PRIMARY_CONSTRUCTOR_DELEGATION_CALL_EXPECTED_IN_ENUM; // warning
}
PsiElement reportOn = calcReportOn(calleeExpression);
context.trace.report(warningOrError.on(reportOn));
}
return null;
}
return resolveConstructorDelegationCall(
context,
call,
call.getCalleeExpression(),
constructorDescriptor
);
return resolveConstructorDelegationCall(context, call, call.getCalleeExpression(), currentClassDescriptor);
}
@NotNull
@@ -452,12 +467,10 @@ public class CallResolver {
@NotNull BasicCallResolutionContext context,
@NotNull KtConstructorDelegationCall call,
@NotNull KtConstructorDelegationReferenceExpression calleeExpression,
@NotNull ClassConstructorDescriptor calleeConstructor
@NotNull ClassDescriptor currentClassDescriptor
) {
context.trace.record(BindingContext.LEXICAL_SCOPE, call, context.scope);
ClassDescriptor currentClassDescriptor = calleeConstructor.getContainingDeclaration();
boolean isThisCall = calleeExpression.isThis();
if (currentClassDescriptor.getKind() == ClassKind.ENUM_CLASS && !isThisCall) {
context.trace.report(DELEGATION_SUPER_CALL_IN_ENUM_CONSTRUCTOR.on(calleeExpression));
@@ -471,9 +484,8 @@ public class CallResolver {
if (!isThisCall && currentClassDescriptor.getUnsubstitutedPrimaryConstructor() != null) {
if (DescriptorUtils.canHaveDeclaredConstructors(currentClassDescriptor)) {
// Diagnostic is meaningless when reporting on interfaces and object
context.trace.report(PRIMARY_CONSTRUCTOR_DELEGATION_CALL_EXPECTED.on(
(KtConstructorDelegationCall) calleeExpression.getParent()
));
PsiElement reportOn = calcReportOn(calleeExpression);
context.trace.report(PRIMARY_CONSTRUCTOR_DELEGATION_CALL_EXPECTED.on(reportOn));
}
if (call.isImplicit()) return OverloadResolutionResultsImpl.nameNotFound();
}
@@ -484,9 +496,8 @@ public class CallResolver {
}
KotlinType superType = isThisCall ?
calleeConstructor.getContainingDeclaration().getDefaultType() :
DescriptorUtils.getSuperClassType(currentClassDescriptor);
KotlinType superType =
isThisCall ? currentClassDescriptor.getDefaultType() : DescriptorUtils.getSuperClassType(currentClassDescriptor);
Pair<Collection<ResolutionCandidate<ConstructorDescriptor>>, BasicCallResolutionContext> candidatesAndContext =
prepareCandidatesAndContextForConstructorCall(superType, context, syntheticScopes);
@@ -508,6 +519,13 @@ public class CallResolver {
return computeTasksFromCandidatesAndResolvedCall(context, candidates, tracing);
}
@Nullable
private PsiElement calcReportOn(@NotNull KtConstructorDelegationReferenceExpression calleeExpression) {
PsiElement delegationCall = calleeExpression.getParent();
return delegationCall instanceof KtConstructorDelegationCall
? CallResolverUtilKt.reportOnElement((KtConstructorDelegationCall) delegationCall) : delegationCall;
}
@NotNull
private static Pair<Collection<ResolutionCandidate<ConstructorDescriptor>>, BasicCallResolutionContext> prepareCandidatesAndContextForConstructorCall(
@NotNull KotlinType superType,

View File

@@ -15,6 +15,7 @@ import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.impl.TypeAliasConstructorDescriptor
import org.jetbrains.kotlin.lexer.KtToken
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingTrace
import org.jetbrains.kotlin.resolve.calls.CallTransformer
import org.jetbrains.kotlin.resolve.calls.components.isVararg
@@ -236,9 +237,12 @@ private fun arrayAssignmentToVarargInNamedFormInAnnotation(
): Boolean {
if (!languageVersionSettings.supportsFeature(LanguageFeature.AssigningArraysToVarargsInNamedFormInAnnotations)) return false
if (!isParameterOfAnnotation(parameterDescriptor)) return false
val isAllowedAssigningSingleElementsToVarargsInNamedForm =
!languageVersionSettings.supportsFeature(LanguageFeature.ProhibitAssigningSingleElementsToVarargsInNamedForm)
return argument.isNamed() && parameterDescriptor.isVararg && isArrayOrArrayLiteral(argument, trace)
if (isAllowedAssigningSingleElementsToVarargsInNamedForm && !isArrayOrArrayLiteral(argument, trace)) return false
return isParameterOfAnnotation(parameterDescriptor) && argument.isNamed() && parameterDescriptor.isVararg
}
private fun arrayAssignmentToVarargInNamedFormInFunction(
@@ -249,7 +253,12 @@ private fun arrayAssignmentToVarargInNamedFormInFunction(
): Boolean {
if (!languageVersionSettings.supportsFeature(LanguageFeature.AllowAssigningArrayElementsToVarargsInNamedFormForFunctions)) return false
return argument.isNamed() && parameterDescriptor.isVararg && isArrayOrArrayLiteral(argument, trace)
val isAllowedAssigningSingleElementsToVarargsInNamedForm =
!languageVersionSettings.supportsFeature(LanguageFeature.ProhibitAssigningSingleElementsToVarargsInNamedForm)
if (isAllowedAssigningSingleElementsToVarargsInNamedForm && !isArrayOrArrayLiteral(argument, trace)) return false
return argument.isNamed() && parameterDescriptor.isVararg
}
fun isArrayOrArrayLiteral(argument: ValueArgument, trace: BindingTrace): Boolean {
@@ -312,3 +321,7 @@ fun createResolutionCandidatesForConstructors(
ResolutionCandidate.create(call, it, dispatchReceiver, receiverKind, knownSubstitutor)
}
}
internal fun KtConstructorDelegationCall.reportOnElement() = if (this.isImplicit) {
this.getStrictParentOfType<KtSecondaryConstructor>()!!
} else this

View File

@@ -159,7 +159,11 @@ class DiagnosticReporterByTrackingStrategy(
CallableReferenceCandidatesAmbiguity::class.java -> {
val ambiguityDiagnostic = diagnostic as CallableReferenceCandidatesAmbiguity
val expression = ambiguityDiagnostic.argument.psiExpression.safeAs<KtCallableReferenceExpression>()
val expression = when (val psiExpression = ambiguityDiagnostic.argument.psiExpression) {
is KtPsiUtil.KtExpressionWrapper -> psiExpression.baseExpression
else -> psiExpression
}.safeAs<KtCallableReferenceExpression>()
val candidates = ambiguityDiagnostic.candidates.map { it.candidate }
if (expression != null) {
trace.reportDiagnosticOnce(CALLABLE_REFERENCE_RESOLUTION_AMBIGUITY.on(expression.callableReference, candidates))

View File

@@ -14,6 +14,7 @@ import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.SPECIAL_FUNCTION_NAMES
import org.jetbrains.kotlin.resolve.calls.callUtil.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.components.stableType
import org.jetbrains.kotlin.resolve.calls.model.*
import org.jetbrains.kotlin.resolve.calls.tower.NewResolvedCallImpl
import org.jetbrains.kotlin.resolve.calls.tower.psiExpression
@@ -96,8 +97,15 @@ object ImplicitNothingAsTypeParameterCallChecker : CallChecker {
}
val resolvedCallAtom = resolvedAtom.getResolvedCallAtom(context.trace.bindingContext) ?: continue
val atom = resolvedAtom.atom
if (atom is SimpleKotlinCallArgument && !atom.receiver.stableType.isNothingOrNullableNothing())
continue
val candidateDescriptor = resolvedCallAtom.candidateDescriptor
val isReturnTypeOwnTypeParameter = candidateDescriptor.typeParameters.any { it.defaultType == candidateDescriptor.returnType }
val isReturnTypeOwnTypeParameter = candidateDescriptor.typeParameters.any {
it.typeConstructor == candidateDescriptor.returnType?.constructor
}
val isSpecialCall = candidateDescriptor.name in SPECIAL_FUNCTION_NAMES
val hasExplicitTypeArguments = resolvedCallAtom.atom.psiKotlinCall.typeArguments.isNotEmpty() // not required

View File

@@ -0,0 +1,49 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* 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.calls.checkers
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.builtins.isBuiltinFunctionalType
import org.jetbrains.kotlin.builtins.isFunctionOrSuspendFunctionType
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.reportDiagnosticOnce
import org.jetbrains.kotlin.diagnostics.reportDiagnosticOnceWrtDiagnosticFactoryList
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.SPECIAL_FUNCTION_NAMES
import org.jetbrains.kotlin.resolve.calls.callUtil.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.*
import org.jetbrains.kotlin.resolve.calls.tower.NewResolvedCallImpl
import org.jetbrains.kotlin.resolve.calls.tower.psiCallArgument
import org.jetbrains.kotlin.resolve.calls.tower.psiExpression
import org.jetbrains.kotlin.resolve.calls.tower.psiKotlinCall
import org.jetbrains.kotlin.resolve.descriptorUtil.isUnderscoreNamed
import org.jetbrains.kotlin.resolve.source.KotlinSourceElement
import org.jetbrains.kotlin.types.DeferredType
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.typeUtil.isNothing
import org.jetbrains.kotlin.types.typeUtil.isNothingOrNullableNothing
import org.jetbrains.kotlin.types.typeUtil.isTypeParameter
object ReferencingToUnderscoreNamedParameterOfCatchBlockChecker : CallChecker {
override fun check(resolvedCall: ResolvedCall<*>, reportOn: PsiElement, context: CallCheckerContext) {
val descriptor = resolvedCall.resultingDescriptor
if (descriptor !is LocalVariableDescriptor || !descriptor.isUnderscoreNamed) return
val sourceElement = descriptor.source as? KotlinSourceElement ?: return
val ktParameter = sourceElement.psi as? KtParameter ?: return
if (ktParameter.isCatchParameter) {
context.trace.reportDiagnosticOnce(Errors.RESOLVED_TO_UNDERSCORE_NAMED_CATCH_PARAMETER.on(reportOn))
}
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* 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.calls.checkers
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.resolve.calls.callUtil.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.components.isVararg
import org.jetbrains.kotlin.resolve.calls.model.*
import org.jetbrains.kotlin.resolve.descriptorUtil.isAnnotationConstructor
object VarargWrongExecutionOrderChecker : CallChecker {
override fun check(resolvedCall: ResolvedCall<*>, reportOn: PsiElement, context: CallCheckerContext) {
val isCorrectExecutionOrderForVarargArgumentsAlreadyUsed =
context.languageVersionSettings.getFeatureSupport(LanguageFeature.UseCorrectExecutionOrderForVarargArguments) == LanguageFeature.State.ENABLED
if (resolvedCall.candidateDescriptor.isAnnotationConstructor()) return
if (isCorrectExecutionOrderForVarargArgumentsAlreadyUsed) return
val valueArguments = resolvedCall.call.valueArguments
val varargIndex = valueArguments.indexOfFirst {
resolvedCall.getParameterForArgument(it)?.isVararg == true
}.takeIf { it != -1 } ?: return
val nonVarargIndex = valueArguments.indexOfLast {
resolvedCall.getParameterForArgument(it)?.isVararg != true
}.takeIf { it != -1 } ?: return
if (varargIndex > nonVarargIndex) return
val varargValueArgument = valueArguments[varargIndex]
if (!varargValueArgument.isNamed() || varargValueArgument !is PsiElement) return
// If named form for vararg is used then we can have only one real value argument on a call site
context.trace.report(Errors.CHANGING_ARGUMENTS_EXECUTION_ORDER_FOR_NAMED_VARARGS.on(varargValueArgument))
}
}

View File

@@ -33,5 +33,5 @@ sealed class CallPosition {
val valueArgument: ValueArgument
) : CallPosition()
class PropertyAssignment(val leftPart: KtExpression?) : CallPosition()
class PropertyAssignment(val leftPart: KtExpression?, val isLeft: Boolean) : CallPosition()
}

View File

@@ -6,6 +6,7 @@
package org.jetbrains.kotlin.resolve.calls.inference
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.impl.*
@@ -81,7 +82,13 @@ class CoroutineInferenceSession(
return !storage.notFixedTypeVariables.keys.any {
val variable = storage.allTypeVariables[it]
val isPostponed = variable != null && variable in storage.postponedTypeVariables
!isPostponed && !kotlinConstraintSystemCompleter.variableFixationFinder.isTypeVariableHasProperConstraint(system, it)
val useInferenceCompatibilityMode =
topLevelCallContext.languageVersionSettings.supportsFeature(LanguageFeature.InferenceCompatibility)
!isPostponed && !kotlinConstraintSystemCompleter.variableFixationFinder.isTypeVariableHasProperConstraint(
system,
it,
useInferenceCompatibilityMode
)
} || candidate.getSubResolvedAtoms().any { it.hasPostponed() }
}

View File

@@ -22,12 +22,11 @@ import org.jetbrains.kotlin.diagnostics.Errors.UNRESOLVED_REFERENCE
import org.jetbrains.kotlin.diagnostics.Errors.UNRESOLVED_REFERENCE_WRONG_RECEIVER
import org.jetbrains.kotlin.psi.Call
import org.jetbrains.kotlin.psi.KtConstructorDelegationCall
import org.jetbrains.kotlin.psi.KtLambdaArgument
import org.jetbrains.kotlin.psi.KtSecondaryConstructor
import org.jetbrains.kotlin.resolve.BindingContext.CALL
import org.jetbrains.kotlin.resolve.BindingContext.REFERENCE_TARGET
import org.jetbrains.kotlin.resolve.BindingContext.RESOLVED_CALL
import org.jetbrains.kotlin.resolve.BindingTrace
import org.jetbrains.kotlin.resolve.calls.callResolverUtil.reportOnElement
import org.jetbrains.kotlin.resolve.calls.context.ResolutionContext
import org.jetbrains.kotlin.resolve.calls.inference.InferenceErrorData
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
@@ -83,8 +82,9 @@ class TracingStrategyForImplicitConstructorDelegationCall(
}
private fun reportError(trace: BindingTrace) {
if (!trace.bindingContext.diagnostics.forElement(delegationCall).any { it.factory == Errors.EXPLICIT_DELEGATION_CALL_REQUIRED }) {
trace.report(Errors.EXPLICIT_DELEGATION_CALL_REQUIRED.on(delegationCall))
val reportOn = delegationCall.reportOnElement()
if (!trace.bindingContext.diagnostics.forElement(reportOn).any { it.factory == Errors.EXPLICIT_DELEGATION_CALL_REQUIRED }) {
trace.report(Errors.EXPLICIT_DELEGATION_CALL_REQUIRED.on(reportOn))
}
}

View File

@@ -6,6 +6,8 @@
package org.jetbrains.kotlin.resolve.calls.tower
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.synthetic.SyntheticMemberDescriptor
@@ -227,7 +229,13 @@ class KotlinToResolvedCallTransformer(
return storedResolvedCall
}
}
return NewResolvedCallImpl(completedSimpleAtom, resultSubstitutor, diagnostics, typeApproximator)
return NewResolvedCallImpl(
completedSimpleAtom,
resultSubstitutor,
diagnostics,
typeApproximator,
expressionTypingServices.languageVersionSettings
)
}
fun runCallCheckers(resolvedCall: ResolvedCall<*>, callCheckerContext: CallCheckerContext) {
@@ -551,6 +559,7 @@ class TrackingBindingTrace(val trace: BindingTrace) : BindingTrace by trace {
sealed class NewAbstractResolvedCall<D : CallableDescriptor>() : ResolvedCall<D> {
abstract val argumentMappingByOriginal: Map<ValueParameterDescriptor, ResolvedCallArgument>
abstract val kotlinCall: KotlinCall
protected abstract val languageVersionSettings: LanguageVersionSettings
protected var argumentToParameterMap: Map<ValueArgument, ArgumentMatchImpl>? = null
protected var _valueArguments: Map<ValueParameterDescriptor, ResolvedValueArgument>? = null
@@ -620,6 +629,8 @@ sealed class NewAbstractResolvedCall<D : CallableDescriptor>() : ResolvedCall<D>
private fun createValueArguments(): Map<ValueParameterDescriptor, ResolvedValueArgument> =
LinkedHashMap<ValueParameterDescriptor, ResolvedValueArgument>().also { result ->
val needToUseCorrectExecutionOrderForVarargArguments =
languageVersionSettings.supportsFeature(LanguageFeature.UseCorrectExecutionOrderForVarargArguments)
var varargMappings: MutableList<Pair<ValueParameterDescriptor, VarargValueArgument>>? = null
for ((originalParameter, resolvedCallArgument) in argumentMappingByOriginal) {
val resultingParameter = resultingDescriptor.valueParameters[originalParameter.index]
@@ -630,12 +641,17 @@ sealed class NewAbstractResolvedCall<D : CallableDescriptor>() : ResolvedCall<D>
is ResolvedCallArgument.SimpleArgument -> {
val valueArgument = resolvedCallArgument.callArgument.psiCallArgument.valueArgument
if (resultingParameter.isVararg) {
val vararg = VarargValueArgument().apply { addArgument(valueArgument) }
if (varargMappings == null) varargMappings = SmartList()
varargMappings.add(resultingParameter to vararg)
continue
} else
if (needToUseCorrectExecutionOrderForVarargArguments) {
VarargValueArgument().apply { addArgument(valueArgument) }
} else {
val vararg = VarargValueArgument().apply { addArgument(valueArgument) }
if (varargMappings == null) varargMappings = SmartList()
varargMappings.add(resultingParameter to vararg)
continue
}
} else {
ExpressionValueArgument(valueArgument)
}
}
is ResolvedCallArgument.VarargArgument ->
VarargValueArgument().apply {
@@ -644,9 +660,11 @@ sealed class NewAbstractResolvedCall<D : CallableDescriptor>() : ResolvedCall<D>
}
}
if (varargMappings != null) {
for ((parameter, argument) in varargMappings) {
result[parameter] = argument
if (varargMappings != null && !needToUseCorrectExecutionOrderForVarargArguments) {
if (varargMappings != null) {
for ((parameter, argument) in varargMappings) {
result[parameter] = argument
}
}
}
}
@@ -658,6 +676,7 @@ class NewResolvedCallImpl<D : CallableDescriptor>(
substitutor: NewTypeSubstitutor?,
private var diagnostics: Collection<KotlinCallDiagnostic>,
private val typeApproximator: TypeApproximator,
override val languageVersionSettings: LanguageVersionSettings,
) : NewAbstractResolvedCall<D>() {
var isCompleted = false
private set

View File

@@ -40,6 +40,7 @@ import org.jetbrains.kotlin.resolve.calls.util.CallMaker
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.descriptorUtil.isUnderscoreNamed
import org.jetbrains.kotlin.resolve.scopes.*
import org.jetbrains.kotlin.resolve.scopes.receivers.*
import org.jetbrains.kotlin.types.*
@@ -837,7 +838,11 @@ class PSICallResolver(
val catchScope = with(scope) {
LexicalWritableScope(this, ownerDescriptor, false, redeclarationChecker, LexicalScopeKind.CATCH)
}
catchScope.addVariableDescriptor(variableDescriptor)
val isReferencingToUnderscoreNamedParameterForbidden =
languageVersionSettings.getFeatureSupport(LanguageFeature.ForbidReferencingToUnderscoreNamedParameterOfCatchBlock) == LanguageFeature.State.ENABLED
if (!variableDescriptor.isUnderscoreNamed || !isReferencingToUnderscoreNamedParameterForbidden) {
catchScope.addVariableDescriptor(variableDescriptor)
}
return replaceScope(catchScope)
}
}

View File

@@ -47,6 +47,7 @@ import org.jetbrains.kotlin.types.expressions.ExpressionTypingServices
import org.jetbrains.kotlin.types.expressions.typeInfoFactory.createTypeInfo
import org.jetbrains.kotlin.types.typeUtil.asTypeProjection
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.types.typeUtil.shouldBeSubstituted
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class ResolvedAtomCompleter(
@@ -212,15 +213,14 @@ class ResolvedAtomCompleter(
resultSubstitutor.safeSubstitute(lambda.returnType)
}
val approximatedValueParameterTypes = lambda.parameters.map {
// Do substitution and approximation only for stub types, which can appear from builder inference (as postponed variables)
if (it is StubType) {
val approximatedValueParameterTypes = lambda.parameters.map { parameterType ->
if (parameterType.shouldBeSubstituted()) {
typeApproximator.approximateDeclarationType(
resultSubstitutor.safeSubstitute(it),
resultSubstitutor.safeSubstitute(parameterType),
local = true,
languageVersionSettings = topLevelCallContext.languageVersionSettings
)
} else it
} else parameterType
}
val approximatedReturnType =
@@ -277,8 +277,7 @@ class ResolvedAtomCompleter(
functionDescriptor.setReturnType(returnType)
for ((i, valueParameter) in functionDescriptor.valueParameters.withIndex()) {
if (valueParameter !is ValueParameterDescriptorImpl || valueParameter.type !is StubType)
continue
if (valueParameter !is ValueParameterDescriptorImpl || !valueParameter.type.shouldBeSubstituted()) continue
valueParameter.setOutType(valueParameters[i])
}

View File

@@ -7,6 +7,7 @@ package org.jetbrains.kotlin.resolve.checkers
import org.jetbrains.kotlin.config.AnalysisFlags
import org.jetbrains.kotlin.config.ExplicitApiMode
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.reportDiagnosticOnce
@@ -14,6 +15,7 @@ import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.visibilityModifier
import org.jetbrains.kotlin.resolve.descriptorUtil.isEffectivelyPublicApi
import org.jetbrains.kotlin.resolve.descriptorUtil.isPublishedApi
class ExplicitApiDeclarationChecker : DeclarationChecker {
override fun check(declaration: KtDeclaration, descriptor: DeclarationDescriptor, context: DeclarationCheckerContext) {
@@ -22,7 +24,7 @@ class ExplicitApiDeclarationChecker : DeclarationChecker {
if (descriptor !is DeclarationDescriptorWithVisibility) return
if (descriptor is ClassDescriptor && descriptor.kind == ClassKind.ENUM_ENTRY) return // Enum entries does not have visibilities
if (!descriptor.isEffectivelyPublicApi) return
if (!descriptor.isEffectivelyPublicApi && !descriptor.isPublishedApi()) return
checkVisibilityModifier(state, declaration, descriptor, context)
checkExplicitReturnType(state, declaration, descriptor, context)
@@ -105,7 +107,9 @@ class ExplicitApiDeclarationChecker : DeclarationChecker {
val callableMemberDescriptor = descriptor as? CallableMemberDescriptor
val visibility = callableMemberDescriptor?.effectiveVisibility()?.toVisibility()
return (checkForPublicApi && visibility?.isPublicAPI == true) || (checkForInternal && visibility == Visibilities.Internal) ||
val isPublicApi =
visibility?.isPublicAPI == true || (visibility == Visibilities.Internal && callableMemberDescriptor.isPublishedApi())
return (checkForPublicApi && isPublicApi) || (checkForInternal && visibility == Visibilities.Internal) ||
(checkForPrivate && visibility == Visibilities.Internal)
}
@@ -119,5 +123,20 @@ class ExplicitApiDeclarationChecker : DeclarationChecker {
return true
}
fun publicReturnTypeShouldBePresentInApiMode(
element: KtCallableDeclaration,
languageVersionSettings: LanguageVersionSettings,
descriptor: DeclarationDescriptor?
): Boolean {
val isInApiMode = languageVersionSettings.getFlag(AnalysisFlags.explicitApiMode) != ExplicitApiMode.DISABLED
return isInApiMode && returnTypeRequired(
element,
descriptor,
checkForPublicApi = true,
checkForInternal = false,
checkForPrivate = false
)
}
}
}

View File

@@ -0,0 +1,36 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* 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.checkers
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.psiUtil.isPrivate
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny
object PrivateInlineFunctionsReturningAnonymousObjectsChecker : DeclarationChecker {
override fun check(declaration: KtDeclaration, descriptor: DeclarationDescriptor, context: DeclarationCheckerContext) {
if (context.languageVersionSettings.supportsFeature(LanguageFeature.ForbidAnonymousReturnTypesInPrivateInlineFunctions))
return
if (descriptor !is SimpleFunctionDescriptor || !descriptor.isInline || !declaration.isPrivate() || declaration !is KtNamedFunction)
return
val returnTypeConstructor = descriptor.returnType?.constructor ?: return
if (returnTypeConstructor.supertypes.singleOrNull { it.isAnyOrNullableAny() } == null) return
val nameIdentifier = declaration.nameIdentifier ?: return
val returnTypeDeclarationDescriptor = returnTypeConstructor.declarationDescriptor ?: return
if (DescriptorUtils.isAnonymousObject(returnTypeDeclarationDescriptor)) {
context.trace.report(Errors.PRIVATE_INLINE_FUNCTIONS_RETURNING_ANONYMOUS_OBJECTS.on(nameIdentifier))
}
}
}

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