Compare commits

...

225 Commits

Author SHA1 Message Date
Igor Yakovlev
fbb39dad15 Removed asserts for mirror files for java stubs on kt files
The behavior of this part of code is following:
1) We wrap the kotlin light class to the object that wraps the kt files into compiled (!) cls stub (notice, that most of the time it is a single file wrapper)
2) Platform wishes to get the mirror psi of this "compiled" stub work with text of it.
3) Platform request mirror element that asserted to be ok ONLY for multifiles stub.
4) It leads to EA-209577

There is no idea why so, but the exception is high-rated, so this assertion was deleted.

Fixed EA-209577
2019-08-28 14:05:40 +03:00
Ilya Gorbunov
418a56c00d Make ExperimentalTime annotation documented
(cherry picked from commit 7ff01b02a9)
2019-08-23 19:25:42 +03:00
Ilya Gorbunov
3935c0b0bd Minor: fix incorrect reference in kdoc
(cherry picked from commit 2c79b1f89e)
2019-08-23 19:25:42 +03:00
Sergey Igushkin
9beb183b30 ~ Workaround: download prebuilt Gradle plugin JARs from MavenCentral 2019-08-23 19:24:36 +03:00
Sergey Igushkin
6d6618aba7 ~ Workaround: download prebuilt Gradle plugin JARs from MavenCentral 2019-08-22 18:37:32 +03:00
nikita.movshin
9a031954c7 Add changelog for 1.3.50 2019-08-22 17:51:48 +03:00
Sergey Igushkin
1eaa698956 Workaround: download prebuilt Gradle plugin JARs from MavenCentral 2019-08-22 17:09:35 +03:00
Mikhael Bogdanov
d63712ad95 Don't trigger 'testJvm6ServerRuntime' initialization during configuration phase 2019-08-21 20:09:53 +03:00
Vyacheslav Gerasimov
42f49751e1 Build: Use cache redirector for buildscript block of :kotlin-reflect 2019-08-21 19:40:23 +03:00
nikita.movshin
2514d6f412 Update Kotlin Native version for release 2019-08-21 19:14:23 +03:00
Ilya Gorbunov
5f26f044bc KT-16602: Improve mutable sorting samples, fix sample references
(cherry picked from commit 4fc942c5e9)
2019-08-21 14:26:16 +03:00
Dat Trieu
9a7b61d31e KT-16602: Provide samples for sorting API usage
(cherry picked from commit 38d26b1d92)
2019-08-21 14:26:15 +03:00
Ilya Chernikov
60c84e36b6 Fix runtime dependencies for published scripting artifacts locally 2019-08-20 18:56:05 +02:00
nikita.movshin
6bd229ce33 Update Kotlin Native version 2019-08-19 00:05:26 +03:00
Vyacheslav Gerasimov
c7e92ed550 Build: Workaround dependency cycle in kotlinCompilerPluginClasspath
When bootstrap version is less than from current version dependencies
of `kotlin-scripting-compiler-embeddable` are resolved into projects
which leads to circular dependencies

 #KT-33287

(cherry picked from commit 0089de7f7f)
2019-08-16 19:00:26 +03:00
Ilya Gorbunov
2f9447d9ca Introduce erroneous operators ClockMark.minus/compareTo(ClockMark)
To provide a better diagnostic message on their misuse.

(cherry picked from commit fba22606e6)
2019-08-16 15:52:07 +03:00
Ilya Gorbunov
e02eaebd65 Change status of ExperimentalTime API to a more risky one
(cherry picked from commit ac07cb686b)
2019-08-16 15:52:06 +03:00
Ilya Gorbunov
7522538167 Introduce ClockMark.hasPassedNow, hasNotPassedNow functions
Makes it more clear to use them than comparing elapsed with Duration.ZERO.

(cherry picked from commit a985402507)
2019-08-16 15:52:05 +03:00
Ilya Gorbunov
11e58facda Rename: Clock.markNow, ClockMark.elapsedNow
Add "Now" suffix to the names of functions that depend on the current
time moment.

(cherry picked from commit 44195d436e)
2019-08-16 15:52:04 +03:00
Ilya Gorbunov
e857d944e4 Make effectively private properties actually private to avoid accessors
(cherry picked from commit a493d46a6e)
2019-08-16 15:52:03 +03:00
Ilya Gorbunov
b5ddf9007d Introduce TestClock.plusAssign(Duration) and hide implementation details
TestClock.plusAssign(Duration) is for advancing TestClock time.
Hide reading value, do not allow to provide initial reading,
fix clock unit to nanoseconds at construction time.

(cherry picked from commit f889d25287)
2019-08-16 15:52:02 +03:00
Ilya Gorbunov
e0f64c4c1a Introduce Duration.isPositive method
(cherry picked from commit 4de9361c37)
2019-08-16 15:52:01 +03:00
Ilya Kirillov
046aa868de Add an ability to switch between old and new J2K via settings window
Before that it was possible to do only via registry
2019-08-16 10:26:23 +03:00
Sergey Igushkin
00241930cb Fix: No value has been specified for 'binaryResultsDirectory' (KT-33246)
With Gradle 5.5+, set the property `binaryResultsDirectory` that
replaces `binResultsDir`.

Issue #KT-33246 Fixed

(cherry picked from commit 5578434629)
2019-08-16 10:12:53 +03:00
Shagen Ogandzhanian
3347b1da64 Update dukat dependency to 0.0.16 2019-08-16 06:36:48 +03:00
Nikolay Krasko
4909348a0c Use kotlin specific OOCB tracker for light classes inner cache
ClassInnerStuffCache from the platform caches everything with platform
OUT_OF_CODE_BLOCK tracker.

(cherry picked from commit ce3ad8f4da)
2019-08-15 19:50:20 +03:00
Ilya Kirillov
bfafb9a4a2 Use old J2K by default 2019-08-15 17:47:29 +03:00
Yan Zhulanow
57e6faf5e4 Fix compatibility issue with the 'kotlinttest' plugin
(cherry picked from commit d86bede293)
2019-08-15 22:19:45 +09:00
Igor Yakovlev
c624f51eb0 Add JvmOverloads to KtLightClassImpl
Added @JvmOverloads annotation to primary constructor for binary compatibility issues
2019-08-15 15:51:29 +03:00
Mikhail Zarechenskiy
62f5a26a4a Disable new inference for IDE analysis by default in releases 2019-08-15 13:48:22 +03:00
Mikhail Zarechenskiy
5f4d6354e0 Refactoring: move versioning.kt file to idea-analysis module 2019-08-15 13:48:22 +03:00
Mikhail Zarechenskiy
f30f105d9e Refactoring: move isSnapshot function closer to similar ones 2019-08-15 13:48:21 +03:00
Sergey Rostov
678ef96f95 Gradle, npm: use state file as fake output for :kotlinNpmInstall task
This is required in case when NpmSimpleLinker works (instead of yarn).
NpmSimpleLinker will not produce yarn.lock file, so :kotlinNpmInstall
was always up-to-date. Adding fake state file fixes the problem.

#KT-32874 Fixed

(cherry picked from commit ba9c632f15)
2019-08-15 11:56:00 +03:00
Dmitry Savvinov
fec917f75b Annotate default interface method with JvmDefault
To keep compatibility with external plugin(s) which inherit their
Java-classes from KotlinProjectConfigurator and make
CompatibilityChecker happy
2019-08-15 11:37:10 +03:00
Alexander Udalov
5ebe84cc28 Recognize Intrinsics.checkNotNullParameter call on lambdas in inline functions
We're going to start using this method since 1.4 for parameter null
checks, and without this change the compiler would fail if it
encountered a call to such method on a lambda parameter inside an inline
function, since that call is not inlinable.

 #KT-22275

(cherry picked from commit d0385e4e7c)
2019-08-14 19:16:53 +02:00
Vyacheslav Gerasimov
d2e3856068 Upgrade plugin-repository-rest-client & use token auth
#KT-33338
2019-08-14 18:38:47 +03:00
Ilya Chernikov
42b5475d5c Fix script config saving to file attributes
also make reading from file attribute more robust
2019-08-14 11:42:27 +02:00
nikita.movshin
9704646e04 Add changelog for 1.3.50 EAP 3 2019-08-14 11:59:06 +03:00
SvyatoslavScherbina
d727fdbd82 Update Kotlin Native version for EAP 3 (#2524) 2019-08-12 13:53:22 +03:00
Dmitry Savvinov
d2819701f0 Move default implementation of TargetPlatform.platformName to leaf classes
Otherwise, we have a static initialization loop, leading to null-leaks

Removing default interface method indeed disconnects the loop, as per JVM
Specification, "5.5 Initialization".

See KT-33245 for detailed explanations

^KT-33245 Fixed
2019-08-12 13:10:06 +03:00
Ilya Kirillov
ff5d08d0d4 New J2K: Don't fail on captured types & don't use functional interface with captured types
Note: we have to print captured types for lambda parameters.
It is needed for nullability inference as it requires explicit types specification to work.
Later in post-processing we remove explicit type specifications for lambda parameters which have captured types

#KT-33186 fixed

(cherry picked from commit 09ab98a4f8)
2019-08-09 16:56:36 +03:00
Yan Zhulanow
4e61cc2a13 Move out compiler plugins from the main IDE plugin JAR (KT-31279) 2019-08-09 20:10:38 +09:00
Ilya Gorbunov
3fa54611bd Fix incorrect Double.toLong conversion for infinite values in JS
#KT-33225 Fixed

(cherry picked from commit ebb59d51d2)
2019-08-09 12:54:30 +03:00
Mikhail Zarechenskiy
d8372d6fc6 Advance bootstrap version to 1.3.50-eap-71
Follow-up of KT-33157.
 This is needed to have proper signatures in stdlib afte the fix (80acc56)
2019-08-09 12:48:07 +03:00
Vladimir Dolzhenko
643f7449b9 Specify parent disposable in JavaOutsideModuleDetector Vfs listener
(cherry picked from commit 3f9480e1c5)
2019-08-09 11:40:35 +02:00
Ilya Matveev
95926e57e6 Gradle: Don't use the deprecated "layout" method for Ivy repos
Issue #KT-30258 fixed
2019-08-08 15:44:01 +07:00
Ilya Gorbunov
60299d328c Unify withIndex docs wording
(cherry picked from commit 65b0a5f903)
2019-08-07 22:24:45 +03:00
Ilya Gorbunov
82315c3c0b Enable test that uses Array.fill in JS and Native
(cherry picked from commit 2e445ebad6)
2019-08-07 22:24:44 +03:00
Ilya Gorbunov
3338231017 Common Array.fill for unsigned arrays, improve docs, native impl name
KT-32359

(cherry picked from commit 3751a8a797)
2019-08-07 22:24:42 +03:00
Jake Wharton
b1aecd6e7a Provide Array.fill in common stdlib
KT-32359

(cherry picked from commit 1a6069382e)
2019-08-07 22:24:42 +03:00
Mikhail Zarechenskiy
82b2bdd2b0 [NI] Introduce feature for passing function references with defaults
Relates to KT-8834, we continue reducing differences between old and new
 inference. Note that as for `SamConversionPerArgument`, this feature
 is enabled in the compiler and not in the IDE to avoid breaking code
 for those users that already enabled new inference in the compiler
2019-08-07 18:04:47 +03:00
Mikhail Zarechenskiy
d56291242b [NI] Fix poor performance of recursive types approximation
#KT-32407 Fixed
2019-08-07 18:04:46 +03:00
Mikhail Zarechenskiy
98da824cbb [NI] Use approximator as a component, don't recreate it during resolve 2019-08-07 18:04:46 +03:00
Sergey Rostov
36141fc5ba Gradle, js, karma: require webpack npm dependencies
(cherry picked from commit 3e25166832)
2019-08-07 16:11:18 +03:00
Sergey Rostov
0f12a797c4 Gradle, js, npm: proper disambiguation classifier for npm and tools configurations
#KT-32293 Fixed

(cherry picked from commit 99762193f9)
2019-08-07 16:11:17 +03:00
Sergey Rostov
fb49f8c068 Gradle, js, npm: fix targets and compilation listener
#KT-32293 Fixed

(cherry picked from commit 1dc860f206)
2019-08-07 16:11:16 +03:00
Sergey Rostov
a6cd4a99cc Gradle, js, external declarations: read flags from properties
(cherry picked from commit 87e80317a0)
2019-08-07 16:11:15 +03:00
Ty Smith
4a74b1dbb1 Add embeddable artifact for jvm-abi-gen
#KT-28824 Fixed
2019-08-07 13:29:38 +03:00
Ilya Chernikov
c08f4ec20a Implement proper expression generation for the last script line
fixes problem with result fields
#KT-33127 fixed
2019-08-07 11:22:24 +02:00
Mikhail Zarechenskiy
c1a29ca7c9 Don't lost type parameters for members of inline classes in the bytecode
#KT-33157 Fixed
2019-08-07 02:44:44 +03:00
Ilya Kirillov
608bc45a66 Do not use dummy resolving for light data classes which extend other classes
When using dummy resolving for creating stubs of data classes we do not have overloading information
which is needed to determine whether we need to generate synthetic members or not.
As a result of that, we may have two different versions of member scope: the first one is
resolved by dummy resolving and the second one resolved via an ordinary one.

As light methods depend on the index of them in the class body,
we can have two different methods with the same index
which breaks mapping from dummy resolved methods to normal ones.

This behaviour can be reproduced when having data class which
extends other class with some synthetic members overridden and marked as final
like described in #KT-32969

#KT-32969 fixed
2019-08-06 21:24:43 +03:00
Vyacheslav Gerasimov
82513af976 Build: Make dependencies on builtins compileOnly
for kotlin-annotations-android & kotlin-annotations-jvm, to prevent
builtins from occurring in maven pom compile scope.

 #KT-33140
2019-08-06 20:04:19 +03:00
Roman Golyshev
6a9485eeb3 KT-32791: Avoid EDT when acquiring editor for setting line mark in scratches
^KT-32791 Fixed

(cherry picked from commit 9d7de8e9ec)
2019-08-05 17:28:11 +03:00
Louis CAD
eda386710b Improve error message (#2505)
Fore the case where a target has been created or configured twice with different presets,
avoid showing "null" inside the error message if existing target has not preset,
and append a point.
2019-08-04 22:34:28 +03:00
Anton Yalyshev
b5401261f5 Cleanup: remove redundant semicolon
(cherry picked from commit 4a20a440a7)
2019-08-02 14:52:21 +03:00
Anton Yalyshev
5da441106c Add statistics (FUS) collector for IDE Settings. At the moment - New Inference only.
(cherry picked from commit 6d53151256)
2019-08-02 14:52:06 +03:00
Dmitriy Novozhilov
e3c1e01697 [NI] Fix extracting type variables for flexible types in in captured types
Bug was introduced in b99efb because of lack of tests.
All code in `AbstractTypeCheckerContextForConstraintSystem.extractTypeVariableForSubtype`
  related to IN projection looks suspicious and needs further investigation
2019-08-01 15:39:18 +03:00
Andrey Uskov
28280285a6 Add transitive dependencies on common MPP modules
Transitive dependencies on modules available via
'dependsOn' dependencies are added to java modules
depending on MPP projects
#KT-33025 Fixed

(cherry picked from commit 02ee950836)
2019-07-31 13:52:23 +03:00
nikita.movshin
f0ffb2eb28 Add changelog for 1.3.50 EAP 2 2019-07-30 21:07:15 +03:00
Vyacheslav Gerasimov
f387c083aa Build: Fix artifact pattern for Android Studio bintray repo 2019-07-26 19:06:48 +03:00
Vyacheslav Gerasimov
c708efb290 as36: Fix groovy-all dependency version 2019-07-26 18:09:55 +03:00
Vyacheslav Gerasimov
d1199f2b68 as36: Add bunches for AS 3.6 C6 based on 192 platform 2019-07-26 17:46:37 +03:00
Vyacheslav Gerasimov
d74cf6f1aa Build: Add repo for prerelease Android Studio
(cherry picked from commit 5c6dedc623)
2019-07-26 17:46:37 +03:00
Ilya Chernikov
8ea35c629e Fix jvm-host-embeddable artefact generation 2019-07-26 16:25:18 +02:00
Ilya Chernikov
34556642dc Filter out local classes on JSR-223 properties mapping
fixes e.g. Spring framework usages of the JSR-223 engine
2019-07-26 16:24:54 +02:00
nikita.movshin
d62a565c6c Update Kotlin Native version for EAP 2 2019-07-26 16:46:32 +03:00
Yan Zhulanow
ced11394e3 Revert "Evaluator: Do not report parsing error on empty block/expression (KT-11938)"
KT-11938 reopened because of KT-32699.

This reverts commit 6686ed2e
2019-07-26 17:37:19 +09:00
Dmitry Gridin
147ba4f511 JavaOutsideModuleDetector: should refresh notification after move
#KT-32967 Fixed

(cherry picked from commit a10e57eaec)
2019-07-26 10:35:08 +03:00
Dmitry Gridin
1a468da0d0 CreateExpectFix: shouldn't suggest create expect property with lateinit or const modifier
#KT-32705 Fixed

(cherry picked from commit 4c8d0acb5d)
2019-07-26 10:35:07 +03:00
Andrey Uskov
0af1b565cc Safe get of registry key in KotlinAndroidGradleMPPModuleDataService 2019-07-26 09:37:05 +03:00
Victor Petukhov
8cd31284a1 Introduce -Xpolymorphic-signature compiler flag as more priority than -XXLanguage:+PolymorphicSignature 2019-07-26 09:05:13 +03:00
Victor Petukhov
806f0114d7 Introduce -Xinline-classes compiler flag as more priority than -XXLanguage:+InlineClasses 2019-07-26 09:04:55 +03:00
Ilya Chernikov
10e6d98723 Fix script classpath utility functions that use classpath filtering by "keys"
The problem was that only the first matching classpath entry were used.
The problem was reported by @lion7 on github (67ad3773de (commitcomment-34443927))
2019-07-26 07:29:02 +02:00
Ilya Chernikov
beadb09fd2 Properly handle REPL snippets with exceptions ...
so the REPL remain operational after exception in one of the snippets:
- separately return script class and script instance on evaluation (
  because in case of an exception the class is valid, while the instance
  is not).
- store both the class and the instance in the history
- handle this data accordingly
2019-07-26 07:29:02 +02:00
Ilya Chernikov
df99e9e3d1 Add a handler for providing evaluation context for scripts
use it on refinement.
also some refactoring on context class and around
2019-07-26 07:29:02 +02:00
Ilya Chernikov
0d601d7eb0 Move caching to after all configuration refinements and ...
move compilation cache setting to the scripting host configuration
The cache implementation can now take into account all external
dependencies that may appear during refinement.
Also change initial refinement location accordingly and rearrange
caching interfaces to make it available in scripting plugin.
2019-07-26 07:29:02 +02:00
Ilya Chernikov
e19fedc962 Introducing transient properties in scripting API 2019-07-26 07:29:01 +02:00
Ilya Chernikov
290ac4f375 Refactor main-kts build scripts - fix red code in IDEA 2019-07-26 07:29:01 +02:00
Ilya Chernikov
62c4dd73e7 Implement base zip cache with tests...
plus some relevant fixes and refactorings
2019-07-26 07:29:01 +02:00
Ilya Chernikov
7a07de629b Move caching tests into a dedicated class
plus some tests refactorings
2019-07-26 07:29:01 +02:00
Ilya Chernikov
101f7a40b5 Add net.jpountz and one.util.streamex to the list of shadowed packages
should fix problem with using REPL infrastructure with Apache Zeppelin
2019-07-26 07:29:01 +02:00
Ilya Chernikov
6573fc6bc7 Fix and test evaluation of scripts with default configurations 2019-07-26 07:29:00 +02:00
Ilya Chernikov
ada5a891cb [minor] Refactor properties collection builder:
add a helper to replace the value only if it is absent or default
rearrange some functions
2019-07-26 07:29:00 +02:00
Ilya Chernikov
863679c9bb Implement composable refinement handlers...
for compilation and evaluation configurations.
Add utilities to apply refinements uniformly.
Also fix one invoke for list values - it was not consistent with
other builders
2019-07-26 07:29:00 +02:00
Ilya Chernikov
7bb445f4c1 [minor] Add a small diagnostics handling utility fun 2019-07-26 07:29:00 +02:00
Ilya Chernikov
2df0821b1e Improve JSR-223 engine diagnostics
also abstract invoke wrapper creation
2019-07-26 07:29:00 +02:00
Ilya Chernikov
8ea4443495 Add test on repl with implicit receiver 2019-07-26 07:29:00 +02:00
Ilya Chernikov
cfd1c1b7ed Implement JSR223 host in the main-kts jar
also improve diagnostics on configuration instantiation
2019-07-26 07:29:00 +02:00
Ilya Chernikov
53ad650265 Extract arguments calculation for base JSR223 engine into an argument 2019-07-26 07:28:59 +02:00
Ilya Chernikov
b26e9e9745 Move direct properties configuration code into public functions in scripting host jar 2019-07-26 07:28:59 +02:00
Ilya Chernikov
7b81415bba Fix testLazyScriptDefinitionProvider:
The KtUsefulTestCase functionality is not used here but seems causes
the side effects resulting in failing test, probably exactly because
the infrastructure loaded by the KtUsefulTestCase is never called
2019-07-26 07:28:59 +02:00
Ilya Chernikov
2330743e1b Fix flaky failures in main-kts IT 2019-07-26 07:28:59 +02:00
Ilya Chernikov
7b6ae0179b Shorten temp paths used in tests
#KT-32490 fixed
2019-07-26 07:28:59 +02:00
Ilya Chernikov
a5f119dbef Fix gradle IT with scripting discovery
The test is not designed to fail if the definitions are not discovered -
the script files have completely custom extensions and therefore ignored.
So checking for the warning in the build log is enough.
#KT-32697 fixed
2019-07-26 07:28:59 +02:00
Ilya Chernikov
e8a90fb622 Fix entries closing on saving compiled script to jar:
also adding a short sleep in tests, otherwise in some cases the
classloader was not able to find class in the jar.
Fixes script to jar saving tests on windows
2019-07-26 07:28:58 +02:00
Ilya Chernikov
a5a93f2bbe Ignoring resolver tests that failing on TC:
should be rewritten to the new scripting API
Some additional diagnostics improvements are remained for possible
future usage.
2019-07-26 07:28:58 +02:00
Ilya Chernikov
a84e93c31f Fix script definition matching for REPL console
fixes IdeReplCompletionTestGenerated tests
in addition, fix default ScriptDefinition generation
2019-07-26 07:28:58 +02:00
Ilya Chernikov
a32a37e229 Convert paths to unix format before matching with filePathPattern
should also fix testPathPattern5_kts test
2019-07-26 07:28:58 +02:00
Ilya Chernikov
57f827e2bb Do not override path calculation in light virtual files in tests:
seems unnecessary anymore and breaks some script testing logic
2019-07-26 07:28:58 +02:00
Ilya Chernikov
e89208e06e Fix nullability in the instrumenter, avoid exceptions on tests setup 2019-07-26 07:28:57 +02:00
Ilya Chernikov
2648f17faa Change default for script displayName parameter to empty, generate name from base class in definition 2019-07-26 07:28:57 +02:00
Ilya Chernikov
dba7160193 Implement filePathPattern in the script configuration with handling
also
- tests
- extending kdoc for the definitions
2019-07-26 07:28:57 +02:00
Mikhail Mazurkevich
0c22204cfb JPS: Add temporary non caching jps storage for 192
This storage available under separate flag. Temporary non caching storage
should be removed after Intellij SDK version update.
2019-07-26 05:06:32 +03:00
Andrey Uskov
54d0798a4c Fix import when android gradle plugin is involved in IDEA 183
All dependencies on MPP modules are added in KotlinAndroidGradleMPPModuleDataService
including transitive ones. Fixes KT-30510 in IDEA 183 and below

(cherry picked from commit 584d441587)
2019-07-26 01:28:56 +03:00
Andrey Uskov
030d08ffa7 Fix import library dependencies when transitive MPP are involved
Fix import dependencies of java modules on MPP modules when
project was not build before import. Unresolved jar dependencies
are not created any more on import of MPP project.
#KT-28822 Fixed
#KT-29757 Fixed

(cherry picked from commit 91365d9fad)
2019-07-26 01:28:36 +03:00
Andrey Uskov
24d014d180 Fixed setting production-on-test flag if project was not build
Make importing production-on-test flag more accurate when
the project to be imported was not previously build

(cherry picked from commit 0b8ad5c6c0)
2019-07-26 01:28:14 +03:00
Andrey Uskov
a69af2472b Add transitive test dependencies on MPP with jvmWithJava on import
Fixed case when production and test source sets depend on MPP module
with jvmWithJava involved and have dependency on the same jar artifact.

(cherry picked from commit 17dec7b389)
2019-07-26 01:27:50 +03:00
Andrey Uskov
dfd6974cd5 Add jvmWithJava IDE import test
(cherry picked from commit 86a26f0cca)
2019-07-26 01:27:31 +03:00
Andrey Uskov
941907dbcf Fix importing transitive dependencies on MPP project
Fix importing dependencies of java projects on MPP projects
when external dependency is resolved into file collection dependency

(cherry picked from commit 6c0469cee0)
2019-07-26 01:27:10 +03:00
Andrey Uskov
6df5136a2a Fix combobox size in facet settings tab (KT-32784)
Size of the select platform combobox fixed in order to fit all elements
#KT-32784 Fixed

(cherry picked from commit 8592396a9a)
2019-07-26 01:26:48 +03:00
Andrey Uskov
b8a1b9d7af Fix order of platforms in Facets (KT-32783)
#KT-32783 Fixed

(cherry picked from commit 9ce9b5945e)
2019-07-26 01:26:29 +03:00
Andrey Uskov
59b35458cf Disable KaptImportingTest in IDEA 183 and below
(cherry picked from commit ad1b795a69)
2019-07-26 01:26:11 +03:00
Andrey Uskov
72390032ab Fix matching file paths under Windows in NewMultiplatformKaptProjectImportingTest
(cherry picked from commit 6e10126c6f)
2019-07-26 01:25:34 +03:00
ilgonmic
92ab6b573d Fix webpack dsl with closure
(cherry picked from commit 795e0eef200bb24b9cba06002b48737c01de02be)
2019-07-25 23:24:17 +03:00
ilgonmic
a81ec9874c Remove duplicated source-map-loader configuring and cleanup kotlin webpack config writer
(cherry picked from commit 681eeaedfb359e85cf98e0e9a7239a0364a5d41c)
2019-07-25 23:24:17 +03:00
Yan Zhulanow
dbade2ffb2 Kapt: Attach generated Kotlin sources in 'compilation' mode (KT-32535)
(cherry picked from commit ccff347ffc)
2019-07-26 02:43:36 +09:00
Ivan Gavrilovic
9141fe93a5 KT-32210: Handle long compiler plugin options
Some of the KAPT compiler plugin options were longer than 0xFFFF bytes in
UTF-8 encoding, causing UTFDataFormatException when serializing them. This
commit avoids that issue by encoding changed files and changed classpath types
one by one instead of joining them to a single string.

(cherry picked from commit 1c63d3aa2f)
2019-07-26 02:43:36 +09:00
Alexey Tsvetkov
f12ad0f6ce Sort source to output mapping before writing to caches
#KT-32902 Fixed
2019-07-25 20:31:54 +03:00
Alexey Tsvetkov
1a72f0d19d Rewrite test of relocatable JPS IC caches
* Caches are compared as files now. It is a more robust approach
than comparing strings with dumped contents. E.g previous test
ignored differences in keys ordering, because dumping caches to string
was added for comparing caches after incremental and non-incremental builds,
which cannot be compared without sorting keys (see KT-32674).
* Calling setUp/tearDown twice within the same test instance was
relatively hacky and fragile. Also it complicated adding new test cases.
2019-07-25 20:31:50 +03:00
Alexey Tsvetkov
a2a5507ae2 Extract EnableICFixture 2019-07-25 20:31:46 +03:00
Alexey Tsvetkov
cf32ccb713 Make lookup storage addAll order independent
Lookup storage output files could differ for projects
with different absolute paths.
This happened because, paths for lookups were
relativized only before writing to the underlying storage.
Storing absolute paths in a hash table could
result in different order of adding files to the lookup storage.
This commit fixes the issue by sorting lookups and files in
LookupStorage#addAll

    #KT-32674 Fixed
2019-07-25 20:31:43 +03:00
Alexey Tsvetkov
da73a0d7ed Improve exception message for directories comparison in tests
It was unclear what dirs were compared (e.g when rebuilding and
comparing caches dirs, it's not obvious which dir is "expected" and
which is "actual"). To improve this, compare resulting strings
with the placeholder for a root dir first. If the comparison fails,
then replace the placeholder with an actual directory and call
assertEquals.
2019-07-25 20:31:39 +03:00
Alexander Podkhalyuzin
da5efe0df0 Revert strong references for compiler only
#KT-32521 Fixed
2019-07-25 16:17:20 +03:00
Alexey Tsvetkov
a923a39bed Inherit max metaspace size of client VM for Kotlin compile daemon
#KT-32521 In Progress
    #KT-32950 Fixed
2019-07-25 16:17:15 +03:00
Alexey Tsvetkov
fc98d4369f Substitute kotlin-reflect with kotlin-reflect-api in compile classpath
Currently Kotlin IC can only track changes in "default" jar files by
associating a history of ABI diffs with a source set's jar file.

kotlin-reflect is a non-default fat jar, which causes
non-inremental builds when it gets changed and included in
a compile classpath. To avoid this problem, kotlin-reflect-api
project was added. It is assumed that only kotlin-reflect-api
should be used for compilation.

However, Gradle is known to leak transitive runtime dependencies
to a compile classpath, i.e. when `:b` has a runtime dependency on `:a`,
and `:c` has a compile dependency on `:b`, `:c` also gets `:a`
in its compile classpath.

Before this change kotlin-reflect was leaked to compiler tests's
classpath through kotlin-scripting-compiler-impl.

To work around this issue, and to prevent similar issues from happening,
this change introduces a dependency substitution from kotlin-reflect
to kotlin-reflect-api in all compile classpath configurations.

        #KT-32954 Fixed
2019-07-25 16:17:11 +03:00
Alexey Tsvetkov
070ac124cc Find only non-default shadow jars in findShadowJarsInClasspath diagnostic
We are interested only in shadow jars that might break the incremental compilation
2019-07-25 16:17:00 +03:00
Alexey Tsvetkov
4cfa52638b Remove unnecessary dependencies on kotlin-compiler-runner 2019-07-25 16:16:56 +03:00
Alexey Tsvetkov
26f8f0d553 Set source and target compatibility in buildSrc
If source and target compatibility are not set explicity,
Gradle will assume they are equal to current JVM version.
This may cause unwanted rebuilds, when a build is run on
different JDK versions (it might happen when switching between
CLI and IDE).
2019-07-25 16:16:52 +03:00
Alexey Tsvetkov
deee9124aa Do not fork java compile tasks when current JDK can be used
I see the following improvements:
* `clean dist --parallel` is ~10% faster (from 3:40 to 3:20)
* incremental `dist --parallel` is ~50% faster
(adding public method to org.jetbrains.kotlin.utils.SmartList)

    #KT-32955 Fixed
2019-07-25 16:16:47 +03:00
Alexey Tsvetkov
9adc695e69 Check JDK env vars once during configuration when not syncing
Previous code (callback in `beforeTask`) was added to allow
opening project without setting up all env. variables.
This change simplifies the code and avoids a callback,
while keeping the ability to open the project without
setting up all variables by checking `kotlinBuildProperties.isInIdeaSync`
2019-07-25 16:16:44 +03:00
Alexey Tsvetkov
4389b38331 Set sourceCompatibility and targetCompatibility for JavaCompile tasks
Currently running build with JAVA_HOME pointing to
any JDK != 1.8 results in errors like

    #KT-30382 Fixed
2019-07-25 16:16:40 +03:00
Ilya Kirillov
df26f8b695 New J2K: use old J2K for evaluate expression instead of new one
#KT-32693 fixed

(cherry picked from commit 4e5e14046d)
2019-07-25 15:25:01 +03:00
Ilya Kirillov
ca09e73d12 New J2K: add conversion of binary literals & fix conversion of octal ones
#KT-32835 fixed

(cherry picked from commit e795e4b73d)
2019-07-25 15:24:42 +03:00
Ilya Kirillov
cdb45eaa2f New J2K: correctly convert number literals with underscores
#KT-32837 fixed

(cherry picked from commit 72a09ab59b)
2019-07-25 15:24:33 +03:00
Ilya Kirillov
ce2c6b917f New J2K: correctly print comments for qualified expression
(cherry picked from commit 4ead820395)
2019-07-25 15:24:23 +03:00
Ilya Kirillov
4d93390e44 New J2K: separate nullability inference from common one & nullability bug fixes
It will be needed for structure mutability inference

#KT-21467 fixed
#KT-32609 fixed
#KT-32572 fixed
#KT-24677 fixed

(cherry picked from commit 2bd5a1f196)
2019-07-25 15:24:13 +03:00
Ilya Kirillov
b42b9955dc New J2K: move all symbols definitions to symbols package
(cherry picked from commit d7960caf89)
2019-07-25 15:23:40 +03:00
Ilya Kirillov
c0022c3917 New J2K: add better support of implicit functional interfaces
#KT-32702 fixed
#KT-19327 fixed

(cherry picked from commit f79b282c60)
2019-07-25 15:23:29 +03:00
Ilya Kirillov
2649758074 New J2K: consider in-context declarations while performing conversion on copy-paste plain text conversion
#KT-32602 fixed

(cherry picked from commit 96ca4712a0)
2019-07-25 15:23:15 +03:00
Ilya Kirillov
2121afa531 New J2K: remove unused dependencies from nj2k modules
(cherry picked from commit c865d74965)
2019-07-25 15:23:05 +03:00
Ilya Kirillov
91fcdf62e8 New J2K: remove unused classes
(cherry picked from commit 1bbdd0bf15)
2019-07-25 15:22:56 +03:00
Ilya Kirillov
1dc136edce New J2K: remove JKVisitor with type parameters
(cherry picked from commit 6e04b1549c)
2019-07-25 15:22:47 +03:00
Ilya Kirillov
192e536837 New J2K: correctly create AST for Java call of Kotlin data class derived members
#KT-32604 fixed

(cherry picked from commit b7917978b8)
2019-07-25 15:22:15 +03:00
Ilya Kirillov
110cedac43 New J2K: do not resolve unary expressions method symbols
As we already have its type and may fail on unresolved declaration

#KT-32603 fixed

(cherry picked from commit d29d7fb257)
2019-07-25 15:21:58 +03:00
Ilya Kirillov
d04642d92a New J2K: use test data for nj2k conversion tests from nj2k tests data instead of old one
(cherry picked from commit 84872e064f)
2019-07-25 15:21:44 +03:00
Leonid Startsev
802196f93a Patch serializable class with addtional annotation
(which contains actual serializer) to make use of it with @AssociatedObjectKey
2019-07-25 14:03:50 +03:00
Leonid Startsev
2c73665c4a Fixes for 1.3.50-eap-1
- Do not insert typeParameters into IrConstructor;
- Set correct property symbol to IrField;

- Use upper bound as a class descriptor for type parameters.
This will allow to get upper bound's KClass in polymorphic serialization.
Fixes https://github.com/Kotlin/kotlinx.serialization/issues/490;

- Lazily add all serializer functions.
Fixes https://github.com/Kotlin/kotlinx.serialization/issues/502;

- Don't generate constructor invocation for abstract(sealed) classes deserializer.
Such code is incorrect anyway (you can't create an instance of abstract class) and causes problems in devirtualization when exporting Native libraries.
2019-07-25 12:57:06 +03:00
Leonid Startsev
86d9d87b16 Change order in SerializableProperties initialization logic
in that way so binding context would be checked only after resolve is triggered (via .getContributed descriptors).
Empty binding context led to some subtle bugs.
Fixes https://github.com/Kotlin/kotlinx.serialization/issues/508
2019-07-25 12:57:06 +03:00
Leonid Startsev
bfe9f7f5c6 Rewrite IDE check whether serialization plugin is enabled
In a such way so it wouldn't check for actual JAR file and wouldn't touch filesystem.
Fixes KT-32346
2019-07-25 12:57:06 +03:00
Nicolay Mitropolsky
c8f822fa49 KtLightParameter introduced as interface
(cherry picked from commit 5f9660cd33)
2019-07-25 12:06:14 +03:00
Nicolay Mitropolsky
2b0f63499c org.jetbrains.kotlin.asJava.elements.LightParameter converted to Kotlin
to avoid clashes in `getMethod` with `KtLightParameter`

(cherry picked from commit 50158e508a)
2019-07-25 12:06:14 +03:00
Nicolay Mitropolsky
91e1cb3cbf org.jetbrains.kotlin.asJava.elements.LightParameter converted to Kotlin: Rename .java to .kt
(cherry picked from commit 7dcd3849e0)
2019-07-25 12:06:14 +03:00
Nicolay Mitropolsky
1b0e46869a renaming KtLightParameter to KtLightParameterImpl
(cherry picked from commit 8982a49dcb)
2019-07-25 12:06:14 +03:00
Ivan Gavrilovic
da8668ad90 Report non-incremental annotation processors correctly
This commit fixes an issue when all APs would be reported as non-incremental,
even if only a single one is non-incremental. Now, additional declared type
is added that is used to denote processors that are incremental, but have
been forced to run non-incrementally in presence of non-incremental APs.

This means that only APs that do not support incremental annotation processing,
or APs that are dynamic and are non-incremental at runtime will be reported.

(cherry picked from commit be3fe9495c)
2019-07-25 04:59:26 +09:00
Ivan Gavrilovic
89dcc4bba6 KT-23880: Enable incremental APT mode with KAPT by default
The feature has been present since 1.3.30 behind a flag. This
commit enables it by default.

(cherry picked from commit ad352355de)
2019-07-25 04:59:22 +09:00
Ivan Gavrilovic
ac16bb21d0 Mark property as output instead of local state when needed
Kapt task incremental annotation processing cache directory
was using @LocalState annotation that was added in Gradle 4.3.
However, minimum supported version is 4.2, so this commit registers
this directory as output of a task for pre 4.3 versions. This is safe
as caching is enabled only for Gradle 4.3+.

Test: verified manually
(cherry picked from commit a108af76d6)
2019-07-25 04:59:20 +09:00
Ivan Gavrilovic
ef14310bc2 Handle classpath snapshot changes better
Because Kapt Gradle task uses PathSensitivity.NONE for the input representing
the classpath structure, there are cases when paths of the files may change,
but because content is the same, there will be no incremental changes.

Classpath snapshot comparison did not handle this case correctly, but this
commit fixes that. In more details:
- classpath entries with the same path and that are not reported as changed
will have their information loaded from the previous snapshot
- any other entry (changed path or changed content) will be reloaded

Test: ClasspathSnapshotTest
(cherry picked from commit 5a2ff86691)
2019-07-25 04:59:16 +09:00
Dmitriy Novozhilov
f291b6e775 [NI] Look for type variables in captured flexible types
#KT-32434 Fixed
2019-07-24 18:01:50 +03:00
Dmitriy Novozhilov
fcaef56459 [NI] Fix passing callable references to suspend functions as functional parameter
#KT-32452 Fixed
2019-07-24 17:59:48 +03:00
Igor Chevdar
7ff66cf310 Fixed bug in LateinitLowering 2019-07-24 16:34:12 +05:00
Igor Chevdar
274d3bd095 [IR] Added IrType.isKSuspendFunction() 2019-07-23 19:56:23 +05:00
Dmitry Petrov
b1263c57d9 psi2ir: Fix KT-30796 ErrorType for '?:' in OI 2019-07-23 19:34:51 +05:00
Dmitry Gridin
9f6559dc44 CreateExpectActualFix: fix package for files with root package from non-root directory
#KT-28746 Fixed

(cherry picked from commit 4e2989e884)
2019-07-23 16:26:39 +03:00
Dmitry Gridin
76dc84e51f KotlinCreateTestIntention: disallow intention for expect classes
#KT-26242 Fixed

(cherry picked from commit c76ca988eb)
2019-07-23 16:26:38 +03:00
Dmitry Gridin
76c6892965 UnimplementedKotlinInterfaceMemberAnnotator: shouldn't report methods with @JvmStatic
#KT-27208 Fixed

(cherry picked from commit 311cfc3806)
2019-07-23 16:26:37 +03:00
Dmitry Gridin
6ceb0e5ff6 UnimplementedKotlinInterfaceMemberAnnotator: cleanup code
(cherry picked from commit cf07585b11)
2019-07-23 16:26:36 +03:00
Toshiaki Kameyama
8b6970bad0 ReplaceGuardClause inspection: do not report when 'if' expression is used as expression
(cherry picked from commit 22c5e208a6)
2019-07-23 12:55:13 +03:00
Toshiaki Kameyama
868fabbe14 ReplaceGuardClause inspection: do not remove 'else' branch
#KT-32797 Fixed

(cherry picked from commit a6690e4e35)
2019-07-23 12:54:42 +03:00
Toshiaki Kameyama
c05b6bc007 ReplaceGuardClause inspection: fix highlight range
(cherry picked from commit a3a3c52c24)
2019-07-23 12:54:36 +03:00
Dmitry Gridin
5d7f3b78f3 multiplatformUtil: implementedModules shouldn't ignore android test module
Relates to #KT-30799

(cherry picked from commit 0993fb82fe)
2019-07-22 17:58:05 +03:00
Dmitry Gridin
8c51795ebb MPP: don't return Main modules from implementedModules for Test modules
#KT-28529 Fixed
#KT-30799 Fixed

(cherry picked from commit b1e371a2dd)
2019-07-22 17:58:04 +03:00
Andrey Uskov
b9eb91df45 Increase heap size for gradle importing tests due to memory
leak in the gradle daemon
#KT-32731 Fixed

(cherry picked from commit 8294e5afc2)
2019-07-22 16:13:30 +03:00
Andrey Uskov
4c77d8b923 Calculation of supported platforms in AndroidSourceSetDataService fixed
for IDEA versions 183 and below.
A deep copy of MPP model for Android source sets is created

(cherry picked from commit db743aa6e8)
2019-07-22 16:12:31 +03:00
Andrey Uskov
22ccbd1e68 Fix serialization of iml files for IDEA 192
#KT-32629 Fixed

(cherry picked from commit d69fbf1177)
2019-07-22 16:01:11 +03:00
Dmitry Gridin
28570a681f AddOperatorModifierInspection: decrease severity to INFORMATION
#KT-32796 Fixed

(cherry picked from commit a9f0d1a53b)
2019-07-22 11:40:09 +03:00
Dmitry Gridin
23c77c4432 GradleBuildScript: throw exception when trying to change level of language features to disable in multiplatform & fix tests
(cherry picked from commit 7d173ed385)
2019-07-22 11:40:09 +03:00
Dmitry Gridin
871cb5708d UpdateConfigurationQuickFixTest: update tests
(cherry picked from commit 0d49ffa831)
2019-07-22 11:40:08 +03:00
Dmitry Gridin
76ebfd4f02 BuildScriptManipulator: implement new syntax for enable experimental features in MPP
#KT-28295 Fixed

(cherry picked from commit cb432acfb7)
2019-07-22 11:40:08 +03:00
Dmitry Gridin
dc7763804d GradleConfiguratorTest: fix configureJvmEAPWithBuildGradleKts test
(cherry picked from commit 8887031962)
2019-07-22 11:40:08 +03:00
Dmitry Gridin
e087fdff6c KotlinBuildScriptManipulator: cleanup code
(cherry picked from commit 46dfff7d82)
2019-07-22 11:40:08 +03:00
Dmitry Gridin
13b87924ba FeatureSupportIntentionActionsFactory: add the missing branch else
(cherry picked from commit b1d1a4b2e1)
2019-07-22 11:40:08 +03:00
Dmitry Gridin
a4f4199314 IDE: add warn on java files outside java source roots
#KT-28121 Fixed

(cherry picked from commit 60421c441e)
2019-07-22 11:40:08 +03:00
Dmitry Gridin
19b3836b88 CreateExpectedFix: fix KNPE from init block
#KT-32639 Fixed

(cherry picked from commit 4928f3ff57)
2019-07-22 11:40:08 +03:00
Dmitry Gridin
c49fedf84b CreateActualFix: should create source root directory if it doesn't exist
#KT-27555 Fixed

(cherry picked from commit fc45948da6)
2019-07-22 11:40:08 +03:00
Dmitry Gridin
69d794591a RemoveRedundantQualifierNameInspection: shouldn't analysis import and package directives
(cherry picked from commit 229b8cb6a3)
2019-07-22 11:40:08 +03:00
Dmitry Gridin
10c0eedf9d RemoveRedundantQualifierNameInspection: fix false negative for java constructor
#KT-32506 Fixed

(cherry picked from commit 694c231689)
2019-07-22 11:40:07 +03:00
Anton Yalyshev
7fba7e299d Cleanup: specify description for Gradle Kotlin/Multiplatform wizard
(cherry picked from commit 959b720e3f)
2019-07-22 11:37:22 +03:00
Anton Yalyshev
25cf276591 Cleanup: make comments more informative
(cherry picked from commit 19dfbfa42c)
2019-07-22 11:37:22 +03:00
Anton Yalyshev
c0520b9f9d Extract adding of sourceSets to subclass, cause superclass is also used in other wizards where this procedure breaks build.gradle
#KT-32105 Fixed

(cherry picked from commit 1cdcde86e3)
2019-07-22 11:37:21 +03:00
Anton Yalyshev
f95e9f2057 Add clarifications about single/multi targeting to framework descriptions
(cherry picked from commit 5b66063650)
2019-07-22 11:37:21 +03:00
Anton Yalyshev
1d33d1bdc1 Refactoring: extract and pull up duplicated code from JVM- and JS- related subclassed
(cherry picked from commit a864715cb8)
2019-07-22 11:37:21 +03:00
Anton Yalyshev
90dbd3bc79 Add Kotlin/MPP to Gradle group of New Project Wizards #KT-32105 Fixed
(cherry picked from commit 9d6367a9be)
2019-07-22 11:37:21 +03:00
Dmitriy Dolovov
213611ee14 Make [Jvm|Js]IdePlatformKind and [Jvm|Js]IdePlatformKindTooling available in all IDEs
Issue #KT-29953 Fixed
2019-07-22 11:42:48 +07:00
Dmitriy Dolovov
a731b0e3ab Always analyze KTS with JVM platform
Issue #KT-29953
2019-07-22 11:42:41 +07:00
Dmitriy Dolovov
9087bdb244 CIDR: Filter aux library order entries that do not represent K/N libraries
Issue #KT-32726 Fixed
2019-07-22 11:42:34 +07:00
Vladimir Dolzhenko
c5626b7600 Fixed a corner case for invalidate package cache for default package
relates to KT-25264

(cherry picked from commit 0f6c381cd7)
2019-07-19 18:03:49 +02:00
Natalia Selezneva
7c52292b28 Invalid script dependencies should be removed from fileAttributes to avoid 'all red file highlighting'
^KT-32061 Fixed

(cherry picked from commit 7d6bb023a8)
2019-07-19 13:12:53 +03:00
Natalia Selezneva
02b4370132 Add Show Kotlin Gradle DSL Logs Action (KT-31440)
Provide a label for this action in some script diagnostics from gradle dsl resolver
^KT-31440 Fixed

(cherry picked from commit f6b03dc02f)
2019-07-19 13:12:52 +03:00
Natalia Selezneva
fef22e58c7 ScriptDefinitionsManager shouldn't be ready if definitions aren't initialized yet (KT-32554)
Otherwise this can lead to wrong script definition detection on project opening
^KT-32554 Fixed

(cherry picked from commit a2d284c769)
2019-07-19 13:12:51 +03:00
Natalia Selezneva
255dd2fa74 Scripts: pass script definition as parameter to loader (KT-32554)
This should avoid situation when script definition for file is changed between isApplicable and loadDependencies calls

^KT-32554 Fixed

(cherry picked from commit e40cdef257)
2019-07-19 13:12:50 +03:00
Natalia Selezneva
7aba6e36cb Scripts: check that file is non-script starting script compilation configuration update
Replace FileType check with more precise method isNonScript

(cherry picked from commit 763f1e8606)
2019-07-19 13:12:50 +03:00
Natalia Selezneva
87e7da4414 Append for commit: switch ScriptReportSink to new scripting API
Commit hash e4d0c2cb0e

(cherry picked from commit 4fed624942)
2019-07-19 13:12:49 +03:00
Natalia Selezneva
44fb1dd3e0 Performance: do not check file type for scripts with standard extension
(cherry picked from commit 63767b4dca)
2019-07-19 13:12:48 +03:00
Vladimir Dolzhenko
cdc165c019 Do not invalidate package caches on generic events, KT-25264
(cherry picked from commit 022275b781)
2019-07-19 10:16:10 +02:00
Vladimir Dolzhenko
0713dc3152 Show progress on remove unused imports, KT-30748
(cherry picked from commit 39f6416757)
2019-07-19 10:15:59 +02:00
victor.petukhov
3b87a770fb Add condition for checkNonParenthesizedAnnotationsOnFunctionalType call to except error reporting in stub mode
(cherry picked from commit 60c4eb68ff)
2019-07-19 11:02:51 +03:00
victor.petukhov
9d640362ee Fix error message for non-parenthesized annotations on functional types
(cherry picked from commit 7ee5583c89)
2019-07-19 11:02:24 +03:00
victor.petukhov
a15e286a44 Support non-parenthesized annotations on functional types without receiver
^KT-31734 Fixed

(cherry picked from commit 6a679d86ab)
2019-07-19 11:02:00 +03:00
Kirill Shmakov
5a82573452 Use same models in MPP and CIDR
(cherry picked from commit 407e5a5270)
2019-07-18 20:18:30 +03:00
nikita.movshin
b7b152f944 Update Kotlin Native version for EAP 2019-07-15 17:56:58 +03:00
Ivan Gavrilovic
d19fdb2008 KT-31291: Wrap ASM version in a method to avoid having it inlined
This commit adds a method to get the value of org.jetbrains.org.objectweb.asm.Oopcodes.API_VERSION.
In general, this should not be a problem, but some Gradle plugins package
Jetbrains ASM version. At runtime, their version may be loaded which may be
different than the one this code was compiled against.

(cherry picked from commit 4caddd2c1c)
2019-07-15 16:55:04 +09:00
Ivan Gavrilovic
4f27cc0efb Improve incremental KAPT logging
This commit improves incremental KAPT logging. It reports processor
stats using their actual names. Also, warning is printed if incremental
annotation processing is requested, but not all APs are incremental

(cherry picked from commit 6619106af2)
2019-07-15 16:54:54 +09:00
Ivan Gavrilovic
226bdfe993 KAPT: Mark incremental cache as LocalState
Use @LocalState to mark incremental annotation processing cache directory.
This is to make sure this is not stored in the build cache as it contains
absolute paths and cannot be shared between machines.

(cherry picked from commit 5cab6fd6cf)
2019-07-15 16:54:40 +09:00
Ivan Gavrilovic
293eb56a9f KT-31840: Fix caching for incremental annotation processing
Artifact transform that uses ASM to analyze KAPT classpath stored absolute
paths in the output artifact. This resulted in remote build cache misses.

This commit changes how analysis is stored. Actual analysis file is the
output of the transform, and there is not need to use a marker file any more.
Output does not store the classpath entry absolute path. Instead, it uses
task action incremental information to find analysis outputs that changed.

Additionally, class that handles analysis snapshot comparison has been
simplified, and lazy loading of the structural information is handled in
a more straightforward way.

(cherry picked from commit 251d8ccd97)
2019-07-15 16:54:29 +09:00
nikita.movshin
8442ecc368 Add changelog for 1.3.50 EAP 1 2019-07-13 15:12:08 +03:00
849 changed files with 28724 additions and 14465 deletions

1
.bunch
View File

@@ -5,3 +5,4 @@
as33_182_183
as34_183
as35
as36_192

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -22,9 +22,11 @@ import org.jetbrains.kotlin.utils.sure
import java.io.File
open class GeneratedFile(
val sourceFiles: Collection<File>,
sourceFiles: Collection<File>,
val outputFile: File
)
) {
val sourceFiles = sourceFiles.sortedBy { it.path }
}
class GeneratedJvmClass (
sourceFiles: Collection<File>,

View File

@@ -75,12 +75,13 @@ open class LookupStorage(
}
@Synchronized
fun addAll(lookups: Set<Map.Entry<LookupSymbol, Collection<String>>>, allPaths: Set<String>) {
val pathToId = allPaths.keysToMap { addFileIfNeeded(File(it)) }
fun addAll(lookups: MultiMap<LookupSymbol, String>, allPaths: Set<String>) {
val pathToId = allPaths.sorted().keysToMap { addFileIfNeeded(File(it)) }
for ((lookupSymbol, paths) in lookups) {
for (lookupSymbol in lookups.keySet().sorted()) {
val key = LookupSymbolKey(lookupSymbol.name, lookupSymbol.scope)
val fileIds = paths.mapTo(HashSet<Int>()) { pathToId[it]!! }
val paths = lookups[lookupSymbol]!!
val fileIds = paths.mapTo(TreeSet()) { pathToId[it]!! }
fileIds.addAll(lookupMap[key] ?: emptySet())
lookupMap[key] = fileIds
}
@@ -227,4 +228,11 @@ class LookupTrackerImpl(private val delegate: LookupTracker) : LookupTracker {
}
}
data class LookupSymbol(val name: String, val scope: String)
data class LookupSymbol(val name: String, val scope: String) : Comparable<LookupSymbol> {
override fun compareTo(other: LookupSymbol): Int {
val scopeCompare = scope.compareTo(other.scope)
if (scopeCompare != 0) return scopeCompare
return name.compareTo(other.name)
}
}

View File

@@ -30,6 +30,7 @@ import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.progress.CompilationCanceledStatus
import org.jetbrains.kotlin.synthetic.SAM_LOOKUP_NAME
import org.jetbrains.kotlin.utils.addToStdlib.flattenTo
import org.jetbrains.kotlin.utils.keysToMap
import java.io.File
import java.util.*
import kotlin.collections.HashSet
@@ -126,7 +127,7 @@ fun LookupStorage.update(
removeLookupsFrom(filesToCompile.asSequence() + removedFiles.asSequence())
addAll(lookupTracker.lookups.entrySet(), lookupTracker.pathInterner.values)
addAll(lookupTracker.lookups, lookupTracker.pathInterner.values)
}
data class DirtyData(

View File

@@ -0,0 +1,90 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.incremental.storage
import com.intellij.util.io.DataExternalizer
import com.intellij.util.io.EnumeratorStringDescriptor
import com.intellij.util.io.KeyDescriptor
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.utils.Printer
import java.io.File
abstract class BasicMap<K : Comparable<K>, V>(
storageFile: File,
keyDescriptor: KeyDescriptor<K>,
valueExternalizer: DataExternalizer<V>
) {
protected val storage: LazyStorage<K, V>
private val nonCachingStorage = System.getProperty("kotlin.jps.non.caching.storage")?.toBoolean() ?: false
init {
storage = if (nonCachingStorage) {
NonCachingLazyStorage(storageFile, keyDescriptor, valueExternalizer)
} else {
CachingLazyStorage(storageFile, keyDescriptor, valueExternalizer)
}
}
fun clean() {
storage.clean()
}
fun flush(memoryCachesOnly: Boolean) {
storage.flush(memoryCachesOnly)
}
fun close() {
storage.close()
}
@TestOnly
fun dump(): String {
return with(StringBuilder()) {
with(Printer(this)) {
println(this@BasicMap::class.java.simpleName)
pushIndent()
for (key in storage.keys.sorted()) {
println("${dumpKey(key)} -> ${dumpValue(storage[key]!!)}")
}
popIndent()
}
this
}.toString()
}
@TestOnly
protected abstract fun dumpKey(key: K): String
@TestOnly
protected abstract fun dumpValue(value: V): String
}
abstract class BasicStringMap<V>(
storageFile: File,
keyDescriptor: KeyDescriptor<String>,
valueExternalizer: DataExternalizer<V>
) : BasicMap<String, V>(storageFile, keyDescriptor, valueExternalizer) {
constructor(
storageFile: File,
valueExternalizer: DataExternalizer<V>
) : this(storageFile, EnumeratorStringDescriptor.INSTANCE, valueExternalizer)
override fun dumpKey(key: String): String = key
}

View File

@@ -0,0 +1,108 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.incremental.storage
import com.intellij.util.io.DataExternalizer
import com.intellij.util.io.KeyDescriptor
import com.intellij.util.io.PersistentHashMap
import java.io.File
/**
* It's lazy in a sense that PersistentHashMap is created only on write
*/
class CachingLazyStorage<K, V>(
private val storageFile: File,
private val keyDescriptor: KeyDescriptor<K>,
private val valueExternalizer: DataExternalizer<V>
) : LazyStorage<K, V> {
@Volatile
private var storage: PersistentHashMap<K, V>? = null
@Synchronized
private fun getStorageIfExists(): PersistentHashMap<K, V>? {
if (storage != null) return storage
if (storageFile.exists()) {
storage = createMap()
return storage
}
return null
}
@Synchronized
private fun getStorageOrCreateNew(): PersistentHashMap<K, V> {
if (storage == null) {
storage = createMap()
}
return storage!!
}
override val keys: Collection<K>
get() = getStorageIfExists()?.allKeysWithExistingMapping ?: listOf()
override operator fun contains(key: K): Boolean =
getStorageIfExists()?.containsMapping(key) ?: false
override operator fun get(key: K): V? =
getStorageIfExists()?.get(key)
override operator fun set(key: K, value: V) {
getStorageOrCreateNew().put(key, value)
}
override fun remove(key: K) {
getStorageIfExists()?.remove(key)
}
override fun append(key: K, value: V) {
getStorageOrCreateNew().appendData(key, { valueExternalizer.save(it, value) })
}
@Synchronized
override fun clean() {
try {
storage?.close()
} catch (ignored: Throwable) {
}
PersistentHashMap.deleteFilesStartingWith(storageFile)
storage = null
}
@Synchronized
override fun flush(memoryCachesOnly: Boolean) {
val existingStorage = storage ?: return
if (memoryCachesOnly) {
if (existingStorage.isDirty) {
existingStorage.dropMemoryCaches()
}
} else {
existingStorage.force()
}
}
@Synchronized
override fun close() {
storage?.close()
}
private fun createMap(): PersistentHashMap<K, V> = PersistentHashMap(storageFile, keyDescriptor, valueExternalizer)
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.incremental.storage
import org.jetbrains.kotlin.incremental.dumpCollection
import org.jetbrains.kotlin.name.FqName
import java.io.File
internal open class ClassOneToManyMap(
storageFile: File
) : BasicStringMap<Collection<String>>(storageFile, StringCollectionExternalizer) {
override fun dumpValue(value: Collection<String>): String = value.dumpCollection()
fun add(key: FqName, value: FqName) {
storage.append(key.asString(), listOf(value.asString()))
}
operator fun get(key: FqName): Collection<FqName> =
storage[key.asString()]?.map(::FqName) ?: setOf()
operator fun set(key: FqName, values: Collection<FqName>) {
if (values.isEmpty()) {
remove(key)
return
}
storage[key.asString()] = values.map(FqName::asString)
}
fun remove(key: FqName) {
storage.remove(key.asString())
}
fun removeValues(key: FqName, removed: Set<FqName>) {
val notRemoved = this[key].filter { it !in removed }
this[key] = notRemoved
}
}
internal class SubtypesMap(storageFile: File) : ClassOneToManyMap(storageFile)
internal class SupertypesMap(storageFile: File) : ClassOneToManyMap(storageFile)

View File

@@ -0,0 +1,29 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.incremental.storage
interface LazyStorage<K, V> {
val keys: Collection<K>
operator fun contains(key: K): Boolean
operator fun get(key: K): V?
operator fun set(key: K, value: V)
fun remove(key: K)
fun append(key: K, value: V)
fun clean()
fun flush(memoryCachesOnly: Boolean)
fun close()
}

View File

@@ -0,0 +1,42 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.incremental.storage
import java.io.File
internal class LookupMap(storage: File) : BasicMap<LookupSymbolKey, Collection<Int>>(storage, LookupSymbolKeyDescriptor, IntCollectionExternalizer) {
override fun dumpKey(key: LookupSymbolKey): String = key.toString()
override fun dumpValue(value: Collection<Int>): String = value.toString()
fun add(name: String, scope: String, fileId: Int) {
storage.append(LookupSymbolKey(name, scope), listOf(fileId))
}
operator fun get(key: LookupSymbolKey): Collection<Int>? = storage[key]
operator fun set(key: LookupSymbolKey, fileIds: Set<Int>) {
storage[key] = fileIds
}
fun remove(key: LookupSymbolKey) {
storage.remove(key)
}
val keys: Collection<LookupSymbolKey>
get() = storage.keys
}

View File

@@ -0,0 +1,106 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.incremental.storage
import com.intellij.util.io.DataExternalizer
import com.intellij.util.io.KeyDescriptor
import com.intellij.util.io.JpsPersistentHashMap
import java.io.File
class NonCachingLazyStorage<K, V>(
private val storageFile: File,
private val keyDescriptor: KeyDescriptor<K>,
private val valueExternalizer: DataExternalizer<V>
) : LazyStorage<K, V> {
@Volatile
private var storage: JpsPersistentHashMap<K, V>? = null
@Synchronized
private fun getStorageIfExists(): JpsPersistentHashMap<K, V>? {
if (storage != null) return storage
if (storageFile.exists()) {
storage = createMap()
return storage
}
return null
}
@Synchronized
private fun getStorageOrCreateNew(): JpsPersistentHashMap<K, V> {
if (storage == null) {
storage = createMap()
}
return storage!!
}
override val keys: Collection<K>
get() = getStorageIfExists()?.allKeysWithExistingMapping ?: listOf()
override operator fun contains(key: K): Boolean =
getStorageIfExists()?.containsMapping(key) ?: false
override operator fun get(key: K): V? =
getStorageIfExists()?.get(key)
override operator fun set(key: K, value: V) {
getStorageOrCreateNew().put(key, value)
}
override fun remove(key: K) {
getStorageIfExists()?.remove(key)
}
override fun append(key: K, value: V) {
getStorageOrCreateNew().appendDataWithoutCache(key, value)
}
@Synchronized
override fun clean() {
try {
storage?.close()
} catch (ignored: Throwable) {
}
JpsPersistentHashMap.deleteFilesStartingWith(storageFile)
storage = null
}
@Synchronized
override fun flush(memoryCachesOnly: Boolean) {
val existingStorage = storage ?: return
if (memoryCachesOnly) {
if (existingStorage.isDirty) {
existingStorage.dropMemoryCaches()
}
} else {
existingStorage.force()
}
}
@Synchronized
override fun close() {
storage?.close()
}
private fun createMap(): JpsPersistentHashMap<K, V> =
JpsPersistentHashMap(storageFile, keyDescriptor, valueExternalizer)
}

View File

@@ -0,0 +1,34 @@
/*
* 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.incremental.storage
import java.io.File
open class RelativeFileToPathConverter(baseDirFile: File?) : FileToPathConverter {
private val baseDirPath = baseDirFile?.canonicalFile?.invariantSeparatorsPath
override fun toPath(file: File): String {
val path = file.canonicalFile.invariantSeparatorsPath
return when {
baseDirPath != null && path.startsWith(baseDirPath) ->
PROJECT_DIR_PLACEHOLDER + path.substring(baseDirPath.length)
else -> path
}
}
override fun toFile(path: String): File =
when {
path.startsWith(PROJECT_DIR_PLACEHOLDER) -> {
val basePath = baseDirPath ?: error("Could not get project root dir")
File(basePath + path.substring(PROJECT_DIR_PLACEHOLDER.length))
}
else -> File(path)
}
private companion object {
private const val PROJECT_DIR_PLACEHOLDER = "${'$'}PROJECT_DIR$"
}
}

View File

@@ -0,0 +1,62 @@
/*
* 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.incremental.storage
import org.jetbrains.kotlin.incremental.dumpCollection
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import java.io.File
internal class SourceToJvmNameMap(
storageFile: File,
pathConverter: FileToPathConverter
) : AbstractSourceToOutputMap<JvmClassName>(JvmClassNameTransformer, storageFile, pathConverter)
internal class SourceToFqNameMap(
storageFile: File,
pathConverter: FileToPathConverter
) : AbstractSourceToOutputMap<FqName>(FqNameTransformer, storageFile, pathConverter)
internal abstract class AbstractSourceToOutputMap<Name>(
private val nameTransformer: NameTransformer<Name>,
storageFile: File,
private val pathConverter: FileToPathConverter
) : BasicStringMap<Collection<String>>(storageFile, PathStringDescriptor, StringCollectionExternalizer) {
fun clearOutputsForSource(sourceFile: File) {
remove(pathConverter.toPath(sourceFile))
}
fun add(sourceFile: File, className: Name) {
storage.append(pathConverter.toPath(sourceFile), listOf(nameTransformer.asString(className)))
}
fun contains(sourceFile: File): Boolean =
pathConverter.toPath(sourceFile) in storage
operator fun get(sourceFile: File): Collection<Name> =
storage[pathConverter.toPath(sourceFile)].orEmpty().map(nameTransformer::asName)
fun getFqNames(sourceFile: File): Collection<FqName> =
storage[pathConverter.toPath(sourceFile)].orEmpty().map(nameTransformer::asFqName)
override fun dumpValue(value: Collection<String>) =
value.dumpCollection()
private fun remove(path: String) {
storage.remove(path)
}
}

View File

@@ -0,0 +1,90 @@
/*
* 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.incremental.storage
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.TestWithWorkingDir
import org.jetbrains.kotlin.incremental.LookupStorage
import org.jetbrains.kotlin.incremental.LookupSymbol
import org.jetbrains.kotlin.incremental.testingUtils.assertEqualDirectories
import org.junit.Test
import java.io.File
class RelocatableCachesTest : TestWithWorkingDir() {
@Test
fun testLookupStorageAddAllReversedFiles() {
val originalRoot = workingDir.resolve("original")
fillLookupStorage(originalRoot, reverseFiles = false, reverseLookups = false)
val reversedFilesOrderRoot = workingDir.resolve("reversedFiles")
fillLookupStorage(reversedFilesOrderRoot, reverseFiles = true, reverseLookups = false)
assertEqualDirectories(originalRoot, reversedFilesOrderRoot, forgiveExtraFiles = false)
}
@Test
fun testLookupStorageAddAllReversedLookups() {
val originalRoot = workingDir.resolve("original")
fillLookupStorage(originalRoot, reverseFiles = false, reverseLookups = false)
val reversedLookupsOrderRoot = workingDir.resolve("reversedLookups")
fillLookupStorage(reversedLookupsOrderRoot, reverseFiles = false, reverseLookups = true)
assertEqualDirectories(originalRoot, reversedLookupsOrderRoot, forgiveExtraFiles = false)
}
@Test
fun testLookupStorageAddAllReversedFilesReversedLookups() {
val originalRoot = workingDir.resolve("original")
fillLookupStorage(originalRoot, reverseFiles = false, reverseLookups = false)
val reversedFilesReversedLookupsOrderRoot = workingDir.resolve("reversedFilesReversedLookupsOrderRoot")
fillLookupStorage(reversedFilesReversedLookupsOrderRoot, reverseFiles = true, reverseLookups = true)
assertEqualDirectories(originalRoot, reversedFilesReversedLookupsOrderRoot, forgiveExtraFiles = false)
}
/**
* Fills lookup storage in [projectRoot] with N fq-names,
* where i_th fq-name myscope_i.MyClass_i has lookups for previous fq-names (from 0 to i-1)
*/
private fun fillLookupStorage(projectRoot: File, reverseFiles: Boolean, reverseLookups: Boolean) {
val storageRoot = projectRoot.storageRoot
val fileToPathConverter = RelativeFileToPathConverter(projectRoot)
val lookupStorage = LookupStorage(storageRoot, fileToPathConverter)
val files = LinkedHashSet<String>()
val symbols = LinkedHashSet<LookupSymbol>()
val lookups = MultiMap.createOrderedSet<LookupSymbol, String>()
for (i in 0..10) {
val newSymbol = LookupSymbol(name = "MyClass_$i", scope = "myscope_$i")
val newSourcePath = projectRoot.resolve("src/${newSymbol.asRelativePath()}").canonicalFile.invariantSeparatorsPath
symbols.add(newSymbol)
for (lookedUpSymbol in symbols) {
lookups.putValue(lookedUpSymbol, newSourcePath)
}
files.add(newSourcePath)
}
val filesToAdd = if (reverseFiles) files.reversedSet() else files
val lookupsToAdd = if (reverseLookups) lookups.reversedMultiMap() else lookups
lookupStorage.addAll(lookupsToAdd, filesToAdd)
lookupStorage.flush(memoryCachesOnly = false)
}
private val File.storageRoot: File
get() = resolve("storage")
private fun <K, V> MultiMap<K, V>.reversedMultiMap(): MultiMap<K, V> {
val newMap = MultiMap.createOrderedSet<K, V>()
for ((key, values) in entrySet().reversedSet()) {
newMap.putValues(key, values.reversed())
}
return newMap
}
private fun <T> Set<T>.reversedSet(): LinkedHashSet<T> =
reversed().toCollection(LinkedHashSet(size))
private fun LookupSymbol.asRelativePath(): String =
if (scope.isBlank()) name else scope.replace('.', '/') + '/' + name
}

View File

@@ -36,6 +36,7 @@ import org.jetbrains.org.objectweb.asm.ClassReader
import org.jetbrains.org.objectweb.asm.util.TraceClassVisitor
import org.junit.Assert
import org.junit.Assert.assertNotNull
import org.junit.ComparisonFailure
import java.io.*
import java.util.*
import java.util.zip.CRC32
@@ -71,7 +72,15 @@ fun assertEqualDirectories(expected: File, actual: File, forgiveExtraFiles: Bool
}
}
Assert.assertEquals(expectedString, actualString)
if (expectedString != actualString) {
val message: String? = null
throw ComparisonFailure(
message,
expectedString.replaceFirst(DIR_ROOT_PLACEHOLDER, expected.canonicalPath),
actualString.replaceFirst(DIR_ROOT_PLACEHOLDER, actual.canonicalPath)
)
}
}
private fun File.checksumString(): String {
@@ -80,6 +89,8 @@ private fun File.checksumString(): String {
return java.lang.Long.toHexString(crc32.value)
}
private const val DIR_ROOT_PLACEHOLDER = "<DIR_ROOT_PLACEHOLDER>"
private fun getDirectoryString(dir: File, interestingPaths: List<String>): String {
val buf = StringBuilder()
val p = Printer(buf)
@@ -108,7 +119,7 @@ private fun getDirectoryString(dir: File, interestingPaths: List<String>): Strin
}
p.println(".")
p.println(DIR_ROOT_PLACEHOLDER)
addDirContent(dir)
for (path in interestingPaths) {

View File

@@ -9,7 +9,7 @@ buildscript {
extra["defaultSnapshotVersion"] = "1.3-SNAPSHOT"
// when updating please also update JPS artifacts configuration: https://jetbrains.quip.com/zzGUAYSJ6gv3/JPS-Build-update-bootstrap
kotlinBootstrapFrom(BootstrapOption.TeamCity("1.3.50-dev-526", onlySuccessBootstrap = false))
kotlinBootstrapFrom(BootstrapOption.TeamCity("1.3.50-eap-71", projectExtId = "Kotlin_1350_Compiler", onlySuccessBootstrap = false))
repositories {
bootstrapKotlinRepo?.let(::maven)
@@ -122,30 +122,19 @@ extra["JDK_9"] = jdkPath("9")
extra["JDK_10"] = jdkPath("10")
extra["JDK_11"] = jdkPath("11")
gradle.taskGraph.beforeTask() {
// allow opening the project without setting up all env variables (see KT-26413)
if (!kotlinBuildProperties.isInIdeaSync) {
checkJDK()
}
var jdkChecked: Boolean = false
fun checkJDK() {
if (jdkChecked) {
return
val missingEnvVars = JdkMajorVersion.values()
.filter { it.isMandatory() && extra[it.name] == jdkNotFoundConst }
.mapTo(ArrayList()) { it.name }
if (missingEnvVars.isNotEmpty()) {
throw GradleException("Required environment variables are missing: ${missingEnvVars.joinToString()}")
}
val unpresentJdks = JdkMajorVersion.values()
.filter { it.isMandatory() }
.map { it.name }
.filter { extra[it] == jdkNotFoundConst }
.toList()
if (unpresentJdks.isNotEmpty()) {
throw GradleException("Please set environment variable" +
(if (unpresentJdks.size > 1) "s" else "") +
": " + unpresentJdks.joinToString() +
" to point to corresponding JDK installation.")
}
jdkChecked = true
}
rootProject.apply {
@@ -182,7 +171,7 @@ extra["versions.trove4j"] = "1.0.20181211"
extra["versions.ktor-network"] = "1.0.1"
if (!project.hasProperty("versions.kotlin-native")) {
extra["versions.kotlin-native"] = "1.3.50-dev-11052"
extra["versions.kotlin-native"] = "1.3.50"
}
val isTeamcityBuild = project.kotlinBuildProperties.isTeamcityBuild
@@ -407,6 +396,9 @@ allprojects {
configurations.findByName("kotlinCompilerClasspath")?.let {
dependencies.add(it.name, files(bootstrapCompilerClasspath))
}
configurations.findByName("kotlinCompilerPluginClasspath")
?.exclude("org.jetbrains.kotlin", "kotlin-scripting-compiler-embeddable")
}
// Aggregate task for build related checks
@@ -731,9 +723,14 @@ fun jdkPath(version: String): String {
fun Project.configureJvmProject(javaHome: String, javaVersion: String) {
val currentJavaHome = File(System.getProperty("java.home")!!).canonicalPath
val shouldFork = !currentJavaHome.startsWith(File(javaHome).canonicalPath)
tasks.withType<JavaCompile> {
if (name != "compileJava9Java") {
options.isFork = true
sourceCompatibility = javaVersion
targetCompatibility = javaVersion
options.isFork = shouldFork
options.forkOptions.javaHome = file(javaHome)
options.compilerArgs.add("-proc:none")
options.encoding = "UTF-8"
@@ -749,6 +746,27 @@ fun Project.configureJvmProject(javaHome: String, javaVersion: String) {
tasks.withType<Test> {
executable = File(javaHome, "bin/java").canonicalPath
}
plugins.withId("java-base") {
configureShadowJarSubstitutionInCompileClasspath()
}
}
fun Project.configureShadowJarSubstitutionInCompileClasspath() {
val substitutionMap = mapOf(":kotlin-reflect" to ":kotlin-reflect-api")
fun configureSubstitution(substitution: DependencySubstitution) {
val requestedProject = (substitution.requested as? ProjectComponentSelector)?.projectPath ?: return
val replacementProject = substitutionMap[requestedProject] ?: return
substitution.useTarget(project(replacementProject), "Non-default shadow jars should not be used in compile classpath")
}
sourceSets.all {
val compileClasspathConfig = configurations.getByName(compileClasspathConfigurationName)
compileClasspathConfig.resolutionStrategy.dependencySubstitution {
all(::configureSubstitution)
}
}
}
tasks.create("findShadowJarsInClasspath").doLast {
@@ -756,12 +774,19 @@ tasks.create("findShadowJarsInClasspath").doLast {
sortedBy { it.path }.forEach { println(indent + it.relativeTo(rootProject.projectDir)) }
}
val mainJars = hashSetOf<File>()
val shadowJars = hashSetOf<File>()
for (project in rootProject.allprojects) {
project.withJavaPlugin {
project.sourceSets.forEach { sourceSet ->
val jarTask = project.tasks.findByPath(sourceSet.jarTaskName) as? Jar
jarTask?.outputFile?.let { mainJars.add(it) }
}
}
for (task in project.tasks) {
when (task) {
is ShadowJar -> {
shadowJars.add(fileFrom(task.archivePath))
shadowJars.add(fileFrom(task.outputFile))
}
is ProGuardTask -> {
shadowJars.addAll(task.outputs.files.toList())
@@ -770,7 +795,8 @@ tasks.create("findShadowJarsInClasspath").doLast {
}
}
println("Shadow jars:")
shadowJars.removeAll(mainJars)
println("Shadow jars that might break incremental compilation:")
shadowJars.printSorted()
fun Project.checkConfig(configName: String) {
@@ -784,7 +810,14 @@ tasks.create("findShadowJarsInClasspath").doLast {
}
for (project in rootProject.allprojects) {
project.checkConfig("compileClasspath")
project.checkConfig("testCompileClasspath")
project.sourceSetsOrNull?.forEach { sourceSet ->
project.checkConfig(sourceSet.compileClasspathConfigurationName)
}
}
}
val Jar.outputFile: File
get() = archiveFile.get().asFile
val Project.sourceSetsOrNull: SourceSetContainer?
get() = convention.findPlugin(JavaPluginConvention::class.java)?.sourceSets

View File

@@ -112,6 +112,11 @@ samWithReceiver {
fun Project.`samWithReceiver`(configure: org.jetbrains.kotlin.samWithReceiver.gradle.SamWithReceiverExtension.() -> Unit): Unit =
extensions.configure("samWithReceiver", configure)
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
tasks["build"].dependsOn(":prepare-deps:build")
allprojects {

View File

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

View File

@@ -65,6 +65,23 @@ repositories {
artifact()
}
}
ivy {
url = URI("https://dl.bintray.com/kotlin/as/")
patternLayout {
artifact("[artifact]-[revision]-$androidStudioOs.[ext]")
}
credentials {
username = System.getenv("AS_BINTRAY_USER_NAME")
password = System.getenv("AS_BINTRAY_API_KEY")
}
metadataSources {
artifact()
}
}
}
maven("https://www.jetbrains.com/intellij-repository/$intellijReleaseType")
@@ -94,7 +111,8 @@ val repoDir = File(customDepsRepoDir, customDepsOrg)
dependencies {
if (androidStudioRelease != null) {
val extension = if (androidStudioOs == "linux" && androidStudioRelease.startsWith("3.5"))
val extension = if (androidStudioOs == "linux" &&
(androidStudioRelease.startsWith("3.5") || androidStudioRelease.startsWith("3.6")))
"tar.gz"
else
"zip"

View File

@@ -23,6 +23,17 @@ if (flags.includeCidrPlugins) {
logger.info("NOT including CIDR plugins in buildSrc/settings.gradle")
}
if (flags.hasKotlinUltimate) {
logger.info("Including extension for IJ Ultimate in buildSrc/settings.gradle")
include ":prepare-deps:lldb-frontend"
include ":prepare-deps:native-debug-plugin"
project(":prepare-deps:lldb-frontend").projectDir = file("${flags.propertiesProvider.rootProjectDir}/kotlin-ultimate/buildSrc/prepare-deps/lldb-frontend")
project(":prepare-deps:native-debug-plugin").projectDir = file("${flags.propertiesProvider.rootProjectDir}/kotlin-ultimate/buildSrc/prepare-deps/native-debug-plugin")
} else {
logger.info("Not including extension for IJ Ultimate in buildSrc/settings.gradle")
}
class LocalBuildPropertiesProvider {
private Settings settings
private Properties localProperties = new Properties()
@@ -57,8 +68,11 @@ class LocalBuildProperties {
boolean includeCidrPlugins
boolean hasKotlinUltimate
LocalBuildProperties(Settings settings) {
propertiesProvider = new LocalBuildPropertiesProvider(settings)
includeCidrPlugins = propertiesProvider.getBoolean('cidrPluginsEnabled') && new File(propertiesProvider.rootProjectDir, 'kotlin-ultimate').exists()
hasKotlinUltimate = new File(propertiesProvider.rootProjectDir, 'kotlin-ultimate').exists()
includeCidrPlugins = propertiesProvider.getBoolean('cidrPluginsEnabled') && hasKotlinUltimate
}
}

View File

@@ -50,7 +50,8 @@ enum class Ide(val platform: Platform) : CompatibilityPredicate {
AS32(Platform.P181),
AS33(Platform.P182),
AS34(Platform.P183),
AS35(Platform.P183);
AS35(Platform.P183),
AS36(Platform.P192);
val kind = Kind.values().first { it.shortName == name.take(2) }
val version = name.dropWhile { !it.isDigit() }.toInt()

View File

@@ -57,9 +57,7 @@ class KotlinBuildProperties(
val useBootstrapStdlib: Boolean
get() = isInJpsBuildIdeaSync || getBoolean("kotlin.build.useBootstrapStdlib", false)
val kotlinUltimateExists: Boolean = propertiesProvider.rootProjectDir.resolve("kotlin-ultimate").exists()
val includeCidrPlugins: Boolean = kotlinUltimateExists && getBoolean("cidrPluginsEnabled")
private val kotlinUltimateExists: Boolean = propertiesProvider.rootProjectDir.resolve("kotlin-ultimate").exists()
val isTeamcityBuild: Boolean = getBoolean("teamcity") || System.getenv("TEAMCITY_VERSION") != null
@@ -72,6 +70,10 @@ class KotlinBuildProperties(
return kotlinUltimateExists && (explicitlyEnabled || isTeamcityBuild)
}
val includeCidrPlugins: Boolean = kotlinUltimateExists && getBoolean("cidrPluginsEnabled")
val includeUltimate: Boolean = kotlinUltimateExists && (isTeamcityBuild || intellijUltimateEnabled)
val postProcessing: Boolean get() = isTeamcityBuild || getBoolean("kotlin.build.postprocessing", true)
val relocation: Boolean get() = postProcessing

View File

@@ -19,7 +19,9 @@ val packagesToRelocate =
"org.picocontainer",
"org.jline",
"org.fusesource",
"kotlinx.coroutines")
"kotlinx.coroutines",
"net.jpountz",
"one.util.streamex")
// The shaded compiler "dummy" is used to rewrite dependencies in projects that are used with the embeddable compiler
// on the runtime and use some shaded dependencies from the compiler

View File

@@ -484,7 +484,9 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
protected void generateInitializers(@NotNull Function0<ExpressionCodegen> createCodegen) {
NotNullLazyValue<ExpressionCodegen> codegen = LockBasedStorageManager.NO_LOCKS.createLazyValue(createCodegen);
for (KtDeclaration declaration : ((KtDeclarationContainer) element).getDeclarations()) {
List<KtDeclaration> declarations = ((KtDeclarationContainer) element).getDeclarations();
for (int i = 0; i < declarations.size(); i++) {
KtDeclaration declaration = declarations.get(i);
if (declaration instanceof KtProperty) {
if (shouldInitializeProperty((KtProperty) declaration)) {
generateNopSeparatorIfNeeded(codegen);
@@ -501,7 +503,11 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
generateNopSeparatorIfNeeded(codegen);
ExpressionCodegen expressionCodegen = codegen.invoke();
expressionCodegen.gen(body, Type.VOID_TYPE);
Type bodyExpressionType = Type.VOID_TYPE;
if (i == declarations.size() - 1 && this instanceof ScriptCodegen) {
bodyExpressionType = expressionCodegen.expressionType(body);
}
expressionCodegen.gen(body, bodyExpressionType);
expressionCodegen.markLineNumber(declaration, true);
nopSeparatorNeeded = true;
}

View File

@@ -1071,15 +1071,17 @@ class MethodInliner(
//remove next template:
// aload x
// LDC paramName
// INTRINSICS_CLASS_NAME.checkParameterIsNotNull(...)
// INTRINSICS_CLASS_NAME.checkParameterIsNotNull/checkNotNullParameter(...)
private fun removeClosureAssertions(node: MethodNode) {
val toDelete = arrayListOf<AbstractInsnNode>()
InsnSequence(node.instructions).filterIsInstance<MethodInsnNode>().forEach { methodInsnNode ->
if (methodInsnNode.name == "checkParameterIsNotNull" && methodInsnNode.owner == IntrinsicMethods.INTRINSICS_CLASS_NAME) {
if (methodInsnNode.owner == IntrinsicMethods.INTRINSICS_CLASS_NAME &&
(methodInsnNode.name == "checkParameterIsNotNull" || methodInsnNode.name == "checkNotNullParameter")
) {
val prev = methodInsnNode.previous
assert(Opcodes.LDC == prev?.opcode) { "'checkParameterIsNotNull' should go after LDC but $prev" }
assert(Opcodes.LDC == prev?.opcode) { "'${methodInsnNode.name}' should go after LDC but $prev" }
val prevPev = methodInsnNode.previous.previous
assert(Opcodes.ALOAD == prevPev?.opcode) { "'checkParameterIsNotNull' should be invoked on local var, but $prev" }
assert(Opcodes.ALOAD == prevPev?.opcode) { "'${methodInsnNode.name}' should be invoked on local var, but $prev" }
toDelete.add(prevPev)
toDelete.add(prev)

View File

@@ -819,6 +819,7 @@ class KotlinTypeMapper @JvmOverloads constructor(
receiverTypeAndTypeParameters.receiverType
}
!isIrBackend && kind == OwnerKind.ERASED_INLINE_CLASS -> {
writeFormalTypeParameters(directMember.typeParameters, sw)
(directMember.containingDeclaration as ClassDescriptor).defaultType
}
else -> {

View File

@@ -16,10 +16,6 @@ import org.jetbrains.kotlin.resolve.TargetPlatform
level = DeprecationLevel.ERROR
)
interface CommonPlatform : TargetPlatform {
@JvmDefault
override val platformName: String
get() = "Default"
companion object {
@JvmField
val INSTANCE: CommonPlatform = CommonPlatforms.CompatCommonPlatform

View File

@@ -128,6 +128,18 @@ abstract class CommonCompilerArguments : CommonToolArguments() {
)
var newInference: Boolean by FreezableVar(false)
@Argument(
value = "-Xinline-classes",
description = "Enable experimental inline classes"
)
var inlineClasses: Boolean by FreezableVar(false)
@Argument(
value = "-Xpolymorphic-signature",
description = "Enable experimental support for @PolymorphicSignature (MethodHandle/VarHandle)"
)
var polymorphicSignature: Boolean by FreezableVar(false)
@Argument(
value = "-Xlegacy-smart-cast-after-try",
description = "Allow var smart casts despite assignment in try block"
@@ -324,6 +336,15 @@ abstract class CommonCompilerArguments : CommonToolArguments() {
if (newInference) {
put(LanguageFeature.NewInference, LanguageFeature.State.ENABLED)
put(LanguageFeature.SamConversionPerArgument, LanguageFeature.State.ENABLED)
put(LanguageFeature.FunctionReferenceWithDefaultValueAsOtherType, LanguageFeature.State.ENABLED)
}
if (inlineClasses) {
put(LanguageFeature.InlineClasses, LanguageFeature.State.ENABLED)
}
if (polymorphicSignature) {
put(LanguageFeature.PolymorphicSignature, LanguageFeature.State.ENABLED)
}
if (legacySmartCastAfterTry) {
@@ -362,19 +383,30 @@ abstract class CommonCompilerArguments : CommonToolArguments() {
val featuresThatForcePreReleaseBinaries = mutableListOf<LanguageFeature>()
var standaloneSamConversionFeaturePassedExplicitly = false
var functionReferenceWithDefaultValueFeaturePassedExplicitly = false
for ((feature, state) in internalArguments.filterIsInstance<ManualLanguageFeatureSetting>()) {
put(feature, state)
if (state == LanguageFeature.State.ENABLED && feature.forcesPreReleaseBinariesIfEnabled()) {
featuresThatForcePreReleaseBinaries += feature
}
if (feature == LanguageFeature.SamConversionPerArgument) {
standaloneSamConversionFeaturePassedExplicitly = true
when (feature) {
LanguageFeature.SamConversionPerArgument ->
standaloneSamConversionFeaturePassedExplicitly = true
LanguageFeature.FunctionReferenceWithDefaultValueAsOtherType ->
functionReferenceWithDefaultValueFeaturePassedExplicitly = true
else -> {}
}
}
if (!standaloneSamConversionFeaturePassedExplicitly && this[LanguageFeature.NewInference] == LanguageFeature.State.ENABLED) {
put(LanguageFeature.SamConversionPerArgument, LanguageFeature.State.ENABLED)
if (this[LanguageFeature.NewInference] == LanguageFeature.State.ENABLED) {
if (!standaloneSamConversionFeaturePassedExplicitly)
put(LanguageFeature.SamConversionPerArgument, LanguageFeature.State.ENABLED)
if (!functionReferenceWithDefaultValueFeaturePassedExplicitly)
put(LanguageFeature.FunctionReferenceWithDefaultValueAsOtherType, LanguageFeature.State.ENABLED)
}
if (featuresThatForcePreReleaseBinaries.isNotEmpty()) {

View File

@@ -53,18 +53,15 @@ abstract class KotlinJsr223JvmScriptEngineBase(protected val myFactory: ScriptEn
createState()
}) as IReplStageState<*>
open fun getInvokeWrapper(context: ScriptContext): InvokeWrapper? = null
open fun overrideScriptArgs(context: ScriptContext): ScriptArgsWithTypes? = null
open fun compileAndEval(script: String, context: ScriptContext): Any? {
val codeLine = nextCodeLine(context, script)
val state = getCurrentState(context)
val result = replEvaluator.compileAndEval(state, codeLine, scriptArgs = overrideScriptArgs(context))
return when (result) {
is ReplEvalResult.ValueResult -> result.value
is ReplEvalResult.UnitResult -> null
is ReplEvalResult.Error -> throw ScriptException(result.message)
is ReplEvalResult.Incomplete -> throw ScriptException("error: incomplete code")
is ReplEvalResult.HistoryMismatch -> throw ScriptException("Repl history mismatch at line: ${result.lineNo}")
return asJsr223EvalResult {
replEvaluator.compileAndEval(state, codeLine, overrideScriptArgs(context), getInvokeWrapper(context))
}
}
@@ -83,17 +80,29 @@ abstract class KotlinJsr223JvmScriptEngineBase(protected val myFactory: ScriptEn
open fun eval(compiledScript: CompiledKotlinScript, context: ScriptContext): Any? {
val state = getCurrentState(context)
val result = try {
replEvaluator.eval(state, compiledScript.compiledData, scriptArgs = overrideScriptArgs(context))
return asJsr223EvalResult {
replEvaluator.eval(state, compiledScript.compiledData, overrideScriptArgs(context), getInvokeWrapper(context))
}
catch (e: Exception) {
}
private fun asJsr223EvalResult(body: () -> ReplEvalResult): Any? {
val result = try {
body()
} catch (e: Exception) {
throw ScriptException(e)
}
return when (result) {
is ReplEvalResult.ValueResult -> result.value
is ReplEvalResult.UnitResult -> null
is ReplEvalResult.Error -> throw ScriptException(result.message)
is ReplEvalResult.Error ->
when {
result is ReplEvalResult.Error.Runtime && result.cause != null ->
throw ScriptException(result.cause)
result is ReplEvalResult.Error.CompileTime && result.location != null ->
throw ScriptException(result.message, result.location.path, result.location.line, result.location.column)
else -> throw ScriptException(result.message)
}
is ReplEvalResult.Incomplete -> throw ScriptException("error: incomplete code")
is ReplEvalResult.HistoryMismatch -> throw ScriptException("Repl history mismatch at line: ${result.lineNo}")
}

View File

@@ -25,7 +25,10 @@ object CommonPlatforms {
defaultJsPlatform.single(),
defaultKonanPlatform.single()
)
), org.jetbrains.kotlin.analyzer.common.CommonPlatform
), org.jetbrains.kotlin.analyzer.common.CommonPlatform {
override val platformName: String
get() = "Default"
}
val defaultCommonPlatform: TargetPlatform
get() = CompatCommonPlatform

View File

@@ -24,7 +24,10 @@ object KonanPlatforms {
)
object CompatKonanPlatform : TargetPlatform(setOf(DefaultSimpleKonanPlatform)),
// Needed for backward compatibility, because old code uses INSTANCEOF checks instead of calling extensions
org.jetbrains.kotlin.resolve.konan.platform.KonanPlatform {}
org.jetbrains.kotlin.resolve.konan.platform.KonanPlatform {
override val platformName: String
get() = "Native"
}
val defaultKonanPlatform: TargetPlatform
get() = CompatKonanPlatform

View File

@@ -16,10 +16,6 @@ import org.jetbrains.kotlin.resolve.TargetPlatform
level = DeprecationLevel.ERROR
)
interface KonanPlatform : TargetPlatform {
@JvmDefault
override val platformName: String
get() = "Native"
companion object {
@JvmField
val INSTANCE: KonanPlatform = KonanPlatforms.CompatKonanPlatform

View File

@@ -293,6 +293,11 @@ class KotlinCoreEnvironment private constructor(
}
}
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))

View File

@@ -459,7 +459,7 @@ object KotlinToJVMBytecodeCompiler {
environment: KotlinCoreEnvironment,
targetDescription: String?
): AnalysisResult? {
if (result is AnalysisResult.RetryWithAdditionalJavaRoots) {
if (result is AnalysisResult.RetryWithAdditionalRoots) {
val configuration = environment.configuration
val oldReadOnlyValue = configuration.isReadOnly
@@ -471,6 +471,10 @@ object KotlinToJVMBytecodeCompiler {
environment.updateClasspath(result.additionalJavaRoots.map { JavaSourceRoot(it, null) })
}
if (result.additionalKotlinRoots.isNotEmpty()) {
environment.addKotlinSourceRoots(result.additionalKotlinRoots)
}
KotlinJavaPsiFacade.getInstance(environment.project).clearPackageCaches()
// Clear all diagnostic messages
@@ -562,7 +566,7 @@ object KotlinToJVMBytecodeCompiler {
val analysisResult = analyzerWithCompilerReport.analysisResult
return if (!analyzerWithCompilerReport.hasErrors() || analysisResult is AnalysisResult.RetryWithAdditionalJavaRoots)
return if (!analyzerWithCompilerReport.hasErrors() || analysisResult is AnalysisResult.RetryWithAdditionalRoots)
analysisResult
else
null

View File

@@ -21,7 +21,9 @@ import java.lang.reflect.*
import java.util.*
private object ClassTraversalCache {
private val cache = ContainerUtil.newConcurrentMap<Class<*>, ClassInfo>()
private val cache =
if (System.getProperty("idea.system.path") != null) ContainerUtil.newConcurrentMap<Class<*>, ClassInfo>()
else ContainerUtil.createConcurrentWeakKeySoftValueMap<Class<*>, ClassInfo>()
fun getClassInfo(c: Class<*>): ClassInfo {
val classInfo = cache.get(c)

View File

@@ -187,13 +187,14 @@ fun Iterable<String>.filterExtractProps(vararg groups: OptionsGroup, prefix: Str
data class DaemonJVMOptions(
var maxMemory: String = "",
var maxPermSize: String = "",
var maxMetaspaceSize: String = "",
var reservedCodeCacheSize: String = "",
var jvmParams: MutableCollection<String> = arrayListOf()
) : OptionsGroup {
override val mappers: List<PropMapper<*, *, *>>
get() = listOf(StringPropMapper(this, DaemonJVMOptions::maxMemory, listOf("Xmx"), mergeDelimiter = ""),
StringPropMapper(this, DaemonJVMOptions::maxPermSize, listOf("XX:MaxPermSize"), mergeDelimiter = "="),
StringPropMapper(this, DaemonJVMOptions::maxMetaspaceSize, listOf("XX:MaxMetaspaceSize"), mergeDelimiter = "="),
StringPropMapper(this, DaemonJVMOptions::reservedCodeCacheSize, listOf("XX:ReservedCodeCacheSize"), mergeDelimiter = "="),
restMapper)
@@ -279,11 +280,13 @@ fun configureDaemonJVMOptions(opts: DaemonJVMOptions,
val targetOptions = if (inheritMemoryLimits) opts else DaemonJVMOptions()
val otherArgs = jvmArguments.filterExtractProps(targetOptions.mappers, prefix = "-")
if (inheritMemoryLimits && opts.maxMemory.isBlank()) {
val maxMemBytes = Runtime.getRuntime().maxMemory()
// rounding up
val maxMemMegabytes = maxMemBytes / (1024 * 1024) + if (maxMemBytes % (1024 * 1024) == 0L) 0 else 1
opts.maxMemory = "${maxMemMegabytes}m"
if (inheritMemoryLimits) {
if (opts.maxMemory.isBlank()) {
val maxMemBytes = Runtime.getRuntime().maxMemory()
// rounding up
val maxMemMegabytes = maxMemBytes / (1024 * 1024) + if (maxMemBytes % (1024 * 1024) == 0L) 0 else 1
opts.maxMemory = "${maxMemMegabytes}m"
}
}
if (inheritOtherJvmOptions) {
@@ -365,7 +368,7 @@ private fun String.memToBytes(): Long? =
private val daemonJVMOptionsMemoryProps =
listOf(DaemonJVMOptions::maxMemory, DaemonJVMOptions::maxPermSize, DaemonJVMOptions::reservedCodeCacheSize)
listOf(DaemonJVMOptions::maxMemory, DaemonJVMOptions::maxPermSize, DaemonJVMOptions::maxMetaspaceSize, DaemonJVMOptions::reservedCodeCacheSize)
infix fun DaemonJVMOptions.memorywiseFitsInto(other: DaemonJVMOptions): Boolean =
daemonJVMOptionsMemoryProps

View File

@@ -8,11 +8,8 @@ package org.jetbrains.kotlin.daemon.experimental
import com.intellij.util.containers.StringInterner
import kotlinx.coroutines.runBlocking
import org.jetbrains.kotlin.daemon.EventManager
import org.jetbrains.kotlin.daemon.common.*
import org.jetbrains.kotlin.daemon.common.experimental.CompilerCallbackServicesFacadeClientSide
import org.jetbrains.kotlin.daemon.common.DummyProfiler
import org.jetbrains.kotlin.daemon.common.Profiler
import org.jetbrains.kotlin.daemon.common.withMeasure
import org.jetbrains.kotlin.daemon.common.withMeasureBlocking
import org.jetbrains.kotlin.incremental.components.LookupInfo
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.incremental.components.Position
@@ -20,7 +17,7 @@ import org.jetbrains.kotlin.incremental.components.ScopeKind
class RemoteLookupTrackerClient(
val facade: CompilerCallbackServicesFacadeClientSide,
val facade: CompilerCallbackServicesFacadeAsync,
eventManager: EventManager,
val profiler: Profiler = DummyProfiler()
) : LookupTracker {

View File

@@ -1017,6 +1017,11 @@ public class Fir2IrTextTestGenerated extends AbstractFir2IrTextTest {
runTest("compiler/testData/ir/irText/expressions/kt30020.kt");
}
@TestMetadata("kt30796.kt")
public void testKt30796() throws Exception {
runTest("compiler/testData/ir/irText/expressions/kt30796.kt");
}
@TestMetadata("lambdaInCAO.kt")
public void testLambdaInCAO() throws Exception {
runTest("compiler/testData/ir/irText/expressions/lambdaInCAO.kt");

View File

@@ -1159,6 +1159,34 @@ public class FirDiagnosticsSmokeTestGenerated extends AbstractFirDiagnosticsSmok
}
}
@TestMetadata("compiler/testData/diagnostics/tests/annotations/functionalTypes")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public static class FunctionalTypes extends AbstractFirDiagnosticsSmokeTest {
private void runTest(String testDataFilePath) throws Exception {
KotlinTestUtils.runTest(this::doTest, TargetBackend.ANY, testDataFilePath);
}
public void testAllFilesPresentInFunctionalTypes() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("compiler/testData/diagnostics/tests/annotations/functionalTypes"), Pattern.compile("^(.+)\\.kt$"), TargetBackend.ANY, true);
}
@TestMetadata("nonParenthesizedAnnotationsWithError.kt")
public void testNonParenthesizedAnnotationsWithError() throws Exception {
runTest("compiler/testData/diagnostics/tests/annotations/functionalTypes/nonParenthesizedAnnotationsWithError.kt");
}
@TestMetadata("nonParenthesizedAnnotationsWithoutError.kt")
public void testNonParenthesizedAnnotationsWithoutError() throws Exception {
runTest("compiler/testData/diagnostics/tests/annotations/functionalTypes/nonParenthesizedAnnotationsWithoutError.kt");
}
@TestMetadata("parenthesizedAnnotations.kt")
public void testParenthesizedAnnotations() throws Exception {
runTest("compiler/testData/diagnostics/tests/annotations/functionalTypes/parenthesizedAnnotations.kt");
}
}
@TestMetadata("compiler/testData/diagnostics/tests/annotations/options")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
@@ -1679,6 +1707,16 @@ public class FirDiagnosticsSmokeTestGenerated extends AbstractFirDiagnosticsSmok
runTest("compiler/testData/diagnostics/tests/callableReference/expectedTypeAsSubtypeOfFunctionType.kt");
}
@TestMetadata("functionReferenceWithDefaultValueAsOtherFunctionType.kt")
public void testFunctionReferenceWithDefaultValueAsOtherFunctionType() throws Exception {
runTest("compiler/testData/diagnostics/tests/callableReference/functionReferenceWithDefaultValueAsOtherFunctionType.kt");
}
@TestMetadata("functionReferenceWithDefaultValueAsOtherFunctionType_enabled.kt")
public void testFunctionReferenceWithDefaultValueAsOtherFunctionType_enabled() throws Exception {
runTest("compiler/testData/diagnostics/tests/callableReference/functionReferenceWithDefaultValueAsOtherFunctionType_enabled.kt");
}
@TestMetadata("kt15439_completeCall.kt")
public void testKt15439_completeCall() throws Exception {
runTest("compiler/testData/diagnostics/tests/callableReference/kt15439_completeCall.kt");
@@ -1694,6 +1732,11 @@ public class FirDiagnosticsSmokeTestGenerated extends AbstractFirDiagnosticsSmok
runTest("compiler/testData/diagnostics/tests/callableReference/kt31981.kt");
}
@TestMetadata("kt32256.kt")
public void testKt32256() throws Exception {
runTest("compiler/testData/diagnostics/tests/callableReference/kt32256.kt");
}
@TestMetadata("kt7430_wrongClassOnLHS.kt")
public void testKt7430_wrongClassOnLHS() throws Exception {
runTest("compiler/testData/diagnostics/tests/callableReference/kt7430_wrongClassOnLHS.kt");
@@ -1739,6 +1782,11 @@ public class FirDiagnosticsSmokeTestGenerated extends AbstractFirDiagnosticsSmok
runTest("compiler/testData/diagnostics/tests/callableReference/subtypeArgumentFromRHSForReference.kt");
}
@TestMetadata("suspendCallableReference.kt")
public void testSuspendCallableReference() throws Exception {
runTest("compiler/testData/diagnostics/tests/callableReference/suspendCallableReference.kt");
}
@TestMetadata("typealiases.kt")
public void testTypealiases() throws Exception {
runTest("compiler/testData/diagnostics/tests/callableReference/typealiases.kt");
@@ -9503,6 +9551,11 @@ public class FirDiagnosticsSmokeTestGenerated extends AbstractFirDiagnosticsSmok
runTest("compiler/testData/diagnostics/tests/inference/cannotCompleteResolveWithFunctionLiterals.kt");
}
@TestMetadata("capturedInProjectedFlexibleType.kt")
public void testCapturedInProjectedFlexibleType() throws Exception {
runTest("compiler/testData/diagnostics/tests/inference/capturedInProjectedFlexibleType.kt");
}
@TestMetadata("coerceFunctionLiteralToSuspend.kt")
public void testCoerceFunctionLiteralToSuspend() throws Exception {
runTest("compiler/testData/diagnostics/tests/inference/coerceFunctionLiteralToSuspend.kt");
@@ -9673,6 +9726,11 @@ public class FirDiagnosticsSmokeTestGenerated extends AbstractFirDiagnosticsSmok
runTest("compiler/testData/diagnostics/tests/inference/kt3184.kt");
}
@TestMetadata("kt32434.kt")
public void testKt32434() throws Exception {
runTest("compiler/testData/diagnostics/tests/inference/kt32434.kt");
}
@TestMetadata("kt6175.kt")
public void testKt6175() throws Exception {
runTest("compiler/testData/diagnostics/tests/inference/kt6175.kt");
@@ -10164,6 +10222,11 @@ public class FirDiagnosticsSmokeTestGenerated extends AbstractFirDiagnosticsSmok
runTest("compiler/testData/diagnostics/tests/inference/constraints/operationsOnIntegerValueTypes.kt");
}
@TestMetadata("recursiveJavaTypeWithStarProjection.kt")
public void testRecursiveJavaTypeWithStarProjection() throws Exception {
runTest("compiler/testData/diagnostics/tests/inference/constraints/recursiveJavaTypeWithStarProjection.kt");
}
@TestMetadata("returnLambdaFromLambda.kt")
public void testReturnLambdaFromLambda() throws Exception {
runTest("compiler/testData/diagnostics/tests/inference/constraints/returnLambdaFromLambda.kt");

View File

@@ -45,7 +45,10 @@ object JvmPlatforms {
)
object CompatJvmPlatform : TargetPlatform(setOf(UNSPECIFIED_SIMPLE_JVM_PLATFORM)),
// Needed for backward compatibility, because old code uses INSTANCEOF checks instead of calling extensions
org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform {}
org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform {
override val platformName: String
get() = "JVM"
}
}
class JdkPlatform(val targetVersion: JvmTarget) : JvmPlatform() {

View File

@@ -16,10 +16,6 @@ import org.jetbrains.kotlin.resolve.TargetPlatform
level = DeprecationLevel.ERROR
)
interface JvmPlatform : TargetPlatform {
@JvmDefault
override val platformName: String
get() = "JVM"
companion object {
@JvmField
val INSTANCE: JvmPlatform = JvmPlatforms.CompatJvmPlatform

View File

@@ -67,10 +67,11 @@ open class AnalysisResult protected constructor(
val exception: Throwable
) : AnalysisResult(bindingContext, ErrorUtils.getErrorModule())
class RetryWithAdditionalJavaRoots(
class RetryWithAdditionalRoots(
bindingContext: BindingContext,
moduleDescriptor: ModuleDescriptor,
val additionalJavaRoots: List<File>,
val additionalKotlinRoots: List<File>,
val addToEnvironment: Boolean = true
) : AnalysisResult(bindingContext, moduleDescriptor)

View File

@@ -8,10 +8,12 @@ package org.jetbrains.kotlin.analyzer
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ModificationTracker
import org.jetbrains.kotlin.psi.KtFile
open class KotlinModificationTrackerService {
open val modificationTracker: ModificationTracker = ModificationTracker.NEVER_CHANGED
open val outOfBlockModificationTracker: ModificationTracker = ModificationTracker.NEVER_CHANGED
open fun fileModificationTracker(file: KtFile): ModificationTracker = ModificationTracker.NEVER_CHANGED
companion object {
private val NEVER_CHANGE_TRACKER_SERVICE = KotlinModificationTrackerService()

View File

@@ -268,6 +268,8 @@ public interface Errors {
DiagnosticFactory1<PsiElement, FqName> EXPERIMENTAL_UNSIGNED_LITERALS = DiagnosticFactory1.create(WARNING);
DiagnosticFactory1<PsiElement, FqName> EXPERIMENTAL_UNSIGNED_LITERALS_ERROR = DiagnosticFactory1.create(ERROR);
DiagnosticFactory0<PsiElement> NON_PARENTHESIZED_ANNOTATIONS_ON_FUNCTIONAL_TYPES = DiagnosticFactory0.create(ERROR);
// Const
DiagnosticFactory0<PsiElement> CONST_VAL_NOT_TOP_LEVEL_OR_OBJECT = DiagnosticFactory0.create(ERROR);
DiagnosticFactory0<PsiElement> CONST_VAL_WITH_GETTER = DiagnosticFactory0.create(ERROR);

View File

@@ -159,6 +159,8 @@ public class DefaultErrorMessages {
MAP.put(EXPERIMENTAL_UNSIGNED_LITERALS, "Unsigned literals are experimental and their usages should be marked with ''@{0}'' or ''@UseExperimental({0}::class)''", TO_STRING);
MAP.put(EXPERIMENTAL_UNSIGNED_LITERALS_ERROR, "Unsigned literals are experimental and their usages must be marked with ''@{0}'' or ''@UseExperimental({0}::class)''", TO_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(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");
MAP.put(REDUNDANT_MODIFIER_IN_GETTER, "Visibility modifiers are redundant in getter");

View File

@@ -34,6 +34,9 @@ import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.codeFragmentUtil.suppressDiagnosticsInDebugMode
import org.jetbrains.kotlin.psi.debugText.getDebugText
import org.jetbrains.kotlin.psi.psiUtil.checkReservedYield
import org.jetbrains.kotlin.psi.psiUtil.getNextSiblingIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.psi.psiUtil.hasSuspendModifier
import org.jetbrains.kotlin.psi.stubs.elements.KtStubElementTypes
import org.jetbrains.kotlin.resolve.PossiblyBareType.bare
import org.jetbrains.kotlin.resolve.PossiblyBareType.type
@@ -69,6 +72,9 @@ class TypeResolver(
private val platformToKotlinClassMap: PlatformToKotlinClassMap,
private val languageVersionSettings: LanguageVersionSettings
) {
private val isNonParenthesizedAnnotationsOnFunctionalTypesEnabled =
languageVersionSettings.getFeatureSupport(LanguageFeature.NonParenthesizedAnnotationsOnFunctionalTypes) == LanguageFeature.State.ENABLED
open class TypeTransformerForTests {
open fun transformType(kotlinType: KotlinType): KotlinType? = null
}
@@ -129,12 +135,54 @@ class TypeResolver(
internal fun KtElementImplStub<*>.getAllModifierLists(): Array<out KtDeclarationModifierList> =
getStubOrPsiChildren(KtStubElementTypes.MODIFIER_LIST, KtStubElementTypes.MODIFIER_LIST.arrayFactory)
// TODO: remove this method and its usages in 1.4
private fun checkNonParenthesizedAnnotationsOnFunctionalType(
typeElement: KtFunctionType,
annotationEntries: List<KtAnnotationEntry>,
trace: BindingTrace
) {
val lastAnnotationEntry = annotationEntries.lastOrNull()
val isAnnotationsGroupedUsingBrackets =
lastAnnotationEntry?.getNextSiblingIgnoringWhitespaceAndComments()?.node?.elementType == KtTokens.RBRACKET
val hasAnnotationParentheses = lastAnnotationEntry?.valueArgumentList != null
val isFunctionalTypeStartingWithParentheses = typeElement.firstChild is KtParameterList
val hasSuspendModifierBeforeParentheses =
typeElement.getPrevSiblingIgnoringWhitespaceAndComments().run { this is KtDeclarationModifierList && hasSuspendModifier() }
if (lastAnnotationEntry != null &&
isFunctionalTypeStartingWithParentheses &&
!hasAnnotationParentheses &&
!isAnnotationsGroupedUsingBrackets &&
!hasSuspendModifierBeforeParentheses
) {
trace.report(Errors.NON_PARENTHESIZED_ANNOTATIONS_ON_FUNCTIONAL_TYPES.on(lastAnnotationEntry))
}
}
private fun resolveTypeAnnotations(c: TypeResolutionContext, modifierListsOwner: KtElementImplStub<*>): Annotations {
val modifierLists = modifierListsOwner.getAllModifierLists()
var result = Annotations.EMPTY
var isSplitModifierList = false
if (!isNonParenthesizedAnnotationsOnFunctionalTypesEnabled) {
val targetType = when (modifierListsOwner) {
is KtNullableType -> modifierListsOwner.innerType
is KtTypeReference -> modifierListsOwner.typeElement
else -> null
}
val annotationEntries = when (modifierListsOwner) {
is KtNullableType -> modifierListsOwner.modifierList?.annotationEntries
is KtTypeReference -> modifierListsOwner.annotationEntries
else -> null
}
// `targetType.stub == null` means that we don't apply this check for files that are built with stubs (that aren't opened in IDE and not in compile time)
if (targetType is KtFunctionType && targetType.stub == null && annotationEntries != null) {
checkNonParenthesizedAnnotationsOnFunctionalType(targetType, annotationEntries, c.trace)
}
}
for (modifierList in modifierLists) {
if (isSplitModifierList) {
c.trace.report(MODIFIER_LIST_NOT_ALLOWED.on(modifierList))

View File

@@ -5,10 +5,10 @@
package org.jetbrains.kotlin.resolve.calls
import com.intellij.psi.util.PsiUtil
import org.jetbrains.kotlin.builtins.UnsignedTypes
import org.jetbrains.kotlin.builtins.functions.FunctionInvokeDescriptor
import org.jetbrains.kotlin.builtins.isExtensionFunctionType
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.Errors.*
import org.jetbrains.kotlin.diagnostics.Errors.BadNamedArgumentsTarget.INVOKE_ON_FUNCTION_TYPE
@@ -147,6 +147,21 @@ class DiagnosticReporterByTrackingStrategy(
}
}
}
CallableReferencesDefaultArgumentUsed::class.java -> {
require(diagnostic is CallableReferencesDefaultArgumentUsed) {
"diagnostic ($diagnostic) should have type CallableReferencesDefaultArgumentUsed"
}
diagnostic.argument.psiExpression?.let {
trace.report(
UNSUPPORTED_FEATURE.on(
it, LanguageFeature.FunctionReferenceWithDefaultValueAsOtherType to context.languageVersionSettings
)
)
}
}
}
}

View File

@@ -27,6 +27,7 @@ import org.jetbrains.kotlin.resolve.calls.tower.*
import org.jetbrains.kotlin.resolve.calls.util.FakeCallableDescriptorForObject
import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver
import org.jetbrains.kotlin.types.StubType
import org.jetbrains.kotlin.types.TypeApproximator
import org.jetbrains.kotlin.types.TypeConstructor
import org.jetbrains.kotlin.types.UnwrappedType
import org.jetbrains.kotlin.types.expressions.DoubleColonExpressionResolver
@@ -47,7 +48,8 @@ class CoroutineInferenceSession(
private val argumentTypeResolver: ArgumentTypeResolver,
private val doubleColonExpressionResolver: DoubleColonExpressionResolver,
private val deprecationResolver: DeprecationResolver,
private val moduleDescriptor: ModuleDescriptor
private val moduleDescriptor: ModuleDescriptor,
private val typeApproximator: TypeApproximator
) : ManyCandidatesResolver<CallableDescriptor>(
psiCallResolver, postponedArgumentsAnalyzer, kotlinConstraintSystemCompleter, callComponents, builtIns
) {
@@ -220,7 +222,7 @@ class CoroutineInferenceSession(
return ResolvedAtomCompleter(
resultSubstitutor, context, kotlinToResolvedCallTransformer,
expressionTypingServices, argumentTypeResolver, doubleColonExpressionResolver, builtIns,
deprecationResolver, moduleDescriptor, context.dataFlowValueFactory
deprecationResolver, moduleDescriptor, context.dataFlowValueFactory, typeApproximator
)
}
}

View File

@@ -146,7 +146,7 @@ class KotlinResolutionCallbacksImpl(
psiCallResolver, postponedArgumentsAnalyzer, kotlinConstraintSystemCompleter,
callComponents, builtIns, topLevelCallContext, stubsForPostponedVariables, trace,
kotlinToResolvedCallTransformer, expressionTypingServices, argumentTypeResolver,
doubleColonExpressionResolver, deprecationResolver, moduleDescriptor
doubleColonExpressionResolver, deprecationResolver, moduleDescriptor, typeApproximator
)
} else {
null

View File

@@ -38,7 +38,6 @@ import org.jetbrains.kotlin.resolve.calls.tasks.ExplicitReceiverKind
import org.jetbrains.kotlin.resolve.calls.tasks.TracingStrategy
import org.jetbrains.kotlin.resolve.constants.CompileTimeConstant
import org.jetbrains.kotlin.resolve.constants.IntegerLiteralTypeConstructor
import org.jetbrains.kotlin.resolve.constants.IntegerValueTypeConstant
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver
import org.jetbrains.kotlin.resolve.scopes.receivers.CastImplicitClassReceiver
@@ -69,7 +68,8 @@ class KotlinToResolvedCallTransformer(
private val moduleDescriptor: ModuleDescriptor,
private val dataFlowValueFactory: DataFlowValueFactory,
private val builtIns: KotlinBuiltIns,
private val typeSystemContext: TypeSystemInferenceExtensionContextDelegate
private val typeSystemContext: TypeSystemInferenceExtensionContextDelegate,
private val typeApproximator: TypeApproximator
) {
companion object {
private val REPORT_MISSING_NEW_INFERENCE_DIAGNOSTIC
@@ -126,7 +126,8 @@ class KotlinToResolvedCallTransformer(
val ktPrimitiveCompleter = ResolvedAtomCompleter(
resultSubstitutor, context, this, expressionTypingServices, argumentTypeResolver,
doubleColonExpressionResolver, builtIns, deprecationResolver, moduleDescriptor, dataFlowValueFactory
doubleColonExpressionResolver, builtIns, deprecationResolver, moduleDescriptor, dataFlowValueFactory,
typeApproximator
)
if (!ErrorUtils.isError(candidate.candidateDescriptor)) {
@@ -207,7 +208,7 @@ class KotlinToResolvedCallTransformer(
return storedResolvedCall
}
}
return NewResolvedCallImpl(completedSimpleAtom, resultSubstitutor, diagnostics)
return NewResolvedCallImpl(completedSimpleAtom, resultSubstitutor, diagnostics, typeApproximator)
}
fun runCallCheckers(resolvedCall: ResolvedCall<*>, callCheckerContext: CallCheckerContext) {
@@ -606,7 +607,8 @@ sealed class NewAbstractResolvedCall<D : CallableDescriptor>() : ResolvedCall<D>
class NewResolvedCallImpl<D : CallableDescriptor>(
val resolvedCallAtom: ResolvedCallAtom,
substitutor: NewTypeSubstitutor?,
private var diagnostics: Collection<KotlinCallDiagnostic>
private var diagnostics: Collection<KotlinCallDiagnostic>,
private val typeApproximator: TypeApproximator
) : NewAbstractResolvedCall<D>() {
var isCompleted = false
private set
@@ -699,7 +701,7 @@ class NewResolvedCallImpl<D : CallableDescriptor>(
// this code is very suspicious. Now it is very useful for BE, because they cannot do nothing with captured types,
// but it seems like temporary solution.
candidateDescriptor.substitute(resolvedCallAtom.substitutor).substituteAndApproximateCapturedTypes(
substitutor ?: FreshVariableNewTypeSubstitutor.Empty
substitutor ?: FreshVariableNewTypeSubstitutor.Empty, typeApproximator
)
else ->
candidateDescriptor
@@ -708,7 +710,7 @@ class NewResolvedCallImpl<D : CallableDescriptor>(
typeArguments = resolvedCallAtom.substitutor.freshVariables.map {
val substituted = (substitutor ?: FreshVariableNewTypeSubstitutor.Empty).safeSubstitute(it.defaultType)
TypeApproximator(substituted.constructor.builtIns)
typeApproximator
.approximateToSuperType(substituted, TypeApproximatorConfiguration.IntegerLiteralsTypesApproximation)
?: substituted
}

View File

@@ -57,6 +57,7 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.*
import org.jetbrains.kotlin.resolve.scopes.utils.canBeResolvedWithoutDeprecation
import org.jetbrains.kotlin.types.DeferredType
import org.jetbrains.kotlin.types.ErrorUtils
import org.jetbrains.kotlin.types.TypeApproximator
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.types.isDynamic
import org.jetbrains.kotlin.util.OperatorNameConventions
@@ -72,7 +73,8 @@ class NewResolutionOldInference(
private val syntheticScopes: SyntheticScopes,
private val languageVersionSettings: LanguageVersionSettings,
private val coroutineInferenceSupport: CoroutineInferenceSupport,
private val deprecationResolver: DeprecationResolver
private val deprecationResolver: DeprecationResolver,
private val typeApproximator: TypeApproximator
) {
sealed class ResolutionKind {
abstract internal fun createTowerProcessor(
@@ -170,7 +172,9 @@ class NewResolutionOldInference(
}
val dynamicScope = dynamicCallableDescriptors.createDynamicDescriptorScope(context.call, context.scope.ownerDescriptor)
val scopeTower = ImplicitScopeTowerImpl(context, dynamicScope, syntheticScopes, context.call.createLookupLocation())
val scopeTower = ImplicitScopeTowerImpl(
context, dynamicScope, syntheticScopes, context.call.createLookupLocation(), typeApproximator
)
val shouldUseOperatorRem = languageVersionSettings.supportsFeature(LanguageFeature.OperatorRem)
val isBinaryRemOperator = isBinaryRemOperator(context.call)
@@ -353,7 +357,8 @@ class NewResolutionOldInference(
val resolutionContext: ResolutionContext<*>,
override val dynamicScope: MemberScope,
override val syntheticScopes: SyntheticScopes,
override val location: LookupLocation
override val location: LookupLocation,
override val typeApproximator: TypeApproximator
) : ImplicitScopeTower {
private val cache = HashMap<ReceiverValue, ReceiverValueWithSmartCastInfo>()

View File

@@ -106,7 +106,10 @@ class PSICallResolver(
return OverloadResolutionResultsImpl.nameNotFound()
}
return convertToOverloadResolutionResults(context, result, tracingStrategy)
val overloadResolutionResults = convertToOverloadResolutionResults<D>(context, result, tracingStrategy)
return overloadResolutionResults.also {
clearCacheForApproximationResults()
}
}
// actually, `D` is at least FunctionDescriptor, but right now because of CallResolver it isn't possible change upper bound for `D`
@@ -133,7 +136,16 @@ class PSICallResolver(
val result = kotlinCallResolver.resolveGivenCandidates(
scopeTower, resolutionCallbacks, kotlinCall, calculateExpectedType(context), givenCandidates, context.collectAllCandidates
)
return convertToOverloadResolutionResults(context, result, tracingStrategy)
val overloadResolutionResults = convertToOverloadResolutionResults<D>(context, result, tracingStrategy)
return overloadResolutionResults.also {
clearCacheForApproximationResults()
}
}
private fun clearCacheForApproximationResults() {
// Mostly, we approximate captured or some other internal types that don't live longer than resolve for a call,
// so it's quite useless to preserve cache for longer time
typeApproximator.clearCache()
}
private fun resolveToDeprecatedMod(
@@ -375,6 +387,7 @@ class PSICallResolver(
override val isDebuggerContext: Boolean get() = context.isDebuggerContext
override val isNewInferenceEnabled: Boolean get() = context.languageVersionSettings.supportsFeature(LanguageFeature.NewInference)
override val lexicalScope: LexicalScope get() = context.scope
override val typeApproximator: TypeApproximator get() = this@PSICallResolver.typeApproximator
private val cache = HashMap<ReceiverParameterDescriptor, ReceiverValueWithSmartCastInfo>()
override fun getImplicitReceiver(scope: LexicalScope): ReceiverValueWithSmartCastInfo? {

View File

@@ -50,7 +50,8 @@ class ResolvedAtomCompleter(
private val builtIns: KotlinBuiltIns,
private val deprecationResolver: DeprecationResolver,
private val moduleDescriptor: ModuleDescriptor,
private val dataFlowValueFactory: DataFlowValueFactory
private val dataFlowValueFactory: DataFlowValueFactory,
private val typeApproximator: TypeApproximator
) {
private val topLevelCallCheckerContext = CallCheckerContext(topLevelCallContext, deprecationResolver, moduleDescriptor)
private val topLevelTrace = topLevelCallCheckerContext.trace
@@ -142,7 +143,7 @@ class ResolvedAtomCompleter(
}
val approximatedReturnType =
TypeApproximator(builtIns).approximateDeclarationType(
typeApproximator.approximateDeclarationType(
returnType,
local = true,
languageVersionSettings = topLevelCallContext.languageVersionSettings

View File

@@ -52,6 +52,7 @@ class LateinitLowering(val context: CommonBackendContext) : FileLoweringPass {
name = oldField.name
}.also { newField ->
newField.parent = oldField.parent
newField.correspondingPropertySymbol = declaration.symbol
declaration.backingField = newField
}

View File

@@ -29,6 +29,7 @@ private val kotlinCoroutinesPackageFqn = kotlinPackageFqn.child(Name.identifier(
fun IrType.isFunction(): Boolean = this.isClassWithNamePrefix("Function", kotlinPackageFqn)
fun IrType.isKFunction(): Boolean = this.isClassWithNamePrefix("KFunction", kotlinReflectionPackageFqn)
fun IrType.isSuspendFunction(): Boolean = this.isClassWithNamePrefix("SuspendFunction", kotlinCoroutinesPackageFqn)
fun IrType.isKSuspendFunction(): Boolean = this.isClassWithNamePrefix("KSuspendFunction", kotlinReflectionPackageFqn)
private fun IrType.isClassWithNamePrefix(prefix: String, packageFqName: FqName): Boolean {
val classifier = classifierOrNull ?: return false

View File

@@ -17,6 +17,7 @@
package org.jetbrains.kotlin.psi2ir.generators
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.builders.*
@@ -35,11 +36,14 @@ import org.jetbrains.kotlin.psi2ir.containsNull
import org.jetbrains.kotlin.psi2ir.findSingleFunction
import org.jetbrains.kotlin.psi2ir.intermediate.safeCallOnDispatchReceiver
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.NewCommonSuperTypeCalculator
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.checkers.PrimitiveNumericComparisonInfo
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.checker.intersectTypes
import org.jetbrains.kotlin.types.isDynamic
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.isPrimitiveNumberType
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
import org.jetbrains.kotlin.types.typeUtil.makeNullable
@@ -190,9 +194,28 @@ class OperatorExpressionGenerator(statementGenerator: StatementGenerator) : Stat
}
}
private fun getResultTypeForElvis(expression: KtExpression): KotlinType {
val binaryExpression = KtPsiUtil.safeDeparenthesize(expression)
val expressionType = context.bindingContext.getType(binaryExpression)!!
if (binaryExpression !is KtBinaryExpression || binaryExpression.operationToken != KtTokens.ELVIS) return expressionType
val inferredType = getResolvedCall(binaryExpression)!!.resultingDescriptor.returnType!!
// OI has a rather complex bug with constraint system for special call for '?:' that breaks IR-based back-ends.
// In NI this bug is fixed.
if (context.languageVersionSettings.supportsFeature(LanguageFeature.NewInference)) return inferredType
if (!inferredType.isError) return inferredType
// Infer type for elvis manually. Take into account possibly nested elvises.
val rightType = getResultTypeForElvis(binaryExpression.right!!).unwrap()
val leftType = getResultTypeForElvis(binaryExpression.left!!).unwrap()
val leftNNType = intersectTypes(listOf(leftType, context.builtIns.anyType))
return NewCommonSuperTypeCalculator.commonSuperType(listOf(rightType, leftNNType))
}
private fun generateElvis(expression: KtBinaryExpression): IrExpression {
val specialCallForElvis = getResolvedCall(expression)!!
val resultType = specialCallForElvis.resultingDescriptor.returnType!!.toIrType()
val resultType = getResultTypeForElvis(expression).toIrType()
val irArgument0 = expression.left!!.genExpr()
val irArgument1 = expression.right!!.genExpr()

View File

@@ -91,20 +91,6 @@ private fun createJavaFileStub(project: Project, packageFqName: FqName, files: C
override fun isPhysical() = false
override fun appendMirrorText(indentLevel: Int, buffer: StringBuilder) {
if (files.size == 1) {
LOG.error("Mirror text should never be calculated for light classes generated from a single file")
}
super.appendMirrorText(indentLevel, buffer)
}
override fun getMirror(): PsiElement {
if (files.size == 1) {
LOG.error("Mirror element should never be calculated for light classes generated from a single file")
}
return super.getMirror()
}
override fun getText(): String {
return files.singleOrNull()?.text ?: super.getText()
}

View File

@@ -0,0 +1,239 @@
/*
* 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.asJava.classes;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.SimpleModificationTracker;
import com.intellij.psi.*;
import com.intellij.psi.augment.PsiAugmentProvider;
import com.intellij.psi.impl.PsiClassImplUtil;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.impl.light.LightMethod;
import com.intellij.psi.impl.source.PsiExtensibleClass;
import com.intellij.psi.scope.ElementClassHint;
import com.intellij.psi.scope.NameHint;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.util.ArrayUtil;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static com.intellij.util.ObjectUtils.notNull;
// Copy of ClassInnerStuffCache with custom list of caching dependencies
@SuppressWarnings({"WeakerAccess", "Java8MapApi"})
public class KotlinClassInnerStuffCache {
private final PsiExtensibleClass myClass;
private final SimpleModificationTracker myTracker = new SimpleModificationTracker();
private final List<Object> dependencies;
public KotlinClassInnerStuffCache(@NotNull PsiExtensibleClass aClass, @NotNull List<Object> externalDependencies) {
myClass = aClass;
dependencies = new SmartList<>();
dependencies.addAll(externalDependencies);
dependencies.add(myTracker);
}
@NotNull
public PsiMethod[] getConstructors() {
return copy(CachedValuesManager.getCachedValue(myClass, () -> makeResult(PsiImplUtil.getConstructors(myClass))));
}
@NotNull
public PsiField[] getFields() {
return copy(CachedValuesManager.getCachedValue(myClass, () -> makeResult(getAllFields())));
}
@NotNull
public PsiMethod[] getMethods() {
return copy(CachedValuesManager.getCachedValue(myClass, () -> makeResult(getAllMethods())));
}
@NotNull
public PsiClass[] getInnerClasses() {
return copy(CachedValuesManager.getCachedValue(myClass, () -> makeResult(getAllInnerClasses())));
}
@Nullable
public PsiField findFieldByName(String name, boolean checkBases) {
if (checkBases) {
return PsiClassImplUtil.findFieldByName(myClass, name, true);
}
else {
return CachedValuesManager.getCachedValue(myClass, () -> makeResult(getFieldsMap())).get(name);
}
}
@NotNull
public PsiMethod[] findMethodsByName(String name, boolean checkBases) {
if (checkBases) {
return PsiClassImplUtil.findMethodsByName(myClass, name, true);
}
else {
return copy(notNull(CachedValuesManager.getCachedValue(myClass, () -> makeResult(getMethodsMap())).get(name), PsiMethod.EMPTY_ARRAY));
}
}
@Nullable
public PsiClass findInnerClassByName(String name, boolean checkBases) {
if (checkBases) {
return PsiClassImplUtil.findInnerByName(myClass, name, true);
}
else {
return CachedValuesManager.getCachedValue(myClass, () -> makeResult(getInnerClassesMap())).get(name);
}
}
@Nullable
public PsiMethod getValuesMethod() {
return myClass.isEnum() && myClass.getName() != null ? CachedValuesManager.getCachedValue(myClass, () -> makeResult(makeValuesMethod())) : null;
}
@Nullable
public PsiMethod getValueOfMethod() {
return myClass.isEnum() && myClass.getName() != null ? CachedValuesManager.getCachedValue(myClass, () -> makeResult(makeValueOfMethod())) : null;
}
private static <T> T[] copy(T[] value) {
return value.length == 0 ? value : value.clone();
}
// This method is modified
private <T> CachedValueProvider.Result<T> makeResult(T value) {
return CachedValueProvider.Result.create(value, dependencies);
}
@NotNull
private PsiField[] getAllFields() {
List<PsiField> own = myClass.getOwnFields();
List<PsiField> ext = PsiAugmentProvider.collectAugments(myClass, PsiField.class);
return ArrayUtil.mergeCollections(own, ext, PsiField.ARRAY_FACTORY);
}
@NotNull
private PsiMethod[] getAllMethods() {
List<PsiMethod> own = myClass.getOwnMethods();
List<PsiMethod> ext = PsiAugmentProvider.collectAugments(myClass, PsiMethod.class);
return ArrayUtil.mergeCollections(own, ext, PsiMethod.ARRAY_FACTORY);
}
@NotNull
private PsiClass[] getAllInnerClasses() {
List<PsiClass> own = myClass.getOwnInnerClasses();
List<PsiClass> ext = PsiAugmentProvider.collectAugments(myClass, PsiClass.class);
return ArrayUtil.mergeCollections(own, ext, PsiClass.ARRAY_FACTORY);
}
@NotNull
private Map<String, PsiField> getFieldsMap() {
PsiField[] fields = getFields();
if (fields.length == 0) return Collections.emptyMap();
Map<String, PsiField> cachedFields = new THashMap<>();
for (PsiField field : fields) {
String name = field.getName();
if (!cachedFields.containsKey(name)) {
cachedFields.put(name, field);
}
}
return cachedFields;
}
@NotNull
private Map<String, PsiMethod[]> getMethodsMap() {
PsiMethod[] methods = getMethods();
if (methods.length == 0) return Collections.emptyMap();
Map<String, List<PsiMethod>> collectedMethods = ContainerUtil.newHashMap();
for (PsiMethod method : methods) {
List<PsiMethod> list = collectedMethods.get(method.getName());
if (list == null) {
collectedMethods.put(method.getName(), list = ContainerUtil.newSmartList());
}
list.add(method);
}
Map<String, PsiMethod[]> cachedMethods = ContainerUtil.newTroveMap();
for (Map.Entry<String, List<PsiMethod>> entry : collectedMethods.entrySet()) {
List<PsiMethod> list = entry.getValue();
cachedMethods.put(entry.getKey(), list.toArray(PsiMethod.EMPTY_ARRAY));
}
return cachedMethods;
}
@NotNull
private Map<String, PsiClass> getInnerClassesMap() {
PsiClass[] classes = getInnerClasses();
if (classes.length == 0) return Collections.emptyMap();
Map<String, PsiClass> cachedInners = new THashMap<>();
for (PsiClass psiClass : classes) {
String name = psiClass.getName();
if (name == null) {
Logger.getInstance(KotlinClassInnerStuffCache.class).error(psiClass);
}
else if (!(psiClass instanceof ExternallyDefinedPsiElement) || !cachedInners.containsKey(name)) {
cachedInners.put(name, psiClass);
}
}
return cachedInners;
}
private PsiMethod makeValuesMethod() {
return getSyntheticMethod("public static " + myClass.getName() + "[] values() { }");
}
private PsiMethod makeValueOfMethod() {
return getSyntheticMethod("public static " + myClass.getName() + " valueOf(java.lang.String name) throws java.lang.IllegalArgumentException { }");
}
private PsiMethod getSyntheticMethod(String text) {
PsiElementFactory factory = JavaPsiFacade.getElementFactory(myClass.getProject());
PsiMethod method = factory.createMethodFromText(text, myClass);
return new LightMethod(myClass.getManager(), method, myClass) {
@Override
public int getTextOffset() {
return myClass.getTextOffset();
}
};
}
public void dropCaches() {
myTracker.incModificationCount();
}
private static final String VALUES_METHOD = "values";
private static final String VALUE_OF_METHOD = "valueOf";
// Copy of PsiClassImplUtil.processDeclarationsInEnum for own cache class
public static boolean processDeclarationsInEnum(@NotNull PsiScopeProcessor processor,
@NotNull ResolveState state,
@NotNull KotlinClassInnerStuffCache innerStuffCache) {
ElementClassHint classHint = processor.getHint(ElementClassHint.KEY);
if (classHint == null || classHint.shouldProcess(ElementClassHint.DeclarationKind.METHOD)) {
NameHint nameHint = processor.getHint(NameHint.KEY);
if (nameHint == null || VALUES_METHOD.equals(nameHint.getName(state))) {
PsiMethod method = innerStuffCache.getValuesMethod();
if (method != null && !processor.execute(method, ResolveState.initial())) return false;
}
if (nameHint == null || VALUE_OF_METHOD.equals(nameHint.getName(state))) {
PsiMethod method = innerStuffCache.getValueOfMethod();
if (method != null && !processor.execute(method, ResolveState.initial())) return false;
}
}
return true;
}
}

View File

@@ -20,16 +20,18 @@ import com.intellij.navigation.ItemPresentationProviders
import com.intellij.psi.*
import com.intellij.psi.impl.PsiClassImplUtil
import com.intellij.psi.impl.light.AbstractLightClass
import com.intellij.psi.impl.source.ClassInnerStuffCache
import com.intellij.psi.impl.source.PsiExtensibleClass
import com.intellij.psi.scope.PsiScopeProcessor
import org.jetbrains.kotlin.analyzer.KotlinModificationTrackerService
import org.jetbrains.kotlin.asJava.classes.KotlinClassInnerStuffCache.processDeclarationsInEnum
import org.jetbrains.kotlin.asJava.elements.KtLightFieldImpl
import org.jetbrains.kotlin.asJava.elements.KtLightMethodImpl
import org.jetbrains.kotlin.idea.KotlinLanguage
abstract class KtLightClassBase protected constructor(manager: PsiManager)
: AbstractLightClass(manager, KotlinLanguage.INSTANCE), KtLightClass, PsiExtensibleClass {
private val myInnersCache = ClassInnerStuffCache(this)
protected open val myInnersCache = KotlinClassInnerStuffCache(
this, listOf(KotlinModificationTrackerService.getInstance(manager.project).outOfBlockModificationTracker))
override fun getDelegate() = clsDelegate
@@ -61,7 +63,7 @@ abstract class KtLightClassBase protected constructor(manager: PsiManager)
processor: PsiScopeProcessor, state: ResolveState, lastParent: PsiElement?, place: PsiElement
): Boolean {
if (isEnum) {
if (!PsiClassImplUtil.processDeclarationsInEnum(processor, state, myInnersCache)) return false
if (!processDeclarationsInEnum(processor, state, myInnersCache)) return false
}
return super.processDeclarations(processor, state, lastParent, place)

View File

@@ -19,7 +19,7 @@ package org.jetbrains.kotlin.asJava.classes
import org.jetbrains.kotlin.psi.KtClassOrObject
// light class for top level or (inner/nested of top level) source declarations
open class KtLightClassImpl(
open class KtLightClassImpl @JvmOverloads constructor(
classOrObject: KtClassOrObject,
forceUsingOldLightClasses: Boolean = false
) : KtLightClassForSourceDeclaration(classOrObject, forceUsingOldLightClasses) {

View File

@@ -9,10 +9,7 @@ import com.intellij.psi.*
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.SearchScope
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.asJava.elements.KtLightAbstractAnnotation
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.asJava.elements.KtLightSimpleModifierList
import org.jetbrains.kotlin.asJava.elements.LightParameter
import org.jetbrains.kotlin.asJava.elements.*
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.isSuspendFunctionType
import org.jetbrains.kotlin.codegen.coroutines.SUSPEND_FUNCTION_COMPLETION_PARAMETER_NAME
@@ -26,11 +23,12 @@ internal class KtUltraLightSuspendContinuationParameter(
private val support: KtUltraLightSupport,
method: KtLightMethod
) : LightParameter(SUSPEND_FUNCTION_COMPLETION_PARAMETER_NAME, PsiType.NULL, method, method.language),
KtUltraLightElementWithNullabilityAnnotation<KtDeclaration, PsiParameter> {
KtLightParameter,
KtUltraLightElementWithNullabilityAnnotation<KtParameter, PsiParameter> {
override val kotlinTypeForNullabilityAnnotation: KotlinType? get() = ktType
override val psiTypeForNullabilityAnnotation: PsiType? get() = psiType
override val kotlinOrigin: KtDeclaration? = null
override val kotlinOrigin: KtParameter? = null
override val clsDelegate: PsiParameter
get() = throw IllegalStateException("Cls delegate shouldn't be loaded for ultra-light PSI!")
@@ -68,7 +66,7 @@ internal class KtUltraLightSuspendContinuationParameter(
internal abstract class KtUltraLightParameter(
name: String,
override val kotlinOrigin: KtDeclaration?,
override val kotlinOrigin: KtParameter?,
protected val support: KtUltraLightSupport,
method: KtLightMethod
) : org.jetbrains.kotlin.asJava.elements.LightParameter(
@@ -76,7 +74,7 @@ internal abstract class KtUltraLightParameter(
PsiType.NULL,
method,
method.language
), KtUltraLightElementWithNullabilityAnnotation<KtDeclaration, PsiParameter> {
), KtUltraLightElementWithNullabilityAnnotation<KtParameter, PsiParameter>, KtLightParameter {
override fun isEquivalentTo(another: PsiElement?): Boolean = kotlinOrigin == another
@@ -137,7 +135,7 @@ internal abstract class KtUltraLightParameter(
internal abstract class KtAbstractUltraLightParameterForDeclaration(
name: String,
kotlinOrigin: KtDeclaration?,
kotlinOrigin: KtParameter?,
support: KtUltraLightSupport,
method: KtLightMethod,
protected val containingDeclaration: KtCallableDeclaration
@@ -192,12 +190,11 @@ internal class KtUltraLightReceiverParameter(
internal class KtUltraLightParameterForDescriptor(
private val descriptor: ParameterDescriptor,
kotlinOrigin: KtDeclaration?,
support: KtUltraLightSupport,
method: KtLightMethod
) : KtUltraLightParameter(
if (descriptor.name.isSpecial) "\$self" else descriptor.name.identifier,
kotlinOrigin, support, method
null, support, method
) {
override val kotlinType: KotlinType?
get() = descriptor.type

View File

@@ -223,11 +223,11 @@ fun KtUltraLightClass.createGeneratedMethodFromDescriptor(
val wrapper = KtUltraLightMethodForDescriptor(descriptor, lightMethod, lightMemberOrigin, support, this)
descriptor.extensionReceiverParameter?.let { receiver ->
lightMethod.addParameter(KtUltraLightParameterForDescriptor(receiver, kotlinOrigin, support, wrapper))
lightMethod.addParameter(KtUltraLightParameterForDescriptor(receiver, support, wrapper))
}
for (valueParameter in descriptor.valueParameters) {
lightMethod.addParameter(KtUltraLightParameterForDescriptor(valueParameter, kotlinOrigin, support, wrapper))
lightMethod.addParameter(KtUltraLightParameterForDescriptor(valueParameter, support, wrapper))
}
lightMethod.setMethodReturnType {

View File

@@ -22,6 +22,7 @@ import org.jetbrains.kotlin.asJava.builder.LightMemberOrigin
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKind
interface KtLightElement<out T : KtElement, out D : PsiElement> : PsiElement {
@@ -48,6 +49,10 @@ interface KtLightMember<out D : PsiMember> : PsiMember, KtLightDeclaration<KtDec
interface KtLightField : PsiField, KtLightMember<PsiField>, PsiVariableEx
interface KtLightParameter : PsiParameter, KtLightDeclaration<KtParameter, PsiParameter> {
val method: KtLightMethod
}
interface KtLightMethod : PsiAnnotationMethod, KtLightMember<PsiMethod> {
val isDelegated: Boolean
get() = lightMemberOrigin?.originKind == JvmDeclarationOriginKind.DELEGATION

View File

@@ -61,7 +61,7 @@ open class KtLightMethodImpl protected constructor(
protected open fun buildParametersForList(): List<PsiParameter> {
val clsParameters by lazyPub { clsDelegate.parameterList.parameters }
return (dummyDelegate?.parameterList?.parameters ?: clsParameters).mapIndexed { index, dummyParameter ->
KtLightParameter(
KtLightParameterImpl(
dummyParameter,
{ clsParameters.getOrNull(index) },
index,

View File

@@ -16,19 +16,16 @@ import com.intellij.util.IncorrectOperationException
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.asJava.classes.lazyPub
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPropertyAccessor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.isExtensionDeclaration
class KtLightParameter(
internal class KtLightParameterImpl(
private val dummyDelegate: PsiParameter,
private val clsDelegateProvider: () -> PsiParameter?,
private val index: Int,
method: KtLightMethod
) : LightParameter(dummyDelegate.name ?: "p$index", dummyDelegate.type, method, KotlinLanguage.INSTANCE),
KtLightDeclaration<KtParameter, PsiParameter> {
KtLightDeclaration<KtParameter, PsiParameter>, KtLightParameter {
private val lazyDelegate by lazyPub { clsDelegateProvider() ?: dummyDelegate }
@@ -104,7 +101,7 @@ class KtLightParameter(
val kotlinOrigin = kotlinOrigin
if (kotlinOrigin?.isEquivalentTo(another) == true) return@Computable true
if (another is KtLightParameter && kotlinOrigin != null) {
if (another is KtLightParameterImpl && kotlinOrigin != null) {
kotlinOrigin == another.kotlinOrigin && clsDelegate == another.clsDelegate
}
else {

View File

@@ -1,73 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.asJava.elements;
import com.intellij.lang.Language;
import com.intellij.psi.*;
import org.jetbrains.annotations.NotNull;
// Based on com.intellij.psi.impl.light.LightParameter
public class LightParameter extends LightVariableBuilder implements PsiParameter {
public static final LightParameter[] EMPTY_ARRAY = new LightParameter[0];
private final String myName;
private final KtLightMethod myDeclarationScope;
private final boolean myVarArgs;
public LightParameter(@NotNull String name, @NotNull PsiType type, @NotNull KtLightMethod declarationScope, Language language) {
this(name, type, declarationScope, language, type instanceof PsiEllipsisType);
}
public LightParameter(@NotNull String name, @NotNull PsiType type, @NotNull KtLightMethod declarationScope, Language language, boolean isVarArgs) {
super(declarationScope.getManager(), name, type, language);
myName = name;
myDeclarationScope = declarationScope;
myVarArgs = isVarArgs;
}
@NotNull
@Override
public KtLightMethod getDeclarationScope() {
return myDeclarationScope;
}
public KtLightMethod getMethod() {
return myDeclarationScope;
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof JavaElementVisitor) {
((JavaElementVisitor)visitor).visitParameter(this);
}
}
public String toString() {
return "Light Parameter";
}
@Override
public boolean isVarArgs() {
return myVarArgs;
}
@Override
@NotNull
public String getName() {
return myName;
}
}

View File

@@ -0,0 +1,49 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.asJava.elements
import com.intellij.lang.Language
import com.intellij.psi.*
// Based on com.intellij.psi.impl.light.LightParameter
open class LightParameter @JvmOverloads constructor(
private val myName: String,
type: PsiType,
val method: KtLightMethod,
language: Language?,
private val myVarArgs: Boolean = type is PsiEllipsisType
) : LightVariableBuilder(method.manager, myName, type, language),
PsiParameter {
override fun getDeclarationScope(): KtLightMethod = method
override fun accept(visitor: PsiElementVisitor) {
if (visitor is JavaElementVisitor) {
visitor.visitParameter(this)
}
}
override fun toString(): String = "Light Parameter"
override fun isVarArgs(): Boolean = myVarArgs
override fun getName(): String = myName
companion object {
val EMPTY_ARRAY = arrayOfNulls<LightParameter>(0)
}
}

View File

@@ -509,24 +509,36 @@ public class KotlinParsing extends AbstractKotlinParsing {
}
private boolean parseTypeModifierList() {
return doParseModifierList(null, TYPE_MODIFIER_KEYWORDS, DEFAULT, TokenSet.EMPTY);
return doParseModifierList(null, TYPE_MODIFIER_KEYWORDS, TYPE_CONTEXT, TokenSet.EMPTY);
}
private boolean parseTypeArgumentModifierList() {
return doParseModifierList(null, TYPE_ARGUMENT_MODIFIER_KEYWORDS, NO_ANNOTATIONS, TokenSet.create(COMMA, COLON, GT));
}
private boolean doParseModifierList(
private boolean doParseModifierListBody(
@Nullable Consumer<IElementType> tokenConsumer,
@NotNull TokenSet modifierKeywords,
@NotNull AnnotationParsingMode annotationParsingMode,
@NotNull TokenSet noModifiersBefore
) {
PsiBuilder.Marker list = mark();
boolean empty = true;
PsiBuilder.Marker beforeAnnotationMarker;
while (!eof()) {
if (at(AT) && annotationParsingMode.allowAnnotations) {
parseAnnotationOrList(annotationParsingMode);
beforeAnnotationMarker = mark();
boolean isAnnotationParsed = parseAnnotationOrList(annotationParsingMode);
if (!isAnnotationParsed && !annotationParsingMode.withSignificantWhitespaceBeforeArguments) {
beforeAnnotationMarker.rollbackTo();
// try parse again, but with significant whitespace
doParseModifierListBody(tokenConsumer, modifierKeywords, WITH_SIGNIFICANT_WHITESPACE_BEFORE_ARGUMENTS, noModifiersBefore);
empty = false;
break;
} else {
beforeAnnotationMarker.drop();
}
}
else if (tryParseModifier(tokenConsumer, noModifiersBefore, modifierKeywords)) {
// modifier advanced
@@ -536,6 +548,25 @@ public class KotlinParsing extends AbstractKotlinParsing {
}
empty = false;
}
return empty;
}
private boolean doParseModifierList(
@Nullable Consumer<IElementType> tokenConsumer,
@NotNull TokenSet modifierKeywords,
@NotNull AnnotationParsingMode annotationParsingMode,
@NotNull TokenSet noModifiersBefore
) {
PsiBuilder.Marker list = mark();
boolean empty = doParseModifierListBody(
tokenConsumer,
modifierKeywords,
annotationParsingMode,
noModifiersBefore
);
if (empty) {
list.drop();
}
@@ -796,8 +827,27 @@ public class KotlinParsing extends AbstractKotlinParsing {
parseTypeArgumentList();
if (at(LPAR)) {
boolean whitespaceAfterAnnotation = WHITE_SPACE_OR_COMMENT_BIT_SET.contains(myBuilder.rawLookup(-1));
boolean shouldBeParsedNextAsFunctionalType = at(LPAR) && whitespaceAfterAnnotation && mode.withSignificantWhitespaceBeforeArguments;
if (at(LPAR) && !shouldBeParsedNextAsFunctionalType) {
myExpressionParsing.parseValueArgumentList();
/*
* There are two problem cases relating to parsing of annotations on a functional type:
* - Annotation on a functional type was parsed correctly with the capture parentheses of the functional type,
* e.g. @Anno () -> Unit
* ^ Parse error only here: Type expected
* - It wasn't parsed, e.g. @Anno (x: kotlin.Any) -> Unit
* ^ Parse error: Expecting ')'
*
* In both cases, parser should rollback to start parsing of annotation and tries parse it with significant whitespace.
* A marker is set here which means that we must to rollback.
*/
if (mode.typeContext && (getLastToken() != RPAR || at(ARROW))) {
annotation.done(ANNOTATION_ENTRY);
return false;
}
}
annotation.done(ANNOTATION_ENTRY);
@@ -1995,7 +2045,7 @@ public class KotlinParsing extends AbstractKotlinParsing {
else if (at(LPAR)) {
PsiBuilder.Marker functionOrParenthesizedType = mark();
// This may be a function parameter list or just a prenthesized type
// This may be a function parameter list or just a parenthesized type
advance(); // LPAR
parseTypeRefContents(TokenSet.EMPTY).drop(); // parenthesized types, no reference element around it is needed
@@ -2423,20 +2473,28 @@ public class KotlinParsing extends AbstractKotlinParsing {
}
enum AnnotationParsingMode {
DEFAULT(false, true),
FILE_ANNOTATIONS_BEFORE_PACKAGE(true, true),
FILE_ANNOTATIONS_WHEN_PACKAGE_OMITTED(true, true),
NO_ANNOTATIONS(false, false);
DEFAULT(false, true, false, false),
FILE_ANNOTATIONS_BEFORE_PACKAGE(true, true, false, false),
FILE_ANNOTATIONS_WHEN_PACKAGE_OMITTED(true, true, false, false),
TYPE_CONTEXT(false, true, true, false),
WITH_SIGNIFICANT_WHITESPACE_BEFORE_ARGUMENTS(false, true, true, true),
NO_ANNOTATIONS(false, false, false, false);
boolean isFileAnnotationParsingMode;
boolean allowAnnotations;
boolean withSignificantWhitespaceBeforeArguments;
boolean typeContext;
AnnotationParsingMode(
boolean isFileAnnotationParsingMode,
boolean allowAnnotations
boolean allowAnnotations,
boolean typeContext,
boolean withSignificantWhitespaceBeforeArguments
) {
this.isFileAnnotationParsingMode = isFileAnnotationParsingMode;
this.allowAnnotations = allowAnnotations;
this.typeContext = typeContext;
this.withSignificantWhitespaceBeforeArguments = withSignificantWhitespaceBeforeArguments;
}
}
}

View File

@@ -22,7 +22,6 @@ import com.intellij.lang.PsiBuilder;
import com.intellij.lang.PsiBuilderFactory;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import kotlin.text.StringsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.parsing.KotlinParser;
import org.jetbrains.kotlin.psi.stubs.elements.KtFileElementType;
@@ -42,10 +41,6 @@ public class KtBlockCodeFragmentType extends KtFileElementType {
@Override
protected ASTNode doParseContents(@NotNull ASTNode chameleon, @NotNull PsiElement psi) {
if (StringsKt.isBlank(chameleon.getText())) {
return null;
}
Project project = psi.getProject();
Language languageForParser = getLanguageForParser(psi);
PsiBuilder builder = PsiBuilderFactory.getInstance().createBuilder(project, chameleon, null, languageForParser, chameleon.getChars());

View File

@@ -46,6 +46,9 @@ class KtClassBody : KtElementImplStub<KotlinPlaceHolderStub<KtClassBody>>, KtDec
val properties: List<KtProperty>
get() = getStubOrPsiChildrenAsList(KtStubElementTypes.PROPERTY)
val functions: List<KtFunction>
get() = getStubOrPsiChildrenAsList(KtStubElementTypes.FUNCTION)
val enumEntries: List<KtEnumEntry>
get() = getStubOrPsiChildrenAsList(KtStubElementTypes.ENUM_ENTRY).filterIsInstance<KtEnumEntry>()

View File

@@ -22,7 +22,6 @@ import com.intellij.lang.PsiBuilder;
import com.intellij.lang.PsiBuilderFactory;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import kotlin.text.StringsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.parsing.KotlinParser;
import org.jetbrains.kotlin.psi.stubs.elements.KtFileElementType;
@@ -42,10 +41,6 @@ public class KtExpressionCodeFragmentType extends KtFileElementType {
@Override
protected ASTNode doParseContents(@NotNull ASTNode chameleon, @NotNull PsiElement psi) {
if (StringsKt.isBlank(chameleon.getText())) {
return null;
}
Project project = psi.getProject();
Language languageForParser = getLanguageForParser(psi);
PsiBuilder builder = PsiBuilderFactory.getInstance().createBuilder(project, chameleon, null, languageForParser, chameleon.getChars());

View File

@@ -6,6 +6,7 @@
package org.jetbrains.kotlin.resolve.calls.components
import org.jetbrains.kotlin.builtins.*
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.resolve.calls.components.CreateFreshVariablesSubstitutor.createToFreshVariableSubstitutorAndAddInitialConstraints
@@ -180,7 +181,9 @@ class CallableReferencesCandidateFactory(
expectedType
)
if (defaults != 0) {
if (defaults != 0 &&
!callComponents.languageVersionSettings.supportsFeature(LanguageFeature.FunctionReferenceWithDefaultValueAsOtherType)
) {
diagnostics.add(CallableReferencesDefaultArgumentUsed(argument, candidateDescriptor, defaults))
}

View File

@@ -93,6 +93,7 @@ class CallableReferenceResolver(
)
}
diagnosticsHolder.addDiagnosticIfNotNull(diagnostic)
chosenCandidate.diagnostics.forEach { diagnosticsHolder.addDiagnostic(it) }
chosenCandidate.freshSubstitutor = toFreshSubstitutor
} else {
if (candidates.isEmpty()) {

View File

@@ -68,13 +68,16 @@ fun CallableDescriptor.substitute(substitutor: NewTypeSubstitutor): CallableDesc
return substitute(TypeSubstitutor.create(wrappedSubstitution))
}
fun CallableDescriptor.substituteAndApproximateCapturedTypes(substitutor: NewTypeSubstitutor): CallableDescriptor {
fun CallableDescriptor.substituteAndApproximateCapturedTypes(
substitutor: NewTypeSubstitutor,
typeApproximator: TypeApproximator
): CallableDescriptor {
val wrappedSubstitution = object : TypeSubstitution() {
override fun get(key: KotlinType): TypeProjection? = null
override fun prepareTopLevelType(topLevelType: KotlinType, position: Variance) =
substitutor.safeSubstitute(topLevelType.unwrap()).let { substitutedType ->
TypeApproximator(builtIns).approximateToSuperType(substitutedType, TypeApproximatorConfiguration.CapturedAndIntegerLiteralsTypesApproximation)
typeApproximator.approximateToSuperType(substitutedType, TypeApproximatorConfiguration.CapturedAndIntegerLiteralsTypesApproximation)
?: substitutedType
}
}

View File

@@ -100,10 +100,14 @@ abstract class AbstractTypeCheckerContextForConstraintSystem : AbstractTypeCheck
return null
}
return if (projection.getVariance() == TypeVariance.OUT)
projection.getType().takeIf { it is SimpleTypeMarker && isMyTypeVariable(it) }?.asSimpleType()
else
null
return if (projection.getVariance() == TypeVariance.OUT) {
val type = projection.getType()
when {
type is SimpleTypeMarker && isMyTypeVariable(type) -> type.asSimpleType()
type is FlexibleTypeMarker && isMyTypeVariable(type.lowerBound()) -> type.asFlexibleType()?.lowerBound()
else -> null
}
} else null
}
/**

View File

@@ -27,6 +27,7 @@ import org.jetbrains.kotlin.resolve.calls.tower.ResolutionCandidateApplicability
import org.jetbrains.kotlin.resolve.scopes.*
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValueWithSmartCastInfo
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeApproximator
interface ImplicitScopeTower {
val lexicalScope: LexicalScope
@@ -42,6 +43,8 @@ interface ImplicitScopeTower {
val isDebuggerContext: Boolean
val isNewInferenceEnabled: Boolean
val typeApproximator: TypeApproximator
}
interface ScopeTowerLevel {

View File

@@ -83,6 +83,7 @@ internal class MemberScopeTowerLevel(
private val syntheticScopes = scopeTower.syntheticScopes
private val isNewInferenceEnabled = scopeTower.isNewInferenceEnabled
private val typeApproximator = scopeTower.typeApproximator
private fun collectMembers(
getMembers: ResolutionScope.(KotlinType?) -> Collection<CallableDescriptor>
@@ -108,9 +109,11 @@ internal class MemberScopeTowerLevel(
if (dispatchReceiver.possibleTypes.isNotEmpty()) {
if (unstableCandidates == null) {
result.retainAll(result.selectMostSpecificInEachOverridableGroup { descriptor.approximateCapturedTypes() })
result.retainAll(result.selectMostSpecificInEachOverridableGroup { descriptor.approximateCapturedTypes(typeApproximator) })
} else {
result.addAll(unstableCandidates.selectMostSpecificInEachOverridableGroup { descriptor.approximateCapturedTypes() })
result.addAll(
unstableCandidates.selectMostSpecificInEachOverridableGroup { descriptor.approximateCapturedTypes(typeApproximator) }
)
}
}
@@ -129,10 +132,9 @@ internal class MemberScopeTowerLevel(
* So method get has signature get(Int): Capture(*). If we also have smartcast to MutableList<String>, then there is also method get(Int): String.
* And we should chose get(Int): String.
*/
private fun CallableDescriptor.approximateCapturedTypes(): CallableDescriptor {
private fun CallableDescriptor.approximateCapturedTypes(approximator: TypeApproximator): CallableDescriptor {
if (!isNewInferenceEnabled) return this
val approximator = TypeApproximator(builtIns)
val wrappedSubstitution = object : TypeSubstitution() {
override fun get(key: KotlinType): TypeProjection? = null
override fun prepareTopLevelType(topLevelType: KotlinType, position: Variance) = when (position) {

View File

@@ -28,6 +28,7 @@ import org.jetbrains.kotlin.types.checker.NewCapturedType
import org.jetbrains.kotlin.types.checker.NewCapturedTypeConstructor
import org.jetbrains.kotlin.types.model.*
import org.jetbrains.kotlin.types.model.CaptureStatus.*
import java.util.concurrent.ConcurrentHashMap
import org.jetbrains.kotlin.types.typeUtil.builtIns
@@ -123,6 +124,10 @@ class TypeApproximator(builtIns: KotlinBuiltIns) : AbstractTypeApproximator(Clas
abstract class AbstractTypeApproximator(val ctx: TypeSystemInferenceExtensionContext) : TypeSystemInferenceExtensionContext by ctx {
private class ApproximationResult(val type: KotlinTypeMarker?)
private val cacheForIncorporationConfigToSuperDirection = ConcurrentHashMap<KotlinTypeMarker, ApproximationResult>()
private val cacheForIncorporationConfigToSubtypeDirection = ConcurrentHashMap<KotlinTypeMarker, ApproximationResult>()
private val referenceApproximateToSuperType = this::approximateSimpleToSuperType
private val referenceApproximateToSubType = this::approximateSimpleToSubType
@@ -140,23 +145,69 @@ abstract class AbstractTypeApproximator(val ctx: TypeSystemInferenceExtensionCon
fun approximateToSubType(type: KotlinTypeMarker, conf: TypeApproximatorConfiguration): KotlinTypeMarker? =
approximateToSubType(type, conf, -type.typeDepth())
fun clearCache() {
cacheForIncorporationConfigToSubtypeDirection.clear()
cacheForIncorporationConfigToSuperDirection.clear()
}
private fun checkExceptionalCases(
type: KotlinTypeMarker, depth: Int, conf: TypeApproximatorConfiguration, toSuper: Boolean
): ApproximationResult? {
return when {
type is TypeUtils.SpecialType ->
null.toApproximationResult()
type.isError() ->
// todo -- fix builtIns. Now builtIns here is DefaultBuiltIns
(if (conf.errorType) null else type.defaultResult(toSuper)).toApproximationResult()
depth > 3 ->
type.defaultResult(toSuper).toApproximationResult()
else -> null
}
}
private fun KotlinTypeMarker?.toApproximationResult(): ApproximationResult = ApproximationResult(this)
private inline fun cachedValue(
type: KotlinTypeMarker,
conf: TypeApproximatorConfiguration,
toSuper: Boolean,
approximate: () -> KotlinTypeMarker?
): KotlinTypeMarker? {
// Approximator depends on a configuration, so cache should take it into account
// Here, we cache only types for configuration "from incorporation", which is used most intensively
if (conf !is TypeApproximatorConfiguration.IncorporationConfiguration) return approximate()
val cache = if (toSuper) cacheForIncorporationConfigToSuperDirection else cacheForIncorporationConfigToSubtypeDirection
return cache.getOrPut(type, { approximate().toApproximationResult() }).type
}
private fun approximateToSuperType(type: KotlinTypeMarker, conf: TypeApproximatorConfiguration, depth: Int): KotlinTypeMarker? {
if (type is TypeUtils.SpecialType) return null
return approximateTo(
prepareType(type), conf, { upperBound() },
referenceApproximateToSuperType, depth
)
checkExceptionalCases(type, depth, conf, toSuper = true)?.let { return it.type }
return cachedValue(type, conf, toSuper = true) {
approximateTo(
prepareType(type), conf, { upperBound() },
referenceApproximateToSuperType, depth
)
}
}
private fun approximateToSubType(type: KotlinTypeMarker, conf: TypeApproximatorConfiguration, depth: Int): KotlinTypeMarker? {
if (type is TypeUtils.SpecialType) return null
return approximateTo(
prepareType(type), conf, { lowerBound() },
referenceApproximateToSubType, depth
)
checkExceptionalCases(type, depth, conf, toSuper = false)?.let { return it.type }
return cachedValue(type, conf, toSuper = false) {
approximateTo(
prepareType(type), conf, { lowerBound() },
referenceApproximateToSubType, depth
)
}
}
// comments for case bound = upperBound, approximateTo = toSuperType
// Don't call this method directly, it should be used only in approximateToSuperType/approximateToSubType (use these methods instead)
// This method contains detailed implementation only for type approximation, it doesn't check exceptional cases and doesn't use cache
private fun approximateTo(
type: KotlinTypeMarker,
conf: TypeApproximatorConfiguration,
@@ -334,13 +385,6 @@ abstract class AbstractTypeApproximator(val ctx: TypeSystemInferenceExtensionCon
toSuper: Boolean,
depth: Int
): KotlinTypeMarker? {
if (type.isError()) {
// todo -- fix builtIns. Now builtIns here is DefaultBuiltIns
return if (conf.errorType) null else type.defaultResult(toSuper)
}
if (depth > 3) return type.defaultResult(toSuper)
if (type.argumentsCount() != 0) {
return approximateParametrizedType(type, conf, toSuper, depth + 1)
}
@@ -386,12 +430,15 @@ abstract class AbstractTypeApproximator(val ctx: TypeSystemInferenceExtensionCon
toSuper: Boolean,
depth: Int
): KotlinTypeMarker? {
val approximatedOriginalType = approximateTo(type.original(), conf, toSuper, depth)
val originalType = type.original()
val approximatedOriginalType =
if (toSuper) approximateToSuperType(originalType, conf, depth) else approximateToSubType(originalType, conf, depth)
return if (conf.definitelyNotNullType) {
approximatedOriginalType?.makeDefinitelyNotNullOrNotNull()
} else {
if (toSuper)
(approximatedOriginalType ?: type.original()).withNullability(false)
(approximatedOriginalType ?: originalType).withNullability(false)
else
type.defaultResult(toSuper)
}
@@ -523,8 +570,8 @@ abstract class AbstractTypeApproximator(val ctx: TypeSystemInferenceExtensionCon
return type.replaceArguments(newArgumentsList)
}
private fun SimpleTypeMarker.defaultResult(toSuper: Boolean) = if (toSuper) nullableAnyType() else {
if (isMarkedNullable()) nullableNothingType() else nothingType()
private fun KotlinTypeMarker.defaultResult(toSuper: Boolean) = if (toSuper) nullableAnyType() else {
if (this is SimpleTypeMarker && isMarkedNullable()) nullableNothingType() else nothingType()
}
// Any? or Any!

View File

@@ -22,6 +22,7 @@ where advanced options include:
-Xdump-perf=<path> Dump detailed performance statistics to the specified file
-Xeffect-system Enable experimental language feature: effect system
-Xexperimental=<fq.name> Enable and propagate usages of experimental API for marker annotation with the given fully qualified name
-Xinline-classes Enable experimental inline classes
-Xintellij-plugin-root=<path> Path to the kotlin-compiler.jar or directory where IntelliJ configuration files can be found
-Xlegacy-smart-cast-after-try Allow var smart casts despite assignment in try block
-Xlist-phases List backend phases
@@ -38,6 +39,7 @@ where advanced options include:
-Xphases-to-validate-after Validate backend state after these phases
-Xphases-to-validate-before Validate backend state before these phases
-Xplugin=<path> Load plugins from the given classpath
-Xpolymorphic-signature Enable experimental support for @PolymorphicSignature (MethodHandle/VarHandle)
-Xprofile-phases Profile backend phases
-Xproper-ieee754-comparisons Generate proper IEEE 754 comparisons in all cases if values are statically known to be of primitive numeric types
-Xread-deserialized-contracts Enable reading of contracts from metadata

View File

@@ -84,6 +84,7 @@ where advanced options include:
-Xdump-perf=<path> Dump detailed performance statistics to the specified file
-Xeffect-system Enable experimental language feature: effect system
-Xexperimental=<fq.name> Enable and propagate usages of experimental API for marker annotation with the given fully qualified name
-Xinline-classes Enable experimental inline classes
-Xintellij-plugin-root=<path> Path to the kotlin-compiler.jar or directory where IntelliJ configuration files can be found
-Xlegacy-smart-cast-after-try Allow var smart casts despite assignment in try block
-Xlist-phases List backend phases
@@ -100,6 +101,7 @@ where advanced options include:
-Xphases-to-validate-after Validate backend state after these phases
-Xphases-to-validate-before Validate backend state before these phases
-Xplugin=<path> Load plugins from the given classpath
-Xpolymorphic-signature Enable experimental support for @PolymorphicSignature (MethodHandle/VarHandle)
-Xprofile-phases Profile backend phases
-Xproper-ieee754-comparisons Generate proper IEEE 754 comparisons in all cases if values are statically known to be of primitive numeric types
-Xread-deserialized-contracts Enable reading of contracts from metadata

View File

@@ -0,0 +1,4 @@
$TESTDATA_DIR$/functionReferenceWithDefaultValuesFeatureIsEnabledWithNewInference.kt
-d
$TEMP_DIR$
-Xnew-inference

View File

@@ -0,0 +1,11 @@
fun foo(a: String, b: Int = 5): String {
return a + b
}
fun bar1(body: (String) -> String): String {
return body("something")
}
fun test() {
bar1(::foo)
}

View File

@@ -0,0 +1,4 @@
$TESTDATA_DIR$/functionReferenceWithDefaultValuesFeatureIsEnabledWithNewInference.kt
-d
$TEMP_DIR$
-XXLanguage\:+NewInference

View File

@@ -0,0 +1,10 @@
warning: ATTENTION!
This build uses unsafe internal compiler arguments:
-XXLanguage:+NewInference
This mode is not recommended for production use,
as no stability/compatibility guarantees are given on
compiler or generated code. Use it at your own risk!
OK

View File

@@ -1,4 +1,4 @@
// !LANGUAGE: +NewInference
// !LANGUAGE: +NewInference +FunctionReferenceWithDefaultValueAsOtherType
// IGNORE_BACKEND: JS
fun foo(s: String = "kotlin", vararg t: String): Boolean {

View File

@@ -1,4 +1,4 @@
// !LANGUAGE: +NewInference
// !LANGUAGE: +NewInference +FunctionReferenceWithDefaultValueAsOtherType
// IGNORE_BACKEND: JS
// WITH_RUNTIME

View File

@@ -1,4 +1,4 @@
// !LANGUAGE: +NewInference
// !LANGUAGE: +NewInference +FunctionReferenceWithDefaultValueAsOtherType
// IGNORE_BACKEND: JS
fun foo(vararg a: String, result: String = "OK"): String =

View File

@@ -1,4 +1,4 @@
// !LANGUAGE: +NewInference
// !LANGUAGE: +NewInference +FunctionReferenceWithDefaultValueAsOtherType
fun foo(x: String, y: Char = 'K'): String = x + y

View File

@@ -1,4 +1,4 @@
// !LANGUAGE: +NewInference
// !LANGUAGE: +NewInference +FunctionReferenceWithDefaultValueAsOtherType
// IGNORE_BACKEND: JS
fun foo(x: String = "O", vararg y: String): String =

View File

@@ -1,4 +1,4 @@
// !LANGUAGE: +NewInference
// !LANGUAGE: +NewInference +FunctionReferenceWithDefaultValueAsOtherType
// IGNORE_BACKEND: JS, JVM_IR
fun foo(vararg l: Long, s: String = "OK"): String =

View File

@@ -1,4 +1,4 @@
// !LANGUAGE: +NewInference
// !LANGUAGE: +NewInference +FunctionReferenceWithDefaultValueAsOtherType
// IGNORE_BACKEND: JS

View File

@@ -1,4 +1,4 @@
// !LANGUAGE: +NewInference
// !LANGUAGE: +NewInference +FunctionReferenceWithDefaultValueAsOtherType
// IGNORE_BACKEND: JS
fun call0(f: (String) -> String, x: String): String = f(x)

View File

@@ -1,4 +1,4 @@
// !LANGUAGE: +NewInference
// !LANGUAGE: +NewInference +FunctionReferenceWithDefaultValueAsOtherType
// IGNORE_BACKEND: JS
// WITH_RUNTIME

View File

@@ -1,4 +1,4 @@
// !LANGUAGE: +NewInference
// !LANGUAGE: +NewInference +FunctionReferenceWithDefaultValueAsOtherType
fun foo(x: String, y: String = "K"): String = x + y

View File

@@ -1,4 +1,4 @@
// !LANGUAGE: +NewInference
// !LANGUAGE: +NewInference +FunctionReferenceWithDefaultValueAsOtherType
// IGNORE_BACKEND: JS
fun foo(x: Int, s: Int, vararg y: CharSequence = arrayOf("Aaa")): String =

View File

@@ -1,5 +1,5 @@
// !LANGUAGE: +InlineClasses
// IGNORE_BACKEND: JS, JS_IR, NATIVE
// KJS_WITH_FULL_RUNTIME
// WITH_RUNTIME
data class RGBA(val rgba: Int)

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