Compare commits

...

151 Commits

Author SHA1 Message Date
Stanislav Erokhin
60cdc34d24 test2 2020-04-13 19:34:08 +03:00
Andrey Uskov
487e702e20 Remove ChangeLogs for old releases 2020-03-23 13:43:48 +03:00
Andrey Uskov
bc63ec24f1 Add changes in New Inference to ChangeLog 2020-03-23 13:38:53 +03:00
Andrey Uskov
08ae7ac9de Update ChangeLog.md for 1.4-M1 release 2020-03-22 11:59:33 +03:00
Zalim Bashorov
e520d54cdc [IDE KJS] Recognize and load correctly Kotlin/JS klibs in IDE
#KT-36276 Fixed
2020-03-17 15:29:01 +03:00
Zalim Bashorov
1befecb65d [IDE KJS] Move JsResolverForModuleFactory to proper place 2020-03-17 15:29:00 +03:00
Zalim Bashorov
322af2c15d [IDE KN] Treat klib as Kotlin/Native library iff manifest contains builtins_platform==NATIVE 2020-03-17 15:29:00 +03:00
Dmitry Savvinov
1a6b64e86b Add builtins_platform property to klib manifest
(cherry picked from commit b8b1dd753c)
2020-03-17 15:28:59 +03:00
Vladimir Dolzhenko
37a3102417 Don't show modal progress dialog on calculate method parameter hint info
#KT-37537 Fixed
Relates to #EA-216268

(cherry picked from commit c29f76580c)
2020-03-17 13:03:12 +01:00
nikita.movshin
f80d8eaa84 Update K/N 2020-03-17 01:00:20 +03:00
Nikolay Krasko
9f8c5ac26e 201: Mute GradleMultiplatformWizardTest.testMobile because of leaked JDK 2020-03-11 22:55:16 +03:00
Nikolay Krasko
834db1c1ec 201: Update test data about test run markers under gradle 2020-03-11 22:55:16 +03:00
Nikolay Krasko
e786be79fc 201: Update to 201.6073.9 2020-03-11 22:55:16 +03:00
Nikolay Krasko
3d6ac7c921 201: Mute JS android tests in MultiplatformProjectImportingTest 2020-03-11 22:55:16 +03:00
Nikolay Krasko
60b4b1f3ff 201: Mute test because of NPE: element.parent must not be null (IDEA-234737) 2020-03-11 22:55:15 +03:00
Nikolay Krasko
7c666e4d80 201: Fix setup for AbstractKotlinExceptionFilterTest tests 2020-03-11 22:55:15 +03:00
Nikolay Krasko
0c66ca85b5 201: Mute SpringRenameTestGenerated tests 2020-03-11 22:55:15 +03:00
Nikolay Krasko
39158ed023 201: Remove declarations added for dropped newApi in hierarchy 2020-03-11 22:55:15 +03:00
Nikolay Krasko
21c600a383 201: Update to 201.5985.32 2020-03-11 22:55:15 +03:00
Nikolay Krasko
b756a3bbff Access to test root disposable through accessor
(cherry picked from commit 6c968859ad)
2020-03-11 22:55:14 +03:00
Nikolay Krasko
07a79efc2e Refactoring: extract resetApplicationToNull to separate file
(cherry picked from commit 272ccf64ae)
2020-03-11 22:55:14 +03:00
Nikolay Krasko
e17131ed5c Update to 201.5259.13-EAP-SNAPSHOT
- No UIUtil.removeLeakingAppleListeners anymore
- getParameterHints nullability
- versions of lz4-java and guava were changed

(cherry picked from commit 2340a86d8d)
2020-03-11 22:55:14 +03:00
Nikolay Krasko
5866ed40da Use createForProduction for running standalone execution
(cherry picked from commit a52ef71d48)
2020-03-11 22:53:23 +03:00
Nikolay Krasko
bbace8d102 Disable parallel execution for gradle tests
(cherry picked from commit 208c7274dd)
2020-03-11 22:53:23 +03:00
Nikolay Krasko
5136dfdc64 Fix testUnresolvedMultiline test data
(cherry picked from commit d47fc7280b)
2020-03-11 22:53:23 +03:00
Nikolay Krasko
8e6a086041 201: Mute SuggestedRefactoring tests
(cherry picked from commit 7a4d414c59)
2020-03-11 22:53:23 +03:00
Nikolay Krasko
c8662c1269 201: Mute HierarchicalMultiplatformProjectImportingTest: No module dependency found
(cherry picked from commit 6a9dfd4935)
2020-03-11 22:53:23 +03:00
Nikolay Krasko
f359fcb9bc 201: Mute quick fix tests: Range must be inside element being annotated
(cherry picked from commit 774db02b23)
2020-03-11 22:53:23 +03:00
Nikolay Krasko
4d0211a941 201: Mute TodoSearchTest: duplicate TODO items
(cherry picked from commit 06adac1abf)
2020-03-11 22:53:23 +03:00
Nikolay Krasko
331bb6ad4d 201: Mute incremental compilation tests with constants
(cherry picked from commit 543168c61d)
2020-03-11 22:53:22 +03:00
Nikolay Krasko
33cf460eec 201: Mute a lot of tests with enums
(cherry picked from commit 8501ea78c8)
2020-03-11 22:53:22 +03:00
Nikolay Krasko
fd128ac5c1 201: Mute QuickFixTestGenerate: Range must be inside element being annotated
(cherry picked from commit 79e663828a)
2020-03-11 22:53:22 +03:00
Nikolay Krasko
0eea3d9187 201: Mute GradleScriptInputsWatcherTest failures
(cherry picked from commit f5a97ea56e)
2020-03-11 22:53:22 +03:00
Nikolay Krasko
9539a16b3a 201: Upgrade nodejs plugin in 201 branch
(cherry picked from commit dad7fd383c)
2020-03-11 22:53:22 +03:00
Nikolay Krasko
63c3b80328 201: Mute NewMultiplatformProjectImportingTest tests
No module dependency found
No source folder found

(cherry picked from commit f0a4f838f2)
2020-03-11 22:53:22 +03:00
Nikolay Krasko
966928e9db 201: Mute MultiplatformProjectImportingTest tests
Failed search dependency in Gradle tests.

(cherry picked from commit f4cd25ce72)
2020-03-11 22:53:22 +03:00
Nikolay Krasko
bb8cfdf24c 201: Mute NewJavaToKotlinConverterSingleFileTestGenerated tests
(cherry picked from commit 67dee52b8a)
2020-03-11 22:53:21 +03:00
Nikolay Krasko
299d8f62aa 201: Fix maven plugin loading by adding repository-search to runtime
(cherry picked from commit 958b8a0b10)
2020-03-11 22:53:21 +03:00
Nikolay Krasko
a704a55981 201: Fix loading project in configuration tests
De-bunch AbstractConfigureKotlinTest.kt, just don't use field in 193.

(cherry picked from commit 0fcd011abb)
2020-03-11 22:53:21 +03:00
Nikolay Krasko
f76efaa3dd 201: Trick idea home path exception with custom idea.home variable
(cherry picked from commit 1a01ba0ae5)
2020-03-11 22:53:21 +03:00
Nikolay Krasko
bc72f926d4 Copy 192 muted tests
(cherry picked from commit da2683d180)
2020-03-11 22:53:21 +03:00
Nikolay Krasko
1c9ea45ab1 Register JDK for default project to prevent create leaking one for Gradle import
(cherry picked from commit dd21736471)
2020-03-11 22:53:21 +03:00
Nikolay Krasko
2ed625d26d Enable mute in code for all KotlinLightCodeInsightFixtureTestCaseBase
(cherry picked from commit c9fd79c311)
2020-03-11 22:53:20 +03:00
Nikolay Krasko
ee70f8bce9 Minor: better asserts in TodoSearchTest.kt
(cherry picked from commit 1c0a9d2981)
2020-03-11 22:53:20 +03:00
Nikolay Krasko
19c28cec0e Enable mute test with database in BaseKotlinJpsBuildTestCase
(cherry picked from commit 26df2a5c68)
2020-03-11 22:53:20 +03:00
Nikolay Krasko
82a8b8f0c0 Ignore auto-mute files
(cherry picked from commit 31ba40cc99)
2020-03-11 22:53:20 +03:00
Nikolay Krasko
5cfc00a8ad Enable mute for KotlinCompletionTestCase
(cherry picked from commit c22272bbca)
2020-03-11 22:53:20 +03:00
Nikolay Krasko
a0ca0944c5 Update method after UsefulTestCase update to make in work in 201
(cherry picked from commit 66e2f95dba)
2020-03-11 22:53:20 +03:00
Nikolay Krasko
4540206da7 Support auto-mute in parametrized JUnit 4 tests
(cherry picked from commit 3c3b1bb5e4)
2020-03-11 22:53:19 +03:00
Nikolay Krasko
c173a6f054 Minor: remove unneeded class
(cherry picked from commit f042b04320)
2020-03-11 22:53:19 +03:00
Nikolay Krasko
34223eb873 Revert global project settings to LATEST_STABLE in teardown
(cherry picked from commit a46c6ce5df)
2020-03-11 22:53:19 +03:00
Nikolay Krasko
163b12b587 Always configure and restore api version settings in tests
(cherry picked from commit f995192f21)
2020-03-11 22:53:19 +03:00
Nikolay Krasko
aa2e661e93 Clean LANGUAGE_VERSION_SETTINGS after the test
(cherry picked from commit 6c83e9fb85)
2020-03-11 22:53:19 +03:00
Nikolay Krasko
db0268e7c6 Clean facet if it wasn't set before test (fix tests on 201)
(cherry picked from commit 19bc39d3ab)
2020-03-11 22:53:19 +03:00
Nikolay Krasko
3e2136b396 Always clean language and api versions after usage
(cherry picked from commit af3b057ba2)
2020-03-11 22:53:18 +03:00
Nikolay Krasko
311d125fb4 Refactoring: extract long function out of local context
(cherry picked from commit c0dac9bf32)
2020-03-11 22:53:18 +03:00
Nikolay Krasko
1d5693c320 Refactoring: always use compiler settings with de-configuration in tests
(cherry picked from commit 3a5f42cc5e)
2020-03-11 22:53:18 +03:00
Nikolay Krasko
b90b08b914 De-bunch KotlinLightCodeInsightFixtureTestCase.kt
(cherry picked from commit 018215f47d)
2020-03-11 22:53:18 +03:00
Svyatoslav Kuzmich
0ad7fa841c [JS IR BE] Fix enum entry initialization
Keep helper fields uninitialized. This way thier initialization
would not depend on field initialization order.
2020-03-11 14:43:39 +03:00
Vladimir Dolzhenko
c80d8670ca Make copy-paste resolve task modal to avoid invalid psi elements
Due to background formatting pasted PSI elements become invalid quite soon and it is not possible to make resolve

#KT-37414 Fixed

(cherry picked from commit 8af5e2bb04)
2020-03-11 11:55:28 +01:00
nikita.movshin
7e0b147e17 Update K/N 2020-03-10 23:32:56 +03:00
Ilya Goncharov
8d56cea923 [Gradle, JS] Fix for produceExecutable in Groovy build script
(cherry picked from commit ae6a603a92)

#KT-37387 fixed
2020-03-10 17:25:39 +03:00
Roman Artemev
dc23cd605c [JS IR] Mute failing test 2020-03-10 12:11:02 +03:00
Roman Artemev
99bce01fcb [KLIB] Do not include return type into mangle
(cherry picked from commit 7fff4e78e5)
2020-03-10 12:11:02 +03:00
Roman Artemev
902070d764 [KLIB] Don't have a special mangle for internal declarations
(cherry picked from commit 62621de4fc)
2020-03-10 12:11:02 +03:00
Alexander Gorshenev
3e3e7a26d1 Print out abi version as a full triple 2020-03-10 12:08:53 +03:00
Alexander Gorshenev
824697715e Provide library producer compiler version in klib abi mismatch disagnostics 2020-03-10 12:08:53 +03:00
Alexander Gorshenev
6fb38c14d7 Be prepared if in the future we extend klib abi version to a triple 2020-03-10 12:08:53 +03:00
Svyatoslav Kuzmich
3c8d2f611d [JS IR BE] Support companion objects in external interfaces
These objects are referenced but value is not actually used.
Replace access to these references with null literals.
2020-03-06 20:34:41 +03:00
Svyatoslav Kuzmich
b2f37fd50a Update klib metadata version to 1.4.0 2020-03-06 20:34:41 +03:00
nikita.movshin
596bc4ac3b Update compatibility range for AS 3.6 and 4.0 2020-03-06 19:15:33 +03:00
nikita.movshin
da250dae2b Update K/N 2020-03-06 18:59:10 +03:00
Sergey Rostov
feaf55a2b9 Fix tests freeze because of ScriptChangesNotifier (KT-37112)
#KT-37112 Fixed
2020-03-06 17:09:36 +03:00
Ilya Goncharov
819ce2ce57 [Gradle, JS] Migrate from singletons to classes
(cherry picked from commit 8fbfa8b819)
2020-03-06 17:01:12 +03:00
Ilya Goncharov
7850e58132 [Gradle, JS] Consider transitivity in cache of npm dependencies
(cherry picked from commit 82de930574)
2020-03-06 17:01:09 +03:00
Ilya Goncharov
c297418961 [Gradle, JS] Fix naming
(cherry picked from commit 49814c438c)
2020-03-06 17:01:06 +03:00
Ilya Goncharov
5ec27a0da5 [Gradle, JS] Support transitive mode for npm dependencies
#KT-36196 fixed

(cherry picked from commit 2eea8b0760)
2020-03-06 17:01:03 +03:00
Ilya Goncharov
688671b701 [Gradle, JS] Move logic of resolving NpmDependency to Npm Api
#KT-36196 fixed

(cherry picked from commit d108c8ef51)
2020-03-06 17:01:02 +03:00
Sergey Igushkin
3e4797316e Internal visibility between common source sets in Gradle (KT-37264)
In KotlinCompileCommon, pass the friendPaths and refinesPaths arguments

In KotlinNativeCompilation, add both friend and refined dependencies as
friends for now.

In getVisibleSourceSetsFromAssociateCompilations, exclude the metadata
compilations to avoid incorrect results (those compilations don't have
proper kotlin

Issue #KT-37264 Fixed
2020-03-06 15:58:40 +03:00
Sergey Igushkin
6454046fd8 Support friend internal visibility in K2Metadata compiler (KT-37264)
Add and handle the friend paths and refines paths compiler arguments;
Reuse klib dependency module descriptors in the resolver for project;

Issue #KT-37264
2020-03-06 15:58:37 +03:00
Andrey Uskov
432cc67f69 Fix import of MPP dependencies on non-jvm modules
#KT-36354 Fixed
2020-03-06 14:43:51 +03:00
Vladimir Dolzhenko
ae209b7607 Handle properly lambda change in incremental analysis
Fixed #KT-37273

(cherry picked from commit dc6be68a41)
2020-03-06 11:19:57 +01:00
nikita.movshin
1df35e0b81 Update K/N 2020-03-06 13:01:36 +03:00
Yan Zhulanow
9420cf4c15 Fix class run configuration applicability (KT-33787)
The bug appeared when we turned “ultra light classes” on by default.
  The difference with the old implementation is that
  PsiClass.getTextRange() returns the correct non-null value.
  This triggers JavaExecutionUtil#stepIntoSingleClass() to return
  a light class instead of the original location (of a PsiIdentifier).
  So AbstractJavaTestConfigurationProducer#isConfigurationFromContext()
  returns true, and the wrong configuration is reused instead of
  creating the new one.

By the way, for Java it also returns an identifier because of the
  PsiTreeUtil.getParentOfType(element, PsiClass.class) != null check.

The proper fix should land in the newer versions of IDEA, however this
  (hopefully, temporary) hack will fix test method gutters for
  all platform versions.

(cherry picked from commit 390d062721)
2020-03-06 18:40:46 +09:00
Yan Zhulanow
204cdb90c0 Revert "Import Kotlin JUnit run configuration settings from Gradle"
(cherry picked from commit b360fb5119)
2020-03-06 18:40:46 +09:00
Yan Zhulanow
c3d326a30e Partially revert "Prefer Kotlin Gradle test run configurations when possible (KT-33787)"
This commit reverts 987307cf92.
Tests are left behind as the different fix will be provided for KT-33787.

(cherry picked from commit 29566723b8)
2020-03-06 18:40:46 +09:00
Yan Zhulanow
7616b2b4a0 Partially revert "Prefer Kotlin Junit test run configurations when possible (KT-33787)"
This commit reverts parts of ef8b3cb72a.
Tests are left behind as the different fix will be provided for KT-33787.

(cherry picked from commit 9016a573ca)
2020-03-06 18:40:46 +09:00
Vyacheslav Gerasimov
51692103f3 Advance bootstrap to 1.4.0-dev-1818
(cherry picked from commit 4b9c7a1ae1)
2020-03-05 23:14:39 +03:00
Vladimir Dolzhenko
4c9ee10d3b Revert "Added AllowNullableArrayArgsInMain (1.4+) language setting"
#KT-35965 Fixed

(cherry picked from commit d1a29df581)
2020-03-05 16:34:24 +01:00
Leonid Startsev
212bec78b7 Leverage existing psi2ir function declaration generator in plugin
This seems to be the only reasonable way to provide function declarations with
_correctly_ substituted type parameters without rewriting logic from scratch;
correctly scoped type parameters in IR are now required in serialization
plugin by all backends.

Also fix some missing upper bounds.

(cherry picked from commit a2c24e696f)
2020-03-05 16:42:26 +03:00
Vladimir Dolzhenko
c3db27250d Use LightJavaModule.getModule for 193
Fixed #KT-37229

(cherry picked from commit 0be5a82460)
2020-03-04 17:26:00 +01:00
Vladimir Dolzhenko
8d69fe7300 Add checkCanceled on common for autocompletion and highlighting resolve path
(cherry picked from commit 15e2afe5ab)
2020-03-04 09:10:38 +01:00
Dmitry Petrov
446cdfc4e8 PSI2IR Use resulting descriptor extension receiver type
Use resulting descriptor extension receiver type instead of
ReceiverValue.type (which can contain captured types, which would be
approximated, and cause IR validation errors).
2020-03-03 11:20:41 +03:00
Dmitry Gridin
242426f7f7 ExperimentalFixesFactory: OptIn shouldn't be added for old version
#KT-36478

(cherry picked from commit ecb7478794)
2020-03-03 14:51:40 +07:00
Natalia Selezneva
aa1131e743 .gradle.kts: fix freezes by avoiding fs walking
^KT-36502 Fixed
2020-03-02 20:42:39 +03:00
Mikhail Zarechenskiy
35583c88e0 Disable New Inference in JS backend
See #KT-37163 for details
2020-03-02 18:09:39 +03:00
Elena Lepilkina
d217241a05 Updated K/N version 2020-03-02 09:51:54 +03:00
Nikita Skvortsov
f765b54478 Reduce UI freezes by preparing affected Gradle project files lists in advance, once per event. isRelevant() method is a hotspot, as it is called for each file in bulk VFS event
(cherry picked from commit 04424a1ec3)
2020-02-28 14:24:42 +03:00
Sergey Rostov
5ed7bcb1f5 .gradle.kts, changes notifier: process events async and on pooled thread
#KT-36401 Fixed

(cherry picked from commit 5e16373af6)
2020-02-28 14:24:42 +03:00
Vladimir Dolzhenko
6e5d4cc20f Add missed calcHashCode for ModuleSourceScope subclasses
(cherry picked from commit 1f47c6d54f)
2020-02-28 08:53:12 +01:00
Mikhail Zarechenskiy
6c2c65fc67 [NI] Reanalyze coroutine-block if there is inapplicable call
It's not clear how one should rollback _all_ resolution results if
 there is inapplicable call. Ideally, such calls should not be available
 in coroutine block but for now, to have backward compatibility, we'll
 just reanalyze coroutine block as a usual lambda if there is at least
 one such call.

 As a result, also remove diagnostic about non-applicable call as it
 become useless with current reanalysis

 #KT-37061 Fixed
 #KT-32097 Fixed
 #KT-32203 Fixed
 #KT-35306 Fixed
 #KT-36202 Fixed
 #KT-36220 Fixed
 #KT-32654 Fixed
2020-02-28 10:41:19 +03:00
Mikhail Zarechenskiy
795769c768 [NI] Update type of complex subcall for last lambda expressions 2020-02-28 10:35:06 +03:00
nikita.movshin
4ffec58da4 Update K/N 2020-02-28 00:42:53 +03:00
Svyatoslav Kuzmich
9e091f197e [JS IR BE] Implement kotlin.js.jsTypeOf as intrinsics 2020-02-27 13:46:09 +03:00
Dmitry Petrov
3bcba5b00b KT-36143 Fix type approximation for type arguments in PSI2IR
(cherry picked from commit 6d1da6e6d5)
2020-02-26 17:46:55 +03:00
Mikhail Zarechenskiy
93dad71817 [NI] Fix coroutine inference for qualified chained call with stub type 2020-02-26 17:21:01 +03:00
Svyatoslav Kuzmich
b6266e85b6 [PSI2IR] Patch parents before referenceExpectsForUsedActuals
There were some ADAPTER_FOR_CALLABLE_REFERENCE functions with
uninitialized parents at this point.
2020-02-26 16:37:44 +03:00
Stanislav Erokhin
3f6d731f58 Fix compile configuration for maven compiler plugins
Previously in kotlin-maven-noarg & kotlin-maven-serialization plugins
java was compiled before kotlin, and because of that links from java
to kotlin was unresolved.
It was fixed as prescribed by docs: https://kotlinlang.org/docs/reference/using-maven.html#compiling-kotlin-and-java-sources

(cherry picked from commit 74348d5ffb)
2020-02-26 13:29:26 +03:00
Stanislav Erokhin
1eef77efbe Deprecated reportFromPlugin way to report diagnostics from plugin
Originally reportFromPlugin method was introduced to address the problem
with loading of DefaultErrorMessages.Extension vis ServiceLoader.
For some cases this extension was not loaded by ServiceLoader because
classes was loaded via different class loader, common scenario here is
compiler plugins. Ideally we should load such extension point via
getService approach, but unfortunately to do that we need project and
DefaultErrorMessages.render is static method for now.
Also with reportFromPlugin approach is a problem -- all diagnostics
reported via this method has the same id: PLUGIN_[WARNING|ERROR|INFO]
and it isn't possible to suppress only one particular diagnostic.
To bypass this problem the new method
initializeFactoryNamesAndDefaultErrorMessages was introduced.
It basically store DiagnosticRenderer inside DiagnosticFactory.
It is not ideal, because one DiagnosticFactory could have different
renderers for different scenarios -- for compiler and for IDE, but
I think that it is better than reportByPlugin approach.

(cherry picked from commit 453008e488)
2020-02-26 13:29:20 +03:00
Mikhail Zarechenskiy
80d413d6e2 Add JvmDefault to recently added method for compiler extensions
This should fix AbstractMethodError when newer compiler is used with
 Compose plugin that haven't implemented recently added method

 #KT-37042 Fixed
2020-02-26 13:19:36 +03:00
Ilya Goncharov
b187de1507 [Gradle, JS] Fix propogation useCommonJs to irTarget
#KT-37036 fixed

(cherry picked from commit ee9be61c20)
2020-02-26 12:12:46 +03:00
Ilya Goncharov
fe7953b2e7 [Gradle, JS] Fix timeout for debug
#KT-37035 fixed

(cherry picked from commit 7719dfca4a)
2020-02-26 12:06:11 +03:00
Nikolay Krasko
5f00fe2f20 Make plugin for 201 compatible with idea trunk 2020-02-26 11:45:53 +03:00
Dmitry Gridin
65245f8fb7 Tests: fix some tests in formatter for AS
(cherry picked from commit 50c2c38624)
2020-02-26 14:47:06 +07:00
Dmitry Gridin
623ab8c8d5 Formatter: fix indent after trailing comma in calls
#KT-36917 Fixed

(cherry picked from commit ca598b6465)
2020-02-26 14:47:06 +07:00
Dmitry Savvinov
896b040a48 Flip default value of kotlin.gradle.testing.enabled to true 2020-02-25 18:25:03 +03:00
Dmitry Savvinov
ff2f02270b Fix CCE under composite mode
This commit essentially reverts change in IdeaResolverForProject made in
423aeb9a08

The issue is that 'platform.findAnalyzerServices' may return non-
CompositeAnalyzerServices even under composite analysis mode, when
platform is single-target (e.g. 'JvmAnalyzerServices' for JVM-only)

^KT-36978
2020-02-25 17:34:49 +03:00
Dmitry Savvinov
32c84524ec Always check project.useCompositeAnalysis in findAnalyzerServices
The important things here are changes in
ResovlerElementCache/PerFileAnalysisCache. Previously, we'd always use
'CompositeAnalyzerServices' for common-platform, even with HMPP turned
off.

However, with HMPP turned off, common-platform is always coerced to
[JVM, JS, Native], no matter which platforms that project actually
targets.
So, even if project compiles only for JVM/Native, we'll detect
platform of common module as [JVM, JS, Native], build composite analyzer
services *which include all checkers from all platforms*, and then
report false-positive errors from JS checkers.

^KT-35031 Fixed
^KT-33573 Fixed
^KT-34925 Fixed
2020-02-25 17:34:45 +03:00
Svyatoslav Kuzmich
6db14bc9dd [JS IR BE] Create temporary variables with wrapped descriptors. 2020-02-25 16:26:10 +03:00
Svyatoslav Kuzmich
ddc0ac87a8 [JS IR BE] Don't fail typeOf lowering on reified type parameters. 2020-02-25 16:26:10 +03:00
Svyatoslav Kuzmich
f2ac1dc10d [JS IR BE] Stop checking mangling for klib-to-js compilation.
It it broken.
2020-02-25 16:26:10 +03:00
Svyatoslav Kuzmich
2004e6c1aa [JS IR BE] Use fresh name for external JsModule declarations. 2020-02-25 16:26:09 +03:00
nikita.movshin
797415a808 Update K/N 2020-02-25 14:21:31 +03:00
Dmitry Gridin
1af6e3c4e9 Formatter: shouldn't format property chains
#KT-36387 Fixed
#KT-36466 Fixed

(cherry picked from commit feaa53c4f2)
2020-02-25 18:07:10 +07:00
Alexander Gorshenev
415a1cc849 Brought back mppKlibs guard lost in rebase 2020-02-25 13:26:47 +03:00
Mikhail Zarechenskiy
ea0e7578f2 [NI] Don't try inferring variables for effectively empty system 2020-02-25 10:48:06 +03:00
Dmitriy Dolovov
71e13e04be [Commonizer] Call commonizer on Gradle configuration phase
Issue #KT-36858

Initially it was called on execution step which may be omit
during project import into IDEA.
2020-02-25 14:16:37 +07:00
Vasily Levchenko
f57ad376e2 [build][native] version with milestone clause
(cherry picked from commit 98ce49ba73)
2020-02-23 17:29:49 +01:00
Zalim Bashorov
e2c4c5e1db [JS DCE] Add an ability to define overwriting strategy when copying dependencies in dev-mode
* CLI option "-Xdev-mode-overwriting-strategy"
* System Property "kotlin.js.dce.devmode.overwriting.strategy"

Possible values: "older", "all".

#KT-36349 Fixed

(cherry picked from commit 6f61ea7f67)
2020-02-22 01:12:24 +03:00
Dmitriy Novozhilov
29c8fbb3d1 [NI] Fix detecting expected type variable for postponed atoms
#KT-36819 Fixed
2020-02-21 18:34:42 +03:00
Mikhail Zarechenskiy
0d6d5ad4b1 [NI] Complete contradictory candidates inside builder-inference
In this test `kotlin` was resolved to the extension
 `val Class<T>.kotlin` because it was saved in builder-inference.
 Usually, it's fine, but not for qualified expressions as they have
 fallback resolve in case of error
2020-02-21 18:32:26 +03:00
Victor Petukhov
1efecbedc6 NI: exclude not fixed type variables from types on which null checks should be generated
^KT-36371 Fixed
2020-02-21 18:29:02 +03:00
Victor Petukhov
3c4709f395 Fix formatting of RuntimeAssertion.kt 2020-02-21 18:28:56 +03:00
Pavel Kirpichenkov
07fe3ad1b4 [NI] Make error CST when any of included types is error
`ErrorType` is not subtype of `Any`, so any set of types containing an `ErrorType` has no common super constructors.
^KT-36745 Fixed
2020-02-21 18:28:51 +03:00
Pavel Kirpichenkov
d8a98f5a57 [NI] Fix smartcasts for conventional contains in when
Call argument for conventional `contains` after expanding `in` may come from a `when` subject during its branch analysis.
In this case data flow info from a previous when branch was not considered,
because data flow info for subject had been used instead of data flow before argument.
Use of the latter one for the conventional `contains` solves the issue.

The old FE uses `isExternal` property of value arguments to skip smartcast reporting on `when` subject,
if they come from branches. To prevent undesired smartcasts on `when` subject after branch analysis in the new FE,
`isExternal` arguments are skipped in diagnostic reporter and during recorded type update.

Also, the new FE interprets `isExternal` completely differently from the old FE.
In the old FE this property is used exclusively by `when` with subject.
In the new FE it is also used for parially resolved calls, lambda return arguments and receivers.
This may be preventing the use of data flow info before argument in the first place, but this assumption requires additional investigation.

^KT-36818 Fixed
2020-02-21 18:28:45 +03:00
Mikhail Zarechenskiy
bf13252646 [NI] Fix substitution in builder-inference for empty common system 2020-02-21 18:23:05 +03:00
Mikhail Zarechenskiy
4158d68063 Provide candidate interceptor for NI infrastructure 2020-02-21 18:22:59 +03:00
Mikhail Zarechenskiy
05d42b5eb5 Fix construction of Mock classes in case of generic inner types
This fixes testMissingDependencyConflictingLibraries for NI and also
 fixes changed test for OI as well
2020-02-21 18:22:52 +03:00
Mikhail Zarechenskiy
819ef8853d [NI] Don't stop on a candidate with unstable smartcast error
#KT-36847 Fixed
2020-02-21 18:22:47 +03:00
Mikhail Zarechenskiy
e06dc1a8bc [NI] Add test to check how behavior will be changed after few commits 2020-02-21 18:22:39 +03:00
Mikhail Zarechenskiy
85ed149572 [NI] Fix isSuccessful property for member with LowPriority resolution
The problem was introduced in e40ba73950
2020-02-21 18:22:26 +03:00
Konstantin Tskhovrebov
dd9d5c43c8 Fix class name for test suite descriptor.
Issue #KT-36725 Fixed
Issue #KT-36716 Fixed
Issue #KT-36726 Fixed
2020-02-21 14:40:53 +03:00
Ilya Goncharov
38f84127f6 [Gradle, JS] Fix DSL for Gradle JS wizard
(cherry picked from commit e631146fa7)
2020-02-21 14:36:49 +03:00
Ilya Goncharov
7331339bc7 [Gradle, JS] Fix DSL for JVM/JS wizard
#KT-36889 fixed

(cherry picked from commit 3ae6b27556)
2020-02-21 14:36:48 +03:00
Sergey Igushkin
34153c8a86 Update Kotlin/Native version to 1.4-dev-14516
(latest K/N build before `1.4.0` diverged)
2020-02-20 19:02:19 +03:00
Sergey Igushkin
9ae091c9b2 Fix KT-36804 by eagerly instantiating the Kotlin/Native tasks
This commit partially reverts 970ee4539b.

The Kotlin/Native klib compilation task configuration logic involved
adding dependencies for the compiler plugin artifacts. However, the
compiler plugins classpath, shared across all of the K/N tasks, was
tracked as the tasks' input. This made the following scenario possible:

1. Configuration of some of the Kotlin/Native tasks is avoided at the
   evaluation phase;

2. During task graph construction, one of the tasks are evaluated, and
   to determine their dependencies, Gradle resolves their inputs,
   including the compiler plugins classpath mentioned above;

3. Another K/N task is evaluated afterwards, and the configuration logic
   attempts to add a dependency into the compiler plugin classpath
   configuration, which has already been resolved in (2).
   The build fails.

Fix this by cancelling task configuration avoidance for the K/N tasks.

Issue #KT-36804 Fixed
2020-02-18 17:06:31 +03:00
Abduqodiri Qurbonzoda
4eb775343e Mark shared global vals to fix K/N worker thread crash
(cherry picked from commit 5a4ce2aa4c)
2020-02-18 12:19:52 +03:00
Ilya Goncharov
4ffb0af20f [Gradle, JS] Provide js compilations parameters to link tasks
#KT-36796 fixed

(cherry picked from commit 9f0ef77531)
2020-02-18 09:36:40 +03:00
Dmitry Savvinov
fc4a6add74 Force-set path to exact project for MPP run configurations
Otherwise, path will be set to the root project. Given that we provide
task names in relative form rather than absolute, that will lead to
launching this task in all subprojects (e.g. task 'jvmTest'). This might
be a huge issue, because when we create run configuration for specific
test method/class, we pass test filter as well. This test filter will
execute in all projects with matched test tasks, so if some other
subproject has similarly-named test task, but doesn't have a suitable
tests for that filter, the whole build will fail.

Note that the ideal fix would involve using fully-qualified task names:
the current approach might lead to isses in advanced scenarious (e.g.
when user selects several test files from different modules -- then, we
won't be able to find one exact project path for the whole test run)

^KT-35038 Fixed
2020-02-17 20:21:53 +03:00
Dmitry Savvinov
eb25a429e2 Add test on multiplatform run configurations in multiproject build
The current behaviour is undesired, see next commit for fix
2020-02-17 20:21:52 +03:00
Dmitry Savvinov
58fd43e613 Add ability to render project of run configuration in tests 2020-02-17 20:21:52 +03:00
436 changed files with 8637 additions and 11973 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -8,7 +8,7 @@ buildscript {
extra["defaultSnapshotVersion"] = "1.4-SNAPSHOT"
val cacheRedirectorEnabled = findProperty("cacheRedirectorEnabled")?.toString()?.toBoolean() == true
kotlinBootstrapFrom(BootstrapOption.BintrayBootstrap("1.4.0-dev-1075", cacheRedirectorEnabled))
kotlinBootstrapFrom(BootstrapOption.BintrayBootstrap("1.4.0-dev-1818", cacheRedirectorEnabled))
repositories {
bootstrapKotlinRepo?.let(::maven)
@@ -179,7 +179,7 @@ extra["versions.r8"] = "1.5.70"
extra["versions.ktor-network"] = "1.0.1"
if (!project.hasProperty("versions.kotlin-native")) {
extra["versions.kotlin-native"] = "1.4-dev-14287"
extra["versions.kotlin-native"] = "1.4-M1"
}
val intellijUltimateEnabled by extra(project.kotlinBuildProperties.intellijUltimateEnabled)

View File

@@ -41,7 +41,7 @@ public class AndroidJpsBuildTestCase extends BaseKotlinJpsBuildTestCase {
}
@Override
protected void runTest() throws Throwable {
protected void runTest() {
doTest();
}

View File

@@ -65,10 +65,14 @@ class CommonResolverForModuleFactory(
override val name: Name,
override val capabilities: Map<ModuleDescriptor.Capability<*>, Any?>,
private val dependencies: Iterable<ModuleInfo>,
override val expectedBy: List<ModuleInfo>,
private val modulesWhoseInternalsAreVisible: Collection<ModuleInfo>,
private val dependOnOldBuiltIns: Boolean
) : ModuleInfo {
override fun dependencies() = listOf(this, *dependencies.toList().toTypedArray() )
override fun modulesWhoseInternalsAreVisible(): Collection<ModuleInfo> = modulesWhoseInternalsAreVisible
override fun dependencyOnBuiltIns(): ModuleInfo.DependencyOnBuiltIns =
if (dependOnOldBuiltIns) ModuleInfo.DependencyOnBuiltIns.LAST else ModuleInfo.DependencyOnBuiltIns.NONE
@@ -123,6 +127,8 @@ class CommonResolverForModuleFactory(
moduleName,
capabilities,
dependenciesContainer?.moduleInfos?.toList().orEmpty(),
dependenciesContainer?.refinesModuleInfos.orEmpty(),
dependenciesContainer?.friendModuleInfos.orEmpty(),
dependOnBuiltIns
)
val project = files.firstOrNull()?.project ?: throw AssertionError("No files to analyze")
@@ -150,7 +156,8 @@ class CommonResolverForModuleFactory(
GlobalSearchScope.allScope(project),
languageVersionSettings = multiplatformLanguageSettings,
syntheticFiles = files,
dependencyModules = dependenciesContainer?.moduleInfos ?: emptyList()
knownDependencyModuleDescriptors = dependenciesContainer?.moduleInfos
?.associateWith(dependenciesContainer::moduleDescriptorForModuleInfo).orEmpty()
)
val moduleDescriptor = resolver.descriptorForModule(moduleInfo)
@@ -167,7 +174,11 @@ class CommonResolverForModuleFactory(
interface CommonDependenciesContainer {
val moduleInfos: List<ModuleInfo>
fun moduleDescriptorForModuleInfo(moduleInfo: ModuleInfo): ModuleDescriptor
fun packageFragmentProviderForModuleInfo(moduleInfo: ModuleInfo): PackageFragmentProvider?
val friendModuleInfos: List<ModuleInfo>
val refinesModuleInfos: List<ModuleInfo>
}
private fun createContainerToResolveCommonCode(

View File

@@ -1,21 +1,13 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.cli.common.arguments
import org.jetbrains.kotlin.cli.common.arguments.DevModeOverwritingStrategies.ALL
import org.jetbrains.kotlin.cli.common.arguments.DevModeOverwritingStrategies.OLDER
class K2JSDceArguments : CommonToolArguments() {
companion object {
@JvmStatic private val serialVersionUID = 0L
@@ -48,4 +40,16 @@ class K2JSDceArguments : CommonToolArguments() {
)
@GradleOption(DefaultValues.BooleanFalseDefault::class)
var devMode: Boolean by FreezableVar(false)
@Argument(
value = "-Xdev-mode-overwriting-strategy",
valueDescription = "{$OLDER|$ALL}",
description = "Overwriting strategy during copy dependencies in development mode"
)
var devModeOverwritingStrategy: String? by NullableStringFreezableVar(null)
}
object DevModeOverwritingStrategies {
const val OLDER = "older"
const val ALL = "all"
}

View File

@@ -40,4 +40,18 @@ class K2MetadataCompilerArguments : CommonCompilerArguments() {
description = "Enable in JPS"
)
var enabledInJps: Boolean by FreezableVar(false)
@Argument(
value = "-Xfriend-paths",
valueDescription = "<path>",
description = "Paths to output directories for friend modules (whose internals should be visible)"
)
var friendPaths: Array<String>? by FreezableVar(null)
@Argument(
value = "-Xfriend-paths",
valueDescription = "<path>",
description = "Paths to output directories for friend modules (whose internals should be visible)"
)
var refinesPaths: Array<String>? by FreezableVar(null)
}

View File

@@ -52,7 +52,9 @@ fun buildConfiguration(environment: KotlinCoreEnvironment, moduleName: String):
return runtimeConfiguration
}
val environment = KotlinCoreEnvironment.createForTests(Disposable { }, CompilerConfiguration(), EnvironmentConfigFiles.JS_CONFIG_FILES)
@Suppress("RedundantSamConstructor")
private val environment =
KotlinCoreEnvironment.createForProduction(Disposable { }, CompilerConfiguration(), EnvironmentConfigFiles.JS_CONFIG_FILES)
fun createPsiFile(fileName: String): KtFile {
val psiManager = PsiManager.getInstance(environment.project)

View File

@@ -0,0 +1,38 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.cli.js
import org.jetbrains.kotlin.config.*
class JSLanguageVersionSettings(private val delegate: LanguageVersionSettings) : LanguageVersionSettings {
companion object {
private val disabledFeatures = setOf(
LanguageFeature.NewInference,
LanguageFeature.FunctionalInterfaceConversion,
LanguageFeature.SamConversionForKotlinFunctions,
LanguageFeature.SamConversionPerArgument,
LanguageFeature.FunctionReferenceWithDefaultValueAsOtherType,
LanguageFeature.NonStrictOnlyInputTypesChecks
)
}
override fun getFeatureSupport(feature: LanguageFeature): LanguageFeature.State {
return if (feature in disabledFeatures)
LanguageFeature.State.DISABLED
else
delegate.getFeatureSupport(feature)
}
override fun isPreRelease(): Boolean = delegate.isPreRelease()
override fun <T> getFlag(flag: AnalysisFlag<T>): T = delegate.getFlag(flag)
override val apiVersion: ApiVersion
get() = delegate.apiVersion
override val languageVersion: LanguageVersion
get() = delegate.languageVersion
}

View File

@@ -246,6 +246,13 @@ public class K2JSCompiler extends CLICompiler<K2JSCompilerArguments> {
configuration.put(CommonConfigurationKeys.MODULE_NAME, FileUtil.getNameWithoutExtension(outputFile));
if (!arguments.getNewInference()) {
CommonConfigurationKeysKt.setLanguageVersionSettings(
configuration,
new JSLanguageVersionSettings(CommonConfigurationKeysKt.getLanguageVersionSettings(configuration))
);
}
JsConfig config = new JsConfig(project, configuration);
JsConfig.Reporter reporter = new JsConfig.Reporter() {
@Override

View File

@@ -24,10 +24,7 @@ import org.jetbrains.kotlin.cli.common.messages.MessageUtil
import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.cli.jvm.plugins.PluginCliParser
import org.jetbrains.kotlin.config.CommonConfigurationKeys
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.IncrementalCompilation
import org.jetbrains.kotlin.config.Services
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.incremental.components.ExpectActualTracker
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.incremental.js.IncrementalDataProvider

View File

@@ -1,23 +1,13 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.cli.js.dce
import org.jetbrains.kotlin.cli.common.CLITool
import org.jetbrains.kotlin.cli.common.ExitCode
import org.jetbrains.kotlin.cli.common.arguments.DevModeOverwritingStrategies
import org.jetbrains.kotlin.cli.common.arguments.K2JSDceArguments
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
@@ -63,7 +53,13 @@ class K2JSDce : CLITool<K2JSDceArguments>() {
return if (!arguments.devMode) {
performDce(files, arguments, messageCollector)
} else {
copyFiles(files)
val devModeOverwritingStrategy =
arguments.devModeOverwritingStrategy ?:
System.getProperty("kotlin.js.dce.devmode.overwriting.strategy", DevModeOverwritingStrategies.OLDER)
val overwriteOnlyOlderFiles = devModeOverwritingStrategy == DevModeOverwritingStrategies.OLDER
copyFiles(files, overwriteOnlyOlderFiles)
ExitCode.OK
}
}
@@ -96,21 +92,22 @@ class K2JSDce : CLITool<K2JSDceArguments>() {
return ExitCode.OK
}
private fun copyFiles(files: List<InputFile>) {
private fun copyFiles(files: List<InputFile>, overwriteOnlyOlderFiles: Boolean) {
for (file in files) {
copyResource(file.resource, File(file.outputPath))
copyResource(file.resource, File(file.outputPath), overwriteOnlyOlderFiles)
file.sourceMapResource?.let { sourceMap ->
val sourceMapTarget = File(file.outputPath + ".map")
val inputFile = File(sourceMap.name)
if (!inputFile.exists() || !mapSourcePaths(inputFile, sourceMapTarget)) {
copyResource(sourceMap, sourceMapTarget)
copyResource(sourceMap, sourceMapTarget, overwriteOnlyOlderFiles)
}
}
}
}
private fun copyResource(resource: InputResource, targetFile: File) {
if (targetFile.exists() && resource.lastModified() < targetFile.lastModified()) return
private fun copyResource(resource: InputResource, targetFile: File, overwriteOnlyOlderFiles: Boolean) {
// TODO shouldn't it be "<="?
if (overwriteOnlyOlderFiles && targetFile.exists() && resource.lastModified() < targetFile.lastModified()) return
targetFile.parentFile.mkdirs()
resource.reader().use { input ->

View File

@@ -25,6 +25,7 @@ import org.jetbrains.kotlin.cli.common.messages.*
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.INFO
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.STRONG_WARNING
import org.jetbrains.kotlin.cli.jvm.compiler.CompileEnvironmentException
import org.jetbrains.kotlin.cli.jvm.compiler.setupIdeaStandaloneExecution
import org.jetbrains.kotlin.config.KotlinCompilerVersion
import org.jetbrains.kotlin.config.LanguageFeature.Kind.BUG_FIX
import org.jetbrains.kotlin.config.LanguageFeature.State.ENABLED
@@ -204,6 +205,9 @@ abstract class CLITool<A : CommonToolArguments> {
if (System.getProperty(PlainTextMessageRenderer.KOTLIN_COLORS_ENABLED_PROPERTY) == null) {
System.setProperty(PlainTextMessageRenderer.KOTLIN_COLORS_ENABLED_PROPERTY, "true")
}
setupIdeaStandaloneExecution()
val exitCode = doMainNoExit(compiler, args)
if (exitCode != ExitCode.OK) {
exitProcess(exitCode.code)

View File

@@ -421,6 +421,7 @@ class KotlinCoreEnvironment private constructor(
fun createForProduction(
parentDisposable: Disposable, configuration: CompilerConfiguration, configFiles: EnvironmentConfigFiles
): KotlinCoreEnvironment {
setupIdeaStandaloneExecution()
val appEnv = getOrCreateApplicationEnvironmentForProduction(parentDisposable, configuration)
val projectEnv = ProjectEnvironment(parentDisposable, appEnv)
val environment = KotlinCoreEnvironment(projectEnv, configuration, configFiles)

View File

@@ -0,0 +1,62 @@
/*
* 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.cli.jvm.compiler
import com.intellij.codeInsight.ExternalAnnotationsManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
class MockExternalAnnotationsManager : ExternalAnnotationsManager() {
override fun chooseAnnotationsPlace(element: PsiElement): AnnotationPlace = AnnotationPlace.NOWHERE
override fun chooseAnnotationsPlaceNoUi(element: PsiElement): AnnotationPlace = AnnotationPlace.NOWHERE
override fun isExternalAnnotationWritable(listOwner: PsiModifierListOwner, annotationFQN: String): Boolean = false
override fun isExternalAnnotation(annotation: PsiAnnotation): Boolean = false
override fun findExternalAnnotationsFiles(listOwner: PsiModifierListOwner): List<PsiFile>? = null
override fun findExternalAnnotation(listOwner: PsiModifierListOwner, annotationFQN: String): PsiAnnotation? = null
override fun findExternalAnnotations(listOwner: PsiModifierListOwner): Array<out PsiAnnotation>? = null
override fun annotateExternally(
listOwner: PsiModifierListOwner,
annotationFQName: String,
fromFile: PsiFile,
value: Array<out PsiNameValuePair>?
) {
throw UnsupportedOperationException("not implemented")
}
override fun deannotate(listOwner: PsiModifierListOwner, annotationFQN: String): Boolean {
throw UnsupportedOperationException("not implemented")
}
override fun editExternalAnnotation(
listOwner: PsiModifierListOwner,
annotationFQN: String,
value: Array<out PsiNameValuePair>?
): Boolean {
throw UnsupportedOperationException("not implemented")
}
override fun hasAnnotationRootsForFile(file: VirtualFile): Boolean = false
override fun findDefaultConstructorExternalAnnotations(aClass: PsiClass, annotationFQN: String): List<PsiAnnotation> = emptyList()
override fun findDefaultConstructorExternalAnnotations(aClass: PsiClass): List<PsiAnnotation> = emptyList()
override fun findExternalAnnotations(listOwner: PsiModifierListOwner, annotationFQN: String): List<PsiAnnotation> = emptyList()
}

View File

@@ -0,0 +1,9 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.cli.jvm.compiler
fun setupIdeaStandaloneExecution() {
}

View File

@@ -0,0 +1,14 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.cli.jvm.compiler
fun setupIdeaStandaloneExecution() {
System.getProperties().setProperty("idea.home.path", System.getProperty("java.io.tmpdir"))
System.getProperties().setProperty("project.structure.add.tools.jar.to.new.jdk", "false")
System.getProperties().setProperty("psi.track.invalidation", "true")
System.getProperties().setProperty("psi.incremental.reparse.depth.limit", "1000")
System.getProperties().setProperty("ide.hide.excluded.files", "false")
}

View File

@@ -0,0 +1,13 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.cli.jvm.config
import org.jetbrains.kotlin.config.CompilerConfigurationKey
object K2MetadataConfigurationKeys {
val FRIEND_PATHS = CompilerConfigurationKey.create<List<String>>("friend module paths")
val REFINES_PATHS = CompilerConfigurationKey.create<List<String>>("refined module paths")
}

View File

@@ -25,6 +25,7 @@ import org.jetbrains.kotlin.cli.common.messages.MessageUtil
import org.jetbrains.kotlin.cli.common.messages.OutputMessageUtil
import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.cli.jvm.config.K2MetadataConfigurationKeys
import org.jetbrains.kotlin.cli.jvm.config.addJvmClasspathRoots
import org.jetbrains.kotlin.cli.jvm.plugins.PluginCliParser
import org.jetbrains.kotlin.codegen.CompilationException
@@ -73,6 +74,10 @@ class K2MetadataCompiler : CLICompiler<K2MetadataCompilerArguments>() {
configuration.put(CLIConfigurationKeys.ALLOW_KOTLIN_PACKAGE, arguments.allowKotlinPackage)
configuration.putIfNotNull(K2MetadataConfigurationKeys.FRIEND_PATHS, arguments.friendPaths?.toList())
configuration.putIfNotNull(K2MetadataConfigurationKeys.REFINES_PATHS, arguments.refinesPaths?.toList())
val destination = arguments.destination
if (destination != null) {
if (destination.endsWith(".jar")) {

View File

@@ -5,7 +5,7 @@
package org.jetbrains.kotlin.cli.metadata
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.analyzer.*
import org.jetbrains.kotlin.analyzer.common.CommonDependenciesContainer
import org.jetbrains.kotlin.analyzer.common.CommonPlatformAnalyzerServices
import org.jetbrains.kotlin.backend.common.serialization.metadata.KlibMetadataMonolithicSerializer
@@ -15,6 +15,7 @@ import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.cli.jvm.config.JvmClasspathRoot
import org.jetbrains.kotlin.cli.jvm.config.JvmContentRoot
import org.jetbrains.kotlin.cli.jvm.config.K2MetadataConfigurationKeys
import org.jetbrains.kotlin.config.CommonConfigurationKeys
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.KotlinCompilerVersion
@@ -25,6 +26,7 @@ import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl
import org.jetbrains.kotlin.descriptors.konan.DeserializedKlibModuleOrigin
import org.jetbrains.kotlin.konan.util.KlibMetadataFactories
import org.jetbrains.kotlin.library.*
import org.jetbrains.kotlin.library.impl.BuiltInsPlatform
import org.jetbrains.kotlin.library.impl.buildKoltinLibrary
import org.jetbrains.kotlin.library.impl.createKotlinLibraryComponents
import org.jetbrains.kotlin.library.metadata.parseModuleHeader
@@ -88,7 +90,8 @@ internal class K2MetadataKlibSerializer(private val metadataVersion: BuiltInsBin
configuration[CommonConfigurationKeys.MODULE_NAME]!!,
nopack = true,
manifestProperties = null,
dataFlowGraph = null
dataFlowGraph = null,
builtInsPlatform = BuiltInsPlatform.COMMON
)
}
}
@@ -109,6 +112,9 @@ private class KlibMetadataDependencyContainer(
klibFiles.map { resolveSingleFileKlib(org.jetbrains.kotlin.konan.file.File(it.absolutePath)) }
}
private val friendPaths = configuration.get(K2MetadataConfigurationKeys.FRIEND_PATHS).orEmpty().toSet()
private val refinesPaths = configuration.get(K2MetadataConfigurationKeys.REFINES_PATHS).orEmpty().toSet()
private val builtIns
get() = DefaultBuiltIns.Instance
@@ -144,7 +150,7 @@ private class KlibMetadataDependencyContainer(
}
}
override val moduleInfos: List<ModuleInfo> = mutableListOf<KlibModuleInfo>().apply {
private val moduleInfosImpl: List<KlibModuleInfo> = mutableListOf<KlibModuleInfo>().apply {
addAll(
moduleDescriptorsForKotlinLibraries.map { (kotlinLibrary, moduleDescriptor) ->
KlibModuleInfo(moduleDescriptor.name, kotlinLibrary, this@apply)
@@ -152,6 +158,28 @@ private class KlibMetadataDependencyContainer(
)
}
override val moduleInfos: List<ModuleInfo> get() = moduleInfosImpl
override val friendModuleInfos: List<ModuleInfo> = moduleInfosImpl.filter {
it.kotlinLibrary.libraryFile.absolutePath in friendPaths
}
override val refinesModuleInfos: List<ModuleInfo> = moduleInfosImpl.filter {
it.kotlinLibrary.libraryFile.absolutePath in refinesPaths
}
override fun moduleDescriptorForModuleInfo(moduleInfo: ModuleInfo): ModuleDescriptor {
if (moduleInfo !in moduleInfos)
error("Unknown module info $moduleInfo")
moduleInfo as KlibModuleInfo
// Ensure that the package fragment provider has been created and the module descriptor has been
// initialized with the package fragment provider:
packageFragmentProviderForModuleInfo(moduleInfo)
return moduleDescriptorsForKotlinLibraries.getValue(moduleInfo.kotlinLibrary)
}
override fun packageFragmentProviderForModuleInfo(
moduleInfo: ModuleInfo
): PackageFragmentProvider? {

View File

@@ -1842,6 +1842,11 @@ public class Fir2IrTextTestGenerated extends AbstractFir2IrTextTest {
runTest("compiler/testData/ir/irText/types/genericPropertyReferenceType.kt");
}
@TestMetadata("inStarProjectionInReceiverType.kt")
public void testInStarProjectionInReceiverType() throws Exception {
runTest("compiler/testData/ir/irText/types/inStarProjectionInReceiverType.kt");
}
@TestMetadata("intersectionType1_NI.kt")
public void testIntersectionType1_NI() throws Exception {
runTest("compiler/testData/ir/irText/types/intersectionType1_NI.kt");
@@ -1872,6 +1877,11 @@ public class Fir2IrTextTestGenerated extends AbstractFir2IrTextTest {
runTest("compiler/testData/ir/irText/types/intersectionType3_OI.kt");
}
@TestMetadata("kt36143.kt")
public void testKt36143() throws Exception {
runTest("compiler/testData/ir/irText/types/kt36143.kt");
}
@TestMetadata("localVariableOfIntersectionType_NI.kt")
public void testLocalVariableOfIntersectionType_NI() throws Exception {
runTest("compiler/testData/ir/irText/types/localVariableOfIntersectionType_NI.kt");
@@ -1892,6 +1902,11 @@ public class Fir2IrTextTestGenerated extends AbstractFir2IrTextTest {
runTest("compiler/testData/ir/irText/types/smartCastOnReceiverOfGenericType.kt");
}
@TestMetadata("starProjection_OI.kt")
public void testStarProjection_OI() throws Exception {
runTest("compiler/testData/ir/irText/types/starProjection_OI.kt");
}
@TestMetadata("compiler/testData/ir/irText/types/nullChecks")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)

View File

@@ -9896,6 +9896,11 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirOldFronte
runTest("compiler/testData/diagnostics/tests/inference/conflictingSubstitutions.kt");
}
@TestMetadata("cstFromErrorAndNonErrorTypes.kt")
public void testCstFromErrorAndNonErrorTypes() throws Exception {
runTest("compiler/testData/diagnostics/tests/inference/cstFromErrorAndNonErrorTypes.kt");
}
@TestMetadata("dependOnExpectedType.kt")
public void testDependOnExpectedType() throws Exception {
runTest("compiler/testData/diagnostics/tests/inference/dependOnExpectedType.kt");
@@ -10096,6 +10101,11 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirOldFronte
runTest("compiler/testData/diagnostics/tests/inference/kt35702.kt");
}
@TestMetadata("kt36819.kt")
public void testKt36819() throws Exception {
runTest("compiler/testData/diagnostics/tests/inference/kt36819.kt");
}
@TestMetadata("kt6175.kt")
public void testKt6175() throws Exception {
runTest("compiler/testData/diagnostics/tests/inference/kt6175.kt");
@@ -21205,6 +21215,11 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirOldFronte
public void testSmartCastOnReceiver() throws Exception {
runTest("compiler/testData/diagnostics/tests/smartCasts/inference/smartCastOnReceiver.kt");
}
@TestMetadata("stabilityOfSmartcastsAgainstGenericFunctions.kt")
public void testStabilityOfSmartcastsAgainstGenericFunctions() throws Exception {
runTest("compiler/testData/diagnostics/tests/smartCasts/inference/stabilityOfSmartcastsAgainstGenericFunctions.kt");
}
}
@TestMetadata("compiler/testData/diagnostics/tests/smartCasts/intersectionScope")

View File

@@ -1360,6 +1360,11 @@ public class FirOldFrontendDiagnosticsTestWithStdlibGenerated extends AbstractFi
runTest("compiler/testData/diagnostics/testsWithStdLib/contracts/smartcasts/extensionReceiver_after.kt");
}
@TestMetadata("externalArguments.kt")
public void testExternalArguments() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/contracts/smartcasts/externalArguments.kt");
}
@TestMetadata("intersectingInfo.kt")
public void testIntersectingInfo() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/contracts/smartcasts/intersectingInfo.kt");
@@ -1508,6 +1513,11 @@ public class FirOldFrontendDiagnosticsTestWithStdlibGenerated extends AbstractFi
KotlinTestUtils.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/diagnostics/testsWithStdLib/contracts/smartcasts/when"), Pattern.compile("^(.+)\\.kt$"), Pattern.compile("^(.+)\\.fir\\.kts?$"), true);
}
@TestMetadata("kt36818.kt")
public void testKt36818() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/contracts/smartcasts/when/kt36818.kt");
}
@TestMetadata("withSubject.kt")
public void testWithSubject() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/contracts/smartcasts/when/withSubject.kt");
@@ -1908,6 +1918,11 @@ public class FirOldFrontendDiagnosticsTestWithStdlibGenerated extends AbstractFi
KotlinTestUtils.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/diagnostics/testsWithStdLib/inference/annotationsForResolve"), Pattern.compile("^(.+)\\.kt$"), Pattern.compile("^(.+)\\.fir\\.kts?$"), true);
}
@TestMetadata("checkLowPriorityIsResolvedSuccessfully.kt")
public void testCheckLowPriorityIsResolvedSuccessfully() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/inference/annotationsForResolve/checkLowPriorityIsResolvedSuccessfully.kt");
}
@TestMetadata("exactAnnotation.kt")
public void testExactAnnotation() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/inference/annotationsForResolve/exactAnnotation.kt");

View File

@@ -39,10 +39,11 @@ class RuntimeAssertionInfo(val needNotNullAssertion: Boolean, val message: Strin
}
companion object {
@JvmStatic fun create(
expectedType: KotlinType,
expressionType: KotlinType,
dataFlowExtras: DataFlowExtras
@JvmStatic
fun create(
expectedType: KotlinType,
expressionType: KotlinType,
dataFlowExtras: DataFlowExtras
): RuntimeAssertionInfo? {
fun assertNotNull(): Boolean {
if (expectedType.isError || expressionType.isError) return false
@@ -81,9 +82,9 @@ private val KtExpression.textForRuntimeAssertionInfo
get() = StringUtil.trimMiddle(text, 50)
class RuntimeAssertionsDataFlowExtras(
private val c: ResolutionContext<*>,
private val expressionType: KotlinType,
private val expression: KtExpression
private val c: ResolutionContext<*>,
private val expressionType: KotlinType,
private val expression: KtExpression
) : RuntimeAssertionInfo.DataFlowExtras {
private val dataFlowValue by lazy(LazyThreadSafetyMode.PUBLICATION) {
c.dataFlowValueFactory.createDataFlowValue(expression, expressionType, c)
@@ -96,13 +97,18 @@ class RuntimeAssertionsDataFlowExtras(
}
object RuntimeAssertionsTypeChecker : AdditionalTypeChecker {
override fun checkType(expression: KtExpression, expressionType: KotlinType, expressionTypeWithSmartCast: KotlinType, c: ResolutionContext<*>) {
if (TypeUtils.noExpectedType(c.expectedType)) return
override fun checkType(
expression: KtExpression,
expressionType: KotlinType,
expressionTypeWithSmartCast: KotlinType,
c: ResolutionContext<*>
) {
if (TypeUtils.noExpectedType(c.expectedType) || c.expectedType is StubType) return
val assertionInfo = RuntimeAssertionInfo.create(
c.expectedType,
expressionType,
RuntimeAssertionsDataFlowExtras(c, expressionType, expression)
c.expectedType,
expressionType,
RuntimeAssertionsDataFlowExtras(c, expressionType, expression)
)
if (assertionInfo != null) {
@@ -127,9 +133,9 @@ object RuntimeAssertionsOnExtensionReceiverCallChecker : CallChecker {
val c = context.resolutionContext
val assertionInfo = RuntimeAssertionInfo.create(
receiverParameter.type,
receiverValue.type,
RuntimeAssertionsDataFlowExtras(c, receiverValue.type, receiverExpression)
receiverParameter.type,
receiverValue.type,
RuntimeAssertionsDataFlowExtras(c, receiverValue.type, receiverExpression)
)
if (assertionInfo != null) {
@@ -141,10 +147,10 @@ object RuntimeAssertionsOnExtensionReceiverCallChecker : CallChecker {
object RuntimeAssertionsOnDeclarationBodyChecker {
@JvmStatic
fun check(
declaration: KtDeclaration,
descriptor: DeclarationDescriptor,
bindingTrace: BindingTrace,
languageVersionSettings: LanguageVersionSettings
declaration: KtDeclaration,
descriptor: DeclarationDescriptor,
bindingTrace: BindingTrace,
languageVersionSettings: LanguageVersionSettings
) {
if (!languageVersionSettings.supportsFeature(LanguageFeature.StrictJavaNullabilityAssertions)) return
@@ -161,9 +167,9 @@ object RuntimeAssertionsOnDeclarationBodyChecker {
}
private fun checkLocalVariable(
declaration: KtProperty,
descriptor: VariableDescriptor,
bindingTrace: BindingTrace
declaration: KtProperty,
descriptor: VariableDescriptor,
bindingTrace: BindingTrace
) {
if (declaration.typeReference != null) return
@@ -171,20 +177,23 @@ object RuntimeAssertionsOnDeclarationBodyChecker {
}
private fun checkFunction(
declaration: KtFunction,
descriptor: FunctionDescriptor,
bindingTrace: BindingTrace
declaration: KtFunction,
descriptor: FunctionDescriptor,
bindingTrace: BindingTrace
) {
if (declaration.typeReference != null || declaration.hasBlockBody()) return
checkNullabilityAssertion(declaration.bodyExpression ?: return, descriptor.returnType ?: return,
bindingTrace)
checkNullabilityAssertion(
declaration.bodyExpression ?: return,
descriptor.returnType ?: return,
bindingTrace
)
}
private fun checkProperty(
declaration: KtProperty,
descriptor: PropertyDescriptor,
bindingTrace: BindingTrace
declaration: KtProperty,
descriptor: PropertyDescriptor,
bindingTrace: BindingTrace
) {
if (declaration.typeReference != null) return
@@ -195,21 +204,24 @@ object RuntimeAssertionsOnDeclarationBodyChecker {
}
private fun checkPropertyAccessor(
declaration: KtPropertyAccessor,
descriptor: PropertyAccessorDescriptor,
bindingTrace: BindingTrace
declaration: KtPropertyAccessor,
descriptor: PropertyAccessorDescriptor,
bindingTrace: BindingTrace
) {
if (declaration.property.typeReference != null || declaration.hasBlockBody()) return
checkNullabilityAssertion(declaration.bodyExpression ?: return, descriptor.correspondingProperty.type,
bindingTrace)
checkNullabilityAssertion(
declaration.bodyExpression ?: return,
descriptor.correspondingProperty.type,
bindingTrace
)
}
private fun checkNullabilityAssertion(
expression: KtExpression,
declarationType: KotlinType,
bindingTrace: BindingTrace
expression: KtExpression,
declarationType: KotlinType,
bindingTrace: BindingTrace
) {
if (declarationType.unwrap().canContainNull()) return
@@ -219,9 +231,9 @@ object RuntimeAssertionsOnDeclarationBodyChecker {
if (!expressionType.hasEnhancedNullability()) return
bindingTrace.record(
JvmBindingContextSlices.BODY_RUNTIME_ASSERTION_INFO,
expression,
RuntimeAssertionInfo(true, expression.textForRuntimeAssertionInfo)
JvmBindingContextSlices.BODY_RUNTIME_ASSERTION_INFO,
expression,
RuntimeAssertionInfo(true, expression.textForRuntimeAssertionInfo)
)
}

View File

@@ -19,12 +19,12 @@ abstract class AbstractResolverForProject<M : ModuleInfo>(
private val debugName: String,
protected val projectContext: ProjectContext,
modules: Collection<M>,
private val fallbackModificationTracker: ModificationTracker? = null,
protected val fallbackModificationTracker: ModificationTracker? = null,
private val delegateResolver: ResolverForProject<M> = EmptyResolverForProject(),
private val packageOracleFactory: PackageOracleFactory = PackageOracleFactory.OptimisticFactory
) : ResolverForProject<M>() {
private class ModuleData(
protected class ModuleData(
val moduleDescriptor: ModuleDescriptorImpl,
val modificationTracker: ModificationTracker?
) {
@@ -37,7 +37,7 @@ abstract class AbstractResolverForProject<M : ModuleInfo>(
}
// Protected by ("projectContext.storageManager.lock")
private val descriptorByModule = mutableMapOf<M, ModuleData>()
protected val descriptorByModule = mutableMapOf<M, ModuleData>()
// Protected by ("projectContext.storageManager.lock")
private val moduleInfoByDescriptor = mutableMapOf<ModuleDescriptorImpl, M>()

View File

@@ -26,17 +26,26 @@ class ResolverForSingleModuleProject<M : ModuleInfo>(
private val languageVersionSettings: LanguageVersionSettings = LanguageVersionSettingsImpl.DEFAULT,
private val syntheticFiles: Collection<KtFile> = emptyList(),
private val sdkDependency: M? = null,
dependencyModules: Iterable<M> = emptyList()
knownDependencyModuleDescriptors: Map<M, ModuleDescriptor> = emptyMap()
) : AbstractResolverForProject<M>(
debugName,
projectContext,
listOf(module) + dependencyModules,
listOf(module) + knownDependencyModuleDescriptors.keys,
null,
EmptyResolverForProject(),
PackageOracleFactory.OptimisticFactory
) {
override fun sdkDependency(module: M): M? = sdkDependency
init {
knownDependencyModuleDescriptors.forEach { (module, descriptor) ->
descriptorByModule[module] = ModuleData(
descriptor as ModuleDescriptorImpl,
(module as? TrackableModuleInfo)?.createModificationTracker() ?: fallbackModificationTracker
)
}
}
override fun modulesContent(module: M): ModuleContent<M> = when (module) {
this.module -> ModuleContent(module, syntheticFiles, searchScope)
else -> ModuleContent(module, emptyList(), searchScope)

View File

@@ -17,6 +17,8 @@
package org.jetbrains.kotlin.diagnostics;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.diagnostics.rendering.DiagnosticRenderer;
import java.util.Arrays;
import java.util.Collection;
@@ -26,6 +28,8 @@ public abstract class DiagnosticFactory<D extends Diagnostic> {
private String name = null;
private final Severity severity;
private DiagnosticRenderer<D> defaultRenderer;
protected DiagnosticFactory(@NotNull Severity severity) {
this.severity = severity;
}
@@ -49,6 +53,15 @@ public abstract class DiagnosticFactory<D extends Diagnostic> {
return severity;
}
@Nullable
public DiagnosticRenderer<D> getDefaultRenderer() {
return defaultRenderer;
}
void setDefaultRenderer(@Nullable DiagnosticRenderer<D> defaultRenderer) {
this.defaultRenderer = defaultRenderer;
}
@NotNull
@SuppressWarnings("unchecked")
public D cast(@NotNull Diagnostic diagnostic) {

View File

@@ -16,6 +16,9 @@ import org.jetbrains.kotlin.config.LanguageVersion;
import org.jetbrains.kotlin.config.LanguageVersionSettings;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.diagnostics.rendering.DeclarationWithDiagnosticComponents;
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages;
import org.jetbrains.kotlin.diagnostics.rendering.DiagnosticFactoryToRendererMap;
import org.jetbrains.kotlin.diagnostics.rendering.DiagnosticRenderer;
import org.jetbrains.kotlin.lexer.KtKeywordToken;
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken;
import org.jetbrains.kotlin.lexer.KtTokens;
@@ -1156,6 +1159,14 @@ public interface Errors {
}
public static void initializeFactoryNames(@NotNull Class<?> aClass) {
initializeFactoryNamesAndDefaultErrorMessages(aClass, DiagnosticFactoryToRendererMap::new);
}
public static void initializeFactoryNamesAndDefaultErrorMessages(
@NotNull Class<?> aClass,
@NotNull DefaultErrorMessages.Extension defaultErrorMessages
) {
DiagnosticFactoryToRendererMap diagnosticToRendererMap = defaultErrorMessages.getMap();
for (Field field : aClass.getFields()) {
if (Modifier.isStatic(field.getModifiers())) {
try {
@@ -1163,6 +1174,9 @@ public interface Errors {
if (value instanceof DiagnosticFactory) {
DiagnosticFactory<?> factory = (DiagnosticFactory<?>)value;
factory.setName(field.getName());
//noinspection rawtypes, unchecked
factory.setDefaultRenderer((DiagnosticRenderer) diagnosticToRendererMap.get(factory));
}
}
catch (IllegalAccessException e) {
@@ -1170,6 +1184,7 @@ public interface Errors {
}
}
}
}
private static final Initializer INSTANCE = new Initializer();

View File

@@ -167,10 +167,17 @@ inline fun <reified T : KtDeclaration> reportOnDeclarationAs(
} ?: throw AssertionError("No declaration for $descriptor")
}
// this method should not be used in the project, but it is leaved for some time for compatibility with old compiler plugins
@Deprecated(
"Please register DefaultErrorMessages.Extension in moment of DiagnosticFactory initialization by calling " +
"initializeFactoryNamesAndDefaultErrorMessages method instead of initializeFactoryNames",
ReplaceWith("report(diagnostic)"),
level = DeprecationLevel.ERROR
)
fun <D : Diagnostic> DiagnosticSink.reportFromPlugin(diagnostic: D, ext: DefaultErrorMessages.Extension) {
@Suppress("UNCHECKED_CAST")
val renderer = ext.map[diagnostic.factory] as? DiagnosticRenderer<D>
?: error("Renderer not found for diagnostic ${diagnostic.factory.name}")
?: error("Renderer not found for diagnostic ${diagnostic.factory.name}")
val renderedDiagnostic = RenderedDiagnostic(diagnostic, renderer)

View File

@@ -56,7 +56,11 @@ public class DefaultErrorMessages {
@Nullable
public static DiagnosticRenderer getRendererForDiagnostic(@NotNull Diagnostic diagnostic) {
return AddToStdlibKt.firstNotNullResult(RENDERER_MAPS, map -> map.get(diagnostic.getFactory()));
DiagnosticRenderer<?> renderer = AddToStdlibKt.firstNotNullResult(RENDERER_MAPS, map -> map.get(diagnostic.getFactory()));
if (renderer != null)
return renderer;
else
return diagnostic.getFactory().getDefaultRenderer();
}
static {

View File

@@ -12,7 +12,9 @@ import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.calls.CallResolver
import org.jetbrains.kotlin.resolve.calls.CandidateResolver
import org.jetbrains.kotlin.resolve.calls.KotlinCallResolver
import org.jetbrains.kotlin.resolve.calls.context.BasicCallResolutionContext
import org.jetbrains.kotlin.resolve.calls.model.CallResolutionResult
import org.jetbrains.kotlin.resolve.calls.tasks.TracingStrategy
import org.jetbrains.kotlin.resolve.calls.tower.ImplicitScopeTower
import org.jetbrains.kotlin.resolve.calls.tower.NewResolutionOldInference
@@ -30,10 +32,28 @@ class CandidateInterceptor(project: Project) {
name: Name,
kind: NewResolutionOldInference.ResolutionKind,
tracing: TracingStrategy
) = extensions.fold(candidates) { it, extension ->
): Collection<NewResolutionOldInference.MyCandidate> = extensions.fold(candidates) { it, extension ->
extension.interceptCandidates(it, context, candidateResolver, callResolver, name, kind, tracing)
}
fun interceptResolvedCandidates(
callResolutionResult: CallResolutionResult,
context: BasicCallResolutionContext,
callResolver: KotlinCallResolver,
name: Name,
kind: NewResolutionOldInference.ResolutionKind,
tracing: TracingStrategy
): CallResolutionResult {
var resolutionResult = callResolutionResult
for (extension in extensions) {
resolutionResult = extension.interceptCandidates(
resolutionResult, context, callResolver, name, kind, tracing
)
}
return resolutionResult
}
fun interceptCandidates(
candidates: Collection<FunctionDescriptor>,
scopeTower: ImplicitScopeTower,

View File

@@ -13,7 +13,9 @@ import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.resolve.calls.CallResolver
import org.jetbrains.kotlin.resolve.calls.CandidateResolver
import org.jetbrains.kotlin.resolve.calls.KotlinCallResolver
import org.jetbrains.kotlin.resolve.calls.context.BasicCallResolutionContext
import org.jetbrains.kotlin.resolve.calls.model.CallResolutionResult
import org.jetbrains.kotlin.resolve.calls.tasks.TracingStrategy
import org.jetbrains.kotlin.resolve.calls.tower.ImplicitScopeTower
import org.jetbrains.kotlin.resolve.calls.tower.NewResolutionOldInference
@@ -58,6 +60,16 @@ interface CallResolutionInterceptorExtension {
tracing: TracingStrategy
): Collection<NewResolutionOldInference.MyCandidate> = candidates
@JvmDefault
fun interceptCandidates(
callResolutionResult: CallResolutionResult,
context: BasicCallResolutionContext,
callResolver: KotlinCallResolver,
name: Name,
kind: NewResolutionOldInference.ResolutionKind,
tracing: TracingStrategy
): CallResolutionResult = callResolutionResult
fun interceptCandidates(
candidates: Collection<FunctionDescriptor>,
scopeTower: ImplicitScopeTower,

View File

@@ -125,9 +125,7 @@ class MainFunctionDetector {
if (typeArguments.size != 1) return false
val typeArgument = typeArguments[0].type
if (!(languageVersionSettings.supportsFeature(LanguageFeature.AllowNullableArrayArgsInMain) &&
KotlinBuiltIns.isStringOrNullableString(typeArgument) || KotlinBuiltIns.isString(typeArgument))
) {
if (!KotlinBuiltIns.isString(typeArgument)) {
return false
}
if (typeArguments[0].projectionKind === Variance.IN_VARIANCE) {

View File

@@ -17,6 +17,7 @@
package org.jetbrains.kotlin.resolve;
import com.google.common.collect.Maps;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.util.containers.Queue;
@@ -196,6 +197,8 @@ public class BodyResolver {
Set<ConstructorDescriptor> visitedInCurrentChain = new HashSet<>();
ConstructorDescriptor currentConstructorDescriptor = constructorDescriptor;
while (true) {
ProgressManager.checkCanceled();
visitedInCurrentChain.add(currentConstructorDescriptor);
ConstructorDescriptor delegatedConstructorDescriptor = getDelegatedConstructor(currentConstructorDescriptor);
if (delegatedConstructorDescriptor == null) break;
@@ -267,6 +270,8 @@ public class BodyResolver {
@NotNull LexicalScope scopeForConstructorResolution,
@NotNull LexicalScope scopeForMemberResolution
) {
ProgressManager.checkCanceled();
LexicalScope scopeForConstructor =
primaryConstructor == null
? null
@@ -399,6 +404,8 @@ public class BodyResolver {
}
for (KtSuperTypeListEntry delegationSpecifier : ktClass.getSuperTypeListEntries()) {
ProgressManager.checkCanceled();
delegationSpecifier.accept(visitor);
}
@@ -657,6 +664,8 @@ public class BodyResolver {
@NotNull KtAnonymousInitializer anonymousInitializer,
@NotNull ClassDescriptorWithResolutionScopes classDescriptor
) {
ProgressManager.checkCanceled();
LexicalScope scopeForInitializers = classDescriptor.getScopeForInitializerResolution();
KtExpression body = anonymousInitializer.getBody();
if (body != null) {
@@ -935,6 +944,8 @@ public class BodyResolver {
// Creates wrapper scope for header resolution if necessary (see resolveSecondaryConstructorBody)
@Nullable Function1<LexicalScope, LexicalScope> headerScopeFactory
) {
ProgressManager.checkCanceled();
PreliminaryDeclarationVisitor.Companion.createForDeclaration(function, trace, languageVersionSettings);
LexicalScope innerScope = FunctionDescriptorUtil.getFunctionInnerScope(scope, functionDescriptor, trace, overloadChecker);
List<KtParameter> valueParameters = function.getValueParameters();

View File

@@ -5,6 +5,7 @@
package org.jetbrains.kotlin.resolve;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -270,6 +271,7 @@ public class ModifiersChecker {
missingSupertypesResolver
);
for (DeclarationChecker checker : declarationCheckers) {
ProgressManager.checkCanceled();
checker.check(declaration, descriptor, context);
}
OperatorModifierChecker.INSTANCE.check(declaration, descriptor, trace, languageVersionSettings);

View File

@@ -304,23 +304,31 @@ class CallExpressionResolver(
private fun KtQualifiedExpression.elementChain(context: ExpressionTypingContext) =
qualifiedExpressionResolver.resolveQualifierInExpressionAndUnroll(this, context) { nameExpression ->
val resolutionResult = resolveSimpleName(context, nameExpression)
val temporaryTraceAndCache =
TemporaryTraceAndCache.create(context, "trace to resolve as local variable or property", nameExpression)
val resolutionResult = resolveSimpleName(context, nameExpression, temporaryTraceAndCache)
if (resolutionResult.isSingleResult && resolutionResult.resultingDescriptor is FakeCallableDescriptorForObject) {
false
} else when (resolutionResult.resultCode) {
NAME_NOT_FOUND, CANDIDATES_WITH_WRONG_RECEIVER -> false
else -> !context.languageVersionSettings.supportsFeature(LanguageFeature.NewInference) || resolutionResult.isSuccess
else -> {
val newInferenceEnabled = context.languageVersionSettings.supportsFeature(LanguageFeature.NewInference)
val success = !newInferenceEnabled || resolutionResult.isSuccess
if (newInferenceEnabled && success) {
temporaryTraceAndCache.commit()
}
success
}
}
}
private fun resolveSimpleName(
context: ExpressionTypingContext, expression: KtSimpleNameExpression
context: ExpressionTypingContext, expression: KtSimpleNameExpression, traceAndCache: TemporaryTraceAndCache
): OverloadResolutionResults<VariableDescriptor> {
val temporaryForVariable = TemporaryTraceAndCache.create(context, "trace to resolve as local variable or property", expression)
val call = CallMaker.makePropertyCall(null, null, expression)
val contextForVariable = BasicCallResolutionContext.create(
context.replaceTraceAndCache(temporaryForVariable), call, CheckArgumentTypesMode.CHECK_VALUE_ARGUMENTS
context.replaceTraceAndCache(traceAndCache), call, CheckArgumentTypesMode.CHECK_VALUE_ARGUMENTS
)
return callResolver.resolveSimpleProperty(contextForVariable)
}

View File

@@ -251,10 +251,12 @@ class DiagnosticReporterByTrackingStrategy(
)
val dataFlowValue = dataFlowValueFactory.createDataFlowValue(expressionArgument.receiver.receiverValue, context)
val call = if (call.callElement is KtBinaryExpression) null else call
smartCastManager.checkAndRecordPossibleCast(
dataFlowValue, smartCastDiagnostic.smartCastType, argumentExpression, context, call,
recordExpressionType = false
)
if (!expressionArgument.valueArgument.isExternal()) {
smartCastManager.checkAndRecordPossibleCast(
dataFlowValue, smartCastDiagnostic.smartCastType, argumentExpression, context, call,
recordExpressionType = false
)
} else null
}
is ReceiverExpressionKotlinCallArgument -> {
trace.markAsReported()

View File

@@ -28,6 +28,7 @@ import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.expressions.DoubleColonExpressionResolver
import org.jetbrains.kotlin.types.expressions.ExpressionTypingServices
import org.jetbrains.kotlin.types.typeUtil.contains
import org.jetbrains.kotlin.utils.addToStdlib.cast
class CoroutineInferenceSession(
@@ -52,9 +53,13 @@ class CoroutineInferenceSession(
) {
private val commonCalls = arrayListOf<PSICompletedCallInfo>()
private val diagnostics = arrayListOf<KotlinCallDiagnostic>()
private var hasInapplicableCall = false
override fun shouldRunCompletion(candidate: KotlinResolutionCandidate): Boolean {
val system = candidate.getSystem() as NewConstraintSystemImpl
if (system.hasContradiction) return true
val storage = system.getBuilder().currentStorage()
fun ResolvedAtom.hasPostponed(): Boolean {
if (this is PostponedResolvedAtom && !analyzed) return true
@@ -75,26 +80,40 @@ class CoroutineInferenceSession(
commonCalls.add(callInfo)
val resultingDescriptor = callInfo.resolvedCall.resultingDescriptor
// This check is similar to one for old inference, see getCoroutineInferenceData() function
val checkCall = resultingDescriptor is LocalVariableDescriptor || anyReceiverContainStubType(resultingDescriptor)
if (!checkCall) return
val isApplicableCall =
callComponents.statelessCallbacks.isApplicableCallForBuilderInference(
callInfo.resolvedCall.resultingDescriptor,
resultingDescriptor,
callComponents.languageVersionSettings
)
if (!isApplicableCall) {
diagnostics.add(NonApplicableCallForBuilderInferenceDiagnostic(callInfo.callResolutionResult.resultCallAtom.atom))
hasInapplicableCall = true
}
}
private fun anyReceiverContainStubType(descriptor: CallableDescriptor): Boolean {
return descriptor.dispatchReceiverParameter?.type?.contains { it is StubType } == true ||
descriptor.extensionReceiverParameter?.type?.contains { it is StubType } == true
}
fun hasInapplicableCall(): Boolean = hasInapplicableCall
override fun writeOnlyStubs(callInfo: SingleCallResolutionResult): Boolean {
return !skipCall(callInfo)
}
private fun skipCall(callInfo: SingleCallResolutionResult): Boolean {
// FakeCallableDescriptorForObject and LocalVariableDescriptor can't introduce new information for inference,
// FakeCallableDescriptorForObject can't introduce new information for inference,
// so it's safe to complete it fully
val descriptor = callInfo.resultCallAtom.candidateDescriptor
return descriptor is FakeCallableDescriptorForObject || descriptor is LocalVariableDescriptor
return descriptor is FakeCallableDescriptorForObject
}
override fun currentConstraintSystem(): ConstraintStorage {
@@ -105,8 +124,12 @@ class CoroutineInferenceSession(
lambda: ResolvedLambdaAtom,
initialStorage: ConstraintStorage,
diagnosticsHolder: KotlinDiagnosticsHolder
): Map<TypeConstructor, UnwrappedType> {
val commonSystem = buildCommonSystem(initialStorage)
): Map<TypeConstructor, UnwrappedType>? {
val (commonSystem, effectivelyEmptyConstraintSystem) = buildCommonSystem(initialStorage)
if (effectivelyEmptyConstraintSystem) {
updateCalls(lambda, commonSystem)
return null
}
val context = commonSystem.asConstraintSystemCompleterContext()
kotlinConstraintSystemCompleter.completeConstraintSystem(
@@ -137,7 +160,7 @@ class CoroutineInferenceSession(
storage: ConstraintStorage,
nonFixedToVariablesSubstitutor: NewTypeSubstitutor,
shouldIntegrateAllConstraints: Boolean
) {
): Boolean {
storage.notFixedTypeVariables.values.forEach { commonSystem.registerVariable(it.typeVariable) }
/*
@@ -149,12 +172,16 @@ class CoroutineInferenceSession(
* */
val callSubstitutor = storage.buildResultingSubstitutor(commonSystem, transformTypeVariablesToErrorTypes = false)
var introducedConstraint = false
for (initialConstraint in storage.initialConstraints) {
val lower = nonFixedToVariablesSubstitutor.safeSubstitute(callSubstitutor.safeSubstitute(initialConstraint.a as UnwrappedType)) // TODO: SUB
val upper = nonFixedToVariablesSubstitutor.safeSubstitute(callSubstitutor.safeSubstitute(initialConstraint.b as UnwrappedType)) // TODO: SUB
if (commonSystem.isProperType(lower) && commonSystem.isProperType(upper)) continue
introducedConstraint = true
when (initialConstraint.constraintKind) {
ConstraintKind.LOWER -> error("LOWER constraint shouldn't be used, please use UPPER")
@@ -173,28 +200,38 @@ class CoroutineInferenceSession(
val typeVariable = storage.allTypeVariables.getValue(variableConstructor)
commonSystem.registerVariable(typeVariable)
commonSystem.addEqualityConstraint((typeVariable as NewTypeVariable).defaultType, type, CoroutinePosition())
introducedConstraint = true
}
}
return introducedConstraint
}
private fun buildCommonSystem(initialStorage: ConstraintStorage): NewConstraintSystemImpl {
private fun buildCommonSystem(initialStorage: ConstraintStorage): Pair<NewConstraintSystemImpl, Boolean> {
val commonSystem = NewConstraintSystemImpl(callComponents.constraintInjector, builtIns)
val nonFixedToVariablesSubstitutor = createNonFixedTypeToVariableSubstitutor()
integrateConstraints(commonSystem, initialStorage, nonFixedToVariablesSubstitutor, false)
var effectivelyEmptyCommonSystem = true
for (call in commonCalls) {
integrateConstraints(commonSystem, call.callResolutionResult.constraintSystem, nonFixedToVariablesSubstitutor, false)
val hasConstraints =
integrateConstraints(commonSystem, call.callResolutionResult.constraintSystem, nonFixedToVariablesSubstitutor, false)
if (hasConstraints) effectivelyEmptyCommonSystem = false
}
for (call in partiallyResolvedCallsInfo) {
integrateConstraints(commonSystem, call.callResolutionResult.constraintSystem, nonFixedToVariablesSubstitutor, true)
val hasConstraints =
integrateConstraints(commonSystem, call.callResolutionResult.constraintSystem, nonFixedToVariablesSubstitutor, true)
if (hasConstraints) effectivelyEmptyCommonSystem = false
}
for (diagnostic in diagnostics) {
commonSystem.addError(diagnostic)
}
return commonSystem
return commonSystem to effectivelyEmptyCommonSystem
}
private fun updateCalls(lambda: ResolvedLambdaAtom, commonSystem: NewConstraintSystemImpl) {
@@ -281,9 +318,8 @@ class CoroutineInferenceSession(
class ComposedSubstitutor(val left: NewTypeSubstitutor, val right: NewTypeSubstitutor) : NewTypeSubstitutor {
override fun substituteNotNullTypeWithConstructor(constructor: TypeConstructor): UnwrappedType? {
return left.substituteNotNullTypeWithConstructor(
right.substituteNotNullTypeWithConstructor(constructor)?.constructor ?: constructor
)
val rightSubstitution = right.substituteNotNullTypeWithConstructor(constructor)
return left.substituteNotNullTypeWithConstructor(rightSubstitution?.constructor ?: constructor) ?: rightSubstitution
}
override val isEmpty: Boolean get() = left.isEmpty && right.isEmpty

View File

@@ -130,7 +130,7 @@ class KotlinResolutionCallbacksImpl(
return createSimplePSICallArgument(
trace.bindingContext, outerCallContext.statementFilter, outerCallContext.scope.ownerDescriptor,
CallMaker.makeExternalValueArgument(ktExpression), DataFlowInfo.EMPTY, typeInfo, languageVersionSettings,
dataFlowValueFactory
dataFlowValueFactory, outerCallContext.call
)
}
@@ -139,8 +139,6 @@ class KotlinResolutionCallbacksImpl(
if (expectedReturnType == null) ContextDependency.DEPENDENT else ContextDependency.INDEPENDENT
)
trace.record(BindingContext.NEW_INFERENCE_LAMBDA_INFO, psiCallArgument.ktFunction, lambdaInfo)
val builtIns = outerCallContext.scope.ownerDescriptor.builtIns
// We have to refine receiverType because resolve inside lambda needs proper scope from receiver,
@@ -179,8 +177,16 @@ class KotlinResolutionCallbacksImpl(
null
}
val temporaryTrace = if (coroutineSession != null)
TemporaryBindingTrace.create(trace, "Trace to resolve coroutine $lambdaArgument")
else
null
(temporaryTrace ?: trace).record(BindingContext.NEW_INFERENCE_LAMBDA_INFO, psiCallArgument.ktFunction, lambdaInfo)
val actualContext = outerCallContext
.replaceBindingTrace(trace)
.replaceBindingTrace(temporaryTrace ?: trace)
.replaceContextDependency(lambdaInfo.contextDependency)
.replaceExpectedType(approximatesExpectedType)
.replaceDataFlowInfo(psiCallArgument.dataFlowInfoBeforeThisArgument).let {
@@ -188,7 +194,13 @@ class KotlinResolutionCallbacksImpl(
}
val functionTypeInfo = expressionTypingServices.getTypeInfo(psiCallArgument.expression, actualContext)
trace.record(BindingContext.NEW_INFERENCE_LAMBDA_INFO, psiCallArgument.ktFunction, LambdaInfo.STUB_EMPTY)
(temporaryTrace ?: trace).record(BindingContext.NEW_INFERENCE_LAMBDA_INFO, psiCallArgument.ktFunction, LambdaInfo.STUB_EMPTY)
if (coroutineSession?.hasInapplicableCall() == true) {
return ReturnArgumentsAnalysisResult(ReturnArgumentsInfo.empty, coroutineSession, hasInapplicableCallForBuilderInference = true)
} else {
temporaryTrace?.commit()
}
var hasReturnWithoutExpression = false
var returnArgumentFound = false

View File

@@ -318,13 +318,15 @@ class KotlinToResolvedCallTransformer(
)
}
updateRecordedType(
argumentExpression,
parameter,
newContext,
constantConvertedArgument?.unknownIntegerType?.unwrap(),
resolvedCall.isReallySuccess()
)
if (!valueArgument.isExternal()) {
updateRecordedType(
argumentExpression,
parameter,
newContext,
constantConvertedArgument?.unknownIntegerType?.unwrap(),
resolvedCall.isReallySuccess()
)
}
}
}

View File

@@ -303,7 +303,8 @@ internal fun createSimplePSICallArgument(
contextForArgument.scope.ownerDescriptor, valueArgument,
contextForArgument.dataFlowInfo, typeInfoForArgument,
contextForArgument.languageVersionSettings,
contextForArgument.dataFlowValueFactory
contextForArgument.dataFlowValueFactory,
contextForArgument.call,
)
internal fun createSimplePSICallArgument(
@@ -314,7 +315,8 @@ internal fun createSimplePSICallArgument(
dataFlowInfoBeforeThisArgument: DataFlowInfo,
typeInfoForArgument: KotlinTypeInfo,
languageVersionSettings: LanguageVersionSettings,
dataFlowValueFactory: DataFlowValueFactory
dataFlowValueFactory: DataFlowValueFactory,
call: Call
): SimplePSIKotlinCallArgument? {
val ktExpression = KtPsiUtil.getLastElementDeparenthesized(valueArgument.getArgumentExpression(), statementFilter) ?: return null
@@ -331,10 +333,10 @@ internal fun createSimplePSICallArgument(
// so we use a fast-path here to avoid calling transformToReceiverWithSmartCastInfo function
ReceiverValueWithSmartCastInfo(expressionReceiver, emptySet(), isStable = true)
} else {
val useDataFlowInfoBeforeArgument = call.callType == Call.CallType.CONTAINS
transformToReceiverWithSmartCastInfo(
ownerDescriptor, bindingContext,
// dataFlowInfoBeforeThisArgument cannot be used here, because of if() { if (x != null) return; x }
typeInfoForArgument.dataFlowInfo,
if (useDataFlowInfoBeforeArgument) dataFlowInfoBeforeThisArgument else typeInfoForArgument.dataFlowInfo,
expressionReceiver,
languageVersionSettings,
dataFlowValueFactory

View File

@@ -109,6 +109,10 @@ class PSICallResolver(
return OverloadResolutionResultsImpl.nameNotFound()
}
result = candidateInterceptor.interceptResolvedCandidates(
result, context, kotlinCallResolver, name, resolutionKind, tracingStrategy
)
val overloadResolutionResults = convertToOverloadResolutionResults<D>(context, result, tracingStrategy)
return overloadResolutionResults.also {
clearCacheForApproximationResults()

View File

@@ -77,6 +77,7 @@ class ResolvedAtomCompleter(
is ResolvedCallableReferenceAtom -> completeCallableReference(resolvedAtom)
is ResolvedLambdaAtom -> completeLambda(resolvedAtom)
is ResolvedCallAtom -> completeResolvedCall(resolvedAtom, emptyList())
is ResolvedSubCallArgument -> completeSubCallArgument(resolvedAtom)
is PartialCallResolutionResult -> completeResolvedCall(resolvedAtom.resultCallAtom, resolvedAtom.diagnostics)
}
}
@@ -90,6 +91,17 @@ class ResolvedAtomCompleter(
complete(resolvedAtom)
}
fun completeSubCallArgument(resolvedSubCallArgument: ResolvedSubCallArgument) {
val contextWithoutExpectedType = topLevelCallContext.replaceExpectedType(TypeUtils.NO_EXPECTED_TYPE)
kotlinToResolvedCallTransformer.updateRecordedType(
resolvedSubCallArgument.atom.psiExpression ?: return,
parameter = null,
context = contextWithoutExpectedType,
reportErrorForTypeMismatch = true,
convertedArgumentType = null
)
}
fun completeResolvedCall(resolvedCallAtom: ResolvedCallAtom, diagnostics: Collection<KotlinCallDiagnostic>): ResolvedCall<*>? {
clearPartiallyResolvedCall(resolvedCallAtom)

View File

@@ -17,6 +17,7 @@
package org.jetbrains.kotlin.resolve.lazy;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.descriptors.*;
@@ -70,6 +71,8 @@ public class ForceResolveUtil {
}
private static void doForceResolveAllContents(Object object) {
ProgressManager.checkCanceled();
if (object instanceof LazyEntity) {
LazyEntity lazyEntity = (LazyEntity) object;
lazyEntity.forceResolveAllContents();

View File

@@ -1402,9 +1402,14 @@ public class BasicExpressionTypingVisitor extends ExpressionTypingVisitor {
ExpressionReceiver receiver = safeGetExpressionReceiver(facade, right, contextWithNoExpectedType);
ExpressionTypingContext contextWithDataFlow = context.replaceDataFlowInfo(dataFlowInfo);
Call containsCall = CallMaker.makeCall(
callElement, receiver, null, operationSign,
Collections.singletonList(leftArgument), Call.CallType.CONTAINS
);
OverloadResolutionResults<FunctionDescriptor> resolutionResult = components.callResolver.resolveCallWithGivenName(
contextWithDataFlow,
CallMaker.makeCall(callElement, receiver, null, operationSign, Collections.singletonList(leftArgument)),
containsCall,
operationSign,
OperatorNameConventions.CONTAINS);
KotlinType containsType = OverloadResolutionResultsUtil.getResultingType(resolutionResult, context);

View File

@@ -5,6 +5,7 @@
package org.jetbrains.kotlin.types.expressions;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -303,6 +304,7 @@ public class ExpressionTypingServices {
boolean isFirstStatement = true;
for (Iterator<? extends KtElement> iterator = block.iterator(); iterator.hasNext(); ) {
ProgressManager.checkCanceled();
// Use filtering trace to keep effect system cache only for one statement
AbstractFilteringTrace traceForSingleStatement = new EffectsFilteringTrace(context.trace);

View File

@@ -7,6 +7,7 @@ package org.jetbrains.kotlin.types.expressions;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.IndexNotReadyException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -159,6 +160,7 @@ public abstract class ExpressionTypingVisitorDispatcher extends KtVisitor<Kotlin
@NotNull
private KotlinTypeInfo getTypeInfo(@NotNull KtExpression expression, ExpressionTypingContext context, KtVisitor<KotlinTypeInfo, ExpressionTypingContext> visitor) {
ProgressManager.checkCanceled();
return typeInfoPerfCounter.time(() -> {
try {
KotlinTypeInfo recordedTypeInfo = BindingContextUtils.getRecordedTypeInfo(expression, context.trace.getBindingContext());

View File

@@ -26,7 +26,7 @@ dependencies {
testCompile(intellijDep()) { includeJars("log4j", "jdom") }
if (Platform.P192.orHigher()) {
testRuntime(intellijDep()) { includeJars("lz4-java-1.6.0") }
testRuntime(intellijDep()) { includeJars("lz4-java", rootProject = rootProject) }
} else {
testRuntime(intellijDep()) { includeJars("lz4-1.3.0") }
}

View File

@@ -81,7 +81,7 @@ class NullableFieldsDeclarationLowering(val backendContext: CommonBackendContext
getter.body = IrBlockBodyImpl(startOffset, endOffset) {
val irBuilder = backendContext.createIrBuilder(getter.symbol, startOffset, endOffset)
irBuilder.run {
val resultVar = scope.createTemporaryVariable(
val resultVar = scope.createTmpVariable(
irGetField(getter.dispatchReceiverParameter?.let { irGet(it) }, backingField)
)
resultVar.parent = getter

View File

@@ -86,7 +86,7 @@ class ReturnableBlockTransformer(val context: CommonBackendContext, val containe
val scopeSymbol = currentScope?.scope?.scopeOwnerSymbol ?: containerSymbol
val builder = context.createIrBuilder(scopeSymbol!!)
val variable by lazy {
builder.scope.createTemporaryVariableDeclaration(expression.type, "tmp\$ret\$${labelCnt++}", true)
builder.scope.createTmpVariable(expression.type, "tmp\$ret\$${labelCnt++}", true)
}
val loop by lazy {

View File

@@ -17,6 +17,7 @@
package org.jetbrains.kotlin.ir.builders
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin
import org.jetbrains.kotlin.ir.declarations.IrVariable
import org.jetbrains.kotlin.ir.declarations.impl.IrVariableImpl
@@ -56,6 +57,34 @@ fun <T : IrElement> IrStatementsBuilder<T>.createTmpVariable(
return variable
}
fun Scope.createTmpVariable(
irType: IrType,
nameHint: String? = null,
isMutable: Boolean = false,
initializer: IrExpression? = null,
origin: IrDeclarationOrigin = IrDeclarationOrigin.IR_TEMPORARY_VARIABLE,
startOffset: Int = UNDEFINED_OFFSET,
endOffset: Int = UNDEFINED_OFFSET
): IrVariable {
val descriptor = WrappedVariableDescriptor()
val symbol = IrVariableSymbolImpl(descriptor)
return IrVariableImpl(
startOffset,
endOffset,
origin,
symbol,
Name.identifier(nameHint ?: "tmp"),
irType,
isMutable,
isConst = false,
isLateinit = false
).apply {
this.initializer = initializer
parent = getLocalDeclarationParent()
descriptor.bind(this)
}
}
fun Scope.createTmpVariable(
irExpression: IrExpression,
nameHint: String? = null,

View File

@@ -96,7 +96,7 @@ class JsIntrinsics(private val irBuiltIns: IrBuiltIns, val context: JsIrBackendC
// Type checks:
val jsInstanceOf = binOpBool("jsInstanceOf")
val jsTypeOf = unOp("jsTypeOf", irBuiltIns.stringType)
val jsTypeOf = getInternalFunction("jsTypeOf")
// Number conversions:

View File

@@ -57,10 +57,11 @@ fun compile(
loadIr(project, mainModule, analyzer, configuration, allDependencies, friendDependencies)
// TODO: not sure whether this check should be enabled by default. Add configuration key for it.
val mangleChecker = ManglerChecker(JsManglerIr, Ir2DescriptorManglerAdapter(JsManglerDesc))
moduleFragment.acceptVoid(mangleChecker)
irBuiltIns.knownBuiltins.forEach { it.acceptVoid(mangleChecker) }
if (mainModule is MainModule.SourceFiles) {
val mangleChecker = ManglerChecker(JsManglerIr, Ir2DescriptorManglerAdapter(JsManglerDesc))
moduleFragment.acceptVoid(mangleChecker)
irBuiltIns.knownBuiltins.forEach { it.acceptVoid(mangleChecker) }
}
val moduleDescriptor = moduleFragment.descriptor

View File

@@ -151,9 +151,10 @@ class ClassReferenceLowering(val context: JsIrBackendContext) : BodyLoweringPass
private fun createSimpleKType(type: IrSimpleType): IrExpression {
val classifier: IrClassifierSymbol = type.classifier
if (classifier is IrTypeParameterSymbol && classifier.owner.isReified) {
error("Fail")
}
// TODO: Check why do we have un-substituted reified parameters
// if (classifier is IrTypeParameterSymbol && classifier.owner.isReified) {
// error("Fail")
// }
val kClassifier = createKClassifier(classifier)
// TODO: Use static array types
@@ -206,9 +207,11 @@ class ClassReferenceLowering(val context: JsIrBackendContext) : BodyLoweringPass
Variance.IN_VARIANCE -> JsIrBuilder.buildString(context.irBuiltIns.stringType, "in")
Variance.OUT_VARIANCE -> JsIrBuilder.buildString(context.irBuiltIns.stringType, "out")
}
if (typeParameter.isReified) {
error("Reified parameter")
}
// TODO: Check why do we have non-inlined reified parameters
// if (typeParameter.isReified) {
// error("Reified parameter")
// }
return buildCall(
context.intrinsics.createKTypeParameter!!,

View File

@@ -343,8 +343,7 @@ class EnumEntryInstancesLowering(val context: JsIrBackendContext) : DeclarationT
isStatic = true
}.apply {
parent = irClass
val builder = context.createIrBuilder(irClass.symbol)
initializer = builder.run { irExprBody(irImplicitCast(irNull(), type)) }
initializer = null
}
enumEntry.correspondingField = result
@@ -407,8 +406,7 @@ class EnumClassCreateInitializerLowering(val context: JsIrBackendContext) : Decl
isStatic = true
}.apply {
parent = irClass
val builder = context.createIrBuilder(irClass.symbol)
initializer = builder.run { irExprBody(irBoolean(false)) }
initializer = null
}
private fun createInitEntryInstancesFun(irClass: IrClass, entryInstancesInitializedField: IrField): IrSimpleFunction =

View File

@@ -91,6 +91,14 @@ class IrElementToJsExpressionTransformer : BaseIrElementToJsNodeTransformer<JsEx
val obj = expression.symbol.owner
assert(obj.kind == ClassKind.OBJECT)
assert(obj.isEffectivelyExternal()) { "Non external IrGetObjectValue must be lowered" }
// External interfaces cannot normally have companion objects.
// However, stdlib uses them to simulate string literal unions
// TODO: Stop abusing this tech
if (obj.isCompanion && obj.parentAsClass.isInterface) {
return JsNullLiteral()
}
return context.getRefForExternalClass(obj)
}

View File

@@ -370,7 +370,7 @@ class NameTables(
declaration !is IrDeclarationWithName ->
return
declaration.isEffectivelyExternal() ->
declaration.isEffectivelyExternal() && (declaration.getJsModule() == null || declaration.isJsNonModule()) ->
globalNames.declareStableName(declaration, declaration.getJsNameOrKotlinName().identifier)
else ->

View File

@@ -62,7 +62,7 @@ class Psi2IrTranslator(
symbolTable: SymbolTable = SymbolTable(signaturer),
extensions: GeneratorExtensions = GeneratorExtensions()
): GeneratorContext =
GeneratorContext(configuration, moduleDescriptor, bindingContext, languageVersionSettings, symbolTable, extensions, signaturer)
createGeneratorContext(configuration, moduleDescriptor, bindingContext, languageVersionSettings, symbolTable, extensions, signaturer)
fun generateModuleFragment(
context: GeneratorContext,
@@ -73,8 +73,8 @@ class Psi2IrTranslator(
val moduleGenerator = ModuleGenerator(context)
val irModule = moduleGenerator.generateModuleFragmentWithoutDependencies(ktFiles)
expectDescriptorToSymbol?.let { referenceExpectsForUsedActuals(it, context.symbolTable, irModule) }
irModule.patchDeclarationParents()
expectDescriptorToSymbol?.let { referenceExpectsForUsedActuals(it, context.symbolTable, irModule) }
postprocess(context, irModule)
// do not generate unbound symbols before postprocessing,
// since plugins must work with non-lazy IR

View File

@@ -56,7 +56,13 @@ fun StatementGenerator.generateReceiver(ktDefaultElement: KtElement, receiver: R
generateReceiver(ktDefaultElement.startOffsetSkippingComments, ktDefaultElement.endOffset, receiver)
fun StatementGenerator.generateReceiver(defaultStartOffset: Int, defaultEndOffset: Int, receiver: ReceiverValue): IntermediateValue {
val irReceiverType = receiver.type.toIrType()
val irReceiverType =
when (receiver) {
is ExtensionReceiver ->
receiver.declarationDescriptor.extensionReceiverParameter!!.type.toIrType()
else ->
receiver.type.toIrType()
}
if (receiver is TransientReceiver) return TransientReceiverValue(irReceiverType)

View File

@@ -1,17 +1,6 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.psi2ir.generators
@@ -24,12 +13,41 @@ import org.jetbrains.kotlin.descriptors.NotFoundClasses
import org.jetbrains.kotlin.ir.builders.IrGeneratorContext
import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns
import org.jetbrains.kotlin.ir.expressions.IrMemberAccessExpression
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.ir.util.ConstantValueGenerator
import org.jetbrains.kotlin.ir.util.IdSignatureComposer
import org.jetbrains.kotlin.ir.util.SymbolTable
import org.jetbrains.kotlin.ir.util.TypeTranslator
import org.jetbrains.kotlin.psi2ir.Psi2IrConfiguration
import org.jetbrains.kotlin.psi2ir.PsiSourceManager
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.storage.LockBasedStorageManager
fun createGeneratorContext(
configuration: Psi2IrConfiguration,
moduleDescriptor: ModuleDescriptor,
bindingContext: BindingContext,
languageVersionSettings: LanguageVersionSettings,
symbolTable: SymbolTable,
extensions: GeneratorExtensions,
signaturer: IdSignatureComposer
): GeneratorContext {
val typeTranslator = TypeTranslator(symbolTable, languageVersionSettings, builtIns = moduleDescriptor.builtIns)
val constantValueGenerator = ConstantValueGenerator(moduleDescriptor, symbolTable)
typeTranslator.constantValueGenerator = constantValueGenerator
constantValueGenerator.typeTranslator = typeTranslator
return GeneratorContext(
configuration,
moduleDescriptor,
bindingContext,
languageVersionSettings,
symbolTable,
extensions,
typeTranslator,
constantValueGenerator,
IrBuiltIns(moduleDescriptor.builtIns, typeTranslator, signaturer, symbolTable)
)
}
class GeneratorContext(
val configuration: Psi2IrConfiguration,
val moduleDescriptor: ModuleDescriptor,
@@ -37,20 +55,13 @@ class GeneratorContext(
val languageVersionSettings: LanguageVersionSettings,
val symbolTable: SymbolTable,
val extensions: GeneratorExtensions,
signaturer: IdSignatureComposer
val typeTranslator: TypeTranslator,
val constantValueGenerator: ConstantValueGenerator,
override val irBuiltIns: IrBuiltIns
) : IrGeneratorContext() {
val constantValueGenerator: ConstantValueGenerator = ConstantValueGenerator(moduleDescriptor, symbolTable)
val typeTranslator: TypeTranslator = TypeTranslator(symbolTable, languageVersionSettings, builtIns = moduleDescriptor.builtIns)
val callToSubstitutedDescriptorMap = mutableMapOf<IrMemberAccessExpression, CallableDescriptor>()
init {
typeTranslator.constantValueGenerator = constantValueGenerator
constantValueGenerator.typeTranslator = typeTranslator
}
override val irBuiltIns: IrBuiltIns = IrBuiltIns(moduleDescriptor.builtIns, typeTranslator, signaturer, symbolTable)
val sourceManager = PsiSourceManager()
// TODO: inject a correct StorageManager instance, or store NotFoundClasses inside ModuleDescriptor

View File

@@ -133,19 +133,26 @@ class TypeTranslator(
return properlyApproximatedType
}
private val isWithNewInference = languageVersionSettings.supportsFeature(LanguageFeature.NewInference)
private fun approximateByKotlinRules(ktType: KotlinType): KotlinType {
if (ktType.constructor.isDenotable) return ktType
return if (languageVersionSettings.supportsFeature(LanguageFeature.NewInference))
typeApproximatorForNI.approximateDeclarationType(
ktType,
local = false,
languageVersionSettings = languageVersionSettings
)
else
approximateCapturedTypes(ktType).upper
}
private fun approximateByKotlinRules(ktType: KotlinType): KotlinType =
if (isWithNewInference) {
if (ktType.constructor.isDenotable && ktType.arguments.isEmpty())
ktType
else
typeApproximatorForNI.approximateDeclarationType(
ktType,
local = false,
languageVersionSettings = languageVersionSettings
)
} else {
// Hack to preserve *-projections in arguments in OI.
// Expected to be removed as soon as OI is deprecated.
if (ktType.constructor.isDenotable)
ktType
else
approximateCapturedTypes(ktType).upper
}
}

View File

@@ -986,7 +986,7 @@ open class IrFileSerializer(
}
private fun serializeIrDeclarationBase(declaration: IrDeclaration, flags: Long?): ProtoDeclarationBase {
expectActualTable.findExpectsForActuals(declaration)
if (!skipExpects) expectActualTable.findExpectsForActuals(declaration)
return with(ProtoDeclarationBase.newBuilder()) {
symbol = serializeIrSymbol((declaration as IrSymbolOwner).symbol)
coordinates = serializeCoordinates(declaration.startOffset, declaration.endOffset)

View File

@@ -10,7 +10,6 @@ import org.jetbrains.kotlin.backend.common.serialization.mangle.MangleConstant
import org.jetbrains.kotlin.backend.common.serialization.mangle.MangleMode
import org.jetbrains.kotlin.backend.common.serialization.mangle.collect
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty
@@ -77,6 +76,8 @@ abstract class DescriptorMangleComputer(protected val builder: StringBuilder, pr
open fun FunctionDescriptor.platformSpecificSuffix(): String? = null
open fun PropertyDescriptor.platformSpecificSuffix(): String? = null
protected open fun addReturnType(): Boolean = false
open fun FunctionDescriptor.specialValueParamPrefix(param: ValueParameterDescriptor): String = ""
private val CallableDescriptor.isRealStatic: Boolean
@@ -98,11 +99,6 @@ abstract class DescriptorMangleComputer(protected val builder: StringBuilder, pr
builder.append(name.asString())
if (visibility == Visibilities.INTERNAL) {
builder.append(MangleConstant.MODULE_SEPARATOR)
builder.append(module.name.asString().run { substring(1, lastIndex) })
}
mangleSignature(isCtor, container)
}
@@ -127,7 +123,7 @@ abstract class DescriptorMangleComputer(protected val builder: StringBuilder, pr
.collect(builder, MangleConstant.TYPE_PARAMETERS) { mangleTypeParameter(this, it) }
returnType?.run {
if (!isCtor && !isUnit()) {
if (!isCtor && !isUnit() && addReturnType()) {
mangleType(builder, this)
}
}

View File

@@ -5,19 +5,16 @@
package org.jetbrains.kotlin.backend.common.serialization.mangle.ir
import org.jetbrains.kotlin.backend.common.ir.isStatic
import org.jetbrains.kotlin.backend.common.serialization.mangle.KotlinMangleComputer
import org.jetbrains.kotlin.backend.common.serialization.mangle.MangleConstant
import org.jetbrains.kotlin.backend.common.serialization.mangle.MangleMode
import org.jetbrains.kotlin.backend.common.serialization.mangle.collect
import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.symbols.IrClassSymbol
import org.jetbrains.kotlin.ir.symbols.IrTypeParameterSymbol
import org.jetbrains.kotlin.ir.types.*
import org.jetbrains.kotlin.ir.util.isVararg
import org.jetbrains.kotlin.ir.util.module
import org.jetbrains.kotlin.ir.util.render
import org.jetbrains.kotlin.ir.visitors.IrElementVisitor
import org.jetbrains.kotlin.types.Variance
@@ -34,6 +31,8 @@ abstract class IrMangleComputer(protected val builder: StringBuilder, private va
open fun IrFunction.specialValueParamPrefix(param: IrValueParameter): String = ""
open fun addReturnType(): Boolean = false
abstract override fun copy(newMode: MangleMode): IrMangleComputer
private fun StringBuilder.appendName(s: String) {
@@ -96,16 +95,6 @@ abstract class IrMangleComputer(protected val builder: StringBuilder, private va
builder.append(name.asString())
if (visibility == Visibilities.INTERNAL) {
builder.append(MangleConstant.MODULE_SEPARATOR)
val moduleName = try {
module.name.asString().run { substring(1, lastIndex) }
} catch (e: Throwable) {
MangleConstant.UNKNOWN_MARK
}
builder.append(moduleName)
}
mangleSignature(isCtor, isStatic)
}
@@ -127,7 +116,7 @@ abstract class IrMangleComputer(protected val builder: StringBuilder, private va
}
typeParameters.collect(builder, MangleConstant.TYPE_PARAMETERS) { mangleTypeParameter(this, it) }
if (!isCtor && !returnType.isUnit()) {
if (!isCtor && !returnType.isUnit() && addReturnType()) {
mangleType(builder, returnType)
}
}

View File

@@ -37,6 +37,7 @@ import org.jetbrains.kotlin.js.config.JSConfigurationKeys
import org.jetbrains.kotlin.konan.properties.propertyList
import org.jetbrains.kotlin.konan.util.KlibMetadataFactories
import org.jetbrains.kotlin.library.*
import org.jetbrains.kotlin.library.impl.BuiltInsPlatform
import org.jetbrains.kotlin.library.impl.buildKoltinLibrary
import org.jetbrains.kotlin.library.resolver.KotlinLibraryResolveResult
import org.jetbrains.kotlin.library.resolver.TopologicalLibraryOrder
@@ -47,6 +48,7 @@ import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi2ir.Psi2IrConfiguration
import org.jetbrains.kotlin.psi2ir.Psi2IrTranslator
import org.jetbrains.kotlin.psi2ir.generators.GeneratorContext
import org.jetbrains.kotlin.psi2ir.generators.createGeneratorContext
import org.jetbrains.kotlin.psi2ir.generators.GeneratorExtensions
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.BindingContextUtils
@@ -241,7 +243,7 @@ private fun runAnalysisAndPreparePsi2Ir(depsDescriptors: ModulesStructure): Gene
val mangler = JsManglerDesc
val signaturer = IdSignatureDescriptor(mangler)
return GeneratorContext(
return createGeneratorContext(
Psi2IrConfiguration(),
analysisResult.moduleDescriptor,
analysisResult.bindingContext,
@@ -503,7 +505,8 @@ fun serializeModuleIntoKlib(
moduleName = moduleName,
nopack = nopack,
output = klibPath,
versions = versions
versions = versions,
builtInsPlatform = BuiltInsPlatform.JS
)
}

View File

@@ -81,7 +81,7 @@ abstract class KtLightClassForSourceDeclaration(
override fun getText() = kotlinOrigin.text ?: ""
override fun getTextRange(): TextRange = kotlinOrigin.textRange ?: TextRange.EMPTY_RANGE
override fun getTextRange(): TextRange? = kotlinOrigin.textRange ?: TextRange.EMPTY_RANGE
override fun getTextOffset() = kotlinOrigin.textOffset

View File

@@ -5,6 +5,8 @@
package org.jetbrains.kotlin.asJava.classes
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.*
import com.intellij.psi.impl.InheritanceImplUtil
import com.intellij.psi.impl.PsiClassImplUtil
@@ -475,4 +477,12 @@ open class KtUltraLightClass(classOrObject: KtClassOrObject, internal val suppor
override fun isDeprecated(): Boolean = _deprecated
override fun copy(): KtLightClassImpl = KtUltraLightClass(classOrObject.copy() as KtClassOrObject, support)
override fun getTextRange(): TextRange? {
if (Registry.`is`("kotlin.ultra.light.classes.empty.text.range", true)) {
return null
}
return super.getTextRange()
}
}

View File

@@ -5,6 +5,7 @@
package org.jetbrains.kotlin.asJava.classes
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.*
import com.intellij.psi.impl.light.LightMethodBuilder
import com.intellij.psi.impl.light.LightModifierList
@@ -174,6 +175,7 @@ internal class UltraLightMembersCreator(
numberOfDefaultParametersToAdd: Int = -1,
methodIndex: Int
): KtLightMethod {
ProgressManager.checkCanceled()
val isConstructor = ktFunction is KtConstructor<*>
val name =
if (isConstructor) containingClass.name

View File

@@ -67,7 +67,7 @@ public interface Call {
KtElement getCallElement();
enum CallType {
DEFAULT, ARRAY_GET_METHOD, ARRAY_SET_METHOD, INVOKE
DEFAULT, ARRAY_GET_METHOD, ARRAY_SET_METHOD, INVOKE, CONTAINS
}
@NotNull

View File

@@ -97,7 +97,7 @@ object NewCommonSuperTypeCalculator {
contextStubTypesEqualToAnything: AbstractTypeCheckerContext,
contextStubTypesNotEqual: AbstractTypeCheckerContext
): SimpleTypeMarker {
if (types.all { it is ErrorType }) {
if (types.any { it is ErrorType }) {
return ErrorUtils.createErrorType("CST(${types.joinToString()}")
}

View File

@@ -50,11 +50,16 @@ data class ReturnArgumentsInfo(
val lastExpression: KotlinCallArgument?,
val lastExpressionCoercedToUnit: Boolean,
val returnArgumentsExist: Boolean
)
) {
companion object {
val empty = ReturnArgumentsInfo(emptyList(), null, lastExpressionCoercedToUnit = false, returnArgumentsExist = false)
}
}
data class ReturnArgumentsAnalysisResult(
val returnArgumentsInfo: ReturnArgumentsInfo,
val inferenceSession: InferenceSession?
val inferenceSession: InferenceSession?,
val hasInapplicableCallForBuilderInference: Boolean = false
)
// This components hold state (trace). Work with this carefully.

View File

@@ -40,7 +40,7 @@ interface InferenceSession {
lambda: ResolvedLambdaAtom,
initialStorage: ConstraintStorage,
diagnosticsHolder: KotlinDiagnosticsHolder
): Map<TypeConstructor, UnwrappedType>
): Map<TypeConstructor, UnwrappedType>?
fun writeOnlyStubs(callInfo: SingleCallResolutionResult): Boolean
fun callCompleted(resolvedAtom: ResolvedAtom): Boolean

View File

@@ -120,15 +120,21 @@ class PostponedArgumentsAnalyzer(
else FilteredAnnotations(annotations, true) { it != KotlinBuiltIns.FQ_NAMES.extensionFunctionType }
}
val (returnArgumentsInfo, inferenceSession) = resolutionCallbacks.analyzeAndGetLambdaReturnArguments(
lambda.atom,
lambda.isSuspend,
receiver,
parameters,
expectedTypeForReturnArguments,
convertedAnnotations ?: Annotations.EMPTY,
stubsForPostponedVariables.cast()
)
val (returnArgumentsInfo, inferenceSession, hasInapplicableCallForBuilderInference) =
resolutionCallbacks.analyzeAndGetLambdaReturnArguments(
lambda.atom,
lambda.isSuspend,
receiver,
parameters,
expectedTypeForReturnArguments,
convertedAnnotations ?: Annotations.EMPTY,
stubsForPostponedVariables.cast()
)
if (hasInapplicableCallForBuilderInference) {
c.getBuilder().removePostponedVariables()
return
}
val returnArguments = returnArgumentsInfo.nonErrorArguments
returnArguments.forEach { c.addSubsystemFromArgument(it) }
@@ -159,6 +165,10 @@ class PostponedArgumentsAnalyzer(
val storageSnapshot = c.getBuilder().currentStorage()
val postponedVariables = inferenceSession.inferPostponedVariables(lambda, storageSnapshot, diagnosticHolder)
if (postponedVariables == null) {
c.getBuilder().removePostponedVariables()
return
}
for ((constructor, resultType) in postponedVariables) {
val variableWithConstraints = storageSnapshot.notFixedTypeVariables[constructor] ?: continue

View File

@@ -179,7 +179,7 @@ private fun checkSubCallArgument(
diagnosticsHolder: KotlinDiagnosticsHolder,
receiverInfo: ReceiverInfo,
): ResolvedAtom {
val subCallResult = subCallArgument.callResult
val subCallResult = ResolvedSubCallArgument(subCallArgument)
if (expectedType == null) return subCallResult

View File

@@ -34,6 +34,7 @@ interface ConstraintSystemOperation {
fun registerVariable(variable: TypeVariableMarker)
fun markPostponedVariable(variable: TypeVariableMarker)
fun unmarkPostponedVariable(variable: TypeVariableMarker)
fun removePostponedVariables()
fun addSubtypeConstraint(lowerType: KotlinTypeMarker, upperType: KotlinTypeMarker, position: ConstraintPosition)
fun addEqualityConstraint(a: KotlinTypeMarker, b: KotlinTypeMarker, position: ConstraintPosition)

View File

@@ -167,9 +167,11 @@ class KotlinConstraintSystemCompleter(
val builtIns = (variable as TypeVariableTypeConstructor).builtIns
val csBuilder = (c as NewConstraintSystemImpl).getBuilder()
val expectedTypeVariable = postponedAtom.expectedType?.constructor?.takeIf { it in c.allTypeVariables } ?: variable
val atomToAnalyze = when (postponedAtom) {
is PostponedCallableReferenceAtom -> postponedAtom.preparePostponedAtomWithTypeVariableAsExpectedType(
c, csBuilder, variable,
c, csBuilder, expectedTypeVariable,
condition = { true },
isSuitable = KotlinType::isBuiltinFunctionalTypeOrSubtype,
typeVariableCreator = { TypeVariableForCallableReferenceReturnType(builtIns, "_Q") },
@@ -180,7 +182,7 @@ class KotlinConstraintSystemCompleter(
}
)
is LambdaWithTypeVariableAsExpectedTypeAtom -> postponedAtom.preparePostponedAtomWithTypeVariableAsExpectedType(
c, csBuilder, variable,
c, csBuilder, expectedTypeVariable,
condition = { it.atom.parametersTypes?.all { type -> type != null } != true },
isSuitable = KotlinType::isBuiltinFunctionalType,
typeVariableCreator = { TypeVariableForLambdaReturnType(postponedAtom.atom, builtIns, "_R") },

View File

@@ -103,6 +103,10 @@ class NewConstraintSystemImpl(
storage.postponedTypeVariables -= variable
}
override fun removePostponedVariables() {
storage.postponedTypeVariables.clear()
}
override fun addSubtypeConstraint(lowerType: KotlinTypeMarker, upperType: KotlinTypeMarker, position: ConstraintPosition) =
constraintInjector.addInitialSubtypeConstraint(
apply { checkState(State.BUILDING, State.COMPLETION, State.TRANSACTION) },

View File

@@ -44,7 +44,7 @@ interface SimpleKotlinCallArgument : KotlinCallArgument, ReceiverKotlinCallArgum
interface ExpressionKotlinCallArgument : SimpleKotlinCallArgument, ResolutionAtom
interface SubKotlinCallArgument : SimpleKotlinCallArgument {
interface SubKotlinCallArgument : SimpleKotlinCallArgument, ResolutionAtom {
val callResult: PartialCallResolutionResult
}

View File

@@ -152,9 +152,7 @@ sealed class UnstableSmartCast(
targetType: UnwrappedType,
isReceiver: Boolean = false, // for reproducing OI behaviour
): UnstableSmartCast {
return if (isReceiver)
UnstableSmartCastResolutionError(argument, targetType)
else UnstableSmartCastDiagnosticError(argument, targetType)
return UnstableSmartCastResolutionError(argument, targetType)
}
}
}

View File

@@ -85,6 +85,12 @@ class ResolvedExpressionAtom(override val atom: ExpressionKotlinCallArgument) :
}
}
class ResolvedSubCallArgument(override val atom: SubKotlinCallArgument) : ResolvedAtom() {
init {
setAnalyzedResults(listOf(atom.callResult))
}
}
interface PostponedResolvedAtomMarker {
val inputTypes: Collection<KotlinTypeMarker>
val outputType: KotlinTypeMarker?

View File

@@ -27,7 +27,7 @@ private val INAPPLICABLE_STATUSES = setOf(
)
val ResolutionCandidateApplicability.isSuccess: Boolean
get() = this <= ResolutionCandidateApplicability.RESOLVED_WITH_ERROR
get() = this <= ResolutionCandidateApplicability.RESOLVED_LOW_PRIORITY
val CallableDescriptor.isSynthesized: Boolean
get() = (this is CallableMemberDescriptor && kind == CallableMemberDescriptor.Kind.SYNTHESIZED)

View File

@@ -1,5 +1,7 @@
Usage: kotlin-dce-js <options> <source files>
where advanced options include:
-Xdev-mode-overwriting-strategy={older|all}
Overwriting strategy during copy dependencies in development mode
-Xprint-reachability-info Print declarations marked as reachable
Advanced options are non-standard and may be changed or removed without any notice.

View File

@@ -0,0 +1,3 @@
$TESTDATA_DIR$/reifiedIntersectionType.kt
-output
$TEMP_DIR$/out.js

View File

@@ -0,0 +1,16 @@
fun test1() {
val flow = combine(
flowOf("1"),
flowOf(2)
) { arr -> arr.joinToString() }
}
fun <T> Array<out T>.joinToString(): String = ""
public inline fun <reified T, R> combine(
vararg flows: Flow<T>,
crossinline transform: suspend (Array<T>) -> R
): Flow<R> = TODO()
fun <T> flowOf(value: T): Flow<T> = TODO()
interface Flow<out T>

View File

@@ -0,0 +1,13 @@
compiler/testData/cli/js/reifiedIntersectionType.kt:2:9: warning: variable 'flow' is never used
val flow = combine(
^
compiler/testData/cli/js/reifiedIntersectionType.kt:11:12: warning: parameter 'flows' is never used
vararg flows: Flow<T>,
^
compiler/testData/cli/js/reifiedIntersectionType.kt:12:17: warning: parameter 'transform' is never used
crossinline transform: suspend (Array<T>) -> R
^
compiler/testData/cli/js/reifiedIntersectionType.kt:15:16: warning: parameter 'value' is never used
fun <T> flowOf(value: T): Flow<T> = TODO()
^
OK

View File

@@ -0,0 +1,31 @@
// !LANGUAGE: +NewInference
// WITH_RUNTIME
// IGNORE_BACKEND_FIR: JVM_IR
// Issue: KT-36371
import kotlin.experimental.ExperimentalTypeInference
class Foo(val string: String? = null)
class Builder<T> {
private var resolver: ((Foo) -> T)? = null
fun build() = resolver!!
fun resolve(resolver: (Foo) -> T) {
this.resolver = resolver
}
}
@OptIn(ExperimentalTypeInference::class)
fun <T> build(@BuilderInference configure: Builder<T>.() -> Unit) =
Builder<T>().apply(configure).build()
fun box(): String {
val resolver = build {
resolve { it.string }
}
resolver(Foo())
return "OK"
}

View File

@@ -0,0 +1,79 @@
// WITH_RUNTIME
// WITH_COROUTINES
// KJS_WITH_FULL_RUNTIME
// IGNORE_BACKEND_FIR: JVM_IR
import helpers.*
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*
import kotlin.experimental.ExperimentalTypeInference
fun test() {
flow {
emit(1)
}.flatMapLatest<Int, Long> {
flow {
expectInt(42)
}
}
flow {
emit(1)
}.flatMapLatest<Int, Long> {
flow {
expectInt(42)
hang {
expectInt(0)
}
}
}
flow {
emit(1)
}.flatMap {
if (it == 1)
flow { expectGeneric(42) }
else
flow<Int> {}
}
flow {
emit(1)
}.flatMap {
if (it == 1)
flow {}
else
flow<Int> {}
}
flow {
emit(1)
}.flatMap {
if (it == 1)
flow {}
else flow {}
}
}
fun expectInt(i: Int) {}
fun <K> expectGeneric(i: K) {}
suspend inline fun hang(onCancellation: () -> Unit) {}
fun <T> Flow<T>.flatMap(mapper: suspend (T) -> Flow<T>): Flow<T> = TODO()
@OptIn(ExperimentalTypeInference::class)
fun <T> flow(@BuilderInference block: suspend FlowCollector<T>.() -> Unit): Flow<T> = TODO()
@OptIn(ExperimentalTypeInference::class)
inline fun <T, R> Flow<T>.flatMapLatest(@BuilderInference crossinline transform: suspend (value: T) -> Flow<R>): Flow<R> = TODO()
interface Flow<out T>
interface FlowCollector<in T> {
suspend fun emit(value: T)
}
fun box(): String {
return "OK"
}

View File

@@ -0,0 +1,20 @@
class Inv<T>
fun Inv<*>.invToInv(): Inv<*>? = null
fun <R> myRun(block: () -> R): R {
return block()
}
fun test(c: Inv<*>) {
myRun {
if (true) return@myRun // coerction to Unit
c.invToInv()?.let {}
}
}
fun box(): String {
test(Inv<Int>())
return "OK"
}

View File

@@ -0,0 +1,37 @@
// IGNORE_BACKEND: JS
// KJS_WITH_FULL_RUNTIME
// Case that was found in kotlinx.coroutines
fun test1() {
val flow = combine(
flowOf("1"),
flowOf(2)
) { arr -> arr.joinToString() }
}
fun <T> Array<out T>.joinToString(): String = ""
public inline fun <reified T, R> combine(
vararg flows: Flow<T>,
crossinline transform: suspend (Array<T>) -> R
): Flow<R> = TODO()
fun <T> flowOf(value: T): Flow<T> = TODO()
interface Flow<out T>
// Simplified case
class In<in T>
inline fun <reified K> select(x: K, y: K): K = x
interface A
interface B
fun test2(a: In<A>, b: In<B>) {
select(a, b)
}
fun box(): String {
return "OK"
}

View File

@@ -7,3 +7,9 @@ class A<T> {
class AA<T> {
inner class Inner<U, V>
}
class AAA<T> {
inner class Inner<K> {
inner class InnerInner<S>
}
}

View File

@@ -2,8 +2,11 @@ package b
import a.A
import a.AA
import a.AAA
interface B1 {
fun produceA(): A<String>.Inner<Int, Unit>
fun produceAA(): AA<Int>.Inner<Unit, String>
fun <T> produceAGeneric(t: T): A<String>.Inner<Int, Unit>
fun produceAAA(): AAA<String>.Inner<Int>.InnerInner<Unit>
}

View File

@@ -7,3 +7,9 @@ class A<T, U: CharSequence, V> {
class AA<T, U> {
inner class Inner<V>
}
class AAA<T> {
inner class Inner<K> {
inner class InnerInner<S>
}
}

View File

@@ -2,8 +2,10 @@ package b
import a.A
import a.AA
import a.AAA
interface B2 {
fun consumeA(a: A<Int, String, Double>.Inner<B2>)
fun consumeAA(a: AA<Int, Unit>.Inner<String>)
fun consumeAAA(a: AAA<String>.Inner<Int>.InnerInner<Unit>)
}

View File

@@ -7,13 +7,28 @@ compiler/testData/compileKotlinAgainstCustomBinaries/missingDependencyConflictin
compiler/testData/compileKotlinAgainstCustomBinaries/missingDependencyConflictingLibraries/source.kt:7:20: error: cannot access class 'a.A.Inner'. Check your module classpath for missing or conflicting dependencies
b2.consumeA(b1.produceA())
^
compiler/testData/compileKotlinAgainstCustomBinaries/missingDependencyConflictingLibraries/source.kt:11:8: error: cannot access class 'a.AA.Inner'. Check your module classpath for missing or conflicting dependencies
compiler/testData/compileKotlinAgainstCustomBinaries/missingDependencyConflictingLibraries/source.kt:8:8: error: cannot access class 'a.A.Inner'. Check your module classpath for missing or conflicting dependencies
b2.consumeA(b1.produceAGeneric("foo"))
^
compiler/testData/compileKotlinAgainstCustomBinaries/missingDependencyConflictingLibraries/source.kt:8:17: error: type mismatch: inferred type is A<String>.Inner<Int, Unit> but A<Int, String, Double>.Inner<B2> was expected
b2.consumeA(b1.produceAGeneric("foo"))
^
compiler/testData/compileKotlinAgainstCustomBinaries/missingDependencyConflictingLibraries/source.kt:8:20: error: cannot access class 'a.A.Inner'. Check your module classpath for missing or conflicting dependencies
b2.consumeA(b1.produceAGeneric("foo"))
^
compiler/testData/compileKotlinAgainstCustomBinaries/missingDependencyConflictingLibraries/source.kt:12:8: error: cannot access class 'a.AA.Inner'. Check your module classpath for missing or conflicting dependencies
b2.consumeAA(b1.produceAA())
^
compiler/testData/compileKotlinAgainstCustomBinaries/missingDependencyConflictingLibraries/source.kt:11:18: error: type mismatch: inferred type is AA<Int>.Inner<Unit, String> but AA<Int, Unit>.Inner<String> was expected
compiler/testData/compileKotlinAgainstCustomBinaries/missingDependencyConflictingLibraries/source.kt:12:18: error: type mismatch: inferred type is AA<Int>.Inner<Unit, String> but AA<Int, Unit>.Inner<String> was expected
b2.consumeAA(b1.produceAA())
^
compiler/testData/compileKotlinAgainstCustomBinaries/missingDependencyConflictingLibraries/source.kt:11:21: error: cannot access class 'a.AA.Inner'. Check your module classpath for missing or conflicting dependencies
compiler/testData/compileKotlinAgainstCustomBinaries/missingDependencyConflictingLibraries/source.kt:12:21: error: cannot access class 'a.AA.Inner'. Check your module classpath for missing or conflicting dependencies
b2.consumeAA(b1.produceAA())
^
COMPILATION_ERROR
compiler/testData/compileKotlinAgainstCustomBinaries/missingDependencyConflictingLibraries/source.kt:16:8: error: cannot access class 'a.AAA.Inner.InnerInner'. Check your module classpath for missing or conflicting dependencies
b2.consumeAAA(b1.produceAAA())
^
compiler/testData/compileKotlinAgainstCustomBinaries/missingDependencyConflictingLibraries/source.kt:16:22: error: cannot access class 'a.AAA.Inner.InnerInner'. Check your module classpath for missing or conflicting dependencies
b2.consumeAAA(b1.produceAAA())
^
COMPILATION_ERROR

View File

@@ -5,8 +5,13 @@ import b.B2
fun testA(b1: B1, b2: B2) {
b2.consumeA(b1.produceA())
b2.consumeA(b1.produceAGeneric("foo"))
}
fun testAA(b1: B1, b2: B2) {
b2.consumeAA(b1.produceAA())
}
fun testAAA(b1: B1, b2: B2) {
b2.consumeAAA(b1.produceAAA())
}

View File

@@ -0,0 +1,9 @@
// !LANGUAGE: +NewInference
fun test() {
run {
if (true)
return@run false
<!UNRESOLVED_REFERENCE!>unresolved<!>.toString()
}
}

View File

@@ -0,0 +1,9 @@
// !LANGUAGE: +NewInference
fun test() {
run {
if (true)
return@run false
<!UNRESOLVED_REFERENCE!>unresolved<!>.<!DEBUG_INFO_MISSING_UNRESOLVED!>toString<!>()
}
}

View File

@@ -0,0 +1,3 @@
package
public fun test(): kotlin.Unit

View File

@@ -0,0 +1,18 @@
// !LANGUAGE: +NewInference
// !DIAGNOSTICS: -UNUSED_PARAMETER -UNUSED_VARIABLE
// ISSUE: KT-36819
fun <K> select(vararg x: K) = x[0]
interface A
class B: A
class C: A
fun <T> id1(x: T): T = x
fun <R> id2(x: R): R = x
class Out<out R>(x: R)
fun main() {
val x1 = select(id1 { B() }, id2 { C() })
val x2 = select({ B() }, { C() }) // OK, CST = () -> A
val x3 = select(id1(Out(B())), id2(Out(C()))) // OK, CST = Out<A>
}

View File

@@ -0,0 +1,18 @@
// !LANGUAGE: +NewInference
// !DIAGNOSTICS: -UNUSED_PARAMETER -UNUSED_VARIABLE
// ISSUE: KT-36819
fun <K> select(vararg x: K) = x[0]
interface A
class B: A
class C: A
fun <T> id1(x: T): T = x
fun <R> id2(x: R): R = x
class Out<out R>(x: R)
fun main() {
val x1 = select(id1 { B() }, id2 { <!TYPE_MISMATCH, TYPE_MISMATCH!>C()<!> })
val x2 = select({ B() }, { C() }) // OK, CST = () -> A
val x3 = select(id1(Out(B())), id2(Out(C()))) // OK, CST = Out<A>
}

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