Compare commits

...

1018 Commits

Author SHA1 Message Date
Nikolay Igotti
31e9b6d904 WIP 2020-03-03 17:09:17 +03:00
Nikolay Igotti
f45ba79a16 Add compose plugin. 2020-03-03 15:47:09 +03:00
Vyacheslav Gerasimov
75a3808230 Build: Use sourceMapBaseDirs in :kotlin-stdlib-js:compileKotlin2Js
instead of freeCompiler args to avoid snapshotting absolute paths
and fix caching
2020-03-03 14:33:57 +03:00
Vyacheslav Gerasimov
4b9c7a1ae1 Advance bootstrap to 1.4.0-dev-1818 2020-03-03 14:33:55 +03:00
Victor Petukhov
d6ccdb3caa NI: fix extensionLambdasAndArrow test 2020-03-03 13:55:15 +03:00
Kristoffer Andersen
6e40117116 [JVM IR] Refactor PromisedValue...
... for an _even leaner_ codegen!

- move discard from extention method to abstract method. This will at
  length avoid some calls to materialize.

- use newly abstract method to specialize discard in cases where it
  would introduce _and_ coerce values only to be popped by discard.

- move coerce to member method, introduce materializeAt with a view to
  eliminate calls to coerce outside of PromisedValue. This will allow
  us to specilaize materialization at particular types in some
  instances, at length avoiding casts etc.

- no calls to coerce outside of PromisedValue.kt! Progress.

- inlined coerce into materializeAt, anticipating specializing
  materializeAt across implementations of PromisedValue

- made materializeAt abstract, copied implementation everywhere!

- made materialize an extention function! Ready to specialize materializeAt

- coerce is no more!

- simplified and specialized all inlinings of materializeAt.

- adjust docs to match refactoring
2020-03-03 11:41:55 +01:00
Pavel Kirpichenkov
ad988dbf43 minor: update test data 2020-03-03 12:57:41 +03:00
Pavel Kirpichenkov
23ed6c4a1f [NI] Narrow nullability constraint check in incorporator
This commit is a hotfix rather then proper solution.
The source of the issue is that currently type variable fixation result
may change due to fixation order alteration for variables with the same priority.
For instance, having variables V1, V2, and proper types Type1, Type2, such that:
V1 <: Type1
V1 <: V2
Type2 <: V2
both variables will be fixed either to Type1, if V1 will be fixed first,
or to Type2 otherwise.

Since this limitation cannot be easily overcome, the taken approach is to remove
incedental constraint added after 2d5a0546 by restricting nullability constraint check
to `Nothing?` constraints only, thus postponing problematic variable fixation.
To clearify, additional constraint is correct and should cause no harm (in ideal world),
but currently its presence changes fixation order.
So without the restriction the previously used constraint from fixed outer variable
is no longer available by the time problematic variable type is being selected.

^KT-37043 Fixed
2020-03-03 12:57:25 +03:00
Dmitriy Novozhilov
ec01893237 [FIR] Resolve return expressions in independent context 2020-03-03 09:57:45 +03:00
Dmitriy Novozhilov
d4f57fb835 [FIR] Support comparision operator and reified parameter reference in html dump 2020-03-03 09:57:45 +03:00
Dmitriy Novozhilov
9eeee6aad7 [FIR-TEST] Move FirBlackBoxCodegenTestGenerated to :fir2ir module 2020-03-03 09:57:45 +03:00
Dmitriy Novozhilov
54e7c79257 [FIR] Safe implicit receiver stack in lambda atom for resolve of inner lambdas
#KT-36887 Fixed
2020-03-03 09:57:42 +03:00
Dmitriy Novozhilov
c7f5a2cba2 [FIR] Make ImplicitReceiverStack persistent 2020-03-03 09:57:41 +03:00
Dmitriy Novozhilov
a332a5f26d Add benchmark with case with a lot of implicit receivers 2020-03-03 09:57:41 +03:00
Dmitriy Novozhilov
7ee125e1ad [FIR] Add receiver for lambda in position of default argument
#KT-36905 Fixed
2020-03-03 09:57:41 +03:00
Dmitriy Novozhilov
c12fb1e069 [FIR] Fix determining type of when subject in exhaustiveness checker
#KT-37091 Fixed
2020-03-03 09:57:41 +03:00
Ivan Gavrilovic
6d4eb9ae52 KT-36113: Make KAPT classpath snapshot deterministic
When snapshotting a classpath entry, sort information about types
so there is no dependency on the order of entries in jar.

Test: ClasspathAnalyzerTest
2020-03-03 14:22:57 +09:00
pyos
9b68e4fe56 Android/IR: handle nulls from getView/getContainerView
Turns out it's possible to create an IR builder without a backend
context
2020-03-03 14:19:47 +09:00
Yan Zhulanow
390d062721 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.
2020-03-03 14:18:04 +09:00
Yan Zhulanow
b360fb5119 Revert "Import Kotlin JUnit run configuration settings from Gradle" 2020-03-03 14:18:03 +09:00
Yan Zhulanow
29566723b8 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.
2020-03-03 14:18:03 +09:00
Yan Zhulanow
9016a573ca 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.
2020-03-03 14:18:03 +09:00
Nikolay Krasko
208c7274dd Disable parallel execution for gradle tests 2020-03-02 23:21:46 +03:00
Natalia Selezneva
c0cd010b7d .gradle.kts: fix freezes by avoiding fs walking
^KT-36502 Fixed
2020-03-02 20:48:55 +03:00
Dmitry Petrov
01c4e66edb 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-02 20:34:02 +03:00
Victor Petukhov
51749b9747 NI: don't try to infer visible lambda parameters, if there is single one – extension parameter
^KT-37038 Fixed
2020-03-02 20:28:59 +03:00
pyos
ed83e3ccef Optimize more redundant kotlin/jvm/internal/Refs
The number of initializations of the `value` field before the live range
begins does not really matter so long as we insert a write of a default
value to the local if there were none.
2020-03-02 20:20:55 +03:00
pyos
7e6d080123 JVM_IR: default-initialize variables visible in the LVT
See KT-36812. Aside from the problem stated there, D8 will throw out the
entire LVT if it sees a variable that has not been written to (and will
generate incorrect SSA if the slot is reused with a different type).

Note: this only fixes a FIR test because it's missing an `else -> throw`
branch, and default initialization satisfies the verifier and masks the
incorrect control flow.
2020-03-02 20:17:10 +03:00
Dmitry Gridin
ecb7478794 ExperimentalFixesFactory: OptIn shouldn't be added for old version
#KT-36478
2020-03-03 00:09:00 +07:00
Nikolay Krasko
08dc03a704 201: Fix refineSignaturesWithResolve failure for primary constructors 2020-03-02 18:25:29 +03:00
Nikolay Krasko
096ff0e8a9 201: Enable mute in KotlinSuggestedRefactoringChangeListenerTest 2020-03-02 18:25:29 +03:00
Mikhail Zarechenskiy
d1a8f57740 Disable New Inference in JS backend
See #KT-37163 for details
2020-03-02 18:03:41 +03:00
Dmitry Savvinov
e6885323da Accept incorrect behaviour for run-config tests for AS
Short description.
It's a corner-case with old MPP plugins and AS, so we
don't care too much that it works incorrectly, but we'd like to avoid
muting it in order to keep track of this "known issue"

Long description.
In IDEA, KotlinJvmTestMethodGradleConfigurationProducer successfully
returns run configuration; in AS, it fails to do so.

This is becasuse it doesn't override 'forceGradleRunner', which means
that in 'setupConfigurationFromContext' we'll delegate to super-call,
which will pull 'GradleProjectSettings.getTestRunner()'.

In IDEA, it will return GRADLE, but in AS it will return PLATFORM,
because AS uses special instance of GradleProjectSettings which forces
runner to PLATFORM.

Note that KotlinMultiplatformJvmTestMethodGradleConfigurationProducer
does override 'forceGradleRunner' to true, that's why other tests work
successfully. However, this test uses old 1.2.X-MPP plugins, therefore
all new KotlinMultiplatform*ConfigurationProducers won't work here.\
2020-03-02 16:40:15 +03:00
Ilmir Usmanov
22de20e7e5 JVM_IR: Generate PUBLIC constructor for suspend lambda
if the lambda is inside inline function.
2020-03-02 14:03:35 +01:00
Ilmir Usmanov
42420cb6fc JVM_IR: Generate inner classes for continuations
Also, generate correct visibilities for constructors and continuation's fields.
2020-03-02 14:03:33 +01:00
Ilmir Usmanov
536e0e23a0 JVM_IR: Lazyly generate continuation classes of suspend functions
Otherwise, they will be generated, but unused, if the function is tail-call.
 #KT-36795 Fixed
2020-03-02 14:03:31 +01:00
Vladimir Dolzhenko
91ee63432a Disable CacheResetOnProcessCancele by default 2020-03-02 11:42:19 +01:00
Konstantin Tskhovrebov
60d592716d Disable KotlinMppTestLogger for non test executions.
Issue #KT-36716 Fixed
2020-03-02 13:41:33 +03:00
Konstantin Tskhovrebov
35055d1895 Fix empty run actions in context menu for non-JVM test results.
Issue #KT-36910 Fixed
Issue #KT-36909 Fixed
2020-03-02 12:25:36 +03:00
Vladimir Ilmov
dc8f24b8bc Revert "Registry key to show hidden variables in debugger."
This reverts commit f5e6001d82.
2020-03-02 08:35:09 +01:00
Dmitry Petrov
61f8d3e558 Minor: update FIR2IR testData 2020-03-02 10:11:51 +03:00
Mikhail Glukhikh
1bad380381 FIR: fix test data in IDEA multi-module tests 2020-03-02 10:03:49 +03:00
Dmitriy Novozhilov
70ee51d88c [FIR] Add anonymous objects to CFG 2020-03-02 09:49:29 +03:00
Dmitriy Novozhilov
e3f1f18ca3 [FIR] Add empty member scope for type variables 2020-03-02 09:49:29 +03:00
Dmitriy Novozhilov
985311d9f0 [FIR] Implement delegate inference 2020-03-02 09:49:29 +03:00
Dmitriy Novozhilov
1003b81c93 [FIR] Introduce inference session 2020-03-02 09:49:28 +03:00
Dmitriy Novozhilov
dfa6dfa960 [FIR] Support deserialization of annotations on JVM 2020-03-02 09:49:28 +03:00
Dmitriy Novozhilov
296ee2da4a [FIR] Support @LowPriorityInOverloadResolution annotation 2020-03-02 09:49:28 +03:00
Dmitriy Novozhilov
4454a0681b [FIR] Get rid of copying function call in process of completion 2020-03-02 09:49:28 +03:00
Dmitriy Novozhilov
cda8177502 [FIR] Add transformDelegate for FirProperty 2020-03-02 09:07:23 +03:00
Dmitriy Novozhilov
e8b0ce00e1 [FIR] Remove useless file argument from FirCallResolver 2020-03-02 09:07:23 +03:00
Dmitriy Novozhilov
807d41028e [FIR] FirComponentCall rendered same as FirFunctionCall 2020-03-02 09:07:23 +03:00
Toshiaki Kameyama
266149b88c RedundantLetInspection: fix false positive with nullable receiver extension call
#KT-31601 Fixed
2020-03-02 10:21:47 +07:00
Ilya Kirillov
a6139f3635 Wizard: minor: fix YamlParsingError package 2020-03-01 21:32:36 +03:00
Ilya Kirillov
a9c96a7cde Wizard: move downloading Kotlin version phase to the end 2020-03-01 19:07:51 +03:00
Ilya Kirillov
a03510e3c0 Wizard: add tags for project templates 2020-03-01 19:07:50 +03:00
Ilya Kirillov
d639816393 Wizard: use kotlinx-collections-immutable for storing IRs 2020-03-01 19:07:49 +03:00
Nikolay Krasko
e38448c6f2 No need to hack PsiSubstitutor anymore in AS 40 (KT-36039)
Remove KotlinCoreApplicationEnvironment for AS 40 after platform update.
2020-03-01 00:37:44 +03:00
Vyacheslav Gerasimov
b1ca06b21d Build: Add missing tools.jar to performance tests runtime 2020-02-29 23:30:27 +03:00
Vyacheslav Gerasimov
05b5894ef1 Build: Use configurations property for shadowJar in :kotlin-main-kts
It marked as classpath and improves cache reuse between different builds
2020-02-29 16:36:02 +03:00
Vyacheslav Gerasimov
0db69cadb6 Build: Make all compile dependencies on toolsJar compileOnly
tools.jar differs between different versions of JDK reducing cache reuse
so better to not leak it to other modules
2020-02-29 16:35:54 +03:00
Vyacheslav Gerasimov
8e0f403f02 Build: normalize inputs of :kotlin-reflect:stripMetadata as classpath 2020-02-29 16:33:34 +03:00
Vyacheslav Gerasimov
6e2fb72bb6 Build: Make :kotlin-reflect:relocateCoreSources task cacheable 2020-02-29 16:33:34 +03:00
Vyacheslav Gerasimov
0ebc11270b Build: Remove duplicated manifestAttributes call from reflectShadowJar
manifestAttributes call done in the result jar
2020-02-29 16:32:02 +03:00
Vyacheslav Gerasimov
54d8afea40 Build: Disable caching for Test tasks until we are sure it is safe
#KT-37089
2020-02-29 16:32:01 +03:00
Vyacheslav Gerasimov
5195cc8c12 Build: Add buildserver.labs.intellij.net to valid hosts in caching check 2020-02-29 16:32:01 +03:00
Vyacheslav Gerasimov
b64c7cce84 Build: Use Jar task for :kotlin-compiler:packCompiler
Right now can't be cached between builds because of compiler version.
We may move module containing compiler version directly to the final jar
2020-02-29 16:32:00 +03:00
Vyacheslav Gerasimov
35c4cc6d45 Build: Use Jar task instead ShadowJar task in :kotlin-daemon-client-new 2020-02-29 16:31:59 +03:00
Vyacheslav Gerasimov
07949aaf4f Build: Use Jar task instead ShadowJar task in :kotlin-daemon 2020-02-29 16:31:59 +03:00
Vyacheslav Gerasimov
6c8c126ebc as40: Update to AS 4.0 Beta 1 2020-02-29 16:15:11 +03:00
Sergey Rostov
7359bb8a00 Fix tests freeze because of ScriptChangesNotifier (KT-37112)
#KT-37112 Fixed
2020-02-29 01:14:26 +03:00
Dmitry Petrov
03913ff029 KT-33119 Generate IINC for primitive types only 2020-02-28 23:20:02 +03:00
Dmitry Petrov
2010d8d2b9 KT-36956 fix back-end part in JVM and JVM_IR
PSI2IR: deparenthesize LHS expression when generating assignment
receiver.

FE: record 'set' operator call for code generation.
2020-02-28 23:04:42 +03:00
Sergey Igushkin
f764d3a021 testCompileOnlyDependencyProcessingForMetadataCompilations -> Gradle 5+
This test fails with Gradle 4.9 due to a Gradle bug when Gradle is
unable to pick up task dependencies from providers nested into a file
collection. That doesn't seem feasible to fix.
2020-02-28 20:09:45 +03:00
Sergey Igushkin
b8602fa31a Fix missing installation dependencies in Gradle integration tests 2020-02-28 20:09:45 +03:00
Vladimir Dolzhenko
197e096017 Disable PerformanceNativeProjectsTest 2020-02-28 17:36:46 +01:00
Vladimir Dolzhenko
bc0e466981 Add undo typing kts performance test 2020-02-28 17:36:33 +01:00
Steven Schäfer
4ac45eb38b JVM IR: Fix inline class constructors taking default values of inline class type. 2020-02-28 17:11:59 +01:00
Vladimir Dolzhenko
846e50a0c0 Backport ActionUtil.underModalProgress to fix 191/192 compilation
Relates to #EA-143709
2020-02-28 15:16:26 +01:00
Nikolay Krasko
d47fc7280b Fix testUnresolvedMultiline test data 2020-02-28 16:51:12 +03:00
Nikolay Krasko
50c92f2a05 Bad string interpolation for empty string in batch (KT-37090)
#KT-37090 Fixed
2020-02-28 16:51:12 +03:00
Steven Schäfer
b173284d1d Add tests for super calls in inline classes 2020-02-28 14:48:17 +01:00
Steven Schäfer
0fe8fec1d1 Mute FIR tests 2020-02-28 14:48:17 +01:00
Steven Schäfer
465e9f2d68 JVM IR: Always produce stubs for interface methods in inline classes
This matches the behavior of the JVM backend, with the exception of
@JvmDefault methods, which are currently broken on the JVM backend.
2020-02-28 14:48:17 +01:00
Steven Schäfer
8c9ebc1bf9 JVM IR: Initialize parent field in InlineCallableReferenceToLambda 2020-02-28 14:48:17 +01:00
Mikhail Glukhikh
c2eab08cc9 FIR: fix arose problem with smartcast un-stability 2020-02-28 15:36:19 +03:00
Mikhail Glukhikh
d5fbd93fe6 Unmute additional FIR black box tests
This was result of comparison commits together (?) with override commits
2020-02-28 15:29:03 +03:00
Mikhail Glukhikh
9e69ffad36 FIR2IR (refactoring): introduce ConversionTypeContext 2020-02-28 15:29:03 +03:00
Mikhail Glukhikh
883dd95e3c FIR: fix class / constructor type parameter duplication 2020-02-28 15:29:02 +03:00
Mikhail Glukhikh
2308e5bb7c FIR2IR: in case of use-site generic type use call from original class 2020-02-28 15:29:02 +03:00
Mikhail Glukhikh
096dc25701 FIR: change callableId of fake overrides to derived class owner 2020-02-28 15:29:02 +03:00
Mikhail Glukhikh
db7401d8eb FIR2IR: set GET_PROPERTY origin for property reads 2020-02-28 15:29:01 +03:00
Mikhail Glukhikh
e066afc67f FIR2IR: set parents for external enum entries 2020-02-28 15:29:01 +03:00
Mikhail Glukhikh
5b3b35cd78 FIR2IR: set "external stub" origin for external enum entries 2020-02-28 15:29:01 +03:00
Mikhail Glukhikh
3a3d6e740c FIR2IR: correctly set type parameters of property accessors
In particular, we generate different type parameters for
getters & setters here.
2020-02-28 15:29:01 +03:00
Mikhail Glukhikh
50abb07245 [FIR] Record & use type arguments of FirQualifiedAccessExpression 2020-02-28 15:29:00 +03:00
Ilya Matveev
f53b059410 [Gradle, tests] Fix native compiler arguments test for Windows 2020-02-28 17:50:55 +07:00
Toshiaki Kameyama
0b9106b0f8 CanBePrimaryConstructorPropertyInspection: do not report for 'open' property used in class initializer in 'open' class 2020-02-28 17:21:56 +07:00
Georgy Bronnikov
963258189a JVM_IR: change parameter type computation in InlineCallableReferenceToLambda
The reference type is approximated in Psi2Ir, so we may get Nothing as
a reference type argument. Better look at the arguments of the
referenced function.
2020-02-28 12:59:21 +03:00
pyos
456139fc5e JVM_IR: cache signatures in BridgeLowering
`mapAsmMethod` is somewhat slow, so this helps if there are a lot of
overrides of same methods and/or deep class hierarchies in a single file
(though it would probably help more if lowerings were not reconstructed
for every file).
2020-02-28 12:32:26 +03:00
Ilya Kirillov
97e320b57f Don't show IR_COMPILED_CLASS error in IJ when it arises in module with backend IR enabled
The problem here is that library resolver uses global project compiler
settings instead of the module ones. That behaviour is caused by more
global problem described in #KT-21246

As a temporary solution we just do not show IR_COMPILED_CLASS error in
IDE if it arises in a module which have -XuseIR or
-Xallow-jvm-ir-dependencies option provided

#KT-36907 fixed
2020-02-28 11:45:51 +03:00
Nikolay Krasko
7a4d414c59 201: Mute SuggestedRefactoring tests 2020-02-28 11:36:42 +03:00
Nikolay Krasko
6a9dfd4935 201: Mute HierarchicalMultiplatformProjectImportingTest: No module dependency found 2020-02-28 11:36:41 +03:00
Nikolay Krasko
774db02b23 201: Mute quick fix tests: Range must be inside element being annotated 2020-02-28 11:36:41 +03:00
Nikolay Krasko
06adac1abf 201: Mute TodoSearchTest: duplicate TODO items 2020-02-28 11:36:41 +03:00
Nikolay Krasko
543168c61d 201: Mute incremental compilation tests with constants 2020-02-28 11:36:40 +03:00
Nikolay Krasko
8501ea78c8 201: Mute a lot of tests with enums 2020-02-28 11:36:40 +03:00
Nikolay Krasko
79e663828a 201: Mute QuickFixTestGenerate: Range must be inside element being annotated 2020-02-28 11:36:39 +03:00
Nikolay Krasko
f5a97ea56e 201: Mute GradleScriptInputsWatcherTest failures 2020-02-28 11:36:39 +03:00
Nikolay Krasko
dad7fd383c 201: Upgrade nodejs plugin in 201 branch 2020-02-28 11:36:39 +03:00
Nikolay Krasko
f0a4f838f2 201: Mute NewMultiplatformProjectImportingTest tests
No module dependency found
No source folder found
2020-02-28 11:36:38 +03:00
Nikolay Krasko
f4cd25ce72 201: Mute MultiplatformProjectImportingTest tests
Failed search dependency in Gradle tests.
2020-02-28 11:36:38 +03:00
Nikolay Krasko
67dee52b8a 201: Mute NewJavaToKotlinConverterSingleFileTestGenerated tests 2020-02-28 11:36:38 +03:00
Nikolay Krasko
958b8a0b10 201: Fix maven plugin loading by adding repository-search to runtime 2020-02-28 11:36:37 +03:00
Nikolay Krasko
0fcd011abb 201: Fix loading project in configuration tests
De-bunch AbstractConfigureKotlinTest.kt, just don't use field in 193.
2020-02-28 11:36:37 +03:00
Nikolay Krasko
1a01ba0ae5 201: Trick idea home path exception with custom idea.home variable 2020-02-28 11:36:36 +03:00
Nikolay Krasko
da2683d180 Copy 192 muted tests 2020-02-28 11:36:36 +03:00
Nikolay Krasko
dd21736471 Register JDK for default project to prevent create leaking one for Gradle import 2020-02-28 11:36:36 +03:00
Nikolay Krasko
c9fd79c311 Enable mute in code for all KotlinLightCodeInsightFixtureTestCaseBase 2020-02-28 11:36:35 +03:00
Nikolay Krasko
1c0a9d2981 Minor: better asserts in TodoSearchTest.kt 2020-02-28 11:36:35 +03:00
Nikolay Krasko
26df2a5c68 Enable mute test with database in BaseKotlinJpsBuildTestCase 2020-02-28 11:36:34 +03:00
Nikolay Krasko
31ba40cc99 Ignore auto-mute files 2020-02-28 11:36:34 +03:00
Nikolay Krasko
c22272bbca Enable mute for KotlinCompletionTestCase 2020-02-28 11:36:34 +03:00
Nikolay Krasko
66e2f95dba Update method after UsefulTestCase update to make in work in 201 2020-02-28 11:36:33 +03:00
Nikolay Krasko
3c3b1bb5e4 Support auto-mute in parametrized JUnit 4 tests 2020-02-28 11:36:33 +03:00
Nikolay Krasko
f042b04320 Minor: remove unneeded class 2020-02-28 11:36:32 +03:00
Mikhail Zarechenskiy
14f7529c1b [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:25:22 +03:00
Vladimir Dolzhenko
aab8555d65 Move adjustExtractionData.performAnalysis under modal progress
Relates to #143709
2020-02-28 08:02:45 +01:00
Vladimir Dolzhenko
ec431460b3 Do not lookup for kotlin tests in non kotlin files
Fixed #EA-220086
2020-02-28 08:02:45 +01:00
Vladimir Dolzhenko
2a27ca828c Commit document before actual imports optimization
Fixed #EA-209827
2020-02-28 08:02:44 +01:00
Vladimir Dolzhenko
acc4118903 Provide import alias suggestion for Companion
Fixed #EA-223797
2020-02-28 08:02:44 +01:00
Vladimir Dolzhenko
3ec2095c9f Don't log ControlFlowException
Fixed #EA-223788
2020-02-28 08:02:44 +01:00
Steven Schäfer
3881220386 JVM IR: Box arguments in abstract method stubs for "remove" bridges 2020-02-28 09:20:29 +03:00
kovalp
86f9cb6eef Adds AdditionalExtractableAnalyser EP.
Adds annotations to ExtractableCodeDescriptor.
Adds functionality of adding annotations to KtPsiFactory.CallableBuilder
2020-02-28 12:38:09 +07:00
Ilya Gorbunov
b53cb5cb4c Cover with a test current Double/Float companion values access 2020-02-28 01:26:56 +03:00
Vladimir Dolzhenko
1f47c6d54f Add missed calcHashCode for ModuleSourceScope subclasses 2020-02-27 21:17:25 +01:00
pyos
035cc57cf4 JVM_IR: don't remap current method signature when detecting clashes
TODO: don't repeatedly map signatures of inherited functions either.
2020-02-27 22:17:19 +03:00
Dmitry Petrov
ad0070ed8a KT-37059 Support 'String?.plus(Any?)' in JVM_IR 2020-02-27 22:13:32 +03:00
simon.ogorodnik
f9483b1f4f [FIR] KT-37027: Add 'out' projection to vararg elements 2020-02-27 19:07:17 +03:00
simon.ogorodnik
f405b3f827 [FIR] Reorganize ConeKotlinTypeProjection hierarchy 2020-02-27 19:07:16 +03:00
simon.ogorodnik
7c4f59dfcb [FIR] KT-37009: Fix loss of bound smart-cast due to synthetic removal 2020-02-27 19:07:16 +03:00
simon.ogorodnik
ec936b7286 [FIR] Setup FIR tests configuration 2020-02-27 19:07:16 +03:00
Denis Zharkov
fbf4abf0cf FIR: Unignore FIR2IR test 2020-02-27 19:01:32 +03:00
Denis Zharkov
53454a783c Fix project compilation 2020-02-27 18:54:26 +03:00
Denis Zharkov
8fca343ef0 FIR: Support FirComparisonOperator in Fir2Ir
^KT-31163 Fixed
2020-02-27 18:21:34 +03:00
Denis Zharkov
434444cd69 FIR: Support FirComparisonOperator in body transformers and DFA
^KT-31163 In Progress
2020-02-27 18:21:34 +03:00
Denis Zharkov
c3aed433ae FIR: Support FirComparisonOperator in builders
^KT-31163 In Progress
2020-02-27 18:21:34 +03:00
Denis Zharkov
80b7fbd07a FIR: Add new nodes kind for comparison operator
^KT-31163 In Progress
2020-02-27 18:21:34 +03:00
Svyatoslav Kuzmich
3ecee5c7cd [JS IR BE] Implement kotlin.js.jsTypeOf as intrinsics 2020-02-27 16:54:55 +03:00
Svyatoslav Kuzmich
dff7d7b7b9 [PSI2IR] Patch parents before referenceExpectsForUsedActuals
There were some ADAPTER_FOR_CALLABLE_REFERENCE functions with
uninitialized parents at this point.
2020-02-27 16:54:55 +03:00
Svyatoslav Kuzmich
1e02fa3db9 [JS IR BE] Create temporary variables with wrapped descriptors. 2020-02-27 16:54:55 +03:00
Svyatoslav Kuzmich
8877bac873 [JS IR BE] Don't fail typeOf lowering on reified type parameters. 2020-02-27 16:54:55 +03:00
Svyatoslav Kuzmich
b359bf1859 [JS IR BE] Stop checking mangling for klib-to-js compilation.
It it broken.
2020-02-27 16:54:55 +03:00
Svyatoslav Kuzmich
cd80eced32 [JS IR BE] Use fresh name for external JsModule declarations. 2020-02-27 16:54:55 +03:00
nataliya.valtman
5c6f452c10 Revert "add cleanup dependencies tasks for buildSrc"
This reverts commit 8a8536f8
2020-02-27 15:23:47 +03:00
Anton Bannykh
e7816b4ec2 JS: support callable references with vararg and default parameters conversion 2020-02-27 15:12:49 +03:00
Dmitriy Novozhilov
f6a23ea441 [FIR] Add infrastructure for call checkers 2020-02-27 15:11:10 +03:00
Dmitriy Novozhilov
9cee2962db [FIR] Add more nodes for declaration checkers 2020-02-27 15:11:09 +03:00
Nikita Skvortsov
04424a1ec3 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 2020-02-27 15:01:34 +03:00
Mikhael Bogdanov
a9e03937a3 Minor. Update tests to support them on Android 2020-02-27 12:28:19 +01:00
nataliya.valtman
8a8536f8ae add cleanup dependencies tasks for buildSrc
change embedded kotlin version to bootstrap for buildSrc
2020-02-27 13:55:58 +03:00
Dmitry Petrov
ea7b5827ab Minor: update testData for bytecode listing tests 2020-02-27 13:36:24 +03:00
Dmitry Gridin
5827be4182 Tests: fix test for AS 3.6 2020-02-27 15:39:27 +07:00
Dmitriy Dolovov
ca3c72c143 IDE perf tests for Kotlin/Native projects
Issue #MMPP-201
2020-02-27 15:23:41 +07:00
Vladimir Ilmov
f5e6001d82 Registry key to show hidden variables in debugger. 2020-02-27 08:59:08 +01:00
Abduqodiri Qurbonzoda
e19c0c9768 Update idea-completion testData after introducing vararg maxOf/minOf 2020-02-27 02:24:49 +03:00
Valentin Kipyatkov
12bf8a44e7 Minor changes after code review 2020-02-26 22:57:35 +01:00
Valentin Kipyatkov
b9a9000569 Suggested Rename and Change Signature implementation for Kotlin 2020-02-26 22:57:34 +01:00
Vyacheslav Karpukhin
a01b840eab Android Import: Search for Android SDK using public API instead of reflection 2020-02-26 19:03:48 +01:00
Dmitriy Dolovov
ec23c25286 [Commonizer] Friendly displaying commonized KLIBs in IDE
Issue #MMPP-195
2020-02-27 00:35:03 +07:00
Anton Bannykh
23e218396e JS: support SAM conversion
The SAM adapter is generate on declaration site. This is different
from the JVM approach.

`external fun interface` is banned for now.

Reusing interface declaration for the adapter is a hack which
reduces code size and makes importing/exporting the adapter
effortless.
2020-02-26 18:57:11 +03:00
Anton Bannykh
2742e643c1 JS: prohibit external fun interface 2020-02-26 18:57:11 +03:00
Anton Bannykh
f20ed39b92 Fix a typo in an error message 2020-02-26 18:57:11 +03:00
Anton Bannykh
a01e66a618 Run IrJsTypeScriptExportTestGenerated tests with jsIrTest instead of jsTest 2020-02-26 18:57:11 +03:00
Kristoffer Andersen
c1d350f8f3 [JVM IR] Added null-checks of handler for non-super $default calls 2020-02-26 16:28:27 +01:00
Abduqodiri Qurbonzoda
fe50bb4b93 KProperty and ReadOnlyProperty type parameter names #KT-16529 2020-02-26 17:34:03 +03:00
Mikhail Zarechenskiy
5ed28b38be [NI] Fix coroutine inference for qualified chained call with stub type 2020-02-26 17:16:15 +03:00
Dmitry Petrov
a47c818a3c Minor: update testData in box tests with signature check 2020-02-26 16:02:04 +03:00
Ilmir Usmanov
af5a381c2b Minor. Use java 6 construct in test
So, the test can be run on android.
2020-02-26 13:23:12 +01:00
Roman Artemev
bb43a66716 [Metadata] Add platform dependent type transformer
- Fix forward declaration type construction
2020-02-26 14:55:54 +03:00
Roman Artemev
25a91a217e [KLIB] Fix package for NullFlexibleTypeDeserializer 2020-02-26 14:55:53 +03:00
Anton Bannykh
b744ee0aa4 JS IR: Remove nested blocks from bodies 2020-02-26 14:51:18 +03:00
Anton Bannykh
7152156659 JS IR: Don't yield methods with no body 2020-02-26 14:51:18 +03:00
Sergey Bogolepov
71cc288a14 [Linker][IdSignature] Rename classFqn property
classFqn is incorrect since this property represents
FqName of any declaration, including properties, functions and
type aliases.
2020-02-26 17:48:38 +07:00
Sergey Bogolepov
221d24c597 [Linker] Do not generate wrapped descriptor if descriptor is provided
Fixes metadata-based interop in Kotlin/Native.
2020-02-26 17:48:38 +07:00
Mikhail Zarechenskiy
6eec8c28ad 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:16:05 +03:00
Stanislav Erokhin
74348d5ffb 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
2020-02-26 12:12:35 +03:00
Stanislav Erokhin
453008e488 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.
2020-02-26 12:12:31 +03:00
Dmitry Petrov
84baa0b4c2 Check more flags in bytecode listing tests 2020-02-26 12:03:37 +03:00
Ilya Goncharov
ee9be61c20 [Gradle, JS] Fix propogation useCommonJs to irTarget
#KT-37036 fixed
2020-02-26 11:40:45 +03:00
Ilya Goncharov
7719dfca4a [Gradle, JS] Fix timeout for debug
#KT-37035 fixed
2020-02-26 11:36:17 +03:00
Ilya Kirillov
870b7d234f Wizard: refactoring do not use context directly in UI 2020-02-26 11:19:09 +03:00
Ilya Kirillov
ad39d0520a Wizard: use first enum entry as default value for enumSetting 2020-02-26 11:19:08 +03:00
Ilya Kirillov
3967522c08 Wizard: fix Android minifyEnabled call for groovy 2020-02-26 11:19:08 +03:00
Ilya Kirillov
7e22572324 Wizard: add configuration for Android MPP target 2020-02-26 11:19:08 +03:00
Ilya Kirillov
3eca687611 Wizard: move module configurator settings to companion objects 2020-02-26 11:19:08 +03:00
Ilya Kirillov
4c62f64396 Wizard: minor, not to use reading context directly in some places 2020-02-26 11:19:08 +03:00
Ilya Kirillov
8259bf749d Wizard: always use all plugin set in tests 2020-02-26 11:19:08 +03:00
Ilya Kirillov
7a3d730aec Wizard: refactoring: rename contexts
TaskRunningContext -> WriteContext,
ValuesReadingContext -> ReadingContext
2020-02-26 11:19:08 +03:00
Ilya Kirillov
1c49b230f4 Wizard: force service to always return non-null value 2020-02-26 11:19:07 +03:00
Ilya Kirillov
05022109fc Wizard: save some setting values in UI
#KT-35585 fixed
2020-02-26 11:19:07 +03:00
Ilya Kirillov
9e47d0b33c Wizard: move Android SDK Setting to AndroidPlugin 2020-02-26 11:19:07 +03:00
Ilya Kirillov
9c5ff6c131 Wizard: create Gradle wrapper 2020-02-26 11:19:07 +03:00
Ilya Kirillov
6228fa4d3e Wizard: remove unused function 2020-02-26 11:19:07 +03:00
Ilya Kirillov
7448b8beb0 Wizard: fix invalid android package name
#KT-36169 fixed
2020-02-26 11:19:07 +03:00
Ilya Kirillov
2600ebb961 Wizard: use custom module icons for every module kind 2020-02-26 11:19:06 +03:00
Ilya Kirillov
299b0f0102 Wizard: prettify error messages 2020-02-26 11:19:06 +03:00
Ilya Kirillov
72f92d7a3b Wizard: use IntelliJ validator in UI instead of custom one 2020-02-26 11:19:06 +03:00
Ilya Kirillov
1431649c4d Wizard: use Kotlin Gradle Icon for Gradle Kotlin build system 2020-02-26 11:19:06 +03:00
Ilya Kirillov
e1b99580eb Wizard: introduce Android & JS multiplatform project kinds
#KT-36155 fixed
2020-02-26 11:19:06 +03:00
Ilya Kirillov
a5a72a89fc Wizard: allow to create multiple JVM targets
#KT-36177 fixed
2020-02-26 11:19:06 +03:00
Ilya Kirillov
bb455ec8f6 Wizard: make error messages in ui clickable
#KT-36162 fixed
2020-02-26 11:19:06 +03:00
Ilya Kirillov
087de68b3a Wizard: flatten JVM targets
#KT-36267 fixed
2020-02-26 11:19:06 +03:00
Ilya Kirillov
54c9582ac4 Wizard: fix wrong line separators
#KT-36328 fixed
2020-02-26 11:19:05 +03:00
Ilya Kirillov
fa4d790f5a Wizard: add jvm target setting for JVM configurations
#KT-36180 fixed
2020-02-26 11:19:05 +03:00
Ilya Kirillov
fabb0584da Wizard: remove module types for some module configurators
#KT-36176 fixed
2020-02-26 11:19:05 +03:00
Ilya Kirillov
0123dbce21 Wizard: trim paths in UI
#KT-36163 fixed
2020-02-26 11:19:05 +03:00
Ilya Kirillov
152def62cb Wizard: get current Kotlin version from compiler
#KT-35693 fixed
2020-02-26 11:19:05 +03:00
Dmitry Gridin
50c2c38624 Tests: fix some tests in formatter for AS 2020-02-26 13:51:47 +07:00
Dmitry Gridin
ca598b6465 Formatter: fix indent after trailing comma in calls
#KT-36917 Fixed
2020-02-26 10:55:58 +07:00
Abduqodiri Qurbonzoda
1f721796b8 Add vararg overloads for maxOf/minOf functions #KT-33906 2020-02-26 04:17:19 +03:00
Vyacheslav Gerasimov
5aae3b5d27 Build: Add localBuildCacheDirectory property to KotlinBuildProperties 2020-02-25 19:37:33 +03:00
Vyacheslav Gerasimov
fc2161c2a6 Build: Don't cache :kotlin-compiler:proguard
Requires to mark inputs of proguard task properly
2020-02-25 19:17:02 +03:00
Dmitry Savvinov
428dcd847f Flip default value of kotlin.gradle.testing.enabled to true 2020-02-25 17:18:49 +03:00
nataliya.valtman
d82dc86c71 Reverts commit 13afb2e4 (buildSrc bootstrap version) 2020-02-25 17:08:51 +03:00
Sergey Rostov
5e16373af6 .gradle.kts, changes notifier: process events async and on pooled thread
#KT-36401 Fixed
2020-02-25 16:00:20 +03:00
Mikhail Zarechenskiy
5393074d61 [NI] Update type of complex subcall for last lambda expressions 2020-02-25 15:26:25 +03:00
Dmitry Savvinov
66ef49cecc 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 15:09:49 +03:00
Ilya Kirillov
b21a9476c0 New J2K: minor, use firstNotNullResult in j2k reference resolver 2020-02-25 13:58:29 +03:00
Ilya Kirillov
b7711678c2 EA-218474: fix IAE in resolving empty fqName in new J2K 2020-02-25 13:58:29 +03:00
Ilya Kirillov
af5a70dcf5 EA-218043: fix getting resolution facade for empty list of elements in new J2K 2020-02-25 13:58:29 +03:00
Ilya Kirillov
a64526acfb EA-210533: fix NPE in LiftReturnOrAssignmentInspection
It may be still active after its application due to slow IDEA responsiveness
Do not try to apply it again on invalid PSI elements
2020-02-25 13:58:29 +03:00
Ilya Kirillov
9af30f4ac7 EA-210362: fix invalid cast to KtFile in KtCodeFragment 2020-02-25 13:58:28 +03:00
Ilya Kirillov
7f50dcb3a8 EA-210234: Fix invalid access to Java resolution facade
Do not try to get Java resolution facade for non-Java PSI elements
2020-02-25 13:58:28 +03:00
Ilya Kirillov
af6d5b76f5 EA-209576: Fix access to disposed module in gradle importer 2020-02-25 13:58:28 +03:00
Steven Schäfer
2b6a0d6c58 JVM IR: Don't create $annotations stubs for fake overridden properties 2020-02-25 11:31:01 +01:00
Alexander Gorshenev
3eed0609b2 Brought back mppKlibs guard lost in rebase 2020-02-25 13:26:11 +03:00
Dmitry Gridin
36ebbc49f4 KotlinExpressionMover: trailing comma support
#KT-34744
2020-02-25 17:13:43 +07:00
Dmitry Gridin
72c8b38864 KotlinExpressionMover: convert to Kotlin 2020-02-25 17:10:58 +07:00
Dmitry Gridin
bca9242492 KotlinExpressionMover: rename .java to .kt 2020-02-25 17:03:28 +07:00
Dmitry Gridin
56064f2a92 JoinLines: add tests 2020-02-25 17:03:28 +07:00
Dmitry Gridin
feaa53c4f2 Formatter: shouldn't format property chains
#KT-36387 Fixed
#KT-36466 Fixed
2020-02-25 16:48:33 +07:00
Mikhail Glukhikh
522eeae062 FIR2IR: standardize expression with smart cast conversion
To convert smart cast expression, now we just convert
original expression in standard way and wrap it with TYPE_OP.
Before this commit original expression was converted in different way,
that led to errors e.g. for this expression casting.
2020-02-25 12:13:42 +03:00
Mikhail Glukhikh
d1fac6dce1 FIR2IR: declare receivers for all accessors of extension properties
Before this commit, extension receivers were declared only for
properties with container source, which is strange & inconsistent.
Now we declare accessor extension receiver iff corresponding property
has extension receiver.
2020-02-25 12:13:42 +03:00
Mikhail Glukhikh
8c155578f7 FIR2IR: generate both dispatch & extension receiver without 'else if' 2020-02-25 12:13:42 +03:00
Juan Chen
4f6fe1d0ca [FIR]: fix translation of top-level property accesses like array.indices
This commit addresses the following issues:

* accessors didn't take into account their property's receiver type,
which caused NoSuchMethod due to signature mismatch. Now the property's
receiver type is passed to Fir2Ir translation of accessors.

* property's parent was not class, e.g., kotlin.collections.indices.
Now the symbol table collects WrappedPropertyDescriptorWithContainerSource
besides WrappedFunctionDescriptorWithContainerSource, so that
facade classes for such properties can be generated before codegen.

* accessor's parent was not class. Now the containerSource of
the property descriptor is passed to accessor descriptor.
2020-02-25 12:13:42 +03:00
Vladimir Dolzhenko
c9658eb6e4 Adjust tests due to keep imports for extension functions used in kdoc
Relates to #KT-27601
2020-02-25 09:29:39 +01:00
Vladimir Dolzhenko
afd71d3d19 Adjust tests due to "Remove argument" quick fix for TOO_MANY_ARGUMENTS
Relates to #KT-34026
Relates to #KT-34332
2020-02-25 09:23:46 +01:00
Dmitry Petrov
b047d78580 Minor: update testData for IR bytecode text and unmute test 2020-02-25 11:17:08 +03:00
Mikhail Zarechenskiy
0b9fc1541d [NI] Don't try inferring variables for effectively empty system 2020-02-25 10:45:59 +03:00
Kristoffer Andersen
fe71d5256c [Minor] Refactor IR Suspend Main code to not use intrinsic 2020-02-24 19:33:43 +01:00
pyos
a3d85e108f JVM_IR: keep suspend fun return type in IrCalls
Otherwise:

  * should the dispatch receiver of a call be another call to a `suspend
    fun` wrapped in something that is optimized away later, the owner of
    the method will be incorrect;

  * references to functions returning non-Unit but casted to `() ->
    Unit` (allowed by new inference) might in fact not return Unit after
    tail call optimization.
2020-02-24 17:12:43 +01:00
Mads Ager
d982203d56 [JVM_IR] Handle big arity suspend functions in existing lowering.
Now that suspend function views are created in
AddContinuationLowering, we can let the
FunctionNVarargBridgeLowering deal with rewriting of large
arity FunctionN/SuspendFunctionN.
2020-02-24 13:01:18 +01:00
Toshiaki Kameyama
e406669190 Invert if condition intention: don't add unnecessary 'continue'
#KT-12329 Fixed
2020-02-24 11:17:20 +01:00
Toshiaki Kameyama
62e335ac88 Implement members: fix it works correctly for data class
#KT-36686 Fixed
2020-02-23 22:00:38 +01:00
Georgy Bronnikov
fe009ac695 IR: restore reading common Klib from JVM
Adapt to changes in linker
2020-02-23 14:55:29 +03:00
Toshiaki Kameyama
d54a35ef56 Add "Remove argument" quick fix for TOO_MANY_ARGUMENTS
#KT-34026 Fixed
#KT-34332 Fixed
2020-02-23 10:17:10 +01:00
nataliya.valtman
13afb2e45e Make kotlin build version for buildSrc the same as for kotlin project 2020-02-23 09:02:22 +03:00
Toshiaki Kameyama
699ea0aa2b Replace 'if' with 'when': don't swallow comments if there is no synthetic else branch
#KT-34640 Fixed
2020-02-22 16:50:37 +01:00
Toshiaki Kameyama
f487118be5 Change signature: fix it works correctly when call site function has no value argument list
#KT-23510 Fixed
2020-02-22 09:07:34 +01:00
kvirolainen
223ed1ad60 KT-27601 review fixes 2020-02-22 08:55:50 +01:00
kvirolainen
90cfa80683 KT-27601 keep imports for extension functions used in kdoc 2020-02-22 08:55:50 +01:00
Dmitry Savvinov
423aeb9a08 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-21 20:00:21 +03:00
Toshiaki Kameyama
e56abcbb85 Inline variable: fix it works correctly for 'when' subject variable
#KT-29870 Fixed
2020-02-21 17:30:13 +01:00
Toshiaki Kameyama
d8ab046136 Convert property to function: remove annotation use-site target
#KT-36834 Fixed
2020-02-21 17:03:26 +01:00
Toshiaki Kameyama
d5e71ebef1 Invert if condition intention: 'isEmpty' <-> 'isNotEmpty'
#KT-34593 Fixed
2020-02-21 16:39:35 +01:00
Toshiaki Kameyama
79c15e49b6 Convert function to property: suggest on fun keyword
#KT-34450 Fixed
2020-02-21 16:32:17 +01:00
Toshiaki Kameyama
820b8c3c54 Introduce "Redundant '?: return null'" inspection
#KT-34819 Fixed
2020-02-21 16:24:42 +01:00
Toshiaki Kameyama
5f1cc3b152 Introduce "Redundant 'inner' modifier" inspection
#KT-3262 Fixed
2020-02-21 16:12:49 +01:00
Dmitriy Dolovov
d76dc6f57e [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-21 21:54:15 +07:00
Mikhail Zarechenskiy
f2f95496e3 [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 17:39:50 +03:00
Toshiaki Kameyama
3398683093 Unused symbol: do not report for secondary constructor when class is used as typealias
#KT-20907 Fixed
2020-02-21 15:11:38 +01:00
Mikhail Glukhikh
81f1f441fc [FIR] Add stub default values to kotlin.Enum constructor parameters 2020-02-21 16:39:00 +03:00
Mikhail Glukhikh
39bd97147f [FIR] Don't create initializers for simple enum entries
Usually FIR enum entry is initialized by anonymous object,
which is the container for all enum entry' declarations.
However, for simple enum entries there is no need of initializer at all.
2020-02-21 16:38:52 +03:00
Mikhail Glukhikh
b1e9dbf994 [FIR] Use super<Enum> as delegated calls in enum constructors 2020-02-21 16:37:56 +03:00
Mikhail Glukhikh
f173af9238 FIR2IR: use enum constructor call for enum entries 2020-02-21 16:37:50 +03:00
Mikhail Glukhikh
9e3f17c52a [FIR TEST] Add test for unresolved reference in default argument
See KT-36905
2020-02-21 16:37:10 +03:00
Toshiaki Kameyama
a3252b9480 Unused symbol: fix false positive in anonymous object in top level or companion object
#KT-31800 Fixed
#KT-20868 Fixed
2020-02-21 14:36:18 +01:00
Toshiaki Kameyama
ef1e54eda9 ReplaceToStringWithStringTemplateInspection: insert curly braces if needed
#KT-36735 Fixed
2020-02-21 14:28:07 +01:00
Toshiaki Kameyama
c87bc2123c Add "Change to val" quick fix for MUST_BE_INITIALIZED
#KT-15723 Fixed
2020-02-21 14:09:54 +01:00
Nikolay Krasko
a46c6ce5df Revert global project settings to LATEST_STABLE in teardown 2020-02-21 16:07:24 +03:00
Nikolay Krasko
f995192f21 Always configure and restore api version settings in tests 2020-02-21 16:07:24 +03:00
Nikolay Krasko
6c83e9fb85 Clean LANGUAGE_VERSION_SETTINGS after the test 2020-02-21 16:07:24 +03:00
Nikolay Krasko
19bc39d3ab Clean facet if it wasn't set before test (fix tests on 201) 2020-02-21 16:07:23 +03:00
Nikolay Krasko
af3b057ba2 Always clean language and api versions after usage 2020-02-21 16:07:23 +03:00
Nikolay Krasko
c0dac9bf32 Refactoring: extract long function out of local context 2020-02-21 16:07:23 +03:00
Nikolay Krasko
3a5f42cc5e Refactoring: always use compiler settings with de-configuration in tests 2020-02-21 16:07:23 +03:00
Nikolay Krasko
018215f47d De-bunch KotlinLightCodeInsightFixtureTestCase.kt 2020-02-21 16:07:23 +03:00
Pavel Punegov
94be4d77ff Fix init order in inline fun (native test) 2020-02-21 16:04:53 +03:00
Toshiaki Kameyama
19093e2e02 Redundant companion reference: fix false positive when companion has same name member as companion name
#KT-36707 Fixed
2020-02-21 13:57:04 +01:00
Vasily Levchenko
98ce49ba73 [build][native] version with milestone clause 2020-02-21 13:51:20 +01:00
Vladimir Dolzhenko
7053f1d00c Drop CancellationCheck usage from 193
Relates to #KT-36891
2020-02-21 13:40:48 +01:00
Toshiaki Kameyama
5a6cf19c68 Complete statement for class declaration: add '()' to supertype
#KT-31668 Fixed
2020-02-21 13:21:26 +01:00
Dmitry Petrov
e9a7be4a46 Fix intersection type handling in PSI2IR 2020-02-21 15:11:16 +03:00
Mikhail Zarechenskiy
1624327ba4 [NI] Fix substitution in builder-inference for empty common system 2020-02-21 14:24:57 +03:00
pyos
c5ffbfd33c JVM_IR: mark origins of capture fields in suspend lambdas 2020-02-21 12:11:19 +01:00
pyos
6b98ea2378 JVM_IR: do not place suspend markers around crossinline lambda calls 2020-02-21 12:11:19 +01:00
pyos
39ebc8cfa5 Add a suspend test that fails on JVM_IR 2020-02-21 12:11:19 +01:00
Ilmir Usmanov
52e7cd5725 JVM_IR: Remove $$forInline suffix for fake inliner variables
Otherwise, IDE will not be able to navigate to inline functions.
 #KT-36797 Fixed
2020-02-21 12:08:25 +01:00
Ilmir Usmanov
325ad14ac9 JVM_IR: Treat suspend main wrapper as always tail-call function
In other words, never generate suspend call markers inside it.
2020-02-21 12:00:54 +01:00
Ilmir Usmanov
8c4eef9844 JVM_IR: Return COROUTINE_SUSPENDED from suspend main wrapper
Before, if the code inside suspend main suspended, the wrapper would
just ignore it and return Unit. This was a signal for runSuspend to exit
main loop and return said Unit.
Instead of poping whatever suspend main returns, just return it.
2020-02-21 12:00:52 +01:00
Kristoffer Andersen
5b62c9e54d [WIP] Add Compiler Smoke Tests for (suspend) main methods
This commit ports the (parameterless) main integration tests in
`CompilerSmokeTest` to the IR backend. It also includes a simple
suspend main test.

The advanced ones (like `helloAppSuspendParameterlessMain`) are
currently blocked by pending changes to capturing suspend lambdas,
which are underway.
2020-02-21 12:00:50 +01:00
Kristoffer Andersen
55aafb3430 [JVM IR] Support Suspend Main
This adds supports for (parameterless) suspend main entry points for
the JVM IR backend.

In case main is a suspend function, it gains a continuation during
lowering, so we simply generate a plain old `public static void
main(String[] args)`. This entry point invokes `suspend main` via
`kotlin.coroutines.jvm.internal.RunSuspendKt#runSuspend`.

This PR introduces `runSuspend` as a built-in, and generates the
following `main`, passing `args` as appropriate:

```
fun main(args: Array<String>) {
  runSuspend { main(args) }
}
```

The phase ordering has been reshuffled countrary to previous
discussion on #2780, as the MainMethodGeneration pass now introduces lambdas in
the IR. Hence, it has to run before InventNamesForLocalClasses, yet
still after JvmOverloadsAnnotations.

Some dead code was discovered in AddContinuationLowering
2020-02-21 12:00:47 +01:00
Ilya Goncharov
068d547375 [Gradle, JS] UpperCased KotlinJsCompilerType 2020-02-21 13:14:36 +03:00
Ilya Goncharov
9acd98071e [Gradle, JS] Divide KotlinJsCompilerAttribute 2020-02-21 13:14:36 +03:00
Ilya Goncharov
cc97138e9c [Gradle, JS] Extract JS presets container, no js in codegen since now 2020-02-21 13:14:36 +03:00
Ilya Goncharov
fa335b5360 [Gradle, JS] Js default compiler type for mpp 2020-02-21 13:14:36 +03:00
Ilya Goncharov
8dc75def19 [Gradle, JS] Use default configuration names only once in constants 2020-02-21 13:14:36 +03:00
Ilya Goncharov
664775a43f [Gradle, JS] Configure compiler type with single platform plugin 2020-02-21 13:14:35 +03:00
Ilya Goncharov
e631146fa7 [Gradle, JS] Fix DSL for Gradle JS wizard 2020-02-21 13:03:21 +03:00
Ilya Goncharov
3ae6b27556 [Gradle, JS] Fix DSL for JVM/JS wizard
#KT-36889 fixed
2020-02-21 13:03:18 +03:00
Abduqodiri Qurbonzoda
6670a2fff8 Update public api dump 2020-02-20 21:14:52 +03:00
Ilya Goncharov
569decce43 [Gradle, JS] Fix missed import 2020-02-20 19:32:35 +03:00
Ilya Goncharov
d114945b76 [Gradle, JS] Change message in polite manner
#KT-36489 fixed
#KT-36843 fixed
2020-02-20 19:32:35 +03:00
Ilya Goncharov
e0be8f271f [Gradle, JS] Not error, but warning with test fix 2020-02-20 19:32:35 +03:00
Ilya Goncharov
40fb6c67d2 [Gradle, JS] Add diagnostic messages for js targets 2020-02-20 19:32:34 +03:00
Ilya Goncharov
aefaa6dc7f [Gradle, JS] Remove deprecated configurations 2020-02-20 19:32:34 +03:00
Ilya Goncharov
92291c03e8 [Gradle, JS] Add methods with string definition of compiler 2020-02-20 19:32:34 +03:00
Ilya Goncharov
203ca018e5 [Gradle, JS] Rename public KotlinJsCompilerType 2020-02-20 19:32:34 +03:00
Ilya Goncharov
488538889b [Gradle, JS] Extract JS presets container, no js in codegen since now 2020-02-20 19:32:34 +03:00
Ilya Goncharov
956b57a55d [Gradle, JS] Do not duplicate target initialization 2020-02-20 19:32:34 +03:00
Ilya Goncharov
881de0a538 [Gradle, JS] Make default configuration of target 2020-02-20 19:32:34 +03:00
Ilya Goncharov
9112da2ad7 [Gradle, JS] Create predefined source sets for single platform plugin 2020-02-20 19:32:34 +03:00
Ilya Goncharov
06be32550b [Gradle, JS] Fix lib and app test for both type 2020-02-20 19:32:34 +03:00
Ilya Goncharov
a5602165ec [Gradle, JS] Fix names for js mpp 2020-02-20 19:32:33 +03:00
Ilya Goncharov
e1f7296426 [Gradle, JS] Fast test with both js compilers 2020-02-20 19:32:33 +03:00
Ilya Goncharov
37b3b3ec56 [Gradle, JS] Js default compiler type for mpp 2020-02-20 19:32:33 +03:00
Ilya Goncharov
3d30598774 [Gradle, JS] Js compiler type in interface 2020-02-20 19:32:33 +03:00
Ilya Goncharov
36631a5954 [Gradle, JS] Fix parallel tests 2020-02-20 19:32:33 +03:00
Ilya Goncharov
86e13c25b3 [Gradle, JS] Default conpiler type instead of legacy 2020-02-20 19:32:33 +03:00
Ilya Goncharov
ae89507736 [Gradle, JS] Add fish for js only lib-app test 2020-02-20 19:32:33 +03:00
Ilya Goncharov
16eb23c6b1 [Gradle, JS] Remove test with lib and app with not only legace
Because of performance reasons

- Fix usage of compiler type property
2020-02-20 19:32:33 +03:00
Ilya Goncharov
13594c80aa [Gradle, JS] Declare default configurations in js single plugin
Because in Kotlin DSL we want to declare configurations in methods instead of extensions of Strings
We need to create configurations explicitly in plugin
2020-02-20 19:32:33 +03:00
Ilya Goncharov
f3f818edc3 [Gradle, JS] Use default configuration names only once in constants 2020-02-20 19:32:32 +03:00
Ilya Goncharov
d9c08945a3 [Gradle, JS] Common dependency configurations for both js 2020-02-20 19:32:32 +03:00
Ilya Goncharov
ecb89ad259 [Gradle, JS] Disambiguation classifier consider single platform plugin 2020-02-20 19:32:32 +03:00
Ilya Goncharov
4189bc88c2 [Gradle, JS] Provide disambiguation classifier for both mode 2020-02-20 19:32:32 +03:00
Ilya Goncharov
b967e11511 [Gradle, JS] Configure compiler type with single platform plugin 2020-02-20 19:32:32 +03:00
Ilya Goncharov
22e826770d [Gradle, JS] Functions in extensions for configure compiler type 2020-02-20 19:32:32 +03:00
Ilya Goncharov
1346883837 [Gradle, JS] Fix published name for both compiler 2020-02-20 19:32:32 +03:00
Ilya Goncharov
185f7419d5 [Gradle, JS] Refactor with remove copypaste 2020-02-20 19:32:32 +03:00
Ilya Goncharov
397ff26e20 [Gradle, JS] With both compilers fully disambiguated names 2020-02-20 19:32:32 +03:00
Ilya Goncharov
ae391f3776 [Gradle, JS] Fix codegen for js platform 2020-02-20 19:32:31 +03:00
Ilya Goncharov
1bebcd398e [Gradle, JS] Move JsCompilerType to Gradle Plugin API 2020-02-20 19:32:31 +03:00
Ilya Goncharov
82d31adb24 [Gradle, JS] Remove js compiler property from MPP plugin 2020-02-20 19:32:31 +03:00
Ilya Goncharov
4af389ba92 [Gradle, JS] Rename target on js in case of single platform 2020-02-20 19:32:31 +03:00
Mikhail Glukhikh
285f613ef7 [FIR TEST] Add test with unresolved member in nested lambdas (KT-36887) 2020-02-20 19:25:50 +03:00
Zalim Bashorov
6f61ea7f67 [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
2020-02-20 19:10:29 +03:00
Pavel Kirpichenkov
07ca355af8 [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-20 19:07:54 +03:00
Abduqodiri Qurbonzoda
afceec71a4 Create an interface with provideDelegate() method #KT-26494 2020-02-20 18:57:52 +03:00
Abduqodiri Qurbonzoda
2566fbea87 toMutableList documentation is vague #KT-35231 2020-02-20 18:52:10 +03:00
Abduqodiri Qurbonzoda
f9ee1dc22d Specify which element Iterable.distinctBy(selector) retains #KT-36356 2020-02-20 18:50:13 +03:00
Mikhail Glukhikh
fb49a586ef FIR2IR: add comment about type parameter indexes 2020-02-20 18:34:52 +03:00
Mikhail Glukhikh
984a11995a FIR2IR: pre-cache type parameters before property creation
Type parameters can be referred from e.g. property accessors,
so we should determine them earlier to be able to set their indexes
2020-02-20 18:34:52 +03:00
Mikhail Glukhikh
a3f676317f FIR2IR: pre-cache type parameters before function creation
Type parameters can be referred from e.g. function return type,
so we should determine them earlier to be able to set their indexes
2020-02-20 18:34:51 +03:00
Mikhail Glukhikh
899d471646 FIR2IR: determine type parameters before class super types
Type parameters can be referred from type arguments of super types,
so we should determine them earlier to be able to set their indexes
2020-02-20 18:34:51 +03:00
Mikhail Glukhikh
8c21f04bf4 FIR2IR: determine type parameters before value parameters
Type parameters can be referred from value parameters,
so we should determine them earlier to be able to set their indexes
2020-02-20 18:34:51 +03:00
Mikhail Glukhikh
334cab7357 [FIR] Don't build redundant fake overrides for private members
The only case we may need fake override for private members is
a situation when class refers itself with different type arguments.
So in this commit we forbid such fake overrides when we can prove
that class does not refers itself here.
2020-02-20 18:34:51 +03:00
Mikhail Glukhikh
b4d026f5bf [FIR] Add fast return from substitution scope when substitutor is empty 2020-02-20 18:34:50 +03:00
Mikhail Glukhikh
a6d11b0207 [FIR] Don't create redundant substitution scopes 2020-02-20 18:34:50 +03:00
Mikhail Glukhikh
01053c938a Generate IGNORE_BACKEND_FIR in black box tests properly 2020-02-20 18:11:43 +03:00
Mikhail Zarechenskiy
d921dd0eed Provide candidate interceptor for NI infrastructure 2020-02-20 18:07:12 +03:00
Igor Yakovlev
4693d595b7 Fix UL classes tests
Fixed #KT-36717
2020-02-20 18:03:10 +03:00
Sergey Igushkin
f47e602118 Use Kotlin/Native version 1.4-dev-14579, as it has the newest klib ABI 2020-02-20 17:48:24 +03:00
Mikhail Glukhikh
ace5d0357c [FIR TEST] Add problematic test describing KT-36881 2020-02-20 17:38:31 +03:00
Konstantin Tskhovrebov
018cfc7df6 Fix class name for test suite descriptor.
Issue #KT-36725 Fixed
Issue #KT-36716 Fixed
Issue #KT-36726 Fixed
2020-02-20 17:37:06 +03:00
Roman Golyshev
1dbb3d7c0f Revert "New J2K: fix testdata"
This reverts commit 285aa123
2020-02-20 17:33:39 +03:00
Roman Golyshev
4042214bb2 Fix tests broken by enhanced RedundantSamConstructor inspection
- The inspection now works in more cases, so the test data had to be
updated accordingly
2020-02-20 17:27:41 +03:00
Dmitriy Novozhilov
22a5bc4144 [FIR-TEST] Add build tasks for running all fir tests
- `:firCompilerTest` run all compiler fir tests
- `:idea:firTest` run all IDE fir tests
- `:firAllTest` run all fir tests
2020-02-20 16:56:34 +03:00
Dmitriy Novozhilov
82c960d40d [FIR-TEST] Run fir test in diagnostic test if fir testdata is missing 2020-02-20 16:56:34 +03:00
Dmitriy Novozhilov
d4d4697202 [FIR-TEST] Fix creating dirs in FirLoadCompiledKotlin test 2020-02-20 16:56:34 +03:00
Dmitriy Novozhilov
3edbf7f541 [FIR-TEST] Move abstract diagnostics tests to tests-common module 2020-02-20 16:56:34 +03:00
Dmitriy Novozhilov
102d5c7d5a [NI] Fix detecting expected type variable for postponed atoms
#KT-36819 Fixed
2020-02-20 16:56:33 +03:00
Vladimir Dolzhenko
7e832e50ac Move copy/paste resource bundles to Kotlin
#KT-36877 #EA-224686 Fixed
2020-02-20 14:06:11 +01:00
Dmitry Petrov
bc7c8e4819 Update bytecode text tests for JVM_IR 2020-02-20 14:59:29 +03:00
Yan Zhulanow
7581e0bd8e Unmute noParametersArgumentCallInExpression test in JVM IR backend 2020-02-20 20:56:36 +09:00
Juan Chen
9dd8eda1c9 [FIR]: fix library methods in packages
Library methods such as 'listOf' are resolved
to have the package fragments as their parents,
but JVM expects their containing file classes as parents.
This fix generates those file classes and
uses them as parent replacements for such library methods.
2020-02-20 14:24:02 +03:00
Dmitry Petrov
81b30b7399 Update bytecode text tests for JVM_IR 2020-02-20 14:20:21 +03:00
Denis Zharkov
071149e0fb Fix exception when Java class has different methods with same erasure
^KT-36856 Fixed
2020-02-20 14:06:13 +03:00
Vladimir Ilmov
7efb32628e [Highlight] Fix for coloring annotation attributes in Kotlin
#KT-36156 Fixed
2020-02-20 11:51:42 +01:00
Vladimir Ilmov
8d4dac398d [COROUTINE] Information message added if breakpoint policy doesn't suspended all
threads.
2020-02-20 11:51:42 +01:00
pyos
eff02b6e72 JVM_IR: improve suspend tail call detection.
* TailCallOptimizationLowering should go into local classes in order to
   transform their suspend methods;
 * the check for invokes of noinline lambda arguments in codegen was
   incorrect, as it also returned true for calls of lambdas stored in
   local variables;
 * IrInlineCodegen should mark non-inlinable arguments used as inline
   suspend parameters;
 * detection of suspend/inline call sites was incorrect (or maybe it's
   the `compilationContextDescriptor` that was incorrect?..)
2020-02-20 11:10:26 +01:00
Steven Schäfer
3cf71c1d2b JVM IR: Move $assertionsDisabled field to interface DefaultImpls 2020-02-20 11:07:46 +01:00
Steven Schäfer
0ed719f792 JVM IR: Use package visibility for $assertionsDisabled field 2020-02-20 11:07:46 +01:00
Mikhail Zarechenskiy
d169435300 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-20 12:34:35 +03:00
Mikhail Zarechenskiy
83824d0ba6 [NI] Don't stop on a candidate with unstable smartcast error
#KT-36847 Fixed
2020-02-20 12:34:34 +03:00
Mikhail Zarechenskiy
162a2d5851 [NI] Add test to check how behavior will be changed after few commits 2020-02-20 12:34:34 +03:00
Sergey Igushkin
0e970407a4 Fixup for 9b861739 (the fix for KT-35942)
* Don't include the JS friend paths into the classpath
* Fix binary compatibility with Gradle < 5.1

Issue #KT-35942
2020-02-19 23:10:53 +03:00
Mikhail Glukhikh
3921613956 [FIR] Code cleanup: DeclarationsConverter 2020-02-19 22:47:59 +03:00
Mikhail Glukhikh
5d7999a808 [FIR] Handle explicitly private sealed class constructors properly
#KT-36850 Fixed
2020-02-19 22:41:24 +03:00
Mikhail Glukhikh
17b473fcb6 FirTowerResolver: code cleanup 2020-02-19 22:41:24 +03:00
Mikhail Glukhikh
f1a418373c RawFirBuilder: code cleanup 2020-02-19 22:41:24 +03:00
Mikhail Glukhikh
e66d6a8954 [FIR] ClassWrapper: code cleanup 2020-02-19 22:41:24 +03:00
Mikhail Glukhikh
bbf448b39d [FIR] Change visibility of default sealed class constructor to private 2020-02-19 22:41:23 +03:00
Mikhail Glukhikh
14fd1d3c9f [FIR] Check visibility correctly for sealed class in file 2020-02-19 22:41:23 +03:00
Mikhail Glukhikh
ace259314b Use 'symbol' instead of 'classId' in FirResolvedQualifier
This commit solves problem with resolved qualifier of local class
#KT-36758 Fixed
2020-02-19 22:41:23 +03:00
Mark Punzalan
3d51af2935 [JVM IR] Fix issue with suspend functions with @JvmOverloads. 2020-02-19 16:48:53 +01:00
Mikhail Glukhikh
c289612e57 [FIR] Remove debugging println in tree generator 2020-02-19 18:14:45 +03:00
Mikhail Glukhikh
a4c4b2650c FIR2IR: remove hacky & redundant resolve of delegating constructor calls 2020-02-19 18:09:06 +03:00
Mikhail Glukhikh
82c8b5f368 [FIR] Eliminate isNotSAM optimization as ineffective (see dc4f332c) 2020-02-19 18:09:06 +03:00
Mikhail Glukhikh
9017654b9d [FIR] Handle default parameters when checking callable reference type
#KT-36759 Fixed
2020-02-19 18:09:06 +03:00
Mikhail Glukhikh
04e6c63cc9 FirSymbolProvider: minor cleanup 2020-02-19 18:09:06 +03:00
Mikhail Glukhikh
1376dbf9cf Remove unused 'dispatchReceiverValue()' from FIR tower levels 2020-02-19 18:09:05 +03:00
Mikhail Glukhikh
e051251b27 FIR: set isOperator only for Java methods with appropriate names
#KT-35133 Fixed
2020-02-19 18:09:04 +03:00
Mikhail Zarechenskiy
cbbbf40b90 [NI] Fix isSuccessful property for member with LowPriority resolution
The problem was introduced in e40ba73950
2020-02-19 18:06:22 +03:00
simon.ogorodnik
8ca2aa47f8 [FIR] Remove duplicated code 2020-02-19 17:53:44 +03:00
simon.ogorodnik
c29c140a9c [FIR] Qualifier resolve 2020-02-19 17:53:44 +03:00
Sergey Igushkin
723ebb4f57 Fix compileOnly dependencies in HMPP (KT-36469)
The `compileOnly` configuration of a source set was not included in the
granular dependency transformation, which led to the dependencies from
the configuration being excluded as unrequested during dependency
processing.

Fix this by properly including the compileOnly scope into the
dependencies transformation.

Issue #KT-36469 Fixed
2020-02-19 17:30:46 +03:00
Sergey Igushkin
9b861739cd Include the production artifacts in friend paths (KT-35942)
In some setups, the friendArtifacts that we had in addition to direct
associate compilations' output classes were insufficient. For example:

1. When an Android module's tests depend on another module which
   transitively depends on the module containing tests: then the AGP
   API doesn't tell us that there are artifacts from the tested
   variant, but instead there's just the module's artifact.

2. Similar case but without Android, and if the classes are read from
   the module's artifact rather than the production output classes dir,
   then they are definitely not on the friend paths (which include the
   production classes dirs and not the the production artifact).

In both cases, the friendArtifacts mechanism allows us to add those
potential sources of the friend classes to the friend paths.

Issue #KT-35942 Fixed
2020-02-19 17:30:45 +03:00
Vladimir Dolzhenko
4eb04af01e Add checkStability to perf tests 2020-02-19 15:26:19 +01:00
Denis Zharkov
a6cf16ddfc FIR: Fix test data for FirMultiModuleResolveTestGenerated 2020-02-19 17:21:11 +03:00
Roman Golyshev
46ae6136cb Rewrite RedundantSamConstructorInspection to support more cases
- Now inspection does not rely on synthetic descriptors at all, instead
it uses `SamConversionOracle` and `SamConversionResolver` to detect
if the argument type support SAM conversion
- This transparently considers all language features like
`SAM conversions for kotlin functions`, `Functional interfaces` etc.
- In case of multiple SAM arguments, part of them can be converted only
when `SAM conversion per argument` is enabled
- Fix inspection and nj2k tests that were failing because of better
working inspection
- Rewrite automatically fixes multiple bugs that were present
- ^KT-36367 ^KT-36368 ^KT-36296 ^KT-36395 Fixed
2020-02-19 17:16:17 +03:00
Roman Golyshev
9b5110b9f3 Refactor RedundantSamConstructorInspection
- Does not change the behaviour
2020-02-19 17:16:17 +03:00
Roman Golyshev
3122760c49 Add more tests for RedundantSamConstructorInspection
- All those tests already pass, they are needed to fix the behaviour of the inspection before the changes
2020-02-19 17:16:17 +03:00
Victor Petukhov
e8524137c3 NI: exclude not fixed type variables from types on which null checks should be generated
^KT-36371 Fixed
2020-02-19 15:58:08 +03:00
Victor Petukhov
f10696da5e Fix formatting of RuntimeAssertion.kt 2020-02-19 15:58:08 +03:00
Denis Zharkov
6793b27330 FIR: Optimize Java types mapping
- Avoid duplicated computations for arguments
- Do not recreate types if they weren't enhanced
2020-02-19 15:53:34 +03:00
Denis Zharkov
c8269baa92 FIR: Fix NI handling flexible type bounds 2020-02-19 15:53:34 +03:00
Denis Zharkov
2ad8488e6a FIR: Rewrite Java type mapping
Previoisly, there were two places where mapping had happened:
- toConeKotlinTypeWithNullability
- enhancePossiblyFlexible

The first one was used for supertypes and bounds and the second one
was used for other signature parts

The main idea is to perform type mapping once to a flexible type,
and then use it as it's needed (it's lower bound, or for the further ehnancement)

Also, this commit fixes flexibility for type arguments, see the tests
2020-02-19 15:53:34 +03:00
Victor Petukhov
748a326104 NI: Discard definitely not-null types inside invariant positions during inference process
^KT-36816 Fixed
2020-02-19 15:32:12 +03:00
Roman Golyshev
36f4b6daf3 Update completion-ranking-kotlin dependency 2020-02-19 14:16:48 +03:00
pyos
3080b4c435 JVM_IR: remove a suspend-related hack from BridgeLowering
`invoke` in suspend lambdas overrides FunctionN.invoke, so the
refactored BridgeLowering already generates correct bridges there.
All the hack does is break overrides of interface suspend methods.
2020-02-19 11:26:45 +01:00
Steven Schäfer
ba90e87756 JVM, JVM IR: Fix assertion status for regenerated anonymous objects
We always set the $assertionsDisabled field based on the top-level
enclosing class. This means that for anonymous objects we have to
rewrite the call to Class.desiredAssertionStatus.
2020-02-19 11:23:24 +01:00
Steven Schäfer
272f6abe69 JVM IR: Fix suspend lambda generic signatures 2020-02-19 11:18:27 +01:00
pyos
e6efb81014 JVM_IR: inline findSuspendAndInlineLambdas 2020-02-19 10:47:27 +01:00
pyos
5d603a8be4 JVM_IR: detect lambdas capturing crossinline through fields 2020-02-19 10:47:27 +01:00
Ilya Kirillov
285aa123b7 New J2K: fix testdata 2020-02-19 12:02:32 +03:00
Ilya Kirillov
17a0e3a078 New J2K: do not call custom diagnostic fixes in EDT as they may have resolve inside 2020-02-19 12:02:31 +03:00
Ilya Kirillov
810966e408 New J2K: call reformat code & shorten references processings only single time 2020-02-19 12:02:30 +03:00
Ilya Kirillov
ee0ec421ce New J2K: do not print Unit types 2020-02-19 12:02:29 +03:00
Ilya Kirillov
6c1e2cc196 New J2K: disable additional post-formatting for J2K
As there is a formatting processing, it's not needed but takes some time
2020-02-19 12:02:28 +03:00
Ilya Kirillov
85be0450ba Fix invalidated element access exception in ObjectLiteralToLambdaIntention
#KT-36149 fixed
#KT-36152 fixed
2020-02-19 12:02:27 +03:00
Ilya Kirillov
6b913da698 New J2K: Fix super call to Kotlin class with implicit constructor
#KT-36159 fixed
2020-02-19 12:02:27 +03:00
Ilya Kirillov
7c586ce736 New J2K: Fix converting recursive types
#KT-36088 fixed
2020-02-19 12:02:26 +03:00
Pavel Semyonov
6982db7d02 chore: improved UI texts for new project wizard 2020-02-19 12:00:30 +03:00
Dmitry Petrov
0b9b1b6945 Update bytecode text tests for JVM_IR 2020-02-18 22:51:29 +03:00
Denis Zharkov
aac72871e7 Fix UI freezes caused by calls with a huge number overloads
While we have an overload resolution algorithm working for O(n^2),
call resolution for the single particular call may work more then just
a second.
Thus, we need to call ProgressManager.checkCanceled() with more granularity

^KT-35135 Fixed
2020-02-18 20:07:14 +03:00
Denis Zharkov
842e2dc02f Optimize retaining most specific methods in LazyJavaScope
See 62a55b7b00
Previously, it was working for O(n^2)
Now, we first group it by jvm descriptor,
then for each groups of size g_i finding the most specific for O(g_i^2)

It should help for the cases when we have a lot of overloads with
different JVM descriptors (modulo return type)
NB: Having the same JVM descriptors is rather rare, because
in Java one cannot generate such a class.

Looks like it's only possible for Scala or some other JVM languages (KT-17560)

It should help a lot for KT-35135
2020-02-18 20:07:13 +03:00
Denis Zharkov
d06e35b061 Minor. Reformat overridingUtils.kt 2020-02-18 19:59:56 +03:00
Pavel Kirpichenkov
a50911156d [NI] Add regression tests for builder inference
Actual fix is c02dd720
^KT-33542 Fixed
^KT-33544 Fixed
^KT-36446 Fixed
2020-02-18 19:12:53 +03:00
Pavel Kirpichenkov
6ed1cc5cd8 [JPS-TESTS] Update incremental compilation test for 1.4
Bug fix `NoConstantValueAttributeForNonConstVals` removes constant attribute from non-constant properties.
Code using such properties does not have to be recompiled, since its value is no longer inlined.
2020-02-18 18:31:47 +03:00
Ilmir Usmanov
f9f715c31e Support suspend lambda with arity 22 in old BE
Somehow, I missed, that its 'create' function has bit arity, while
'invoke' does not. Thus, instead of directly passing arguments of
'invoke' to 'create', pack them into an array first.
2020-02-18 16:21:27 +01:00
Mads Ager
752ff9de5d JVM_IR: Support suspend lambdas with many arguments. 2020-02-18 16:21:25 +01:00
Dmitriy Dolovov
f2b940ffd4 [Commonizer] Apply interner to avoid duplicated CirValueParameterImpl objects 2020-02-18 22:03:55 +07:00
Dmitriy Dolovov
5663dfb772 [Commonizer] Apply interner to avoid duplicated CirSetter objects 2020-02-18 22:03:49 +07:00
Dmitriy Dolovov
e54640ddad [Commonizer] Apply interner to avoid duplicated CirGetter objects 2020-02-18 22:03:41 +07:00
Dmitriy Dolovov
39125a75e7 [Commonizer] Apply interner to avoid duplicated CirAnnotation objects 2020-02-18 22:03:35 +07:00
Dmitriy Dolovov
c88ea2f2e6 [Commonizer] Apply interner to avoid duplicated CirSimpleType objects 2020-02-18 22:03:16 +07:00
Dmitriy Dolovov
84bc151cb3 Minor. Add toString() to CommonizedClassDescriptor.CommonizedClassTypeConstructor 2020-02-18 22:03:10 +07:00
Dmitriy Dolovov
d0e9dc05b5 [Commonizer] Apply interner to avoid duplicated Name objects 2020-02-18 22:03:03 +07:00
Dmitriy Dolovov
47d091702b [Commonizer] Apply interner to avoid duplicated FqName objects 2020-02-18 22:02:57 +07:00
Dmitriy Dolovov
adc5a55d65 [Commonizer] Apply interner to avoid duplicated String objects 2020-02-18 22:02:50 +07:00
Dmitriy Dolovov
667e96f971 [Commonizer] Don't keep references to descriptor objects when they are not needed anymore
This is necessary to reduce overall memory consumption.
2020-02-18 22:02:44 +07:00
Dmitriy Dolovov
9a8a1113db [Commonizer] Don't commonize deprecated functions
1. All functions marked with @Deprecated from Kotlin/Native platform libraries
have DeprecationLevel.ERROR, and therefore practically can not be used by
a developer in their code. So, it does not make sence to keep such
declarations in commonized libraries.

2. Commonization of such functions would also require commonization of
annotations with nested annotations as const values (ex:
@Deprecated(level = DeprecationLevel.ERROR), where both @Deprecated
and DeprecationLevel are annotation classes). This is not implemented yet.
2020-02-18 22:02:38 +07:00
Dmitriy Dolovov
11e0f427ac [Commonizer] Refactor CIR to avoid strong refs on descriptors
This is necessary to reduce memory consumption in commonizer while
processing sets of massive libraries.
Ex: ios_x64 (127 libraries) vs ios_arm64 (127 libraries).
2020-02-18 22:02:29 +07:00
Vladimir Dolzhenko
a0b0f72edf Add missed dependencies for performance tests 2020-02-18 16:00:44 +01:00
Dmitriy Novozhilov
635ff59d10 [FIR] Fix compiler error after 2aeb1ea2 2020-02-18 17:46:43 +03:00
Sergey Igushkin
faa95bfc33 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 16:48:12 +03:00
Vyacheslav Karpukhin
582ce1199f Merge remote-tracking branch 'origin/master' 2020-02-18 14:34:36 +01:00
Vyacheslav Karpukhin
eef86d47a0 Merge branch 'slava/mpp-import-experiments'
# Conflicts:
#	idea/idea-gradle/src/org/jetbrains/kotlin/idea/configuration/KotlinMPPGradleProjectResolver.kt
2020-02-18 14:14:23 +01:00
Vyacheslav Karpukhin
4462ecb280 Simplified SdkLocator usage in AndroidDependencyResolver 2020-02-18 14:10:29 +01:00
Vyacheslav Karpukhin
d9f9c93dc8 KotlinMPPGradleProjectResolver: extracted similar Android checks 2020-02-18 14:10:29 +01:00
Vyacheslav Karpukhin
082c358f9d Removed references to AndroidDependencyResolver from KotlinMultiplatformExtension 2020-02-18 14:10:29 +01:00
Vyacheslav Karpukhin
bdb8811f95 Nullability check 2020-02-18 14:10:29 +01:00
Vyacheslav Karpukhin
aaf939a650 Android dependency resolving stuff moved out of KotlinMultiplatformExtension.kt 2020-02-18 14:10:28 +01:00
Vyacheslav Karpukhin
9788525ec7 Import sources for Android SDK, include proper identifiers for Gradle dependencies 2020-02-18 14:10:28 +01:00
Vyacheslav Karpukhin
663c8e5a46 Import Android modules only if Android Plugin for IDEA is missing 2020-02-18 14:10:28 +01:00
Vyacheslav Karpukhin
ad314e93eb Do not explicitly depend on prerelease Android Gradle Plugin 2020-02-18 14:10:28 +01:00
Vyacheslav Karpukhin
a6e488e2b4 Android import: simplified configuration matching 2020-02-18 14:10:28 +01:00
Vyacheslav Karpukhin
45a0aa04a1 Android import: import R.jar 2020-02-18 14:10:22 +01:00
Vyacheslav Karpukhin
17059682e9 Android import: initial implementation 2020-02-18 14:10:13 +01:00
Nikolay Krasko
f47e5cb2d0 Make 201 plugin compatible with IDEA trunk (KT-36780)
^KT-36780 Fixed
2020-02-18 16:08:27 +03:00
Dmitriy Novozhilov
6941cd6d28 [FIR] Add @PrivateForInline to prevent setting to var's from inconvenient places 2020-02-18 16:06:11 +03:00
Dmitriy Novozhilov
2aeb1ea234 [FIR] Move some util methods from resolve.calls to types package 2020-02-18 15:19:34 +03:00
Dmitriy Novozhilov
cd3fc5b8ec [FIR] Reorganize packages for resolve module 2020-02-18 15:19:34 +03:00
Dmitriy Novozhilov
41d2f41141 [FIR] Fix incorrect smartcasts from || expressions
#KT-36057 Fixed
2020-02-18 15:19:34 +03:00
Dmitriy Novozhilov
89e377763a [FIR] Change rendering for captured types and stub types 2020-02-18 15:19:33 +03:00
Dmitriy Novozhilov
c83244c8b5 [FIR] Fix creating and substituting definitely not null types
#KT-36764 Fixed
2020-02-18 15:19:33 +03:00
Dmitriy Novozhilov
bf11f1892d [FIR] Change order of initialization synthetic fun in SAM resolution
It's needed because of `substitutedReturnType` relies on bounds
  of type parameters that should be build before access via symbol
  from lookup tag
2020-02-18 15:19:33 +03:00
Pavel Kirpichenkov
6430209074 [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-18 14:46:29 +03:00
Dmitry Petrov
6d1da6e6d5 KT-36143 Fix type approximation for type arguments in PSI2IR 2020-02-18 14:39:12 +03:00
Nikolay Krasko
2340a86d8d Update to 201.5259.13-EAP-SNAPSHOT
- No UIUtil.removeLeakingAppleListeners anymore
- getParameterHints nullability
- versions of lz4-java and guava were changed
2020-02-18 14:13:55 +03:00
Nikolay Krasko
6c968859ad Access to test root disposable through accessor 2020-02-18 14:13:55 +03:00
Nikolay Krasko
272ccf64ae Refactoring: extract resetApplicationToNull to separate file 2020-02-18 14:13:54 +03:00
Ilmir Usmanov
c748b6f3ee JVM_IR. Minor. Update bytecode text test to JVM_IR or create issues when this
is not feasible.
2020-02-18 11:43:37 +01:00
Steven Schäfer
4b954c347a JVM IR: Avoid optimizing comparisons between boxed primitives and null
A comparison of the form `x == null` where `x` is of type `Int` might not
be vacuous if `x` is a boxed value coming from Java code.
2020-02-18 13:37:48 +03:00
Pavel Kirpichenkov
32e1ec8e98 [minor] Update build output in test to fit NI 2020-02-18 11:19:19 +03:00
Pavel Kirpichenkov
64590cc56b [JPS-TEST] Update test checking JPS build with NI in IDE
Set explicit 1.3 version to disable NI during compilation
2020-02-18 11:19:19 +03:00
Pavel Kirpichenkov
2ead2fba08 [IDEA-TESTS] Update quickfix test parameters for 1.4
Tests check language feature `ProhibitVarargAsArrayAfterSamArgument`
2020-02-18 11:19:18 +03:00
Mikhail Glukhikh
fdf4f477a6 FIR2IR: fix problems with enum entry / anonymous object visibility 2020-02-18 10:50:03 +03:00
Ilya Goncharov
9f0ef77531 [Gradle, JS] Provide js compilations parameters to link tasks
#KT-36796 fixed
2020-02-18 09:35:36 +03:00
Abduqodiri Qurbonzoda
ce8e511b79 Add setOfNotNull function #KT-35851 2020-02-18 02:33:59 +03:00
Abduqodiri Qurbonzoda
5a4ce2aa4c Mark shared global vals to fix K/N worker thread crash 2020-02-18 01:49:24 +03:00
Dmitry Petrov
94d20d9176 Update bytecode text tests in JVM_IR 2020-02-17 23:52:48 +03:00
Mark Punzalan
64141b8b38 [JVM IR] Fix issue where fields are not being set to their default
values within initializer blocks.

The issue occurs in code like this:
```
class C {
  var b = true
  init {
    b = false   // Missing PUTFIELD for this statement
  }
}
```

Added a new statement origin for field initialization (at declaration)
instead of relying on `origin == null` in ExpressionCodegen to determine
whether to generate the initializations.

This was unintentionally broken in
d68a1898d0.
2020-02-17 23:04:11 +03:00
Mikhail Glukhikh
56c819f06e FIR2IR: add two-statements block with iterator + while for 'for' loops
Before this commit we had two statements blocks for 'for' loops:
range variable declaration + iterator variable declaration + while loop.
However, BE requires a bit different loop structure to make lowerings
properly so in this commit iterator declaration & while loop were
extracted to separate block.
2020-02-17 20:35:17 +03:00
Mikhail Glukhikh
2bfce4f127 FIR2IR: provide correct origins for 'for' loops 2020-02-17 20:35:17 +03:00
Mikhail Glukhikh
83e68be2dc FIR2IR: add declarations to all library classes from kotlin.* package
Before this commit, all library classes were just stubs.
This commit helps to solve problems with some functions
indirectly used by BE, like IntProgression.first.
2020-02-17 20:35:17 +03:00
Mikhail Glukhikh
4a4fb5a590 Raw FIR: eliminate range variable declaration in 'for' loops 2020-02-17 20:35:17 +03:00
Mikhail Glukhikh
4abbcd1267 Unmute two passing FIR black box tests (fixed by commits of demiurg) 2020-02-17 20:35:16 +03:00
Mikhail Glukhikh
91814364de Mute two failing FIR black box tests (broken by commits of demiurg) 2020-02-17 20:35:16 +03:00
Dmitry Savvinov
baa2c56e2d 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:05:50 +03:00
Dmitry Savvinov
cc2884b8ae Add test on multiplatform run configurations in multiproject build
The current behaviour is undesired, see next commit for fix
2020-02-17 20:05:50 +03:00
Dmitry Savvinov
1ea3db90e1 Add ability to render project of run configuration in tests 2020-02-17 20:05:50 +03:00
Victor Petukhov
51edf2b351 NI: introduce warning about implicitly inferred Nothing with existing non-Nothing expected type
^KT-35406 Fixed
2020-02-17 19:43:05 +03:00
Jinseong Jeon
e3184e407d KT-20844 Re-enable stack spilling during inline.
`dx` has entered the final stage of sunset:
https://android-developers.googleblog.com/2020/02/the-path-to-dx-deprecation.html
2020-02-17 15:44:48 +01:00
Vladimir Dolzhenko
c9ed27e674 KT-36685 "Convert to a range check" transform hex range to int if it is compared with "Less" or "Greater"
#KT-36685 Fixed
2020-02-17 14:43:37 +01:00
Dmitriy Novozhilov
811ed1ade4 [FIR] Don't update expression in receiver value with smartcast in candidate factory 2020-02-17 14:45:44 +03:00
Dmitriy Novozhilov
e302e06c73 [FIR-TEST] Add test with nullability annotation problem
#KT-36770
2020-02-17 14:45:44 +03:00
Dmitriy Novozhilov
47d5bbc224 [FIR-TEST] Move fixed tests out problems directory 2020-02-17 14:45:44 +03:00
Dmitriy Novozhilov
e67c8a55bf [FIR-TEST] Add test with callable reference to member of local class
#KT-36758
2020-02-17 14:45:44 +03:00
Dmitriy Novozhilov
d10e56c358 [FIR] Add mapping of primitive types to JVM signatures 2020-02-17 14:45:43 +03:00
Mikhael Bogdanov
031952268a Minor. Disable test on Android 2020-02-17 12:03:08 +01:00
Alexey Tsvetkov
ee2e40ce6b Regenerate test 2020-02-17 13:14:04 +03:00
Mikhail Zarechenskiy
70d416cafd Remove test that become useless after enabling NI everywhere
It checked that with default settings new inference is enabled in IDE
 and SAM conversions are _disabled_. Now this is useless as NI is
 enabled everywhere
2020-02-17 12:38:22 +03:00
Mikhail Zarechenskiy
dfe23e770c Update test about lookups for SAMs after enabling NI
In NI we don't perform lookup if argument is obviously can't be
 adapted by SAM conversion (and here there is no argument at all)
2020-02-17 12:38:21 +03:00
Igor Chevdar
297d296b62 [JS] Respect SKIP_DCE_DRIVEN in tests 2020-02-17 12:21:00 +03:00
Igor Chevdar
9bc7a43991 [IR] [JS_IR] Supported fun interfaces in JS 2020-02-17 12:21:00 +03:00
Pavel Kirpichenkov
4a7b4d655c [NI] Fix completion for ILT when Nothing constraint is present
Full completion should not be done if lower `Nothing`
is the only proper constraint when constraint with ILT type is present.
ILT will be selected as a resulting type and transformed into `Int`
without attention to possible restrictions from outer calls.
2020-02-17 12:02:51 +03:00
Sergey Bogolepov
208c06516b [IR][Serialization] Allow backends to skip files
This change is required for Native interop libraries.
For enums and structs we generate full-blown IR classes that should not
be serialized because they will be generated anew.
2020-02-17 16:00:37 +07:00
Natalia Selezneva
bcf6ee0c0b KotlinDslScriptsModel: pass provider mode properly 2020-02-17 11:44:50 +03:00
Natalia Selezneva
ed6f13cf56 KotlinDslScriptsModel: do not add prepare task for each gradle task invocation
^KT-36090 Fixed
2020-02-17 11:44:50 +03:00
Natalia Selezneva
e40dc37be8 KotlinDslScriptsModel: pass correlationId during the request
^KT-36200 Fixed
2020-02-17 11:42:21 +03:00
Pavel Kirpichenkov
55b836a0ac Mute light class tests
Muted test failures are stable with LV 1.4
Related ticket KT-36717
2020-02-17 10:56:46 +03:00
Pavel Kirpichenkov
fda8d7de8b [IDEA-TESTS] Specify language version in feature-dependent tests
Some quickfixes are relying on diagnostics, that won't be reported
with new language features enabled.
`MixedNamedArgumentsInTheirOwnPosition`
`AllowBreakAndContinueInsideWhen`
2020-02-17 10:56:46 +03:00
Pavel Kirpichenkov
85d7a0f6b1 [IDEA-TESTS] Fix ReplaceProtectedToPublishedApiCallFix
Register error factory in addition to warning factory
2020-02-17 10:56:46 +03:00
Pavel Kirpichenkov
05b00a1302 [JPS-TEST] Update deprecated language version in test 2020-02-17 10:56:46 +03:00
Pavel Kirpichenkov
bd3b23b933 Use LATEST_STABLE version during prerelease in VersionView
^KT-36644 Fixed
2020-02-17 10:56:41 +03:00
Mikhail Zarechenskiy
f9129332b7 [NI] Minor optimisation: don't call extra contains checks 2020-02-17 10:29:47 +03:00
Mikhail Zarechenskiy
724bb1b134 [NI] Force variable substitution for properties with stub types 2020-02-17 10:29:46 +03:00
Mikhail Zarechenskiy
155b716e7e Revert "Disable NewInference for stdlib tests"
This reverts commit cdf5323f8c.
2020-02-17 10:29:46 +03:00
Mikhail Zarechenskiy
18b218bfa8 [NI] Use projected type for constraint like Cap(out A) <: out @Exact T
This is an implicit semantics of Exact annotation
2020-02-17 10:29:46 +03:00
Mikhail Zarechenskiy
3cf77d29b5 Unmute test for NI
It was fixed in 7f6c03c9
2020-02-17 10:29:45 +03:00
Mikhail Zarechenskiy
4542f3b720 [NI] Finish analysis for coerced last lambda expressions if needed 2020-02-17 10:29:45 +03:00
Mikhail Zarechenskiy
220bf6d62f [NI] Update test data 2020-02-16 23:49:50 +03:00
Roman Golyshev
3461effd47 KT-33372 Remove renaming file reference to the contents of the file
- There is still a hack with returning null from `getLastFileReference`,
it is here to keep KT-25674 issue fixed
- Overrides of `bindToElement` are removed, they caused renames of the
file references to their contents
- Code of `KotlinFilePathReferenceContributor.kt` is refactored
- ^KT-33372 ^KT-32514 ^KT-36306 Fixed
2020-02-16 17:08:11 +03:00
Toshiaki Kameyama
7f2cf571b0 Convert to range check: do not transform binaries/hexadecimals to decimals
#KT-36685 Fixed
2020-02-16 15:56:44 +09:00
Steven Schäfer
50c477bee1 Update IR text test expectations for FIR 2020-02-15 22:38:10 +03:00
Kristoffer Andersen
de33b83bb3 Update asFunKSmall.kt 2020-02-15 22:38:10 +03:00
Kristoffer Andersen
577250d73f [FIR] Fix FIR2IR Types on SetVariable Expressions 2020-02-15 22:38:06 +03:00
Kristoffer Andersen
4dc6583f31 Update asFunKSmall.kt 2020-02-15 22:32:23 +03:00
Kristoffer Andersen
4f36e2ccfc [FIR] Fix FIR2IR Types on SetVariable Expressions 2020-02-15 22:32:23 +03:00
Dmitry Petrov
1e7f8ea037 PSI2IR test for coercion to unit in lambda 2020-02-15 22:32:23 +03:00
Steven Schäfer
5760c0be9c JVM IR: Avoid redundant coercions in ExpressionCodegen 2020-02-15 22:32:23 +03:00
Steven Schäfer
2b2ae8a5f1 IR: Optimize implicit integer coercions on constants. 2020-02-15 22:32:23 +03:00
Steven Schäfer
bc2b96f634 IR: Fix return types in IrConstImpl 2020-02-15 22:32:23 +03:00
Sergey Rostov
2677fa7472 .gradle.kts: more clear tooltip for out of project scripts notification
The current text/action/help text may not be clear: action is not related to project import, and help text doesn't make it clear.

#KT-36703 Fixed
2020-02-15 11:38:05 +03:00
Vladimir Dolzhenko
52bf630f6c Add ApplicationUtils.as40 as it does not have CancellationCheck
Relates to #KT-35135
2020-02-15 09:35:56 +01:00
Vladimir Dolzhenko
ba5a335e95 Add missed create in usage of new annotation highlighting API
Relates to #KT-36712
2020-02-15 08:23:58 +01:00
Roman Artemev
3407904e68 [JS IR] Add todo 2020-02-14 18:22:17 +03:00
Roman Artemev
e57d34dd9e Make fix test:
- [JS IR] Unmute fixed tests
 - [IrText] Update testdata
 - [WASM] Temporary turn wasm test off
 - [FirText] Temporary turn fit text tests off
 - [JVM IR] Turn off klib jvm test
 - [IR] Add new test
2020-02-14 18:22:17 +03:00
Roman Artemev
46491c12ee [KLIB] Promote Klib ABI version 2020-02-14 18:22:16 +03:00
Roman Artemev
a411549e38 [KLIB] Fix zipped layout 2020-02-14 18:22:16 +03:00
Roman Artemev
5004bb3636 [Psi2Ir] Fix generation of hashcode for generic inline class 2020-02-14 18:22:16 +03:00
Roman Artemev
6a37955a36 [KLIB] Implement new linker based on IdSignature
- Remove klib dependency on metadata and uniqID
 - Refactored proto format to make it more effective and compact
  -- Use special encoding for some types of data (coordinates, flags, types)
  -- Remove symbols table
  -- Use packed proto list if it is possible
 - Remove extension from metadata
 - Remove special ids for function interfaces
 - Fix klib IO
 - Fix incremental cache
 - General code clean up
2020-02-14 18:22:16 +03:00
Roman Artemev
31d73c5d79 [Psi2Ir] Move to new linkage scheme based on IdSignature
Now SymbolTable operates with two types of symbols (public and private)
In case of Public symbol IdSignature is used as table key
Private one uses descriptor as the key in similar scheme as before
2020-02-14 18:22:16 +03:00
Roman Artemev
df7b7cf61a [K/N] Provide original class id for forward-declared declarataion 2020-02-14 18:22:15 +03:00
Roman Artemev
e81a7f10c1 [KLIB] Implement special encoding for Klib data 2020-02-14 18:22:15 +03:00
Roman Artemev
7688197841 [JS IR] Fix access to coroutine empty context for suspend main 2020-02-14 18:22:15 +03:00
Roman Artemev
cef9ed1dae [IR] Implement new IrSymbol API
- Add predicate whether symbol is PublicAPI
 - Split symbols into 2 types (Public/Private)
 - Fix special implementations
2020-02-14 18:22:15 +03:00
Roman Artemev
bb04eae93e [IR] Implement IdSignature API
- Basic implementation of IdSignature classes and interafces
 - Abstract and platform Ir/Descriptor based signature builders
2020-02-14 18:22:15 +03:00
Roman Artemev
45f036548b [Psi2Ir] Make IrEnumEntry corresponding class always privite 2020-02-14 18:22:15 +03:00
Roman Artemev
d51b14fe3c [IR] Fix classic mangler expect checker 2020-02-14 18:22:15 +03:00
Roman Artemev
0254734bb5 [IR] Refactored Kotlin Mangler API
- Implement abstract Ir-based, Descriptor-based
 mangler computers and export checkers and corresponding platform
 specializations
 - Add runtime verifier which check whether all types of mangler
 produces the same type of data

Note: code migration is not finished yet
2020-02-14 18:22:15 +03:00
Pavel Kirpichenkov
ba25b0faaf [NI] Report unsafe invoke properly for flexible types
`isNullable` check returns `true` for flexible types,
which leads to false positive unsafe invoke error, when
receiver for invoke's property is flexible.
^KT-30695 Fixed
2020-02-14 18:06:35 +03:00
Pavel Kirpichenkov
b161839092 [NI] Report unsafe implicit invoke accordingly to OI
This reverts commit df046683cc.
KT-30695
2020-02-14 18:06:34 +03:00
Dmitriy Novozhilov
1a2d28d25b [FIR-TEST] Add test with callable reference on function with default argument 2020-02-14 17:53:29 +03:00
Dmitriy Novozhilov
3790f31d80 [FIR] Support FirVarargArgumentsExpression in html dump 2020-02-14 17:53:29 +03:00
Dmitriy Novozhilov
e696d1d06a [FIR] Improve mapping arguments to parameters 2020-02-14 17:53:28 +03:00
Vladimir Dolzhenko
2e597a3a32 Use new annotation highlighting API
Fixed #KT-36712
2020-02-14 15:42:45 +01:00
Mikhail Glukhikh
2a55560f3b [FIR TEST] Add test on qualifier resolve priority (corner case) 2020-02-14 17:38:37 +03:00
Mikhail Glukhikh
abfe566255 [FIR] Add object support as implicit invoke receiver 2020-02-14 17:38:31 +03:00
Mikhail Glukhikh
a8a696c7e1 [FIR TEST] Extend test on invoke priorities 2020-02-14 17:38:25 +03:00
Georgy Bronnikov
79060e7f40 IR: handle conflicts in resolveFakeOverride() 2020-02-14 17:20:34 +03:00
Georgy Bronnikov
c71e87068a JVM_IR: in InheritedDefaultMethodsOnClassesLowering, skip bridges when resolving overrides 2020-02-14 17:20:34 +03:00
Svyatoslav Scherbina
829e5908d0 Allow Native @Throws on override when the same list is specified 2020-02-14 17:10:58 +03:00
Shagen Ogandzhanian
3fcdf6c78c Update dukat dependency to 0.0.28 2020-02-14 15:00:29 +01:00
Ilya Goncharov
64f13ab3ae [Gradle, JS] Migrate on strings 2020-02-14 16:36:49 +03:00
Ilya Goncharov
9b462b76d4 [Gradle, JS] Add all possible values of library target as enums 2020-02-14 16:36:49 +03:00
Ilya Goncharov
fbabbfab44 [Gradle, JS] Add webpack output 2020-02-14 16:36:49 +03:00
Natalia Selezneva
dc77df1083 GradleScriptInputsWatcher: move long running operation out of EDT
^KT-36502
2020-02-14 16:18:35 +03:00
Mikhail Zarechenskiy
2d15914d20 Enable new inference in IDE by default 2020-02-14 14:37:23 +03:00
Leonid Startsev
bdf1441c80 Remove special casing for Unit in kotlinx.serialization
Unignore test since it is in muted list and auto-generated
2020-02-14 14:28:51 +03:00
Dmitry Petrov
59cdf3c52e Update bytecode text tests in JVM_IR 2020-02-14 14:07:03 +03:00
Ilya Chernikov
db91b520a5 [minor] Fix test source - avoid warning about uused main args 2020-02-14 11:41:30 +01:00
Ilya Chernikov
6356807997 Reapply "Only create descriptors for candidates with lambda args"
#KT-36247 fixed
A lot of testdata changed because significanly less (error) descriptors
are created for unresolved types, so diagnostics became different.
2020-02-14 11:41:30 +01:00
Dmitry Gridin
238bfe3771 Fix compilation 2020-02-14 12:05:14 +03:00
Yan Zhulanow
1c945430bc Fix class loading deadlock in Error diagnostic classes
Because of non-trivial initialization logic, Errors/ErrorsJvm/etc.
  are prone to class loading issues. This commit prevents them by
  preloading all error on plugin initialization step.
2020-02-14 17:35:19 +09:00
Yan Zhulanow
2f34bc88dc Debugger: Add test for KT-14869 2020-02-14 17:35:19 +09:00
Yan Zhulanow
ea7ffa70b3 Debugger: Add test for KT-34905 2020-02-14 17:35:19 +09:00
Yan Zhulanow
6690f946d6 Debugger: Add test for KT-14296 2020-02-14 17:35:19 +09:00
Yan Zhulanow
6f425ee951 Debugger: Add test for KT-15652 2020-02-14 17:35:18 +09:00
Yan Zhulanow
dd33640238 Debugger: Skip inlined library frames on step over (KT-12016) 2020-02-14 17:35:18 +09:00
Yan Zhulanow
7490c229ac EA-219152 (partially): Support KClass 'unboxing' in debugger
KClass can be 'unboxed' to a plain Java class. Debugger should be aware of this.
Unfortunately, this commit is not enough to fully support this scenario, as it's impossible to invoke KClass methods/extension on java.lang.Class instance. There should be an additional diagnostic that will forbid such calls.
2020-02-14 17:35:18 +09:00
Yan Zhulanow
a7071344f5 EA-219152 (partially): Provide correct PropertyDescriptor for _field 2020-02-14 17:35:18 +09:00
Yan Zhulanow
9c889aab17 EA-213309: Eliminate "Invalid method id" exception 2020-02-14 17:35:18 +09:00
Yan Zhulanow
f6b62f2299 Minor: extract wrapEvaluateException() 2020-02-14 17:35:18 +09:00
Yan Zhulanow
3027fab238 EA-218160: Force-box only assignment l-values 2020-02-14 17:35:18 +09:00
Yan Zhulanow
d539a870ed EA-214668, EA-209980: Use StackFrameProxyImpl with safe implementation of thisObject() 2020-02-14 17:35:18 +09:00
Yan Zhulanow
fabbfdc7f8 EA-214654: Add missing read action 2020-02-14 17:35:18 +09:00
Yan Zhulanow
dc71ab5bb3 EA-211010: Fix receiver parameter name for lambdas passed as value arguments 2020-02-14 17:35:18 +09:00
Yan Zhulanow
b1414fa477 EA-214662: Support property accessors in UastLightIdentifier 2020-02-14 17:35:18 +09:00
Yan Zhulanow
be99f44c4f EA-209623: Check library disposed state 2020-02-14 17:35:18 +09:00
Yan Zhulanow
eb3685d6ac EA-218902: Check PsiElement for validity 2020-02-14 17:35:17 +09:00
Yan Zhulanow
615d24bbd2 Minor: Rename KotlinStepOverInlineFilter to KotlinStepOverFilter 2020-02-14 17:35:17 +09:00
Yan Zhulanow
f4337eede1 Debugger, BE: Support lambda breakpoints for lambdas passed to '@InlineOnly' functions 2020-02-14 17:35:17 +09:00
Yan Zhulanow
f129ab55c5 Debugger: Rewrite step out action
This commit fixes the following tests:
 - KotlinSteppingTestGenerated.Custom.testStepOutInlineFunctionStdlib
 - KotlinSteppingTestGenerated.StepOut.testStepOutSeveralInlineArgumentDeepest
2020-02-14 17:35:17 +09:00
Yan Zhulanow
cc2fe6b0c6 Debugger, BE: Generate original line number after inlining if call is used in an if condition
If a part of an 'if' condition is an inline function call, we need to insert the original condition line after it. Otherwise, the debugger will think it is inside the inline function implementation. Obviously, this breaks stepping – instead of the 'if' body, we go on stepping through the inline function.

This commit fixes 'KotlinSteppingTestGenerated.StepOver#testSoInlineLibFun' test.
2020-02-14 17:35:17 +09:00
Yan Zhulanow
f115bde682 Debugger, BE: Provide Java-like stepping for 'for' loops
- Visit '}' instead of 'for' keyword on post-condition
- Visit 'for' keyword on pre-condition
2020-02-14 17:35:17 +09:00
Yan Zhulanow
8b17718086 Debugger, BE: Make the NOP instruction optimizer save the first NOP, not the last
This commit fixes the following tests:
 - KotlinSteppingTestGenerated.StepOver#testSoInlineLibFun
 - KotlinSteppingTestGenerated.StepOver#testSoInlineIterableFun
 - KotlinSteppingTestGenerated.StepOver#testSoInlineFunOnOneLineFor
2020-02-14 17:35:17 +09:00
Yan Zhulanow
9cba72d5dd Debugger: Remove flaky sleep-based stepping tests 2020-02-14 17:35:17 +09:00
Yan Zhulanow
01a6e7abf3 Debugger, eval4j: Remove eager class loading in findField() (KT-35354) 2020-02-14 17:35:17 +09:00
Yan Zhulanow
8f29f8bc9d Debugger: Rewrite step over action (KT-14296)
The main goal is to make behavior similar to what happens in Java. For instance, now we always skip lambdas.
Also, we can reliably use '$i$f' and '$i$a' synthetic local variables. There is no need in complicated hacks any more.
2020-02-14 17:35:17 +09:00
Yan Zhulanow
b7449c2d6e Debugger, minor: Move Action to its own file, rename to KotlinStepAction 2020-02-14 17:35:17 +09:00
Yan Zhulanow
dd4a8d01c9 Debugger: Remove obsolete hacks needed for old Android dex 2020-02-14 17:35:16 +09:00
Yan Zhulanow
dd743f05c1 Debugger: Remove/change tests for the deprecated Android dex 2020-02-14 17:35:16 +09:00
Yan Zhulanow
f912602ddc Debugger, minor: Move KotlinSourcePosition to top level 2020-02-14 17:35:16 +09:00
Yan Zhulanow
2df646e273 Debugger, minor: Remove unneeded nullability dance 2020-02-14 17:35:16 +09:00
Yan Zhulanow
1a3553cdb7 Debugger: Simplify method filters, use smart pointer in KotlinLambdaMethodFilter 2020-02-14 17:35:16 +09:00
Yan Zhulanow
c6262b5ff2 Debugger, minor: Fix element equivalence check in basic step filter 2020-02-14 17:35:16 +09:00
Yan Zhulanow
fc09534464 Debugger, minor: move step filters to the 'filter' package 2020-02-14 17:35:16 +09:00
Yan Zhulanow
d53c554c8c Debugger, minor: Add missing 'const' modifier 2020-02-14 17:35:16 +09:00
Yan Zhulanow
6d606e5291 Debugger, minor: Move createStepOverCommandWithCustomFilter() to DebuggerSteppingFilter 2020-02-14 17:35:16 +09:00
Yan Zhulanow
26371ea023 Debugger, minor: Update getActiveFilters() implementation, use prepend() 2020-02-14 17:35:16 +09:00
Yan Zhulanow
c196ce5f09 Pill: Pack embedded dependencies to artifacts 2020-02-14 17:35:16 +09:00
Yan Zhulanow
a2be789d37 Pill: Move out Pill tasks from buildSrc 2020-02-14 17:35:16 +09:00
Yan Zhulanow
6f1b3e0f17 Pill: Fix pre-built run configurations 2020-02-14 17:35:15 +09:00
Yan Zhulanow
73813aef23 Pill: Support all Gradle source sets, not just main/test 2020-02-14 17:35:15 +09:00
nataliya.valtman
3acf7a4679 TCServiceMessageOutputStreamHandlerTest: fix tests
Fix test to support updates in ServiceMessageParser and attributes
remove TCServiceMessageOutputStreamHandlerTest from ignored tests
2020-02-14 11:14:17 +03:00
Dmitriy Novozhilov
389dcff125 [FIR] Discard argument with spread in place of non-vararg parameter 2020-02-14 09:18:54 +03:00
Dmitriy Novozhilov
50ac8eb95b [FIR] Add smartcast info to argument of invoke of function with receiver 2020-02-14 09:18:54 +03:00
Dmitriy Novozhilov
4fbed9b363 [FIR] Add builder for FirExpressionWithSmartcast 2020-02-14 09:18:53 +03:00
Dmitriy Novozhilov
1da036ac98 [FIR-TEST] Split outdated dfa test to separate tests 2020-02-14 09:18:53 +03:00
Dmitriy Novozhilov
1dd7417746 [FIR] Fix configuring label name for lambdas in light tree builder 2020-02-14 09:18:53 +03:00
Dmitriy Novozhilov
6b378cab29 [FIR] Don't render lambda bodies in arguments of calls in cfg dump 2020-02-14 09:18:53 +03:00
Dmitriy Novozhilov
28c95b1108 [FIR] Don't use psi for rendering control flow graph 2020-02-14 09:18:53 +03:00
Dmitriy Novozhilov
a4b53b4a20 [FIR] Fix passing flow from contracts with form returns(false) ... 2020-02-14 09:18:53 +03:00
Dmitriy Novozhilov
643a4b9c3b [FIR] Support makeDefinitelyNotNull for intersection types 2020-02-14 09:18:53 +03:00
Dmitriy Novozhilov
b71e4ebb3f [FIR-TEST] Add !DUMP_CFG directive. Get rid of cfg diagnostic tests 2020-02-14 09:18:52 +03:00
Dmitriy Novozhilov
f495c4e215 [FIR-TEST] Move stdlib resolve tests out from resolve directory 2020-02-14 09:18:52 +03:00
Dmitriy Novozhilov
90021f3ece [FIR-TEST] Reorganize tests for data flow analysis 2020-02-14 09:18:52 +03:00
Dmitriy Novozhilov
89fa3572ec [FIR-TEST] Move tests for solved issues from problems directory 2020-02-14 09:18:52 +03:00
Toshiaki Kameyama
0c9720f20c ReplaceGetOrSetInspection: do not report for 'get' with spread operator
#KT-36171 Fixed
2020-02-14 08:47:10 +03:00
Mark Punzalan
b782e8f0f0 Add IR equivalent of AbstractBytecodeListingTest and muted failures. 2020-02-13 23:44:53 +03:00
Mark Punzalan
06b6477d04 [JVM IR] Do not add nullability annotation for functions that return
platform types.

This behavior matches the non-IR backend, which was added in
f16dcdd8a9.
2020-02-13 23:44:53 +03:00
Dmitry Petrov
0c984c5e62 PSI2IR tests for b29993739e85dbceb02d04a964741b1410a568f8 2020-02-13 23:43:04 +03:00
Jinseong Jeon
5a49ccac76 JVM_IR: Relax bailout condition for SAM conversion generation.
Previously, resolved call is expected to have SAM converted argument map
if SamConversionPerArgument is enabled. However, if SAM argument is
followed by vararg parameter and an array _without_ a spread operator is
passed, New Inference left a type mismatch error on a resolved call, which
made that resolved candidate filtered out. Instead, another resolution
result wihtout SAM converted arugment map will be provided.

All other logics, such as adding SAM conversion type op and lowering SAM
conversion and/or call references, are already there for resolved calls
without SAM converted argument map. This change just relaxes the bailout
condition so that array passed to vararg after SAM argument can be
handled in JVM IR.
2020-02-13 23:43:03 +03:00
Kristoffer Andersen
f782ea075b [JVM IR] ProperVisibilityForCompanionObjectInstanceField
- Uncomment tests
- Add proper visibility to companion field
  + Make exception for interfaces -> they need to respect language versions 1.8
    before they can put private members there.
- Adjust synthetic accessor lowering to look for enclosing classes with access
  via companion object.
2020-02-13 21:50:48 +03:00
Igor Yakovlev
a67d97bdf8 Remove redundant fake facade classes
Fixed #KT-35122 #EA-218642 #EA-217640
2020-02-13 19:08:54 +03:00
Pavel Kirpichenkov
5d6d287faa [NI] Refactor UnstableSmartCast diagnostic
Split diagnostic classes for unstable smartcast with different resolution applicability.

^KT-36264 Fixed
2020-02-13 18:02:38 +03:00
Pavel Kirpichenkov
15d744c3da [NI] Continue resolution after unstable smart cast on receiver
The old inference cosideres candidates with unstable smartcast on
receiver unsuccessful, therefore another one may be selected.
KT-36264
2020-02-13 18:02:38 +03:00
Pavel Kirpichenkov
4997c9535c Mute test, affected by changes in unstable smart casts
Revealed by changes in e02b7b58, but they are not the source of a bug
See KT-36459
2020-02-13 18:02:37 +03:00
Pavel Kirpichenkov
e40ba73950 [NI] Add resolution applicability for resolved candidates with error
New resolution applicability is needed in cases when error is found,
but candidate still should be selected. Currently there are two cases,
when this behaviour is required:
- unstable smartcast (choose candidate with non-nullable parameter)
- unknown lambda parameter type (against non-functional expected type)

KT-36264
2020-02-13 18:02:37 +03:00
Ilya Goncharov
4fa87d2caa [Gradle, JS] Compilations with js type because of compatibility
- In kotlinx.html there is invocation of packageJson function on compilations["main"]
It can be casted in user script to KotlinJsCompilation, or override on plugin side
2020-02-13 17:49:46 +03:00
Steven Schäfer
76f8109ff6 JVM IR: Implement LookupLocation in IrSourceCompilerForInline
This is used when compiling calls to inline functions with a different
@JvmName for incremental compilation.
2020-02-13 14:46:35 +01:00
Alexander Udalov
3278451b07 JVM IR: do not generate certain special bridges as final
Special bridges which are generated as a replacement for a non-final
fake override and use invokespecial to call the already existing
implementation in the superclass, should not be final. Otherwise we
can't generate an override for the original Kotlin function in a
subclass with the same JVM signature.
2020-02-13 14:34:18 +01:00
Pavel Kirpichenkov
df046683cc Revert "[NI] Report unsafe implicit invoke accordingly to OI"
This reverts commit b045adf83a.
2020-02-13 16:06:40 +03:00
Nicolay Mitropolsky
bf9d4f065b Uast: eliminating the kotlin.uast.multiresolve.enabled, it is always true for a long time 2020-02-13 15:54:48 +03:00
Nicolay Mitropolsky
e4b7c39110 Uast: forcing kotlin.uast.force.uinjectionhost=true always 2020-02-13 15:54:48 +03:00
Mikhail Zarechenskiy
ee48580e06 [NI] Update test data 2020-02-13 15:01:39 +03:00
Ilya Kirillov
531a63bd19 Show experimental features panel only for non-stable plugin versions
Also, use registry as backend for features settings
2020-02-13 14:59:42 +03:00
Pavel Kirpichenkov
b045adf83a [NI] Report unsafe implicit invoke accordingly to OI
There are several issues with unsafe desugaring for convention calls.
Proper fix is not implemented here (see design proposal KT-30872).
This commit only applies the old logic in the new inference.
^KT-30695 Fixed
2020-02-13 14:49:43 +03:00
Vladimir Dolzhenko
9d51180202 Guard resolve calls with runWithCancellationCheck
Relates to #KT-35135
2020-02-13 12:47:58 +01:00
Mikhail Zarechenskiy
74becc7e96 Fix compilation of idea module for old inference
Also, fix code in a way so it'll compile in NI & -progressive too
2020-02-13 14:46:02 +03:00
Vladimir Dolzhenko
918895b88f Avoid using quite new ScratchFileService API
Relates to #KT-35918
2020-02-13 12:10:27 +01:00
Vladimir Dolzhenko
aa0c2486c3 Fix GenerateTests after performance tests modularization 2020-02-13 12:06:18 +01:00
Ilya Chernikov
b96109f23f Add diagnostic code to the ScriptDiagnostic
to allow checking for specific errors, e.g. incomplete statements in
the REPL
2020-02-13 11:33:40 +01:00
Ilya Chernikov
77eacae958 [minor] drop unused dependencies 2020-02-13 11:33:40 +01:00
Ilya Chernikov
49d092cae8 [minor] add incomplete test to the repl tests 2020-02-13 11:33:40 +01:00
Ilya Chernikov
0761a17e2f Fix embedding and relocation in main-kts
The relocation root different from the one in embeddable compiler
lead to "linking" errors for classes included in both jars, e.g.
Disposable. Reuse common root to avoid it.
2020-02-13 11:33:40 +01:00
Ilya Chernikov
514282fb0a Use correct platform classloader on script evaluation in cli compiler
#KT-28475 fixed
also minor testing infrastruct refactoring
2020-02-13 11:33:40 +01:00
Mikhail Zarechenskiy
489c4ec5ec Fix "progressive" warnings to fix compilation under progressive mode 2020-02-13 13:26:11 +03:00
Mikhail Zarechenskiy
3d28945ecb [NI] Disable feature explicitly as it's required in test 2020-02-13 12:08:10 +03:00
Mikhail Zarechenskiy
7526162f6f Mute one inline codegen test for NI
#KT-36448
2020-02-13 11:54:08 +03:00
Mikhail Zarechenskiy
3702d31cbc Set latest stable version for diagnostic tests with unsigned types 2020-02-13 11:54:08 +03:00
Dmitry Petrov
866f188120 Report JVM signature clashes from JVM_IR
Also:

* Do not rename public ABI fields
This includes backing fields for const, lateinit, @JvmField properties,
and instance fields for objects.

* FAKE_OVERRIDE declarations for static members of parent Java classes
Required to report cases when a Kotlin function accidentally overrides
Java class member.
2020-02-13 11:35:48 +03:00
Mikhail Zarechenskiy
c1db9b6d40 [NI] Fix incremental compilation for SAM adapters
This commit fixes test:
 - JavaUsedInKotlin.SamConversions#testMethodAddedSamAdapter
2020-02-13 11:16:00 +03:00
Mikhail Zarechenskiy
1ba0870ae3 [NI-MIGRATE] Update IR text tests 2020-02-13 11:16:00 +03:00
Mikhail Zarechenskiy
abc5eb4740 [NI-MIGRATE-BAD] Update problematic/questionable tests
These tests are going to be reviewed in more detail before 1.4
2020-02-13 11:15:59 +03:00
Mikhail Zarechenskiy
c2fc633ad6 [NI-MIGRATE] Update test about signature enhancements
It's required as now there are no synthetic candidates
2020-02-13 11:15:59 +03:00
Mikhail Zarechenskiy
319a38bd5c [NI-MIGRATE] Update diagnostic messages 2020-02-13 11:15:59 +03:00
Mikhail Zarechenskiy
cd0012c527 [NI-MIGRATE] Update CLI tests 2020-02-13 11:15:59 +03:00
Mikhail Zarechenskiy
ca57d6cd16 [NI-MIGRATE] Update pseudocode tests for NI 2020-02-13 11:15:58 +03:00
Mikhail Zarechenskiy
a0071885bf [NI-MIGRATE] Update type binding tests for NI 2020-02-13 11:15:58 +03:00
Mikhail Zarechenskiy
687c96060f [NI-MIGRATE] Update test data for resolve tests after enabling NI 2020-02-13 11:15:58 +03:00
Mikhail Zarechenskiy
17df92e999 Fix case in stdlib where more specific type lead to error
See #KT-30299 & #KT-32125
2020-02-13 11:15:57 +03:00
Mikhail Zarechenskiy
599ff4711e Temporary fix code before proper support of UnsafeVariance in NI
See #KT-34433
2020-02-13 11:15:57 +03:00
Mikhail Zarechenskiy
c64577b735 Temporary fixes for Kotlin project after enabling NI
Most of these fixes will gone away after compiler bootstraping
2020-02-13 11:15:57 +03:00
Mikhail Zarechenskiy
cdf5323f8c Disable NewInference for stdlib tests
There is one failing test namely `ValByMapExtensionsTest.doTest`, which
 is quite questionable because its checks the use of out projection and
 Exact annotation (see KT-18789)
2020-02-13 11:15:56 +03:00
Mikhail Zarechenskiy
2a4caf6dc8 Enable new inference in the compiler 2020-02-13 10:22:42 +03:00
Dmitry Gridin
8da05ed597 RemoveReturnLabelFix: introduce labelName parameter 2020-02-13 13:51:34 +07:00
Dmitry Gridin
7c65bb2e3f AbstractDiagnosticBasedMigrationInspection: cleanup code 2020-02-13 13:51:34 +07:00
Dmitry Gridin
b98bdca849 RemoveAnnotationFix: inline default argument 2020-02-13 13:51:34 +07:00
Dmitry Gridin
f8a21340d0 ProhibitRepeatedUseSiteTargetAnnotationsMigrationInspection: add test
#KT-36257
2020-02-13 13:51:33 +07:00
Dmitry Gridin
09e6ffdb0a AbstractDiagnosticBasedMigrationInspection: make lazy initialization 2020-02-13 13:51:33 +07:00
Valentin Kipyatkov
cfc2c0fb20 Changes after rebasing on master 2020-02-13 07:40:37 +02:00
Valentin Kipyatkov
4f5d121478 Minor code improvements 2020-02-13 07:40:37 +02:00
Valentin Kipyatkov
e7c72637a1 Removed misleading comments from test data 2020-02-13 07:40:37 +02:00
Valentin Kipyatkov
ae578e0a5d Copyright comments 2020-02-13 07:40:37 +02:00
Valentin Kipyatkov
ee6d6adf70 processAllExactUsages() only for KtDeclaration 2020-02-13 07:40:36 +02:00
Valentin Kipyatkov
c33a4c5c5b Code formatting 2020-02-13 07:40:36 +02:00
Valentin Kipyatkov
3ccb8fa3a8 Workaround for compiler crash 2020-02-13 07:40:36 +02:00
Valentin Kipyatkov
e71bd4e4a4 No need to intersect with element's useScope - it's performed by reference search by default 2020-02-13 07:40:36 +02:00
Valentin Kipyatkov
f43626f57f Refactoring 2020-02-13 07:40:36 +02:00
Valentin Kipyatkov
826c5dd92e Minor 2020-02-13 07:40:35 +02:00
Valentin Kipyatkov
3897f51f8e Refactoring code 2020-02-13 07:40:35 +02:00
Valentin Kipyatkov
f60d24c621 Refactoring 2020-02-13 07:40:35 +02:00
Valentin Kipyatkov
1b5b0d2839 Minor refactoring 2020-02-13 07:40:35 +02:00
Valentin Kipyatkov
af32cad1ae Minor 2020-02-13 07:40:35 +02:00
Valentin Kipyatkov
fd7331bbc0 Refactoring 2020-02-13 07:40:35 +02:00
Valentin Kipyatkov
8008185b77 Renamed mistyping in function name 2020-02-13 07:40:34 +02:00
Valentin Kipyatkov
8f7648c60a Reordered methods 2020-02-13 07:40:34 +02:00
Valentin Kipyatkov
ff39880677 Refactoring - converting extensions to normal functions 2020-02-13 07:40:34 +02:00
Valentin Kipyatkov
b1cd56ba91 We must check super property usages also when analyzing inflow 2020-02-13 07:40:34 +02:00
Valentin Kipyatkov
612fd6d1bf Refactoring to split big file 2020-02-13 07:40:34 +02:00
Valentin Kipyatkov
ff516cac73 Do not include overriders when analyzing parameter usages unless invoked on parameter 2020-02-13 07:40:33 +02:00
Valentin Kipyatkov
e76eaa4b5b Refactored code to avoid duplication 2020-02-13 07:40:33 +02:00
Valentin Kipyatkov
b406d85ca3 Analyze Data Flow to Here: Java super-methods supported 2020-02-13 07:40:33 +02:00
Valentin Kipyatkov
cfa1d91aa4 Analyze Data Flow to Here to work with virtual methods 2020-02-13 07:40:33 +02:00
Valentin Kipyatkov
c34286a327 More usable rendering of usage context in Analyze Data Flow to/from Here 2020-02-13 07:40:32 +02:00
Abduqodiri Qurbonzoda
ed7b8e9b85 Scan functions for Sequences and Iterable #KT-7657 2020-02-13 04:01:47 +03:00
Vladimir Dolzhenko
0d7e641736 Extra dependencies after performance tests modularization 2020-02-12 22:37:25 +01:00
Mark Punzalan
89cf32eccc Clarify comments about KT-36625 that it is pending design decision. 2020-02-12 23:38:12 +03:00
Mark Punzalan
ba606147c9 [JVM IR] Maintain KT-36625 bug compatibility between non-IR and IR
backends by removing IMPLICIT_NOTNULL casts from IrStringConcatenation
arguments.

Also fixed an issue where IrStringConcatenation can be lowered into
a null String instead of a literal "null" String if the lone argument
was a platform type String or String with enhanced nullability and the
value was null (e.g., "${FromJava.nullPlatformString()}").
2020-02-12 22:57:15 +03:00
Vladimir Dolzhenko
18a3d7ee08 Moved extra files after performance tests modularization 2020-02-12 20:56:19 +01:00
Vladimir Dolzhenko
60f17c3adf Modularization of performance tests 2020-02-12 20:06:01 +01:00
Pavel Kirpichenkov
572dee6835 Revert "Only create descriptors for candidates with lambda args"
This reverts commits:
349d07ad43
2249c223fe

Revert due to differences in test data with NI enabled
^KT-36247 Open
2020-02-12 20:52:30 +03:00
Anton Bannykh
52ae63f191 IR: decommonize AbstractSuspendFunctionsLowering.kt
Some issues emerged while building kotlinx.coroutines
Reverted changes to the common lowering.

TODO: fix after M1
2020-02-12 20:19:10 +03:00
Alexander Udalov
d5987fd7f3 Minor, move wrongAnnotationArgumentInCtor.kt to CLI tests
The fact that this was a codegen box test was probably an abuse of the
testing infrastructure. It was never meant to pass, since it checks
presence of an error, and diagnostic tests aren't enough since they
might not check the full compiler execution.
2020-02-12 17:36:08 +01:00
Alexander Udalov
9c9e13d93e Minor, move obsolete test to oldLanguageVersions
Ignore this directory in JVM IR boxAgainstJava tests (similarly to box
tests) so that we can ignore the fact that this test doesn't pass in
JVM_IR, since it shouldn't.
2020-02-12 17:36:08 +01:00
Alexander Udalov
0df455cb52 Minor, remove duplicate test
There's already a test that checks exactly this behavior at
box/oldLanguageVersions/platformTypes/primitives/equalsNull_lv11.kt.
2020-02-12 17:36:08 +01:00
Sergey Igushkin
c28d8c6575 Don't iterate over all tasks in KotlinProjectNpmResolver (KT-36472)
Iterating over all tasks triggered the tasks to configure even if that
was not necessary. Filter the task collection by type instead.

Issue #KT-36472 Fixed
2020-02-12 19:04:06 +03:00
Igor Yakovlev
9e05c702ab Fix KtDotQualifiedExpressionElementType stub building for complex qualified elements
Fixed #EA212081
2020-02-12 18:59:35 +03:00
Abduqodiri Qurbonzoda
ddcc3b39f7 JS Regex.find does not throw on invalid start index #KT-36082 2020-02-12 18:26:50 +03:00
Abduqodiri Qurbonzoda
c592201a43 Fail fast in Regex.findAll on an invalid startIndex #KT-28356 2020-02-12 18:26:49 +03:00
Pavel Kirpichenkov
95a8060946 [NI] Don't report uninferred type parameter error on special functions
Type parameters can't be specified explicitly for special constructions.
Reporting this error does not help fixing the cause of it and needlessly
reveals implementation details.

^KT-36342 Fixed
2020-02-12 17:33:42 +03:00
Ilya Goncharov
fd0c644b6f [Gradle, JS] Fix order of free compiler args assigning 2020-02-12 17:29:36 +03:00
Ilya Goncharov
cd8af5d3ec [Gradle, JS] Configure build for nodejs in ir 2020-02-12 17:29:36 +03:00
Ilya Goncharov
a1497682ed [Gradle, JS] Remove depending of link tasks on assemble 2020-02-12 17:29:36 +03:00
Ilya Goncharov
db86076864 [Gradle, JS] Remove redundant dependsOn
- in CopySpec if task in from, dependsOn is automatically set
2020-02-12 17:29:36 +03:00
Ilya Goncharov
752d676523 [Gradle, JS] Fix tests for VariantAwareDependenciesIT.kt 2020-02-12 17:29:35 +03:00
Ilya Goncharov
589cea557b [Gradle, JS] Fix tests after changing default on legacy instead of ir 2020-02-12 17:29:35 +03:00
Ilya Goncharov
fc872d5a53 [Gradle, JS] Fix clean output test 2020-02-12 17:29:35 +03:00
Ilya Goncharov
e53fd1b582 [Gradle, JS] Distribution and distribute task for KotlinBrowserJsIr.kt 2020-02-12 17:29:35 +03:00
Ilya Goncharov
bbb98f9168 [Gradle, JS] Change default on legacy instead of ir 2020-02-12 17:29:35 +03:00
Ilya Goncharov
a33affc325 [Gradle, JS] Fix android tests
- Can't write npm project to task data because 2 reasons:
-- May be not npm project (if not declared nodejs or browser)
-- In Android there is clash of clean tasks on creating NPM project
2020-02-12 17:29:35 +03:00
Ilya Goncharov
016dd91e37 [Gradle, JS] Fix destination dir for link tasks
- Add test on empty output with empty inputs
2020-02-12 17:29:35 +03:00
Ilya Goncharov
24d229e5a0 [Gradle, JS] Make entryModule internally 2020-02-12 17:29:35 +03:00
Ilya Goncharov
5aed541d9e [Gradle, JS] Remove redundant 2020-02-12 17:29:35 +03:00
Ilya Goncharov
333bb4da50 [Gradle, JS] Remove redundant delegation 2020-02-12 17:29:34 +03:00
Ilya Goncharov
196907b2ef [Gradle, JS] Compatibility with lower than 4.9 2020-02-12 17:29:34 +03:00
Ilya Goncharov
0129b71cfe [Gradle, JS] Link task is part of assemble 2020-02-12 17:29:34 +03:00
Ilya Goncharov
347f52ae10 [Gradle, JS] Fix tests for both mode 2020-02-12 17:29:34 +03:00
Ilya Goncharov
c8be2876bc [Gradle, JS] Remove redundant compiler flags and make them internal 2020-02-12 17:29:34 +03:00
Ilya Goncharov
bdf76f9264 fixup! [Gradle, JS] Fix review remarks
- setup compiler args in appropriate fun
- remove redundant
2020-02-12 17:29:34 +03:00
Ilya Goncharov
29a55fc47e [Gradle, JS] Remove redundant testTasks 2020-02-12 17:29:34 +03:00
Ilya Goncharov
300fd9bd07 [Gradle, JS] Extract archiveType property on Configurator level 2020-02-12 17:29:34 +03:00
Ilya Goncharov
cedfb71a1e [Gradle, JS] Task configuration avoidance with providers 2020-02-12 17:29:33 +03:00
Ilya Goncharov
05b48bbf85 [Gradle, JS] Fix names for js compiler property 2020-02-12 17:29:33 +03:00
Ilya Goncharov
d44aef3f3d [Gradle, JS] Check existence of input file before run and test
#KT-36326 fixed
2020-02-12 17:29:33 +03:00
Ilya Goncharov
bcd2707fe6 [Gradle, JS] Fix naming from jsMode to jsCompilerType 2020-02-12 17:29:33 +03:00
Ilya Goncharov
b30328a766 [Gradle, JS] Fix capilatiozation for gradle attributes 2020-02-12 17:29:33 +03:00
Ilya Goncharov
54e068dee2 [Gradle, JS] Attribute and compiler type is on one enum 2020-02-12 17:29:33 +03:00
Ilya Goncharov
d86384225e [Gradle, JS] Rename of property for control compiler type 2020-02-12 17:29:33 +03:00
Ilya Goncharov
8de4966e53 [Gradle, JS] Fix name of workers file 2020-02-12 17:29:33 +03:00
Ilya Goncharov
f342508a6e [Gradle, JS] Fix ambiguity with target name 2020-02-12 17:29:32 +03:00
Ilya Goncharov
6793fb285e [Gradle, JS] Prepare for review 2020-02-12 17:29:32 +03:00
Ilya Goncharov
85919ed0fc [Gradle, JS] Fix manifest destination 2020-02-12 17:29:32 +03:00
Ilya Goncharov
433053e479 [Gradle, JS] Fix manifest destination 2020-02-12 17:29:32 +03:00
Ilya Goncharov
a4ed71075d [Gradle, JS] Fix test for lib and app 2020-02-12 17:29:32 +03:00
Ilya Goncharov
43903e5d19 [Gradle, JS] Fix test incremental compilation (only for legacy) 2020-02-12 17:29:32 +03:00
Ilya Goncharov
c6935a57a4 [Gradle, JS] Fix test for old kotlin2js plugin 2020-02-12 17:29:32 +03:00
Ilya Goncharov
d69266de50 [Gradle, JS] Fix parallel tasks test 2020-02-12 17:29:32 +03:00
Ilya Goncharov
5ff07baf53 [Gradle, JS] Fix parallel tasks test 2020-02-12 17:29:31 +03:00
Ilya Goncharov
40f5663a57 [Gradle, JS] Fix associated compilations test and adopt to js ir 2020-02-12 17:29:31 +03:00
Ilya Goncharov
6698dc7597 [Gradle, JS] new-mpp-with-dce is actual only for legacy 2020-02-12 17:29:31 +03:00
Ilya Goncharov
57d2939cf9 [Gradle, JS] Fix lower case of target 2020-02-12 17:29:31 +03:00
Ilya Goncharov
d50f520639 [Gradle, JS] Fix WorkersIT tests 2020-02-12 17:29:31 +03:00
Ilya Goncharov
8646f6a098 [Gradle, JS] Commonization setting of js mode 2020-02-12 17:29:31 +03:00
Ilya Goncharov
e7b981c467 [Gradle, JS] Fix testBrowserDistribution 2020-02-12 17:29:31 +03:00
Ilya Goncharov
99d0fa0d29 [Gradle, JS] Fix newFileProperty for gradle <5.0 2020-02-12 17:29:31 +03:00
Ilya Goncharov
d2261f5491 [Gradle, JS] Fix legacy test
- kotlin2js depends on MPP
2020-02-12 17:29:30 +03:00
Ilya Goncharov
26c27f55b3 [Gradle, JS] Fix test for resolving 2020-02-12 17:29:30 +03:00
Ilya Goncharov
fff5d9a684 [Gradle, JS] Remove redundant disambiguation for ir preset 2020-02-12 17:29:30 +03:00
Ilya Goncharov
c208f038ad [Gradle, JS] Fix gradle <5.1 incompatibility with fileProperty 2020-02-12 17:29:30 +03:00
Ilya Goncharov
24451f62ac [Gradle, JS] Fix gradle <5.1 incompatibility #2 2020-02-12 17:29:30 +03:00
Ilya Goncharov
cd5ed54cd6 [Gradle, JS] Fix gradle <5.1 incompatibility 2020-02-12 17:29:30 +03:00
Ilya Goncharov
df5b86c289 [Gradle, JS] Use include instead of sources for link stage of compiler 2020-02-12 17:29:30 +03:00
Ilya Goncharov
da9080055c [Gradle, JS] Remove sources for link tasks 2020-02-12 17:29:29 +03:00
Ilya Goncharov
247da4984e [Gradle, JS] Fix naming 2020-02-12 17:29:29 +03:00
Ilya Goncharov
ded996aedf [Gradle, JS] Delegates all calls from js target to ir target 2020-02-12 17:29:29 +03:00
Ilya Goncharov
62aa6d01e9 [Gradle, JS] Remove redundant 2020-02-12 17:29:29 +03:00
Ilya Goncharov
406c249d99 [Gradle, JS] Fix mpp generator 2020-02-12 17:29:29 +03:00
Ilya Goncharov
0b06f0a05b [Gradle, JS] Remove redundant classes 2020-02-12 17:29:29 +03:00
Ilya Goncharov
5904591676 [Gradle, JS] Commonize targets with interfaces 2020-02-12 17:29:29 +03:00
Ilya Goncharov
d33521052f [Gradle, JS] In Ir target should configure Ir subtarget 2020-02-12 17:29:28 +03:00
Ilya Goncharov
831757018c [Gradle, JS] Check only once set producing type 2020-02-12 17:29:28 +03:00
Ilya Goncharov
9f3601412b [Gradle, JS] Commonize producing for js targets 2020-02-12 17:29:28 +03:00
Ilya Goncharov
8322d7b007 [Gradle, JS] Move producing dsl from subtarget to target in IR 2020-02-12 17:29:28 +03:00
Ilya Goncharov
7a3b6e2d71 [Gradle, JS] Move producing dsl from subtarget to target 2020-02-12 17:29:28 +03:00
Ilya Goncharov
2680ea6bdd [Gradle, JS] Fix after rebase on master 2020-02-12 17:29:28 +03:00
Ilya Goncharov
a2930b45f6 [Gradle, JS] Fix compilation after rebase 2020-02-12 17:29:28 +03:00
Ilya Goncharov
35c681685b [Gradle, JS] Set only one attribute for ir target
- Because if new library version can be consumed from old plugin, which doesn't know about new attribute
We don't add attribute for legacy variant, and Gradle find necessary variant with less attribute count
2020-02-12 17:29:28 +03:00
Ilya Goncharov
31f8fe0461 [Gradle, JS] Api and runtime variants for legacy and ir 2020-02-12 17:29:27 +03:00
Ilya Goncharov
15a33a8503 [Gradle, JS] Fix naming 2020-02-12 17:29:27 +03:00
Ilya Goncharov
8f8eaa28d5 [Gradle, JS] Add attribute for IR target 2020-02-12 17:29:27 +03:00
Ilya Goncharov
9833e2202e [Gradle, JS] Hack for npm resolving of js mixed mode 2020-02-12 17:29:27 +03:00
Ilya Goncharov
a1e6f566f6 [Gradle, JS] Add disambiguation classifier for MPP 2020-02-12 17:29:27 +03:00
Ilya Goncharov
246fb31786 [Gradle, JS] Add hack for process ir compilations in NPM resolver in mixed 2020-02-12 17:29:27 +03:00
Ilya Goncharov
18fa5266b7 [Gradle, JS] Producing for ir target through legacy target 2020-02-12 17:29:27 +03:00
Ilya Goncharov
21a1e2e89f [Gradle, JS] Add additinal DSL (with KotlinLibrary or Executable) for mixed and legacy 2020-02-12 17:29:26 +03:00
Ilya Goncharov
00572395da [Gradle, JS] Fix naming of produce Js 2020-02-12 17:29:26 +03:00
Ilya Goncharov
808a776efb [Gradle, JS] Default source-set name w/o legacy disambiguation in mixed 2020-02-12 17:29:26 +03:00
Ilya Goncharov
27b9c6ff29 [Gradle, JS] Fix compilation after cherry-pick 2020-02-12 17:29:26 +03:00
Ilya Goncharov
619b922215 [Gradle, JS] Difference through gradle attribute 2020-02-12 17:29:26 +03:00
Ilya Goncharov
4d323d3567 [Gradle, JS] Fix attribute type on type of zip 2020-02-12 17:29:26 +03:00
Ilya Goncharov
b3067d655e [Gradle, JS] Rebase on master 2020-02-12 17:29:26 +03:00
Ilya Goncharov
3731d4b89a [Gradle, JS] Publish with 2 variants 2020-02-12 17:29:26 +03:00
Ilya Goncharov
f15d1ef23e [Gradle, JS] Create not Jar tasks, but Zip tasks, because we can create klibs 2020-02-12 17:29:25 +03:00
Ilya Goncharov
3467230242 [Gradle, JS] Add appendix for archive in case of mixed mode 2020-02-12 17:29:25 +03:00
Ilya Goncharov
f169c8ea24 [Gradle, JS] Flags with producing unzipped klib is by default 2020-02-12 17:29:25 +03:00
Ilya Goncharov
b37c2a05fd [Gradle, JS] Configure ir target in legacy plugin #2 2020-02-12 17:29:25 +03:00
Ilya Goncharov
43ab4ad8e8 [Gradle, JS] Configure ir target in legacy plugin 2020-02-12 17:29:25 +03:00
Ilya Goncharov
04c0b8c07d [Gradle, JS] Inject ir's classes into legacy for mixed mode #2 2020-02-12 17:29:25 +03:00
Ilya Goncharov
fd93654c4f [Gradle, JS] Inject ir's classes into legacy for mixed mode 2020-02-12 17:29:25 +03:00
Ilya Goncharov
e6be134f2a [Gradle, JS] Activate legacy plugin and new plugin via gradle property 2020-02-12 17:29:25 +03:00
Ilya Goncharov
29c2d62e43 [Gradle, JS] Compile fix after rebase 2020-02-12 17:29:24 +03:00
Ilya Goncharov
0c7284de01 [Gradle, JS] Link test task with property of compile task 2020-02-12 17:29:24 +03:00
Ilya Goncharov
dd577e1008 [Gradle, JS] Migrate in KotlinJsIrTest 2020-02-12 17:29:24 +03:00
Ilya Goncharov
bf415704b6 [Gradle, JS] Generalization of Js test frameworks to work with ir 2020-02-12 17:29:24 +03:00
Ilya Goncharov
599215e74a [Gradle, JS] Migrate on properties to link output of compile with consumer 2020-02-12 17:29:24 +03:00
Ilya Goncharov
4bd744f163 [Gradle, JS] Fix run for nodejs with IR backend 2020-02-12 17:29:24 +03:00
Ilya Goncharov
14387332d5 [Gradle, JS] Distribution task depends on processed resources 2020-02-12 17:29:24 +03:00
Ilya Goncharov
9c89859c67 [Gradle, JS] Webpack catch files from js compilations 2020-02-12 17:29:24 +03:00
Ilya Goncharov
d827f9b040 [Gradle, JS] JS compile tasks nit in archives now 2020-02-12 17:29:23 +03:00
Ilya Goncharov
4861b47f9c [Gradle, JS] Enable IR backend for prod and dev tasks 2020-02-12 17:29:23 +03:00
Ilya Goncharov
2e22b8eb9a [Gradle, JS] Register link tasks 2020-02-12 17:29:23 +03:00
Ilya Goncharov
60da60757d [Gradle, JS] Extract KotlinJsLinkTask 2020-02-12 17:29:23 +03:00
Ilya Goncharov
c043fc2272 [Gradle, JS] Prod and dev compile tasks depends on klib compile task 2020-02-12 17:29:23 +03:00
Ilya Goncharov
3ee7e9272b [Gradle, JS] Depends on prod and dev compile tasks 2020-02-12 17:29:23 +03:00
Ilya Goncharov
222c663fac [Gradle, JS] Configure prod and dev compilations 2020-02-12 17:29:23 +03:00
Ilya Goncharov
abf2a9e073 [Gradle, JS] Extract ir compiler flags 2020-02-12 17:29:22 +03:00
Ilya Goncharov
ad321e45dc [Gradle, JS] Create KotlinJsIrCompilationFactory 2020-02-12 17:29:22 +03:00
Ilya Goncharov
5bdf9f6e39 [Gradle, JS] Fix codegen and avoid deprecate 2020-02-12 17:29:22 +03:00
Ilya Goncharov
544a6bf15e [Gradle, JS] Add production and development compilations 2020-02-12 17:29:22 +03:00
Ilya Goncharov
2f4f4dbbd8 [Gradle, JS] Fix deprecation replace with on register task 2020-02-12 17:29:22 +03:00
Ilya Goncharov
d0e2a653f7 [Gradle, JS] Reformat code 2020-02-12 17:29:22 +03:00
Ilya Goncharov
64def2e173 [Gradle, JS] Continue to migrate on ir compiler
- Create own inheritor of KotlinJsCompilation with specific tasks for production and development
- Copy TargetConfigurator for IR purposes
2020-02-12 17:29:22 +03:00
Ilya Goncharov
8b641bf613 [Gradle, JS] Add mpp presets for jsIr 2020-02-12 17:29:22 +03:00
Ilya Goncharov
a20e9ae0ed [Gradle, JS] Extract hack for Native and JS IR compiler
- IR to klib compiler needs all dependencies (including transitive implementations)
- move hack from native to common with extracting to protected fun
2020-02-12 17:29:21 +03:00
Ilya Goncharov
f936a0fc9b [Gradle, JS] NodeJs and browser producing handlers 2020-02-12 17:29:21 +03:00
Ilya Goncharov
2de7051165 [Gradle, JS] Add produceJs 2020-02-12 17:29:21 +03:00
Ilya Goncharov
64c2b4b076 [Gradle, JS] Add callbacks on configuring producing target for JS IR 2020-02-12 17:29:21 +03:00
Ilya Goncharov
e7c6653182 [Gradle, JS] Remove DCE from ir tooling 2020-02-12 17:29:21 +03:00
Ilya Goncharov
6be8a83ff9 [Gradle, JS] Configure compiler args for produceKotlinLibrary in IR 2020-02-12 17:29:21 +03:00
Ilya Goncharov
0ff84eaa63 [Gradle, JS] Copy JS subtargets dsl for IR 2020-02-12 17:29:21 +03:00
Ilya Goncharov
3ac2bae4ce [Gradle, JS] Copy JS plugin for IR 2020-02-12 17:29:21 +03:00
Mikhail Glukhikh
ba770f7b61 FIR2IR: fix type parameter indexes & fix some black-box & FIR2IR tests 2020-02-12 17:02:41 +03:00
Toshiaki Kameyama
3ebad2acec "Constructor has non-null self reference parameter": don't report for vararg parameter
#KT-36160 Fixed
2020-02-12 16:35:26 +03:00
Mikhail Glukhikh
f3f88cae7a FIR: unmute accidentally muted black-box test 2020-02-12 16:30:47 +03:00
Toshiaki Kameyama
6c93217539 Lift assignment out: don't report when expression is used as expression
#KT-36357 Fixed
2020-02-12 16:17:25 +03:00
Toshiaki Kameyama
8baba38099 "To raw string literal" intention: fix false negative with string content starts with newline symbol \n
#KT-36369 Fixed
2020-02-12 16:15:18 +03:00
Denis Zharkov
61d02d9ecb FIR: Unbound FirJavaElementFinder from Kotlin PSI 2020-02-12 16:05:11 +03:00
Denis Zharkov
9c1577092b FIR: Fix SAM conversion for constructor calls 2020-02-12 16:05:11 +03:00
Denis Zharkov
51db272e0e FIR: Clean environment in AbstractFirTypeEnhancementTest 2020-02-12 16:05:11 +03:00
Denis Zharkov
95b4fa4b31 FIR: Support flexible types in getErasedVersionOfFirstUpperBound 2020-02-12 16:05:11 +03:00
Denis Zharkov
42e8017bde FIR: Minor. Refactor calculation of erased upper bound 2020-02-12 16:05:11 +03:00
Denis Zharkov
bc34bc3f96 FIR: Use flexible type for generic parameters bounds
Otherwise star projections may be incorrectly approximated to strictly
nullable types (as in test)
2020-02-12 16:05:11 +03:00
Denis Zharkov
5a2cdfcab4 FIR: Run callable references resolution for synthetic-select calls 2020-02-12 16:05:11 +03:00
Denis Zharkov
003aea2e68 FIR: Consider abbreviation's nullability when expanding types 2020-02-12 16:05:11 +03:00
Alexander Udalov
2bb6e4fd97 Minor, add package to typeOfCapturedStar.kt test
This fixes this test on Android where packages are replaced.
2020-02-12 14:03:22 +01:00
Nikolay Krasko
eca562a006 Add possibility to depend on nightly repository 2020-02-12 14:54:47 +03:00
Natalia Selezneva
95b2a583ae build.gradle.kts: change notification text 2020-02-12 14:21:30 +03:00
Pavel Kirpichenkov
c02dd720dc [NI] Restore missing call checker errors in coroutine inference
Reported diagnostics from the call checkers didn't get to a top-level
trace, if an intermediate wrapping call was a lambda call.
Use of the top-level trace in call completer is a workaround for
the unreliable commit order of common calls' temporary traces.
^KT-33542 Fixed
2020-02-12 12:27:02 +03:00
Mikhail Zarechenskiy
6af8f320f7 Add JS runtime to the failing test 2020-02-12 12:23:13 +03:00
Dmitriy Novozhilov
9408bb84e9 [FIR-TEST] Update testname in testdata 2020-02-12 11:20:40 +03:00
Dmitriy Novozhilov
a7de4a8b4b [FIR-TEST] Update testname in testdata 2020-02-12 11:14:14 +03:00
Mikhail Zarechenskiy
759127df9a Add NI diagnostics for spec tests 2020-02-12 10:37:35 +03:00
Mikhail Zarechenskiy
c58e819a6a Regenerate tests 2020-02-12 10:36:46 +03:00
Mikhail Zarechenskiy
0d310c0fa4 [NI] Support signed-unsigned conversions for K/Native
#KT-34545 Fixed
2020-02-12 10:36:45 +03:00
Mikhail Zarechenskiy
e14e58c121 Update test about conversions, remove irrelevant case 2020-02-12 10:36:44 +03:00
Mikhail Zarechenskiy
1acce46133 [NI] Fix recording info about captured local variables 2020-02-12 10:36:43 +03:00
Mikhail Zarechenskiy
7f6c03c926 [NI] Fix search of effects for substituted descriptors
This fixed *testExactlyOnce* tests for NI
2020-02-12 10:36:42 +03:00
Mikhail Zarechenskiy
7df92cd00b Set isOperator property for dynamic calls by convention 2020-02-12 10:36:41 +03:00
Mikhail Zarechenskiy
a736551c2a Add test checking that fun isn't inherited from base interface 2020-02-12 10:36:40 +03:00
Mikhail Zarechenskiy
45bbdaf73f Add base declaration checker for fun interfaces 2020-02-12 10:36:39 +03:00
Dmitriy Novozhilov
6735cc8937 [FIR] Implement new bound smartcast algorithm
#KT-36055 Fixed
2020-02-12 10:17:45 +03:00
Ilya Kirillov
40f907ec2f Fix compilation for 191 & as35 2020-02-11 23:49:30 +03:00
Mikhail Glukhikh
67668d798b FIR2IR: update test data 2020-02-11 23:22:55 +03:00
Mikhail Glukhikh
12c001f491 FIR: unmute two additional black-box tests 2020-02-11 23:14:51 +03:00
Mikhail Glukhikh
76f78d3fde FIR2IR: don't mutate basic FIR for invoke / next calls 2020-02-11 22:50:06 +03:00
Juan Chen
37abdb1732 [FIR2IR] Fix NoSuchMethod for Iterator::next (same issue with invoke) 2020-02-11 22:50:06 +03:00
Juan Chen
8e35545e10 FIR2IR: provide type arguments for class 'this' receiver 2020-02-11 22:50:06 +03:00
Mikhail Glukhikh
df07b77271 FIR2IR: get rid of "creates list under the hood" warnings 2020-02-11 22:50:05 +03:00
Mikhail Glukhikh
fe5dd4dba1 FIR2IR: extract 'declareThisReceiverParameter', rename 'setThisReceiver' 2020-02-11 22:50:05 +03:00
Nikolay Krasko
b75d0eb1a1 201: Restrict 193 and own plugin for 201 2020-02-11 20:28:05 +03:00
Nikolay Krasko
a983b0bf74 201: Additional method getOwnReferences is introduced (bunched) 2020-02-11 20:28:05 +03:00
Nikolay Krasko
c9d97ae555 201: Notification group was rewritten to Kotlin (no sam conversion) 2020-02-11 20:28:05 +03:00
Nikolay Krasko
034243b5e7 201: ExecutionManager.contentManager was rewritten to Kotlin (bunched) 2020-02-11 20:28:05 +03:00
Nikolay Krasko
1cb56ee946 201: Processor<in PsiMethod> used in PsiShortNamesCache 2020-02-11 20:28:04 +03:00
Nikolay Krasko
9f6f8088e3 201: Processors changed for UsageInfo and SliceUsage 2020-02-11 20:28:04 +03:00
Nikolay Krasko
e23f3b54c6 201: New DynamicBundle.LanguageBundleEP.EP_NAME needed for Java
https://github.com/JetBrains/intellij-community/commits/master/platform/core-api/src/com/intellij/DynamicBundle.java
2020-02-11 20:28:04 +03:00
Nikolay Krasko
51244d7b1d 201: Return JavaCoreApplicationEnvironment subclassing (bunched) 2020-02-11 20:28:04 +03:00
Nikolay Krasko
cfd92f252a 201: Update version to 201.4515.24-EAP-SNAPSHOT 2020-02-11 20:28:04 +03:00
Nikolay Krasko
314474c33b 201: uast-tests.jar new dependency (depend on whole idea in tests) 2020-02-11 20:28:04 +03:00
Nikolay Krasko
7a89bd9c90 201: Change of ProblemDescriptorBase.getFixes() return type
15a39d5742
2020-02-11 20:28:04 +03:00
Nikolay Krasko
8cb4a8f5c6 201: Raw Class -> Class<?> (bunched)
f8b7e8b0b5
2020-02-11 20:28:04 +03:00
Nikolay Krasko
890109beb8 201: PsiElementVisitor.visitElement nullability 2020-02-11 20:28:04 +03:00
Nikolay Krasko
98c6efaed9 201: BinaryFileStubBuilders.EP_NAME dropped (bunched) 2020-02-11 20:28:03 +03:00
Nikolay Krasko
2cc4d878a8 201: ProjectManagerEx.forceCloseProject(project, true) - no second parameter 2020-02-11 20:28:03 +03:00
Nikolay Krasko
41ca51cb9e 201: MadTestingUtil.enableAllInspections second parameter was removed 2020-02-11 20:28:03 +03:00
Nikolay Krasko
ae1cfff5d2 201: IdeaTestApplication -> TestApplicationManager in tests 2020-02-11 20:28:03 +03:00
Nikolay Krasko
3eb4d46c3d 201: ExternalProjectsManagerImpl.disableProjectWatcherAutoUpdate removed (bunched) 2020-02-11 20:28:03 +03:00
Nikolay Krasko
10ce3c58e1 201: No PlatformTestCase.myProjectManager anymore (bunched) 2020-02-11 20:28:03 +03:00
Nikolay Krasko
75f05d8329 201: TemplateManagerImpl.setTemplateTesting() parameter removed 2020-02-11 20:28:03 +03:00
Nikolay Krasko
b17a28381b 201: Can't instantiate subclass of Task anymore 2020-02-11 20:28:03 +03:00
Nikolay Krasko
54b1c512c5 201: LookupImpl.focusedDegree renamed 2020-02-11 20:28:03 +03:00
Nikolay Krasko
56d960c65b 201: "testFramework" and "testFramework.core" libs introduced 2020-02-11 20:28:02 +03:00
Nikolay Krasko
641fa1f17c 201: TextEditorWithPreview.java update - no ApiStatus (bunched)
Class should be removed
2020-02-11 20:28:02 +03:00
Nikolay Krasko
10aef79434 201: AbstractProjectResolverExtension.createModule returns nullable 2020-02-11 20:28:02 +03:00
Nikolay Krasko
066d77f396 201: Tool windows - source incompatible change with Kotlin (bunched) 2020-02-11 20:28:02 +03:00
Nikolay Krasko
4afd7c553b 201: AbstractTreeNode generified in ide.projectView package (bunched) 2020-02-11 20:28:02 +03:00
Nikolay Krasko
b425bf9a1b 201: TreeStructureProvider api changed: AbstractTreeNode<Any -> *> 2020-02-11 20:28:02 +03:00
Nikolay Krasko
9261f69dc8 201: MoveDestination.analyzeModuleConflicts variance in parameter changed 2020-02-11 20:28:02 +03:00
Nikolay Krasko
7ea52ebb45 201: Print type explicitly as RefactoringBundle.message() not null 2020-02-11 20:28:02 +03:00
Nikolay Krasko
4bc10f4c4f 201: MoveMultipleElementsViewDescriptor constructor nullability 2020-02-11 20:28:01 +03:00
Nikolay Krasko
2c72f53937 201: AbstractNavBarModelExtension.adjustElement nullability (bunched) 2020-02-11 20:28:01 +03:00
Nikolay Krasko
78385d5f63 201: Update hierarchy to new API (fix bugs introduced by the platform)
193 plugins with old API are affected while being binary compatible.
2020-02-11 20:28:01 +03:00
Nikolay Krasko
5e58a66c58 201: Convert KotlinHierarchyViewTestBase.java because of typealiases 2020-02-11 20:28:01 +03:00
Nikolay Krasko
6bd91ec5b0 201: Rename .java to .kt 2020-02-11 20:28:01 +03:00
Nikolay Krasko
27467e4db7 201: Convert AbstractHierarchyTest.java because of typealiases 2020-02-11 20:28:01 +03:00
Nikolay Krasko
9f6f6838b8 201: Rename .java to .kt 2020-02-11 20:28:01 +03:00
Nikolay Krasko
579dd8f8fe 201: J2K manual 2020-02-11 20:28:01 +03:00
Nikolay Krasko
b92a228fb3 201: Convert KotlinCallHierarchyBrowser and KotlinCallHierarchyBrowser
Need convert to use Kotlin typealias feature.
2020-02-11 20:28:01 +03:00
Nikolay Krasko
b795b38794 201: Rename .java to .kt 2020-02-11 20:28:00 +03:00
Nikolay Krasko
866c33fbde 201: RefactoringHelper.prepareOperation nullability (bunched) 2020-02-11 20:28:00 +03:00
Nikolay Krasko
5440a5e228 201: No BinaryFileStubBuilders.EP_NAME anymore (bunched) 2020-02-11 20:28:00 +03:00
Nikolay Krasko
beb70526a2 201: CoreApplicationEnvironment.registerExtensionPointAndExtensions accepts Path 2020-02-11 20:28:00 +03:00
Nikolay Krasko
cf78058cc2 201: PsiShortNamesCache.getAllClassNames(HashSet<String>) removed 2020-02-11 20:28:00 +03:00
Nikolay Krasko
4668518b2f 201: ContainerUtil.newTroveSet<T>() removed 2020-02-11 20:28:00 +03:00
Nikolay Krasko
9d3d59fccb 201: Remove JpsPersistentHashMap (bunched) 2020-02-11 20:28:00 +03:00
Nikolay Krasko
1ecd1a293d 201: Processor<String> -> Processor<in String> in PsiShortNamesCache 2020-02-11 20:28:00 +03:00
Nikolay Krasko
2a71fe97cf 201: picocontainer.jar is removed 2020-02-11 20:27:59 +03:00
Nikolay Krasko
354d7306dd 201: versions.jar.streamex and versions.jar.gson versions 2020-02-11 20:27:59 +03:00
Nikolay Krasko
162c2f3dc9 201: openapi.jar is removed 2020-02-11 20:27:59 +03:00
Nikolay Krasko
c26e1e9c1a 201: Introduce 201 platform 2020-02-11 20:27:59 +03:00
Nikolay Krasko
0f4fadf104 201: Create bunch 2020-02-11 20:27:59 +03:00
simon.ogorodnik
4a1451ab63 [FIR] Optimize TowerGroup 2020-02-11 19:32:08 +03:00
simon.ogorodnik
d775852781 [FIR] Refactor tower resolver to coroutines 2020-02-11 19:32:07 +03:00
Vyacheslav Gerasimov
695558465d Build: Fix idea sources jar ivy for -EAP-SNAPSHOT versions 2020-02-11 19:09:50 +03:00
Steven Schäfer
6d23e50142 JVM IR: Create non-synthetic multifile parts for -Xmultifile-parts-inherit 2020-02-11 17:01:22 +01:00
Steven Schäfer
9db82bfcc8 JVM IR: Create package private synthetic multi file part classes 2020-02-11 17:01:22 +01:00
Steven Schäfer
6584df3e01 JVM IR: Fix references to const properties in facade classes 2020-02-11 17:01:22 +01:00
simon.ogorodnik
d9883067e6 [FIR] Hide primary constructor parameters from accessors 2020-02-11 18:50:51 +03:00
Vladimir Dolzhenko
a0ed2c8640 Enforce analysis inside top-level property initializer
Relates to #KT-36460
2020-02-11 16:47:10 +01:00
Vyacheslav Gerasimov
bf9e7ad09a Update 193 platform version to 193.6494.35 2020-02-11 18:21:46 +03:00
Steven Schäfer
058b229544 JVM IR: Handle external static declarations in companion objects 2020-02-11 15:53:25 +01:00
Igor Yakovlev
48db96b66d Improved kotlin decompiler range indexes
Fixed #KT-30628
2020-02-11 17:42:12 +03:00
Toshiaki Kameyama
cb1c0344b8 Rename: add test for overridden method renaming in generic class
#KT-26047 Fixed
2020-02-11 17:25:12 +03:00
Toshiaki Kameyama
ff76ba52d8 Inline Function: fix false positive with inner function with 'return'
#KT-34190 Fixed
2020-02-11 16:23:57 +03:00
Juan Chen
04e8cba857 [FIR] fixed overridden symbols of "invoke" in KFunction
IR expects overridden symbols of "invoke" in KFunction to be "invoke"
in the corresponding Function classes.
Before this commit we don't set overriddenSymbol, now we do.
2020-02-11 16:09:21 +03:00
Mikhail Glukhikh
e3721ed406 [FIR] Implement bare type modification with known type arguments 2020-02-11 16:09:21 +03:00
Mikhail Glukhikh
28332933ce [FIR TEST] Add test case about values() priority (static over companion) 2020-02-11 16:09:20 +03:00
Mikhail Glukhikh
dc7621a112 [FIR] Fix Java override ambiguity (Kotlin type parameter VS Java Object) 2020-02-11 16:09:20 +03:00
Toshiaki Kameyama
4b5f3b7a94 Extract property: do not add unnecessary extension receiver
#KT-24615 Fixed
2020-02-11 15:52:47 +03:00
Ilya Kirillov
0fe5694cb7 Do not render redundant Nullable annotations when generating declarations
#KT-36321 fixed
2020-02-11 13:48:58 +03:00
Ilya Kirillov
4df8744b34 Rename by-name parameter usage in function calls when renaming function's parameter
#KT-32999 fixed
2020-02-11 13:48:56 +03:00
Ilya Chernikov
349d07ad43 [minor] Fix testdata after commit "Only create descriptors for candidate"... 2020-02-11 11:20:05 +01:00
Dmitriy Dolovov
a5e9e09755 [Commonizer] Properly detect commonized KLIBs in IDE 2020-02-11 17:14:19 +07:00
Dmitriy Dolovov
51af1c13b1 [Commonizer] Don't use base64 with padding in paths to libraries 2020-02-11 17:14:11 +07:00
Dmitry Gridin
f46fc19fdf ProhibitRepeatedUseSiteTargetAnnotationsMigration: improve name and description
#KT-36477 Fixed
2020-02-11 10:25:46 +07:00
Dmitry Gridin
bcfd089473 AbstractDiagnosticBasedMigrationInspection: fix case with nullable custom factory
#KT-36479 Fixed
2020-02-11 09:58:59 +07:00
Dmitriy Dolovov
b9911d0e0c [Commonizer] Use only if kotlin.native.enableDependencyPropagation=false 2020-02-11 08:51:54 +07:00
Dmitriy Dolovov
f98a4e6715 Minor. Text formatted in commonizer CLI 2020-02-11 08:51:47 +07:00
Dmitriy Dolovov
63b03d29dc [Commonizer] Prevent from running commonizer from Gradle more then once 2020-02-11 08:51:39 +07:00
Dmitriy Dolovov
7cf4395ccd [Commonizer] Integrate commonizer to the Gradle plugin, p.2
Call commonizer CLI via Gradle tool runner.
2020-02-11 08:51:32 +07:00
Dmitriy Dolovov
d7e82bf899 [Commonizer] Integrate commonizer to the Gradle plugin, p.1
Detect when it's really necessary to run commonizer. Resolve Kotlin/Native
platform dependencies. Add dependencies to the proper Gradle configurations.

Note: The most common source sets such as "commonMain" and "commonTest"
should not be used as Native intermediate source sets.
2020-02-11 08:51:24 +07:00
Dmitriy Dolovov
4ccff3f1b1 [Commonizer] Add extendable uniform multi-task CLI 2020-02-11 08:51:15 +07:00
Dmitriy Dolovov
91fce721b3 [Commonizer] Publish artifact for Kotlin embeddable compiler 2020-02-11 08:51:07 +07:00
Dmitriy Dolovov
4027079b41 [Commonizer] Fix dependencies visible in POM file 2020-02-11 08:51:00 +07:00
Dmitriy Dolovov
b711c6d398 Rename :native:kotlin-native-commonizer to :native:kotlin-klib-commonizer 2020-02-11 08:50:50 +07:00
Igor Yakovlev
07863b61d8 Fix UL classes failing tests
UltraLightClassLoadingTestGenerated.testInferringAnonymousObjectTypes
UltraLightClassLoadingTestGenerated.testObjects
2020-02-10 23:35:47 +03:00
Alexander Udalov
dc7b1fbff9 JVM IR: report warning instead of error for language/API version 1.2
This is needed for testing JVM IR on existing projects which for some
reason are still on Kotlin 1.2.
2020-02-10 17:32:18 +01:00
victor.petukhov
b8aacf0786 Fix test data around flexibility after ae39d748e4 2020-02-10 19:23:57 +03:00
Dmitry Gridin
dc2a9cdc81 Add missing inspections for 191, 192 2020-02-10 23:13:50 +07:00
Mikhail Glukhikh
2c918d2787 [FIR TEST] Add example with invoke priority inconsistent with old FE 2020-02-10 18:51:35 +03:00
Mikhail Glukhikh
232efa6303 [FIR] Fix situation with synthetic property in implicit body 2020-02-10 18:51:35 +03:00
Mikhail Glukhikh
d19d52292e [FIR] Use builder to create synthetic properties 2020-02-10 18:51:34 +03:00
Mikhail Glukhikh
9a80850700 [FIR] Fix Kotlin-Java supertype recursion problem 2020-02-10 18:51:34 +03:00
Mikhail Glukhikh
cc0e39ebca [FIR] Support synthetic property setters 2020-02-10 18:51:34 +03:00
Mikhail Glukhikh
a9ba94cf0e [FIR] Use only variable symbol inheritors in processPropertiesByName 2020-02-10 18:51:34 +03:00
Mikhail Glukhikh
a569e29091 [FIR] Make SyntheticPropertySymbol derived from FirAccessorSymbol 2020-02-10 18:51:33 +03:00
Mikhail Glukhikh
a7f9e3ab09 [FIR] Accessor symbol is now a property symbol, not a function symbol 2020-02-10 18:51:33 +03:00
Mikhail Glukhikh
69809fef94 [FIR] Synthetic property symbol is now a property symbol, not a function 2020-02-10 18:51:33 +03:00
Georgy Bronnikov
17e1f081c7 JVM_IR: handle nested function references in InlineCallableReferenceToLambda 2020-02-10 18:47:04 +03:00
Alexander Udalov
15ff74209c JVM IR: do not resolve fake override in InterfaceSuperCallsLowering
This leads to problems after 4dd794c2d2, because the immediate super
function's DefaultImpls and the implementation's DefaultImpls have
differing type parameters.

Looks like resolveFakeOverride was used here (maybe unintentionally) as
a workaround to the problem caused by the incorrect origin check in
isDefinitelyNotDefaultImplsMethod.
2020-02-10 16:08:10 +01:00
Vladimir Dolzhenko
d9cbc459d0 Use PluginManagerCore instead of PluginManager
Relates to #KT-35918
2020-02-10 15:50:37 +01:00
Vladimir Dolzhenko
44cf0a9f72 Don't insert import if deprecation replacement contains stdlib typealias
Fixed #KT-14781
2020-02-10 14:59:40 +01:00
Ilya Chernikov
2249c223fe Only create descriptors for candidates with lambda args
#KT-36247 fixed
2020-02-10 14:21:02 +01:00
Dmitriy Novozhilov
6ed4229359 [FIR] Fix smartcasts on member vals in init blocks 2020-02-10 15:53:57 +03:00
Yan Zhulanow
36a6eedd9c Minor: Update generated tests for KT-34569 2020-02-10 21:25:01 +09:00
Vladimir Dolzhenko
052710db16 Added idea-plugin-performance-tests task 2020-02-10 12:27:38 +01:00
Denis Zharkov
becc9c21f0 FIR: Map raw types properly 2020-02-10 14:11:49 +03:00
Denis Zharkov
b3f9fa22b4 FIR: Fix inference when bound comes from type alias
It's type depth may be computed incorrectly
and relevant constraint is being skipped
2020-02-10 14:11:49 +03:00
Dmitry Gridin
733e596eed Create WarningOnMainUnusedParameterMigrationInspection
#KT-36256 Fixed
2020-02-10 17:04:07 +07:00
Dmitry Gridin
8d48d899d0 Create ProhibitRepeatedUseSiteTargetAnnotationsMigrationInspection
#KT-36257 Fixed
2020-02-10 17:04:07 +07:00
Dmitry Gridin
266a7a67f0 Create ProhibitUseSiteTargetAnnotationsOnSuperTypesMigrationInspection
#KT-36258 Fixed
2020-02-10 17:04:07 +07:00
Dmitry Gridin
181dd432ca RestrictReturnStatementTargetMigrationInspection: add quickfix
#KT-36262 Fixed
2020-02-10 17:04:07 +07:00
Dmitry Gridin
f1bad0c9ae Convert RemoveReturnLabelFix from LocalQuickFix to KotlinQuickFixAction 2020-02-10 17:04:07 +07:00
Dmitry Gridin
e9dc1e07b9 Extract RemoveReturnLabelFix 2020-02-10 17:04:07 +07:00
Dmitry Gridin
311860699e Create RedundantLabelMigrationInspection
#KT-36262
2020-02-10 17:04:06 +07:00
Dmitry Gridin
2441ee80e4 Create RestrictReturnStatementTargetMigrationInspection
#KT-36262
2020-02-10 17:04:06 +07:00
Dmitry Gridin
2f3e3b9c9e Create ProhibitJvmOverloadsOnConstructorsOfAnnotationClassesMigrationInspection
#KT-36260 Fixed
2020-02-10 17:04:06 +07:00
Dmitry Gridin
cbcc76c3ff Create ProhibitTypeParametersForLocalVariablesMigrationInspection
#KT-36261 Fixed
2020-02-10 17:04:06 +07:00
Dmitry Gridin
8c455d9e08 Create AbstractDiagnosticBasedInspection 2020-02-10 17:04:06 +07:00
Victor Petukhov
ae39d748e4 NI: Try to solve constraint system with another flexibility from a type variable if couldn't solve
^KT-36254 Fixed
2020-02-10 12:31:42 +03:00
Dmitriy Novozhilov
b5dd16784a [FIR] Add .gitattributes for correct line endings on windows 2020-02-10 11:58:54 +03:00
Dmitry Petrov
b9357b5486 Fix project build, part 2 2020-02-10 11:49:54 +03:00
5377 changed files with 102750 additions and 106950 deletions

1
.bunch
View File

@@ -1,4 +1,5 @@
193
201
192
191_192
as35_191_192

View File

@@ -1,8 +0,0 @@
<component name="ArtifactManager">
<artifact build-on-make="true" name="dist_root">
<output-path>$PROJECT_DIR$/dist</output-path>
<root id="root">
<element id="artifact" artifact-name="dist" />
</root>
</artifact>
</component>

View File

@@ -6,6 +6,7 @@
<w>destructured</w>
<w>hacky</w>
<w>impls</w>
<w>inlined</w>
<w>kapt</w>
<w>kotlinc</w>
<w>mutators</w>

View File

@@ -0,0 +1,50 @@
/*
* 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.benchmarks
import org.openjdk.jmh.annotations.*
import org.openjdk.jmh.infra.Blackhole
import java.util.concurrent.TimeUnit
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
open class ManyImplicitReceiversBenchmark : AbstractSimpleFileBenchmark() {
@Param("1", "10", "50")
private var size: Int = 0
@Benchmark
fun benchmark(bh: Blackhole) {
analyzeGreenFile(bh)
}
override fun buildText(): String {
return buildString {
appendln("inline fun <T, R> with(receiver: T, block: T.() -> R): R = block()")
for (i in 1..size) {
appendln("interface A$i {")
appendln(" fun foo$i()")
appendln("}")
appendln()
}
appendln()
append("fun test(")
append((1..size).joinToString(", ") { "a$it: A$it" })
appendln(" {")
for (i in 1..size) {
appendln("with(a$i) {")
}
for (i in 1..size) {
appendln("foo$i()")
}
for (i in 1..size) {
appendln("}")
}
appendln("}")
}
}
}

View File

@@ -23,8 +23,9 @@ dependencies {
testCompile(commonDep("junit:junit"))
testCompile(protobufFull())
testCompile(kotlinStdlib())
testCompileOnly(intellijDep()) { includeJars("openapi") }
Platform[193].orLower {
testCompileOnly(intellijDep()) { includeJars("openapi", rootProject = rootProject) }
}
testRuntime(project(":kotlin-reflect"))
}

View File

@@ -128,8 +128,8 @@ open class IncrementalJsCache(
}
for ((srcFile, irData) in incrementalResults.irFileData) {
val (fileData, symbols, types, strings, declarations, bodies, fqn) = irData
irTranslationResults.put(srcFile, fileData, symbols, types, strings, declarations, bodies, fqn)
val (fileData, types, signatures, strings, declarations, bodies, fqn) = irData
irTranslationResults.put(srcFile, fileData, types, signatures, strings, declarations, bodies, fqn)
}
}
@@ -240,8 +240,8 @@ private class TranslationResultMap(
private object IrTranslationResultValueExternalizer : DataExternalizer<IrTranslationResultValue> {
override fun save(output: DataOutput, value: IrTranslationResultValue) {
output.writeArray(value.fileData)
output.writeArray(value.symbols)
output.writeArray(value.types)
output.writeArray(value.signatures)
output.writeArray(value.strings)
output.writeArray(value.declarations)
output.writeArray(value.bodies)
@@ -262,14 +262,14 @@ private object IrTranslationResultValueExternalizer : DataExternalizer<IrTransla
override fun read(input: DataInput): IrTranslationResultValue {
val fileData = input.readArray()
val symbols = input.readArray()
val types = input.readArray()
val signatures = input.readArray()
val strings = input.readArray()
val declarations = input.readArray()
val bodies = input.readArray()
val fqn = input.readArray()
return IrTranslationResultValue(fileData, symbols, types, strings, declarations, bodies, fqn)
return IrTranslationResultValue(fileData, types, signatures, strings, declarations, bodies, fqn)
}
}
@@ -280,8 +280,8 @@ private class IrTranslationResultMap(
BasicStringMap<IrTranslationResultValue>(storageFile, IrTranslationResultValueExternalizer) {
override fun dumpValue(value: IrTranslationResultValue): String =
"Filedata: ${value.fileData.md5()}, " +
"Symbols: ${value.symbols.md5()}, " +
"Types: ${value.types.md5()}, " +
"Signatures: ${value.signatures.md5()}, " +
"Strings: ${value.strings.md5()}, " +
"Declarations: ${value.declarations.md5()}, " +
"Bodies: ${value.bodies.md5()}"
@@ -289,15 +289,15 @@ private class IrTranslationResultMap(
fun put(
sourceFile: File,
newFiledata: ByteArray,
newSymbols: ByteArray,
newTypes: ByteArray,
newSignatures: ByteArray,
newStrings: ByteArray,
newDeclarations: ByteArray,
newBodies: ByteArray,
fqn: ByteArray
) {
storage[pathConverter.toPath(sourceFile)] =
IrTranslationResultValue(newFiledata, newSymbols, newTypes, newStrings, newDeclarations, newBodies, fqn)
IrTranslationResultValue(newFiledata, newTypes, newSignatures, newStrings, newDeclarations, newBodies, fqn)
}
operator fun get(sourceFile: File): IrTranslationResultValue? =

View File

@@ -28,9 +28,8 @@ import org.jetbrains.kotlin.modules.KotlinModuleXmlBuilder
import org.jetbrains.kotlin.modules.TargetId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.progress.CompilationCanceledStatus
import org.jetbrains.kotlin.synthetic.SAM_LOOKUP_NAME
import org.jetbrains.kotlin.resolve.sam.SAM_LOOKUP_NAME
import org.jetbrains.kotlin.utils.addToStdlib.flattenTo
import org.jetbrains.kotlin.utils.keysToMap
import java.io.File
import java.util.*
import kotlin.collections.HashSet

View File

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

View File

@@ -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)
@@ -28,6 +28,7 @@ buildscript {
dependencies {
bootstrapCompilerClasspath(kotlin("compiler-embeddable", bootstrapKotlinVersion))
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.12")
classpath("com.gradle.publish:plugin-publish-plugin:0.9.7")
classpath(kotlin("gradle-plugin", bootstrapKotlinVersion))
classpath("net.sf.proguard:proguard-gradle:6.1.0")
@@ -172,14 +173,14 @@ extra["versions.org.springframework"] = "4.2.0.RELEASE"
extra["versions.jflex"] = "1.7.0"
extra["versions.markdown"] = "0.1.25"
extra["versions.trove4j"] = "1.0.20181211"
extra["versions.completion-ranking-kotlin"] = "0.0.2"
extra["versions.completion-ranking-kotlin"] = "0.1.2"
extra["versions.r8"] = "1.5.70"
// NOTE: please, also change KTOR_NAME in pathUtil.kt and all versions in corresponding jar names in daemon tests.
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-dev-14579"
}
val intellijUltimateEnabled by extra(project.kotlinBuildProperties.intellijUltimateEnabled)
@@ -197,11 +198,11 @@ extra["IntellijCoreDependencies"] =
"jdom",
"jna",
"log4j",
"picocontainer",
if (Platform[201].orHigher()) null else "picocontainer",
"snappy-in-java",
"streamex",
"trove4j"
)
).filterNotNull()
extra["compilerModules"] = arrayOf(
@@ -385,6 +386,11 @@ allprojects {
isReproducibleFileOrder = true
}
tasks.withType<Test> {
outputs.cacheIf { false }
// https://youtrack.jetbrains.com/issue/KT-37089
}
tasks {
register("listArchives") { listConfigurationContents("archives") }
@@ -536,7 +542,8 @@ tasks {
}
register("wasmCompilerTest") {
dependsOn(":js:js.tests:wasmTest")
// TODO: fix once
// dependsOn(":js:js.tests:wasmTest")
}
register("firCompilerTest") {
@@ -545,7 +552,17 @@ tasks {
dependsOn(":compiler:fir:fir2ir:test")
dependsOn(":compiler:fir:lightTree:test")
}
register("firAllTest") {
dependsOn(
":compiler:fir:psi2fir:test",
":compiler:fir:lightTree:test",
":compiler:fir:resolve:test",
":compiler:fir:fir2ir:test",
":idea:firTest"
)
}
register("compilerFrontendVisualizerTest") {
dependsOn("compiler:visualizer:test")
}
@@ -615,7 +632,7 @@ tasks {
register("konan-tests") {
dependsOn("dist")
dependsOn(
":native:kotlin-native-commonizer:test"
":native:kotlin-klib-commonizer:test"
)
}
@@ -657,6 +674,13 @@ tasks {
)
}
register("idea-plugin-performance-tests") {
dependsOn("dist")
dependsOn(
":idea:performanceTests:performanceTest"
)
}
register("android-ide-tests") {
dependsOn("dist")
dependsOn(

View File

@@ -1,4 +1,3 @@
extra["versions.shadow"] = "5.2.0"
extra["versions.native-platform"] = "0.14"
buildscript {
@@ -22,7 +21,7 @@ buildscript {
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.8")
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.12")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$buildSrcKotlinVersion")
classpath("org.jetbrains.kotlin:kotlin-sam-with-receiver:$buildSrcKotlinVersion")
}
@@ -46,10 +45,6 @@ plugins {
gradlePlugin {
plugins {
register("pill-configurable") {
id = "pill-configurable"
implementationClass = "org.jetbrains.kotlin.pill.PillConfigurablePlugin"
}
register("jps-compatible") {
id = "jps-compatible"
implementationClass = "org.jetbrains.kotlin.pill.JpsCompatiblePlugin"
@@ -72,10 +67,11 @@ val intellijUltimateEnabled by extra(kotlinBuildProperties.intellijUltimateEnabl
val intellijSeparateSdks by extra(project.getBooleanProperty("intellijSeparateSdks") ?: false)
val verifyDependencyOutput by extra( getBooleanProperty("kotlin.build.dependency.output.verification") ?: isTeamcityBuild)
extra["intellijReleaseType"] = if (extra["versions.intellijSdk"]?.toString()?.endsWith("SNAPSHOT") == true)
"snapshots"
else
"releases"
extra["intellijReleaseType"] = when {
extra["versions.intellijSdk"]?.toString()?.contains("-EAP-") == true -> "snapshots"
extra["versions.intellijSdk"]?.toString()?.endsWith("SNAPSHOT") == true -> "nightly"
else -> "releases"
}
extra["versions.androidDxSources"] = "5.0.0_r2"
@@ -94,14 +90,14 @@ repositories {
dependencies {
implementation(kotlin("stdlib", embeddedKotlinVersion))
implementation("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.8")
implementation("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.12")
implementation("net.rubygrapefruit:native-platform:${property("versions.native-platform")}")
implementation("net.rubygrapefruit:native-platform-windows-amd64:${property("versions.native-platform")}")
implementation("net.rubygrapefruit:native-platform-windows-i386:${property("versions.native-platform")}")
implementation("com.jakewharton.dex:dex-method-list:3.0.0")
implementation("com.github.jengelman.gradle.plugins:shadow:${property("versions.shadow")}")
implementation("com.github.jengelman.gradle.plugins:shadow:${rootProject.extra["versions.shadow"]}")
implementation("org.jetbrains.intellij.deps:asm-all:7.0.1")
implementation("gradle.plugin.org.jetbrains.gradle.plugin.idea-ext:gradle-idea-ext:0.5")

View File

@@ -373,10 +373,7 @@ fun writeIvyXml(
sourcesJar.forEach { jarFile ->
emptyElement("artifact") {
val sourcesArtifactName = jarFile.name
.substringBeforeLast("-")
.substringBeforeLast("-")
val sourcesArtifactName = jarFile.name.substringBefore("-$version")
attributes(
"name" to sourcesArtifactName,
"type" to "jar",

View File

@@ -20,7 +20,7 @@ buildscript {
}
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.8")
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.12")
}
}

View File

@@ -26,7 +26,7 @@ fun CompatibilityPredicate.or(other: CompatibilityPredicate): CompatibilityPredi
}
enum class Platform : CompatibilityPredicate {
P183, P191, P192, P193;
P183, P191, P192, P193, P201;
val version: Int = name.drop(1).toInt()
@@ -44,6 +44,7 @@ enum class Ide(val platform: Platform) : CompatibilityPredicate {
IJ191(Platform.P191),
IJ192(Platform.P192),
IJ193(Platform.P193),
IJ201(Platform.P201),
AS35(Platform.P183),
AS36(Platform.P192),

View File

@@ -14,9 +14,15 @@ import org.gradle.kotlin.dsl.extra
import org.gradle.kotlin.dsl.project
import java.io.File
val Project.isSnapshotIntellij get() = rootProject.extra["versions.intellijSdk"].toString().endsWith("SNAPSHOT")
private val Project.isEAPIntellij get() = rootProject.extra["versions.intellijSdk"].toString().contains("-EAP-")
private val Project.isNightlyIntellij get() = rootProject.extra["versions.intellijSdk"].toString().endsWith("SNAPSHOT") && !isEAPIntellij
val Project.intellijRepo get() = "https://www.jetbrains.com/intellij-repository/" + if (isSnapshotIntellij) "snapshots" else "releases"
val Project.intellijRepo get() =
when {
isEAPIntellij -> "https://www.jetbrains.com/intellij-repository/snapshots"
isNightlyIntellij -> "https://www.jetbrains.com/intellij-repository/nightly"
else -> "https://www.jetbrains.com/intellij-repository/releases"
}
fun Project.commonDep(coord: String): String {
val parts = coord.split(':')

View File

@@ -0,0 +1,36 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@file:Suppress("PackageDirectoryMismatch")
package org.jetbrains.kotlin.pill
import org.gradle.api.Plugin
import org.gradle.api.Project
@Suppress("unused")
class JpsCompatiblePlugin : Plugin<Project> {
override fun apply(project: Project) {
project.configurations.maybeCreate(EmbeddedComponents.CONFIGURATION_NAME)
project.extensions.create("pill", PillExtension::class.java)
// 'jpsTest' does not require the 'tests-jar' artifact
project.configurations.create("jpsTest")
if (project == project.rootProject) {
project.tasks.create("pill") {
dependsOn(":pill:pill-importer:pill")
if (System.getProperty("pill.android.tests", "false") == "true") {
TaskUtils.useAndroidSdk(this)
TaskUtils.useAndroidJar(this)
}
}
project.tasks.create("unpill") {
dependsOn(":pill:pill-importer:unpill")
}
}
}
}

View File

@@ -1,3 +1,8 @@
/*
* 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.
*/
@file:Suppress("PackageDirectoryMismatch")
package org.jetbrains.kotlin.pill
@@ -7,33 +12,40 @@ import org.gradle.api.Project
open class PillExtension {
enum class Variant {
// Default variant (./gradlew pill)
BASE() { override val includes = setOf(BASE) },
BASE() {
override val includes = setOf(BASE)
},
// Full variant (./gradlew pill -Dpill.variant=full)
FULL() { override val includes = setOf(BASE, FULL) },
FULL() {
override val includes = setOf(BASE, FULL)
},
// Do not import the project to JPS model, but set some options for it
NONE() { override val includes = emptySet<Variant>() },
NONE() {
override val includes = emptySet<Variant>()
},
// 'BASE' if the "jps-compatible" plugin is applied, 'NONE' otherwise
DEFAULT() { override val includes = emptySet<Variant>() };
DEFAULT() {
override val includes = emptySet<Variant>()
};
abstract val includes: Set<Variant>
}
open var variant: Variant = Variant.DEFAULT
open var importAsLibrary: Boolean = false
open var excludedDirs: List<File> = emptyList()
@Suppress("unused")
fun Project.excludedDirs(vararg dirs: String) {
excludedDirs = excludedDirs + dirs.map { File(projectDir, it) }
}
open var libraryPath: File? = null
set(v) {
importAsLibrary = true
field = v
}
@Suppress("unused")
fun serialize() = mapOf<String, Any?>(
"variant" to variant.name,
"excludedDirs" to excludedDirs
)
}

View File

@@ -1,33 +0,0 @@
@file:Suppress("PackageDirectoryMismatch")
package org.jetbrains.kotlin.pill
import org.gradle.api.artifacts.*
import org.gradle.api.artifacts.component.*
class DependencyMapper(val predicate: (ResolvedArtifact) -> Boolean, val mapping: (ResolvedArtifact) -> MappedDependency?) {
companion object {
fun forProject(path: String, mapping: (ResolvedArtifact) -> MappedDependency?): DependencyMapper {
return DependencyMapper(
predicate = { artifact ->
val identifier = artifact.id.componentIdentifier as? ProjectComponentIdentifier
identifier?.projectPath == path
},
mapping = mapping
)
}
fun forModule(group: String, module: String, version: String?, mapping: (ResolvedArtifact) -> MappedDependency?): DependencyMapper {
return DependencyMapper(
predicate = { artifact ->
val identifier = artifact.id.componentIdentifier as? ModuleComponentIdentifier
identifier?.group == group && identifier?.module == module && (version == null || identifier?.version == version)
},
mapping = mapping
)
}
}
}
class MappedDependency(val main: PDependency?, val deferred: List<PDependency> = emptyList())
class ParserContext(val dependencyMappers: List<DependencyMapper>, val variant: PillExtension.Variant)

View File

@@ -1,94 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@file:Suppress("PackageDirectoryMismatch")
package org.jetbrains.kotlin.pill
import java.io.File
import org.gradle.api.Project
import org.gradle.api.tasks.SourceSet
import org.gradle.api.artifacts.*
import org.gradle.api.artifacts.component.*
data class PDependencies(val main: List<PDependency>, val deferred: List<PDependency>) {
fun join(): List<PDependency> {
return main + deferred
}
}
fun Project.resolveDependencies(
configuration: Configuration,
forTests: Boolean,
dependencyMappers: List<DependencyMapper>,
withEmbedded: Boolean = false
): PDependencies {
val dependencies = mutableListOf<PDependency>()
val deferred = mutableListOf<PDependency>()
nextArtifact@ for (artifact in configuration.resolvedConfiguration.resolvedArtifacts) {
val identifier = artifact.id.componentIdentifier
for (mapper in dependencyMappers) {
if (mapper.predicate(artifact)) {
val mapped = mapper.mapping(artifact)
if (mapped != null) {
mapped.main?.let { dependencies += it }
deferred += mapped.deferred
}
continue@nextArtifact
}
}
fun addProjectDependency(projectPath: String) {
val project = rootProject.findProject(projectPath) ?: error("Cannot find project $projectPath")
fun addSourceSet(name: String, suffix: String): Boolean {
val sourceSet = project.sourceSets?.findByName(name)?.takeIf { !it.allSource.isEmpty() } ?: return false
dependencies += PDependency.Module(project.pillModuleName + '.' + suffix)
return true
}
if (forTests && artifact.classifier == "tests") {
addSourceSet(SourceSet.TEST_SOURCE_SET_NAME, "test") || addSourceSet(SourceSet.MAIN_SOURCE_SET_NAME, "src")
} else {
addSourceSet(SourceSet.MAIN_SOURCE_SET_NAME, "src")
}
if (withEmbedded) {
val embeddedConfiguration = project.configurations.findByName(EmbeddedComponents.CONFIGURATION_NAME)
if (embeddedConfiguration != null) {
dependencies += resolveDependencies(embeddedConfiguration, forTests, dependencyMappers, withEmbedded).join()
}
}
}
when (identifier) {
is ProjectComponentIdentifier -> addProjectDependency(identifier.projectPath)
is LibraryBinaryIdentifier -> addProjectDependency(identifier.projectPath)
is ModuleComponentIdentifier -> {
val file = artifact.file
val library = PLibrary(file.name, classes = listOf(file))
dependencies += PDependency.ModuleLibrary(library)
}
}
}
val existingFiles = mutableSetOf<File>()
for (dependency in configuration.dependencies) {
if (dependency !is SelfResolvingDependency) {
continue
}
val files = dependency.resolve().filter { it !in existingFiles }.takeIf { it.isNotEmpty() } ?: continue
existingFiles.addAll(files)
val library = PLibrary(dependency.name, classes = files.toList())
deferred += PDependency.ModuleLibrary(library)
}
return PDependencies(dependencies, deferred)
}

View File

@@ -1,420 +0,0 @@
/*
* 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.
*/
@file:Suppress("PackageDirectoryMismatch")
package org.jetbrains.kotlin.pill
import org.gradle.api.Project
import org.gradle.api.artifacts.*
import org.gradle.api.tasks.*
import org.gradle.api.plugins.JavaPlugin
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.kotlin.dsl.configure
import org.gradle.plugins.ide.idea.IdeaPlugin
import org.gradle.api.file.SourceDirectorySet
import org.gradle.api.internal.HasConvention
import org.gradle.api.internal.file.copy.CopySpecInternal
import org.gradle.api.internal.file.copy.SingleParentCopySpec
import org.gradle.language.jvm.tasks.ProcessResources
import org.jetbrains.kotlin.pill.POrderRoot.*
import org.jetbrains.kotlin.pill.PSourceRoot.*
import org.jetbrains.kotlin.pill.PillExtension.*
import java.io.File
import java.util.LinkedList
data class PProject(
val name: String,
val rootDirectory: File,
val modules: List<PModule>,
val libraries: List<PLibrary>
)
data class PModule(
val name: String,
val rootDirectory: File,
val moduleFile: File,
val contentRoots: List<PContentRoot>,
val orderRoots: List<POrderRoot>,
val moduleForProductionSources: PModule? = null
)
data class PContentRoot(
val path: File,
val forTests: Boolean,
val sourceRoots: List<PSourceRoot>,
val excludedDirectories: List<File>
)
data class PSourceRoot(
val path: File,
val kind: Kind,
val kotlinOptions: PSourceRootKotlinOptions?
) {
enum class Kind { PRODUCTION, TEST, RESOURCES, TEST_RESOURCES }
}
data class PSourceRootKotlinOptions(
val noStdlib: Boolean?,
val noReflect: Boolean?,
val moduleName: String?,
val apiVersion: String?,
val languageVersion: String?,
val jvmTarget: String?,
val extraArguments: List<String>
) {
fun intersect(other: PSourceRootKotlinOptions) = PSourceRootKotlinOptions(
if (noStdlib == other.noStdlib) noStdlib else null,
if (noReflect == other.noReflect) noReflect else null,
if (moduleName == other.moduleName) moduleName else null,
if (apiVersion == other.apiVersion) apiVersion else null,
if (languageVersion == other.languageVersion) languageVersion else null,
if (jvmTarget == other.jvmTarget) jvmTarget else null,
extraArguments.intersect(other.extraArguments).toList()
)
}
data class POrderRoot(
val dependency: PDependency,
val scope: Scope,
val isExported: Boolean = false,
val isProductionOnTestDependency: Boolean = false
) {
enum class Scope { COMPILE, TEST, RUNTIME, PROVIDED }
}
sealed class PDependency {
data class Module(val name: String) : PDependency()
data class Library(val name: String) : PDependency()
data class ModuleLibrary(val library: PLibrary) : PDependency()
}
data class PLibrary(
val name: String,
val classes: List<File>,
val javadoc: List<File> = emptyList(),
val sources: List<File> = emptyList(),
val annotations: List<File> = emptyList(),
val dependencies: List<PLibrary> = emptyList(),
val originalName: String = name
) {
fun attachSource(file: File): PLibrary {
return this.copy(sources = this.sources + listOf(file))
}
}
fun parse(project: Project, libraries: List<PLibrary>, context: ParserContext): PProject = with (context) {
if (project != project.rootProject) {
error("$project is not a root project")
}
fun Project.matchesSelectedVariant(): Boolean {
val extension = this.extensions.findByType(PillExtension::class.java) ?: return true
val projectVariant = extension.variant.takeUnless { it == Variant.DEFAULT } ?: Variant.BASE
return projectVariant in context.variant.includes
}
val (includedProjects, excludedProjects) = project.allprojects
.partition { it.plugins.hasPlugin(JpsCompatiblePlugin::class.java) && it.matchesSelectedVariant() }
val modules = includedProjects.flatMap { parseModules(it, excludedProjects) }
return PProject("Kotlin", project.projectDir, modules, libraries)
}
/*
Ordering here and below is significant.
Placing 'runtime' configuration dependencies on the top make 'idea' tests to run normally.
('idea' module has 'intellij-core' as transitive dependency, and we really need to get rid of it.)
*/
private val CONFIGURATION_MAPPING = mapOf(
listOf("runtimeClasspath") to Scope.RUNTIME,
listOf("compileClasspath", "compileOnly") to Scope.PROVIDED,
listOf("embedded") to Scope.COMPILE
)
private val TEST_CONFIGURATION_MAPPING = mapOf(
listOf("runtimeClasspath", "testRuntimeClasspath") to Scope.RUNTIME,
listOf("compileClasspath", "testCompileClasspath", "compileOnly", "testCompileOnly") to Scope.PROVIDED,
listOf("jpsTest") to Scope.TEST
)
private fun ParserContext.parseModules(project: Project, excludedProjects: List<Project>): List<PModule> {
val (productionContentRoots, testContentRoots) = parseContentRoots(project).partition { !it.forTests }
val modules = mutableListOf<PModule>()
fun getJavaExcludedDirs() = project.plugins.findPlugin(IdeaPlugin::class.java)
?.model?.module?.excludeDirs?.toList() ?: emptyList()
fun getPillExcludedDirs() = project.extensions.getByType(PillExtension::class.java).excludedDirs
val allExcludedDirs = getPillExcludedDirs() + getJavaExcludedDirs() + project.buildDir +
(if (project == project.rootProject) excludedProjects.map { it.buildDir } else emptyList())
var productionSourcesModule: PModule? = null
fun getModuleFile(suffix: String = ""): File {
val relativePath = File(project.projectDir, project.pillModuleName + suffix + ".iml")
.toRelativeString(project.rootProject.projectDir)
return File(project.rootProject.projectDir, ".idea/modules/$relativePath")
}
for ((nameSuffix, roots) in mapOf(".src" to productionContentRoots, ".test" to testContentRoots)) {
if (roots.isEmpty()) {
continue
}
val mainRoot = roots.first()
var dependencies = parseDependencies(project, mainRoot.forTests)
if (productionContentRoots.isNotEmpty() && mainRoot.forTests) {
val productionModuleDependency = PDependency.Module(project.pillModuleName + ".src")
dependencies += POrderRoot(productionModuleDependency, Scope.COMPILE, true)
}
val module = PModule(
project.pillModuleName + nameSuffix,
mainRoot.path,
getModuleFile(nameSuffix),
roots,
dependencies,
productionSourcesModule
)
modules += module
if (!mainRoot.forTests) {
productionSourcesModule = module
}
}
val mainModuleFileRelativePath = when (project) {
project.rootProject -> File(project.rootProject.projectDir, project.rootProject.name + ".iml")
else -> getModuleFile()
}
modules += PModule(
project.pillModuleName,
project.projectDir,
mainModuleFileRelativePath,
listOf(PContentRoot(project.projectDir, false, emptyList(), allExcludedDirs)),
if (modules.isEmpty()) parseDependencies(project, false) else emptyList()
)
return modules
}
private fun parseContentRoots(project: Project): List<PContentRoot> {
val sourceRoots = parseSourceRoots(project).groupBy { it.kind }
fun getRoots(kind: PSourceRoot.Kind) = sourceRoots[kind] ?: emptyList()
val productionSourceRoots = getRoots(Kind.PRODUCTION) + getRoots(Kind.RESOURCES)
val testSourceRoots = getRoots(Kind.TEST) + getRoots(Kind.TEST_RESOURCES)
fun createContentRoots(sourceRoots: List<PSourceRoot>, forTests: Boolean): List<PContentRoot> {
return sourceRoots.map { PContentRoot(it.path, forTests, listOf(it), emptyList()) }
}
return createContentRoots(productionSourceRoots, forTests = false) +
createContentRoots(testSourceRoots, forTests = true)
}
private fun parseSourceRoots(project: Project): List<PSourceRoot> {
if (!project.plugins.hasPlugin(JavaPlugin::class.java)) {
return emptyList()
}
val kotlinTasksBySourceSet = project.tasks.names
.filter { it.startsWith("compile") && it.endsWith("Kotlin") }
.map { project.tasks.getByName(it) }
.associateBy { it.invokeInternal("getSourceSetName") }
val sourceRoots = mutableListOf<PSourceRoot>()
val sourceSets = project.sourceSets
if (sourceSets != null) {
for (sourceSet in sourceSets) {
val kotlinCompileTask = kotlinTasksBySourceSet[sourceSet.name]
val kind = if (sourceSet.isTestSourceSet) Kind.TEST else Kind.PRODUCTION
fun Any.getKotlin(): SourceDirectorySet {
val kotlinMethod = javaClass.getMethod("getKotlin")
val oldIsAccessible = kotlinMethod.isAccessible
try {
kotlinMethod.isAccessible = true
return kotlinMethod(this) as SourceDirectorySet
} finally {
kotlinMethod.isAccessible = oldIsAccessible
}
}
val kotlinSourceDirectories = (sourceSet as HasConvention).convention
.plugins["kotlin"]?.getKotlin()?.srcDirs
?: emptySet()
val directories = (sourceSet.java.sourceDirectories.files + kotlinSourceDirectories).toList()
.filter { it.exists() }
.takeIf { it.isNotEmpty() }
?: continue
val kotlinOptions = kotlinCompileTask?.let { getKotlinOptions(it) }
for (resourceRoot in sourceSet.resources.sourceDirectories.files) {
if (!resourceRoot.exists() || resourceRoot in directories) {
continue
}
val resourceRootKind = when (kind) {
Kind.PRODUCTION -> Kind.RESOURCES
Kind.TEST -> Kind.TEST_RESOURCES
else -> error("Invalid source root kind $kind")
}
sourceRoots += PSourceRoot(resourceRoot, resourceRootKind, kotlinOptions)
}
for (directory in directories) {
sourceRoots += PSourceRoot(directory, kind, kotlinOptions)
}
for (root in parseResourceRootsProcessedByProcessResourcesTask(project, sourceSet)) {
if (sourceRoots.none { it.path == root.path }) {
sourceRoots += root
}
}
}
}
return sourceRoots
}
private fun parseResourceRootsProcessedByProcessResourcesTask(project: Project, sourceSet: SourceSet): List<PSourceRoot> {
val isMainSourceSet = sourceSet.name == SourceSet.MAIN_SOURCE_SET_NAME
val resourceRootKind = if (sourceSet.isTestSourceSet) PSourceRoot.Kind.TEST_RESOURCES else PSourceRoot.Kind.RESOURCES
val taskNameBase = "processResources"
val taskName = if (isMainSourceSet) taskNameBase else sourceSet.name + taskNameBase.capitalize()
val task = project.tasks.findByName(taskName) as? ProcessResources ?: return emptyList()
val roots = mutableListOf<File>()
fun collectRoots(spec: CopySpecInternal) {
if (spec is SingleParentCopySpec && spec.children.none()) {
roots += spec.sourcePaths.map { File(project.projectDir, it.toString()) }.filter { it.exists() }
return
}
spec.children.forEach(::collectRoots)
}
collectRoots(task.rootSpec)
return roots.map { PSourceRoot(it, resourceRootKind, null) }
}
private val SourceSet.isTestSourceSet: Boolean
get() = name == SourceSet.TEST_SOURCE_SET_NAME
|| name.endsWith("Test")
|| name.endsWith("Tests")
private fun getKotlinOptions(kotlinCompileTask: Any): PSourceRootKotlinOptions? {
val compileArguments = run {
val method = kotlinCompileTask::class.java.getMethod("getSerializedCompilerArguments")
method.isAccessible = true
method.invoke(kotlinCompileTask) as List<String>
}
fun parseBoolean(name: String) = compileArguments.contains("-$name")
fun parseString(name: String) = compileArguments.dropWhile { it != "-$name" }.drop(1).firstOrNull()
fun isOptionForScriptingCompilerPlugin(option: String)
= option.startsWith("-Xplugin=") && option.contains("kotlin-scripting-compiler")
val extraArguments = compileArguments.filter {
it.startsWith("-X") && !isOptionForScriptingCompilerPlugin(it)
}
return PSourceRootKotlinOptions(
parseBoolean("no-stdlib"),
parseBoolean("no-reflect"),
parseString("module-name"),
parseString("api-version"),
parseString("language-version"),
parseString("jvm-target"),
extraArguments
)
}
private fun Any.invokeInternal(name: String, instance: Any = this): Any? {
val method = javaClass.methods.single { it.name.startsWith(name) && it.parameterTypes.isEmpty() }
val oldIsAccessible = method.isAccessible
try {
method.isAccessible = true
return method.invoke(instance)
} finally {
method.isAccessible = oldIsAccessible
}
}
private fun ParserContext.parseDependencies(project: Project, forTests: Boolean): List<POrderRoot> {
val configurations = project.configurations
val configurationMapping = if (forTests) TEST_CONFIGURATION_MAPPING else CONFIGURATION_MAPPING
val mainRoots = mutableListOf<POrderRoot>()
val deferredRoots = mutableListOf<POrderRoot>()
for ((configurationNames, scope) in configurationMapping) {
for (configurationName in configurationNames) {
val configuration = configurations.findByName(configurationName) ?: continue
val (main, deferred) = project.resolveDependencies(configuration, forTests, dependencyMappers)
mainRoots += main.map { POrderRoot(it, scope) }
deferredRoots += deferred.map { POrderRoot(it, scope) }
}
}
return removeDuplicates(mainRoots + deferredRoots)
}
fun removeDuplicates(roots: List<POrderRoot>): List<POrderRoot> {
val dependenciesByScope = roots.groupBy { it.scope }.mapValues { it.value.mapTo(mutableSetOf()) { it.dependency } }
fun dependenciesFor(scope: Scope) = dependenciesByScope[scope] ?: emptySet<PDependency>()
val result = mutableSetOf<POrderRoot>()
for (root in roots.distinct()) {
val scope = root.scope
val dependency = root.dependency
if (root in result) {
continue
}
if ((scope == Scope.PROVIDED || scope == Scope.RUNTIME) && dependency in dependenciesFor(Scope.COMPILE)) {
continue
}
if (scope == Scope.PROVIDED && dependency in dependenciesFor(Scope.RUNTIME)) {
result += POrderRoot(dependency, Scope.COMPILE)
continue
}
if (scope == Scope.RUNTIME && dependency in dependenciesFor(Scope.PROVIDED)) {
result += POrderRoot(dependency, Scope.COMPILE)
continue
}
result += root
}
return result.toList()
}
val Project.pillModuleName: String
get() = path.removePrefix(":").replace(':', '.')
val Project.sourceSets: SourceSetContainer?
get() {
val convention = project.convention.findPlugin(JavaPluginConvention::class.java) ?: return null
return convention.sourceSets
}

View File

@@ -1,343 +0,0 @@
@file:Suppress("PackageDirectoryMismatch")
package org.jetbrains.kotlin.pill
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.plugins.BasePluginConvention
import org.gradle.kotlin.dsl.extra
import shadow.org.jdom2.input.SAXBuilder
import shadow.org.jdom2.*
import shadow.org.jdom2.output.Format
import shadow.org.jdom2.output.XMLOutputter
import java.io.File
class PillConfigurablePlugin : Plugin<Project> {
override fun apply(project: Project) {
project.configurations.maybeCreate(EmbeddedComponents.CONFIGURATION_NAME)
project.extensions.create("pill", PillExtension::class.java)
}
}
class JpsCompatiblePlugin : Plugin<Project> {
companion object {
private fun getDependencyMappers(projectLibraries: List<PLibrary>): List<DependencyMapper> {
val mappersForKotlinLibrariesExeptStdlib = projectLibraries
.filter { it.name != "kotlin-stdlib" }
.map { DependencyMapper.forProject(it.originalName) { MappedDependency(PDependency.Library(it.name)) } }
val disabledModuleMappers = listOf(
":kotlin-stdlib-common",
":core:builtins",
":kotlin-compiler",
":kotlin-compiler-embeddable",
":kotlin-test:kotlin-test-common",
":kotlin-test:kotlin-test-annotations-common"
).map { DependencyMapper.forProject(it) { null } }
return listOf(
DependencyMapper.forProject(":kotlin-stdlib") {
MappedDependency(
PDependency.Library("kotlin-stdlib"),
listOf(PDependency.Library("annotations-13.0"))
)
},
DependencyMapper.forProject(":kotlin-test:kotlin-test-jvm") { MappedDependency(PDependency.Library("kotlin-test-jvm")) },
DependencyMapper.forProject(":kotlin-reflect-api") { MappedDependency(PDependency.Library("kotlin-reflect")) }
) + mappersForKotlinLibrariesExeptStdlib + disabledModuleMappers
}
fun getProjectLibraries(rootProject: Project): List<PLibrary> {
val distLibDir = File(rootProject.extra["distLibDir"].toString())
fun distJar(name: String) = File(rootProject.projectDir, "dist/kotlinc/lib/$name.jar")
val libraries = rootProject.allprojects
.mapNotNull { library ->
val libraryExtension = library.extensions.findByType(PillExtension::class.java)
?.takeIf { it.importAsLibrary }
?: return@mapNotNull null
val libraryPath = libraryExtension.libraryPath ?: distLibDir
val archivesBaseName = library.convention.findPlugin(BasePluginConvention::class.java)?.archivesBaseName ?: library.name
fun List<File>.filterExisting() = filter { it.exists() }
PLibrary(
library.name,
classes = listOf(File(libraryPath, "$archivesBaseName.jar")).filterExisting(),
sources = listOf(File(libraryPath, "$archivesBaseName-sources.jar")).filterExisting(),
originalName = library.path
)
}
return libraries + PLibrary("annotations-13.0", classes = listOf(distJar("annotations-13.0")))
}
}
override fun apply(project: Project) {
project.plugins.apply(PillConfigurablePlugin::class.java)
// 'jpsTest' does not require the 'tests-jar' artifact
project.configurations.create("jpsTest")
if (project == project.rootProject) {
project.tasks.create("pill") {
doLast { pill(project) }
if (System.getProperty("pill.android.tests", "false") == "true") {
TaskUtils.useAndroidSdk(this)
TaskUtils.useAndroidJar(this)
}
}
project.tasks.create("unpill") {
doLast { unpill(project) }
}
}
}
private lateinit var projectDir: File
private lateinit var platformVersion: String
private lateinit var platformBaseNumber: String
private lateinit var platformDir: File
private lateinit var intellijCoreDir: File
private var isAndroidStudioPlatform: Boolean = false
private fun initEnvironment(project: Project) {
projectDir = project.projectDir
platformVersion = project.extensions.extraProperties.get("versions.intellijSdk").toString()
platformBaseNumber = platformVersion.substringBefore(".", "").takeIf { it.isNotEmpty() }
?: platformVersion.substringBefore("-", "").takeIf { it.isNotEmpty() }
?: error("Invalid platform version: $platformVersion")
platformDir = IntellijRootUtils.getIntellijRootDir(project)
intellijCoreDir = File(platformDir.parentFile.parentFile.parentFile, "intellij-core")
isAndroidStudioPlatform = project.extensions.extraProperties.has("versions.androidStudioRelease")
}
private fun pill(rootProject: Project) {
initEnvironment(rootProject)
val variantOptionValue = System.getProperty("pill.variant", "base").toUpperCase()
val variant = PillExtension.Variant.values().firstOrNull { it.name == variantOptionValue }
?: run {
rootProject.logger.error("Invalid variant name: $variantOptionValue")
return
}
rootProject.logger.lifecycle("Pill: Setting up project for the '${variant.name.toLowerCase()}' variant...")
if (variant == PillExtension.Variant.NONE || variant == PillExtension.Variant.DEFAULT) {
rootProject.logger.error("'none' and 'default' should not be passed as a Pill variant property value")
return
}
val projectLibraries = getProjectLibraries(rootProject)
val dependencyMappers = getDependencyMappers(projectLibraries)
val parserContext = ParserContext(dependencyMappers, variant)
val jpsProject = parse(rootProject, projectLibraries, parserContext)
.mapLibraries(this::attachPlatformSources, this::attachAsmSources)
val files = render(jpsProject)
removeExistingIdeaLibrariesAndModules()
removeJpsAndPillRunConfigurations()
removeAllArtifactConfigurations()
generateKotlinPluginArtifactFile(rootProject, dependencyMappers).write()
copyRunConfigurations()
setOptionsForDefaultJunitRunConfiguration(rootProject)
files.forEach { it.write() }
}
private fun unpill(project: Project) {
initEnvironment(project)
removeExistingIdeaLibrariesAndModules()
removeJpsAndPillRunConfigurations()
removeAllArtifactConfigurations()
}
private fun removeExistingIdeaLibrariesAndModules() {
File(projectDir, ".idea/libraries").deleteRecursively()
File(projectDir, ".idea/modules").deleteRecursively()
}
private fun removeJpsAndPillRunConfigurations() {
File(projectDir, ".idea/runConfigurations")
.walk()
.filter { (it.name.startsWith("JPS_") || it.name.startsWith("Pill_")) && it.extension.toLowerCase() == "xml" }
.forEach { it.delete() }
}
private fun removeAllArtifactConfigurations() {
File(projectDir, ".idea/artifacts")
.walk()
.filter { it.extension.toLowerCase() == "xml" }
.forEach { it.delete() }
}
private fun copyRunConfigurations() {
val runConfigurationsDir = File(projectDir, "buildSrc/src/main/resources/runConfigurations")
val targetDir = File(projectDir, ".idea/runConfigurations")
val platformDirProjectRelative = "\$PROJECT_DIR\$/" + platformDir.toRelativeString(projectDir)
val additionalIdeaArgs = if (isAndroidStudioPlatform) "-Didea.platform.prefix=AndroidStudio" else ""
targetDir.mkdirs()
fun substitute(text: String): String {
return text
.replace("\$IDEA_HOME_PATH\$", platformDirProjectRelative)
.replace("\$ADDITIONAL_IDEA_ARGS\$", additionalIdeaArgs)
}
runConfigurationsDir.listFiles()
.filter { it.extension == "xml" }
.map { it.name to substitute(it.readText()) }
.forEach { File(targetDir, it.first).writeText(it.second) }
}
/*
This sets a proper (project root) working directory and a "idea.home.path" property to the default JUnit configuration,
so one does not need to make these changes manually.
*/
private fun setOptionsForDefaultJunitRunConfiguration(project: Project) {
val workspaceFile = File(projectDir, ".idea/workspace.xml")
if (!workspaceFile.exists()) {
project.logger.warn("${workspaceFile.name} does not exist, JUnit default run configuration was not modified")
return
}
val document = SAXBuilder().build(workspaceFile)
val rootElement = document.rootElement
fun Element.getOrCreateChild(name: String, vararg attributes: Pair<String, String>): Element {
for (child in getChildren(name)) {
if (attributes.all { (attribute, value) -> child.getAttributeValue(attribute) == value }) {
return child
}
}
return Element(name).apply {
for ((attributeName, value) in attributes) {
setAttribute(attributeName, value)
}
this@getOrCreateChild.addContent(this@apply)
}
}
val platformDirProjectRelative = "\$PROJECT_DIR\$/" + platformDir.toRelativeString(projectDir)
val runManagerComponent = rootElement.getOrCreateChild("component", "name" to "RunManager")
val junitConfiguration = runManagerComponent.getOrCreateChild(
"configuration",
"default" to "true",
"type" to "JUnit",
"factoryName" to "JUnit"
)
val kotlinJunitConfiguration = runManagerComponent.getOrCreateChild(
"configuration",
"default" to "true",
"type" to "KotlinJUnit",
"factoryName" to "Kotlin JUnit"
)
fun Element.applyJUnitTemplate() {
getOrCreateChild("option", "name" to "WORKING_DIRECTORY").setAttribute("value", "file://\$PROJECT_DIR\$")
getOrCreateChild("option", "name" to "VM_PARAMETERS").also { vmParams ->
var options = vmParams.getAttributeValue("value", "")
.split(' ')
.map { it.trim() }
.filter { it.isNotEmpty() }
fun addOrReplaceOptionValue(name: String, value: Any?) {
val optionsWithoutNewValue = options.filter { !it.startsWith("-D$name=") }
options = if (value == null) optionsWithoutNewValue else (optionsWithoutNewValue + listOf("-D$name=$value"))
}
if (options.none { it == "-ea" }) {
options += "-ea"
}
addOrReplaceOptionValue("idea.home.path", platformDirProjectRelative)
addOrReplaceOptionValue("ideaSdk.androidPlugin.path", platformDirProjectRelative + "/plugins/android/lib")
addOrReplaceOptionValue("use.jps", "true")
addOrReplaceOptionValue("kotlinVersion", project.rootProject.extra["kotlinVersion"].toString())
val isAndroidStudioBunch = project.findProperty("versions.androidStudioRelease") != null
addOrReplaceOptionValue("idea.platform.prefix", if (isAndroidStudioBunch) "AndroidStudio" else null)
val androidJarPath = project.configurations.findByName("androidJar")?.singleFile
val androidSdkPath = project.configurations.findByName("androidSdk")?.singleFile
if (androidJarPath != null && androidSdkPath != null) {
addOrReplaceOptionValue("android.sdk", "\$PROJECT_DIR\$/" + androidSdkPath.toRelativeString(projectDir))
addOrReplaceOptionValue("android.jar", "\$PROJECT_DIR\$/" + androidJarPath.toRelativeString(projectDir))
}
vmParams.setAttribute("value", options.joinToString(" "))
}
}
junitConfiguration.applyJUnitTemplate()
kotlinJunitConfiguration.applyJUnitTemplate()
val output = XMLOutputter().also {
it.format = Format.getPrettyFormat().apply {
setEscapeStrategy { Verifier.isHighSurrogate(it) || it == '"' }
setIndent(" ")
setTextMode(Format.TextMode.TRIM)
setOmitEncoding(false)
setOmitDeclaration(false)
}
}
val postProcessedXml = output.outputString(document)
.replace("&#x22;", "&quot;")
.replace("&#xA;", "&#10;")
.replace("&#xC;", "&#13;")
workspaceFile.writeText(postProcessedXml)
}
private fun attachPlatformSources(library: PLibrary): PLibrary {
val platformSourcesJar = File(platformDir, "../../../sources/intellij-$platformVersion-sources.jar")
if (library.classes.any { it.startsWith(platformDir) || it.startsWith(intellijCoreDir) }) {
return library.attachSource(platformSourcesJar)
}
return library
}
private fun attachAsmSources(library: PLibrary): PLibrary {
val asmSourcesJar = File(platformDir, "../asm-shaded-sources/asm-src-$platformBaseNumber.jar")
val asmAllJar = File(platformDir, "lib/asm-all.jar")
if (library.classes.any { it == asmAllJar }) {
return library.attachSource(asmSourcesJar)
}
return library
}
private fun PProject.mapLibraries(vararg mappers: (PLibrary) -> PLibrary): PProject {
fun mapLibrary(root: POrderRoot): POrderRoot {
val dependency = root.dependency
if (dependency is PDependency.ModuleLibrary) {
val newLibrary = mappers.fold(dependency.library) { lib, mapper -> mapper(lib) }
return root.copy(dependency = dependency.copy(library = newLibrary))
}
return root
}
val modules = this.modules.map { it.copy(orderRoots = it.orderRoots.map(::mapLibrary)) }
return this.copy(modules = modules)
}
}

View File

@@ -71,6 +71,10 @@ android {
ktest1 {
dimension "box"
}
ktest2 {
dimension "box"
}
}
}
@@ -96,4 +100,5 @@ dependencies {
ktest0Implementation fileTree(dir: 'libs/test', include: ['libtest0.jar'])
ktest1Implementation fileTree(dir: 'libs/test', include: ['libtest1.jar'])
ktest2Implementation fileTree(dir: 'libs/test', include: ['libtest2.jar'])
}

View File

@@ -13,7 +13,10 @@ dependencies {
compile(project(":kotlin-reflect"))
compile(projectTests(":compiler:tests-common"))
compile(commonDep("junit:junit"))
compileOnly(intellijDep()) { includeJars("openapi") }
Platform[193].orLower {
compileOnly(intellijDep()) { includeJars("openapi") }
}
testCompile(project(":compiler:incremental-compilation-impl"))
testCompile(project(":core:descriptors"))
@@ -21,7 +24,11 @@ dependencies {
testCompile(project(":compiler:frontend.java"))
testCompile(projectTests(":jps-plugin"))
testCompile(commonDep("junit:junit"))
testCompile(intellijDep()) { includeJars("openapi", "util", "idea", "idea_rt", "groovy-all", rootProject = rootProject) }
Platform[193].orLower {
testCompile(intellijDep()) { includeJars("openapi", rootProject = rootProject) }
}
testCompile(intellijDep()) { includeJars("util", "idea", "idea_rt", "groovy-all", rootProject = rootProject) }
Platform[191].orLower {
testCompile(intellijDep()) { includeJars("jps-builders") }
}

View File

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

View File

@@ -138,12 +138,12 @@ class CodegenTestsOnAndroidGenerator private constructor(private val pathManager
private fun writeFiles(filesToCompile: List<KtFile>, environment: KotlinCoreEnvironment) {
if (filesToCompile.isEmpty()) return
//3000 files per folder that would be used by flavor to avoid multidex usage,
//2500 files per folder that would be used by flavor to avoid multidex usage,
// each folder would be jared by build.gradle script
writtenFilesCount += filesToCompile.size
val index = writtenFilesCount / 3000
val index = writtenFilesCount / 2500
val outputDir = File(pathManager.getOutputForCompiledFiles(index))
assertTrue("Add flavors for ktest$index", index < 2)
assertTrue("Add flavors for ktest$index", index < 3)
println("Generating ${filesToCompile.size} files into ${outputDir.name}, configuration: '${environment.configuration}'...")

View File

@@ -83,6 +83,9 @@ public class SpecialFiles {
//special symbols in names
excludedFiles.add("nameWithWhitespace.kt");
//some classes are moved from stdlib to compatibility package
excludedFiles.add("suspendFunction_1_2.kt");
}
private SpecialFiles() {

View File

@@ -1081,27 +1081,23 @@ public class AsmUtil {
}
public static void pushDefaultValueOnStack(@NotNull Type type, @NotNull InstructionAdapter v) {
if (type.getSort() == Type.OBJECT || type.getSort() == Type.ARRAY) {
v.aconst(null);
}
else {
pushDefaultPrimitiveValueOnStack(type, v);
}
v.visitInsn(defaultValueOpcode(type));
}
public static void pushDefaultPrimitiveValueOnStack(@NotNull Type type, @NotNull InstructionAdapter v) {
public static int defaultValueOpcode(@NotNull Type type) {
if (type.getSort() == Type.OBJECT || type.getSort() == Type.ARRAY) {
return ACONST_NULL;
}
if (type.getSort() == Type.FLOAT) {
v.fconst(0);
return FCONST_0;
}
else if (type.getSort() == Type.DOUBLE) {
v.dconst(0);
if (type.getSort() == Type.DOUBLE) {
return DCONST_0;
}
else if (type.getSort() == Type.LONG) {
v.lconst(0);
}
else {
v.iconst(0);
if (type.getSort() == Type.LONG) {
return LCONST_0;
}
return ICONST_0;
}
public static boolean isInstancePropertyWithStaticBackingField(@NotNull PropertyDescriptor propertyDescriptor) {

View File

@@ -6,6 +6,8 @@
package org.jetbrains.kotlin.codegen
import org.jetbrains.kotlin.codegen.coroutines.createCustomCopy
import org.jetbrains.kotlin.codegen.optimization.common.InsnSequence
import org.jetbrains.kotlin.codegen.optimization.common.findPreviousOrNull
import org.jetbrains.kotlin.config.JVMAssertionsMode
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.isTopLevelInPackage
@@ -19,12 +21,15 @@ import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo
import org.jetbrains.kotlin.resolve.calls.tasks.TracingStrategy
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.org.objectweb.asm.Label
import org.jetbrains.org.objectweb.asm.MethodVisitor
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
import org.jetbrains.org.objectweb.asm.tree.FieldInsnNode
import org.jetbrains.org.objectweb.asm.tree.LdcInsnNode
import org.jetbrains.org.objectweb.asm.tree.MethodInsnNode
import org.jetbrains.org.objectweb.asm.tree.MethodNode
const val ASSERTIONS_DISABLED_FIELD_NAME = "\$assertionsDisabled"
@@ -130,7 +135,7 @@ private fun inlineAlwaysInlineAssert(resolvedCall: ResolvedCall<*>, codegen: Exp
)
}
fun generateAssertionsDisabledFieldInitialization(classBuilder: ClassBuilder, clInitBuilder: MethodVisitor) {
fun generateAssertionsDisabledFieldInitialization(classBuilder: ClassBuilder, clInitBuilder: MethodVisitor, className: String) {
classBuilder.newField(
JvmDeclarationOrigin.NO_ORIGIN, Opcodes.ACC_STATIC or Opcodes.ACC_FINAL or Opcodes.ACC_SYNTHETIC, ASSERTIONS_DISABLED_FIELD_NAME,
"Z", null, null
@@ -139,7 +144,7 @@ fun generateAssertionsDisabledFieldInitialization(classBuilder: ClassBuilder, cl
val elseLabel = Label()
with(InstructionAdapter(clInitBuilder)) {
mark(Label())
aconst(Type.getObjectType(classBuilder.thisName))
aconst(Type.getObjectType(className))
invokevirtual("java/lang/Class", "desiredAssertionStatus", "()Z", false)
ifne(thenLabel)
iconst(1)
@@ -153,6 +158,16 @@ fun generateAssertionsDisabledFieldInitialization(classBuilder: ClassBuilder, cl
}
}
fun rewriteAssertionsDisabledFieldInitialization(methodNode: MethodNode, className: String) {
InsnSequence(methodNode.instructions).firstOrNull {
it is FieldInsnNode && it.opcode == Opcodes.PUTSTATIC && it.name == ASSERTIONS_DISABLED_FIELD_NAME
}?.findPreviousOrNull {
it is MethodInsnNode && it.opcode == Opcodes.INVOKEVIRTUAL
&& it.owner == "java/lang/Class" && it.name == "desiredAssertionStatus" && it.desc == "()Z"
}?.previous?.safeAs<LdcInsnNode>()?.cst =
Type.getObjectType(className)
}
private fun <D : FunctionDescriptor> ResolvedCall<D>.replaceAssertWithAssertInner(): ResolvedCall<D> {
val newCandidateDescriptor = resultingDescriptor.createCustomCopy {
setName(Name.identifier(ALWAYS_ENABLED_ASSERT_FUNCTION_NAME))

View File

@@ -47,7 +47,7 @@ interface BaseExpressionCodegen {
functionReferenceReceiver: StackValue?
)
fun markLineNumberAfterInlineIfNeeded()
fun markLineNumberAfterInlineIfNeeded(registerLineNumberAfterwards: Boolean)
fun consumeReifiedOperationMarker(typeParameter: TypeParameterMarker)

View File

@@ -677,6 +677,10 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
generator.checkEmptyLoop(loopExit);
v.mark(loopEntry);
resetLastLineNumber();
markStartLineNumber(generator.getForExpression());
v.nop();
generator.checkPreCondition(loopExit);
// Some forms of for-loop can be optimized as post-condition loops.
@@ -1495,10 +1499,9 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
v.visitLineNumber(lineNumber, label);
}
//we should generate additional linenumber info after inline call only if it used as argument
@Override
public void markLineNumberAfterInlineIfNeeded() {
if (!shouldMarkLineNumbers) {
public void markLineNumberAfterInlineIfNeeded(boolean registerLineNumberAfterwards) {
if (!shouldMarkLineNumbers || registerLineNumberAfterwards) {
//if it used as general argument
if (myLastLineNumber > -1) {
Label label = new Label();
@@ -1506,11 +1509,14 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
v.visitLineNumber(myLastLineNumber, label);
}
} else {
//if it used as argument of infix call (in this case lineNumber for simple inlineCall also would be reset)
myLastLineNumber = -1;
resetLastLineNumber();
}
}
private void resetLastLineNumber() {
myLastLineNumber = -1;
}
@Override
public int getLastLineNumber() {
return myLastLineNumber;

View File

@@ -44,6 +44,7 @@ import org.jetbrains.kotlin.resolve.constants.ArrayValue;
import org.jetbrains.kotlin.resolve.constants.ConstantValue;
import org.jetbrains.kotlin.resolve.constants.KClassValue;
import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt;
import org.jetbrains.kotlin.resolve.inline.InlineOnlyKt;
import org.jetbrains.kotlin.resolve.inline.InlineUtil;
import org.jetbrains.kotlin.resolve.jvm.AsmTypes;
import org.jetbrains.kotlin.resolve.jvm.RuntimeAssertionInfo;
@@ -76,6 +77,7 @@ import static org.jetbrains.kotlin.codegen.state.KotlinTypeMapper.isAccessor;
import static org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.DECLARATION;
import static org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.DELEGATION;
import static org.jetbrains.kotlin.descriptors.ModalityKt.isOverridable;
import static org.jetbrains.kotlin.load.java.JvmAbi.LOCAL_VARIABLE_INLINE_ARGUMENT_SYNTHETIC_LINE_NUMBER;
import static org.jetbrains.kotlin.resolve.DescriptorToSourceUtils.getSourceFromDescriptor;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.*;
import static org.jetbrains.kotlin.resolve.inline.InlineOnlyKt.isEffectivelyInlineOnly;
@@ -636,11 +638,19 @@ public class FunctionCodegen {
frameMap.enter(continuationValueDescriptor, typeMapper.mapType(continuationValueDescriptor));
}
if (context.isInlineMethodContext()) {
functionFakeIndex = newFakeTempIndex(mv, frameMap);
functionFakeIndex = newFakeTempIndex(mv, frameMap, -1);
}
if (context instanceof InlineLambdaContext) {
lambdaFakeIndex = newFakeTempIndex(mv, frameMap);
int lineNumber = -1;
if (strategy instanceof ClosureGenerationStrategy) {
KtDeclarationWithBody declaration = ((ClosureGenerationStrategy) strategy).getDeclaration();
BindingContext bindingContext = typeMapper.getBindingContext();
if (declaration instanceof KtFunctionLiteral && isLambdaPassedToInlineOnly((KtFunction) declaration, bindingContext)) {
lineNumber = LOCAL_VARIABLE_INLINE_ARGUMENT_SYNTHETIC_LINE_NUMBER;
}
}
lambdaFakeIndex = newFakeTempIndex(mv, frameMap, lineNumber);
}
methodEntry = new Label();
@@ -704,8 +714,27 @@ public class FunctionCodegen {
}
}
private static int newFakeTempIndex(@NotNull MethodVisitor mv, FrameMap frameMap) {
private static boolean isLambdaPassedToInlineOnly(KtFunction lambda, BindingContext bindingContext) {
ValueParameterDescriptor parameterDescriptor = InlineUtil.getInlineArgumentDescriptor(lambda, bindingContext);
if (parameterDescriptor == null) {
return false;
}
CallableDescriptor containingCallable = parameterDescriptor.getContainingDeclaration();
if (containingCallable instanceof FunctionDescriptor) {
return InlineOnlyKt.isInlineOnly((MemberDescriptor) containingCallable);
}
return false;
}
private static int newFakeTempIndex(@NotNull MethodVisitor mv, @NotNull FrameMap frameMap, int lineNumber) {
int fakeIndex = frameMap.enterTemp(Type.INT_TYPE);
if (lineNumber >= 0) {
Label label = new Label();
mv.visitLabel(label);
mv.visitLineNumber(lineNumber, label);
}
mv.visitLdcInsn(0);
mv.visitVarInsn(ISTORE, fakeIndex);
return fakeIndex;

View File

@@ -965,7 +965,7 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
public void generateAssertField() {
if (jvmAssertFieldGenerated) return;
AssertCodegenUtilKt.generateAssertionsDisabledFieldInitialization(v, createOrGetClInitCodegen().v);
AssertCodegenUtilKt.generateAssertionsDisabledFieldInitialization(v, createOrGetClInitCodegen().v, v.getThisName());
jvmAssertFieldGenerated = true;
}

View File

@@ -15,6 +15,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.builtins.PrimitiveType;
import org.jetbrains.kotlin.builtins.UnsignedTypes;
import org.jetbrains.kotlin.codegen.binding.CodegenBinding;
import org.jetbrains.kotlin.codegen.coroutines.CoroutineCodegenUtilKt;
import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicMethods;
@@ -635,11 +636,8 @@ public abstract class StackValue {
if (toType.equals(UNIT_TYPE) || toType.equals(OBJECT_TYPE)) {
putUnitInstance(v);
}
else if (toType.getSort() == Type.OBJECT || toType.getSort() == Type.ARRAY) {
v.aconst(null);
}
else {
pushDefaultPrimitiveValueOnStack(toType, v);
pushDefaultValueOnStack(toType, v);
}
}
else if (toType.equals(UNIT_TYPE)) {
@@ -794,8 +792,11 @@ public abstract class StackValue {
ResolvedCall resolvedCall,
@NotNull ExpressionCodegen codegen
) {
if (stackValue instanceof StackValue.Local && Type.INT_TYPE == stackValue.type) {
return preIncrementForLocalVar(((StackValue.Local) stackValue).index, delta, stackValue.kotlinType);
KotlinType kotlinType = stackValue.kotlinType;
if (stackValue instanceof StackValue.Local && Type.INT_TYPE == stackValue.type &&
kotlinType != null && KotlinBuiltIns.isPrimitiveType(kotlinType)
) {
return preIncrementForLocalVar(((StackValue.Local) stackValue).index, delta, kotlinType);
}
return new PrefixIncrement(type, stackValue, resolvedCall, codegen);
}

View File

@@ -461,10 +461,18 @@ fun getCallLabelForLambdaArgument(declaration: KtFunctionLiteral, bindingContext
lambdaExpressionParent.name?.let { return it }
}
val lambdaArgument = lambdaExpression.parent as? KtLambdaArgument ?: return null
val callExpression = lambdaArgument.parent as? KtCallExpression ?: return null
val call = callExpression.getResolvedCall(bindingContext) ?: return null
val callExpression = when (val argument = lambdaExpression.parent) {
is KtLambdaArgument -> {
argument.parent as? KtCallExpression ?: return null
}
is KtValueArgument -> {
val valueArgumentList = argument.parent as? KtValueArgumentList ?: return null
valueArgumentList.parent as? KtCallExpression ?: return null
}
else -> return null
}
val call = callExpression.getResolvedCall(bindingContext) ?: return null
return call.resultingDescriptor.name.asString()
}

View File

@@ -307,10 +307,29 @@ class CoroutineCodegenForLambda private constructor(
val createArgumentTypes =
if (generateErasedCreate || doNotGenerateInvokeBridge) typeMapper.mapAsmMethod(createCoroutineDescriptor).argumentTypes.asList()
else parameterTypes
var index = 0
parameterTypes.withVariableIndices().forEach { (varIndex, type) ->
load(varIndex + 1, type)
StackValue.coerce(type, createArgumentTypes[index++], this)
// invoke is not big arity, but create is. Pass an array to create.
if (parameterTypes.size == 22 && createArgumentTypes.size == 1) {
iconst(22)
newarray(AsmTypes.OBJECT_TYPE)
// 0 - this
// 1..22 - parameters
// 23 - first empy slot
val arraySlot = 23
store(arraySlot, AsmTypes.OBJECT_TYPE)
for ((varIndex, type) in parameterTypes.withVariableIndices()) {
load(arraySlot, AsmTypes.OBJECT_TYPE)
iconst(varIndex)
load(varIndex + 1, type)
StackValue.coerce(type, AsmTypes.OBJECT_TYPE, this)
astore(AsmTypes.OBJECT_TYPE)
}
load(arraySlot, AsmTypes.OBJECT_TYPE)
} else {
var index = 0
parameterTypes.withVariableIndices().forEach { (varIndex, type) ->
load(varIndex + 1, type)
StackValue.coerce(type, createArgumentTypes[index++], this)
}
}
// this.create(..)

View File

@@ -8,7 +8,6 @@ package org.jetbrains.kotlin.codegen.inline
import com.intellij.util.ArrayUtil
import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.coroutines.DEBUG_METADATA_ANNOTATION_ASM_TYPE
import org.jetbrains.kotlin.codegen.coroutines.isCapturedSuspendLambda
import org.jetbrains.kotlin.codegen.coroutines.isCoroutineSuperClass
import org.jetbrains.kotlin.codegen.coroutines.isResumeImplMethodName
import org.jetbrains.kotlin.codegen.inline.coroutines.CoroutineTransformer
@@ -154,6 +153,11 @@ class AnonymousObjectTransformer(
coroutineTransformer.shouldGenerateStateMachine(next) -> coroutineTransformer.newMethod(next)
else -> newMethod(classBuilder, next)
}
if (next.name == "<clinit>") {
rewriteAssertionsDisabledFieldInitialization(next, inliningContext.root.callSiteInfo.ownerClassName)
}
val funResult = inlineMethodAndUpdateGlobalResult(parentRemapper, deferringVisitor, next, allCapturedParamBuilder, false)
val returnType = Type.getReturnType(next.desc)
@@ -195,7 +199,7 @@ class AnonymousObjectTransformer(
if (inliningContext.generateAssertField && fieldNames.none { it.key == ASSERTIONS_DISABLED_FIELD_NAME }) {
val clInitBuilder = classBuilder.newMethod(NO_ORIGIN, Opcodes.ACC_STATIC, "<clinit>", "()V", null, null)
generateAssertionsDisabledFieldInitialization(classBuilder, clInitBuilder)
generateAssertionsDisabledFieldInitialization(classBuilder, clInitBuilder, inliningContext.root.callSiteInfo.ownerClassName)
clInitBuilder.visitInsn(Opcodes.RETURN)
clInitBuilder.visitEnd()
}
@@ -521,10 +525,8 @@ class AnonymousObjectTransformer(
alreadyAddedParam?.newFieldName ?: getNewFieldName(desc.fieldName, false),
alreadyAddedParam != null
)
if (info is PsiExpressionLambda && info.closure.captureVariables.any { it.value.fieldName == desc.fieldName }) {
recapturedParamInfo.functionalArgument = NonInlineableArgumentForInlineableParameterCalledInSuspend(
isCapturedSuspendLambda(info.closure, desc.fieldName, inliningContext.state.bindingContext)
)
if (info is ExpressionLambda && info.isCapturedSuspend(desc, inliningContext)) {
recapturedParamInfo.functionalArgument = NonInlineableArgumentForInlineableParameterCalledInSuspend
}
val composed = StackValue.field(
desc.type,

View File

@@ -118,28 +118,29 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
AsmUtil.genThrow(codegen.v, "java/lang/UnsupportedOperationException", message)
}
protected fun endCall(result: InlineResult) {
protected fun endCall(result: InlineResult, registerLineNumberAfterwards: Boolean) {
leaveTemps()
codegen.propagateChildReifiedTypeParametersUsages(result.reifiedTypeParametersUsages)
state.factory.removeClasses(result.calcClassesToRemove())
codegen.markLineNumberAfterInlineIfNeeded()
codegen.markLineNumberAfterInlineIfNeeded(registerLineNumberAfterwards)
}
fun performInline(
typeArguments: List<TypeParameterMarker>?,
inlineDefaultLambdas: Boolean,
mapDefaultSignature: Boolean,
typeSystem: TypeSystemCommonBackendContext
typeSystem: TypeSystemCommonBackendContext,
registerLineNumberAfterwards: Boolean
) {
var nodeAndSmap: SMAPAndMethodNode? = null
try {
nodeAndSmap = createInlineMethodNode(
functionDescriptor, methodOwner, jvmSignature, mapDefaultSignature, typeArguments, typeSystem, state, sourceCompiler
)
endCall(inlineCall(nodeAndSmap, inlineDefaultLambdas))
endCall(inlineCall(nodeAndSmap, inlineDefaultLambdas), registerLineNumberAfterwards)
} catch (e: CompilationException) {
throw e
} catch (e: InlineException) {
@@ -149,12 +150,7 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
}
}
@Suppress("UNREACHABLE_CODE")
private fun canSkipStackSpillingOnInline(methodNode: MethodNode): Boolean {
// TODO: Temporary disable this optimization until
// https://issuetracker.google.com/issues/68796377 is fixed
// or until d8 substitute dex
return false
// Stack spilling before inline function 'f' call is required if:
// - 'f' is a suspend function
// - 'f' has try-catch blocks
@@ -395,7 +391,7 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
info = invocationParamBuilder.addNextValueParameter(jvmType, false, remappedValue, parameterIndex)
info.functionalArgument = when (kind) {
ValueKind.NON_INLINEABLE_ARGUMENT_FOR_INLINE_PARAMETER_CALLED_IN_SUSPEND ->
NonInlineableArgumentForInlineableParameterCalledInSuspend(kotlinType?.isSuspendFunctionTypeOrSubtype == true)
NonInlineableArgumentForInlineableParameterCalledInSuspend
ValueKind.NON_INLINEABLE_ARGUMENT_FOR_INLINE_SUSPEND_PARAMETER -> NonInlineableArgumentForInlineableSuspendParameter
else -> null
}

View File

@@ -14,6 +14,7 @@ import org.jetbrains.kotlin.codegen.binding.CodegenBinding.*
import org.jetbrains.kotlin.codegen.binding.MutableClosure
import org.jetbrains.kotlin.codegen.context.EnclosedValueDescriptor
import org.jetbrains.kotlin.codegen.coroutines.getOrCreateJvmSuspendFunctionView
import org.jetbrains.kotlin.codegen.coroutines.isCapturedSuspendLambda
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.config.isReleaseCoroutines
@@ -82,7 +83,7 @@ abstract class LambdaInfo(@JvmField val isCrossInline: Boolean) : FunctionalArgu
}
}
class NonInlineableArgumentForInlineableParameterCalledInSuspend(val isSuspend: Boolean) : FunctionalArgument
object NonInlineableArgumentForInlineableParameterCalledInSuspend : FunctionalArgument
object NonInlineableArgumentForInlineableSuspendParameter : FunctionalArgument
@@ -215,6 +216,7 @@ abstract class ExpressionLambda(isCrossInline: Boolean) : LambdaInfo(isCrossInli
}
abstract fun getInlineSuspendLambdaViewDescriptor(): FunctionDescriptor
abstract fun isCapturedSuspend(desc: CapturedParamDesc, inliningContext: InliningContext): Boolean
}
class PsiExpressionLambda(
@@ -328,4 +330,7 @@ class PsiExpressionLambda(
typeMapper.bindingContext
)
}
override fun isCapturedSuspend(desc: CapturedParamDesc, inliningContext: InliningContext): Boolean =
isCapturedSuspendLambda(closure, desc.fieldName, inliningContext.state.bindingContext)
}

View File

@@ -14,7 +14,10 @@ import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.psi.KtCallableReferenceExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtIfExpression
import org.jetbrains.kotlin.psi.KtPsiUtil
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCallWithAssert
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.inline.InlineUtil
@@ -66,12 +69,19 @@ class PsiInlineCodegen(
return
}
try {
performInline(resolvedCall?.typeArguments?.keys?.toList(), callDefault, callDefault, codegen.typeSystem)
val registerLineNumber = registerLineNumberAfterwards(resolvedCall)
performInline(resolvedCall?.typeArguments?.keys?.toList(), callDefault, callDefault, codegen.typeSystem, registerLineNumber)
} finally {
state.globalInlineContext.exitFromInliningOf(inlineCall)
}
}
private fun registerLineNumberAfterwards(resolvedCall: ResolvedCall<*>?): Boolean {
val callElement = resolvedCall?.call?.callElement ?: return false
val parentIfCondition = callElement.getParentOfType<KtIfExpression>(true)?.condition ?: return false
return parentIfCondition.isAncestor(callElement, false)
}
override fun processAndPutHiddenParameters(justProcess: Boolean) {
if (getMethodAsmFlags(functionDescriptor, sourceCompiler.contextKind, state) and Opcodes.ACC_STATIC == 0) {
invocationParamBuilder.addNextParameter(methodOwner, false, actualDispatchReceiver)
@@ -146,7 +156,8 @@ class PsiInlineCodegen(
} else {
val value = codegen.gen(argumentExpression)
val kind = when {
isCallSiteIsSuspend(valueParameterDescriptor) -> ValueKind.NON_INLINEABLE_ARGUMENT_FOR_INLINE_PARAMETER_CALLED_IN_SUSPEND
isCallSiteIsSuspend(valueParameterDescriptor) && parameterType.kotlinType?.isSuspendFunctionTypeOrSubtype == true ->
ValueKind.NON_INLINEABLE_ARGUMENT_FOR_INLINE_PARAMETER_CALLED_IN_SUSPEND
isInlineSuspendParameter(valueParameterDescriptor) -> ValueKind.NON_INLINEABLE_ARGUMENT_FOR_INLINE_SUSPEND_PARAMETER
else -> ValueKind.GENERAL
}

View File

@@ -12,6 +12,7 @@ import org.jetbrains.kotlin.codegen.inline.SMAP.Companion.END
import org.jetbrains.kotlin.codegen.inline.SMAP.Companion.FILE_SECTION
import org.jetbrains.kotlin.codegen.inline.SMAP.Companion.LINE_SECTION
import org.jetbrains.kotlin.codegen.inline.SMAP.Companion.STRATA_SECTION
import org.jetbrains.kotlin.load.java.JvmAbi
import java.util.*
import kotlin.math.max
@@ -92,6 +93,10 @@ open class NestedSourceMapper(
private var lastVisitedRange: RangeMapping? = null
override fun mapLineNumber(lineNumber: Int): Int {
if (lineNumber in JvmAbi.SYNTHETIC_MARKER_LINE_NUMBERS) {
return lineNumber
}
val mappedLineNumber = visitedLines.get(lineNumber)
return if (mappedLineNumber > 0) {

View File

@@ -17,6 +17,7 @@
package org.jetbrains.kotlin.codegen.inline
import org.jetbrains.kotlin.codegen.optimization.common.InsnSequence
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.org.objectweb.asm.tree.LineNumberNode
import org.jetbrains.org.objectweb.asm.tree.MethodNode
import java.util.*
@@ -30,7 +31,13 @@ class SMAPAndMethodNode(val node: MethodNode, val classSMAP: SMAP) {
private fun createLineNumberSequence(node: MethodNode, classSMAP: SMAP): Sequence<RangeMapping> {
return InsnSequence(node.instructions.first, null).filterIsInstance<LineNumberNode>().map { lineNumber ->
val index = classSMAP.intervals.binarySearch(RangeMapping(lineNumber.line, lineNumber.line, 1), Comparator { value, key ->
val mapping = RangeMapping(lineNumber.line, lineNumber.line, 1)
if (lineNumber.line in JvmAbi.SYNTHETIC_MARKER_LINE_NUMBERS) {
return@map mapping
}
val index = classSMAP.intervals.binarySearch(mapping, Comparator { value, key ->
if (key.dest in value) 0 else RangeMapping.Comparator.compare(value, key)
})
if (index < 0) {

View File

@@ -6,7 +6,6 @@
package org.jetbrains.kotlin.codegen.inline.coroutines
import com.intellij.util.ArrayUtil
import org.jetbrains.kotlin.backend.common.CodegenUtil
import org.jetbrains.kotlin.codegen.AsmUtil.CAPTURED_THIS_FIELD
import org.jetbrains.kotlin.codegen.ClassBuilder
import org.jetbrains.kotlin.codegen.TransformationMethodVisitor
@@ -19,18 +18,7 @@ import org.jetbrains.kotlin.codegen.optimization.fixStack.FixStackMethodTransfor
import org.jetbrains.kotlin.config.isReleaseCoroutines
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.load.java.JvmAnnotationNames
import org.jetbrains.kotlin.load.kotlin.FileBasedKotlinClass
import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader
import org.jetbrains.kotlin.load.kotlin.header.ReadKotlinClassHeaderAnnotationVisitor
import org.jetbrains.kotlin.metadata.ProtoBuf
import org.jetbrains.kotlin.metadata.deserialization.*
import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmProtoBufUtil
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import org.jetbrains.kotlin.serialization.deserialization.getClassId
import org.jetbrains.kotlin.serialization.deserialization.getName
import org.jetbrains.kotlin.utils.addToStdlib.cast
import org.jetbrains.org.objectweb.asm.*
import org.jetbrains.org.objectweb.asm.tree.*
@@ -291,8 +279,7 @@ class SurroundSuspendLambdaCallsWithSuspendMarkersMethodVisitor(
}
private fun FunctionalArgument.isSuspendLambda(): Boolean =
(this is NonInlineableArgumentForInlineableParameterCalledInSuspend && isSuspend) ||
(this is PsiExpressionLambda && isSuspend)
this is NonInlineableArgumentForInlineableParameterCalledInSuspend || (this is ExpressionLambda && isSuspend)
fun surroundInvokesWithSuspendMarkers(
methodNode: MethodNode,

View File

@@ -17,6 +17,7 @@
package org.jetbrains.kotlin.codegen.optimization
import org.jetbrains.kotlin.builtins.PrimitiveType
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.codegen.optimization.common.*
import org.jetbrains.kotlin.codegen.optimization.fixStack.peek
import org.jetbrains.kotlin.codegen.optimization.fixStack.top
@@ -207,13 +208,6 @@ class CapturedVarsOptimizationMethodTransformer : MethodTransformer() {
refValue.localVarIndex = localVar.index
}
val startIndex = localVar.start.getIndex()
val initFieldInsns = refValue.putFieldInsns.filter { it.getIndex() < startIndex }
if (initFieldInsns.size != 1) {
refValue.hazard = true
continue
}
val cleanInstructions = findCleanInstructions(refValue, oldVarIndex, methodNode.instructions)
if (cleanInstructions.size > 1) {
refValue.hazard = true
@@ -227,14 +221,14 @@ class CapturedVarsOptimizationMethodTransformer : MethodTransformer() {
return InsnSequence(instructions).filterIsInstance<VarInsnNode>().filter {
it.opcode == Opcodes.ASTORE && it.`var` == oldVarIndex
}.filter {
it.previous?.opcode == Opcodes.ACONST_NULL
}.filter {
val operationIndex = instructions.indexOf(it)
val localVariableNode = refValue.localVar!!
instructions.indexOf(localVariableNode.start) < operationIndex && operationIndex < instructions.indexOf(
localVariableNode.end
)
}.toList()
it.previous?.opcode == Opcodes.ACONST_NULL
}.filter {
val operationIndex = instructions.indexOf(it)
val localVariableNode = refValue.localVar!!
instructions.indexOf(localVariableNode.start) < operationIndex && operationIndex < instructions.indexOf(
localVariableNode.end
)
}.toList()
}
private fun rewrite() {
@@ -250,9 +244,17 @@ class CapturedVarsOptimizationMethodTransformer : MethodTransformer() {
private fun rewriteRefValue(capturedVar: CapturedVarDescriptor) {
methodNode.instructions.run {
capturedVar.localVar!!.let {
it.signature = null
it.desc = capturedVar.valueType.descriptor
val localVar = capturedVar.localVar!!
localVar.signature = null
localVar.desc = capturedVar.valueType.descriptor
val loadOpcode = capturedVar.valueType.getOpcode(Opcodes.ILOAD)
val storeOpcode = capturedVar.valueType.getOpcode(Opcodes.ISTORE)
if (capturedVar.putFieldInsns.none { it.getIndex() < localVar.start.getIndex() }) {
// variable needs to be initialized before its live range can begin
insertBefore(capturedVar.newInsn, InsnNode(AsmUtil.defaultValueOpcode(capturedVar.valueType)))
insertBefore(capturedVar.newInsn, VarInsnNode(storeOpcode, capturedVar.localVarIndex))
}
remove(capturedVar.newInsn)
@@ -260,14 +262,8 @@ class CapturedVarsOptimizationMethodTransformer : MethodTransformer() {
capturedVar.stackInsns.forEach { remove(it) }
capturedVar.aloadInsns.forEach { remove(it) }
capturedVar.astoreInsns.forEach { remove(it) }
capturedVar.getFieldInsns.forEach {
set(it, VarInsnNode(capturedVar.valueType.getOpcode(Opcodes.ILOAD), capturedVar.localVarIndex))
}
capturedVar.putFieldInsns.forEach {
set(it, VarInsnNode(capturedVar.valueType.getOpcode(Opcodes.ISTORE), capturedVar.localVarIndex))
}
capturedVar.getFieldInsns.forEach { set(it, VarInsnNode(loadOpcode, capturedVar.localVarIndex)) }
capturedVar.putFieldInsns.forEach { set(it, VarInsnNode(storeOpcode, capturedVar.localVarIndex)) }
//after visiting block codegen tries to delete all allocated references:
// see ExpressionCodegen.addLeaveTaskToRemoveLocalVariableFromFrameMap

View File

@@ -103,16 +103,16 @@ class RedundantNopsCleanupMethodTransformer : MethodTransformer() {
internal fun getRequiredNopInRange(firstInclusive: AbstractInsnNode, lastExclusive: AbstractInsnNode?): AbstractInsnNode? {
var lastNop: AbstractInsnNode? = null
var firstNop: AbstractInsnNode? = null
var current: AbstractInsnNode? = firstInclusive
while (current != null && current != lastExclusive) {
if (current.isMeaningful && current.opcode != Opcodes.NOP) {
return null
} else if (current.opcode == Opcodes.NOP) {
lastNop = current
} else if (current.opcode == Opcodes.NOP && firstNop == null) {
firstNop = current
}
current = current.next
}
return lastNop
return firstNop
}

View File

@@ -185,7 +185,7 @@ class GenerationState private constructor(
val diagnostics: DiagnosticSink get() = extraJvmDiagnosticsTrace
val collectedExtraJvmDiagnostics: Diagnostics = LazyJvmDiagnostics {
duplicateSignatureFactory.reportDiagnostics()
duplicateSignatureFactory?.reportDiagnostics()
extraJvmDiagnosticsTrace.bindingContext.diagnostics
}
@@ -221,7 +221,7 @@ class GenerationState private constructor(
val mappingsClassesForWhenByEnum: MappingsClassesForWhenByEnum = MappingsClassesForWhenByEnum(this)
val jvmRuntimeTypes: JvmRuntimeTypes = JvmRuntimeTypes(module, configuration.languageVersionSettings)
val factory: ClassFileFactory
private lateinit var duplicateSignatureFactory: BuilderFactoryForDuplicateSignatureDiagnostics
private var duplicateSignatureFactory: BuilderFactoryForDuplicateSignatureDiagnostics? = null
val scriptSpecific = ForScript()
@@ -284,11 +284,16 @@ class GenerationState private constructor(
it
},
{
BuilderFactoryForDuplicateSignatureDiagnostics(
it, this.bindingContext, diagnostics, this.moduleName, this.languageVersionSettings,
shouldGenerate = { !shouldOnlyCollectSignatures(it) },
mapAsmMethod = if (isIrBackend) { descriptor: FunctionDescriptor -> irBasedMapAsmMethod(descriptor) } else null
).apply { duplicateSignatureFactory = this }
// In IR backend, we have more precise information about classes and methods we are going to generate,
// and report signature conflict errors in JvmSignatureClashTracker.
if (isIrBackend)
it
else
BuilderFactoryForDuplicateSignatureDiagnostics(
it, this.bindingContext, diagnostics, this.moduleName, this.languageVersionSettings,
shouldGenerate = { origin -> !shouldOnlyCollectSignatures(origin) },
mapAsmMethod = if (isIrBackend) { descriptor: FunctionDescriptor -> irBasedMapAsmMethod(descriptor) } else null
).apply { duplicateSignatureFactory = this }
},
{ BuilderFactoryForDuplicateClassNameDiagnostics(it, diagnostics) },
{

View File

@@ -67,7 +67,10 @@ dependencies {
testCompileOnly(project(it))
}
testCompileOnly(intellijCoreDep()) { includeJars("intellij-core") }
testCompileOnly(intellijDep()) { includeJars("openapi", "idea", "idea_rt", "util", "asm-all", rootProject = rootProject) }
Platform[193].orLower {
testCompileOnly(intellijDep()) { includeJars("openapi", rootProject = rootProject) }
}
testCompileOnly(intellijDep()) { includeJars("idea", "idea_rt", "util", "asm-all", rootProject = rootProject) }
Platform[192].orHigher {
testRuntimeOnly(intellijPluginDep("java"))

View File

@@ -31,7 +31,7 @@ if not "%_KOTLIN_RUNNER%"=="" (
"%_JAVACMD%" %JAVA_OPTS% "-Dkotlin.home=%_KOTLIN_HOME%" -cp "%_KOTLIN_HOME%\lib\kotlin-runner.jar" ^
org.jetbrains.kotlin.runner.Main %*
) else (
SET _ADDITIONAL_CLASSPATH=""
SET _ADDITIONAL_CLASSPATH=
if not "%_KOTLIN_TOOL%"=="" (
set _ADDITIONAL_CLASSPATH=;%_KOTLIN_HOME%\lib\%_KOTLIN_TOOL%

View File

@@ -30,7 +30,7 @@ dependencies {
compile(project(":kotlin-util-io"))
compile(project(":compiler:ir.serialization.common"))
compile(toolsJar())
compileOnly(toolsJar())
compileOnly(intellijCoreDep()) { includeJars("intellij-core") }
compileOnly(intellijDep()) { includeIntellijCoreJarDependencies(project) }

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

@@ -360,8 +360,9 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
|| languageVersionSettings.apiVersion < ApiVersion.KOTLIN_1_3
) {
collector.report(
CompilerMessageSeverity.ERROR,
"IR backend cannot be used with language or API version below 1.3"
CompilerMessageSeverity.STRONG_WARNING,
"IR backend does not support language or API version lower than 1.3. " +
"This can lead to unexpected behavior or compilation failures"
)
}
}

View File

@@ -7,7 +7,10 @@ dependencies {
compile(project(":compiler:cli"))
compile(project(":compiler:ir.serialization.js"))
runtime(project(":kotlin-reflect"))
compile(intellijDep()) { includeJars("picocontainer", "trove4j", "guava", "jdom", rootProject = rootProject) }
if (Platform[193].orLower()) {
compile(intellijDep()) { includeJars("picocontainer", rootProject = rootProject) }
}
compile(intellijDep()) { includeJars("trove4j", "guava", "jdom", rootProject = rootProject) }
compile(intellijCoreDep()) { includeJars("intellij-core") }
}

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

@@ -30,15 +30,14 @@ import com.intellij.openapi.fileTypes.PlainTextFileType;
import com.intellij.openapi.fileTypes.PlainTextLanguage;
import com.intellij.openapi.fileTypes.PlainTextParserDefinition;
import com.intellij.openapi.projectRoots.JavaVersionService;
import com.intellij.openapi.util.KeyWithDefaultValue;
import com.intellij.openapi.vfs.VirtualFileSystem;
import com.intellij.psi.*;
import com.intellij.psi.augment.PsiAugmentProvider;
import com.intellij.psi.augment.TypeAnnotationModifier;
import com.intellij.psi.compiled.ClassFileDecompilers;
import com.intellij.psi.impl.PsiSubstitutorFactoryImpl;
import com.intellij.psi.impl.LanguageConstantExpressionEvaluator;
import com.intellij.psi.impl.PsiExpressionEvaluator;
import com.intellij.psi.impl.PsiSubstitutorFactoryImpl;
import com.intellij.psi.impl.compiled.ClassFileStubBuilder;
import com.intellij.psi.impl.file.PsiPackageImplementationHelper;
import com.intellij.psi.impl.search.MethodSuperSearcher;
@@ -53,9 +52,6 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.cli.jvm.modules.CoreJrtFileSystem;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
/**
* adapted from com.intellij.core.JavaCoreApplicationEnvironment
* TODO: initiate removal original from com.intellij.core since it seems that there are no usages left

View File

@@ -0,0 +1,55 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.cli.jvm.compiler;
import com.intellij.DynamicBundle;
import com.intellij.codeInsight.ContainerProvider;
import com.intellij.codeInsight.runner.JavaMainMethodProvider;
import com.intellij.core.JavaCoreApplicationEnvironment;
import com.intellij.lang.MetaLanguage;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.vfs.VirtualFileSystem;
import com.intellij.psi.FileContextProvider;
import com.intellij.psi.augment.PsiAugmentProvider;
import com.intellij.psi.compiled.ClassFileDecompilers;
import com.intellij.psi.meta.MetaDataContributor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.cli.jvm.modules.CoreJrtFileSystem;
public class KotlinCoreApplicationEnvironment extends JavaCoreApplicationEnvironment {
public static KotlinCoreApplicationEnvironment create(@NotNull Disposable parentDisposable, boolean unitTestMode) {
KotlinCoreApplicationEnvironment environment = new KotlinCoreApplicationEnvironment(parentDisposable, unitTestMode);
registerExtensionPoints();
return environment;
}
private KotlinCoreApplicationEnvironment(@NotNull Disposable parentDisposable, boolean unitTestMode) {
super(parentDisposable, unitTestMode);
}
private static void registerExtensionPoints() {
registerApplicationExtensionPoint(DynamicBundle.LanguageBundleEP.EP_NAME, DynamicBundle.LanguageBundleEP.class);
registerApplicationExtensionPoint(FileContextProvider.EP_NAME, FileContextProvider.class);
registerApplicationExtensionPoint(MetaDataContributor.EP_NAME, MetaDataContributor.class);
registerApplicationExtensionPoint(PsiAugmentProvider.EP_NAME, PsiAugmentProvider.class);
registerApplicationExtensionPoint(JavaMainMethodProvider.EP_NAME, JavaMainMethodProvider.class);
registerApplicationExtensionPoint(ContainerProvider.EP_NAME, ContainerProvider.class);
registerApplicationExtensionPoint(ClassFileDecompilers.EP_NAME, ClassFileDecompilers.Decompiler.class);
registerApplicationExtensionPoint(MetaLanguage.EP_NAME, MetaLanguage.class);
IdeaExtensionPoints.INSTANCE.registerVersionSpecificAppExtensionPoints(Extensions.getRootArea());
}
@Nullable
@Override
protected VirtualFileSystem createJrtFileSystem() {
return new CoreJrtFileSystem();
}
}

View File

@@ -1,197 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.cli.jvm.compiler;
import com.intellij.codeInsight.ContainerProvider;
import com.intellij.codeInsight.JavaContainerProvider;
import com.intellij.codeInsight.folding.JavaCodeFoldingSettings;
import com.intellij.codeInsight.folding.impl.JavaCodeFoldingSettingsBase;
import com.intellij.codeInsight.folding.impl.JavaFoldingBuilderBase;
import com.intellij.codeInsight.runner.JavaMainMethodProvider;
import com.intellij.core.CoreApplicationEnvironment;
import com.intellij.core.CoreJavaDirectoryService;
import com.intellij.core.CorePsiPackageImplementationHelper;
import com.intellij.ide.highlighter.ArchiveFileType;
import com.intellij.ide.highlighter.JavaClassFileType;
import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.lang.LanguageASTFactory;
import com.intellij.lang.MetaLanguage;
import com.intellij.lang.folding.LanguageFolding;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.lang.java.JavaParserDefinition;
import com.intellij.navigation.ItemPresentationProviders;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.extensions.ExtensionsArea;
import com.intellij.openapi.fileTypes.FileTypeExtensionPoint;
import com.intellij.openapi.fileTypes.PlainTextFileType;
import com.intellij.openapi.fileTypes.PlainTextLanguage;
import com.intellij.openapi.fileTypes.PlainTextParserDefinition;
import com.intellij.openapi.projectRoots.JavaVersionService;
import com.intellij.openapi.util.KeyWithDefaultValue;
import com.intellij.openapi.vfs.VirtualFileSystem;
import com.intellij.psi.*;
import com.intellij.psi.augment.PsiAugmentProvider;
import com.intellij.psi.augment.TypeAnnotationModifier;
import com.intellij.psi.compiled.ClassFileDecompilers;
import com.intellij.psi.impl.EmptySubstitutorImpl;
import com.intellij.psi.impl.LanguageConstantExpressionEvaluator;
import com.intellij.psi.impl.PsiExpressionEvaluator;
import com.intellij.psi.impl.compiled.ClassFileStubBuilder;
import com.intellij.psi.impl.file.PsiPackageImplementationHelper;
import com.intellij.psi.impl.search.MethodSuperSearcher;
import com.intellij.psi.impl.source.tree.JavaASTFactory;
import com.intellij.psi.impl.source.tree.PlainTextASTFactory;
import com.intellij.psi.meta.MetaDataContributor;
import com.intellij.psi.presentation.java.*;
import com.intellij.psi.search.searches.SuperMethodsSearch;
import com.intellij.psi.stubs.BinaryFileStubBuilders;
import com.intellij.util.QueryExecutor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.cli.jvm.modules.CoreJrtFileSystem;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
/**
* adapted from com.intellij.core.JavaCoreApplicationEnvironment
* TODO: initiate removal original from com.intellij.core since it seems that there are no usages left
*/
public class KotlinCoreApplicationEnvironment extends CoreApplicationEnvironment {
public static KotlinCoreApplicationEnvironment create(@NotNull Disposable parentDisposable, boolean unitTestMode) {
return new KotlinCoreApplicationEnvironment(parentDisposable, unitTestMode);
}
private KotlinCoreApplicationEnvironment(@NotNull Disposable parentDisposable, boolean unitTestMode) {
super(parentDisposable, unitTestMode);
registerExtensionPoints();
registerExtensions();
}
private void registerExtensionPoints() {
ExtensionsArea area = Extensions.getRootArea();
CoreApplicationEnvironment.registerExtensionPoint(area, BinaryFileStubBuilders.EP_NAME, FileTypeExtensionPoint.class);
CoreApplicationEnvironment.registerExtensionPoint(area, FileContextProvider.EP_NAME, FileContextProvider.class);
CoreApplicationEnvironment.registerExtensionPoint(area, MetaDataContributor.EP_NAME, MetaDataContributor.class);
CoreApplicationEnvironment.registerExtensionPoint(area, PsiAugmentProvider.EP_NAME, PsiAugmentProvider.class);
CoreApplicationEnvironment.registerExtensionPoint(area, JavaMainMethodProvider.EP_NAME, JavaMainMethodProvider.class);
CoreApplicationEnvironment.registerExtensionPoint(area, ContainerProvider.EP_NAME, ContainerProvider.class);
CoreApplicationEnvironment.registerExtensionPoint(area, ClassFileDecompilers.EP_NAME, ClassFileDecompilers.Decompiler.class);
CoreApplicationEnvironment.registerExtensionPoint(area, TypeAnnotationModifier.EP_NAME, TypeAnnotationModifier.class);
CoreApplicationEnvironment.registerExtensionPoint(area, MetaLanguage.EP_NAME, MetaLanguage.class);
IdeaExtensionPoints.INSTANCE.registerVersionSpecificAppExtensionPoints(area);
}
private void registerExtensions() {
registerFileType(JavaClassFileType.INSTANCE, "class");
registerFileType(JavaFileType.INSTANCE, "java");
registerFileType(ArchiveFileType.INSTANCE, "jar;zip");
registerFileType(PlainTextFileType.INSTANCE, "txt;sh;bat;cmd;policy;log;cgi;MF;jad;jam;htaccess");
addExplicitExtension(LanguageASTFactory.INSTANCE, PlainTextLanguage.INSTANCE, new PlainTextASTFactory());
registerParserDefinition(new PlainTextParserDefinition());
addExplicitExtension(FileTypeFileViewProviders.INSTANCE, JavaClassFileType.INSTANCE, new ClassFileViewProviderFactory());
addExplicitExtension(BinaryFileStubBuilders.INSTANCE, JavaClassFileType.INSTANCE, new ClassFileStubBuilder());
addExplicitExtension(LanguageASTFactory.INSTANCE, JavaLanguage.INSTANCE, new JavaASTFactory());
registerParserDefinition(new JavaParserDefinition());
addExplicitExtension(LanguageConstantExpressionEvaluator.INSTANCE, JavaLanguage.INSTANCE, new PsiExpressionEvaluator());
addExtension(ContainerProvider.EP_NAME, new JavaContainerProvider());
myApplication.registerService(PsiPackageImplementationHelper.class, new CorePsiPackageImplementationHelper());
EmptySubstitutorImpl emptySubstitutor = new EmptySubstitutorImpl();
myApplication.registerService(EmptySubstitutor.class, emptySubstitutor);
// Patch null values obtained because of cyclic dependency during initialization
updateInterfaceField(PsiSubstitutor.class, "EMPTY", emptySubstitutor);
updateInterfaceField(PsiSubstitutor.class, "UNKNOWN", PsiSubstitutor.EMPTY);
myApplication.registerService(JavaDirectoryService.class, createJavaDirectoryService());
myApplication.registerService(JavaVersionService.class, new JavaVersionService());
addExplicitExtension(ItemPresentationProviders.INSTANCE, PsiPackage.class, new PackagePresentationProvider());
addExplicitExtension(ItemPresentationProviders.INSTANCE, PsiClass.class, new ClassPresentationProvider());
addExplicitExtension(ItemPresentationProviders.INSTANCE, PsiMethod.class, new MethodPresentationProvider());
addExplicitExtension(ItemPresentationProviders.INSTANCE, PsiField.class, new FieldPresentationProvider());
addExplicitExtension(ItemPresentationProviders.INSTANCE, PsiLocalVariable.class, new VariablePresentationProvider());
addExplicitExtension(ItemPresentationProviders.INSTANCE, PsiParameter.class, new VariablePresentationProvider());
registerApplicationService(JavaCodeFoldingSettings.class, new JavaCodeFoldingSettingsBase());
addExplicitExtension(LanguageFolding.INSTANCE, JavaLanguage.INSTANCE, new JavaFoldingBuilderBase() {
@Override
protected boolean shouldShowExplicitLambdaType(@NotNull PsiAnonymousClass anonymousClass, @NotNull PsiNewExpression expression) {
return false;
}
@Override
protected boolean isBelowRightMargin(@NotNull PsiFile file, int lineLength) {
return false;
}
});
registerApplicationExtensionPoint(SuperMethodsSearch.EP_NAME, QueryExecutor.class);
addExtension(SuperMethodsSearch.EP_NAME, new MethodSuperSearcher());
}
// overridden in upsource
protected CoreJavaDirectoryService createJavaDirectoryService() {
return new CoreJavaDirectoryService();
}
@Nullable
@Override
protected VirtualFileSystem createJrtFileSystem() {
return new CoreJrtFileSystem();
}
private static void updateInterfaceField(Class<?> klass, String name, Object value) {
try {
Field field = klass.getDeclaredField(name);
boolean wasAccessible = field.isAccessible();
try {
if (!wasAccessible) {
field.setAccessible(true);
}
Field modifiersField = Field.class.getDeclaredField("modifiers");
int modifiers = field.getModifiers();
try {
modifiersField.setAccessible(true);
modifiersField.setInt(field, modifiers & ~Modifier.FINAL);
field.set(null, value);
}
finally {
modifiersField.setInt(field, modifiers);
modifiersField.setAccessible(false);
}
}
finally {
if (!wasAccessible) {
field.setAccessible(false);
}
}
}
catch (NoSuchFieldException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
}

View File

@@ -216,7 +216,7 @@ class KotlinCoreEnvironment private constructor(
)
val (initialRoots, javaModules) =
classpathRootsResolver.convertClasspathRoots(configuration.getList(CLIConfigurationKeys.CONTENT_ROOTS))
classpathRootsResolver.convertClasspathRoots(configuration.getList(CLIConfigurationKeys.CONTENT_ROOTS))
this.initialRoots.addAll(initialRoots)
if (!configuration.getBoolean(JVMConfigurationKeys.SKIP_RUNTIME_VERSION_CHECK) && messageCollector != null) {
@@ -228,7 +228,7 @@ class KotlinCoreEnvironment private constructor(
}
val (roots, singleJavaFileRoots) =
initialRoots.partition { (file) -> file.isDirectory || file.extension != JavaFileType.DEFAULT_EXTENSION }
initialRoots.partition { (file) -> file.isDirectory || file.extension != JavaFileType.DEFAULT_EXTENSION }
// REPL and kapt2 update classpath dynamically
rootsIndex = JvmDependenciesDynamicCompoundIndex().apply {
@@ -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)
@@ -528,7 +529,7 @@ class KotlinCoreEnvironment private constructor(
false
}
val pluginRoot =
val pluginRoot: File =
configuration.get(CLIConfigurationKeys.INTELLIJ_PLUGIN_ROOT)?.let(::File)
?: PathUtil.getResourcePathForClass(this::class.java).takeIf { it.hasConfigFile(configFilePath) }
// hack for load extensions when compiler run directly from project directory (e.g. in tests)
@@ -538,7 +539,7 @@ class KotlinCoreEnvironment private constructor(
"(cp:\n ${(Thread.currentThread().contextClassLoader as? UrlClassLoader)?.urls?.joinToString("\n ") { it.file }})"
)
CoreApplicationEnvironment.registerExtensionPointAndExtensions(pluginRoot, configFilePath, Extensions.getRootArea())
registerExtensionPointAndExtensionsEx(pluginRoot, configFilePath, Extensions.getRootArea())
}
private fun workaroundIbmJdkStaxReportCdataEventIssue() {
@@ -714,5 +715,4 @@ class KotlinCoreEnvironment private constructor(
}
}
}
}
}

View File

@@ -31,6 +31,7 @@ import org.jetbrains.kotlin.asJava.finder.JavaElementFinder
import org.jetbrains.kotlin.backend.common.output.OutputFileCollection
import org.jetbrains.kotlin.backend.common.output.SimpleOutputFileCollection
import org.jetbrains.kotlin.backend.common.phaser.PhaseConfig
import org.jetbrains.kotlin.backend.common.serialization.signature.IdSignatureDescriptor
import org.jetbrains.kotlin.backend.jvm.JvmIrCodegenFactory
import org.jetbrains.kotlin.backend.jvm.jvmPhases
import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
@@ -59,6 +60,7 @@ import org.jetbrains.kotlin.fir.resolve.firProvider
import org.jetbrains.kotlin.fir.resolve.impl.FirProviderImpl
import org.jetbrains.kotlin.fir.resolve.transformers.FirTotalResolveTransformer
import org.jetbrains.kotlin.idea.MainFunctionDetector
import org.jetbrains.kotlin.ir.backend.jvm.serialization.JvmManglerDesc
import org.jetbrains.kotlin.javac.JavacWrapper
import org.jetbrains.kotlin.load.kotlin.ModuleVisibilityManager
import org.jetbrains.kotlin.modules.Module
@@ -339,8 +341,11 @@ object KotlinToJVMBytecodeCompiler {
throw e
}
}
val signaturer = IdSignatureDescriptor(JvmManglerDesc())
val (moduleFragment, symbolTable, sourceManager) =
Fir2IrConverter.createModuleFragment(session, firFiles, moduleConfiguration.languageVersionSettings)
Fir2IrConverter.createModuleFragment(session, firFiles, moduleConfiguration.languageVersionSettings, signaturer = signaturer)
val dummyBindingContext = NoScopeRecordCliBindingTrace().bindingContext
val codegenFactory = JvmIrCodegenFactory(moduleConfiguration.get(CLIConfigurationKeys.PHASE_CONFIG) ?: PhaseConfig(jvmPhases))

View File

@@ -71,7 +71,7 @@ import org.jetbrains.kotlin.resolve.jvm.extensions.PackageFragmentProviderExtens
import org.jetbrains.kotlin.resolve.lazy.KotlinCodeAnalyzer
import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactory
import org.jetbrains.kotlin.resolve.lazy.declarations.FileBasedDeclarationProviderFactory
import org.jetbrains.kotlin.serialization.konan.NullFlexibleTypeDeserializer
import org.jetbrains.kotlin.library.metadata.NullFlexibleTypeDeserializer
import org.jetbrains.kotlin.storage.LockBasedStorageManager
import org.jetbrains.kotlin.storage.StorageManager
import java.util.*

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,16 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.cli.jvm.compiler
import com.intellij.core.CoreApplicationEnvironment
import com.intellij.openapi.extensions.ExtensionsArea
import java.io.File
// BUNCH: 193
fun registerExtensionPointAndExtensionsEx(pluginFile: File, fileName: String, area: ExtensionsArea) {
@Suppress("MissingRecentApi")
CoreApplicationEnvironment.registerExtensionPointAndExtensions(pluginFile, fileName, area)
}

View File

@@ -0,0 +1,18 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.cli.jvm.compiler
import com.intellij.core.CoreApplicationEnvironment
import com.intellij.openapi.extensions.ExtensionsArea
import java.io.File
import java.nio.file.FileSystems
// BUNCH: 193
fun registerExtensionPointAndExtensionsEx(pluginFile: File, fileName: String, area: ExtensionsArea) {
val pluginRoot = FileSystems.getDefault().getPath(pluginFile.path)
@Suppress("MissingRecentApi")
CoreApplicationEnvironment.registerExtensionPointAndExtensions(pluginRoot, fileName, area)
}

View File

@@ -8,7 +8,6 @@ package org.jetbrains.kotlin.cli.metadata
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.analyzer.common.CommonDependenciesContainer
import org.jetbrains.kotlin.analyzer.common.CommonPlatformAnalyzerServices
import org.jetbrains.kotlin.backend.common.serialization.DescriptorTable
import org.jetbrains.kotlin.backend.common.serialization.metadata.KlibMetadataMonolithicSerializer
import org.jetbrains.kotlin.backend.common.serialization.metadata.KlibMetadataVersion
import org.jetbrains.kotlin.builtins.DefaultBuiltIns
@@ -27,7 +26,8 @@ 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.buildKoltinLibrary
import org.jetbrains.kotlin.library.impl.createKotlinLibraryComponents
import org.jetbrains.kotlin.library.metadata.NativeTypeTransformer
import org.jetbrains.kotlin.library.metadata.NullFlexibleTypeDeserializer
import org.jetbrains.kotlin.library.metadata.parseModuleHeader
import org.jetbrains.kotlin.metadata.builtins.BuiltInsBinaryVersion
import org.jetbrains.kotlin.name.Name
@@ -68,7 +68,6 @@ internal class K2MetadataKlibSerializer(private val metadataVersion: BuiltInsBin
val serializedMetadata: SerializedMetadata = KlibMetadataMonolithicSerializer(
configuration.languageVersionSettings,
metadataVersion,
DescriptorTable.createDefault(),
skipExpects = false,
includeOnlyModuleContent = true
).serializeModule(module)
@@ -167,7 +166,8 @@ private class KlibMetadataDependencyContainer(
KlibMetadataModuleDescriptorFactoryImpl(
MetadataFactories.DefaultDescriptorFactory,
MetadataFactories.DefaultPackageFragmentsFactory,
MetadataFactories.flexibleTypeDeserializer
MetadataFactories.flexibleTypeDeserializer,
MetadataFactories.platformDependentTypeTransformer
)
}
@@ -197,5 +197,6 @@ private class KlibMetadataDependencyContainer(
private val MetadataFactories =
KlibMetadataFactories(
{ DefaultBuiltIns.Instance },
org.jetbrains.kotlin.serialization.konan.NullFlexibleTypeDeserializer
NullFlexibleTypeDeserializer,
NativeTypeTransformer()
)

View File

@@ -49,11 +49,7 @@ sourceSets {
publish()
noDefaultJar()
runtimeJar(tasks.register<ShadowJar>("shadowJar")) {
from(mainSourceSet.output)
}
runtimeJar()
sourcesJar()

View File

@@ -63,11 +63,7 @@ sourceSets {
publish()
noDefaultJar()
runtimeJar(tasks.register<ShadowJar>("shadowJar")) {
from(mainSourceSet.output)
}
runtimeJar()
sourcesJar()

View File

@@ -18,8 +18,8 @@ class RemoteIncrementalResultsConsumer(val facade: CompilerCallbackServicesFacad
override fun processIrFile(
sourceFile: File,
fileData: ByteArray,
symbols: ByteArray,
types: ByteArray,
signatures: ByteArray,
strings: ByteArray,
declarations: ByteArray,
bodies: ByteArray,
@@ -29,8 +29,7 @@ class RemoteIncrementalResultsConsumer(val facade: CompilerCallbackServicesFacad
}
init {
eventManager.
onCompilationFinished(this::flush)
eventManager.onCompilationFinished(this::flush)
}
override fun processHeader(headerMetadata: ByteArray) {

View File

@@ -25,27 +25,25 @@ enum class ProjectionKind {
}
}
sealed class ConeKotlinTypeProjection : TypeArgumentMarker {
sealed class ConeTypeProjection : TypeArgumentMarker {
abstract val kind: ProjectionKind
companion object {
val EMPTY_ARRAY = arrayOf<ConeKotlinTypeProjection>()
val EMPTY_ARRAY = arrayOf<ConeTypeProjection>()
}
}
object ConeStarProjection : ConeKotlinTypeProjection() {
object ConeStarProjection : ConeTypeProjection() {
override val kind: ProjectionKind
get() = ProjectionKind.STAR
}
data class ConeKotlinTypeProjectionIn(override val type: ConeKotlinType) : ConeKotlinTypeProjection(),
ConeTypedProjection {
data class ConeKotlinTypeProjectionIn(override val type: ConeKotlinType) : ConeKotlinTypeProjection() {
override val kind: ProjectionKind
get() = ProjectionKind.IN
}
data class ConeKotlinTypeProjectionOut(override val type: ConeKotlinType) : ConeKotlinTypeProjection(),
ConeTypedProjection {
data class ConeKotlinTypeProjectionOut(override val type: ConeKotlinType) : ConeKotlinTypeProjection() {
override val kind: ProjectionKind
get() = ProjectionKind.OUT
}
@@ -53,13 +51,12 @@ data class ConeKotlinTypeProjectionOut(override val type: ConeKotlinType) : Cone
// We assume type IS an invariant type projection to prevent additional wrapper here
// (more exactly, invariant type projection contains type)
sealed class ConeKotlinType : ConeKotlinTypeProjection(),
ConeTypedProjection,
KotlinTypeMarker,
TypeArgumentListMarker {
override val kind: ProjectionKind
get() = ProjectionKind.INVARIANT
abstract val typeArguments: Array<out ConeKotlinTypeProjection>
abstract val typeArguments: Array<out ConeTypeProjection>
override val type: ConeKotlinType
get() = this
@@ -73,8 +70,8 @@ sealed class ConeKotlinType : ConeKotlinTypeProjection(),
sealed class ConeSimpleKotlinType : ConeKotlinType(), SimpleTypeMarker
interface ConeTypedProjection {
val type: ConeKotlinType
sealed class ConeKotlinTypeProjection : ConeTypeProjection() {
abstract val type: ConeKotlinType
}
typealias ConeKotlinErrorType = ConeClassErrorType
@@ -85,7 +82,7 @@ class ConeClassErrorType(val reason: String) : ConeClassLikeType() {
override val lookupTag: ConeClassLikeLookupTag
get() = ConeClassLikeErrorLookupTag(ClassId.fromString("<error>"))
override val typeArguments: Array<out ConeKotlinTypeProjection>
override val typeArguments: Array<out ConeTypeProjection>
get() = EMPTY_ARRAY
override val nullability: ConeNullability
@@ -109,7 +106,7 @@ open class ConeFlexibleType(val lowerBound: ConeKotlinType, val upperBound: Cone
require(upperBound is SimpleTypeMarker, message)
}
override val typeArguments: Array<out ConeKotlinTypeProjection>
override val typeArguments: Array<out ConeTypeProjection>
get() = emptyArray()
override val nullability: ConeNullability
@@ -139,7 +136,7 @@ fun ConeKotlinType.upperBoundIfFlexible() = (this as? ConeFlexibleType)?.upperBo
fun ConeKotlinType.lowerBoundIfFlexible() = (this as? ConeFlexibleType)?.lowerBound ?: this
class ConeCapturedTypeConstructor(
val projection: ConeKotlinTypeProjection,
val projection: ConeTypeProjection,
var supertypes: List<ConeKotlinType>? = null,
val typeParameterMarker: TypeParameterMarker? = null
) : CapturedTypeConstructorMarker
@@ -151,7 +148,7 @@ class ConeCapturedType(
val constructor: ConeCapturedTypeConstructor
) : ConeSimpleKotlinType(), CapturedTypeMarker {
constructor(
captureStatus: CaptureStatus, lowerType: ConeKotlinType?, projection: ConeKotlinTypeProjection,
captureStatus: CaptureStatus, lowerType: ConeKotlinType?, projection: ConeTypeProjection,
typeParameterMarker: TypeParameterMarker
) : this(
captureStatus,
@@ -162,7 +159,7 @@ class ConeCapturedType(
)
)
override val typeArguments: Array<out ConeKotlinTypeProjection>
override val typeArguments: Array<out ConeTypeProjection>
get() = emptyArray()
}
@@ -170,11 +167,11 @@ data class ConeTypeVariableType(
override val nullability: ConeNullability,
override val lookupTag: ConeClassifierLookupTag
) : ConeLookupTagBasedType() {
override val typeArguments: Array<out ConeKotlinTypeProjection> get() = emptyArray()
override val typeArguments: Array<out ConeTypeProjection> get() = emptyArray()
}
data class ConeDefinitelyNotNullType(val original: ConeKotlinType) : ConeSimpleKotlinType(), DefinitelyNotNullTypeMarker {
override val typeArguments: Array<out ConeKotlinTypeProjection>
override val typeArguments: Array<out ConeTypeProjection>
get() = original.typeArguments
override val nullability: ConeNullability
get() = ConeNullability.NOT_NULL
@@ -193,7 +190,7 @@ class ConeRawType(lowerBound: ConeKotlinType, upperBound: ConeKotlinType) : Cone
class ConeIntersectionType(
val intersectedTypes: Collection<ConeKotlinType>
) : ConeSimpleKotlinType(), TypeConstructorMarker {
override val typeArguments: Array<out ConeKotlinTypeProjection>
override val typeArguments: Array<out ConeTypeProjection>
get() = emptyArray()
override val nullability: ConeNullability
@@ -205,7 +202,7 @@ fun ConeIntersectionType.mapTypes(func: (ConeKotlinType) -> ConeKotlinType): Con
}
class ConeStubType(val variable: ConeTypeVariable, override val nullability: ConeNullability) : StubTypeMarker, ConeSimpleKotlinType() {
override val typeArguments: Array<out ConeKotlinTypeProjection>
override val typeArguments: Array<out ConeTypeProjection>
get() = emptyArray()
}
@@ -226,7 +223,7 @@ abstract class ConeIntegerLiteralType(val value: Long) : ConeSimpleKotlinType(),
abstract val possibleTypes: Collection<ConeClassLikeType>
abstract val supertypes: List<ConeClassLikeType>
override val typeArguments: Array<out ConeKotlinTypeProjection> = emptyArray()
override val typeArguments: Array<out ConeTypeProjection> = emptyArray()
override val nullability: ConeNullability = ConeNullability.NOT_NULL
abstract fun getApproximatedType(expectedType: ConeKotlinType? = null): ConeClassLikeType

View File

@@ -15,7 +15,7 @@ fun ConeKotlinType.render(): String {
is ConeTypeVariableType -> "TypeVariable(${this.lookupTag.name})"
is ConeDefinitelyNotNullType -> "${original.render()}!!"
is ConeClassErrorType -> "ERROR CLASS: $reason"
is ConeCapturedType -> "captured type: lowerType = ${lowerType?.render()}"
is ConeCapturedType -> "CapturedType(${constructor.projection.render()})"
is ConeClassLikeType -> {
buildString {
append(lookupTag.classId.asString())
@@ -45,12 +45,12 @@ fun ConeKotlinType.render(): String {
postfix = ")"
)
}
is ConeStubType -> "stub type: $variable"
is ConeStubType -> "Stub: $variable"
is ConeIntegerLiteralType -> "ILT: $value"
} + nullabilitySuffix
}
private fun ConeKotlinTypeProjection.render(): String {
private fun ConeTypeProjection.render(): String {
return when (this) {
ConeStarProjection -> "*"
is ConeKotlinTypeProjectionIn -> "in ${type.render()}"

View File

@@ -7,12 +7,12 @@ package org.jetbrains.kotlin.fir.types.impl
import org.jetbrains.kotlin.fir.symbols.ConeClassLikeLookupTag
import org.jetbrains.kotlin.fir.types.ConeClassLikeType
import org.jetbrains.kotlin.fir.types.ConeKotlinTypeProjection
import org.jetbrains.kotlin.fir.types.ConeTypeProjection
import org.jetbrains.kotlin.fir.types.ConeNullability
class ConeClassLikeTypeImpl(
override val lookupTag: ConeClassLikeLookupTag,
override val typeArguments: Array<out ConeKotlinTypeProjection>,
override val typeArguments: Array<out ConeTypeProjection>,
isNullable: Boolean
) : ConeClassLikeType() {
override val nullability: ConeNullability = ConeNullability.create(isNullable)

View File

@@ -13,6 +13,8 @@ import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.descriptors.Visibility
import org.jetbrains.kotlin.fir.*
import org.jetbrains.kotlin.fir.backend.left
import org.jetbrains.kotlin.fir.backend.right
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.declarations.impl.FirDefaultPropertyAccessor
import org.jetbrains.kotlin.fir.diagnostics.FirDiagnostic
@@ -22,9 +24,7 @@ import org.jetbrains.kotlin.fir.expressions.impl.FirUnitExpression
import org.jetbrains.kotlin.fir.references.*
import org.jetbrains.kotlin.fir.references.impl.FirSimpleNamedReference
import org.jetbrains.kotlin.fir.resolve.directExpansionType
import org.jetbrains.kotlin.fir.resolve.firSymbolProvider
import org.jetbrains.kotlin.fir.resolve.toSymbol
import org.jetbrains.kotlin.fir.resolve.withNullability
import org.jetbrains.kotlin.fir.symbols.AbstractFirBasedSymbol
import org.jetbrains.kotlin.fir.resolve.diagnostics.FirAmbiguityError
import org.jetbrains.kotlin.fir.resolve.diagnostics.FirInapplicableCandidateError
@@ -698,10 +698,10 @@ class HtmlFirDump internal constructor(private var linkResolver: FirLinkResolver
generate(variableAssignment.rValue)
}
private fun FlowContent.generate(projection: ConeKotlinTypeProjection) {
private fun FlowContent.generate(projection: ConeTypeProjection) {
when (projection) {
is ConeStarProjection -> +"*"
is ConeTypedProjection -> {
is ConeKotlinTypeProjection -> {
when (projection.kind) {
ProjectionKind.IN -> keyword("in ")
ProjectionKind.OUT -> keyword("out ")
@@ -1412,11 +1412,10 @@ class HtmlFirDump internal constructor(private var linkResolver: FirLinkResolver
private fun FlowContent.generate(resolvedQualifier: FirResolvedQualifier) {
resolved {
val symbolProvider = session.firSymbolProvider
val classId = resolvedQualifier.classId
if (classId != null) {
symbolRef(symbolProvider.getClassLikeSymbolByFqName(classId)) {
fqn(classId.relativeClassName)
val symbol = resolvedQualifier.symbol
if (symbol != null) {
symbolRef(symbol) {
fqn(resolvedQualifier.classId?.relativeClassName ?: FqName("<???>"))
}
} else {
fqn(resolvedQualifier.packageFqName)
@@ -1476,11 +1475,29 @@ class HtmlFirDump internal constructor(private var linkResolver: FirLinkResolver
is FirOperatorCall -> generate(expression)
is FirBinaryLogicExpression -> generate(expression)
is FirCheckNotNullCall -> generate(expression)
is FirVarargArgumentsExpression -> generate(expression)
is FirResolvedReifiedParameterReference -> generate(expression)
is FirComparisonExpression -> generate(expression)
else -> inlineUnsupported(expression)
}
}
}
private fun FlowContent.generate(comparisonExpression: FirComparisonExpression) {
generate(comparisonExpression.left)
+" ${comparisonExpression.operation.operator} "
generate(comparisonExpression.right)
}
private fun FlowContent.generate(resolvedReifiedParameterReference: FirResolvedReifiedParameterReference) {
val typeParameter = resolvedReifiedParameterReference.symbol.fir
+typeParameter.name.identifier
}
private fun FlowContent.generate(varargArgumentExpression: FirVarargArgumentsExpression) {
generateList(varargArgumentExpression.arguments, separator = ",") { generate(it) }
}
private fun FlowContent.generate(binaryLogicExpression: FirBinaryLogicExpression) {
generate(binaryLogicExpression.leftOperand)
+" ${binaryLogicExpression.kind.token} "

View File

@@ -8,6 +8,9 @@ package org.jetbrains.kotlin.fir.backend
import com.intellij.psi.PsiCompiledElement
import org.jetbrains.kotlin.fir.FirElement
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.declarations.FirClass
import org.jetbrains.kotlin.fir.declarations.FirSimpleFunction
import org.jetbrains.kotlin.fir.declarations.FirVariable
import org.jetbrains.kotlin.fir.expressions.FirConstExpression
import org.jetbrains.kotlin.fir.expressions.FirConstKind
import org.jetbrains.kotlin.fir.psi
@@ -31,6 +34,7 @@ import org.jetbrains.kotlin.ir.types.impl.IrStarProjectionImpl
import org.jetbrains.kotlin.ir.types.impl.makeTypeProjection
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffsetSkippingComments
import org.jetbrains.kotlin.types.Variance
@@ -46,47 +50,72 @@ internal fun <T : IrElement> FirElement.convertWithOffsets(
internal fun createErrorType(): IrErrorType = IrErrorTypeImpl(null, emptyList(), Variance.INVARIANT)
fun FirTypeRef.toIrType(session: FirSession, declarationStorage: Fir2IrDeclarationStorage, irBuiltIns: IrBuiltIns): IrType {
internal enum class ConversionTypeOrigin {
DEFAULT,
SETTER
}
class ConversionTypeContext internal constructor(
internal val definitelyNotNull: Boolean,
internal val origin: ConversionTypeOrigin
) {
fun definitelyNotNull() = ConversionTypeContext(true, origin)
fun inSetter() = ConversionTypeContext(definitelyNotNull, ConversionTypeOrigin.SETTER)
companion object {
internal val DEFAULT = ConversionTypeContext(
definitelyNotNull = false, origin = ConversionTypeOrigin.DEFAULT
)
}
}
fun FirTypeRef.toIrType(
session: FirSession,
declarationStorage: Fir2IrDeclarationStorage,
irBuiltIns: IrBuiltIns,
typeContext: ConversionTypeContext = ConversionTypeContext.DEFAULT
): IrType {
if (this !is FirResolvedTypeRef) {
return createErrorType()
}
return type.toIrType(session, declarationStorage, irBuiltIns)
return type.toIrType(session, declarationStorage, irBuiltIns, typeContext)
}
fun ConeKotlinType.toIrType(
session: FirSession,
declarationStorage: Fir2IrDeclarationStorage,
irBuiltIns: IrBuiltIns,
definitelyNotNull: Boolean = false
typeContext: ConversionTypeContext = ConversionTypeContext.DEFAULT
): IrType {
return when (this) {
is ConeKotlinErrorType -> createErrorType()
is ConeLookupTagBasedType -> {
val irSymbol = getArrayType(this.classId, irBuiltIns) ?: run {
val firSymbol = this.lookupTag.toSymbol(session) ?: return createErrorType()
firSymbol.toIrSymbol(session, declarationStorage)
firSymbol.toIrSymbol(session, declarationStorage, typeContext)
}
// TODO: annotations
IrSimpleTypeImpl(
irSymbol, !definitelyNotNull && this.isMarkedNullable,
irSymbol, !typeContext.definitelyNotNull && this.isMarkedNullable,
typeArguments.map { it.toIrTypeArgument(session, declarationStorage, irBuiltIns) },
emptyList()
)
}
is ConeFlexibleType -> {
// TODO: yet we take more general type. Not quite sure it's Ok
upperBound.toIrType(session, declarationStorage, irBuiltIns, definitelyNotNull)
upperBound.toIrType(session, declarationStorage, irBuiltIns, typeContext)
}
is ConeCapturedType -> TODO()
is ConeDefinitelyNotNullType -> {
original.toIrType(session, declarationStorage, irBuiltIns, definitelyNotNull = true)
original.toIrType(session, declarationStorage, irBuiltIns, typeContext.definitelyNotNull())
}
is ConeIntersectionType -> {
// TODO: add intersectionTypeApproximation
intersectedTypes.first().toIrType(session, declarationStorage, irBuiltIns, definitelyNotNull)
intersectedTypes.first().toIrType(session, declarationStorage, irBuiltIns, typeContext)
}
is ConeStubType -> createErrorType()
is ConeIntegerLiteralType -> getApproximatedType().toIrType(session, declarationStorage, irBuiltIns, definitelyNotNull)
is ConeIntegerLiteralType -> getApproximatedType().toIrType(session, declarationStorage, irBuiltIns, typeContext)
}
}
@@ -106,7 +135,7 @@ private fun getArrayType(classId: ClassId?, irBuiltIns: IrBuiltIns): IrClassifie
return irType?.let { irBuiltIns.primitiveArrayForType.getValue(it) }
}
fun ConeKotlinTypeProjection.toIrTypeArgument(
fun ConeTypeProjection.toIrTypeArgument(
session: FirSession,
declarationStorage: Fir2IrDeclarationStorage,
irBuiltIns: IrBuiltIns
@@ -128,10 +157,14 @@ fun ConeKotlinTypeProjection.toIrTypeArgument(
}
}
fun FirClassifierSymbol<*>.toIrSymbol(session: FirSession, declarationStorage: Fir2IrDeclarationStorage): IrClassifierSymbol {
fun FirClassifierSymbol<*>.toIrSymbol(
session: FirSession,
declarationStorage: Fir2IrDeclarationStorage,
typeContext: ConversionTypeContext = ConversionTypeContext.DEFAULT
): IrClassifierSymbol {
return when (this) {
is FirTypeParameterSymbol -> {
toTypeParameterSymbol(declarationStorage)
toTypeParameterSymbol(declarationStorage, typeContext)
}
is FirTypeAliasSymbol -> {
val typeAlias = fir
@@ -147,7 +180,18 @@ fun FirClassifierSymbol<*>.toIrSymbol(session: FirSession, declarationStorage: F
fun FirReference.toSymbol(declarationStorage: Fir2IrDeclarationStorage): IrSymbol? {
return when (this) {
is FirResolvedNamedReference -> resolvedSymbol.toSymbol(declarationStorage)
is FirResolvedNamedReference -> {
when (val resolvedSymbol = resolvedSymbol) {
is FirCallableSymbol<*> -> {
val originalCallableSymbol =
resolvedSymbol.overriddenSymbol?.takeIf { it.callableId == resolvedSymbol.callableId } ?: resolvedSymbol
originalCallableSymbol.toSymbol(declarationStorage)
}
else -> {
resolvedSymbol.toSymbol(declarationStorage)
}
}
}
is FirThisReference -> {
when (val boundSymbol = boundSymbol?.toSymbol(declarationStorage)) {
is IrClassSymbol -> boundSymbol.owner.thisReceiver?.symbol
@@ -174,8 +218,11 @@ fun FirClassSymbol<*>.toClassSymbol(declarationStorage: Fir2IrDeclarationStorage
return declarationStorage.getIrClassSymbol(this)
}
fun FirTypeParameterSymbol.toTypeParameterSymbol(declarationStorage: Fir2IrDeclarationStorage): IrTypeParameterSymbol {
return declarationStorage.getIrTypeParameterSymbol(this)
fun FirTypeParameterSymbol.toTypeParameterSymbol(
declarationStorage: Fir2IrDeclarationStorage,
typeContext: ConversionTypeContext = ConversionTypeContext.DEFAULT
): IrTypeParameterSymbol {
return declarationStorage.getIrTypeParameterSymbol(this, typeContext)
}
fun FirFunctionSymbol<*>.toFunctionSymbol(declarationStorage: Fir2IrDeclarationStorage): IrFunctionSymbol {
@@ -215,3 +262,43 @@ private fun FirConstKind<*>.toIrConstKind(): IrConstKind<*> = when (this) {
FirConstKind.Double -> IrConstKind.Double
FirConstKind.IntegerLiteral -> throw IllegalArgumentException()
}
internal fun FirClass<*>.collectCallableNamesFromSupertypes(session: FirSession, result: MutableList<Name> = mutableListOf()): List<Name> {
for (superTypeRef in superTypeRefs) {
superTypeRef.collectCallableNamesFromThisAndSupertypes(session, result)
}
return result
}
private fun FirTypeRef.collectCallableNamesFromThisAndSupertypes(
session: FirSession,
result: MutableList<Name> = mutableListOf()
): List<Name> {
if (this is FirResolvedTypeRef) {
val superType = type
if (superType is ConeClassLikeType) {
when (val superSymbol = superType.lookupTag.toSymbol(session)) {
is FirClassSymbol -> {
val superClass = superSymbol.fir as FirClass<*>
for (declaration in superClass.declarations) {
when (declaration) {
is FirSimpleFunction -> result += declaration.name
is FirVariable<*> -> result += declaration.name
}
}
superClass.collectCallableNamesFromSupertypes(session, result)
}
is FirTypeAliasSymbol -> {
val superAlias = superSymbol.fir
superAlias.expandedTypeRef.collectCallableNamesFromThisAndSupertypes(session, result)
}
}
}
}
return result
}
internal tailrec fun FirCallableSymbol<*>.deepestOverriddenSymbol(): FirCallableSymbol<*> {
val overriddenSymbol = overriddenSymbol ?: return this
return overriddenSymbol.deepestOverriddenSymbol()
}

View File

@@ -24,15 +24,16 @@ object Fir2IrConverter {
session: FirSession,
firFiles: List<FirFile>,
languageVersionSettings: LanguageVersionSettings,
fakeOverrideMode: FakeOverrideMode = FakeOverrideMode.NORMAL
fakeOverrideMode: FakeOverrideMode = FakeOverrideMode.NORMAL,
signaturer: IdSignatureComposer
): Fir2IrResult {
val moduleDescriptor = FirModuleDescriptor(session)
val symbolTable = SymbolTable()
val symbolTable = SymbolTable(signaturer)
val constantValueGenerator = ConstantValueGenerator(moduleDescriptor, symbolTable)
val typeTranslator = TypeTranslator(symbolTable, languageVersionSettings, moduleDescriptor.builtIns)
constantValueGenerator.typeTranslator = typeTranslator
typeTranslator.constantValueGenerator = constantValueGenerator
val builtIns = IrBuiltIns(moduleDescriptor.builtIns, typeTranslator, symbolTable)
val builtIns = IrBuiltIns(moduleDescriptor.builtIns, typeTranslator, signaturer, symbolTable)
val sourceManager = PsiSourceManager()
val fir2irTransformer = Fir2IrVisitor(session, moduleDescriptor, symbolTable, sourceManager, builtIns, fakeOverrideMode)
val irFiles = mutableListOf<IrFile>()

View File

@@ -14,15 +14,12 @@ import org.jetbrains.kotlin.fir.declarations.impl.FirDefaultPropertyGetter
import org.jetbrains.kotlin.fir.declarations.impl.FirDefaultPropertySetter
import org.jetbrains.kotlin.fir.descriptors.FirModuleDescriptor
import org.jetbrains.kotlin.fir.descriptors.FirPackageFragmentDescriptor
import org.jetbrains.kotlin.fir.expressions.impl.FirExpressionStub
import org.jetbrains.kotlin.fir.psi
import org.jetbrains.kotlin.fir.render
import org.jetbrains.kotlin.fir.resolve.firProvider
import org.jetbrains.kotlin.fir.resolve.firSymbolProvider
import org.jetbrains.kotlin.fir.resolve.getOrPut
import org.jetbrains.kotlin.fir.symbols.impl.FirClassSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirFunctionSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirTypeParameterSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirVariableSymbol
import org.jetbrains.kotlin.fir.resolve.*
import org.jetbrains.kotlin.fir.scopes.impl.FirClassSubstitutionScope
import org.jetbrains.kotlin.fir.symbols.impl.*
import org.jetbrains.kotlin.fir.types.ConeKotlinType
import org.jetbrains.kotlin.fir.types.FirTypeRef
import org.jetbrains.kotlin.fir.types.arrayElementType
@@ -64,6 +61,8 @@ class Fir2IrDeclarationStorage(
private val typeParameterCache = mutableMapOf<FirTypeParameter, IrTypeParameter>()
private val typeParameterCacheForSetter = mutableMapOf<FirTypeParameter, IrTypeParameter>()
private val functionCache = mutableMapOf<FirSimpleFunction, IrSimpleFunction>()
private val constructorCache = mutableMapOf<FirConstructor, IrConstructor>()
@@ -103,8 +102,11 @@ class Fir2IrDeclarationStorage(
irSymbolTable.leaveScope(descriptor)
}
private fun FirTypeRef.toIrType(session: FirSession, declarationStorage: Fir2IrDeclarationStorage) =
toIrType(session, declarationStorage, irBuiltIns)
private fun FirTypeRef.toIrType(
session: FirSession,
declarationStorage: Fir2IrDeclarationStorage,
typeContext: ConversionTypeContext = ConversionTypeContext.DEFAULT
) = toIrType(session, declarationStorage, irBuiltIns, typeContext)
private fun getIrExternalPackageFragment(fqName: FqName): IrExternalPackageFragment {
return fragmentCache.getOrPut(fqName) {
@@ -113,13 +115,15 @@ class Fir2IrDeclarationStorage(
}
}
private fun IrClass.declareThisReceiver() {
enterScope(descriptor)
val thisOrigin = IrDeclarationOrigin.INSTANCE_RECEIVER
val thisType = IrSimpleTypeImpl(symbol, false, emptyList(), emptyList())
val parent = this
private fun IrDeclaration.declareThisReceiverParameter(
parent: IrDeclarationParent,
thisType: IrType,
thisOrigin: IrDeclarationOrigin,
startOffset: Int = this.startOffset,
endOffset: Int = this.endOffset
): IrValueParameter {
val receiverDescriptor = WrappedReceiverParameterDescriptor()
thisReceiver = irSymbolTable.declareValueParameter(
return irSymbolTable.declareValueParameter(
startOffset, endOffset, thisOrigin, receiverDescriptor, thisType
) { symbol ->
IrValueParameterImpl(
@@ -131,32 +135,59 @@ class Fir2IrDeclarationStorage(
receiverDescriptor.bind(this)
}
}
}
private fun IrClass.setThisReceiver() {
enterScope(descriptor)
val typeArguments = this.typeParameters.map {
IrSimpleTypeImpl(it.symbol, false, emptyList(), emptyList())
}
thisReceiver = declareThisReceiverParameter(
parent = this,
thisType = IrSimpleTypeImpl(symbol, false, typeArguments, emptyList()),
thisOrigin = IrDeclarationOrigin.INSTANCE_RECEIVER
)
leaveScope(descriptor)
}
private fun IrClass.declareSupertypesAndTypeParameters(klass: FirClass<*>): IrClass {
for (superTypeRef in klass.superTypeRefs) {
superTypes += superTypeRef.toIrType(session, this@Fir2IrDeclarationStorage)
}
if (klass is FirRegularClass) {
for ((index, typeParameter) in klass.typeParameters.withIndex()) {
typeParameters += getIrTypeParameter(typeParameter, index).apply {
parent = this@declareSupertypesAndTypeParameters
}
private fun preCacheTypeParameters(owner: FirTypeParametersOwner) {
owner.typeParameters.mapIndexed { index, typeParameter ->
getIrTypeParameter(typeParameter, index)
if (owner is FirProperty && owner.isVar) {
getIrTypeParameter(typeParameter, index, ConversionTypeContext.DEFAULT.inSetter())
}
}
}
private fun IrTypeParametersContainer.setTypeParameters(
owner: FirTypeParametersOwner,
typeContext: ConversionTypeContext = ConversionTypeContext.DEFAULT
) {
typeParameters = owner.typeParameters.mapIndexed { index, typeParameter ->
getIrTypeParameter(typeParameter, index, typeContext).apply { parent = this@setTypeParameters }
}
}
private fun IrClass.declareSupertypesAndTypeParameters(klass: FirClass<*>): IrClass {
if (klass is FirRegularClass) {
setTypeParameters(klass)
}
superTypes = klass.superTypeRefs.map { superTypeRef ->
superTypeRef.toIrType(session, this@Fir2IrDeclarationStorage)
}
return this
}
fun getIrClass(klass: FirClass<*>, setParent: Boolean = true): IrClass {
fun getIrClass(klass: FirClass<*>, setParentAndContent: Boolean = true): IrClass {
val regularClass = klass as? FirRegularClass
fun create(): IrClass {
val descriptor = WrappedClassDescriptor()
val origin = IrDeclarationOrigin.DEFINED
val modality = regularClass?.modality ?: Modality.FINAL
val visibility = regularClass?.visibility ?: Visibilities.PUBLIC
return klass.convertWithOffsets { startOffset, endOffset ->
irSymbolTable.declareClass(startOffset, endOffset, origin, descriptor, modality) { symbol ->
irSymbolTable.declareClass(startOffset, endOffset, origin, descriptor, modality, visibility) { symbol ->
IrClassImpl(
startOffset,
endOffset,
@@ -175,7 +206,7 @@ class Fir2IrDeclarationStorage(
isFun = false // TODO FirRegularClass.isFun
).apply {
descriptor.bind(this)
if (setParent && regularClass != null) {
if (setParentAndContent && regularClass != null) {
val classId = regularClass.classId
val parentId = classId.outerClassId
if (parentId != null) {
@@ -189,7 +220,6 @@ class Fir2IrDeclarationStorage(
parent = getIrExternalPackageFragment(packageFqName)
}
}
declareThisReceiver()
}
}
}
@@ -201,11 +231,61 @@ class Fir2IrDeclarationStorage(
val created = create()
localStorage.putLocalClass(klass, created)
created.declareSupertypesAndTypeParameters(klass)
created.setThisReceiver()
return created
}
// NB: klass can be either FirRegularClass or FirAnonymousObject
return classCache.getOrPut(klass as FirRegularClass, { create() }) {
it.declareSupertypesAndTypeParameters(klass)
return classCache.getOrPut(klass as FirRegularClass, { create() }) { irClass ->
irClass.declareSupertypesAndTypeParameters(klass)
irClass.setThisReceiver()
if (setParentAndContent && regularClass != null &&
regularClass.symbol.classId.packageFqName.startsWith(Name.identifier("kotlin"))
) {
// Note: yet this is necessary only for *Range / *Progression classes
// due to BE optimizations (for lowering) that use their first / last / step members
// TODO: think how to refactor this piece of code and/or merge it with similar Fir2IrVisitor fragment
val processedNames = mutableSetOf<Name>()
for (declaration in regularClass.declarations) {
irClass.declarations += when (declaration) {
is FirSimpleFunction -> {
processedNames += declaration.name
getIrFunction(declaration, irClass, shouldLeaveScope = true)
}
is FirProperty -> {
processedNames += declaration.name
getIrProperty(declaration, irClass)
}
is FirConstructor -> getIrConstructor(declaration, irClass, shouldLeaveScope = true)
is FirRegularClass -> getIrClass(declaration)
else -> continue
}
}
val allNames = regularClass.collectCallableNamesFromSupertypes(session)
val scope = regularClass.buildUseSiteMemberScope(session, ScopeSession())
if (scope != null) {
for (name in allNames) {
if (name in processedNames) continue
processedNames += name
scope.processFunctionsByName(name) { functionSymbol ->
if (functionSymbol is FirNamedFunctionSymbol) {
val fakeOverrideSymbol =
FirClassSubstitutionScope.createFakeOverrideFunction(session, functionSymbol.fir, functionSymbol)
irClass.declarations += getIrFunction(fakeOverrideSymbol.fir, irClass, shouldLeaveScope = true)
}
}
scope.processPropertiesByName(name) { propertySymbol ->
if (propertySymbol is FirPropertySymbol) {
val fakeOverrideSymbol =
FirClassSubstitutionScope.createFakeOverrideProperty(session, propertySymbol.fir, propertySymbol)
irClass.declarations += getIrProperty(fakeOverrideSymbol.fir, irClass)
}
}
}
}
for (irDeclaration in irClass.declarations) {
irDeclaration.parent = irClass
}
}
}
}
@@ -213,17 +293,18 @@ class Fir2IrDeclarationStorage(
val descriptor = WrappedClassDescriptor()
val origin = IrDeclarationOrigin.DEFINED
val modality = Modality.FINAL
val visibility = Visibilities.LOCAL
return anonymousObject.convertWithOffsets { startOffset, endOffset ->
irSymbolTable.declareClass(startOffset, endOffset, origin, descriptor, modality) { symbol ->
irSymbolTable.declareClass(startOffset, endOffset, origin, descriptor, modality, visibility) { symbol ->
IrClassImpl(
startOffset, endOffset, origin, symbol,
Name.special("<no name provided>"), anonymousObject.classKind,
Visibilities.LOCAL, modality,
visibility, modality,
isCompanion = false, isInner = false, isData = false,
isExternal = false, isInline = false, isExpect = false, isFun = false
).apply {
descriptor.bind(this)
declareThisReceiver()
setThisReceiver()
}
}
}.declareSupertypesAndTypeParameters(anonymousObject)
@@ -233,17 +314,18 @@ class Fir2IrDeclarationStorage(
val descriptor = WrappedClassDescriptor()
val origin = IrDeclarationOrigin.DEFINED
val modality = Modality.FINAL
val visibility = Visibilities.PRIVATE
return anonymousObject.convertWithOffsets { startOffset, endOffset ->
irSymbolTable.declareClass(startOffset, endOffset, origin, descriptor, modality) { symbol ->
irSymbolTable.declareClass(startOffset, endOffset, origin, descriptor, modality, visibility) { symbol ->
IrClassImpl(
startOffset, endOffset, origin, symbol,
enumEntry.name, anonymousObject.classKind,
Visibilities.LOCAL, modality,
visibility, modality,
isCompanion = false, isInner = false, isData = false,
isExternal = false, isInline = false, isExpect = false, isFun = false
).apply {
descriptor.bind(this)
declareThisReceiver()
setThisReceiver()
if (irParent != null) {
this.parent = irParent
}
@@ -252,8 +334,33 @@ class Fir2IrDeclarationStorage(
}.declareSupertypesAndTypeParameters(anonymousObject)
}
private fun getIrTypeParameter(typeParameter: FirTypeParameter, index: Int = 0): IrTypeParameter {
return typeParameterCache[typeParameter] ?: typeParameter.run {
private fun getIrTypeParameter(
typeParameter: FirTypeParameter,
index: Int = -1,
typeContext: ConversionTypeContext = ConversionTypeContext.DEFAULT
): IrTypeParameter {
// Here transformation is a bit difficult because one FIR property type parameter
// can be transformed to two different type parameters: one for getter and another one for setter
val simpleCachedParameter = typeParameterCache[typeParameter]
if (simpleCachedParameter != null) {
if (typeContext.origin != ConversionTypeOrigin.SETTER) {
return simpleCachedParameter
}
if (index < 0) {
val parent = simpleCachedParameter.parent
if (parent !is IrSimpleFunction || parent.returnType == unitType) {
return simpleCachedParameter
}
}
}
if (typeContext.origin == ConversionTypeOrigin.SETTER) {
typeParameterCacheForSetter[typeParameter]?.let { return it }
}
return typeParameter.run {
// Yet I don't want to enable this requirement because it breaks some tests
// However, if we get here it *should* mean that type parameter index is given explicitly
// At this moment (20.02.2020) this requirement breaks 11/355 Fir2IrText tests
// require(index != -1)
val descriptor = WrappedTypeParameterDescriptor()
val origin = IrDeclarationOrigin.DEFINED
val irTypeParameter =
@@ -261,7 +368,7 @@ class Fir2IrDeclarationStorage(
irSymbolTable.declareGlobalTypeParameter(startOffset, endOffset, origin, descriptor) { symbol ->
IrTypeParameterImpl(
startOffset, endOffset, origin, symbol,
name, index,
name, if (index < 0) 0 else index,
isReified,
variance
).apply {
@@ -271,7 +378,11 @@ class Fir2IrDeclarationStorage(
}
// Cache the type parameter BEFORE processing its bounds/supertypes, to properly handle recursive type bounds.
typeParameterCache[typeParameter] = irTypeParameter
if (typeContext.origin == ConversionTypeOrigin.SETTER) {
typeParameterCacheForSetter[typeParameter] = irTypeParameter
} else {
typeParameterCache[typeParameter] = irTypeParameter
}
bounds.mapTo(irTypeParameter.superTypes) { it.toIrType(session, this@Fir2IrDeclarationStorage) }
irTypeParameter
}
@@ -314,75 +425,76 @@ class Fir2IrDeclarationStorage(
private fun <T : IrFunction> T.declareDefaultSetterParameter(type: IrType): T {
val parent = this
val descriptor = WrappedValueParameterDescriptor()
valueParameters += irSymbolTable.declareValueParameter(
startOffset, endOffset, origin, descriptor, type
) { symbol ->
IrValueParameterImpl(
startOffset, endOffset, IrDeclarationOrigin.DEFINED, symbol,
Name.special("<set-?>"), 0, type,
varargElementType = null,
isCrossinline = false, isNoinline = false
).apply {
this.parent = parent
descriptor.bind(this)
valueParameters = listOf(
irSymbolTable.declareValueParameter(
startOffset, endOffset, origin, descriptor, type
) { symbol ->
IrValueParameterImpl(
startOffset, endOffset, IrDeclarationOrigin.DEFINED, symbol,
Name.special("<set-?>"), 0, type,
varargElementType = null,
isCrossinline = false, isNoinline = false
).apply {
this.parent = parent
descriptor.bind(this)
}
}
}
)
return this
}
private fun <T : IrFunction> T.declareParameters(function: FirFunction<*>?, containingClass: IrClass?, isStatic: Boolean) {
private fun <T : IrFunction> T.declareParameters(
function: FirFunction<*>?,
containingClass: IrClass?,
isStatic: Boolean,
// Can be not-null only for property accessors
parentPropertyReceiverType: FirTypeRef?
) {
val parent = this
if (function is FirSimpleFunction) {
setTypeParameters(function)
}
val forSetter = function is FirPropertyAccessor && function.isSetter
val typeContext = ConversionTypeContext(
definitelyNotNull = false,
origin = if (forSetter) ConversionTypeOrigin.SETTER else ConversionTypeOrigin.DEFAULT
)
if (function is FirDefaultPropertySetter) {
val type = function.valueParameters.first().returnTypeRef.toIrType(session, this@Fir2IrDeclarationStorage)
val type = function.valueParameters.first().returnTypeRef.toIrType(
session, this@Fir2IrDeclarationStorage, ConversionTypeContext.DEFAULT.inSetter()
)
declareDefaultSetterParameter(type)
} else if (function != null) {
for ((index, valueParameter) in function.valueParameters.withIndex()) {
valueParameters += createAndSaveIrParameter(valueParameter, index).apply { this.parent = parent }
valueParameters = function.valueParameters.mapIndexed { index, valueParameter ->
createAndSaveIrParameter(
valueParameter, index,
useStubForDefaultValueStub = function !is FirConstructor || containingClass?.name != Name.identifier("Enum"),
typeContext
).apply {
this.parent = parent
}
}
}
if (function !is FirConstructor) {
val thisOrigin = IrDeclarationOrigin.DEFINED
if (function is FirSimpleFunction) {
for ((index, typeParameter) in function.typeParameters.withIndex()) {
typeParameters += getIrTypeParameter(typeParameter, index).apply { this.parent = parent }
}
}
val receiverTypeRef = function?.receiverTypeRef
val receiverTypeRef = if (function !is FirPropertyAccessor) function?.receiverTypeRef else parentPropertyReceiverType
if (receiverTypeRef != null) {
extensionReceiverParameter = receiverTypeRef.convertWithOffsets { startOffset, endOffset ->
val type = receiverTypeRef.toIrType(session, this@Fir2IrDeclarationStorage)
val receiverDescriptor = WrappedReceiverParameterDescriptor()
irSymbolTable.declareValueParameter(
startOffset, endOffset, thisOrigin,
receiverDescriptor, type
) { symbol ->
IrValueParameterImpl(
startOffset, endOffset, thisOrigin, symbol,
Name.special("<this>"), -1, type,
varargElementType = null, isCrossinline = false, isNoinline = false
).apply {
this.parent = parent
receiverDescriptor.bind(this)
}
}
declareThisReceiverParameter(
parent,
thisType = receiverTypeRef.toIrType(session, this@Fir2IrDeclarationStorage, typeContext),
thisOrigin = thisOrigin,
startOffset = startOffset,
endOffset = endOffset
)
}
}
if (containingClass != null && !isStatic) {
val thisType = containingClass.thisReceiver!!.type
val descriptor = WrappedReceiverParameterDescriptor()
dispatchReceiverParameter = irSymbolTable.declareValueParameter(
startOffset, endOffset, thisOrigin, descriptor,
thisType
) { symbol ->
IrValueParameterImpl(
startOffset, endOffset, thisOrigin, symbol,
Name.special("<this>"), -1, thisType,
varargElementType = null, isCrossinline = false, isNoinline = false
).apply {
this.parent = parent
descriptor.bind(this)
}
}
dispatchReceiverParameter = declareThisReceiverParameter(
parent,
thisType = containingClass.thisReceiver!!.type,
thisOrigin = thisOrigin
)
}
}
}
@@ -392,11 +504,12 @@ class Fir2IrDeclarationStorage(
descriptor: WrappedCallableDescriptor<T>,
irParent: IrDeclarationParent?,
isStatic: Boolean,
shouldLeaveScope: Boolean
shouldLeaveScope: Boolean,
parentPropertyReceiverType: FirTypeRef? = null
): T {
descriptor.bind(this)
enterScope(descriptor)
declareParameters(function, containingClass = irParent as? IrClass, isStatic = isStatic)
declareParameters(function, irParent as? IrClass, isStatic, parentPropertyReceiverType)
if (shouldLeaveScope) {
leaveScope(descriptor)
}
@@ -421,11 +534,13 @@ class Fir2IrDeclarationStorage(
fun create(): IrSimpleFunction {
val containerSource = function.containerSource
val descriptor = containerSource?.let { WrappedFunctionDescriptorWithContainerSource(it) } ?: WrappedSimpleFunctionDescriptor()
val updatedOrigin = if (function.symbol.callableId.isKFunctionInvoke()) IrDeclarationOrigin.FAKE_OVERRIDE else origin
preCacheTypeParameters(function)
return function.convertWithOffsets { startOffset, endOffset ->
enterScope(descriptor)
val result = irSymbolTable.declareSimpleFunction(startOffset, endOffset, origin, descriptor) { symbol ->
IrFunctionImpl(
startOffset, endOffset, origin, symbol,
startOffset, endOffset, updatedOrigin, symbol,
function.name, function.visibility, function.modality!!,
function.returnTypeRef.toIrType(session, this),
isInline = function.isInline,
@@ -433,7 +548,7 @@ class Fir2IrDeclarationStorage(
isTailrec = function.isTailRec,
isSuspend = function.isSuspend,
isExpect = function.isExpect,
isFakeOverride = origin == IrDeclarationOrigin.FAKE_OVERRIDE,
isFakeOverride = updatedOrigin == IrDeclarationOrigin.FAKE_OVERRIDE,
isOperator = function.isOperator
)
}
@@ -456,6 +571,11 @@ class Fir2IrDeclarationStorage(
return if (shouldLeaveScope) cached else cached.enterLocalScope(function)
}
val created = create()
if (function.symbol.callableId.isKFunctionInvoke()) {
(function.symbol.overriddenSymbol as? FirNamedFunctionSymbol)?.let {
created.overriddenSymbols += (it.toFunctionSymbol(this) as IrSimpleFunctionSymbol)
}
}
functionCache[function] = created
return created
}
@@ -521,6 +641,7 @@ class Fir2IrDeclarationStorage(
private fun createIrPropertyAccessor(
propertyAccessor: FirPropertyAccessor?,
property: FirProperty,
correspondingProperty: IrProperty,
propertyType: IrType,
irParent: IrDeclarationParent?,
@@ -529,7 +650,11 @@ class Fir2IrDeclarationStorage(
startOffset: Int,
endOffset: Int
): IrSimpleFunction {
val descriptor = WrappedSimpleFunctionDescriptor()
val propertyDescriptor = correspondingProperty.descriptor
val descriptor =
if (propertyDescriptor is WrappedPropertyDescriptorWithContainerSource)
WrappedFunctionDescriptorWithContainerSource(propertyDescriptor.containerSource)
else WrappedSimpleFunctionDescriptor()
val prefix = if (isSetter) "set" else "get"
return irSymbolTable.declareSimpleFunction(
propertyAccessor?.psi?.startOffsetSkippingComments ?: startOffset,
@@ -546,11 +671,18 @@ class Fir2IrDeclarationStorage(
isFakeOverride = origin == IrDeclarationOrigin.FAKE_OVERRIDE,
isOperator = false
).apply {
setTypeParameters(property, ConversionTypeContext(
definitelyNotNull = false,
origin = if (isSetter) ConversionTypeOrigin.SETTER else ConversionTypeOrigin.DEFAULT
))
if (propertyAccessor == null && isSetter) {
declareDefaultSetterParameter(propertyType)
declareDefaultSetterParameter(
property.returnTypeRef.toIrType(session, this@Fir2IrDeclarationStorage, ConversionTypeContext.DEFAULT.inSetter())
)
}
}.bindAndDeclareParameters(
propertyAccessor, descriptor, irParent, isStatic = irParent !is IrClass, shouldLeaveScope = true
propertyAccessor, descriptor, irParent, isStatic = irParent !is IrClass, shouldLeaveScope = true,
parentPropertyReceiverType = property.receiverTypeRef
).apply {
if (irParent != null) {
parent = irParent
@@ -586,8 +718,9 @@ class Fir2IrDeclarationStorage(
this.correspondingClass = klass
} else if (irParent != null) {
this.initializerExpression =
IrExpressionBodyImpl(IrEnumConstructorCallImpl(startOffset, endOffset, irType, irParent.constructors.first().symbol))
this.initializerExpression = IrExpressionBodyImpl(
IrEnumConstructorCallImpl(startOffset, endOffset, irType, irParent.constructors.first().symbol)
)
}
}
}
@@ -605,6 +738,7 @@ class Fir2IrDeclarationStorage(
return propertyCache.getOrPut(property) {
val containerSource = property.containerSource
val descriptor = containerSource?.let { WrappedPropertyDescriptorWithContainerSource(it) } ?: WrappedPropertyDescriptor()
preCacheTypeParameters(property)
property.convertWithOffsets { startOffset, endOffset ->
enterScope(descriptor)
val result = irSymbolTable.declareProperty(
@@ -626,7 +760,7 @@ class Fir2IrDeclarationStorage(
descriptor.bind(this)
val type = property.returnTypeRef.toIrType(session, this@Fir2IrDeclarationStorage)
getter = createIrPropertyAccessor(
property.getter, this, type, irParent, false,
property.getter, property, this, type, irParent, false,
when {
property.delegate != null -> IrDeclarationOrigin.DELEGATED_PROPERTY_ACCESSOR
property.getter is FirDefaultPropertyGetter -> IrDeclarationOrigin.DEFAULT_PROPERTY_ACCESSOR
@@ -636,7 +770,7 @@ class Fir2IrDeclarationStorage(
)
if (property.isVar) {
setter = createIrPropertyAccessor(
property.setter, this, type, irParent, true,
property.setter, property, this, type, irParent, true,
when {
property.delegate != null -> IrDeclarationOrigin.DELEGATED_PROPERTY_ACCESSOR
property.setter is FirDefaultPropertySetter -> IrDeclarationOrigin.DEFAULT_PROPERTY_ACCESSOR
@@ -678,7 +812,12 @@ class Fir2IrDeclarationStorage(
}
}
private fun createAndSaveIrParameter(valueParameter: FirValueParameter, index: Int = -1): IrValueParameter {
private fun createAndSaveIrParameter(
valueParameter: FirValueParameter,
index: Int = -1,
useStubForDefaultValueStub: Boolean = true,
typeContext: ConversionTypeContext = ConversionTypeContext.DEFAULT
): IrValueParameter {
val descriptor = WrappedValueParameterDescriptor()
val origin = IrDeclarationOrigin.DEFINED
val type = valueParameter.returnTypeRef.toIrType(session, this)
@@ -690,11 +829,16 @@ class Fir2IrDeclarationStorage(
startOffset, endOffset, origin, symbol,
valueParameter.name, index, type,
if (!valueParameter.isVararg) null
else valueParameter.returnTypeRef.coneTypeSafe<ConeKotlinType>()?.arrayElementType(session)?.toIrType(session, this, irBuiltIns),
else valueParameter.returnTypeRef.coneTypeSafe<ConeKotlinType>()?.arrayElementType(session)?.toIrType(
session, this, irBuiltIns, typeContext
),
valueParameter.isCrossinline, valueParameter.isNoinline
).apply {
descriptor.bind(this)
if (valueParameter.defaultValue != null) {
if (valueParameter.defaultValue.let {
it != null && (useStubForDefaultValueStub || it !is FirExpressionStub)
}
) {
this.defaultValue = IrExpressionBodyImpl(
IrErrorExpressionImpl(
UNDEFINED_OFFSET, UNDEFINED_OFFSET, type,
@@ -733,11 +877,15 @@ class Fir2IrDeclarationStorage(
}
}
fun createAndSaveIrVariable(variable: FirVariable<*>): IrVariable {
fun createAndSaveIrVariable(variable: FirVariable<*>, givenOrigin: IrDeclarationOrigin? = null): IrVariable {
val type = variable.returnTypeRef.toIrType(session, this)
// Some temporary variables are produced in RawFirBuilder, but we consistently use special names for them.
val origin =
if (variable.name.isSpecial) IrDeclarationOrigin.IR_TEMPORARY_VARIABLE else IrDeclarationOrigin.DEFINED
val origin = when {
givenOrigin != null -> givenOrigin
variable.name == Name.special("<iterator>") -> IrDeclarationOrigin.FOR_LOOP_ITERATOR
variable.name.isSpecial -> IrDeclarationOrigin.IR_TEMPORARY_VARIABLE
else -> IrDeclarationOrigin.DEFINED
}
val irVariable = variable.convertWithOffsets { startOffset, endOffset ->
declareIrVariable(
startOffset, endOffset, origin,
@@ -763,8 +911,11 @@ class Fir2IrDeclarationStorage(
return irSymbolTable.referenceClass(irClass.descriptor)
}
fun getIrTypeParameterSymbol(firTypeParameterSymbol: FirTypeParameterSymbol): IrTypeParameterSymbol {
val irTypeParameter = getIrTypeParameter(firTypeParameterSymbol.fir)
fun getIrTypeParameterSymbol(
firTypeParameterSymbol: FirTypeParameterSymbol,
typeContext: ConversionTypeContext
): IrTypeParameterSymbol {
val irTypeParameter = getIrTypeParameter(firTypeParameterSymbol.fir, typeContext = typeContext)
return irSymbolTable.referenceTypeParameter(irTypeParameter.descriptor)
}
@@ -836,7 +987,14 @@ class Fir2IrDeclarationStorage(
fun getIrValueSymbol(firVariableSymbol: FirVariableSymbol<*>): IrSymbol {
return when (val firDeclaration = firVariableSymbol.fir) {
is FirEnumEntry -> {
val irEnumEntry = getIrEnumEntry(firDeclaration)
val containingFile = firProvider.getFirCallableContainerFile(firVariableSymbol)
val parentClassSymbol = firVariableSymbol.callableId.classId?.let { firSymbolProvider.getClassLikeSymbolByFqName(it) }
val irParentClass = (parentClassSymbol?.fir as? FirClass<*>)?.let { getIrClass(it, setParentAndContent = false) }
val irEnumEntry = getIrEnumEntry(
firDeclaration,
irParent = irParentClass,
origin = if (containingFile == null) IrDeclarationOrigin.IR_EXTERNAL_DECLARATION_STUB else IrDeclarationOrigin.DEFINED
)
irSymbolTable.referenceEnumEntry(irEnumEntry.descriptor)
}
is FirValueParameter -> {

View File

@@ -12,7 +12,9 @@ import org.jetbrains.kotlin.fir.declarations.impl.FirDefaultPropertyGetter
import org.jetbrains.kotlin.fir.declarations.impl.FirDefaultPropertySetter
import org.jetbrains.kotlin.fir.descriptors.FirModuleDescriptor
import org.jetbrains.kotlin.fir.expressions.*
import org.jetbrains.kotlin.fir.expressions.impl.*
import org.jetbrains.kotlin.fir.expressions.impl.FirElseIfTrueCondition
import org.jetbrains.kotlin.fir.expressions.impl.FirNoReceiverExpression
import org.jetbrains.kotlin.fir.expressions.impl.FirUnitExpression
import org.jetbrains.kotlin.fir.references.FirReference
import org.jetbrains.kotlin.fir.references.FirResolvedNamedReference
import org.jetbrains.kotlin.fir.references.FirSuperReference
@@ -24,6 +26,7 @@ import org.jetbrains.kotlin.fir.resolve.transformers.IntegerLiteralTypeApproxima
import org.jetbrains.kotlin.fir.scopes.impl.FirClassSubstitutionScope
import org.jetbrains.kotlin.fir.scopes.impl.FirIntegerOperator
import org.jetbrains.kotlin.fir.symbols.AccessorSymbol
import org.jetbrains.kotlin.fir.symbols.StandardClassIds
import org.jetbrains.kotlin.fir.symbols.impl.*
import org.jetbrains.kotlin.fir.types.*
import org.jetbrains.kotlin.fir.visitors.FirDefaultVisitor
@@ -44,12 +47,9 @@ import org.jetbrains.kotlin.ir.symbols.*
import org.jetbrains.kotlin.ir.types.*
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi2ir.PsiSourceManager
import org.jetbrains.kotlin.types.AbstractStrictEqualityTypeChecker
import java.util.*
class Fir2IrVisitor(
@@ -163,9 +163,8 @@ class Fir2IrVisitor(
declarations += irDeclaration
}
file.annotations.forEach {
val irCall = it.accept(this@Fir2IrVisitor, data) as? IrConstructorCall ?: return@forEach
annotations += irCall
annotations = file.annotations.mapNotNull {
it.accept(this@Fir2IrVisitor, data) as? IrConstructorCall
}
}
}
@@ -184,44 +183,12 @@ class Fir2IrVisitor(
return irEnumEntry.setParentByParentStack()
}
private fun FirTypeRef.collectCallableNamesFromThisAndSupertypes(result: MutableList<Name> = mutableListOf()): List<Name> {
if (this is FirResolvedTypeRef) {
val superType = type
if (superType is ConeClassLikeType) {
when (val superSymbol = superType.lookupTag.toSymbol(this@Fir2IrVisitor.session)) {
is FirClassSymbol -> {
val superClass = superSymbol.fir as FirClass<*>
for (declaration in superClass.declarations) {
when (declaration) {
is FirSimpleFunction -> result += declaration.name
is FirVariable<*> -> result += declaration.name
}
}
superClass.collectCallableNamesFromSupertypes(result)
}
is FirTypeAliasSymbol -> {
val superAlias = superSymbol.fir
superAlias.expandedTypeRef.collectCallableNamesFromThisAndSupertypes(result)
}
}
}
}
return result
}
private fun FirClass<*>.collectCallableNamesFromSupertypes(result: MutableList<Name> = mutableListOf()): List<Name> {
for (superTypeRef in superTypeRefs) {
superTypeRef.collectCallableNamesFromThisAndSupertypes(result)
}
return result
}
private fun FirClass<*>.getPrimaryConstructorIfAny(): FirConstructor? =
declarations.filterIsInstance<FirConstructor>().firstOrNull()?.takeIf { it.isPrimary }
private fun IrClass.addFakeOverrides(klass: FirClass<*>, processedCallableNames: MutableList<Name>) {
if (fakeOverrideMode == FakeOverrideMode.NONE) return
val superTypesCallableNames = klass.collectCallableNamesFromSupertypes()
val superTypesCallableNames = klass.collectCallableNamesFromSupertypes(session)
val useSiteMemberScope = (klass as? FirRegularClass)?.buildUseSiteMemberScope(session, ScopeSession()) ?: return
for (name in superTypesCallableNames) {
if (name in processedCallableNames) continue
@@ -239,7 +206,7 @@ class Fir2IrVisitor(
declarations += irFunction.setParentByParentStack().withFunction {
setFunctionContent(irFunction.descriptor, originalFunction, firOverriddenSymbol = baseSymbol)
}
} else if (fakeOverrideMode != FakeOverrideMode.SUBSTITUTION) {
} else if (fakeOverrideMode != FakeOverrideMode.SUBSTITUTION && originalFunction.visibility != Visibilities.PRIVATE) {
// Trivial fake override case
val fakeOverrideSymbol =
FirClassSubstitutionScope.createFakeOverrideFunction(session, originalFunction, functionSymbol)
@@ -267,7 +234,7 @@ class Fir2IrVisitor(
declarations += irProperty.setParentByParentStack().withProperty {
setPropertyContent(irProperty.descriptor, originalProperty, firOverriddenSymbol = baseSymbol)
}
} else if (fakeOverrideMode != FakeOverrideMode.SUBSTITUTION) {
} else if (fakeOverrideMode != FakeOverrideMode.SUBSTITUTION && originalProperty.visibility != Visibilities.PRIVATE) {
// Trivial fake override case
val fakeOverrideSymbol =
FirClassSubstitutionScope.createFakeOverrideProperty(session, originalProperty, propertySymbol)
@@ -305,9 +272,8 @@ class Fir2IrVisitor(
}
}
addFakeOverrides(klass, processedCallableNames)
klass.annotations.forEach {
val irCall = it.accept(this@Fir2IrVisitor, null) as? IrConstructorCall ?: return@forEach
annotations += irCall
annotations = klass.annotations.mapNotNull {
it.accept(this@Fir2IrVisitor, null) as? IrConstructorCall
}
}
if (irPrimaryConstructor != null) {
@@ -317,7 +283,7 @@ class Fir2IrVisitor(
}
override fun visitRegularClass(regularClass: FirRegularClass, data: Any?): IrElement {
return declarationStorage.getIrClass(regularClass, setParent = false)
return declarationStorage.getIrClass(regularClass, setParentAndContent = false)
.setParentByParentStack()
.withParent {
setClassContent(regularClass)
@@ -352,7 +318,7 @@ class Fir2IrVisitor(
val containingClass = if (firOverriddenSymbol == null || firFunctionSymbol == null) {
lastClass
} else {
val callableId = firFunctionSymbol.callableId
val callableId = firFunctionSymbol.deepestOverriddenSymbol().callableId
val ownerClassId = callableId.classId
if (ownerClassId == null) {
lastClass
@@ -362,7 +328,7 @@ class Fir2IrVisitor(
lastClass
} else {
val firClass = classLikeSymbol.fir as FirClass<*>
declarationStorage.getIrClass(firClass, setParent = false)
declarationStorage.getIrClass(firClass, setParentAndContent = false)
}
}
}
@@ -377,7 +343,7 @@ class Fir2IrVisitor(
if (firOverriddenSymbol != null && this is IrSimpleFunction && firFunctionSymbol != null) {
val overriddenSymbol = declarationStorage.getIrFunctionSymbol(firOverriddenSymbol)
if (overriddenSymbol is IrSimpleFunctionSymbol) {
overriddenSymbols += overriddenSymbol
overriddenSymbols = listOf(overriddenSymbol)
}
}
var body = firFunction?.body?.convertToIrBlockBody()
@@ -438,32 +404,31 @@ class Fir2IrVisitor(
}
}
private fun FirDelegatedConstructorCall.toIrDelegatingConstructorCall(): IrDelegatingConstructorCall? {
val constructedClassSymbol = with(typeContext) {
(constructedTypeRef as FirResolvedTypeRef).type.typeConstructor()
} as? FirClassSymbol<*> ?: return null
private fun FirDelegatedConstructorCall.toIrDelegatingConstructorCall(): IrCallWithIndexedArgumentsBase? {
val constructedIrType = constructedTypeRef.toIrType(this@Fir2IrVisitor.session, declarationStorage)
// TODO: find delegated constructor correctly
val classId = constructedClassSymbol.classId
var constructorSymbol: FirConstructorSymbol? = null
constructedClassSymbol.buildUseSiteMemberScope(this@Fir2IrVisitor.session, ScopeSession())!!.processFunctionsByName(
classId.shortClassName
) {
when {
it !is FirConstructorSymbol -> {
}
arguments.size <= it.fir.valueParameters.size && constructorSymbol == null -> {
constructorSymbol = it
}
}
}
val foundConstructorSymbol = constructorSymbol ?: return null
val constructorSymbol = (this.calleeReference as? FirResolvedNamedReference)?.resolvedSymbol as? FirConstructorSymbol
?: return null
return convertWithOffsets { startOffset, endOffset ->
IrDelegatingConstructorCallImpl(
startOffset, endOffset,
constructedIrType,
declarationStorage.getIrFunctionSymbol(foundConstructorSymbol) as IrConstructorSymbol
).apply {
val irConstructorSymbol = declarationStorage.getIrFunctionSymbol(constructorSymbol) as IrConstructorSymbol
if (constructorSymbol.fir.isFromEnumClass || constructorSymbol.fir.returnTypeRef.isEnum) {
IrEnumConstructorCallImpl(
startOffset, endOffset,
constructedIrType,
irConstructorSymbol
).apply {
val typeArguments = (constructedTypeRef as? FirResolvedTypeRef)?.type?.typeArguments
if (typeArguments?.isNotEmpty() == true) {
val irType = (typeArguments.first() as ConeKotlinTypeProjection).type.toIrType(session, declarationStorage, irBuiltIns)
putTypeArgument(0, irType)
}
}
} else {
IrDelegatingConstructorCallImpl(
startOffset, endOffset,
constructedIrType,
irConstructorSymbol
)
}.apply {
for ((index, argument) in arguments.withIndex()) {
val argumentExpression = argument.toIrExpression()
putValueArgument(index, argumentExpression)
@@ -503,9 +468,14 @@ class Fir2IrVisitor(
private fun visitLocalVariable(variable: FirProperty): IrElement {
assert(variable.isLocal)
val irVariable = declarationStorage.createAndSaveIrVariable(variable)
val initializer = variable.initializer
val isNextVariable = initializer is FirFunctionCall &&
initializer.resolvedNamedFunctionSymbol()?.callableId?.isIteratorNext() == true &&
variable.source.psi?.parent is KtForExpression
val irVariable = declarationStorage.createAndSaveIrVariable(
variable, if (isNextVariable) IrDeclarationOrigin.FOR_LOOP_VARIABLE else null
)
return irVariable.setParentByParentStack().apply {
val initializer = variable.initializer
if (initializer != null) {
this.initializer = initializer.toIrExpression()
}
@@ -581,18 +551,18 @@ class Fir2IrVisitor(
property.getter, this, propertyType, property.getter is FirDefaultPropertyGetter, property.getter == null
)
getter?.apply {
overriddenProperty?.owner?.getter?.symbol?.let { overriddenSymbols += it }
overriddenProperty?.owner?.getter?.symbol?.let { overriddenSymbols = listOf(it) }
}
if (property.isVar) {
setter?.setPropertyAccessorContent(
property.setter, this, propertyType, property.setter is FirDefaultPropertySetter, property.setter == null
)
setter?.apply {
overriddenProperty?.owner?.setter?.symbol?.let { overriddenSymbols += it }
overriddenProperty?.owner?.setter?.symbol?.let { overriddenSymbols = listOf(it) }
}
}
property.annotations.forEach {
annotations += it.accept(this@Fir2IrVisitor, null) as IrConstructorCall
annotations = property.annotations.mapNotNull {
it.accept(this@Fir2IrVisitor, null) as? IrConstructorCall
}
declarationStorage.leaveScope(descriptor)
return this
@@ -705,7 +675,13 @@ class Fir2IrVisitor(
is FirPropertyFromParameterResolvedNamedReference -> IrStatementOrigin.INITIALIZE_PROPERTY_FROM_PARAMETER
is FirResolvedNamedReference -> when (resolvedSymbol) {
is AccessorSymbol, is SyntheticPropertySymbol -> IrStatementOrigin.GET_PROPERTY
is FirNamedFunctionSymbol -> if (resolvedSymbol.callableId.isInvoke()) IrStatementOrigin.INVOKE else null
is FirNamedFunctionSymbol -> when {
resolvedSymbol.callableId.isInvoke() -> IrStatementOrigin.INVOKE
source.psi is KtForExpression && resolvedSymbol.callableId.isIteratorNext() -> IrStatementOrigin.FOR_LOOP_NEXT
source.psi is KtForExpression && resolvedSymbol.callableId.isIteratorHasNext() -> IrStatementOrigin.FOR_LOOP_HAS_NEXT
source.psi is KtForExpression && resolvedSymbol.callableId.isIterator() -> IrStatementOrigin.FOR_LOOP_ITERATOR
else -> null
}
else -> null
}
else -> null
@@ -732,7 +708,7 @@ class Fir2IrVisitor(
symbol is IrPropertySymbol && symbol.isBound -> {
val getter = symbol.owner.getter
if (getter != null) {
IrCallImpl(startOffset, endOffset, type, getter.symbol)
IrCallImpl(startOffset, endOffset, type, getter.symbol, origin = IrStatementOrigin.GET_PROPERTY)
} else {
IrErrorCallExpressionImpl(startOffset, endOffset, type, "No getter found for ${calleeReference.render()}")
}
@@ -809,13 +785,13 @@ class Fir2IrVisitor(
}
}
private fun IrExpression.applyTypeArguments(call: FirFunctionCall): IrExpression {
private fun IrExpression.applyTypeArguments(access: FirQualifiedAccess): IrExpression {
return when (this) {
is IrCallWithIndexedArgumentsBase -> {
val argumentsCount = call.typeArguments.size
val argumentsCount = access.typeArguments.size
if (argumentsCount <= typeArgumentsCount) {
apply {
for ((index, argument) in call.typeArguments.withIndex()) {
for ((index, argument) in access.typeArguments.withIndex()) {
val argumentIrType = (argument as FirTypeProjectionWithVariance).typeRef.toIrType(
session,
declarationStorage
@@ -852,7 +828,7 @@ class Fir2IrVisitor(
it is FirAnonymousObject || it is FirRegularClass && it.classKind == ClassKind.OBJECT
}
firClass?.convertWithOffsets { startOffset, endOffset ->
val irClass = declarationStorage.getIrClass(firClass, setParent = false)
val irClass = declarationStorage.getIrClass(firClass, setParentAndContent = false)
IrGetObjectValueImpl(startOffset, endOffset, irClass.defaultType, irClass.symbol)
}
}
@@ -871,7 +847,8 @@ class Fir2IrVisitor(
val ownerFunction = symbol.owner
if (ownerFunction.dispatchReceiverParameter != null) {
dispatchReceiver = qualifiedAccess.findIrDispatchReceiver()
} else if (ownerFunction.extensionReceiverParameter != null) {
}
if (ownerFunction.extensionReceiverParameter != null) {
extensionReceiver = qualifiedAccess.findIrExtensionReceiver()
}
this
@@ -887,32 +864,39 @@ class Fir2IrVisitor(
}
}
override fun visitFunctionCall(functionCall: FirFunctionCall, data: Any?): IrElement {
override fun visitFunctionCall(functionCall: FirFunctionCall, data: Any?): IrExpression {
val convertibleCall = if (functionCall.toResolvedCallableSymbol()?.fir is FirIntegerOperator) {
functionCall.copy().transformSingle(integerApproximator, null)
} else {
checkIfInvoke(functionCall)
val resolvedSymbol = functionCall.resolvedNamedFunctionSymbol()
if (resolvedSymbol != null) {
functionCall.replaceCalleeReferenceWithOverridden(resolvedSymbol)
} else {
functionCall
}
}
return convertibleCall.toIrExpression(convertibleCall.typeRef)
.applyCallArguments(convertibleCall).applyTypeArguments(convertibleCall).applyReceivers(convertibleCall)
}
// Use the generic invoke method in Function classes, to match bridges generated by the backend.
private fun checkIfInvoke(functionCall: FirFunctionCall): FirFunctionCall {
if (functionCall !is FirFunctionCallImpl) {
return functionCall
}
val calleeReference = (functionCall.calleeReference as? FirResolvedNamedReference) ?: return functionCall
val resolvedSymbol = (calleeReference.resolvedSymbol as? FirNamedFunctionSymbol) ?: return functionCall
if (resolvedSymbol.callableId.isInvoke()) {
functionCall.calleeReference =
buildResolvedNamedReference {
private fun FirFunctionCall.resolvedNamedFunctionSymbol(): FirNamedFunctionSymbol? {
val calleeReference = (calleeReference as? FirResolvedNamedReference) ?: return null
return calleeReference.resolvedSymbol as? FirNamedFunctionSymbol
}
// Use the generic invoke & next methods to match bridges generated by the backend.
private fun FirFunctionCall.replaceCalleeReferenceWithOverridden(resolvedSymbol: FirNamedFunctionSymbol): FirFunctionCall {
val overriddenSymbol = resolvedSymbol.overriddenSymbol ?: return this
if (resolvedSymbol.callableId.isInvoke() || resolvedSymbol.callableId.isIteratorNext()) {
return copy(
calleeReference = buildResolvedNamedReference {
source = calleeReference.source
name = calleeReference.name
this.resolvedSymbol = resolvedSymbol.overriddenSymbol!!
this.resolvedSymbol = overriddenSymbol
}
)
}
return functionCall
return this
}
override fun visitAnnotationCall(annotationCall: FirAnnotationCall, data: Any?): IrElement {
@@ -920,7 +904,8 @@ class Fir2IrVisitor(
}
override fun visitQualifiedAccessExpression(qualifiedAccessExpression: FirQualifiedAccessExpression, data: Any?): IrElement {
return qualifiedAccessExpression.toIrExpression(qualifiedAccessExpression.typeRef).applyReceivers(qualifiedAccessExpression)
return qualifiedAccessExpression.toIrExpression(qualifiedAccessExpression.typeRef)
.applyTypeArguments(qualifiedAccessExpression).applyReceivers(qualifiedAccessExpression)
}
override fun visitThisReceiverExpression(thisReceiverExpression: FirThisReceiverExpression, data: Any?): IrElement {
@@ -931,7 +916,7 @@ class Fir2IrVisitor(
it is FirAnonymousObject || it is FirRegularClass && it.classKind == ClassKind.OBJECT
}
if (firObject != null) {
val irObject = declarationStorage.getIrClass(firObject, setParent = false)
val irObject = declarationStorage.getIrClass(firObject, setParentAndContent = false)
if (irObject != classStack.lastOrNull()) {
return thisReceiverExpression.convertWithOffsets { startOffset, endOffset ->
IrGetObjectValueImpl(startOffset, endOffset, irObject.defaultType, irObject.symbol)
@@ -952,7 +937,7 @@ class Fir2IrVisitor(
override fun visitExpressionWithSmartcast(expressionWithSmartcast: FirExpressionWithSmartcast, data: Any?): IrElement {
// Generate the expression with the original type and then cast it to the smart cast type.
val value = expressionWithSmartcast.toIrExpression(expressionWithSmartcast.originalType).applyReceivers(expressionWithSmartcast)
val value = expressionWithSmartcast.originalExpression.toIrExpression()
val castType = expressionWithSmartcast.typeRef.toIrType(session, declarationStorage)
if (value.type == castType) return value
return IrTypeOperatorCallImpl(
@@ -1032,7 +1017,7 @@ class Fir2IrVisitor(
}
is IrVariableSymbol -> {
IrSetVariableImpl(
startOffset, endOffset, symbol.owner.type, symbol, variableAssignment.rValue.toIrExpression(), null
startOffset, endOffset, irBuiltIns.unitType, symbol, variableAssignment.rValue.toIrExpression(), null
)
}
else -> generateErrorCallExpression(startOffset, endOffset, calleeReference)
@@ -1110,9 +1095,32 @@ class Fir2IrVisitor(
}
}
private fun FirBlock.mapToIrStatements(): List<IrStatement?> {
val irRawStatements = statements.map { it.toIrStatement() }
val result = mutableListOf<IrStatement?>()
var missNext = false
for ((index, irRawStatement) in irRawStatements.withIndex()) {
if (missNext) {
missNext = false
continue
} else if (irRawStatement is IrVariable && irRawStatement.origin == IrDeclarationOrigin.FOR_LOOP_ITERATOR) {
missNext = true
val irNextStatement = irRawStatements[index + 1]!!
result += IrBlockImpl(
irRawStatement.startOffset, irNextStatement.endOffset,
(irNextStatement as IrExpression).type, IrStatementOrigin.FOR_LOOP,
listOf(irRawStatement, irNextStatement)
)
} else {
result += irRawStatement
}
}
return result
}
private fun FirBlock.convertToIrBlockBody(): IrBlockBody {
return convertWithOffsets { startOffset, endOffset ->
val irStatements = statements.map { it.toIrStatement() }
val irStatements = mapToIrStatements()
IrBlockBodyImpl(
startOffset, endOffset,
if (irStatements.isNotEmpty()) {
@@ -1125,7 +1133,7 @@ class Fir2IrVisitor(
}
}
private fun FirBlock.convertToIrExpressionOrBlock(): IrExpression {
private fun FirBlock.convertToIrExpressionOrBlock(origin: IrStatementOrigin? = null): IrExpression {
if (statements.size == 1) {
val firStatement = statements.single()
if (firStatement is FirExpression) {
@@ -1136,8 +1144,8 @@ class Fir2IrVisitor(
(statements.lastOrNull() as? FirExpression)?.typeRef?.toIrType(this@Fir2IrVisitor.session, declarationStorage) ?: unitType
return convertWithOffsets { startOffset, endOffset ->
IrBlockImpl(
startOffset, endOffset, type, null,
statements.mapNotNull { it.toIrStatement() }
startOffset, endOffset, type, origin,
mapToIrStatements().filterNotNull()
)
}
}
@@ -1239,15 +1247,13 @@ class Fir2IrVisitor(
override fun visitWhileLoop(whileLoop: FirWhileLoop, data: Any?): IrElement {
return whileLoop.convertWithOffsets { startOffset, endOffset ->
IrWhileLoopImpl(
startOffset, endOffset, unitType,
if (whileLoop.psi is KtForExpression) IrStatementOrigin.FOR_LOOP_INNER_WHILE
else IrStatementOrigin.WHILE_LOOP
).apply {
val origin = if (whileLoop.psi is KtForExpression) IrStatementOrigin.FOR_LOOP_INNER_WHILE
else IrStatementOrigin.WHILE_LOOP
IrWhileLoopImpl(startOffset, endOffset, unitType, origin).apply {
loopMap[whileLoop] = this
label = whileLoop.label?.name
condition = whileLoop.condition.toIrExpression()
body = whileLoop.block.convertToIrExpressionOrBlock()
body = whileLoop.block.convertToIrExpressionOrBlock(origin)
loopMap.remove(whileLoop)
}
}
@@ -1307,50 +1313,72 @@ class Fir2IrVisitor(
}
}
private fun generateComparisonCall(
startOffset: Int, endOffset: Int, operation: FirOperation, first: FirExpression, second: FirExpression
): IrExpression {
val firstType = first.typeRef as? FirResolvedTypeRef
val secondType = second.typeRef as? FirResolvedTypeRef
if (firstType == null || secondType == null) {
return IrErrorCallExpressionImpl(startOffset, endOffset, booleanType, "Comparison of arguments with unresolved types")
override fun visitComparisonExpression(comparisonExpression: FirComparisonExpression, data: Any?): IrElement {
return comparisonExpression.convertWithOffsets { startOffset, endOffset ->
generateComparisonCall(startOffset, endOffset, comparisonExpression)
}
if (!AbstractStrictEqualityTypeChecker.strictEqualTypes(typeContext, firstType.type, secondType.type)) {
return IrErrorCallExpressionImpl(
startOffset, endOffset, booleanType,
"Comparison of arguments with different types: ${firstType.type.render()}, ${secondType.type.render()}"
}
private fun generateComparisonCall(
startOffset: Int, endOffset: Int,
comparisonExpression: FirComparisonExpression
): IrExpression {
val operation = comparisonExpression.operation
fun fallbackToRealCall(): IrExpression {
val (symbol, origin) = getSymbolAndOriginForComparison(operation, irBuiltIns.intType.classifierOrFail)
return primitiveOp2(
startOffset, endOffset,
symbol!!,
booleanType,
origin,
visitFunctionCall(comparisonExpression.compareToCall, null),
IrConstImpl.int(startOffset, endOffset, irBuiltIns.intType, 0)
)
}
// TODO: it's temporary hack which should be refactored
val simpleType = when (val classId = (firstType.type as? ConeClassLikeType)?.lookupTag?.classId) {
ClassId(FqName("kotlin"), FqName("Long"), false) -> irBuiltIns.longType
ClassId(FqName("kotlin"), FqName("Int"), false) -> irBuiltIns.intType
ClassId(FqName("kotlin"), FqName("Float"), false) -> irBuiltIns.floatType
ClassId(FqName("kotlin"), FqName("Double"), false) -> irBuiltIns.doubleType
ClassId(FqName("kotlin"), FqName("Char"), false) -> irBuiltIns.charType
else -> {
return IrErrorCallExpressionImpl(
startOffset, endOffset, booleanType, "Comparison of arguments with unsupported type: $classId"
)
}
val comparisonInfo = comparisonExpression.inferPrimitiveNumericComparisonInfo() ?: return fallbackToRealCall()
val comparisonType = comparisonInfo.comparisonType
// Currently inferPrimitiveNumericComparisonInfo returns null for different primitive values
// TODO: Support different primitive types as well and fix inferPrimitiveNumericComparisonInfo
require(comparisonInfo.leftPrimitiveType == comparisonInfo.rightPrimitiveType && comparisonInfo.leftType == comparisonInfo.rightType) {
"Contract for inferPrimitiveNumericComparisonInfo is violated"
}
val classifier = simpleType.classifierOrFail
val (symbol, origin) = when (operation) {
val simpleType = when ((comparisonType.type as? ConeClassLikeType)?.lookupTag?.classId) {
StandardClassIds.Long -> irBuiltIns.longType
StandardClassIds.Int -> irBuiltIns.intType
StandardClassIds.Float -> irBuiltIns.floatType
StandardClassIds.Double -> irBuiltIns.doubleType
StandardClassIds.Char -> irBuiltIns.charType
else -> return fallbackToRealCall()
}
val (symbol, origin) = getSymbolAndOriginForComparison(operation, simpleType.classifierOrFail)
return primitiveOp2(
startOffset, endOffset, symbol!!, booleanType, origin,
comparisonExpression.left.toIrExpression(), comparisonExpression.right.toIrExpression()
)
}
private fun getSymbolAndOriginForComparison(
operation: FirOperation,
classifier: IrClassifierSymbol
): Pair<IrSimpleFunctionSymbol?, IrStatementOriginImpl> {
return when (operation) {
FirOperation.LT -> irBuiltIns.lessFunByOperandType[classifier] to IrStatementOrigin.LT
FirOperation.GT -> irBuiltIns.greaterFunByOperandType[classifier] to IrStatementOrigin.GT
FirOperation.LT_EQ -> irBuiltIns.lessOrEqualFunByOperandType[classifier] to IrStatementOrigin.LTEQ
FirOperation.GT_EQ -> irBuiltIns.greaterOrEqualFunByOperandType[classifier] to IrStatementOrigin.GTEQ
else -> throw AssertionError("Unexpected comparison operation: $operation")
else -> error("Unexpected comparison operation: $operation")
}
return primitiveOp2(startOffset, endOffset, symbol!!, booleanType, origin, first.toIrExpression(), second.toIrExpression())
}
private fun generateOperatorCall(
startOffset: Int, endOffset: Int, operation: FirOperation, arguments: List<FirExpression>
): IrExpression {
if (operation in FirOperation.COMPARISONS) {
return generateComparisonCall(startOffset, endOffset, operation, arguments[0], arguments[1])
}
val (type, symbol, origin) = when (operation) {
FirOperation.EQ -> Triple(booleanType, irBuiltIns.eqeqSymbol, IrStatementOrigin.EQEQ)
FirOperation.NOT_EQ -> Triple(booleanType, irBuiltIns.eqeqSymbol, IrStatementOrigin.EXCLEQ)
@@ -1363,7 +1391,8 @@ class Fir2IrVisitor(
FirOperation.MINUS_ASSIGN, FirOperation.TIMES_ASSIGN,
FirOperation.DIV_ASSIGN, FirOperation.REM_ASSIGN,
FirOperation.IS, FirOperation.NOT_IS,
FirOperation.AS, FirOperation.SAFE_AS -> {
FirOperation.AS, FirOperation.SAFE_AS
-> {
TODO("Should not be here: incompatible operation in FirOperatorCall: $operation")
}
}
@@ -1452,9 +1481,8 @@ class Fir2IrVisitor(
}
override fun visitResolvedQualifier(resolvedQualifier: FirResolvedQualifier, data: Any?): IrElement {
val classId = resolvedQualifier.classId
if (classId != null) {
val classSymbol = ConeClassLikeLookupTagImpl(classId).toSymbol(session)!!
val classSymbol = resolvedQualifier.symbol
if (classSymbol != null) {
return resolvedQualifier.convertWithOffsets { startOffset, endOffset ->
IrGetObjectValueImpl(
startOffset, endOffset,

View File

@@ -0,0 +1,58 @@
/*
* 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.fir.backend
import org.jetbrains.kotlin.fir.*
import org.jetbrains.kotlin.fir.expressions.FirComparisonExpression
import org.jetbrains.kotlin.fir.expressions.FirExpression
import org.jetbrains.kotlin.fir.resolve.firSymbolProvider
import org.jetbrains.kotlin.fir.types.*
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
class PrimitiveConeNumericComparisonInfo(
val comparisonType: ConeKotlinType,
val leftPrimitiveType: ConeClassLikeType,
val rightPrimitiveType: ConeClassLikeType,
val leftType: ConeKotlinType,
val rightType: ConeKotlinType
)
val FirComparisonExpression.left: FirExpression
get() = compareToCall.explicitReceiver ?: error("There should be an explicit receiver for ${compareToCall.render()}")
val FirComparisonExpression.right: FirExpression
get() = compareToCall.arguments.getOrNull(0) ?: error("There should be a first arg for ${compareToCall.render()}")
fun FirComparisonExpression.inferPrimitiveNumericComparisonInfo(): PrimitiveConeNumericComparisonInfo? {
val leftType = left.typeRef.coneTypeSafe<ConeKotlinType>() ?: return null
val rightType = right.typeRef.coneTypeSafe<ConeKotlinType>() ?: return null
val leftPrimitiveOrNullableType = leftType.getPrimitiveTypeOrSupertype() ?: return null
val rightPrimitiveOrNullableType = rightType.getPrimitiveTypeOrSupertype() ?: return null
val leftPrimitiveType = leftPrimitiveOrNullableType.withNullability(ConeNullability.NOT_NULL)
val rightPrimitiveType = rightPrimitiveOrNullableType.withNullability(ConeNullability.NOT_NULL)
// TODO: Support different types with coercion
if (leftPrimitiveType != rightPrimitiveType) return null
val leastCommonType = rightPrimitiveType
return PrimitiveConeNumericComparisonInfo(
leastCommonType,
leftPrimitiveType, rightPrimitiveType,
leftPrimitiveOrNullableType, rightPrimitiveOrNullableType
)
}
private fun ConeKotlinType.getPrimitiveTypeOrSupertype(): ConeClassLikeType? =
when {
this is ConeTypeParameterType ->
this.lookupTag.typeParameterSymbol.fir.bounds.firstNotNullResult {
it.coneTypeSafe<ConeKotlinType>()?.getPrimitiveTypeOrSupertype()
}
this is ConeClassLikeType && isPrimitiveNumberType() ->
this
else ->
null
}

View File

@@ -30,7 +30,7 @@ class FirPackageFragmentDescriptor(override val fqName: FqName, val moduleDescri
}
override fun <R : Any?, D : Any?> accept(visitor: DeclarationDescriptorVisitor<R, D>?, data: D): R {
TODO("not implemented")
return visitor?.visitPackageFragmentDescriptor(this, data) as R
}
override fun getSource(): SourceElement {
@@ -38,7 +38,7 @@ class FirPackageFragmentDescriptor(override val fqName: FqName, val moduleDescri
}
override fun acceptVoid(visitor: DeclarationDescriptorVisitor<Void, Void>?) {
TODO("not implemented")
visitor?.visitPackageFragmentDescriptor(this, null)
}
override val annotations: Annotations

View File

@@ -216,11 +216,6 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/annotations/varargInAnnotationParameter.kt");
}
@TestMetadata("wrongAnnotationArgumentInCtor.kt")
public void testWrongAnnotationArgumentInCtor() throws Exception {
runTest("compiler/testData/codegen/box/annotations/wrongAnnotationArgumentInCtor.kt");
}
@TestMetadata("compiler/testData/codegen/box/annotations/annotatedLambda")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
@@ -1701,6 +1696,24 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
}
}
@TestMetadata("compiler/testData/codegen/box/builderInference")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public static class BuilderInference extends AbstractFirBlackBoxCodegenTest {
private void runTest(String testDataFilePath) throws Exception {
KotlinTestUtils.runTestWithCustomIgnoreDirective(this::doTest, TargetBackend.JVM_IR, testDataFilePath, "// IGNORE_BACKEND_FIR: ");
}
public void testAllFilesPresentInBuilderInference() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/codegen/box/builderInference"), Pattern.compile("^(.+)\\.kt$"), null, TargetBackend.JVM_IR, true);
}
@TestMetadata("lackOfNullCheckOnNullableInsideBuild.kt")
public void testLackOfNullCheckOnNullableInsideBuild() throws Exception {
runTest("compiler/testData/codegen/box/builderInference/lackOfNullCheckOnNullableInsideBuild.kt");
}
}
@TestMetadata("compiler/testData/codegen/box/builtinStubMethods")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
@@ -1955,6 +1968,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/callableReference/classesAreSynthetic.kt");
}
@TestMetadata("nested.kt")
public void testNested() throws Exception {
runTest("compiler/testData/codegen/box/callableReference/nested.kt");
}
@TestMetadata("compiler/testData/codegen/box/callableReference/bound")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
@@ -2148,6 +2166,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
KotlinTestUtils.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/codegen/box/callableReference/function"), Pattern.compile("^(.+)\\.kt$"), null, TargetBackend.JVM_IR, true);
}
@TestMetadata("argumentTypes.kt")
public void testArgumentTypes() throws Exception {
runTest("compiler/testData/codegen/box/callableReference/function/argumentTypes.kt");
}
@TestMetadata("booleanNotIntrinsic.kt")
public void testBooleanNotIntrinsic() throws Exception {
runTest("compiler/testData/codegen/box/callableReference/function/booleanNotIntrinsic.kt");
@@ -2795,6 +2818,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/callableReference/varargAndDefaults/simpleEmptyVararg.kt");
}
@TestMetadata("unboundReferences.kt")
public void testUnboundReferences() throws Exception {
runTest("compiler/testData/codegen/box/callableReference/varargAndDefaults/unboundReferences.kt");
}
@TestMetadata("varargViewedAsArray.kt")
public void testVarargViewedAsArray() throws Exception {
runTest("compiler/testData/codegen/box/callableReference/varargAndDefaults/varargViewedAsArray.kt");
@@ -3438,6 +3466,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/classes/initializerBlockDImpl.kt");
}
@TestMetadata("initializerBlockResetToDefault.kt")
public void testInitializerBlockResetToDefault() throws Exception {
runTest("compiler/testData/codegen/box/classes/initializerBlockResetToDefault.kt");
}
@TestMetadata("innerClass.kt")
public void testInnerClass() throws Exception {
runTest("compiler/testData/codegen/box/classes/innerClass.kt");
@@ -5982,6 +6015,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/coroutines/builderInferenceAndGenericArrayAcessCall.kt");
}
@TestMetadata("captureMutableLocalVariableInsideCoroutineBlock.kt")
public void testCaptureMutableLocalVariableInsideCoroutineBlock() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/captureMutableLocalVariableInsideCoroutineBlock.kt");
}
@TestMetadata("capturedVarInSuspendLambda.kt")
public void testCapturedVarInSuspendLambda_1_3() throws Exception {
runTestWithPackageReplacement("compiler/testData/codegen/box/coroutines/capturedVarInSuspendLambda.kt", "kotlin.coroutines");
@@ -6027,6 +6065,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTestWithPackageReplacement("compiler/testData/codegen/box/coroutines/crossInlineWithCapturedOuterReceiver.kt", "kotlin.coroutines");
}
@TestMetadata("defaultParametersInSuspendWithJvmOverloads.kt")
public void testDefaultParametersInSuspendWithJvmOverloads() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/defaultParametersInSuspendWithJvmOverloads.kt");
}
@TestMetadata("defaultParametersInSuspend.kt")
public void testDefaultParametersInSuspend_1_3() throws Exception {
runTestWithPackageReplacement("compiler/testData/codegen/box/coroutines/defaultParametersInSuspend.kt", "kotlin.coroutines");
@@ -6047,6 +6090,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTestWithPackageReplacement("compiler/testData/codegen/box/coroutines/emptyClosure.kt", "kotlin.coroutines");
}
@TestMetadata("emptyCommonConstraintSystemForCoroutineInferenceCall.kt")
public void testEmptyCommonConstraintSystemForCoroutineInferenceCall() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/emptyCommonConstraintSystemForCoroutineInferenceCall.kt");
}
@TestMetadata("epam.kt")
public void testEpam_1_3() throws Exception {
runTestWithPackageReplacement("compiler/testData/codegen/box/coroutines/epam.kt", "kotlin.coroutines");
@@ -6357,6 +6405,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTestWithPackageReplacement("compiler/testData/codegen/box/coroutines/suspendFunImportedFromObject.kt", "kotlin.coroutines");
}
@TestMetadata("suspendImplBridge.kt")
public void testSuspendImplBridge() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/suspendImplBridge.kt");
}
@TestMetadata("suspendInCycle.kt")
public void testSuspendInCycle_1_3() throws Exception {
runTestWithPackageReplacement("compiler/testData/codegen/box/coroutines/suspendInCycle.kt", "kotlin.coroutines");
@@ -6382,6 +6435,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/coroutines/suspendJavaOverrides.kt");
}
@TestMetadata("suspendReturningPlatformType.kt")
public void testSuspendReturningPlatformType() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/suspendReturningPlatformType.kt");
}
@TestMetadata("suspensionInsideSafeCallWithElvis.kt")
public void testSuspensionInsideSafeCallWithElvis_1_3() throws Exception {
runTestWithPackageReplacement("compiler/testData/codegen/box/coroutines/suspensionInsideSafeCallWithElvis.kt", "kotlin.coroutines");
@@ -6443,6 +6501,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
KotlinTestUtils.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/codegen/box/coroutines/bridges"), Pattern.compile("^(.+)\\.kt$"), null, TargetBackend.JVM_IR, true);
}
@TestMetadata("interfaceSpecialization.kt")
public void testInterfaceSpecialization_1_3() throws Exception {
runTestWithPackageReplacement("compiler/testData/codegen/box/coroutines/bridges/interfaceSpecialization.kt", "kotlin.coroutines");
}
@TestMetadata("lambdaWithLongReceiver.kt")
public void testLambdaWithLongReceiver_1_3() throws Exception {
runTestWithPackageReplacement("compiler/testData/codegen/box/coroutines/bridges/lambdaWithLongReceiver.kt", "kotlin.coroutines");
@@ -7597,6 +7660,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
KotlinTestUtils.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/codegen/box/coroutines/tailCallOptimizations/unit"), Pattern.compile("^(.+)\\.kt$"), null, TargetBackend.JVM_IR, true);
}
@TestMetadata("functionReference.kt")
public void testFunctionReference() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/tailCallOptimizations/unit/functionReference.kt");
}
@TestMetadata("override.kt")
public void testOverride() throws Exception {
runTest("compiler/testData/codegen/box/coroutines/tailCallOptimizations/unit/override.kt");
@@ -8181,6 +8249,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/defaultArguments/superCallCheck.kt");
}
@TestMetadata("superCallHandlerOrder.kt")
public void testSuperCallHandlerOrder() throws Exception {
runTest("compiler/testData/codegen/box/defaultArguments/superCallHandlerOrder.kt");
}
@TestMetadata("useNextParamInLambda.kt")
public void testUseNextParamInLambda() throws Exception {
runTest("compiler/testData/codegen/box/defaultArguments/useNextParamInLambda.kt");
@@ -8719,6 +8792,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/delegatedProperty/useReflectionOnKProperty.kt");
}
@TestMetadata("valByMapDelegatedProperty.kt")
public void testValByMapDelegatedProperty() throws Exception {
runTest("compiler/testData/codegen/box/delegatedProperty/valByMapDelegatedProperty.kt");
}
@TestMetadata("valInInnerClass.kt")
public void testValInInnerClass() throws Exception {
runTest("compiler/testData/codegen/box/delegatedProperty/valInInnerClass.kt");
@@ -10525,11 +10603,21 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/funInterface/castFromAny.kt");
}
@TestMetadata("funInterfaceInheritance.kt")
public void testFunInterfaceInheritance() throws Exception {
runTest("compiler/testData/codegen/box/funInterface/funInterfaceInheritance.kt");
}
@TestMetadata("inlinedSamWrapper.kt")
public void testInlinedSamWrapper() throws Exception {
runTest("compiler/testData/codegen/box/funInterface/inlinedSamWrapper.kt");
}
@TestMetadata("multimodule.kt")
public void testMultimodule() throws Exception {
runTest("compiler/testData/codegen/box/funInterface/multimodule.kt");
}
@TestMetadata("nullableSam.kt")
public void testNullableSam() throws Exception {
runTest("compiler/testData/codegen/box/funInterface/nullableSam.kt");
@@ -10540,6 +10628,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/funInterface/partialSam.kt");
}
@TestMetadata("primitiveConversions.kt")
public void testPrimitiveConversions() throws Exception {
runTest("compiler/testData/codegen/box/funInterface/primitiveConversions.kt");
}
@TestMetadata("receiverEvaluatedOnce.kt")
public void testReceiverEvaluatedOnce() throws Exception {
runTest("compiler/testData/codegen/box/funInterface/receiverEvaluatedOnce.kt");
@@ -11469,6 +11562,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/increment/genericClassWithGetSet.kt");
}
@TestMetadata("kt36956.kt")
public void testKt36956() throws Exception {
runTest("compiler/testData/codegen/box/increment/kt36956.kt");
}
@TestMetadata("memberExtOnLong.kt")
public void testMemberExtOnLong() throws Exception {
runTest("compiler/testData/codegen/box/increment/memberExtOnLong.kt");
@@ -11562,11 +11660,26 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/inference/builderInference.kt");
}
@TestMetadata("builderInferenceLeakingVariable.kt")
public void testBuilderInferenceLeakingVariable() throws Exception {
runTest("compiler/testData/codegen/box/inference/builderInferenceLeakingVariable.kt");
}
@TestMetadata("capturedStarProjection.kt")
public void testCapturedStarProjection() throws Exception {
runTest("compiler/testData/codegen/box/inference/capturedStarProjection.kt");
}
@TestMetadata("coercionToUnitWithLastLambdaExpression.kt")
public void testCoercionToUnitWithLastLambdaExpression() throws Exception {
runTest("compiler/testData/codegen/box/inference/coercionToUnitWithLastLambdaExpression.kt");
}
@TestMetadata("coerctionToUnitForLastExpressionWithStarProjection.kt")
public void testCoerctionToUnitForLastExpressionWithStarProjection() throws Exception {
runTest("compiler/testData/codegen/box/inference/coerctionToUnitForLastExpressionWithStarProjection.kt");
}
@TestMetadata("integerLiteralTypeInLamdaReturnType.kt")
public void testIntegerLiteralTypeInLamdaReturnType() throws Exception {
runTest("compiler/testData/codegen/box/inference/integerLiteralTypeInLamdaReturnType.kt");
@@ -11587,6 +11700,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/inference/kt35684.kt");
}
@TestMetadata("kt36446.kt")
public void testKt36446() throws Exception {
runTest("compiler/testData/codegen/box/inference/kt36446.kt");
}
@TestMetadata("lastExpressionOfLambdaWithNothingConstraint.kt")
public void testLastExpressionOfLambdaWithNothingConstraint() throws Exception {
runTest("compiler/testData/codegen/box/inference/lastExpressionOfLambdaWithNothingConstraint.kt");
@@ -11610,6 +11728,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/inlineClasses/annotatedMemberExtensionProperty.kt");
}
@TestMetadata("anySuperCall.kt")
public void testAnySuperCall() throws Exception {
runTest("compiler/testData/codegen/box/inlineClasses/anySuperCall.kt");
}
@TestMetadata("boundCallableReferencePassedToInlineFunction.kt")
public void testBoundCallableReferencePassedToInlineFunction() throws Exception {
runTest("compiler/testData/codegen/box/inlineClasses/boundCallableReferencePassedToInlineFunction.kt");
@@ -11890,6 +12013,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/inlineClasses/fieldNameClash.kt");
}
@TestMetadata("genericInlineClassSynthMembers.kt")
public void testGenericInlineClassSynthMembers() throws Exception {
runTest("compiler/testData/codegen/box/inlineClasses/genericInlineClassSynthMembers.kt");
}
@TestMetadata("inlineClassAsLastExpressionInInLambda.kt")
public void testInlineClassAsLastExpressionInInLambda() throws Exception {
runTest("compiler/testData/codegen/box/inlineClasses/inlineClassAsLastExpressionInInLambda.kt");
@@ -12150,6 +12278,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/inlineClasses/kt28920_javaPrimitiveType.kt");
}
@TestMetadata("kt33119.kt")
public void testKt33119() throws Exception {
runTest("compiler/testData/codegen/box/inlineClasses/kt33119.kt");
}
@TestMetadata("kt34268.kt")
public void testKt34268() throws Exception {
runTest("compiler/testData/codegen/box/inlineClasses/kt34268.kt");
@@ -12598,6 +12731,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/inlineClasses/defaultParameterValues/inlineClassPrimaryConstructor.kt");
}
@TestMetadata("inlineClassPrimaryConstructorWithInlineClassValue.kt")
public void testInlineClassPrimaryConstructorWithInlineClassValue() throws Exception {
runTest("compiler/testData/codegen/box/inlineClasses/defaultParameterValues/inlineClassPrimaryConstructorWithInlineClassValue.kt");
}
@TestMetadata("inlineClassSecondaryConstructor.kt")
public void testInlineClassSecondaryConstructor() throws Exception {
runTest("compiler/testData/codegen/box/inlineClasses/defaultParameterValues/inlineClassSecondaryConstructor.kt");
@@ -12852,6 +12990,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/inlineClasses/interfaceMethodCalls/genericMethodWithInlineClassOverride.kt");
}
@TestMetadata("interfaceSuperCall.kt")
public void testInterfaceSuperCall() throws Exception {
runTest("compiler/testData/codegen/box/inlineClasses/interfaceMethodCalls/interfaceSuperCall.kt");
}
@TestMetadata("overriddenDefaultInterfaceMethodCall.kt")
public void testOverriddenDefaultInterfaceMethodCall() throws Exception {
runTest("compiler/testData/codegen/box/inlineClasses/interfaceMethodCalls/overriddenDefaultInterfaceMethodCall.kt");
@@ -13311,6 +13454,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/intrinsics/nonShortCircuitAnd.kt");
}
@TestMetadata("nullPlusString.kt")
public void testNullPlusString() throws Exception {
runTest("compiler/testData/codegen/box/intrinsics/nullPlusString.kt");
}
@TestMetadata("prefixIncDec.kt")
public void testPrefixIncDec() throws Exception {
runTest("compiler/testData/codegen/box/intrinsics/prefixIncDec.kt");
@@ -16329,6 +16477,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/objects/initializationOrder.kt");
}
@TestMetadata("initializerBlockResetToDefault.kt")
public void testInitializerBlockResetToDefault() throws Exception {
runTest("compiler/testData/codegen/box/objects/initializerBlockResetToDefault.kt");
}
@TestMetadata("interfaceCompanion.kt")
public void testInterfaceCompanion() throws Exception {
runTest("compiler/testData/codegen/box/objects/interfaceCompanion.kt");
@@ -17232,11 +17385,6 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/platformTypes/primitives/equalsNull.kt");
}
@TestMetadata("equalsNull_withExplicitFlag.kt")
public void testEqualsNull_withExplicitFlag() throws Exception {
runTest("compiler/testData/codegen/box/platformTypes/primitives/equalsNull_withExplicitFlag.kt");
}
@TestMetadata("hashCode.kt")
public void testHashCode() throws Exception {
runTest("compiler/testData/codegen/box/platformTypes/primitives/hashCode.kt");
@@ -18054,6 +18202,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/properties/genericPropertyMultiModule.kt");
}
@TestMetadata("genericWithSameName.kt")
public void testGenericWithSameName() throws Exception {
runTest("compiler/testData/codegen/box/properties/genericWithSameName.kt");
}
@TestMetadata("initOrderMultiModule.kt")
public void testInitOrderMultiModule() throws Exception {
runTest("compiler/testData/codegen/box/properties/initOrderMultiModule.kt");
@@ -22884,6 +23037,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
public void testSignatureOfSimpleInnerSimpleOuter() throws Exception {
runTest("compiler/testData/codegen/box/reflection/genericSignature/signatureOfSimpleInnerSimpleOuter.kt");
}
@TestMetadata("suspendFunctionLiteralGenericSignature.kt")
public void testSuspendFunctionLiteralGenericSignature() throws Exception {
runTest("compiler/testData/codegen/box/reflection/genericSignature/suspendFunctionLiteralGenericSignature.kt");
}
}
@TestMetadata("compiler/testData/codegen/box/reflection/isInstance")
@@ -24890,6 +25048,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/reified/reifiedInlineIntoNonInlineableLambda.kt");
}
@TestMetadata("reifiedIntersectionType.kt")
public void testReifiedIntersectionType() throws Exception {
runTest("compiler/testData/codegen/box/reified/reifiedIntersectionType.kt");
}
@TestMetadata("safecast.kt")
public void testSafecast() throws Exception {
runTest("compiler/testData/codegen/box/reified/safecast.kt");
@@ -25720,6 +25883,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/specialBuiltins/removeSetInt.kt");
}
@TestMetadata("specialBridgeModality.kt")
public void testSpecialBridgeModality() throws Exception {
runTest("compiler/testData/codegen/box/specialBuiltins/specialBridgeModality.kt");
}
@TestMetadata("throwable.kt")
public void testThrowable() throws Exception {
runTest("compiler/testData/codegen/box/specialBuiltins/throwable.kt");
@@ -25994,6 +26162,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/strings/stringBuilderAppend.kt");
}
@TestMetadata("stringFromJavaPlus.kt")
public void testStringFromJavaPlus() throws Exception {
runTest("compiler/testData/codegen/box/strings/stringFromJavaPlus.kt");
}
@TestMetadata("stringPlusOnlyWorksOnString.kt")
public void testStringPlusOnlyWorksOnString() throws Exception {
runTest("compiler/testData/codegen/box/strings/stringPlusOnlyWorksOnString.kt");
@@ -26142,6 +26315,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/super/multipleSuperTraits.kt");
}
@TestMetadata("superCallToNonGenericImplThroughGenericDefaultImpls.kt")
public void testSuperCallToNonGenericImplThroughGenericDefaultImpls() throws Exception {
runTest("compiler/testData/codegen/box/super/superCallToNonGenericImplThroughGenericDefaultImpls.kt");
}
@TestMetadata("traitproperty.kt")
public void testTraitproperty() throws Exception {
runTest("compiler/testData/codegen/box/super/traitproperty.kt");
@@ -26541,6 +26719,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/traits/diamondPropertyAccessors.kt");
}
@TestMetadata("doubleDiamond.kt")
public void testDoubleDiamond() throws Exception {
runTest("compiler/testData/codegen/box/traits/doubleDiamond.kt");
}
@TestMetadata("genericMethod.kt")
public void testGenericMethod() throws Exception {
runTest("compiler/testData/codegen/box/traits/genericMethod.kt");
@@ -26641,6 +26824,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/traits/multiple.kt");
}
@TestMetadata("multipleImplFromJava.kt")
public void testMultipleImplFromJava() throws Exception {
runTest("compiler/testData/codegen/box/traits/multipleImplFromJava.kt");
}
@TestMetadata("noPrivateDelegation.kt")
public void testNoPrivateDelegation() throws Exception {
runTest("compiler/testData/codegen/box/traits/noPrivateDelegation.kt");
@@ -26651,6 +26839,11 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/traits/privateInterfaceMethod.kt");
}
@TestMetadata("receiverOfIntersectionType.kt")
public void testReceiverOfIntersectionType() throws Exception {
runTest("compiler/testData/codegen/box/traits/receiverOfIntersectionType.kt");
}
@TestMetadata("syntheticAccessor.kt")
public void testSyntheticAccessor() throws Exception {
runTest("compiler/testData/codegen/box/traits/syntheticAccessor.kt");

View File

@@ -11,6 +11,7 @@ import com.intellij.psi.PsiElementFinder
import com.intellij.psi.search.GlobalSearchScope
import junit.framework.TestCase
import org.jetbrains.kotlin.asJava.finder.JavaElementFinder
import org.jetbrains.kotlin.backend.common.serialization.signature.IdSignatureDescriptor
import org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM
import org.jetbrains.kotlin.config.languageVersionSettings
import org.jetbrains.kotlin.fir.backend.Fir2IrConverter
@@ -19,6 +20,7 @@ import org.jetbrains.kotlin.fir.resolve.firProvider
import org.jetbrains.kotlin.fir.resolve.impl.FirProviderImpl
import org.jetbrains.kotlin.fir.resolve.transformers.FirTotalResolveTransformer
import org.jetbrains.kotlin.ir.AbstractIrTextTestCase
import org.jetbrains.kotlin.ir.backend.jvm.serialization.JvmManglerDesc
import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
import java.io.File
@@ -92,8 +94,10 @@ abstract class AbstractFir2IrTextTest : AbstractIrTextTestCase() {
}
}
val signaturer = IdSignatureDescriptor(JvmManglerDesc())
return Fir2IrConverter.createModuleFragment(
session, firFiles, myEnvironment.configuration.languageVersionSettings
session, firFiles, myEnvironment.configuration.languageVersionSettings, signaturer = signaturer
).irModuleFragment
}
}

View File

@@ -131,6 +131,11 @@ public class Fir2IrTextTestGenerated extends AbstractFir2IrTextTest {
runTest("compiler/testData/ir/irText/classes/enumWithSecondaryCtor.kt");
}
@TestMetadata("fakeOverridesForJavaStaticMembers.kt")
public void testFakeOverridesForJavaStaticMembers() throws Exception {
runTest("compiler/testData/ir/irText/classes/fakeOverridesForJavaStaticMembers.kt");
}
@TestMetadata("implicitNotNullOnDelegatedImplementation.kt")
public void testImplicitNotNullOnDelegatedImplementation() throws Exception {
runTest("compiler/testData/ir/irText/classes/implicitNotNullOnDelegatedImplementation.kt");
@@ -161,6 +166,11 @@ public class Fir2IrTextTestGenerated extends AbstractFir2IrTextTest {
runTest("compiler/testData/ir/irText/classes/inlineClass.kt");
}
@TestMetadata("inlineClassSyntheticMethods.kt")
public void testInlineClassSyntheticMethods() throws Exception {
runTest("compiler/testData/ir/irText/classes/inlineClassSyntheticMethods.kt");
}
@TestMetadata("innerClass.kt")
public void testInnerClass() throws Exception {
runTest("compiler/testData/ir/irText/classes/innerClass.kt");
@@ -1052,6 +1062,11 @@ public class Fir2IrTextTestGenerated extends AbstractFir2IrTextTest {
runTest("compiler/testData/ir/irText/expressions/kt30796.kt");
}
@TestMetadata("kt36956.kt")
public void testKt36956() throws Exception {
runTest("compiler/testData/ir/irText/expressions/kt36956.kt");
}
@TestMetadata("lambdaInCAO.kt")
public void testLambdaInCAO() throws Exception {
runTest("compiler/testData/ir/irText/expressions/lambdaInCAO.kt");
@@ -1485,6 +1500,11 @@ public class Fir2IrTextTestGenerated extends AbstractFir2IrTextTest {
KotlinTestUtils.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/ir/irText/expressions/funInterface"), Pattern.compile("^(.+)\\.kt$"), null, true);
}
@TestMetadata("arrayAsVarargAfterSamArgument_fi.kt")
public void testArrayAsVarargAfterSamArgument_fi() throws Exception {
runTest("compiler/testData/ir/irText/expressions/funInterface/arrayAsVarargAfterSamArgument_fi.kt");
}
@TestMetadata("basicFunInterfaceConversion.kt")
public void testBasicFunInterfaceConversion() throws Exception {
runTest("compiler/testData/ir/irText/expressions/funInterface/basicFunInterfaceConversion.kt");
@@ -1528,6 +1548,11 @@ public class Fir2IrTextTestGenerated extends AbstractFir2IrTextTest {
KotlinTestUtils.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/ir/irText/expressions/sam"), Pattern.compile("^(.+)\\.kt$"), null, true);
}
@TestMetadata("arrayAsVarargAfterSamArgument.kt")
public void testArrayAsVarargAfterSamArgument() throws Exception {
runTest("compiler/testData/ir/irText/expressions/sam/arrayAsVarargAfterSamArgument.kt");
}
@TestMetadata("genericSamProjectedOut.kt")
public void testGenericSamProjectedOut() throws Exception {
runTest("compiler/testData/ir/irText/expressions/sam/genericSamProjectedOut.kt");
@@ -1807,11 +1832,26 @@ public class Fir2IrTextTestGenerated extends AbstractFir2IrTextTest {
runTest("compiler/testData/ir/irText/types/asOnPlatformType.kt");
}
@TestMetadata("castsInsideCoroutineInference.kt")
public void testCastsInsideCoroutineInference() throws Exception {
runTest("compiler/testData/ir/irText/types/castsInsideCoroutineInference.kt");
}
@TestMetadata("coercionToUnitInLambdaReturnValue.kt")
public void testCoercionToUnitInLambdaReturnValue() throws Exception {
runTest("compiler/testData/ir/irText/types/coercionToUnitInLambdaReturnValue.kt");
}
@TestMetadata("genericPropertyReferenceType.kt")
public void testGenericPropertyReferenceType() throws Exception {
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");
@@ -1842,11 +1882,21 @@ 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");
}
@TestMetadata("receiverOfIntersectionType.kt")
public void testReceiverOfIntersectionType() throws Exception {
runTest("compiler/testData/ir/irText/types/receiverOfIntersectionType.kt");
}
@TestMetadata("smartCastOnFakeOverrideReceiver.kt")
public void testSmartCastOnFakeOverrideReceiver() throws Exception {
runTest("compiler/testData/ir/irText/types/smartCastOnFakeOverrideReceiver.kt");
@@ -1862,6 +1912,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

@@ -23,7 +23,6 @@ import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.psi
import org.jetbrains.kotlin.fir.resolve.firProvider
import org.jetbrains.kotlin.fir.resolve.fullyExpandedType
import org.jetbrains.kotlin.fir.resolve.toSymbol
@@ -33,7 +32,6 @@ import org.jetbrains.kotlin.fir.symbols.impl.FirClassSymbol
import org.jetbrains.kotlin.fir.types.*
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.jvm.JvmPrimitiveType
import org.jetbrains.kotlin.resolve.jvm.KotlinFinderMarker
@@ -68,8 +66,7 @@ class FirJavaElementFinder(
firProvider.getFirClassifierByFqName(classId) as? FirRegularClass
?: return null
val ktFile = firClass.psi?.containingFile as? KtFile ?: return null
val fileStub = createJavaFileStub(classId.packageFqName, listOf(ktFile))
val fileStub = createJavaFileStub(classId.packageFqName, psiManager)
return buildStub(firClass, fileStub).psi
}
@@ -187,20 +184,16 @@ private fun newTypeParameterList(parent: StubElement<*>, parameters: List<Pair<S
}
}
private fun createJavaFileStub(packageFqName: FqName, files: Collection<KtFile>): PsiJavaFileStub {
private fun createJavaFileStub(packageFqName: FqName, psiManager: PsiManager): PsiJavaFileStub {
val javaFileStub = PsiJavaFileStubImpl(packageFqName.asString(), /*compiled = */true)
javaFileStub.psiFactory = ClsStubPsiFactory.INSTANCE
val fakeFile = object : ClsFileImpl(files.first().viewProvider) {
val fakeFile = object : ClsFileImpl(DummyHolderViewProvider(psiManager)) {
override fun getStub() = javaFileStub
override fun getPackageName() = packageFqName.asString()
override fun isPhysical() = false
override fun getText(): String {
return files.singleOrNull()?.text ?: super.getText()
}
}
javaFileStub.psi = fakeFile
@@ -239,7 +232,7 @@ private fun ConeClassLikeType.mapToCanonicalNoExpansionString(session: FirSessio
if (lookupTag.classId == StandardClassIds.Array) {
return when (val typeProjection = typeArguments[0]) {
is ConeStarProjection -> CommonClassNames.JAVA_LANG_OBJECT
is ConeTypedProjection -> {
is ConeKotlinTypeProjection -> {
if (typeProjection.kind == ProjectionKind.IN)
CommonClassNames.JAVA_LANG_VOID
else
@@ -266,10 +259,10 @@ private fun ConeClassLikeType.mapToCanonicalNoExpansionString(session: FirSessio
}
private fun ConeKotlinTypeProjection.mapToCanonicalString(session: FirSession): String {
private fun ConeTypeProjection.mapToCanonicalString(session: FirSession): String {
return when (this) {
is ConeStarProjection -> "?"
is ConeTypedProjection -> {
is ConeKotlinTypeProjection -> {
val wildcard = when (kind) {
ProjectionKind.STAR -> error("Should be handled in the case above")
ProjectionKind.IN -> "? super "

View File

@@ -8,6 +8,7 @@ package org.jetbrains.kotlin.fir.java
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.declarations.FirClass
import org.jetbrains.kotlin.fir.declarations.FirRegularClass
import org.jetbrains.kotlin.fir.declarations.classId
import org.jetbrains.kotlin.fir.java.declarations.FirJavaClass
import org.jetbrains.kotlin.fir.java.scopes.JavaClassEnhancementScope
import org.jetbrains.kotlin.fir.java.scopes.JavaClassUseSiteMemberScope
@@ -76,7 +77,9 @@ class JavaScopeProvider(
// We need JavaClassEnhancementScope here to have already enhanced signatures from supertypes
val scope = buildJavaEnhancementScope(useSiteSession, symbol, scopeSession, visitedSymbols)
visitedSymbols.remove(symbol)
useSiteSuperType.wrapSubstitutionScopeIfNeed(useSiteSession, scope, symbol.fir, scopeSession)
useSiteSuperType.wrapSubstitutionScopeIfNeed(
useSiteSession, scope, symbol.fir, scopeSession, regularClass.classId
)
} else {
null
}
@@ -111,7 +114,15 @@ class JavaScopeProvider(
)
)
}
return FirStaticScope(enhancementScope)
return FirOnlyCallablesScope(FirStaticScope(enhancementScope))
}
override fun getNestedClassifierScope(klass: FirClass<*>, useSiteSession: FirSession, scopeSession: ScopeSession): FirScope? {
return lazyNestedClassifierScope(
klass.classId,
(klass as FirJavaClass).existingNestedClassifierNames,
useSiteSession.firSymbolProvider
)
}
}

View File

@@ -11,7 +11,7 @@ import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.Visibility
import org.jetbrains.kotlin.fir.*
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.declarations.FirRegularClass
import org.jetbrains.kotlin.fir.declarations.FirTypeParameter
import org.jetbrains.kotlin.fir.declarations.addDefaultBoundIfNecessary
@@ -19,14 +19,17 @@ import org.jetbrains.kotlin.fir.declarations.builder.FirTypeParameterBuilder
import org.jetbrains.kotlin.fir.java.declarations.*
import org.jetbrains.kotlin.fir.resolve.AbstractFirSymbolProvider
import org.jetbrains.kotlin.fir.resolve.constructType
import org.jetbrains.kotlin.fir.generateValueOfFunction
import org.jetbrains.kotlin.fir.generateValuesFunction
import org.jetbrains.kotlin.fir.java.declarations.FirJavaClass
import org.jetbrains.kotlin.fir.resolve.scopes.wrapScopeWithJvmMapped
import org.jetbrains.kotlin.fir.scopes.FirScope
import org.jetbrains.kotlin.fir.scopes.impl.lazyNestedClassifierScope
import org.jetbrains.kotlin.fir.scopes.impl.nestedClassifierScope
import org.jetbrains.kotlin.fir.symbols.CallableId
import org.jetbrains.kotlin.fir.symbols.impl.*
import org.jetbrains.kotlin.fir.types.ConeNullability
import org.jetbrains.kotlin.fir.types.builder.buildResolvedTypeRef
import org.jetbrains.kotlin.fir.toFirSourceElement
import org.jetbrains.kotlin.fir.types.impl.ConeTypeParameterTypeImpl
import org.jetbrains.kotlin.load.java.JavaClassFinder
import org.jetbrains.kotlin.load.java.JvmAnnotationNames
@@ -73,39 +76,52 @@ class JavaSymbolProvider(
}
}
private fun JavaTypeParameter.toFirTypeParameter(javaTypeParameterStack: JavaTypeParameterStack): FirTypeParameterBuilder {
javaTypeParameterStack.getBuilder(this)?.let { return it }
private fun JavaTypeParameter.toFirTypeParameterSymbol(
javaTypeParameterStack: JavaTypeParameterStack
): Pair<FirTypeParameterSymbol, Boolean> {
val stored = javaTypeParameterStack.safeGet(this)
if (stored != null) return stored to true
val firSymbol = FirTypeParameterSymbol()
javaTypeParameterStack.add(this, firSymbol)
return firSymbol to false
}
private fun JavaTypeParameter.toFirTypeParameter(
firSymbol: FirTypeParameterSymbol,
javaTypeParameterStack: JavaTypeParameterStack
): FirTypeParameter {
return FirTypeParameterBuilder().apply {
session = this@JavaSymbolProvider.session
name = this@toFirTypeParameter.name
this.session = this@JavaSymbolProvider.session
this.name = this@toFirTypeParameter.name
symbol = firSymbol
variance = INVARIANT
isReified = false
}.also {
javaTypeParameterStack.add(this, it)
}
addBounds(this@toFirTypeParameter, javaTypeParameterStack)
}.build()
}
private fun FirTypeParameterBuilder.addBounds(
javaTypeParameter: JavaTypeParameter,
stack: JavaTypeParameterStack,
stack: JavaTypeParameterStack
) {
for (upperBound in javaTypeParameter.upperBounds) {
bounds += upperBound.toFirResolvedTypeRef(this@JavaSymbolProvider.session, stack, nullability = ConeNullability.NULLABLE)
bounds += upperBound.toFirResolvedTypeRef(
this@JavaSymbolProvider.session,
stack,
isForSupertypes = false,
forTypeParameterBounds = true
)
}
addDefaultBoundIfNecessary()
}
private fun List<JavaTypeParameter>.convertTypeParameters(stack: JavaTypeParameterStack): List<FirTypeParameter> {
return this
.map { it.toFirTypeParameter(stack) }
.mapIndexed { index, typeParameterBuilder ->
if (typeParameterBuilder.bounds.isEmpty()) {
typeParameterBuilder.addBounds(this[index], stack)
}
typeParameterBuilder.build()
}
return map { it.toFirTypeParameterSymbol(stack) }.mapIndexed { index, (symbol, initialized) ->
// This nasty logic is required, because type parameter bound can refer other type parameter from the list
// So we have to create symbols first, and type parameters themselves after them
if (initialized) symbol.fir
else this[index].toFirTypeParameter(symbol, stack)
}
}
override fun getClassLikeSymbolByFqName(classId: ClassId): FirRegularClassSymbol? {
@@ -122,7 +138,10 @@ class JavaSymbolProvider(
classId,
{
val foundClass = findClass(classId, content)
if (foundClass == null || foundClass.annotations.any { it.classId?.asSingleFqName() == JvmAnnotationNames.METADATA_FQ_NAME }) {
if (foundClass == null || foundClass.annotations.any {
it.classId?.asSingleFqName() == JvmAnnotationNames.METADATA_FQ_NAME
}
) {
null to null
} else {
FirRegularClassSymbol(classId) to foundClass
@@ -136,13 +155,13 @@ class JavaSymbolProvider(
if (!isTopLevel) {
val parentId = ClassId(classId.packageFqName, parentFqName, false)
val parentClassSymbol = getClassLikeSymbolByFqName(parentId)
val parentStack = parentClassTypeParameterStackCache[parentClassSymbol] ?:
(parentClassSymbol?.fir as? FirJavaClass)?.javaTypeParameterStack
val parentStack = parentClassTypeParameterStackCache[parentClassSymbol]
?: (parentClassSymbol?.fir as? FirJavaClass)?.javaTypeParameterStack
if (parentStack != null) {
javaTypeParameterStack.addStack(parentStack)
}
}
buildJavaClass {
val firJavaClass = buildJavaClass {
source = (javaClass as? JavaElementImpl<*>)?.psi?.toFirSourceElement()
session = this@JavaSymbolProvider.session
symbol = firSymbol
@@ -158,11 +177,6 @@ class JavaSymbolProvider(
scopeProvider = this@JavaSymbolProvider.scopeProvider
typeParameters += foundClass.typeParameters.convertTypeParameters(javaTypeParameterStack)
addAnnotationsFrom(this@JavaSymbolProvider.session, javaClass, javaTypeParameterStack)
for (supertype in javaClass.supertypes) {
superTypeRefs += supertype.toFirResolvedTypeRef(
this@JavaSymbolProvider.session, javaTypeParameterStack, typeParametersNullability = ConeNullability.UNKNOWN
)
}
// TODO: may be we can process fields & methods later.
// However, they should be built up to override resolve stage
for (javaField in javaClass.fields) {
@@ -218,13 +232,13 @@ class JavaSymbolProvider(
): FirJavaConstructorBuilder {
val constructorSymbol = FirConstructorSymbol(constructorId)
val classTypeParameters = javaClass.typeParameters.convertTypeParameters(javaTypeParameterStack)
val firJavaConstructor = FirJavaConstructorBuilder().apply {
return FirJavaConstructorBuilder().apply {
source = psi?.toFirSourceElement()
session = this@JavaSymbolProvider.session
symbol = constructorSymbol
this.visibility = visibility
this.isPrimary = isPrimary
isInner = !javaClass.isStatic
isInner = javaClass.outerClass != null && !javaClass.isStatic
returnTypeRef = buildResolvedTypeRef {
type = firSymbol.constructType(
classTypeParameters.map { ConeTypeParameterTypeImpl(it.symbol.toLookupTag(), false) }.toTypedArray(),
@@ -233,7 +247,6 @@ class JavaSymbolProvider(
}
typeParameters += classTypeParameters
}
return firJavaConstructor
}
if (javaClassDeclaredConstructors.isEmpty() && javaClass.classKind == ClassKind.CLASS) {
@@ -257,9 +270,15 @@ class JavaSymbolProvider(
generateValuesFunction(session, classId.packageFqName, classId.relativeClassName)
generateValueOfFunction(session, classId.packageFqName, classId.relativeClassName)
}
isNotSam = isNotSam()
parentClassTypeParameterStackCache.remove(firSymbol)
}
firJavaClass.replaceSuperTypeRefs(
javaClass.supertypes.map { supertype ->
supertype.toFirResolvedTypeRef(
this@JavaSymbolProvider.session, javaTypeParameterStack, isForSupertypes = true, forTypeParameterBounds = false
)
}
)
}
}
}

View File

@@ -5,16 +5,15 @@
package org.jetbrains.kotlin.fir.java
import org.jetbrains.kotlin.fir.declarations.builder.FirTypeParameterBuilder
import org.jetbrains.kotlin.fir.symbols.impl.FirTypeParameterSymbol
import org.jetbrains.kotlin.load.java.structure.JavaTypeParameter
internal class JavaTypeParameterStack {
private val typeParameterMap = mutableMapOf<JavaTypeParameter, FirTypeParameterBuilder>()
private val typeParameterMap = mutableMapOf<JavaTypeParameter, FirTypeParameterSymbol>()
fun add(javaTypeParameter: JavaTypeParameter, firTypeParameterBuilder: FirTypeParameterBuilder) {
typeParameterMap[javaTypeParameter] = firTypeParameterBuilder
fun add(javaTypeParameter: JavaTypeParameter, symbol: FirTypeParameterSymbol) {
typeParameterMap[javaTypeParameter] = symbol
}
fun addStack(javaTypeParameterStack: JavaTypeParameterStack) {
@@ -30,9 +29,7 @@ internal class JavaTypeParameterStack {
?: throw IllegalArgumentException("Cannot find Java type parameter $javaTypeParameter in stack")
}
fun safeGet(javaTypeParameter: JavaTypeParameter) = typeParameterMap[javaTypeParameter]?.symbol
fun getBuilder(javaTypeParameter: JavaTypeParameter) = typeParameterMap[javaTypeParameter]
fun safeGet(javaTypeParameter: JavaTypeParameter) = typeParameterMap[javaTypeParameter]
companion object {
val EMPTY: JavaTypeParameterStack = JavaTypeParameterStack()

View File

@@ -11,6 +11,7 @@ import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.builder.FirAnnotationContainerBuilder
import org.jetbrains.kotlin.fir.builder.FirBuilderDsl
import org.jetbrains.kotlin.fir.declarations.FirRegularClass
import org.jetbrains.kotlin.fir.declarations.FirTypeParameter
import org.jetbrains.kotlin.fir.declarations.FirValueParameter
import org.jetbrains.kotlin.fir.diagnostics.DiagnosticKind
@@ -24,9 +25,11 @@ import org.jetbrains.kotlin.fir.java.declarations.buildJavaValueParameter
import org.jetbrains.kotlin.fir.java.enhancement.readOnlyToMutable
import org.jetbrains.kotlin.fir.references.builder.buildErrorNamedReference
import org.jetbrains.kotlin.fir.references.builder.buildResolvedNamedReference
import org.jetbrains.kotlin.fir.resolve.constructClassType
import org.jetbrains.kotlin.fir.resolve.defaultType
import org.jetbrains.kotlin.fir.resolve.firSymbolProvider
import org.jetbrains.kotlin.fir.resolve.getClassDeclaredCallableSymbols
import org.jetbrains.kotlin.fir.resolve.toSymbol
import org.jetbrains.kotlin.fir.resolve.transformers.body.resolve.firUnsafe
import org.jetbrains.kotlin.fir.symbols.StandardClassIds
import org.jetbrains.kotlin.fir.symbols.impl.ConeClassLikeLookupTagImpl
import org.jetbrains.kotlin.fir.symbols.impl.FirRegularClassSymbol
@@ -39,6 +42,7 @@ import org.jetbrains.kotlin.fir.types.jvm.FirJavaTypeRef
import org.jetbrains.kotlin.fir.types.jvm.buildJavaTypeRef
import org.jetbrains.kotlin.load.java.structure.*
import org.jetbrains.kotlin.load.java.structure.impl.JavaElementImpl
import org.jetbrains.kotlin.load.java.typeEnhancement.TypeComponentPosition
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.types.Variance.*
@@ -59,31 +63,24 @@ internal val JavaClass.classKind: ClassKind
}
internal fun ClassId.toConeKotlinType(
typeArguments: Array<ConeKotlinTypeProjection>,
typeArguments: Array<ConeTypeProjection>,
isNullable: Boolean
): ConeLookupTagBasedType {
val lookupTag = ConeClassLikeLookupTagImpl(this)
return ConeClassLikeTypeImpl(lookupTag, typeArguments, isNullable)
}
internal fun FirTypeRef.toNotNullConeKotlinType(
internal fun FirTypeRef.toConeKotlinTypeProbablyFlexible(
session: FirSession, javaTypeParameterStack: JavaTypeParameterStack
): ConeKotlinType =
when (this) {
is FirResolvedTypeRef -> type
is FirJavaTypeRef -> {
val javaType = type
javaType.toNotNullConeKotlinType(session, javaTypeParameterStack)
type.toConeKotlinTypeWithoutEnhancement(session, javaTypeParameterStack)
}
else -> ConeKotlinErrorType("Unexpected type reference in JavaClassUseSiteMemberScope: ${this::class.java}")
}
internal fun JavaType?.toNotNullConeKotlinType(
session: FirSession, javaTypeParameterStack: JavaTypeParameterStack
): ConeKotlinType {
return toConeKotlinTypeWithNullability(session, javaTypeParameterStack, ConeNullability.NOT_NULL)
}
internal fun JavaType.toFirJavaTypeRef(session: FirSession, javaTypeParameterStack: JavaTypeParameterStack): FirJavaTypeRef {
val annotations = (this as? JavaClassifierType)?.annotations.orEmpty()
return buildJavaTypeRef {
@@ -95,25 +92,28 @@ internal fun JavaType.toFirJavaTypeRef(session: FirSession, javaTypeParameterSta
internal fun JavaClassifierType.toFirResolvedTypeRef(
session: FirSession,
javaTypeParameterStack: JavaTypeParameterStack,
nullability: ConeNullability = ConeNullability.NOT_NULL,
typeParametersNullability: ConeNullability = ConeNullability.NOT_NULL
isForSupertypes: Boolean,
forTypeParameterBounds: Boolean
): FirResolvedTypeRef {
val coneType = this.toConeKotlinTypeWithNullability(session, javaTypeParameterStack, nullability, typeParametersNullability)
val coneType =
if (isForSupertypes)
toConeKotlinTypeForFlexibleBound(session, javaTypeParameterStack, isLowerBound = true, forTypeParameterBounds)
else
toConeKotlinTypeWithoutEnhancement(session, javaTypeParameterStack, forTypeParameterBounds)
return buildResolvedTypeRef {
type = coneType
this@toFirResolvedTypeRef.annotations.mapTo(annotations) { it.toFirAnnotationCall(session, javaTypeParameterStack) }
}
}
internal fun JavaType?.toConeKotlinTypeWithNullability(
internal fun JavaType?.toConeKotlinTypeWithoutEnhancement(
session: FirSession,
javaTypeParameterStack: JavaTypeParameterStack,
nullability: ConeNullability,
typeParametersNullability: ConeNullability = ConeNullability.NOT_NULL
javaTypeParameterStack: JavaTypeParameterStack
): ConeKotlinType {
return when (this) {
is JavaClassifierType -> {
toConeKotlinTypeWithNullability(session, nullability, typeParametersNullability, javaTypeParameterStack)
toConeKotlinTypeWithoutEnhancement(session, javaTypeParameterStack)
}
is JavaPrimitiveType -> {
val primitiveType = type
@@ -121,71 +121,213 @@ internal fun JavaType?.toConeKotlinTypeWithNullability(
null -> "Unit"
else -> javaName.capitalize()
}
val classId = StandardClassIds.byName(kotlinPrimitiveName)
classId.toConeKotlinType(emptyArray(), nullability.isNullable)
classId.toConeKotlinType(emptyArray(), isNullable = false)
}
is JavaArrayType -> {
val componentType = componentType
if (componentType !is JavaPrimitiveType) {
val classId = StandardClassIds.Array
val argumentType = ConeFlexibleType(
componentType.toConeKotlinTypeWithNullability(session, javaTypeParameterStack, ConeNullability.NOT_NULL),
componentType.toConeKotlinTypeWithNullability(session, javaTypeParameterStack, ConeNullability.NULLABLE)
val argumentType = componentType.toConeKotlinTypeWithoutEnhancement(session, javaTypeParameterStack)
classId.toConeFlexibleType(
arrayOf(argumentType),
typeArgumentsForUpper = arrayOf(ConeKotlinTypeProjectionOut(argumentType))
)
classId.toConeKotlinType(arrayOf(argumentType), nullability.isNullable)
} else {
val javaComponentName = componentType.type?.typeName?.asString()?.capitalize() ?: error("Array of voids")
val classId = StandardClassIds.byName(javaComponentName + "Array")
classId.toConeKotlinType(emptyArray(), nullability.isNullable)
classId.toConeFlexibleType(emptyArray())
}
}
is JavaWildcardType -> bound?.toNotNullConeKotlinType(session, javaTypeParameterStack) ?: run {
val classId = StandardClassIds.Any
classId.toConeKotlinType(emptyArray(), nullability.isNullable)
is JavaWildcardType -> bound?.toConeKotlinTypeWithoutEnhancement(session, javaTypeParameterStack) ?: run {
StandardClassIds.Any.toConeFlexibleType(emptyArray())
}
null -> {
val classId = StandardClassIds.Any
classId.toConeKotlinType(emptyArray(), nullability.isNullable)
StandardClassIds.Any.toConeFlexibleType(emptyArray())
}
else -> error("Strange JavaType: ${this::class.java}")
}
}
internal fun JavaClassifierType.toConeKotlinTypeWithNullability(
private fun ClassId.toConeFlexibleType(
typeArguments: Array<ConeTypeProjection>,
typeArgumentsForUpper: Array<ConeTypeProjection> = typeArguments
) = ConeFlexibleType(
toConeKotlinType(typeArguments, isNullable = false),
toConeKotlinType(typeArgumentsForUpper, isNullable = true)
)
private fun JavaClassifierType.toConeKotlinTypeWithoutEnhancement(
session: FirSession,
nullability: ConeNullability,
typeParametersNullability: ConeNullability,
javaTypeParameterStack: JavaTypeParameterStack
javaTypeParameterStack: JavaTypeParameterStack,
forTypeParameterBounds: Boolean = false
): ConeKotlinType {
if (nullability == ConeNullability.UNKNOWN) {
return ConeFlexibleType(
toConeKotlinTypeWithNullability(session, ConeNullability.NOT_NULL, typeParametersNullability, javaTypeParameterStack),
toConeKotlinTypeWithNullability(session, ConeNullability.NULLABLE, typeParametersNullability, javaTypeParameterStack)
val lowerBound = toConeKotlinTypeForFlexibleBound(session, javaTypeParameterStack, isLowerBound = true, forTypeParameterBounds)
val upperBound =
toConeKotlinTypeForFlexibleBound(
session, javaTypeParameterStack, isLowerBound = false, forTypeParameterBounds, lowerBound
)
return if (isRaw) ConeRawType(lowerBound, upperBound) else ConeFlexibleType(lowerBound, upperBound)
}
private fun computeRawProjection(
session: FirSession,
parameter: FirTypeParameter,
attr: TypeComponentPosition,
erasedUpperBound: ConeKotlinType = parameter.getErasedUpperBound()
) = when (attr) {
// Raw(List<T>) => (List<Any?>..List<*>)
// Raw(Enum<T>) => (Enum<Enum<*>>..Enum<out Enum<*>>)
// In the last case upper bound is equal to star projection `Enum<*>`,
// but we want to keep matching tree structure of flexible bounds (at least they should have the same size)
TypeComponentPosition.FLEXIBLE_LOWER -> {
// T : String -> String
// in T : String -> String
// T : Enum<T> -> Enum<*>
erasedUpperBound
}
TypeComponentPosition.FLEXIBLE_UPPER, TypeComponentPosition.INFLEXIBLE -> {
if (!parameter.variance.allowsOutPosition)
// in T -> Comparable<Nothing>
session.builtinTypes.nothingType.type
else if (erasedUpperBound is ConeClassLikeType &&
erasedUpperBound.lookupTag.toSymbol(session)!!.firUnsafe<FirRegularClass>().typeParameters.isNotEmpty()
)
// T : Enum<E> -> out Enum<*>
ConeKotlinTypeProjectionOut(erasedUpperBound)
else
// T : String -> *
ConeStarProjection
}
}
// Definition:
// ErasedUpperBound(T : G<t>) = G<*> // UpperBound(T) is a type G<t> with arguments
// ErasedUpperBound(T : A) = A // UpperBound(T) is a type A without arguments
// ErasedUpperBound(T : F) = UpperBound(F) // UB(T) is another type parameter F
private fun FirTypeParameter.getErasedUpperBound(
// Calculation of `potentiallyRecursiveTypeParameter.upperBounds` may recursively depend on `this.getErasedUpperBound`
// E.g. `class A<T extends A, F extends A>`
// To prevent recursive calls return defaultValue() instead
potentiallyRecursiveTypeParameter: FirTypeParameter? = null,
defaultValue: (() -> ConeKotlinType) = { ConeKotlinErrorType("Can't compute erased upper bound of type parameter `$this`") }
): ConeKotlinType {
if (this === potentiallyRecursiveTypeParameter) return defaultValue()
val firstUpperBound = this.bounds.first().coneTypeUnsafe<ConeKotlinType>()
return getErasedVersionOfFirstUpperBound(firstUpperBound, mutableSetOf(this, potentiallyRecursiveTypeParameter), defaultValue)
}
private fun getErasedVersionOfFirstUpperBound(
firstUpperBound: ConeKotlinType,
alreadyVisitedParameters: MutableSet<FirTypeParameter?>,
defaultValue: () -> ConeKotlinType
): ConeKotlinType =
when (firstUpperBound) {
is ConeClassLikeType ->
firstUpperBound.withArguments(firstUpperBound.typeArguments.map { ConeStarProjection }.toTypedArray())
is ConeFlexibleType -> {
val lowerBound =
getErasedVersionOfFirstUpperBound(firstUpperBound.lowerBound, alreadyVisitedParameters, defaultValue)
.lowerBoundIfFlexible()
if (firstUpperBound.upperBound is ConeTypeParameterType) {
// Avoid exponential complexity
ConeFlexibleType(
lowerBound,
lowerBound.withNullability(ConeNullability.NULLABLE)
)
} else {
ConeFlexibleType(
lowerBound,
getErasedVersionOfFirstUpperBound(firstUpperBound.upperBound, alreadyVisitedParameters, defaultValue)
)
}
}
is ConeTypeParameterType -> {
val current = firstUpperBound.lookupTag.typeParameterSymbol.fir
if (alreadyVisitedParameters.add(current)) {
val nextUpperBound = current.bounds.first().coneTypeUnsafe<ConeKotlinType>()
getErasedVersionOfFirstUpperBound(nextUpperBound, alreadyVisitedParameters, defaultValue)
} else {
defaultValue()
}
}
else -> error("Unexpected kind of firstUpperBound: $firstUpperBound [${firstUpperBound::class}]")
}
private fun JavaClassifierType.toConeKotlinTypeForFlexibleBound(
session: FirSession,
javaTypeParameterStack: JavaTypeParameterStack,
isLowerBound: Boolean,
forTypeParameterBounds: Boolean,
lowerBound: ConeLookupTagBasedType? = null
): ConeLookupTagBasedType {
return when (val classifier = classifier) {
is JavaClass -> {
//val classId = classifier.classId!!
var classId = JavaToKotlinClassMap.mapJavaToKotlin(classifier.fqName!!) ?: classifier.classId!!
classId = classId.readOnlyToMutable() ?: classId
if (isLowerBound) {
classId = classId.readOnlyToMutable() ?: classId
}
val lookupTag = ConeClassLikeLookupTagImpl(classId)
lookupTag.constructClassType(
if (!isLowerBound && !isRaw && lookupTag == lowerBound?.lookupTag) {
return lookupTag.constructClassType(
lowerBound.typeArguments, isNullable = true
)
}
val mappedTypeArguments = if (isRaw) {
val defaultArgs = (1..classifier.typeParameters.size).map { ConeStarProjection }
if (forTypeParameterBounds) {
// This is not fully correct, but it's a simple fix for some time to avoid recursive definition:
// to create a proper raw type arguments, we should take class parameters some time
defaultArgs
} else {
val classSymbol = session.firSymbolProvider.getClassLikeSymbolByFqName(classId) as? FirRegularClassSymbol
val position = if (isLowerBound) TypeComponentPosition.FLEXIBLE_LOWER else TypeComponentPosition.FLEXIBLE_UPPER
classSymbol?.fir?.createRawArguments(defaultArgs, position) ?: defaultArgs
}
} else {
typeArguments.map { argument ->
argument.toConeProjection(
session, javaTypeParameterStack, boundTypeParameter = null, nullability = typeParametersNullability
argument.toConeProjectionWithoutEnhancement(
session, javaTypeParameterStack, boundTypeParameter = null
)
}.toTypedArray(), nullability.isNullable
}
}
lookupTag.constructClassType(
mappedTypeArguments.toTypedArray(), isNullable = !isLowerBound
)
}
is JavaTypeParameter -> {
val symbol = javaTypeParameterStack[classifier]
ConeTypeParameterTypeImpl(symbol.toLookupTag(), nullability.isNullable)
ConeTypeParameterTypeImpl(symbol.toLookupTag(), isNullable = !isLowerBound)
}
else -> ConeClassErrorType(reason = "Unexpected classifier: $classifier")
else -> ConeKotlinErrorType("Unexpected classifier: $classifier")
}
}
private fun FirRegularClass.createRawArguments(
defaultArgs: List<ConeStarProjection>,
position: TypeComponentPosition
) = typeParameters.map { typeParameter ->
val erasedUpperBound = typeParameter.getErasedUpperBound {
defaultType().withArguments(defaultArgs.toTypedArray())
}
computeRawProjection(session, typeParameter, position, erasedUpperBound)
}
internal fun JavaAnnotation.toFirAnnotationCall(
session: FirSession, javaTypeParameterStack: JavaTypeParameterStack
): FirAnnotationCall {
@@ -221,12 +363,11 @@ internal fun JavaValueParameter.toFirValueParameter(
}
}
internal fun JavaType?.toConeProjection(
private fun JavaType?.toConeProjectionWithoutEnhancement(
session: FirSession,
javaTypeParameterStack: JavaTypeParameterStack,
boundTypeParameter: FirTypeParameter?,
nullability: ConeNullability = ConeNullability.NOT_NULL
): ConeKotlinTypeProjection {
boundTypeParameter: FirTypeParameter?
): ConeTypeProjection {
return when (this) {
null -> ConeStarProjection
is JavaWildcardType -> {
@@ -236,7 +377,7 @@ internal fun JavaType?.toConeProjection(
if (bound == null || parameterVariance != INVARIANT && parameterVariance != argumentVariance) {
ConeStarProjection
} else {
val boundType = bound.toConeKotlinTypeWithNullability(session, javaTypeParameterStack, nullability)
val boundType = bound.toConeKotlinTypeWithoutEnhancement(session, javaTypeParameterStack)
if (argumentVariance == OUT_VARIANCE) {
ConeKotlinTypeProjectionOut(boundType)
} else {
@@ -244,7 +385,7 @@ internal fun JavaType?.toConeProjection(
}
}
}
is JavaClassifierType -> toConeKotlinTypeWithNullability(session, javaTypeParameterStack, nullability)
is JavaClassifierType -> toConeKotlinTypeWithoutEnhancement(session, javaTypeParameterStack)
else -> ConeClassErrorType("Unexpected type argument: $this")
}
}
@@ -337,7 +478,12 @@ internal fun Any?.createConstant(session: FirSession): FirExpression {
private fun JavaType.toFirResolvedTypeRef(
session: FirSession, javaTypeParameterStack: JavaTypeParameterStack
): FirResolvedTypeRef {
if (this is JavaClassifierType) return toFirResolvedTypeRef(session, javaTypeParameterStack)
if (this is JavaClassifierType) return toFirResolvedTypeRef(
session,
javaTypeParameterStack,
isForSupertypes = false,
forTypeParameterBounds = false
)
return buildResolvedTypeRef {
type = ConeClassErrorType("Unexpected JavaType: $this")
}

View File

@@ -9,7 +9,6 @@ import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.Visibility
import org.jetbrains.kotlin.fir.FirImplementationDetail
import org.jetbrains.kotlin.fir.FirPureAbstractElement
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.FirSourceElement
import org.jetbrains.kotlin.fir.builder.FirAnnotationContainerBuilder
@@ -119,7 +118,6 @@ internal class FirJavaClassBuilder : AbstractFirRegularClassBuilder, FirAnnotati
isCompanion = false
isData = false
isInline = false
isNotSAM = this@FirJavaClassBuilder.isNotSam
}
return FirJavaClass(

View File

@@ -116,6 +116,10 @@ class FirJavaField @FirImplementationDetail constructor(
}
override fun replaceReceiverTypeRef(newReceiverTypeRef: FirTypeRef?) {}
override fun <D> transformDelegate(transformer: FirTransformer<D>, data: D): FirField {
return this
}
}
@FirBuilderDsl

View File

@@ -22,6 +22,20 @@ import org.jetbrains.kotlin.fir.types.FirTypeRef
import org.jetbrains.kotlin.fir.types.jvm.FirJavaTypeRef
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedContainerSource
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.util.OperatorNameConventions.ASSIGNMENT_OPERATIONS
import org.jetbrains.kotlin.util.OperatorNameConventions.BINARY_OPERATION_NAMES
import org.jetbrains.kotlin.util.OperatorNameConventions.COMPARE_TO
import org.jetbrains.kotlin.util.OperatorNameConventions.CONTAINS
import org.jetbrains.kotlin.util.OperatorNameConventions.DELEGATED_PROPERTY_OPERATORS
import org.jetbrains.kotlin.util.OperatorNameConventions.EQUALS
import org.jetbrains.kotlin.util.OperatorNameConventions.GET
import org.jetbrains.kotlin.util.OperatorNameConventions.HAS_NEXT
import org.jetbrains.kotlin.util.OperatorNameConventions.INVOKE
import org.jetbrains.kotlin.util.OperatorNameConventions.ITERATOR
import org.jetbrains.kotlin.util.OperatorNameConventions.NEXT
import org.jetbrains.kotlin.util.OperatorNameConventions.SET
import org.jetbrains.kotlin.util.OperatorNameConventions.UNARY_OPERATION_NAMES
import kotlin.properties.Delegates
@UseExperimental(FirImplementationDetail::class)
@@ -55,6 +69,10 @@ class FirJavaMethod @FirImplementationDetail constructor(
annotations,
)
private val ALL_JAVA_OPERATION_NAMES =
UNARY_OPERATION_NAMES + BINARY_OPERATION_NAMES + ASSIGNMENT_OPERATIONS + DELEGATED_PROPERTY_OPERATORS +
EQUALS + COMPARE_TO + CONTAINS + INVOKE + ITERATOR + GET + SET + NEXT + HAS_NEXT
@FirBuilderDsl
class FirJavaMethodBuilder : FirSimpleFunctionBuilder() {
lateinit var visibility: Visibility
@@ -69,7 +87,9 @@ class FirJavaMethodBuilder : FirSimpleFunctionBuilder() {
isExpect = false
isActual = false
isOverride = false
isOperator = true // All Java methods with name that allows to use it in operator form are considered operators
// Approximation: all Java methods with name that allows to use it in operator form are considered operators
// We need here more detailed checks (see modifierChecks.kt)
isOperator = name in ALL_JAVA_OPERATION_NAMES || OperatorNameConventions.COMPONENT_REGEX.matches(name.asString())
isInfix = false
isInline = false
isTailRec = false

View File

@@ -0,0 +1,44 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.java.deserialization
import org.jetbrains.kotlin.fir.expressions.FirArrayOfCall
import org.jetbrains.kotlin.fir.expressions.FirConstKind
import org.jetbrains.kotlin.fir.expressions.FirExpression
import org.jetbrains.kotlin.fir.expressions.builder.buildArrayOfCall
import org.jetbrains.kotlin.fir.expressions.builder.buildConstExpression
object ConstantValueFactory {
fun createArrayValue(value: List<FirExpression>): FirArrayOfCall {
return buildArrayOfCall {
arguments += value
}
}
fun createConstantValue(value: Any?): FirExpression? {
return when (value) {
is Byte -> buildConstExpression(null, FirConstKind.Byte, value)
is Short -> buildConstExpression(null, FirConstKind.Short, value)
is Int -> buildConstExpression(null, FirConstKind.Int, value)
is Long -> buildConstExpression(null, FirConstKind.Long, value)
is Char -> buildConstExpression(null, FirConstKind.Char, value)
is Float -> buildConstExpression(null, FirConstKind.Float, value)
is Double -> buildConstExpression(null, FirConstKind.Double, value)
is Boolean -> buildConstExpression(null, FirConstKind.Boolean, value)
is String -> buildConstExpression(null, FirConstKind.String, value)
is ByteArray -> createArrayValue(value.map { createConstantValue(it)!! })
is ShortArray -> createArrayValue(value.map { createConstantValue(it)!! })
is IntArray -> createArrayValue(value.map { createConstantValue(it)!! })
is LongArray -> createArrayValue(value.map { createConstantValue(it)!! })
is CharArray -> createArrayValue(value.map { createConstantValue(it)!! })
is FloatArray -> createArrayValue(value.map { createConstantValue(it)!! })
is DoubleArray -> createArrayValue(value.map { createConstantValue(it)!! })
is BooleanArray -> createArrayValue(value.map { createConstantValue(it)!! })
null -> buildConstExpression(null, FirConstKind.Null, value)
else -> null
}
}
}

View File

@@ -5,18 +5,349 @@
package org.jetbrains.kotlin.fir.java.deserialization
import org.jetbrains.kotlin.descriptors.SourceElement
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.declarations.FirConstructor
import org.jetbrains.kotlin.fir.deserialization.AbstractAnnotationDeserializer
import org.jetbrains.kotlin.fir.deserialization.ProtoContainer
import org.jetbrains.kotlin.fir.diagnostics.FirSimpleDiagnostic
import org.jetbrains.kotlin.fir.expressions.FirAnnotationCall
import org.jetbrains.kotlin.fir.expressions.FirExpression
import org.jetbrains.kotlin.fir.expressions.builder.*
import org.jetbrains.kotlin.fir.references.builder.buildResolvedNamedReference
import org.jetbrains.kotlin.fir.resolve.firSymbolProvider
import org.jetbrains.kotlin.fir.symbols.impl.ConeClassLikeLookupTagImpl
import org.jetbrains.kotlin.fir.symbols.impl.FirClassSymbol
import org.jetbrains.kotlin.fir.types.ConeKotlinType
import org.jetbrains.kotlin.fir.types.builder.buildResolvedTypeRef
import org.jetbrains.kotlin.fir.types.impl.ConeClassLikeTypeImpl
import org.jetbrains.kotlin.load.kotlin.AbstractBinaryClassAnnotationAndConstantLoader
import org.jetbrains.kotlin.load.kotlin.JvmPackagePartSource
import org.jetbrains.kotlin.load.kotlin.KotlinJvmBinaryClass
import org.jetbrains.kotlin.load.kotlin.MemberSignature
import org.jetbrains.kotlin.metadata.ProtoBuf
import org.jetbrains.kotlin.metadata.deserialization.NameResolver
import org.jetbrains.kotlin.metadata.deserialization.TypeTable
import org.jetbrains.kotlin.metadata.deserialization.getExtensionOrNull
import org.jetbrains.kotlin.metadata.jvm.JvmProtoBuf
import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmProtoBufUtil
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.protobuf.MessageLite
import org.jetbrains.kotlin.resolve.constants.ClassLiteralValue
import org.jetbrains.kotlin.serialization.deserialization.AnnotatedCallableKind
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import org.jetbrains.kotlin.utils.compact
import java.util.*
class JvmBinaryAnnotationDeserializer(
session: FirSession
) : AbstractAnnotationDeserializer(session) {
override fun loadTypeAnnotations(typeProto: ProtoBuf.Type, nameResolver: NameResolver): List<FirAnnotationCall> {
private val cache: MutableMap<KotlinJvmBinaryClass, Storage> = mutableMapOf()
private class Storage(
val memberAnnotations: Map<MemberSignature, List<FirAnnotationCall>>,
val propertyConstants: Map<MemberSignature, FirExpression>
)
private val ProtoContainer.kotlinJvmBinaryClass: KotlinJvmBinaryClass?
get() = (sourceElement as? JvmPackagePartSource)?.knownJvmBinaryClass
override fun loadTypeAnnotations(
containingDeclaration: ProtoContainer,
typeProto: ProtoBuf.Type,
nameResolver: NameResolver,
typeTable: TypeTable
): List<FirAnnotationCall> {
val annotations = typeProto.getExtension(JvmProtoBuf.typeAnnotation).orEmpty()
return annotations.map { deserializeAnnotation(it, nameResolver) }
}
override fun loadFunctionAnnotations(
containingDeclaration: ProtoContainer,
functionProto: ProtoBuf.Function,
nameResolver: NameResolver,
typeTable: TypeTable
): List<FirAnnotationCall> {
val kotlinClass = containingDeclaration.kotlinJvmBinaryClass ?: return emptyList()
val signature = getCallableSignature(functionProto, nameResolver, typeTable, AnnotatedCallableKind.FUNCTION) ?: return emptyList()
val storage = loadClassFileContent(kotlinClass)
return storage.memberAnnotations[signature] ?: emptyList()
}
override fun loadPropertyAnnotations(
containingDeclaration: ProtoContainer,
propertyProto: ProtoBuf.Property,
nameResolver: NameResolver,
typeTable: TypeTable
): List<FirAnnotationCall> {
val kotlinClass = containingDeclaration.kotlinJvmBinaryClass ?: return emptyList()
val signature = getPropertySignature(propertyProto, nameResolver, typeTable) ?: return emptyList()
val storage = loadClassFileContent(kotlinClass)
return storage.memberAnnotations[signature] ?: emptyList()
}
override fun loadConstructorAnnotations(
containingDeclaration: ProtoContainer,
constructorProto: ProtoBuf.Constructor,
nameResolver: NameResolver,
typeTable: TypeTable
): List<FirAnnotationCall> {
val kotlinClass = containingDeclaration.kotlinJvmBinaryClass ?: return emptyList()
val signature = getCallableSignature(constructorProto, nameResolver, typeTable, AnnotatedCallableKind.FUNCTION) ?: return emptyList()
val storage = loadClassFileContent(kotlinClass)
return storage.memberAnnotations[signature] ?: emptyList()
}
private fun getCallableSignature(
proto: MessageLite,
nameResolver: NameResolver,
typeTable: TypeTable,
kind: AnnotatedCallableKind,
requireHasFieldFlagForField: Boolean = false
): MemberSignature? {
return when (proto) {
is ProtoBuf.Constructor -> {
MemberSignature.fromJvmMemberSignature(
JvmProtoBufUtil.getJvmConstructorSignature(proto, nameResolver, typeTable) ?: return null
)
}
is ProtoBuf.Function -> {
MemberSignature.fromJvmMemberSignature(JvmProtoBufUtil.getJvmMethodSignature(proto, nameResolver, typeTable) ?: return null)
}
is ProtoBuf.Property -> {
val signature = proto.getExtensionOrNull(JvmProtoBuf.propertySignature) ?: return null
when (kind) {
AnnotatedCallableKind.PROPERTY_GETTER ->
if (signature.hasGetter()) MemberSignature.fromMethod(nameResolver, signature.getter) else null
AnnotatedCallableKind.PROPERTY_SETTER ->
if (signature.hasSetter()) MemberSignature.fromMethod(nameResolver, signature.setter) else null
AnnotatedCallableKind.PROPERTY ->
getPropertySignature(proto, nameResolver, typeTable, true, true, requireHasFieldFlagForField)
else -> null
}
}
else -> null
}
}
private fun getPropertySignature(
proto: ProtoBuf.Property,
nameResolver: NameResolver,
typeTable: TypeTable,
field: Boolean = false,
synthetic: Boolean = false,
requireHasFieldFlagForField: Boolean = true
): MemberSignature? {
val signature = proto.getExtensionOrNull(JvmProtoBuf.propertySignature) ?: return null
if (field) {
val fieldSignature =
JvmProtoBufUtil.getJvmFieldSignature(proto, nameResolver, typeTable, requireHasFieldFlagForField) ?: return null
return MemberSignature.fromJvmMemberSignature(fieldSignature)
} else if (synthetic && signature.hasSyntheticMethod()) {
return MemberSignature.fromMethod(nameResolver, signature.syntheticMethod)
}
return null
}
private fun loadClassFileContent(kotlinClass: KotlinJvmBinaryClass): Storage {
cache[kotlinClass]?.let { return it }
val memberAnnotations = HashMap<MemberSignature, MutableList<FirAnnotationCall>>()
val propertyConstants = HashMap<MemberSignature, FirExpression>()
kotlinClass.visitMembers(object : KotlinJvmBinaryClass.MemberVisitor {
override fun visitMethod(name: Name, desc: String): KotlinJvmBinaryClass.MethodAnnotationVisitor? {
return AnnotationVisitorForMethod(MemberSignature.fromMethodNameAndDesc(name.asString(), desc))
}
override fun visitField(name: Name, desc: String, initializer: Any?): KotlinJvmBinaryClass.AnnotationVisitor? {
val signature = MemberSignature.fromFieldNameAndDesc(name.asString(), desc)
if (initializer != null) {
val constant = loadConstant(desc, initializer)
if (constant != null) {
propertyConstants[signature] = constant
}
}
return MemberAnnotationVisitor(signature)
}
inner class AnnotationVisitorForMethod(signature: MemberSignature) : MemberAnnotationVisitor(signature),
KotlinJvmBinaryClass.MethodAnnotationVisitor {
override fun visitParameterAnnotation(
index: Int, classId: ClassId, source: SourceElement
): KotlinJvmBinaryClass.AnnotationArgumentVisitor? {
val paramSignature = MemberSignature.fromMethodSignatureAndParameterIndex(signature, index)
var result = memberAnnotations[paramSignature]
if (result == null) {
result = ArrayList()
memberAnnotations[paramSignature] = result
}
return loadAnnotationIfNotSpecial(classId, source, result)
}
}
open inner class MemberAnnotationVisitor(protected val signature: MemberSignature) : KotlinJvmBinaryClass.AnnotationVisitor {
private val result = ArrayList<FirAnnotationCall>()
override fun visitAnnotation(classId: ClassId, source: SourceElement): KotlinJvmBinaryClass.AnnotationArgumentVisitor? {
return loadAnnotationIfNotSpecial(classId, source, result)
}
override fun visitEnd() {
if (result.isNotEmpty()) {
memberAnnotations[signature] = result
}
}
}
}, getCachedFileContent(kotlinClass))
return Storage(memberAnnotations, propertyConstants).also {
cache[kotlinClass] = it
}
}
fun getCachedFileContent(kotlinClass: KotlinJvmBinaryClass): ByteArray? = null
private fun loadConstant(desc: String, initializer: Any): FirExpression? {
val normalizedValue: Any = if (desc in "ZBCS") {
val intValue = initializer as Int
when (desc) {
"Z" -> intValue != 0
"B" -> intValue.toByte()
"C" -> intValue.toChar()
"S" -> intValue.toShort()
else -> throw AssertionError(desc)
}
} else {
initializer
}
return ConstantValueFactory.createConstantValue(normalizedValue)
}
private fun loadAnnotationIfNotSpecial(
annotationClassId: ClassId,
source: SourceElement,
result: MutableList<FirAnnotationCall>
): KotlinJvmBinaryClass.AnnotationArgumentVisitor? {
if (annotationClassId in AbstractBinaryClassAnnotationAndConstantLoader.SPECIAL_ANNOTATIONS) return null
return loadAnnotation(annotationClassId, result)
}
fun loadClass(classId: ClassId): FirClassSymbol<*>? {
return session.firSymbolProvider.getClassLikeSymbolByFqName(classId) as? FirClassSymbol<*>
}
private fun ClassId.toConeKotlinType(): ConeKotlinType = ConeClassLikeTypeImpl(ConeClassLikeLookupTagImpl(this), emptyArray(), isNullable = false)
fun loadAnnotation(
annotationClassId: ClassId,
result: MutableList<FirAnnotationCall>
): KotlinJvmBinaryClass.AnnotationArgumentVisitor? {
val annotationClass = loadClass(annotationClassId) ?: return null
val annotationConstructor = annotationClass.fir.declarations.firstIsInstanceOrNull<FirConstructor>() ?: return null
val builder = FirAnnotationCallBuilder().apply {
annotationTypeRef = buildResolvedTypeRef {
type = annotationClassId.toConeKotlinType()
}
}
return object : KotlinJvmBinaryClass.AnnotationArgumentVisitor {
private val arguments = HashMap<Name, FirExpression>()
override fun visit(name: Name?, value: Any?) {
if (name != null) {
arguments[name] = createConstant(name, value)
}
}
override fun visitClassLiteral(name: Name, value: ClassLiteralValue) {
arguments[name] = buildClassLiteral(value)
}
override fun visitEnum(name: Name, enumClassId: ClassId, enumEntryName: Name) {
arguments[name] = buildEnum(enumClassId, enumEntryName)
}
private fun buildClassLiteral(value: ClassLiteralValue): FirExpression {
return buildGetClassCall {
arguments += buildResolvedQualifier {
}
}
}
private fun buildEnum(
enumClassId: ClassId,
enumEntryName: Name
): FirExpression {
return buildQualifiedAccessExpression {
typeRef = buildResolvedTypeRef {
type = enumClassId.toConeKotlinType()
}
calleeReference = buildResolvedNamedReference {
name = enumEntryName
resolvedSymbol = loadClass(enumClassId)!!
}
}
}
override fun visitArray(name: Name): KotlinJvmBinaryClass.AnnotationArrayArgumentVisitor? {
return object : KotlinJvmBinaryClass.AnnotationArrayArgumentVisitor {
private val elements = ArrayList<FirExpression>()
override fun visit(value: Any?) {
elements.add(createConstant(name, value))
}
override fun visitEnum(enumClassId: ClassId, enumEntryName: Name) {
elements.add(buildEnum(enumClassId, enumEntryName))
}
override fun visitClassLiteral(value: ClassLiteralValue) {
elements.add(buildClassLiteral(value))
}
override fun visitEnd() {
val parameter = annotationConstructor.valueParameters.firstOrNull { it.name == name }
if (parameter != null) {
arguments[name] = ConstantValueFactory.createArrayValue(elements.compact())
}
}
}
}
override fun visitAnnotation(name: Name, classId: ClassId): KotlinJvmBinaryClass.AnnotationArgumentVisitor? {
val list = ArrayList<FirAnnotationCall>()
val visitor = loadAnnotation(classId, list)!!
return object : KotlinJvmBinaryClass.AnnotationArgumentVisitor by visitor {
override fun visitEnd() {
visitor.visitEnd()
arguments[name] = list.single()
}
}
}
override fun visitEnd() {
result += builder.build()
}
private fun createConstant(name: Name?, value: Any?): FirExpression {
return ConstantValueFactory.createConstantValue(value)
?: buildErrorExpression {
diagnostic = FirSimpleDiagnostic("Unsupported annotation argument: $name")
}
}
}
}
}

View File

@@ -122,6 +122,7 @@ class KotlinDeserializedJvmSymbolsProvider(
FirDeserializationContext.createForPackage(
packageFqName, packageProto, nameResolver, session,
JvmBinaryAnnotationDeserializer(session),
source
),
source,
)

View File

@@ -12,9 +12,8 @@ import org.jetbrains.kotlin.fir.declarations.FirValueParameter
import org.jetbrains.kotlin.fir.expressions.FirAnnotationCall
import org.jetbrains.kotlin.fir.expressions.classId
import org.jetbrains.kotlin.fir.java.JavaTypeParameterStack
import org.jetbrains.kotlin.fir.java.toConeKotlinTypeWithNullability
import org.jetbrains.kotlin.fir.java.toConeKotlinTypeWithoutEnhancement
import org.jetbrains.kotlin.fir.java.toFirJavaTypeRef
import org.jetbrains.kotlin.fir.java.toNotNullConeKotlinType
import org.jetbrains.kotlin.fir.symbols.ConeClassLikeLookupTag
import org.jetbrains.kotlin.fir.types.*
import org.jetbrains.kotlin.fir.types.jvm.FirJavaTypeRef
@@ -58,7 +57,8 @@ internal class EnhancementSignatureParts(
}
}
val containsFunctionN = current.toNotNullConeKotlinType(session, javaTypeParameterStack).contains {
val typeWithoutEnhancement = current.type.toConeKotlinTypeWithoutEnhancement(session, javaTypeParameterStack)
val containsFunctionN = typeWithoutEnhancement.contains {
if (it is ConeClassErrorType) false
else {
val classId = it.lookupTag.classId
@@ -67,7 +67,10 @@ internal class EnhancementSignatureParts(
}
}
val enhancedCurrent = current.enhance(session, javaTypeParameterStack, qualifiersWithPredefined ?: qualifiers)
val enhancedCurrent = current.enhance(
session, qualifiersWithPredefined ?: qualifiers,
typeWithoutEnhancement
)
return PartEnhancementResult(
enhancedCurrent, wereChanges = true, containsFunctionN = containsFunctionN
)
@@ -150,10 +153,10 @@ internal class EnhancementSignatureParts(
}
}
is FirJavaTypeRef -> {
val convertedType = type.toConeKotlinTypeWithoutEnhancement(session, javaTypeParameterStack)
Pair(
// TODO: optimize
type.toConeKotlinTypeWithNullability(session, javaTypeParameterStack, nullability = ConeNullability.NOT_NULL),
type.toConeKotlinTypeWithNullability(session, javaTypeParameterStack, nullability = ConeNullability.NULLABLE)
convertedType.lowerBoundIfFlexible(),
convertedType.upperBoundIfFlexible()
)
}
else -> return JavaTypeQualifiers.NONE

View File

@@ -16,15 +16,11 @@ import org.jetbrains.kotlin.fir.expressions.builder.buildQualifiedAccessExpressi
import org.jetbrains.kotlin.fir.java.JavaTypeParameterStack
import org.jetbrains.kotlin.fir.java.declarations.FirJavaClass
import org.jetbrains.kotlin.fir.java.declarations.FirJavaField
import org.jetbrains.kotlin.fir.java.toConeProjection
import org.jetbrains.kotlin.fir.java.toNotNullConeKotlinType
import org.jetbrains.kotlin.fir.references.builder.buildResolvedNamedReference
import org.jetbrains.kotlin.fir.resolve.*
import org.jetbrains.kotlin.fir.resolve.transformers.body.resolve.firUnsafe
import org.jetbrains.kotlin.fir.resolve.toSymbol
import org.jetbrains.kotlin.fir.symbols.ConeClassLikeLookupTag
import org.jetbrains.kotlin.fir.symbols.ConeClassifierLookupTag
import org.jetbrains.kotlin.fir.symbols.ConeTypeParameterLookupTag
import org.jetbrains.kotlin.fir.symbols.FirBasedSymbol
import org.jetbrains.kotlin.fir.symbols.impl.ConeClassLikeLookupTagImpl
import org.jetbrains.kotlin.fir.symbols.impl.FirCallableSymbol
import org.jetbrains.kotlin.fir.typeContext
@@ -36,13 +32,14 @@ import org.jetbrains.kotlin.load.java.JvmAnnotationNames.DEFAULT_VALUE_FQ_NAME
import org.jetbrains.kotlin.load.java.descriptors.AnnotationDefaultValue
import org.jetbrains.kotlin.load.java.descriptors.NullDefaultValue
import org.jetbrains.kotlin.load.java.descriptors.StringDefaultValue
import org.jetbrains.kotlin.load.java.structure.*
import org.jetbrains.kotlin.load.java.structure.JavaClassifierType
import org.jetbrains.kotlin.load.java.structure.JavaType
import org.jetbrains.kotlin.load.java.typeEnhancement.*
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.types.AbstractStrictEqualityTypeChecker
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.RawType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.kotlin.utils.extractRadix
@@ -56,60 +53,23 @@ internal class IndexedJavaTypeQualifiers(private val data: Array<JavaTypeQualifi
internal fun FirJavaTypeRef.enhance(
session: FirSession,
javaTypeParameterStack: JavaTypeParameterStack,
qualifiers: IndexedJavaTypeQualifiers
qualifiers: IndexedJavaTypeQualifiers,
typeWithoutEnhancement: ConeKotlinType,
): FirResolvedTypeRef {
return type.enhancePossiblyFlexible(session, javaTypeParameterStack, annotations, qualifiers, 0)
return typeWithoutEnhancement.enhancePossiblyFlexible(session, annotations, qualifiers, 0)
}
// The index in the lambda is the position of the type component:
// Example: for `A<B, C<D, E>>`, indices go as follows: `0 - A<...>, 1 - B, 2 - C<D, E>, 3 - D, 4 - E`,
// which corresponds to the left-to-right breadth-first walk of the tree representation of the type.
// For flexible types, both bounds are indexed in the same way: `(A<B>..C<D>)` gives `0 - (A<B>..C<D>), 1 - B and D`.
private fun JavaType?.enhancePossiblyFlexible(
private fun ConeKotlinType.enhancePossiblyFlexible(
session: FirSession,
javaTypeParameterStack: JavaTypeParameterStack,
annotations: List<FirAnnotationCall>,
qualifiers: IndexedJavaTypeQualifiers,
index: Int
): FirResolvedTypeRef {
val type = this
val arguments = this?.typeArguments().orEmpty()
val enhanced = when (type) {
is JavaClassifierType -> {
val lowerResult = type.enhanceInflexibleType(
session, javaTypeParameterStack, annotations, arguments, TypeComponentPosition.FLEXIBLE_LOWER, qualifiers, index
)
val upperResult = type.enhanceInflexibleType(
session, javaTypeParameterStack, annotations, arguments, TypeComponentPosition.FLEXIBLE_UPPER, qualifiers, index
)
when {
type.isRaw -> ConeRawType(lowerResult, upperResult)
else -> coneFlexibleOrSimpleType(
session, lowerResult, upperResult, isNotNullTypeParameter = qualifiers(index).isNotNullTypeParameter
)
}
}
is JavaArrayType -> {
val baseEnhanced = type.toNotNullConeKotlinType(session, javaTypeParameterStack)
val upperBound = if (baseEnhanced.typeArguments.isNotEmpty()) {
val typeArgument = baseEnhanced.typeArguments.first() as ConeKotlinType
baseEnhanced.withArguments(arrayOf(ConeKotlinTypeProjectionOut(typeArgument)))
} else {
baseEnhanced
}
coneFlexibleOrSimpleType(
session, baseEnhanced,
upperBound.withNullability(ConeNullability.NULLABLE),
isNotNullTypeParameter = false
)
}
else -> {
type.toNotNullConeKotlinType(session, javaTypeParameterStack)
}
}
val enhanced = enhanceConeKotlinType(session, qualifiers, index)
return buildResolvedTypeRef {
this.type = enhanced
@@ -117,9 +77,35 @@ private fun JavaType?.enhancePossiblyFlexible(
}
}
private fun JavaType?.subtreeSize(): Int {
if (this !is JavaClassifierType) return 1
return 1 + typeArguments.sumBy { it?.subtreeSize() ?: 0 }
private fun ConeKotlinType.enhanceConeKotlinType(
session: FirSession,
qualifiers: IndexedJavaTypeQualifiers,
index: Int
): ConeKotlinType {
return when (this) {
is ConeFlexibleType -> {
val lowerResult = lowerBound.enhanceInflexibleType(
session, TypeComponentPosition.FLEXIBLE_LOWER, qualifiers, index
)
val upperResult = upperBound.enhanceInflexibleType(
session, TypeComponentPosition.FLEXIBLE_UPPER, qualifiers, index
)
when {
lowerResult === lowerBound && upperResult === upperBound -> this
this is ConeRawType -> ConeRawType(lowerResult, upperResult)
else -> coneFlexibleOrSimpleType(
session, lowerResult, upperResult, isNotNullTypeParameter = qualifiers(index).isNotNullTypeParameter
)
}
}
is ConeSimpleKotlinType -> enhanceInflexibleType(session, TypeComponentPosition.INFLEXIBLE, qualifiers, index)
else -> this
}
}
private fun ConeKotlinType.subtreeSize(): Int {
return 1 + typeArguments.sumBy { ((it as? ConeKotlinType)?.subtreeSize() ?: 0) + 1 }
}
private fun coneFlexibleOrSimpleType(
@@ -164,134 +150,51 @@ private fun ClassId.mutableToReadOnly(): ClassId? {
}
}
// Definition:
// ErasedUpperBound(T : G<t>) = G<*> // UpperBound(T) is a type G<t> with arguments
// ErasedUpperBound(T : A) = A // UpperBound(T) is a type A without arguments
// ErasedUpperBound(T : F) = UpperBound(F) // UB(T) is another type parameter F
private fun FirTypeParameter.getErasedUpperBound(
// Calculation of `potentiallyRecursiveTypeParameter.upperBounds` may recursively depend on `this.getErasedUpperBound`
// E.g. `class A<T extends A, F extends A>`
// To prevent recursive calls return defaultValue() instead
potentiallyRecursiveTypeParameter: FirTypeParameter? = null,
defaultValue: (() -> ConeKotlinType) = { ConeKotlinErrorType("Can't compute erased upper bound of type parameter `$this`") }
): ConeKotlinType {
if (this === potentiallyRecursiveTypeParameter) return defaultValue()
val firstUpperBound = this.bounds.first().coneTypeUnsafe<ConeKotlinType>()
if (firstUpperBound is ConeClassLikeType) {
return firstUpperBound.withArguments(firstUpperBound.typeArguments.map { ConeStarProjection }.toTypedArray())
}
val alreadyVisited = mutableSetOf(potentiallyRecursiveTypeParameter, this)
var current = (firstUpperBound as ConeTypeParameterType).lookupTag.typeParameterSymbol.fir
while (current !in alreadyVisited) {
alreadyVisited += current
val nextUpperBound = current.bounds.first().coneTypeUnsafe<ConeKotlinType>()
if (nextUpperBound is ConeClassLikeType) {
return nextUpperBound.withArguments(nextUpperBound.typeArguments.map { ConeStarProjection }.toTypedArray())
}
current = (nextUpperBound as ConeTypeParameterType).lookupTag.typeParameterSymbol.fir
}
return defaultValue()
}
fun computeProjection(
private fun ConeKotlinType.enhanceInflexibleType(
session: FirSession,
parameter: FirTypeParameter,
attr: TypeComponentPosition,
erasedUpperBound: ConeKotlinType = parameter.getErasedUpperBound()
) = when (attr) {
// Raw(List<T>) => (List<Any?>..List<*>)
// Raw(Enum<T>) => (Enum<Enum<*>>..Enum<out Enum<*>>)
// In the last case upper bound is equal to star projection `Enum<*>`,
// but we want to keep matching tree structure of flexible bounds (at least they should have the same size)
TypeComponentPosition.FLEXIBLE_LOWER -> {
// T : String -> String
// in T : String -> String
// T : Enum<T> -> Enum<*>
erasedUpperBound
}
TypeComponentPosition.FLEXIBLE_UPPER, TypeComponentPosition.INFLEXIBLE -> {
if (!parameter.variance.allowsOutPosition)
// in T -> Comparable<Nothing>
session.builtinTypes.nothingType.type
else if (erasedUpperBound is ConeClassLikeType &&
erasedUpperBound.lookupTag.toSymbol(session)!!.firUnsafe<FirRegularClass>().typeParameters.isNotEmpty()
)
// T : Enum<E> -> out Enum<*>
ConeKotlinTypeProjectionOut(erasedUpperBound)
else
// T : String -> *
ConeStarProjection
}
}
private fun JavaClassifierType.enhanceInflexibleType(
session: FirSession,
javaTypeParameterStack: JavaTypeParameterStack,
annotations: List<FirAnnotationCall>,
arguments: List<JavaType?>,
position: TypeComponentPosition,
qualifiers: IndexedJavaTypeQualifiers,
index: Int
): ConeKotlinType {
val originalTag = when (val classifier = classifier) {
is JavaClass -> {
val classId = classifier.classId!!
var mappedId = JavaToKotlinClassMap.mapJavaToKotlin(classId.asSingleFqName())
if (mappedId != null) {
if (position == TypeComponentPosition.FLEXIBLE_LOWER) {
mappedId = mappedId.readOnlyToMutable() ?: mappedId
}
}
val kotlinClassId = mappedId ?: classId
ConeClassLikeLookupTagImpl(kotlinClassId)
}
is JavaTypeParameter -> javaTypeParameterStack[classifier].toLookupTag()
else -> return toNotNullConeKotlinType(session, javaTypeParameterStack)
require(this !is ConeFlexibleType) {
"$this should not be flexible"
}
if (this !is ConeLookupTagBasedType) return this
val originalTag = lookupTag
val effectiveQualifiers = qualifiers(index)
val enhancedTag = originalTag.enhanceMutability(effectiveQualifiers, position)
val enhancedArguments = if (isRaw) {
val firClassifier = originalTag.toSymbol(session)!!.firUnsafe<FirRegularClass>()
firClassifier.typeParameters.map {
val fir = it
val erasedUpperBound = fir.getErasedUpperBound {
firClassifier.defaultType().withArguments(firClassifier.typeParameters.map { ConeStarProjection }.toTypedArray())
}
computeProjection(session, fir, position, erasedUpperBound)
}
var wereChangesInArgs = false
val enhancedArguments = if (this is RawType) {
// TODO: Support enhancing for raw types
typeArguments
} else {
var globalArgIndex = index + 1
arguments.mapIndexed { localArgIndex, arg ->
if (arg is JavaWildcardType) {
typeArguments.mapIndexed { localArgIndex, arg ->
if (arg.kind != ProjectionKind.INVARIANT) {
globalArgIndex++
arg.toConeProjection(
session,
javaTypeParameterStack,
((originalTag as? FirBasedSymbol<*>)?.fir as? FirCallableMemberDeclaration<*>)?.typeParameters?.getOrNull(localArgIndex)
)
arg
} else {
val argEnhancedTypeRef =
arg.enhancePossiblyFlexible(session, javaTypeParameterStack, annotations, qualifiers, globalArgIndex)
require(arg is ConeKotlinType) { "Should be invariant type: $arg" }
globalArgIndex += arg.subtreeSize()
argEnhancedTypeRef.type.type.toTypeProjection(Variance.INVARIANT)
arg.enhanceConeKotlinType(session, qualifiers, globalArgIndex).also {
if (it !== arg) {
wereChangesInArgs = true
}
}
}
}
}.toTypedArray()
}
val enhancedNullability = getEnhancedNullability(effectiveQualifiers, position)
val enhancedType = enhancedTag.constructType(enhancedArguments.toTypedArray(), enhancedNullability)
if (!wereChangesInArgs && originalTag == enhancedTag && enhancedNullability == isNullable) return this
val enhancedType = enhancedTag.constructType(enhancedArguments, enhancedNullability)
// TODO: why all of these is needed
// val enhancement = if (effectiveQualifiers.isNotNullTypeParameter) NotNullTypeParameter(enhancedType) else enhancedType

View File

@@ -13,7 +13,9 @@ import org.jetbrains.kotlin.fir.declarations.builder.FirConstructorBuilder
import org.jetbrains.kotlin.fir.declarations.builder.FirPrimaryConstructorBuilder
import org.jetbrains.kotlin.fir.declarations.builder.FirSimpleFunctionBuilder
import org.jetbrains.kotlin.fir.declarations.builder.buildValueParameter
import org.jetbrains.kotlin.fir.declarations.impl.FirDeclarationStatusImpl
import org.jetbrains.kotlin.fir.declarations.impl.*
import org.jetbrains.kotlin.fir.declarations.synthetic.FirSyntheticProperty
import org.jetbrains.kotlin.fir.declarations.synthetic.buildSyntheticProperty
import org.jetbrains.kotlin.fir.expressions.FirConstKind
import org.jetbrains.kotlin.fir.expressions.FirExpression
import org.jetbrains.kotlin.fir.expressions.builder.buildConstExpression
@@ -55,11 +57,11 @@ class JavaClassEnhancementScope(
private val enhancements = mutableMapOf<FirCallableSymbol<*>, FirCallableSymbol<*>>()
override fun processPropertiesByName(name: Name, processor: (FirCallableSymbol<*>) -> Unit) {
override fun processPropertiesByName(name: Name, processor: (FirVariableSymbol<*>) -> Unit) {
useSiteMemberScope.processPropertiesByName(name) process@{ original ->
val field = enhancements.getOrPut(original) { enhance(original, name) }
processor(field)
processor(field as FirVariableSymbol<*>)
}
return super.processPropertiesByName(name, processor)
@@ -104,11 +106,17 @@ class JavaClassEnhancementScope(
}
return symbol
}
is FirJavaMethod -> {
original as FirAccessorSymbol
return enhanceMethod(
firElement, original.accessorId, original.accessorId.callableName, isAccessor = true, propertyId = original.callableId
) as FirAccessorSymbol
is FirSyntheticProperty -> {
val accessorSymbol = firElement.symbol
val enhancedFunctionSymbol = enhanceMethod(
firElement.getter.delegate, accessorSymbol.accessorId, accessorSymbol.accessorId.callableName
)
return buildSyntheticProperty {
session = this@JavaClassEnhancementScope.session
this.name = name
symbol = FirAccessorSymbol(accessorSymbol.callableId, accessorSymbol.accessorId)
delegateGetter = enhancedFunctionSymbol.fir as FirSimpleFunction
}.symbol
}
else -> {
if (original is FirPropertySymbol || original is FirAccessorSymbol) return original
@@ -132,9 +140,7 @@ class JavaClassEnhancementScope(
private fun enhanceMethod(
firMethod: FirFunction<*>,
methodId: CallableId,
name: Name,
isAccessor: Boolean = false,
propertyId: CallableId? = null
name: Name
): FirFunctionSymbol<*> {
val memberContext = context.copyWithNewDefaultTypeQualifiers(typeQualifierResolver, jsr305State, firMethod.annotations)
@@ -225,8 +231,7 @@ class JavaClassEnhancementScope(
receiverTypeRef = newReceiverTypeRef
this.name = name
status = firMethod.status
symbol = if (!isAccessor) FirNamedFunctionSymbol(methodId)
else FirAccessorSymbol(callableId = propertyId!!, accessorId = methodId)
symbol = FirNamedFunctionSymbol(methodId)
resolvePhase = FirResolvePhase.ANALYZED_DEPENDENCIES
valueParameters += newValueParameters
typeParameters += firMethod.typeParameters

View File

@@ -9,6 +9,8 @@ import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.declarations.builder.FirSimpleFunctionBuilder
import org.jetbrains.kotlin.fir.declarations.builder.FirValueParameterBuilder
import org.jetbrains.kotlin.fir.declarations.synthetic.FirSyntheticProperty
import org.jetbrains.kotlin.fir.declarations.synthetic.buildSyntheticProperty
import org.jetbrains.kotlin.fir.expressions.FirExpression
import org.jetbrains.kotlin.fir.java.JavaTypeParameterStack
import org.jetbrains.kotlin.fir.java.declarations.*
@@ -16,10 +18,7 @@ import org.jetbrains.kotlin.fir.resolve.calls.FirSyntheticPropertiesScope
import org.jetbrains.kotlin.fir.scopes.FirScope
import org.jetbrains.kotlin.fir.scopes.impl.AbstractFirUseSiteMemberScope
import org.jetbrains.kotlin.fir.symbols.CallableId
import org.jetbrains.kotlin.fir.symbols.impl.FirAccessorSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirCallableSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirFunctionSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirNamedFunctionSymbol
import org.jetbrains.kotlin.fir.symbols.impl.*
import org.jetbrains.kotlin.fir.types.jvm.FirJavaTypeRef
import org.jetbrains.kotlin.name.Name
@@ -52,37 +51,39 @@ class JavaClassUseSiteMemberScope(
overrideCandidates: MutableSet<FirCallableSymbol<*>>,
isGetter: Boolean
): FirAccessorSymbol? {
if (functionSymbol is FirNamedFunctionSymbol) {
val fir = functionSymbol.fir
if (fir.isStatic) {
if (functionSymbol !is FirNamedFunctionSymbol) {
return null
}
val fir = functionSymbol.fir
if (fir.isStatic) {
return null
}
when (isGetter) {
true -> if (fir.valueParameters.isNotEmpty()) {
return null
}
when (isGetter) {
true -> if (fir.valueParameters.isNotEmpty()) {
return null
}
false -> if (fir.valueParameters.size != 1) {
return null
}
false -> if (fir.valueParameters.size != 1) {
return null
}
}
overrideCandidates += functionSymbol
val accessorSymbol = FirAccessorSymbol(
accessorId = functionSymbol.callableId,
callableId = CallableId(functionSymbol.callableId.packageName, functionSymbol.callableId.className, syntheticPropertyName)
)
if (functionSymbol is FirNamedFunctionSymbol) {
functionSymbol.fir.let { callableMember -> accessorSymbol.bind(callableMember) }
}
return accessorSymbol
return buildSyntheticProperty {
session = this@JavaClassUseSiteMemberScope.session
name = syntheticPropertyName
symbol = FirAccessorSymbol(
accessorId = functionSymbol.callableId,
callableId = CallableId(functionSymbol.callableId.packageName, functionSymbol.callableId.className, syntheticPropertyName)
)
delegateGetter = fir
}.symbol
}
private fun processAccessorFunctionsAndPropertiesByName(
propertyName: Name,
getterNames: List<Name>,
setterName: Name?,
processor: (FirCallableSymbol<*>) -> Unit
): Unit {
processor: (FirVariableSymbol<*>) -> Unit
) {
val overrideCandidates = mutableSetOf<FirCallableSymbol<*>>()
val klass = symbol.fir
declaredMemberScope.processPropertiesByName(propertyName) { variableSymbol ->
@@ -142,7 +143,7 @@ class JavaClassUseSiteMemberScope(
}
}
override fun processPropertiesByName(name: Name, processor: (FirCallableSymbol<*>) -> Unit) {
override fun processPropertiesByName(name: Name, processor: (FirVariableSymbol<*>) -> Unit) {
// Do not generate accessors at all?
if (name.isSpecial) {
return processAccessorFunctionsAndPropertiesByName(name, emptyList(), null, processor)

View File

@@ -13,7 +13,7 @@ import org.jetbrains.kotlin.fir.declarations.FirSimpleFunction
import org.jetbrains.kotlin.fir.declarations.modality
import org.jetbrains.kotlin.fir.java.JavaTypeParameterStack
import org.jetbrains.kotlin.fir.java.enhancement.readOnlyToMutable
import org.jetbrains.kotlin.fir.java.toNotNullConeKotlinType
import org.jetbrains.kotlin.fir.java.toConeKotlinTypeProbablyFlexible
import org.jetbrains.kotlin.fir.resolve.substitution.ConeSubstitutor
import org.jetbrains.kotlin.fir.scopes.impl.FirAbstractOverrideChecker
import org.jetbrains.kotlin.fir.typeContext
@@ -28,22 +28,29 @@ class JavaOverrideChecker internal constructor(
private fun isEqualTypes(candidateType: ConeKotlinType, baseType: ConeKotlinType, substitutor: ConeSubstitutor): Boolean {
if (candidateType is ConeFlexibleType) return isEqualTypes(candidateType.lowerBound, baseType, substitutor)
if (baseType is ConeFlexibleType) return isEqualTypes(candidateType, baseType.lowerBound, substitutor)
return if (candidateType is ConeClassLikeType && baseType is ConeClassLikeType) {
candidateType.lookupTag.classId.let { it.readOnlyToMutable() ?: it } == baseType.lookupTag.classId.let { it.readOnlyToMutable() ?: it }
} else {
with(context) {
isEqualTypeConstructors(
substitutor.substituteOrSelf(candidateType).typeConstructor(),
substitutor.substituteOrSelf(baseType).typeConstructor()
)
if (candidateType is ConeClassLikeType && baseType is ConeClassLikeType) {
return candidateType.lookupTag.classId.let { it.readOnlyToMutable() ?: it } == baseType.lookupTag.classId.let { it.readOnlyToMutable() ?: it }
}
if (candidateType is ConeClassLikeType && baseType is ConeTypeParameterType) {
val boundType = baseType.lookupTag.typeParameterSymbol.fir.bounds.singleOrNull()?.toConeKotlinTypeProbablyFlexible(
session, javaTypeParameterStack
)
if (boundType != null) {
return isEqualTypes(candidateType, boundType, substitutor)
}
}
return with(context) {
isEqualTypeConstructors(
substitutor.substituteOrSelf(candidateType).typeConstructor(),
substitutor.substituteOrSelf(baseType).typeConstructor()
)
}
}
override fun isEqualTypes(candidateTypeRef: FirTypeRef, baseTypeRef: FirTypeRef, substitutor: ConeSubstitutor) =
isEqualTypes(
candidateTypeRef.toNotNullConeKotlinType(session, javaTypeParameterStack),
baseTypeRef.toNotNullConeKotlinType(session, javaTypeParameterStack),
candidateTypeRef.toConeKotlinTypeProbablyFlexible(session, javaTypeParameterStack),
baseTypeRef.toConeKotlinTypeProbablyFlexible(session, javaTypeParameterStack),
substitutor
)

View File

@@ -6,9 +6,9 @@
package org.jetbrains.kotlin.fir.resolve.calls.jvm
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.resolve.calls.Candidate
import org.jetbrains.kotlin.fir.resolve.calls.AbstractConeCallConflictResolver
import org.jetbrains.kotlin.fir.resolve.calls.InferenceComponents
import org.jetbrains.kotlin.fir.resolve.calls.Candidate
import org.jetbrains.kotlin.fir.resolve.inference.InferenceComponents
import org.jetbrains.kotlin.fir.types.ConeKotlinType
import org.jetbrains.kotlin.fir.types.coneTypeUnsafe
import org.jetbrains.kotlin.resolve.calls.results.FlatSignature

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