Compare commits

..

1908 Commits

Author SHA1 Message Date
Nikolay Lunyak
2c6b51b9a5 Code cleanup 2021-07-20 14:52:47 +03:00
Nikolay Lunyak
f7de637ca0 Added a long chain test 2021-07-20 12:13:34 +03:00
Nikolay Lunyak
d7a09bf8ab Fixing abstract properties overrides 2021-07-19 20:46:14 +03:00
Nikolay Lunyak
8ff7c8033d Refactored FirModifierChecker 2021-07-16 19:11:53 +03:00
Nikolay Lunyak
36a2873621 Fixed 145 failing FE 1.0 tests 2021-07-16 13:44:18 +03:00
Nikolay Lunyak
1c33c6910c Moving tests to their own place 2021-07-15 15:07:12 +03:00
Nikolay Lunyak
e11172e6b2 Resolving some threads 2021-07-14 13:17:33 +03:00
Nikolay Lunyak
c734975d32 Making calls to getters conditional 2021-07-14 10:57:22 +03:00
Nikolay Lunyak
bb353839ff Adding BE support 2021-07-13 13:46:52 +03:00
Nikolay Lunyak
7a75f5480c Adding a "C >= A" check 2021-07-09 21:51:42 +03:00
Nikolay Lunyak
43ebae7f51 + Some sample IR tests 2021-07-09 21:49:10 +03:00
Nikolay Lunyak
ddfb50226d More tests on overrides + fixed checkPermissiveGetter() 2021-07-09 12:00:40 +03:00
Nikolay Lunyak
afa4b6c425 Working with delegates :) 2021-07-08 16:46:16 +03:00
Nikolay Lunyak
1430d7b5d9 Added checks for overridden getters' return types 2021-07-08 13:05:08 +03:00
Nikolay Lunyak
162541609d Fixing a typo in the diagnostic + more tests on overrides 2021-07-08 11:17:19 +03:00
Nikolay Lunyak
8549f5c0b2 Fixing overriding issues 2021-07-07 20:32:28 +03:00
Nikolay Lunyak
79e48c73fb More tests on overrides 2021-07-07 16:50:48 +03:00
Nikolay Lunyak
cd82548409 Added imposter tests for uninitialized properties 2021-07-07 14:34:17 +03:00
Nikolay Lunyak
570cce3cf7 Added tests on override 2021-07-07 14:06:11 +03:00
Nikolay Lunyak
eca7a84381 Fixed the setter test 2021-07-07 11:23:54 +03:00
Nikolay Lunyak
95870d2adc Resolving review threads - 1 2021-07-06 17:06:09 +03:00
Nikolay Lunyak
a4f94d3268 Fixing the diagnostic for getters with a different explicit type 2021-07-06 15:20:13 +03:00
Nikolay Lunyak
f673e3d67a Allowing getters without a body 2021-07-06 14:38:09 +03:00
Nikolay Lunyak
41e7591165 Swiching to the first implementation idea 2021-07-05 20:10:41 +03:00
Nikolay Lunyak
a78931cd82 Trying out the second implementation idea 2021-07-05 17:26:16 +03:00
Vyacheslav Gerasimov
aff9d96e8a Build: Update gradle enterprise and test distribution plugins 2021-07-04 18:15:36 +03:00
Dmitriy Novozhilov
6e1fce6b8b [FIR] Fix creating scopes for enum entry initializers
Before we analyzed initializers of enum entry with scope for constructor
  in implict type mode, so scope was untouchable. Now we analyze them
  in body resolve phase, so previously we add value parameters to
  constructors scope, which mess up scope of enum entry initializer
2021-07-04 13:29:03 +03:00
Dmitriy Novozhilov
1593c4859d [FIR] Get rid of all conditional reads of FirDeclaration.resolvePhase 2021-07-04 13:29:03 +03:00
Dmitriy Novozhilov
43fe0c3bc1 [FIR] Don't initialize type of FirAnonymousObjectExpression
In some cases we check that some declaration (e.g. field) was
  analyzed by checking type of it's body/initializer (is it implicit
  or not), so if type of FirAnonymousObjectExpression is not implicit
  we can skip resolve of anonymous object itself
2021-07-04 11:17:50 +03:00
Dmitriy Novozhilov
32173a408a [FIR] Update type of getter after approximation of property type 2021-07-04 11:17:49 +03:00
Roman Artemev
d472b6c71c [Psi2Ir] Replace custom IrProperty node with common one 2021-07-02 19:58:31 +03:00
Roman Artemev
4d5186d332 [Psi2Ir] Untangle psi2ir from frontend.java
Add extension method to detect and unwrap `JavaSyntheticProperty`
2021-07-02 19:58:30 +03:00
Dmitriy Novozhilov
3f5e6a79c7 Replace all throw error(...) with just error(...)
`throw` is not needed in this case, because `error(...)` already
  raises exception (so `throw` is unreachable). Also after previous
  commit compiler reports `UNREACHABLE_CODE` warning on such `throw`
2021-07-02 17:55:21 +03:00
Dmitriy Novozhilov
ae608ea67f [FE 1.0] Always create return value for CallInstruction
This fixes missing `USED_AS_EXPRESSION` recordings
^KT-47527 Fixed
2021-07-02 17:55:20 +03:00
bracadabra
b2372ff0b9 Fix UTFDataFormatException on encoding long subplugin options.
ObjectOutputStream.writeUTF(String) has an unsigned short limit on
String length. On Projects with deep nested modules subplugin
options could produce String over this limit.

^KT-45202 Fixed
2021-07-02 16:17:54 +02:00
Simon Ogorodnik
f8ab16c823 [Build] Fix useFir project exclusion logic 2021-07-02 16:13:05 +03:00
Dmitriy Novozhilov
f7c68afb18 [FIR] Don't report EXPOSED_FUNCTION_RETURN_TYPE on property accessors 2021-07-02 15:55:12 +03:00
Dmitriy Novozhilov
3a34a2ca62 [FIR] Properly infer published effective visibility for member declarations 2021-07-02 15:55:10 +03:00
Dmitriy Novozhilov
f1bf3c0d5a [FIR] Don't duplicate annotations from enum entry to its initializer 2021-07-02 15:55:09 +03:00
Dmitriy Novozhilov
9f547171da [FIR] Properly calculate annotation targets for enum entries 2021-07-02 15:55:08 +03:00
Dmitriy Novozhilov
7baea7244a [FIR] Don't report VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION on lambda parameters 2021-07-02 15:55:07 +03:00
Dmitriy Novozhilov
0ab4770f02 [FIR] Add correctly reported diagnostics to testdata 2021-07-02 15:55:05 +03:00
Dmitriy Novozhilov
1f1065d858 [FIR] Add specific checkers for each leaf expression type 2021-07-02 15:55:04 +03:00
Dmitriy Novozhilov
d3ba821371 [FIR] Add specific checkers for each leaf declaration type 2021-07-02 15:55:02 +03:00
Dmitriy Novozhilov
2446ad9510 Advance bootstrap to 1.6.0-dev-328 2021-07-02 15:46:20 +03:00
Igor Laevsky
ce6459d059 WASM: Optimize few cases where spread operator is used on an immediate array 2021-07-02 15:39:30 +03:00
Igor Laevsky
d835b3c164 WASM: Implement spread operator 2021-07-02 15:39:29 +03:00
Igor Laevsky
f5e59194b5 WASM: Fix linker issues around fake overrides 2021-07-02 15:39:28 +03:00
Igor Laevsky
74a87e2b79 WASM: Add few helper array library functions from Slava's changes 2021-07-02 15:39:26 +03:00
Ilya Matveev
dc8186cb83 [K/N][Interop] Fix throwing exceptions through bridges in opt mode
By default, C functions compiled to bitcode by clang have the
nounwind attribute. If such functions throws an exception, the
behaviour is undefined.

Our interop machinery can process foreign exceptions on call sites
(terminate or wrap them in Kotlin exceptions). But if the interop
bridges have the nounwind attribute, LLVM optimizations (particularly
inlining) may lead to the situation when a foreign exception is ignored by
our foreign exception handler.

This patch fixes the issue by compiling bridges with -fexceptions flag.
This flag makes clang to not set the nounwind attribute, so exceptions
can be thrown through C frames.
2021-07-02 11:51:06 +00:00
Dmitry Petrov
c132e1a39f PSI2IR fix flaky SOE 2021-07-02 13:10:04 +03:00
Roman Golyshev
7b1052296e Do not try to create a light class for classes in unexpected positions
Example of such class declaration would be `10 < class A` expression

The expression is uncompilable, but parsable. Unfortunately, the
FIR compiler does not save `class A` reference in it (because it
is not an expression, and only an expression can be a LHS or RHS of
binary expression `10 < ...`)

When we try to build light classes, we will try to find/build FIR
declaration for this class, but we won't be able to, and this will throw
an error

Adding this check should fix few
`FirKotlinHighlightingPassTestGenerated$Regression` tests
2021-07-02 04:07:26 +03:00
Dmitry Petrov
584310615c JVM_IR KT-47499 use proper signature for 'clone' intrinsic 2021-07-01 22:10:47 +03:00
Alexander Udalov
e2f462095d IR: move JVM-specific flexible types to backend.jvm 2021-07-01 19:35:46 +02:00
Alexander Udalov
2834c22a85 IR: add BackendContext.typeSystem and JvmIrTypeSystemContext
To be able to override JVM-specific behavior of IrTypeSystemContext in
JVM IR, for things like JVM flexible types.
2021-07-01 19:35:44 +02:00
Alexander Udalov
ae07127f08 JVM IR: support raw types in typeOf 2021-07-01 19:33:56 +02:00
Alexander Udalov
012c7c39af Improve KType.toString for primitive type arguments in stdlib implementation 2021-07-01 19:33:55 +02:00
Alexander Udalov
7306256127 JVM IR: support mutability-flexible types 2021-07-01 19:33:55 +02:00
Alexander Udalov
0cb905a4b1 Support mutable collection types in typeOf
flexibleTypes_1_6.kt is fixed for JVM IR in a subsequent commit.

 #KT-35877 Fixed
2021-07-01 19:33:55 +02:00
Alexander Udalov
6e975b3498 Support flexible types internally in typeOf
#KT-45066 Fixed
2021-07-01 19:33:55 +02:00
Alexander Udalov
26cdb2f928 Reformat reflection.jvm, fix inspections 2021-07-01 19:33:54 +02:00
Yahor Berdnikau
a44e82a1d9 Fix publication failed in projects which are using BOM.
^KT-47444 Fixed
2021-07-01 15:14:35 +00:00
Denis.Zharkov
6e763f5a61 Minor. Add review fixes
Didn't squash them because there are file-moving-renaming commits above
2021-07-01 17:49:40 +03:00
Denis.Zharkov
a3f64f65f2 FIR: Fix serialization of non-delegated members in FirDelegatedMemberScope 2021-07-01 17:49:39 +03:00
Denis.Zharkov
3671b14e5b FIR: Fix compilation after rebase 2021-07-01 17:49:38 +03:00
Denis.Zharkov
44113f8501 FIR: Get rid of hacks related to previous structure of FirDelegatedScope
^KT-47413 Fixed
2021-07-01 17:49:36 +03:00
Denis.Zharkov
8a3a7a1ab5 FIR: Rename FirNewDelegatedMemberScope 2021-07-01 17:49:34 +03:00
Denis.Zharkov
4d28b9ea3b FIR: Remove FirDelegatedMemberScope 2021-07-01 17:49:32 +03:00
Denis.Zharkov
a77cbb8f63 FIR: Rework FirNotImplementedOverrideChecker around delegated members reporting 2021-07-01 17:49:30 +03:00
Denis.Zharkov
a213ee0e01 FIR: Rework delegated scope
Now delegated members are generated just to declared scope

^KT-47413 In Progress
2021-07-01 17:49:29 +03:00
Denis.Zharkov
082dc3332e FIR2IR: Move util methods closer to the single usage 2021-07-01 17:49:27 +03:00
Roman Artemev
9ef0909e39 Advance K/N version to make Gradle Klib IT tests work 2021-07-01 17:40:47 +03:00
Roman Artemev
7ef63fbb45 [Psi2Ir] Isolate type translator in file scope
Create TypeTranslator per file to avoid reusing it between files
2021-07-01 17:40:46 +03:00
Roman Artemev
ae3a2d4e71 Use DescriptorVisibilities.isPrivate instead of simple equality 2021-07-01 17:40:44 +03:00
Roman Artemev
55793d078c [KLIB] Fix Mangler Checker to work with new signatures 2021-07-01 17:40:43 +03:00
Roman Artemev
09d30c91bf [JS TESTS] Disable mangler checker in tests 2021-07-01 17:40:41 +03:00
Roman Artemev
a8d0e60328 [JS TESTS] Extend test frame with some features
- Setting up specific ABI version for module
- Disabling mangle verification
2021-07-01 17:40:40 +03:00
Roman Artemev
3403c464fe [KLIB] Promote library ABI version 2021-07-01 17:40:39 +03:00
Roman Artemev
b8e5185b61 [KLIB] Add extra debug information for Local signatures 2021-07-01 17:40:37 +03:00
Roman Artemev
b5c28c1912 [KLIB] Introduce compatible mode for klibs.
Based on library ABI version linker could decide which signature mode
to be used to guarantee backward compatibility.
2021-07-01 17:40:36 +03:00
Roman Artemev
3e99951a66 [Psi2Ir] Fix IrText testdata 2021-07-01 17:40:33 +03:00
Roman Artemev
6cdac22a23 [IR] Introduce new IdSignatures
FileSignature, CompositeSignature, LocalSignature

They are needed to make possible reference any non-local declaration via
 signature, including private signature, type parameters and so on.

- Support those new signatures in proto and klibs
- Rename `isPublic` -> `isPubliclyVisible` due to changed semantic
- Fix FIR
- clean up code
2021-07-01 17:40:31 +03:00
Roman Artemev
7139785036 [KLIB] Rename proto PublicIdSignature -> CommonIdSignature 2021-07-01 17:40:30 +03:00
Roman Artemev
0856cd82d7 [IR] Rename PublicSignature -> CommonSignature 2021-07-01 17:40:28 +03:00
Roman Artemev
5a284de2d4 add tests for private signatures
regenerate tests

add test for EnumEntry's argument declarations

add another test

regenerate test

fix test a bit
2021-07-01 17:40:27 +03:00
Svyatoslav Scherbina
2865d8bd45 Deprecate Obj-C 'alloc' and 'allocWithZone:' methods in Kotlin
Using these methods in Kotlin is usually a mistake.
2021-07-01 12:20:24 +00:00
Ilya Matveev
e5aa7e1625 [K/N] Disable some tests for noop GC 2021-07-01 10:05:02 +00:00
Alexander Shabalin
c286a9d8c6 Extract StackTrace from Exceptions 2021-07-01 07:23:47 +00:00
Roman Golyshev
bd0f48e07a Add rendering for FirValueParameter in DECLARATION_NAME renderer
Without it NAME renderer renders parameters as '???'
2021-06-30 19:35:33 +03:00
Ivan Kylchik
c176d4d7b0 Rename createTempDirectory to getOrCreateTempDirectory
With cache this function can be used to get already created directory
by name.
2021-06-30 19:33:17 +03:00
Ivan Kylchik
88aa71b0aa Add possibility to dump and test IR after execution of given lowering 2021-06-30 19:33:15 +03:00
Ilya Kirillov
330f15ff7d Add uast-kotlin-idea-fir module to the list of ide modules 2021-06-30 16:38:31 +02:00
Konstantin Tskhovrebov
b45140d237 Update default K/N ios test simulator to "iPhone 12".
#KT-45416
2021-06-30 14:19:53 +00:00
Pavel Kunyavskiy
b2f0e0e0d3 Revert "Native: exclude tests that fail due to the KT-47405 and KT-47408"
This reverts commit 6ae6209031.
2021-06-30 13:47:28 +00:00
Pavel Kunyavskiy
abf6ae70e2 [K/N] Add workaround options to arm64 targets 2021-06-30 13:47:28 +00:00
Dmitry Petrov
37b05cd9c2 JVM_IR KT-47120 treat outer name as case-insensitive for local classes 2021-06-30 14:04:22 +03:00
Andrey Zinovyev
1130344fb1 [lombok] Get field names directly from JavaClassImpl
Otherwise it fails with recursion on annotation types
#KT-47513 Fixed
2021-06-30 10:44:31 +03:00
Ivan Kochurkin
9b71175902 [FIR] Get rid of unnecessary creation of error expression for LightTree, other minor simplifications 2021-06-29 22:39:24 +03:00
Ivan Kochurkin
9f7a8c3948 [FIR] Implement ILLEGAL_SELECTOR 2021-06-29 22:39:23 +03:00
Ivan Kochurkin
a7276b25ae [FIR] Add expression field to FirErrorExpression
It is used to report diagnostics even in erroneous code (within ILLEGAL_SELECTOR for instance).
2021-06-29 22:39:22 +03:00
Ivan Kochurkin
59257e47c9 [FIR] Implement FUNCTION_CALL_EXPECTED 2021-06-29 22:39:22 +03:00
Dmitriy Novozhilov
d048bccfa2 Build: fix detecting .iml files for kotlin-ide development 2021-06-29 21:03:31 +03:00
Dmitriy Novozhilov
5816d7ae9f [FIR] Rename FirStatusOwner back to FirMemberDeclaration 2021-06-29 21:03:30 +03:00
Dmitriy Novozhilov
f400477c70 [FIR] Remove generic parameter from FirDeclaration 2021-06-29 21:03:30 +03:00
Dmitriy Novozhilov
511e564b20 [FIR] Add specific symbols for value parameters and enum entries
Make FirVariableSymbol a sealed class
2021-06-29 21:03:30 +03:00
Dmitriy Novozhilov
62d781a70f [FIR] Move delegateFieldSymbol from FirVariable to FirProperty 2021-06-29 21:03:30 +03:00
Dmitriy Novozhilov
dc3ee6318c [FIR] Rename type parameters of NullableMap from KEY, VALUE to K, V 2021-06-29 21:03:30 +03:00
Dmitriy Novozhilov
6c8096643c [FIR] Move danglingConstraints attribute to other attributes 2021-06-29 21:03:30 +03:00
Dmitriy Novozhilov
eca77324e0 [FIR] Move declaration comparators to separate package 2021-06-29 21:03:29 +03:00
Dmitriy Novozhilov
725be466f0 [FIR] Move declaration utils to separate package 2021-06-29 21:03:29 +03:00
Dmitriy Novozhilov
10ff0975bc [FIR] Split FirDeclarationUtil.kt to multiple files 2021-06-29 21:03:29 +03:00
Dmitriy Novozhilov
4225813d79 [FIR] Update CFG dumps according to changed order of visiting class children 2021-06-29 21:03:29 +03:00
Dmitriy Novozhilov
1324e9223f [FIR] Make FirDeclaration an abstract class 2021-06-29 21:03:28 +03:00
Dmitriy Novozhilov
b3e5c6e079 [FIR] Add symbol to all declarations. Get rid of FirSymbolOwner 2021-06-29 21:03:28 +03:00
Dmitriy Novozhilov
39cd1c8504 [FIR] Squash AbstractFirBasedSymbol with FirBasedSymbol 2021-06-29 21:03:28 +03:00
Dmitriy Novozhilov
823cbc59b7 [FIR] Split FirAnonymousFunction to expression and declaration 2021-06-29 21:03:28 +03:00
Dmitriy Novozhilov
85b844c748 [FIR] Split FirAnonymousObject to expression and declaration 2021-06-29 21:03:27 +03:00
Victor Petukhov
ad89d43186 Prevent recursion on captured recursive type parameters of inner classes during computing bound for them
^KT-47459 Fixed
2021-06-29 20:53:54 +03:00
Victor Petukhov
e071281b20 Prevent recursion on erasion of raw types with interdependent type parameters
^KT-47480 Fixed
2021-06-29 20:53:52 +03:00
Jiaxiang Chen
0774d4d734 expose original message collector in CLIConfiguration 2021-06-29 19:01:09 +03:00
Simon Ogorodnik
54c914e3fd [Build] Update NodeJs to 16.2.0 2021-06-29 18:35:13 +03:00
Simon Ogorodnik
021d053cfe [Gradle, JS] Fix architecture detection for M1 in NodeJsPlatform 2021-06-29 18:35:11 +03:00
Dmitry Petrov
68c3f30aa7 JVM_IR KT-47510 indy callee parent is a package fragment, not a class 2021-06-29 17:00:31 +03:00
Konstantin Tskhovrebov
a54e758189 For XCFramework with default name register 'nameless' task 'assembleXCFramework`
#KT-42667
2021-06-29 13:11:14 +00:00
Ivan Gavrilovic
08c505f9ba KT-47347: Kapt processors should not be input files for stub generation
This commit avoids passing kapt processors as sources for stub generation
task, and it also avoid using them as input files for stub generation.
Instead, it adds a new property that simply records if processors are
present (as going from empty to 1+ processors should re-run stubs).

Fixes #KT-47347

Test: Kapt3IT.kt
2021-06-29 15:11:29 +03:00
Aleksei.Cherepanov
d564bfd450 Fix visibility for JPS build 2021-06-29 14:36:50 +03:00
max-kammerer
71d59f89cb Fix type 2021-06-29 12:54:43 +02:00
Andrei Klunnyi
72d188efd9 Update contributing guide
After Kotlin-IDE-plugin is moved to intellij repository, this commit
updates contributing.md guide with corresponding references.
Other than that brief information on current repository is provided.
2021-06-29 10:46:29 +00:00
Ilya Goncharov
b678cc3c90 [JS IR] Fast return in boolean externals lowering
- Put fqname when available instead of just name
2021-06-29 10:12:56 +00:00
Ilya Goncharov
b03af384af [JS IR] Add test with exception diagnostic of boolean in externals 2021-06-29 10:12:56 +00:00
Ilya Goncharov
82f979b11f [JS IR] Add property name to boolean in externals diagnostic 2021-06-29 10:12:55 +00:00
Ilya Goncharov
21a3494bca [JS IR] Add test with boolean in external interface
[JS IR] Add possibility to safely access Boolean in external declaration

[JS IR] Add diagnostic for booleans in externals
2021-06-29 10:12:54 +00:00
Tianyu Geng
2e049c1208 FIR DFA: fix CFG with normal arg after lambda [KT-46825]
The fix is a bit hacky, but it's very simple. In addition, it still does
not handle the case where the receiver is a lambda function. But such
case seems to be fairly rare in practice.
2021-06-29 10:46:41 +03:00
Tianyu Geng
b78b50e1f8 FIR DFA: workaround KT-46826 2021-06-29 10:46:40 +03:00
Tianyu Geng
0ecc752813 FIR checker: report SMARTCAST_IMPOSSIBLE for local variables 2021-06-29 10:46:38 +03:00
Alexander Shabalin
092750e215 Fix race in Lazy for the new MM 2021-06-29 06:29:57 +00:00
Alexander Shabalin
455625bcee Use FreezableAtomicReference in unhandled exception hook 2021-06-29 06:29:57 +00:00
Dmitry Gridin
fe855d09d8 fix idea compilation 2021-06-29 10:46:47 +07:00
Dmitry Gridin
274bae1d05 KtArrayAccessReference: remove redundant functions 2021-06-29 10:04:27 +07:00
Alexander Udalov
4b7fa44e80 CLI: fix resolution of Java records as single file roots
#KT-46764 Fixed
2021-06-29 01:22:08 +02:00
Ivan Kochurkin
e295849733 [FIR] Refactor FirSupertypesChecker: split big function on small ones 2021-06-29 02:00:11 +03:00
Ivan Kochurkin
fb9ce06ff5 [FIR] Implement DELEGATION_NOT_TO_INTERFACE 2021-06-29 02:00:11 +03:00
Ivan Kochurkin
c3a6ba52f6 [FIR] Implement CLASS_CANNOT_BE_EXTENDED_DIRECTLY 2021-06-29 02:00:10 +03:00
Ivan Kochurkin
92d7a61b4f [FIR] Implement INCONSISTENT_TYPE_PARAMETER_VALUES, INCONSISTENT_TYPE_PARAMETER_BOUNDS 2021-06-29 02:00:09 +03:00
Ivan Kochurkin
ec20f52707 [FIR] Implement EXPANDED_TYPE_CANNOT_BE_INHERITED, PROJECTION_IN_IMMEDIATE_ARGUMENT_TO_SUPERTYPE
Add `starAsModifier` to `modifierSetPosition`
2021-06-29 02:00:08 +03:00
Ivan Kochurkin
937846b62d [FIR] Implement TYPEALIAS_SHOULD_EXPAND_TO_CLASS 2021-06-29 02:00:06 +03:00
Ivan Kochurkin
e8a790993b [FIR] Add ConeUnsupportedDynamicType 2021-06-29 02:00:03 +03:00
Denis.Zharkov
0ec693db89 Fix parsing regression related to T!!
^KT-47445 Fixed
2021-06-28 21:48:13 +03:00
Dmitry Petrov
768afc5ba4 JVM_IR KT-47492 fix 'for' loop generation 2021-06-28 21:07:54 +03:00
Roman Artemev
6993b86d3b [IR] Fix IrCapturedType equals/hashCode
It could lead to SOE if CT has itself as superType
- fix KT-47424
2021-06-28 20:43:14 +03:00
Dmitry Petrov
7ccefebf1c PSI2IR flatten more levels of indirection to avoid SOE in big exprs 2021-06-28 18:18:27 +03:00
Igor Yakovlev
cd0ea7f7f7 [FIR] Add explicit types to needReplacePhase transformers methods 2021-06-28 17:21:43 +03:00
Igor Yakovlev
30c381f16d [FIR] Fix invalid CallableId for methods in anonymous objects 2021-06-28 17:21:42 +03:00
Abduqodiri Qurbonzoda
47aa04d55d Test fix: java6 doesn't throw on invalid AbstractMutableList.addAll index
If the collection of elements to be added is empty, java6 implementation
of AbstractMutableList.addAll doesn't throw on invalid index.

The failing test was introduced in 59031543e2
which fixed #KT-47211.
2021-06-28 13:58:41 +00:00
Zalim Bashorov
a908e5576d [JS] Extract sourcemap generating related files to a separate module
It's required to reuse the same infrastructure in the new backend.
2021-06-28 16:04:09 +03:00
sebastian.sellmair
a63c179227 KotlinNativePlatformDependencies: Ensure 'commonizeNativeDistributionTask' is registered when 'isAllowCommonizer' is true 2021-06-28 13:00:19 +00:00
Svyatoslav Scherbina
b3980f9555 kotlin-native/samples: fix cocoapods after faulty cherry-pick 64129314
Move its source file to where it belongs.
2021-06-28 12:56:09 +00:00
Dmitry Petrov
560c269e05 PSI2IR KT-47450 prevent SOE when generating IR for deep expressions 2021-06-28 15:41:41 +03:00
Dmitriy Novozhilov
c4d9945782 Fix JPS build after removal of IDE plugin from repo 2021-06-28 14:32:24 +03:00
Ilya Goncharov
b76cbdaa41 [Gradle, JS] Remove redundant worksapces properties in yarn extensions 2021-06-28 13:38:04 +03:00
Ilya Goncharov
e3c291db27 [Gradle, JS] Not rewrite package.json if json was not changed 2021-06-28 13:38:03 +03:00
Ilya Goncharov
6219eb24c0 [Gradle, JS] Remove redundant test 2021-06-28 13:38:02 +03:00
Ilya Goncharov
1cc5a9493c [Gradle, JS] RootPackageJson task with up-to-date status 2021-06-28 13:38:01 +03:00
Ilya Goncharov
f182a1c750 [Gradle, JS] Sort for tools npm dependencies 2021-06-28 13:37:58 +03:00
Ilya Goncharov
3fc2a77281 [Gradle, JS] Remove redundant caching infrastructure 2021-06-28 13:37:57 +03:00
Ilya Goncharov
4d2376ac4c [Gradle, JS] Use package.json files instead of pre-package.json 2021-06-28 13:37:55 +03:00
Ilya Goncharov
f8bd440356 [Gradle, JS] Not force to write package.json in rootPackageJson 2021-06-28 13:37:53 +03:00
Ilya Goncharov
c4a1053aa7 [Gradle, JS] Add imported packages as workspace, not file dependencies 2021-06-28 13:37:52 +03:00
Alexander Udalov
f430d569d0 Fix warnings in js-ir/runtime/jsIntrinsics.kt
Suppress "UNUSED_PARAMETER" to fix compilation warnings. Also suppress
"unused" to make the file less yellow in the IDE.

Also enable `-Werror`, unless Gradle property
`kotlin.build.disable.werror` is set to true.
2021-06-28 12:19:35 +02:00
Svyatoslav Scherbina
eeffa49cd9 Native: don't generate .companion in ObjCExport if the companion is not exported
^KT-47462 Fixed
2021-06-28 08:19:12 +00:00
Svyatoslav Scherbina
786cb47450 Native: improve ObjCExport test for companion enum entry clash 2021-06-28 08:19:11 +00:00
Ivan Gavrilovic
929c4624cc KT-47416: Pass Android annotationProcessorOptions to kapt
This commits makes sure that "static" DSL options from
`android.javaCompileOptions.annotationProcessorOptions`
are passed to KAPT when running w/o kotlinc.

A regression was introduced in 19708cfa87.

Fixes #KT-47416
Test: Kapt3AndroidIT.testStaticDslOptionsPassedToKapt
2021-06-28 09:10:53 +02:00
Anton Bannykh
d303b783be KLIB: serialization support for global signatures and lowered IR features
Including:
- returnable blocks
- raw function references
- standalone type and value parameters
- file symbols
2021-06-27 22:56:35 +03:00
Anton Bannykh
6f01789139 IR: public symbols for the new global signatures 2021-06-27 22:56:35 +03:00
Anton Bannykh
aa5e7c65be KLIB: queue modules instead of ModuleDeserializationState
This approach is more general and expandable.
2021-06-27 22:56:35 +03:00
Anton Bannykh
e4707b236b JS IC: new signatures
Lowered IR might have cross-file references for fields, type parameters
and other stuff. Thus there is a need to make file-local and scope-local
signatures unique at least within a module.
2021-06-27 22:56:34 +03:00
Anton Bannykh
eba0661016 JS IC: .proto update 2021-06-27 22:56:34 +03:00
Anton Bannykh
b77d481ac6 IR: hide assert behind a flag
In JS IC the symbol might be unbound at this moment
2021-06-27 22:56:34 +03:00
Anton Bannykh
dbeb09af89 IR: fix SecondaryCtorLowering.kt 2021-06-27 22:56:34 +03:00
Anton Bannykh
bd4e7ffef8 JS PIR: store signatures for lowered declarations inside PIR declarations 2021-06-27 22:56:33 +03:00
Anton Bannykh
e0bdabcf61 JS IR: fix js SAM lowering 2021-06-27 22:56:33 +03:00
Anton Bannykh
9462131014 JS IR: fix offsets in BlockDecompositionLowering 2021-06-27 22:56:33 +03:00
Anton Bannykh
600099585d IR: refactor IdSignatureSerializer
Use a separate instance for each file.
2021-06-27 22:56:33 +03:00
Yahor Berdnikau
87dd357ec6 Add Gradle test task to run Gradle and Kotlin daemon tests.
These tests could not run in parallel, as they could not share
Gradle or Kotlin daemons with other running in parallel tests.

^KT-45745 In Progress
2021-06-27 21:35:54 +02:00
Andrey Zinovyev
c8fa8b0444 [lombok] Don't fail on fake overrides
#KT-47455 Fixes
2021-06-27 13:46:09 +03:00
Dmitriy Novozhilov
80b81934de Advance bootstrap to 1.5.30-dev-2862 2021-06-26 18:18:43 +03:00
Dmitriy Novozhilov
a8501bcef5 [FE 1.0] Fix message of INTEGER_OPERATOR_RESOLVE_WILL_CHANGE warning
^KT-47446 Fixed
2021-06-26 13:46:27 +03:00
Mikhael Bogdanov
5f62b72c82 Properly process big types 2021-06-26 06:10:16 +02:00
Mikhael Bogdanov
0fd1f549a9 Properly process special symbols during indy-with-constants concatenation
#KT-47320 Fixed
2021-06-26 06:10:16 +02:00
Zalim Bashorov
e947556aaa [IR] Use separate directories for each module for IR dumps
It allows avoiding overwriting content generated for other modules.

Also, added using additional ".kt" prefix to file extension for dumps generated with  Kotlin like syntax.
2021-06-26 01:38:04 +03:00
Alexander Shabalin
28b6427d3e Make FreezableAtomicReference atomic when unfrozen for the new MM. 2021-06-25 21:18:37 +00:00
Alexander Likhachev
518e8691b7 [Gradle, JS] Remove duplicate minimal Gradle version requirement
Minimal Gradle version for all Kotlin plugins is now 6.1 and minimal Gradle versions for all integration tests is set to 6.1.1
2021-06-25 22:40:06 +03:00
Alexander Likhachev
e8e95e6476 [Gradle, JS] Add test for KT-47154 regression
#KT-47154 Fixed
2021-06-25 22:40:04 +03:00
Alexander Likhachev
26510190cc [Gradle, JS] Include compiler type into library filter cache key
Previous fix could lead to unresolved symbols from main implementation in test compilation when module is compiled with both JS (IR and legacy) compilers because of single cached filter for both compileTestKotlinJsLegacy and compileTestKotlinJsIr tasks
#KT-47154 In Progress
2021-06-25 22:40:03 +03:00
Ivan Kochurkin
568eb255f5 [FIR] Split UpperBoundViolated checkers on two files (expression and declaration), add FirUpperBoundViolatedHelpers 2021-06-25 20:57:48 +03:00
Ivan Kochurkin
a26ffde820 [FIR] Correct support of projections and type aliases for UPPER_BOUND_VIOLATED, extend tests 2021-06-25 20:57:47 +03:00
Ivan Kochurkin
66e2b44272 [FIR] Implement UPPER_BOUND_VIOLATED_IN_TYPEALIAS_EXPANSION diagnostics, fix handling of UPPER_BOUND_VIOLATED 2021-06-25 20:57:46 +03:00
Ivan Kochurkin
5741374883 [FIR] Report UPPER_BOUND_VIOLATED only on checkers stage, fix detection of missing cases and testData 2021-06-25 20:57:45 +03:00
Ivan Kochurkin
ada14413e0 [FIR] Fix location of UPPER_BOUND_VIOLATED, fix detecting of several diagnostics, simplify FirUpperBoundViolatedChecker.kt 2021-06-25 20:57:44 +03:00
Dmitry Petrov
1298ba431b JVM_IR KT-47449 handle star projection arguments in default lambda types 2021-06-25 20:42:22 +03:00
Yahor Berdnikau
5486fec0f9 Validate Java and Kotlin target compatibility have same value.
This will ensure compiled java sources and kotlin sources class files
has the same bytecode version.

^KT-45611 Fixed
^KT-43095 Fixed
2021-06-25 16:28:57 +00:00
Yahor Berdnikau
6d929a8c3b Ensure toolchain is properly configured.
User specified toolchain maybe configured after initial task
configuration action will happen.

^KT-43095 In Progress
2021-06-25 16:28:56 +00:00
Yahor Berdnikau
4e556af54d Rename KotlinJavaToolchainProvider to DefaultKotlinJavaToolchain.
'Provider' suffix doesn't make sense.

^KT-45611 In Progress
^KT-43095 In Progress
2021-06-25 16:28:56 +00:00
Yahor Berdnikau
af2f716f4d Set 'jvmTarget' value on toolchain configuration.
Toolchain will set 'kotlinOptions.jvmTarget' value to the toolchain
jdk version, if 'jvmTarget' is not explicitly set by user.

If toolchain is not configured, 'jvmTarget' field uses default value,
which is now - "1.8".

^KT-45611 In Progress
^KT-43095 In Progress
2021-06-25 16:28:55 +00:00
Yahor Berdnikau
430306b23d Change 'jvmTarget' backing property visibility to internal.
Allows to check if this property was updated by the user or not.

^KT-45611 In Progress
^KT-43095 In Progress
2021-06-25 16:28:54 +00:00
Denis.Zharkov
48d170a858 Regenerate DiagnosisCompilerTestFE10TestdataTestGenerated 2021-06-25 18:41:15 +03:00
Denis.Zharkov
7645663d12 Deprecate (V)::a reference resolution to companion in FE 1.0
^KT-45315 Fixed
2021-06-25 18:41:14 +03:00
Denis.Zharkov
46b297477c Deprecate ambiguous cases in FE 1.0: companion property vs enum entry
^KT-37591 Fixed
2021-06-25 18:41:12 +03:00
Dmitriy Novozhilov
24bb9a4e14 Approximate expected type before reporting INTEGER_OPERATOR_RESOLVE_WILL_CHANGE
^KT-47447 Fixed
2021-06-25 18:39:01 +03:00
Ilya Goncharov
5bfdd5be5f [Gradle, JS] SubPlugin environment to js ir link task 2021-06-25 14:15:58 +00:00
Dmitriy Novozhilov
05883afc0a Deprecate simplification of complex boolean constant expressions in whens and loops
^KT-39883 In Progress
2021-06-25 16:37:35 +03:00
Dmitriy Novozhilov
8a2e0cedf9 Add test for exhaustive when with subject of Boolean! type 2021-06-25 16:37:34 +03:00
Dmitriy Novozhilov
09994ee8ea [FIR] Make type of safe call always nullable
^KT-46860 In Progress
2021-06-25 16:37:32 +03:00
Dmitriy Novozhilov
f18e38a49f [FIR] Properly setup source element for FirSafeCallExpression 2021-06-25 16:37:31 +03:00
Dmitriy Novozhilov
26b9948e5f [FE 1.0] Make type of safe call always nullable
^KT-46860 In Progress
2021-06-25 16:37:30 +03:00
Dmitriy Novozhilov
805fad980f [FIR] Fix creating DEBUG_CALL_INFO for safe calls 2021-06-25 16:37:29 +03:00
Dmitriy Novozhilov
9116c341ba [FIR] Fix detecting selector for safe calls in light tree 2021-06-25 16:37:27 +03:00
Dmitry Savvinov
4f8c854ead Exclude stdlib-common from jvm-specific compilations and source sets
^KT-46936 Fixed

Note that it is the slightly hack-ish fix; the proper one would remove
the dependency from kotlin-stdlib to kotlin-stdlib-common
2021-06-25 15:17:07 +03:00
Dmitry Savvinov
fa869c2c2a Add test on KT-46936 2021-06-25 15:17:06 +03:00
Dmitriy Novozhilov
1bce49023d Advance bootstrap to 1.5.30-dev-2757 2021-06-25 13:25:48 +03:00
sebastian.sellmair
b2dda0769c [Commonizer] HierarchicalClassAndTypeAliasCommonizationTest: Ignore tests for ^KT-47434 2021-06-25 09:25:11 +00:00
sebastian.sellmair
c234999c09 [Commonizer] HierarchicalClassAndTypeAliasCommonizationTest: Ignore tests for ^KT-47433 2021-06-25 09:25:10 +00:00
sebastian.sellmair
815d71a923 [Commonizer] HierarchicalClassAndTypeAliasCommonizationTest: Ignore tests for ^KT-47432 2021-06-25 09:25:10 +00:00
sebastian.sellmair
eaa0eb2851 [Commonizer] HierarchicalClassAndTypeAliasCommonizationTest: Add function parameter tests 2021-06-25 09:25:09 +00:00
sebastian.sellmair
4bcae0cc6f [Commonizer] Add CommonizeNativeDistributionTest.commonize - unix platforms() 2021-06-25 09:25:08 +00:00
sebastian.sellmair
1adf8091b1 [Commonizer] HierarchicalClassAndTypeAliasCommonizationTest: Add tests for issues found during okio investigation 2021-06-25 09:25:07 +00:00
Abduqodiri Qurbonzoda
aabc00f53f Throw IllegalStateException from MapBuilder iterator.remove() #KT-47419 2021-06-24 22:59:15 +00:00
Anton Bannykh
1006eb0945 IR: fix offsets in constant folding lowering 2021-06-25 00:59:28 +03:00
Anton Bannykh
9d1a8b2d58 IR: fill type parameters in inline class static method delegation call 2021-06-25 00:59:27 +03:00
Anton Bannykh
61a08be6b4 JS IR: don't rename the local declarations
IR2JS handles clashing declarations anyway.
2021-06-25 00:59:25 +03:00
Anton Bannykh
a56cc89010 JS IR: fill enum constructor call type parameters 2021-06-25 00:59:24 +03:00
Anton Bannykh
eb0c13793b JS IR: introduce 'lower per module' mode
This mode is closer to how IC supposed to work - reusing work
from dependencies, not re-lowering them.
2021-06-25 00:59:23 +03:00
Anton Bannykh
a4cb70af31 JS IR: gather statement origins in one place
Preparing to serialize lowered IR
2021-06-25 00:59:22 +03:00
Anton Bannykh
1b2f4ad071 dumpKotlinLike: add a flag to treat else as true
Deserialized IR always has `true` instead of `else` branch.
Dumping `else` as `true` helps comparing regular and serialized IR.
2021-06-25 00:59:20 +03:00
Sergey Igushkin
cf2c686630 Fix kotlin-test variants for correct resolution in *DependenciesMetadata
Make Gradle choose the `commonVariant` when a capability-less dependency
on kotlin-test is resolved for configurations requesting the common
artifacts.

Issue #KTIJ-6098 Fixed
2021-06-24 19:49:14 +00:00
Tianyu Geng
84f8d4d315 FIR IDE: handle reference to package and outer classes
For a qualified name like `foo.bar.Outer.Inner`, FIR represents it as
one atomic FIR element. Hence, to properly resolve these names to the
corresponding package and class, we need some additional work.
2021-06-24 18:27:51 +02:00
Tianyu Geng
a537074e1e FIR: add a boolean tracking if a class ref resolves to the companion object 2021-06-24 18:27:50 +02:00
Tianyu Geng
45ccec3b64 FIR IDE: Add HLAddWhenRemainingBranchesIntention 2021-06-24 18:26:20 +02:00
Tianyu Geng
63c65edda2 FIR IDE: AddWhenRemainingBranchFix
The fix reuses logic that is already available from
FirWhenExhaustivenessTransformer to collect missing when branches. The
current logic unfortunately uses hackyAllowRunningOnEdt to shorten the
generated code.
2021-06-24 18:26:18 +02:00
Tianyu Geng
6ec247b861 FIR: accept when(nothing) {} as exhaustive
FE1.0 accepts this but FIR current rejects it.
2021-06-24 18:26:17 +02:00
pyos
26e3237b8c JVM_IR: never rename public/protected fields
And if that causes a platform declaration clash, that's not a problem
that can be solved without breaking the ABI anyway.

 #KT-47412 Fixed
2021-06-24 17:41:06 +03:00
Jinseong Jeon
ee02303816 FIR IDE/UAST: resolve call from KtUnaryExpression 2021-06-24 16:38:24 +02:00
Jinseong Jeon
ed2cf9afd7 FIR IDE: handle other FIR calls for KtBinaryExpression 2021-06-24 16:38:24 +02:00
Elena Lepilkina
85ecbcb8f0 [K/N] Changed inlineThreshold after BCE for varargs 2021-06-24 12:57:57 +00:00
Yahor Berdnikau
e57ac5f67b Fix flaky test.
Narrow down unexpected string, so it will not clash with other output.
In this case 'AutoCloseable' was printed when Gradle 7 was generating
api jar.
2021-06-24 14:08:24 +02:00
pyos
88320cbb05 JVM_IR: produce collection stubs in a stable order
This means not storing intermediate results in any HashSets.

 #KT-47411 Fixed
2021-06-24 14:47:49 +03:00
Pavel Punegov
6ae6209031 Native: exclude tests that fail due to the KT-47405 and KT-47408 2021-06-24 10:54:45 +00:00
Denis.Zharkov
c8c558b575 FIR: Use Any? expect type to the argument list of ==
^KT-47409 Related
2021-06-24 12:17:46 +03:00
Denis.Zharkov
4892ad42b9 FIR: Do not mark not found classes' based types from Java as error
The same happens in FE1.0
2021-06-24 12:17:45 +03:00
Denis.Zharkov
201dded237 FIR: Fix serialization of delegated members
^KT-47413 Relates
2021-06-24 12:17:43 +03:00
Alexander Shabalin
cc71069a3a Do not require freezing for Worker.executeAfter on experimental MM 2021-06-24 07:57:23 +00:00
Ilya Kirillov
16e9c74523 FIR IDE: fix testdata after introducing isStatic property for symbols 2021-06-23 22:22:19 +03:00
Tianyu Geng
476d1da1cf Rename SelfTargetingIntention#allowCaretInsideElement
The current method makes it a bit hard to understand its purpose.
2021-06-23 22:22:18 +03:00
Tianyu Geng
abcc716ffc Document org.jetbrains.kotlin.idea.intentions.SelfTargetingIntention#allowCaretInsideElement
Also update its usage so that the contract of this method is easier to
understand.
2021-06-23 22:22:17 +03:00
Tianyu Geng
5a1223e812 FIR IDE: don't add return for when expressions when converting to block
There doesn't seem to be a good reason why FE1.0 does this. Hence we
won't do it in FIR.
2021-06-23 22:22:15 +03:00
Tianyu Geng
55e7cc7ea3 FIR IDE: add HLConvertToBlockBodyIntention 2021-06-23 22:22:14 +03:00
Tianyu Geng
030749eaeb FIR IDE: make KtExpressionTypeProvider work for more cases
Currently it doesn't work for the following

* labeled expression
* annotated expressions
* object literal expressions
2021-06-23 22:22:13 +03:00
Tianyu Geng
3aa6cb25ba FIR IDE: Add ImportMemberIntention 2021-06-23 22:22:12 +03:00
Tianyu Geng
66d44f2471 FIR IDE: Add ImportAllMembersIntention 2021-06-23 22:22:10 +03:00
Tianyu Geng
8d69f32d04 FIR IDE: fix test infra swallowing test failure output 2021-06-23 22:22:09 +03:00
Tianyu Geng
22fbd2044c FIR IDE: make ref shortener strictly follow range restriction 2021-06-23 22:22:08 +03:00
Tianyu Geng
726d141589 FIR IDE: Add fine-grained control to KtReferenceShortener
This change makes it possible to control how references to a symbol should be shortened.
2021-06-23 22:22:07 +03:00
Ilya Kirillov
8ac2a48eaf Allow specify path of compiler extension points for ide tests 2021-06-23 20:36:20 +03:00
Dmitry Petrov
0104b1275f JVM_IR KT-47398 handle @EnhancedNullability String subject as in 1.0 2021-06-23 20:11:24 +03:00
Dmitry Petrov
c26d71c4ef JVM KT-47365 add box test 2021-06-23 20:11:23 +03:00
sebastian.sellmair
7535f142c0 [Commonizer] SetExtensions: isSubsetOf: Use == over identity check
^KT-47301
2021-06-23 13:43:46 +00:00
sebastian.sellmair
ae57641456 [Commonizer] deserializeCirTree.kt: Optimize imports
^KT-47301
2021-06-23 13:43:45 +00:00
sebastian.sellmair
6044c58333 [Gradle] NativeDistributionCommonizerTask: Cleanup up-to-date checker comments
^KT-47301
2021-06-23 13:43:44 +00:00
sebastian.sellmair
a643ce89ff [Commonizer] Add CommonizerQueueTest.test diamond output targets()
^KT-47301
2021-06-23 13:43:44 +00:00
sebastian.sellmair
770efb7ecb [Commonizer] Replace InputTargetsSelectorInterface with a simple function
^KT-47301
2021-06-23 13:43:43 +00:00
sebastian.sellmair
5a8b39e08d [Gradle] GetCommonizerTargetOfSourceSet: Simplify implementation by only relying on compilations 2021-06-23 13:43:42 +00:00
sebastian.sellmair
19b99d5d91 [Gradle] Project.getCommonizerTarget(sourceSet: KotlinSourceSet): Ignore orphan source sets
Orphan source set's (source sets without compilation) can't break any
compilation. The decision to ignore those source sets for determining
the platform was already done for the IDE import.
In order to stay consistent, this function also ignores orphans.
2021-06-23 13:43:41 +00:00
sebastian.sellmair
97ea9c2c16 [Gradle] Rename HierarchicalNativeDistributionCommonizerTask to NativeDistributionCommonizerTask
^KT-47301
2021-06-23 13:43:40 +00:00
sebastian.sellmair
91259569d7 [Gradle] Remove old NativeDistributionCommonizerTask.kt
- Remove kotlin.mpp.enableHierarchicalCommonization gradle property:
This had to be done, since newer optimizations are not compatible
with non-hierarchical commonization

^KT-47301
2021-06-23 13:43:39 +00:00
sebastian.sellmair
73ffc0d180 [Gradle] NativeDistributionCommonizationCache: Support associative commonization
^KT-47301
2021-06-23 13:43:38 +00:00
sebastian.sellmair
21cef41ba5 [Commonizer] AbstractCommonizationFromSourcesTest remove assertions on commonized leaf/platform libraries
Those assertions are not necessary anymore, since the commonizer is not
expected to produce any new "actuals" per given expect.
The IDE is supposed to analyze leaf source sets against the original
platform libraries.
2021-06-23 13:43:37 +00:00
sebastian.sellmair
42f60d981f [Commonizer] Implement associative commonization
^KT-47301 Verification Pending
2021-06-23 13:43:36 +00:00
Kirill Shmakov
5fdbcb3dd1 [K/N][debug] Update LLDB bundle to support Apple Silicon
This is related to KTIJ-18889
2021-06-23 15:13:05 +03:00
Nikita Bobko
5a6f07402b Fix 'Generate FIR Checker Components and FIR/IDE Diagnostics' run configuration 2021-06-23 14:06:08 +02:00
Ilmir Usmanov
435b522cc5 Minor. Unmute test 2021-06-23 11:18:25 +02:00
pyos
537ce05bc9 JVM_IR: assume function reference adapters are tail-call
Meaning, they never need continuation objects. This shouldn't affect
correctness (if the assumption is valid, the continuation object
should always have been removed in the end), but the phantom
continuation sometimes left behind unused accessors (and in case of
inline function references, those accessors would refer to non-existent
functions) - see the modified test and Kotlin/kotlinx.coroutines#2769.
2021-06-23 11:18:25 +02:00
Vasily Levchenko
635a0fb01c [build][performance]kotlin:kotlin-build-gradle-plugin 0.0.29 -> 0.0.30 2021-06-23 09:07:29 +00:00
Andrey Uskov
92b08dfcfb Revert "Unify the way to set compiler options using System.properties"
This reverts commit 28e4e775
2021-06-23 11:34:04 +03:00
Dmitry Petrov
f30fc4863c JVM add ABI tests for non-approximated SAM types
Note that resulting SAM method
    public final method accept(p0: java.lang.Object): void
has a signature less specific than the resulting bridge method
    public synthetic bridge method accept(p0: X): void
2021-06-22 21:13:57 +03:00
Dmitry Petrov
c77884f067 Refactor SAM type handling, replace non-approximated arguments with * 2021-06-22 21:13:56 +03:00
Victor Petukhov
4aeabb6b0f Use upper bound aware type approximator for intersection types inside sam types in contravariant positions to build proper types in terms of subtyping 2021-06-22 21:13:55 +03:00
Victor Petukhov
6a78e0a10c Introduce type parameter's upper bound aware type approximator for intersection types 2021-06-22 21:13:54 +03:00
Victor Petukhov
750f327878 Use receivers from candidate as a fallback during completion of callable references
^KT-45083 Fixed
2021-06-22 21:13:53 +03:00
Nikita Bobko
fe8f7cfcae settings.gradle: update list of FIR IDE modules & attach them only when latest platform is used 2021-06-22 18:43:51 +02:00
Andrey Uskov
28e4e77542 Unify the way to set compiler options using System.properties
Now compiler flags with boolean values which are controlled by system
properties could be set in similar way. The following syntax is
appropriate. For setting flag:
'-DflagName,'-DflagName=[y|Y|true|TRUE|yes|YES|on|ON]'
for unsetting flag:
'-DflagName=[n|N|false|FALSE|no|NO|off|OFF]'
2021-06-22 19:35:28 +03:00
Svyatoslav Scherbina
04e8140162 Native: emit _Nullable_result attribute when generating Objective-C header
^KT-47042 Fixed
2021-06-22 16:12:37 +00:00
Nikita Bobko
9bf802a188 Move some idea-frontend-fir testData from compiler to IDE repo
This testData isn't used here but used in IDE repo
2021-06-22 18:41:42 +03:00
Nikita Bobko
c35e0438b6 Switch disableKotlinPluginModules flag 2021-06-22 17:21:04 +03:00
sebastian.sellmair
2006f89260 KotlinTargetContainerWithNativeShortcuts: Remove macos arm based targets
^KT-47126 Verification Pending
2021-06-22 12:21:05 +00:00
Svyatoslav Scherbina
9b49d0cf76 Native: fix testObjCExport testdata after 53baef88
(was broken during rebase)
2021-06-22 12:49:09 +03:00
Svyatoslav Scherbina
53baef8892 Add more tests for Native ObjCExport virtual adapters machinery 2021-06-22 09:29:30 +00:00
Svyatoslav Scherbina
5d5628f56e Native: apply ObjCExport virtual adapters from interfaces of supers
Previously they were skipped, and this was an incorrect optimization:
even if super class implements the interface too, this doesn't mean
that virtual adapters provided by that interface are inherited
by non-exported subclass that needs them;
for example, this doesn't happen when the super class is exported
(i.e. Obj-C class is not created at runtime).

Remove incorrect optimization instead of making it more sophisticated,
because it is useless anyway.

^KT-46431 Fixed
2021-06-22 09:29:29 +00:00
Alexander Shabalin
b7fbe09ef4 Fix Experimental MM tests on mingw 2021-06-22 08:58:00 +00:00
Abduqodiri Qurbonzoda
6db5fc0a23 Use teamcity kotlinLibsRepo and kotlinNativeDistDir parameters 2021-06-22 08:40:58 +00:00
Abduqodiri Qurbonzoda
013a7fe62d Rename the project from kotlin-dokka-stdlib to kotlin-stdlib-docs 2021-06-22 08:40:57 +00:00
Abduqodiri Qurbonzoda
d8d9a2689d Add sourcelink to generated documentation 2021-06-22 08:40:57 +00:00
Abduqodiri Qurbonzoda
6a9b9dc0a5 Print extracting info 2021-06-22 08:40:56 +00:00
Abduqodiri Qurbonzoda
40e23d8366 Use local libs from kotlin/build/repo and kotlin/kotlin-native/dist 2021-06-22 08:40:55 +00:00
Abduqodiri Qurbonzoda
5611fdcf25 Handle TeamCity build environment 2021-06-22 08:40:55 +00:00
Abduqodiri Qurbonzoda
e5b4fa83cb Use local sources dirs 2021-06-22 08:40:54 +00:00
Abduqodiri Qurbonzoda
72b1459353 Remove dependency on dokka build configuration artifacts 2021-06-22 08:40:53 +00:00
Abduqodiri Qurbonzoda
b5be7ddc4c Remove redundant kotlin_sources configuration 2021-06-22 08:40:52 +00:00
Abduqodiri Qurbonzoda
9777888ed4 Remove redundant use of mac and windows binaries 2021-06-22 08:40:52 +00:00
Abduqodiri Qurbonzoda
feaef467cd Remove redundant configuration declarations 2021-06-22 08:40:51 +00:00
Abduqodiri Qurbonzoda
d5d5891476 Move kotlin-dokka-stdlib scripts to libraries/tools/ 2021-06-22 08:40:50 +00:00
Nikolay Krasko
b406689035 Re-enable ":compiler:android-tests" module 2021-06-22 11:02:51 +03:00
Nikolay Krasko
d6aedc3229 Ignore more tasks if disableKotlinPluginModules explicitly set 2021-06-22 11:02:49 +03:00
Konstantin Tskhovrebov
28b8237836 Adapt XCFramework for using with groovy dsl. 2021-06-22 07:13:06 +00:00
Konstantin Tskhovrebov
c906d62c55 Add debug symbols for XCFrameworks. 2021-06-22 07:13:05 +00:00
Konstantin Tskhovrebov
297d661107 Add Apple M1 platforms to fat plist mapper. 2021-06-22 07:13:04 +00:00
Konstantin Tskhovrebov
84ae3df8b6 Add 'XCFramework' extension for creating XCFrameworks.
#KT-42667
2021-06-22 07:13:03 +00:00
Viacheslav Kormushkin
9fa55a6809 Fixed cocoapods error: expected ';' after module name
#KT-44235
2021-06-22 05:10:52 +00:00
nataliya.valtman
f6b428f271 KT-34862 use abi snapshot instead of build history files
Use jar snapshot instead build history file to avoid using time stamps and support remote gradle cache
2021-06-22 07:48:14 +03:00
Nikita Bobko
e5fbd0e2d8 Publish :idea-frontend-api, :idea-frontend-fir, :idea-fir-low-level-api modules artifacts
These artifacts are used in Kotlin plugin
2021-06-22 03:06:18 +03:00
Nikita Bobko
8b018f0a40 frontend-api-generator: remove unused module dependencies 2021-06-22 03:06:17 +03:00
Nikita Bobko
938cd955e1 Remove :idea prefix in IDE FIR modules which are going to stay in kotlin repo
This commit fixes not possibility to build project with `disableKotlinPluginModules`
flag on because Gradle tries to resolve `:idea` module which is disabled
2021-06-22 03:06:16 +03:00
Georgy Bronnikov
40872dd4ca JVM_IR: fix parallel compilation
Non-static inline functions that return inline
classes need to be tracked when copying files for by-file lowering.

FIXED: KT-45680
2021-06-22 02:22:36 +03:00
Ilya Goncharov
594cc29dd2 [Gradle, JS] Necessary to use approach with traversing all source sets
Because common source sets included into JS compilation, it can be detected as JS associated compilations.
So necessary to set attribute about JS compiler attribute only (at least at the beginning) to JS only source sets (source sets which are not included into any non js compilations)

[Gradle, JS] Add test with resolving JS variant of MPP library

[Gradle, JS] Add additional filtering of JS targets

[Gradle, JS] Add test on local resolve

^KT-47163 fixed
^KT-47114 fixed
2021-06-21 21:22:35 +03:00
Jinseong Jeon
03f85bea8f FIR checker: report VAL_REASSIGNMENT on value parameter 2021-06-21 20:58:01 +03:00
Jinseong Jeon
2486555208 FIR checker: refactor VAL_REASSIGNMENT checker 2021-06-21 20:58:00 +03:00
Jinseong Jeon
338503a4ae FIR checker: minor cleanup in FirPropertyInitializationAnalyzer 2021-06-21 20:57:58 +03:00
Ilya Kirillov
06918769e7 FIR IDE: actualize testdata 2021-06-21 20:43:45 +03:00
Ilya Kirillov
80c6506a21 FIR IDE: return back symbol restoring to symbol testss 2021-06-21 20:43:44 +03:00
Ilya Kirillov
dbba9297ff FIR IDE: restore InnerDeclarationsResolvePhaseTest 2021-06-21 20:43:43 +03:00
Ilya Kirillov
a9715de704 FIR IDE: fix leaking of FirJavaElementFinder in tests 2021-06-21 20:43:42 +03:00
Ilya Kirillov
61651c685c FIR IDE: restore FirLazyDeclarationResolveTest 2021-06-21 20:43:40 +03:00
Ilya Kirillov
c70629c22a FIR IDE: migrate LL API test to the test infrastructure from HL API 2021-06-21 20:43:39 +03:00
Dmitry Petrov
c19792e7c5 JVM_IR KT-47326 downcast field receiver on JvmField lowering 2021-06-21 19:17:54 +03:00
Alexander Shabalin
ebc4e10684 Fix GC stress test. 2021-06-21 16:07:57 +00:00
pyos
cf660cf24a JVM_IR: expect unboxed return value from suspend default stubs
#KT-47206 Fixed
2021-06-21 18:53:31 +03:00
Mark Punzalan
578fcf2ebf FIR: Render fun status flag in FirRenderer. 2021-06-21 18:45:38 +03:00
Mark Punzalan
efe3f7b87e FIR: Do not load inline flag when deserializing properties; there is
no `inline` flag for serialized properties.

In order to test this, I added the changes to FirRenderer to make sure
the flag is not loaded. However, this revealed that the `inline` status
was propagated upward to the `FirProperty` during raw FIR building,
causing test failures.

I removed the upward propagation for `inline`. I also removed it for
`external` because it is incorrect: `external` on properties (used in
JS) should be separate from `external` on accessors (used in JNI
interop for JVM). The `external` flags are also serialized separately
for properties and accessors.
2021-06-21 18:45:37 +03:00
Yahor Berdnikau
030697d430 Restore removed 'kotlinPluginVersion' property.
And marked it as '@Deprecated'.

^KT-47317 Fixed
2021-06-21 17:38:57 +02:00
Marina Shishkina
b68c00e0e9 rrr/1.5.20-release/ayalyshev/change-notes
Update links in the plugin description

Update UTM for the kotlinlang link

Add change notes for 1.5.20

Co-authored-by: Anton Yalyshev <Anton.Yalyshev@jetbrains.com>
2021-06-21 18:30:05 +03:00
pyos
913ac289ed JVM_IR: extract boolean-valued DFS on IR elements into a helper 2021-06-21 16:19:24 +03:00
pyos
ee4d9a89ea JVM_IR: read inline fun bytecode to detect unused property references
I.e. optimize `$$delegatedProperties` in the same way as the old
backend. This is more reliable than trying to match bytecode.
2021-06-21 16:19:23 +03:00
pyos
bd6d96114b JVM_IR: generate shorter bytecode for reflected property references 2021-06-21 16:19:23 +03:00
Alexander Shabalin
7079ad49bc Add a test on attaching new threads while collecting 2021-06-21 12:26:01 +00:00
Elena Lepilkina
7c45154fc5 [K/N] Added copy array benchmark 2021-06-21 12:23:25 +00:00
Jinseong Jeon
bc09d94717 FIR UAST: running resolve API tests for both plugins 2021-06-21 13:49:47 +03:00
Jinseong Jeon
610b68c29d FIR/UAST: commonize expressions with label 2021-06-21 13:49:46 +03:00
Jinseong Jeon
fa613a32b2 FIR/UAST: commonize safe qualified expression 2021-06-21 13:49:45 +03:00
Jinseong Jeon
2999d0bd4b FIR/UAST: commonize double colon expressions 2021-06-21 13:49:44 +03:00
Jinseong Jeon
77e8aed995 FIR/UAST: move multi resolve utils/APIs to the base module/service 2021-06-21 13:49:42 +03:00
Jinseong Jeon
e870bf7399 FIR/UAST: commonize simple reference expression 2021-06-21 13:49:41 +03:00
Jinseong Jeon
4ec745abd7 FIR: relax simple type requirement in AbstractTypeMapper
The counterparts in old FE don't have such restriction, so it can
map a type that has a flexible type as a type argument to JVM type,
e.g., Stream<String..String?>
2021-06-21 13:49:40 +03:00
Jinseong Jeon
08e486d1a7 FIR/UAST: commonize dot qualified expression 2021-06-21 13:49:39 +03:00
Ilya Kirillov
8f70ef41f0 FIR IDE: consider resolve inside completion candidate checker 2021-06-21 13:43:49 +03:00
Ilya Kirillov
9d07832175 fix "FIR IDE: implement completion for variables with functional types with receivers" 2021-06-21 13:43:48 +03:00
Ilya Kirillov
0ebb9cc4a6 FIR IDE: extract completion groups to object 2021-06-21 13:43:47 +03:00
Ilya Kirillov
20f2e4f313 FIR IDE: introduce basic weighting for completion based by groups 2021-06-21 13:43:46 +03:00
Ilya Kirillov
a5edbd531b FIR IDE: add ::class/::class.java to callable references completion 2021-06-21 13:43:45 +03:00
Ilya Kirillov
915c8b7996 FIR IDE: implement completion for variables with functional types with receivers 2021-06-21 13:43:44 +03:00
Ilya Kirillov
167917cf07 FIR IDE: ignore attributes in completion tests 2021-06-21 13:43:43 +03:00
Ilya Kirillov
72e26771d8 FIR IDE: do not require resolve bodies toc check candidates for completion 2021-06-21 13:43:41 +03:00
Ilya Kirillov
b8248f0197 FIR IDE: do not ignore parameters for extension applicability for completion 2021-06-21 13:43:40 +03:00
Ilya Kirillov
ae9ac33f0f FIR IDE: implement completion for infix functions 2021-06-21 13:43:39 +03:00
Ilya Kirillov
2ffc7ad0a0 FIR IDE: implement completion for callable references 2021-06-21 13:43:38 +03:00
Dmitriy Novozhilov
a42e9c236a [FIR] Fix PSI types of some diagnostics 2021-06-21 13:13:18 +03:00
Dmitriy Novozhilov
b218573bb3 [FIR] Add pretty toString to FirDiagnosticFactory 2021-06-21 13:13:17 +03:00
Dmitriy Novozhilov
3564db4f7b [FIR] Add assertion which checks that diagnostic is reported on proper PSI element 2021-06-21 13:13:17 +03:00
Dmitriy Novozhilov
a288b8b00e [FIR] Remove useless type parameters from classes related to diagnostics
Generics removed from:
 - FirPsiSourceElement
 - FirDiagnostic
 - FirDiagnosticRenderer
 - FirDiagnosticFactory
2021-06-21 13:13:17 +03:00
Dmitriy Novozhilov
386f6d9331 [FIR] Safe KClass of PSI type in diagnostic factory 2021-06-21 13:13:17 +03:00
Dmitriy Novozhilov
399b7aceef [FIR] Fix reporting diagnostics in CLI which was broken in previous commit
Note: reporting properly works only for PSI
2021-06-21 13:13:17 +03:00
Dmitriy Novozhilov
d807ac2f05 [FIR] Don't inherit FIR diagnostics from FE 1.0 diagnostics 2021-06-21 13:13:17 +03:00
Dmitriy Novozhilov
3d544be655 [FIR] Add ability to specify custom position strategy for specific diagnostic 2021-06-21 13:13:17 +03:00
Dmitriy Novozhilov
9ef712c096 [FIR] Prohibit using FirDiagnosticFactory.on for creating diagnostics
In most cases it's better to use `FirDiagnosticReporter.reportOn`, so
  `on` methods now marked as opt in
2021-06-21 13:13:16 +03:00
Andrei Klunnyi
89801a1ac7 KT-44841 Move sealed: no warning on splitting hierarchy (JPS)
To provide similar behavior for both Gradle and JPS projects target and
source directories are now taken into account.

Prior to this commit AbstractMoveTest.kt contained a hack allowing not
to create empty target directories. It breaks updated logic of the move
check and therefore is removed.
To commit empty target directories under 'before' to git one needs to
put something in them (git ignores dirs otherwise). Hence .gitignore-s.

^KT-44841 Fixed
2021-06-21 09:51:17 +00:00
Svyatoslav Scherbina
b961812efd Native: fix thread state when calling ObjC completion for Kotlin suspend 2021-06-21 09:37:25 +00:00
Ilya Kirillov
87c6ab493b FIR IDE: mute some highlighting tests
They may fail if they run separately
2021-06-21 04:15:37 +02:00
Ilya Kirillov
bbefc064a9 FIR IDE: fix EntityWasGarbageCollectedException for KtType 2021-06-21 03:38:25 +02:00
Ilya Kirillov
f00170eb31 FIR IDE: add missing runtime dependencies for tests 2021-06-21 02:50:11 +02:00
Ilya Kirillov
caf4eba2df FIR IDE: do not run tests from idea-fir module in parallel 2021-06-21 02:19:23 +02:00
Ilya Kirillov
dd0a91cc15 FIR IDE: invalidate caches between lightclasses tests 2021-06-21 00:51:31 +02:00
Ilya Kirillov
c2ae434737 Remove // FIR_IDE_IGNORE directive from passing tests 2021-06-21 00:51:31 +02:00
Ilya Kirillov
822590a62b FIR IDE: temporary disable AbstractFirLazyDeclarationResolveTest.kt 2021-06-21 00:51:31 +02:00
Ilya Kirillov
90f6d458b5 FIR IDE: fix test task name 2021-06-21 00:51:31 +02:00
Ilya Kirillov
f20dd8b673 FIR IDE: fixes after rebase 2021-06-21 00:51:30 +02:00
Ilya Kirillov
cf04be5207 FIR IDE: temp mute failing light class test 2021-06-21 00:51:30 +02:00
Ilya Kirillov
e9d1fb7c40 FIR IDE: mute completion tests failing with "Class LinkedHashMap was not found" 2021-06-21 00:51:30 +02:00
Ilya Kirillov
3e42ae03a9 Move frontend api modules out of ide modules 2021-06-20 22:07:49 +02:00
Ilya Kirillov
495a5136bb extract frontendApiTests to separate gradle task 2021-06-20 22:07:49 +02:00
Ilya Kirillov
d5cd4955cc FIR IDE: temporary update testdata of lazy resovle test 2021-06-20 22:07:46 +02:00
Ilya Kirillov
72b8593240 FIR IDE: do not use IJ test infrastructure in frontend-api-fir tests 2021-06-20 22:07:31 +02:00
Ilya Kirillov
606c3c136c FIR IDE: remove dependency to IDEA from low-level-api fir impl module 2021-06-20 22:07:28 +02:00
Ilya Kirillov
0c5883cbe0 FIR IDE: do not depend on IDEA modules in frontend-api 2021-06-20 22:07:15 +02:00
Ilya Kirillov
28dbfeb845 Move KtReference interface to psi module 2021-06-20 22:07:15 +02:00
Ilya Kirillov
796baf261d FIR IDE: move KtIconProvider out of idea-frontend-api module 2021-06-20 22:07:15 +02:00
Ilya Kirillov
75331b3448 FIR IDE: abstract low-level-api from dependency on idea 2021-06-20 22:07:11 +02:00
Ilya Kirillov
a483098303 FIR IDE: abstract DeclarationProvider 2021-06-20 22:02:17 +02:00
Ilya Kirillov
7fe2adc37e FIR IDE: do not use helper methods unavailable in intellij-core 2021-06-20 22:02:17 +02:00
Ilya Kirillov
32919489f4 FIR IDE: separate index helper in LL API and completion 2021-06-20 22:02:17 +02:00
Jinseong Jeon
7a5d61928b FIR/IDE: migrate FIR evaluator to idea-frontend-fir 2021-06-19 21:58:48 -07:00
Jinseong Jeon
fcdb8866d2 FIR: rewrite evaluator to use eval utils in frontend.common 2021-06-19 21:58:47 -07:00
Jinseong Jeon
477c1c8cd7 Migrate CompileTimeType and OperationsMap to frontend.common 2021-06-19 21:58:47 -07:00
Jinseong Jeon
833761ac3c FIR IDE/UAST: add KtCompileTimeConstantProvider with evaluate API 2021-06-19 21:58:41 -07:00
Jinseong Jeon
7d157f006b Rename CompileTimeConstantEvaluator to have Fir prefix 2021-06-19 21:35:36 -07:00
Jinseong Jeon
720104de78 Temporarily allow deprecated conversions in FIR operations map
Also, switch to the new copyright header
2021-06-19 21:35:35 -07:00
Jinseong Jeon
fc5d1d8cb5 FirConstKind has been renamed to ConstantValueKind (d243319) 2021-06-19 21:35:35 -07:00
Jinseong Jeon
bb297b87bd Avoid hard-coded operator names in CompileTimeConstantEvaluator 2021-06-19 21:35:34 -07:00
Jinseong Jeon
a969924248 FIR: generate operations map for CompileTimeConstantEvaluator 2021-06-19 21:35:34 -07:00
Jinseong Jeon
5e2525175e Introduce fir.evaluate module with CompileTimeConstantEvaluator 2021-06-19 21:35:33 -07:00
Igor Yakovlev
ec80c21fd1 [FIR IDE] Fix lazy resolve for local declarations 2021-06-19 19:23:24 +02:00
Igor Yakovlev
c17a67ba61 [FIR IDE] Fix invalid collecting designation for local declarations 2021-06-19 19:23:24 +02:00
Igor Yakovlev
41c42a5016 [FIR IDE] Remove session scope default parameter from lazy resolve interface 2021-06-19 19:23:24 +02:00
Igor Yakovlev
52765c333d [FIR IDE] Add test for local function lazy resolve and add phase into test data 2021-06-19 19:23:24 +02:00
Igor Yakovlev
2319a53fae [FIR] Fixed invalid phase for values value parameter 2021-06-19 19:23:23 +02:00
Igor Yakovlev
8012429e31 [FIR IDE] Fix loop inheritance tests 2021-06-19 19:23:23 +02:00
Igor Yakovlev
3a1057eb60 [FIR IDE] Enable passing spec tests 2021-06-19 19:23:23 +02:00
Igor Yakovlev
b612e13061 [FIR IDE] Always resolve to Body in ide fir renderer 2021-06-19 19:23:23 +02:00
Igor Yakovlev
e900a1fa57 [FIR IDE] Fix local declarations resolve 2021-06-19 19:23:23 +02:00
Igor Yakovlev
4a212dc6a0 [FIR IDE] Fix unresolved supertype for typealiases 2021-06-19 19:23:23 +02:00
Igor Yakovlev
6c0bacc548 [FIR IDE] Fix invalid status for class symbols 2021-06-19 19:23:23 +02:00
Igor Yakovlev
21b1e4b072 [FIR IDE] Add lazy resolve phases tests 2021-06-19 19:23:23 +02:00
Igor Yakovlev
df1b41f05c [FIR IDE] Rename refactoring 2021-06-19 19:23:22 +02:00
Igor Yakovlev
eded837115 [FIR IDE] Add typed lazy resolve implementation 2021-06-19 19:23:22 +02:00
Igor Yakovlev
7a0391b9b3 [FIR IDE] Move refactoring for constructor of the FileStructure 2021-06-19 19:23:22 +02:00
Igor Yakovlev
a60be78898 [FIR IDE] Remove designation collecting for local declarations 2021-06-19 19:23:22 +02:00
Igor Yakovlev
0cbb29f494 [FIR IDE] Remove typed fir designation 2021-06-19 19:23:22 +02:00
Igor Yakovlev
a4dbf0ae57 [FIR IDE] Update class modifiers requirements for resolve phase 2021-06-19 19:23:22 +02:00
Igor Yakovlev
3573f5066b [FIR] Remove redundant println from RawFirBuilder 2021-06-19 19:23:22 +02:00
Igor Yakovlev
83382bea13 [FIR IDE] Concurrent identity cache for files 2021-06-19 19:23:21 +02:00
Igor Yakovlev
f98995f6cb [FIR IDE] Implement lazy designated resolve for all resolve FIR phases 2021-06-19 19:23:21 +02:00
Jinseong Jeon
cda1a7edbe FIR/UAST: commonize UAnnotationMethod 2021-06-19 11:39:46 +02:00
Jinseong Jeon
638b0beadb FIR UAST: unify UMethod creation 2021-06-19 11:39:46 +02:00
Jinseong Jeon
5ec5b7f041 FIR/UAST: commonize constructor declarations 2021-06-19 11:39:45 +02:00
Jinseong Jeon
cbaa645dbe FIR/UAST: commonize base UMethod 2021-06-19 11:39:45 +02:00
Jinseong Jeon
4a06ca637a FIR/UAST: commonize anonymous UClass 2021-06-19 11:39:45 +02:00
Jinseong Jeon
3bd4cb274d FIR/UAST: commonize invalid UClass 2021-06-19 11:39:44 +02:00
Jinseong Jeon
1749c90083 FIR/UAST: commonize base UClass (with bogus annotation abstraction) 2021-06-19 11:39:44 +02:00
Jinseong Jeon
06c20bb10e FIR/UAST: commonize abstraction of Kotlin UClass 2021-06-19 11:39:43 +02:00
Jinseong Jeon
0c011f4e73 UAST: place method declarations together 2021-06-19 11:39:43 +02:00
Jinseong Jeon
beddf03f74 FIR/UAST: convert annotation via base converter 2021-06-19 11:39:42 +02:00
Jinseong Jeon
33ff90a6da FIR/UAST: commonize named/vararg expressions 2021-06-19 11:39:42 +02:00
Jinseong Jeon
dcf99e9fd1 UAST: delete redundant file
This is rather a test input, and indeed there is testData/Suspend.kt
2021-06-19 11:39:42 +02:00
Jinseong Jeon
4e4b104488 FIR/UAST: commonize expression list 2021-06-19 11:39:41 +02:00
Jinseong Jeon
2e58b57db9 UAST: remove redundant override: expression list's evaluate()
The super function in `KotlinEvaluatableUElement` is almost same,
except for handling of `UnsignedErrorValueTypeConstant`.
Such handling was added later, so I assume the addition to this override
was missed. In any cases, this override is unnecessary.
2021-06-19 11:39:41 +02:00
Jinseong Jeon
31d1c002c5 FIR UAST: implement constructors/delegations
But, the logic is identical to the counterpart in FE1.0 UAST
Many declaration abstractions, such as (primary|secondary) constructor
methods and class, are very similar, and thus can be commonized soon
once the remaining parts (in particular, annotations) are done.
2021-06-19 11:39:40 +02:00
Nikita Bobko
8b3c6489da Fix kotlin resources iml path 2021-06-18 17:42:23 +02:00
Nikita Bobko
306f8b7358 [imltogradle] Add "imls in same directory are not allowed" check 2021-06-18 17:42:23 +02:00
Ilya Goncharov
eed23ddbe3 [JS, Frontend] Add test with extension member in external interface 2021-06-18 17:20:57 +03:00
Ilya Goncharov
83c1a119ee [JS, Frontend] Add option to allow extension lambdas in externals 2021-06-18 17:20:56 +03:00
Svyatoslav Scherbina
2a54f1c610 Improve exception messages for kotlin.native.concurrent.* operations 2021-06-18 13:51:21 +00:00
nataliya.valtman
6a32e7bd5a Add typealias testcase for incremental compilation 2021-06-18 16:50:17 +03:00
Anton Bannykh
48fe46303d JS IR: declare intrinsics for lowerings in stdlib
- simplifies lowered IR serialization
- removes some hacks in jsOperators.kt
- intrinsics can be directly invoked in stdlib
2021-06-18 15:26:52 +03:00
Ilya Matveev
94384ce2ca [K/N][Runtime] Add a lock method to thread registry 2021-06-18 12:20:04 +00:00
Ilya Matveev
cece652412 [K/N][Runtime] Separate thread registering and making it 'Runnable'
The new GC will require threads to suspend right after registering
if Stop-The-World is requested. This patch changes the initial
thread state to kNative and adds a separate state switch right
after thread registering. This switch suspends if it is necessary.
2021-06-18 12:20:03 +00:00
Alexander Shabalin
e240b8a8ee Add a separate aggressive GC mode 2021-06-18 12:03:02 +00:00
Igor Chevdar
1cfe1c41ef [K/N][IR] Fixed problem with klib compilation
Fixes https://youtrack.jetbrains.com/issue/KT-46896
2021-06-18 16:21:24 +05:00
Igor Chevdar
421ff68cd6 [K/N][codegen] Fix for https://youtrack.jetbrains.com/issue/KT-47183 2021-06-18 15:57:45 +05:00
Yahor Berdnikau
7aa882b921 Add test for multiplatform plugin.
^KT-43095 In Progress
2021-06-18 10:50:26 +00:00
Yahor Berdnikau
0f1da3c412 Make GradleCompileTaskProvider compatible with configuration cache.
Refactor it such way that it could be used via Provider and
don't raise configuration cache errors.

^KT-45611 In Progress
^KT-43095 In Progress
2021-06-18 10:50:26 +00:00
Yahor Berdnikau
84ec4106f7 Don't set toolchain if it is not configured.
Before even when user did not configure toolchain, default toolchain
was still created, but with recent changes it does not make sense.

^KT-43095 In Progress
2021-06-18 10:50:25 +00:00
Yahor Berdnikau
1c9b013732 Change dsl method to 'jvmToolchain'.
This better reflects that applying toolchain only affects jvm
backend compilations.

^KT-43095 In Progress
2021-06-18 10:50:24 +00:00
Yahor Berdnikau
1a6bb5cd08 Allow to pass any object for 'jdkVersion'.
This object should be accepted by 'JavaVersion.toVersion' method.

^KT-45611 In Progress
2021-06-18 10:50:23 +00:00
Yahor Berdnikau
46d5df4991 Consider toolchain only as input for 'jdkHome' compilation option.
This change will limit toolchain scope only to the JVM compilations,
as Kotlin compiler itself does not care about JDK version it is running
 on and should always produce same output for non-JVM backends.
For JVM backend there is one condition - 'jdkHome' should always point
 to the same JDK version.

Few additional changes:
- allow to set specific JDK location even on Gradle versions 6.7+
- Fix typo in deprecation message

^KT-45611 In Progress
^KT-43095 In Progress
2021-06-18 10:50:23 +00:00
Yahor Berdnikau
1bb64ffa22 Revert "Print path to java executable Kotlin daemon was started with."
This reverts commit 3e69bcba47.
2021-06-18 10:50:22 +00:00
Yahor Berdnikau
f9ec6bb66a Revert "Optionally make java executable path contribute to the daemon id."
This reverts commit ac86ad252f.
2021-06-18 10:50:21 +00:00
Pavel Kunyavskiy
d7a3310042 [K/N] KT-43780: support of more convenient objects using from objC/Swift 2021-06-18 08:02:22 +00:00
Pavel Kunyavskiy
0952a95949 [K/N] reuse common code for companionObject util 2021-06-18 08:02:21 +00:00
Viacheslav Kormushkin
0b6d2cd21a Custom name support for fat frameworks
#KT-30805
2021-06-18 06:28:01 +00:00
Dmitry Petrov
ce107d06d4 JVM_IR add test for KT-47300 2021-06-17 21:40:30 +03:00
Roman Golyshev
1cd75b1e82 kotlin-stdlib:jvm-minimal-for-test -> kotlin-stdlib-jvm-minimal-for-test
Changed after cherry-picking 8baf570ee7
to the master-for-ide branch
2021-06-17 20:19:49 +03:00
Roman Golyshev
6ea4b8997b Add kotlin-stdlib-minimal-for-test.jar artefact to the published dependencies
Some compiler tests rely on this jar instead of the regular `stdlib`
2021-06-17 20:19:48 +03:00
Vyacheslav Gerasimov
73d4110c92 Build: Rollback kotlin-stdlib-jvm-minimal-for-test publication
Continue publishing to the internal/repo only
2021-06-17 19:43:11 +03:00
Vyacheslav Gerasimov
58f1fb644f Build: Stop publishing jars with original classifier
#KTI-580
2021-06-17 19:43:10 +03:00
Vyacheslav Gerasimov
fb805028c1 Build: Add runtimeJar variant to the default java component if present 2021-06-17 19:43:09 +03:00
Vyacheslav Gerasimov
a0469a1d62 Build: Make Gradle plugin publications reuse POMs from the main one
#KTI-571
2021-06-17 19:43:07 +03:00
Nikolay Krasko
80677c88cb Update gradle task in generated files 2021-06-17 18:36:10 +03:00
Nikolay Krasko
c8ae9a7090 [imltogradle] Speedup files traversing by ignoring directories 2021-06-17 18:36:09 +03:00
Nikolay Krasko
7e8168a7e6 Ignore more boostrap libraries in dependency verification 2021-06-17 18:36:08 +03:00
Nikolay Krasko
d72f1097d7 Cleanup dependency verification for 211 kotlin-ide 2021-06-17 18:36:07 +03:00
Nikolay Krasko
6139f095e7 Disable dependencies verification for kotlin-ide projects 2021-06-17 18:36:06 +03:00
Nikolay Krasko
71ee9cf1be Fix generateIdeaGradleFiles on Windows 2021-06-17 18:36:04 +03:00
Ilya Kirillov
8c69913640 FIR IDE: temporary ignore failing intention tests 2021-06-17 17:27:00 +03:00
Mark Punzalan
97c10b0b84 FIR IDE: Change PSI element type for NO_COMPANION_OBJECT and
EXPRESSION_EXPECTED_PACKAGE_FOUND from KtSimpleNameExpression to
KtExpression (source can be KtDotQualifiedExpression).
2021-06-17 17:26:58 +03:00
Alexander Shabalin
91a852d3fd Fix integer conversion on 32-bit 2021-06-17 14:16:16 +00:00
Margarita Bobova
eaed67df29 Move 1.4.x changelog to a separate file 2021-06-17 14:50:36 +03:00
Ivan Kochurkin
a0aaf42fb1 Some string and minor optimizations 2021-06-17 13:49:08 +03:00
Ivan Kochurkin
bc3c05a3bd [FIR] Replace lists with Long in Modifier, refactor Modifier and derived classes 2021-06-17 13:49:08 +03:00
Ivan Kochurkin
6199b85eb9 [FIR] Introduce ModifierKind and optimize Modifier in lightTree 2021-06-17 13:49:08 +03:00
Ivan Kochurkin
ce4e60afd3 [FIR] Simplify FirCyclicTypeBoundsChecker and replace PersistentList with MutableList 2021-06-17 13:49:07 +03:00
Ivan Kochurkin
1e430b7b03 [FIR] Replace PersistentList with MutableList in Context, simplify DeclarationConverter 2021-06-17 13:49:07 +03:00
Ivan Kochurkin
366017d267 [FIR] Replace PersistentList with MutableList in BodyResolveContext, LocalClassesNavigation 2021-06-17 13:49:06 +03:00
Andrey Zinovyev
d360932ebc [FIR] Fill overriddenSymbols for fake overridden IrProperty 2021-06-17 13:24:12 +03:00
Sergey Bogolepov
4f98a0e083 [Native] Introduce optInCacheableTargets
Create an explicit list of targets that have unstable compiler caches
in konan.properties. It allows to control all lists of cacheable targets
in a single place.
2021-06-17 09:19:44 +00:00
Roman Golyshev
108dd37242 Add possibility to use baseDir in CoroutineHelpersSourceFilesProvider 2021-06-17 02:41:32 +03:00
Nikita Nazarov
adec873118 [EE_IR] Update ignore directive 2021-06-17 02:40:04 +03:00
Alexander Shabalin
e3eec33b24 Add aggressively allocating stress test for GC 2021-06-16 21:34:05 +00:00
Alexander Shabalin
7ae59856cb Add internal MemoryUsageInfo object
Currently it only provides peak RSS usage for iOS, Linux, macOS and Windows.
2021-06-16 21:34:04 +00:00
Nikita Bobko
670d66984f Reduce Gradle configuration phase time in case when 'attachedIntellijVersion' flag is specified
Traversing intellij repo is long
2021-06-16 21:58:36 +03:00
Nikita Bobko
526a664077 [imltogradle] Add a bit of logging 2021-06-16 21:58:36 +03:00
Nikita Bobko
c954fa4900 Make it possible to attach community version of kotlin-ide 2021-06-16 21:58:34 +03:00
Roman Artemev
8ac5d03f02 [Test] fix module name in klib text tests
It failed on windows machines due to illegal '<' in path
2021-06-16 21:16:58 +03:00
Roman Artemev
56604a9654 [K/N] Promote kotlin-build-gradle-plugin version 0.0.29 -> 0.0.30
Missed fix
2021-06-16 21:16:57 +03:00
Roman Artemev
2c34888a57 [TEST] Add comment in klib text tests runner 2021-06-16 21:16:56 +03:00
Roman Artemev
71af11052a [TEST] Mute tests irText klib tests 2021-06-16 21:16:55 +03:00
Roman Artemev
e82552975d [TEST] support test muting in klib text tests runner 2021-06-16 21:16:54 +03:00
Roman Artemev
5bc884ce2b [KLIB] Fix fakeoverride builder
Set proper visibility in case of cross-module internal overrides.
TODO: KT-47192
2021-06-16 21:16:53 +03:00
Roman Artemev
0cb23a6e65 [KLIB] Fix serialization of loops with control statements in condition 2021-06-16 21:16:52 +03:00
Roman Artemev
e5c6a5b80d [IR] Clean up Fake Override builder a bit 2021-06-16 21:16:51 +03:00
Roman Artemev
1831c0a14b [IR] Support disabling of rendering IrErrorType inner KotlinType 2021-06-16 21:16:50 +03:00
Roman Artemev
2eac442705 [IR] Support stable order in IR dump
That mode is need to test deserialization of klibs
2021-06-16 21:16:49 +03:00
Roman Artemev
bbcd511c44 [TEST] fix irText testData
- support DELEGATED_MEMBER overrides
2021-06-16 21:16:48 +03:00
Roman Artemev
cb130181a2 [Psi2Ir] Fix overridden symbols of Delegated Properties 2021-06-16 21:16:47 +03:00
Roman Artemev
32bbc3b8ad [KLIB] Fix SimpleTypeKey in case of type abbreviation 2021-06-16 21:16:46 +03:00
Roman Artemev
2f772c7a7c [KLIB] Add IrStatementOrigin into IrConstructorCall message 2021-06-16 21:16:45 +03:00
Roman Artemev
16ea3d9ae9 [TEST] Add IrText klib tests 2021-06-16 21:16:44 +03:00
Roman Artemev
14c91ca0de [TEST] Set proper TARGET_BACKEND for jvm-specific irText tests 2021-06-16 21:16:43 +03:00
Roman Golyshev
b587b71b0f FIR IDE: Move KtDeclarationAndFirDeclarationEqualityChecker.kt to nested api package 2021-06-16 15:38:57 +00:00
Roman Golyshev
c42fec5c93 FIR IDE: Refactor findSourceFirCompiledDeclaration
Add `FirDeclarationForCompiledElementSearcher` class to encapsulate
searching by the compiled declarations, move it to the separate file
2021-06-16 15:38:56 +00:00
Roman Golyshev
b0bac90a8b FIR IDE: Make findNonLocalDeclarationForCompiledElement a member of FirModuleResolveState 2021-06-16 15:38:56 +00:00
Roman Golyshev
e1f985424f FIR IDE: Move KtDeclarationAndFirDeclarationEqualityChecker to api package 2021-06-16 15:38:55 +00:00
Roman Golyshev
ad34c19f9a FIR IDE: Add explicit assertion that module info is ModuleSourceInfo 2021-06-16 15:38:54 +00:00
Roman Golyshev
44f74888e0 FIR IDE: Add tests for resolving compiled declarations
Also, use correct index to find source for properties in
`FirIdeDeserializedDeclarationSourceProvider` - this bug
was revealed by the tests
2021-06-16 15:38:53 +00:00
Roman Golyshev
0fe068c6ce FIR IDE: Find FIR declarations for compiled PSI elements separately
When PSI declaration comes from the library with classfiles,
its `moduleInfo` is represented by `LibrarySourceInfo` class.
In this case we have to resort to other ways of looking for
corresponding FIR declaration

It is easy to do for classes (by `classId`) and for the properties
(by `classId` of the containing class and property's name)

It is harder for callables, so we use
`KtDeclarationAndFirDeclarationEqualityChecker` to do that
2021-06-16 15:38:52 +00:00
Roman Golyshev
be51738483 FIR IDE: Move KtDeclarationAndFirDeclarationEqualityChecker to idea-fir-low-level-api module
It will be required to compare PSI and FIR declarations
for compiled PSI elements
2021-06-16 15:38:51 +00:00
Roman Golyshev
66047f159f FIR IDE: Resolve declaration in withFirDeclaration only if needed 2021-06-16 15:38:51 +00:00
Roman Golyshev
9e4c5eed5f FIR IDE: Make ModuleLibrariesSearchScope work only on .class sources
If this scope will accepts sources, then it will cause problems later
(when we will get libraries' sources from indices and will try to
resolve them to FIR declaration)
2021-06-16 15:38:50 +00:00
Igor Chevdar
caa852061a [box-tests] Ignored a test for K/N
More info in https://youtrack.jetbrains.com/issue/KT-44571
2021-06-16 17:25:07 +05:00
Abduqodiri Qurbonzoda
59031543e2 Throw on invalid AbstractMutableList.addAll index #KT-47211 2021-06-16 11:59:46 +00:00
Nikita Nazarov
7e44cddbab Introduce the fragment compiler backend to the debugger infrastructure 2021-06-16 13:58:18 +03:00
pyos
aa47191de4 JVM: hide ExpressionCodegen in finally block generation during inlining 2021-06-16 12:13:32 +02:00
pyos
108bd01698 JVM: refine the stack spilling around inline calls
Not all suspend functions need it - only those with suspension points.
2021-06-16 12:13:32 +02:00
pyos
b136acb185 JVM: move callSiteFile to InlineCallSiteInfo 2021-06-16 12:13:32 +02:00
pyos
6c1a5e1211 JVM: make inline function argument processing a bit shorter 2021-06-16 12:13:32 +02:00
pyos
392e4fba42 JVM: fix inlining of default lambdas of signature (Result) -> Any
They have no `invoke` bridge, and the overridden invoke expectes a boxed
`Result` as an argument.
2021-06-16 12:13:32 +02:00
pyos
a0a14d9e25 JVM: remove descriptors from SourceCompilerForInline
Printing the call site source on errors isn't really useful anyway - the
old backend points to a specific PsiElement, and JVM_IR wraps the
exception in FunctionCodegen (and printing the source never worked with
JVM_IR anyway).
2021-06-16 12:13:32 +02:00
pyos
32ad747632 JVM: load default lambda method nodes immediately
The ones that are not needed are filtered out before DefaultLambda is
even constructed anyway, and this way we need fewer lateinit vars.
2021-06-16 12:13:32 +02:00
pyos
1e953eaf01 JVM: remove contextKind from SourceCompilerForInline
Guess what? It's only useful for the old backend's type mapper!
2021-06-16 12:13:32 +02:00
pyos
1109348b6d JVM: remove lookupLocation from SourceCompilerForInline 2021-06-16 12:13:32 +02:00
pyos
b6e9f64e18 JVM: remove functionDescriptor from InlineCodegen 2021-06-16 12:13:32 +02:00
pyos
d89e2d9f08 JVM: split inline intrinsics into "needed by JVM_IR" and "not"
or, alternatively, "suspend" and "not".
2021-06-16 12:13:32 +02:00
pyos
eb4d831d27 JVM_IR: implement typeOf<T> as a codegen intrinsic
rather than a fake inline function.

Also, generate more correct instructions for typeOf. Not sure how that
even worked before - `aconst(Boolean)` isn't even valid.
2021-06-16 12:13:32 +02:00
pyos
7dbf08ae1c JVM: move loadCompiledInlineFunction out of InlineCodegen 2021-06-16 12:13:32 +02:00
pyos
8307367f90 JVM: don't thread callDefault through the inliner
It's only used by the old backend, and should be given to
PsiSourceCompilerForInline by PsiInlineCodegen.
2021-06-16 12:13:32 +02:00
sebastian.sellmair
6dd598c7a7 [Gradle] Enable Kotlin tooling metadata artifact by default
^KT-44584
2021-06-16 09:44:32 +00:00
Igor Chevdar
a1e5bef3ad [box-tests] Ignored some tests for K/N
A file included twice in a source set is not supported for now
2021-06-16 14:27:14 +05:00
Iaroslav Postovalov
0ba3ddcc29 Minor. Fix a typo, change visibility of internal object 2021-06-16 10:22:44 +03:00
Svyatoslav Scherbina
e324c9b3fb Generate initRuntimeIfNeeded() at the beginning of staticCFunction
#KT-44283 Fixed
2021-06-16 06:39:51 +00:00
Yaroslav Chernyshev
6e9739caec Add regression test for MPP android source set with resources 2021-06-16 09:32:45 +03:00
Georgy Bronnikov
f0f01db66e Temporarily mute a failing test 2021-06-16 01:48:28 +03:00
Ilya Kirillov
39e2df6916 FIR IDE: render unresolved types as qualifiers for member generator 2021-06-16 01:17:44 +03:00
Ilya Kirillov
cf7870e376 FIR IDE: implement toString for KtType 2021-06-16 01:17:43 +03:00
Ilya Kirillov
af9e6253e4 FIR IDE: add ability to specify type argument in KtClassTypeBuilder 2021-06-16 01:17:42 +03:00
Ilya Kirillov
148c90dd1e FIR IDE: do not make KtTypeArgumentWithVariance abstract
As it does not require specific FIR implementation
2021-06-16 01:17:41 +03:00
Ilya Kirillov
6a9c49dd9d FIR IDE: rename coneType parameter in KtFirType constructors to not accidentally leak it via lambdas 2021-06-16 01:17:40 +03:00
Ilya Kirillov
1d1eab6947 FIR IDE: make KtSymbolByFirBuilder to be a weak ref in KtType to avoid memory leaks 2021-06-16 01:17:39 +03:00
Ilya Kirillov
73bb2e76f2 FIR IDE: introduce KtFirDefinitelyNotNullType 2021-06-16 01:17:38 +03:00
Ilya Kirillov
8177a70ff9 FIR IDE: introduce KtCapturedType 2021-06-16 01:17:36 +03:00
Ilya Kirillov
e2cfd933f1 FIR IDE: introduce HL API for creating class types 2021-06-16 01:17:35 +03:00
Ilya Kirillov
8094a5448d FIR IDE: render error message for KtClassErrorType 2021-06-16 01:17:34 +03:00
Ilya Kirillov
0a6c96492a FIR IDE: simplify KtType hierarchy
- get rid of Kt(Non)DenotatbleType super classes as unused
- make KtErrorType to inherit KtClassType to be consistent with FIR
2021-06-16 01:17:32 +03:00
Tianyu Geng
f6078b24df FIR IDE: AddToString quickfix 2021-06-15 20:19:53 +02:00
Tianyu Geng
1b8b5b9a79 FIR IDE: move AddToStringFix to fe-independent 2021-06-15 20:19:52 +02:00
Tianyu Geng
4bedf41f9c FIR IDE: RemoveNulalbleFix quickfix 2021-06-15 20:19:52 +02:00
Tianyu Geng
b10de3dd2d FIR IDE: Move RemoveNullableFix to fe-independent 2021-06-15 20:19:52 +02:00
Victor Petukhov
559bedf5ae Continue processing not builder inference stub variables in the type checker during computing common super type
^KT-47148 Fixed
2021-06-15 17:40:56 +03:00
Victor Petukhov
85f4cec948 Don't ignore Java nullability annotations without target and unresolved when nullability qualifiers are extracted, with enabled type enhancement improvements
^KT-47276 Fixed
2021-06-15 17:28:25 +03:00
Mads Ager
ae03e2983d [JVM_IR] Keep track of catch variable gaps.
This ensures that catch variables are not visible in duplicated
finally blocks generated at an exit within the catch variable
scope.

^KT-46449 Fixed
2021-06-15 15:18:59 +02:00
Elena Lepilkina
6aba6ea670 [K/N][perf] Fix separator stayed wrong after migrating from groovy 2021-06-15 11:39:25 +00:00
Victor Petukhov
9fa0cf132f Regenerate idea fir low level api tests 2021-06-15 12:52:06 +03:00
Pavel Punegov
f9d5cc90a8 [native] Disable test that fail due to the unaligned int64 access 2021-06-15 11:51:43 +03:00
Vasily Levchenko
695339e21f [k/n][tests][debugger] test for KT-47198. 2021-06-15 08:04:19 +00:00
Vasily Levchenko
524a9351de [k/n][tests][debugger] modify test to conform KT-47198 2021-06-15 08:04:18 +00:00
Vasily Levchenko
81fd6126d9 [k/n][codegen][d/i] dont generate debug line information for prolog and {locals,stack}_init
- fixes KT-47198
2021-06-15 08:04:17 +00:00
Vasily Levchenko
bb42e601ab [k/n][tests][lldb] add quit to each lldb tests. 2021-06-15 08:04:17 +00:00
Victor Petukhov
1b82227308 Don't do new captured type specific checks for old ones in the type checker
^KT-47143 Fixed
2021-06-15 10:07:20 +03:00
Nikita Bobko
02a56a3077 [imltogradle] Fix 'Configuration with name 'compileOnlyApi' not found' 2021-06-14 16:56:55 +02:00
Nikita Bobko
ce0bef6b60 Update 211 platform version for Kotlin plugin 2021-06-14 16:56:55 +02:00
Nikita Bobko
3bf7eef4d8 [imltogradle] Generate maven repos based on 'jarRepositories.xml' from Community
This commit minimizes difference between build.gradle.kts
files generated from ultimate & community infrastructure
2021-06-14 16:56:55 +02:00
Jinseong Jeon
ce26d54917 FIR IDE: extract PsiType conversions to KtPsiTypeProvider 2021-06-13 00:10:47 +03:00
Jinseong Jeon
0db510ad8b FIR IDE/UAST: introduce UAST-specific version of analyse 2021-06-13 00:10:46 +03:00
Jinseong Jeon
1517fd0ca0 FIR/UAST: commonoize array access expression 2021-06-13 00:10:45 +03:00
Jinseong Jeon
ef8eddf1da FIR UAST: add array access tests 2021-06-13 00:10:44 +03:00
Jinseong Jeon
9a539aac7d FIR/UAST: commonize binary expression with type 2021-06-13 00:10:43 +03:00
Jinseong Jeon
b2e644b485 FIR/UAST: commonize type check expression 2021-06-13 00:10:41 +03:00
Jinseong Jeon
6e0f755b39 UAST: migrate kinds constants to the base module 2021-06-13 00:10:39 +03:00
Jinseong Jeon
47ede5bdc8 FIR IDE/UAST: get PsiType from KtTypeReference 2021-06-13 00:10:38 +03:00
Jinseong Jeon
a3710bed6a FIR/UAST: commonize type reference expression 2021-06-13 00:10:37 +03:00
Jinseong Jeon
517fd24f14 UAST: unify implementation/creation of type reference expression 2021-06-13 00:10:36 +03:00
Jinseong Jeon
fa36098214 FIR IDE/UAST: get PsiType from KtExpression 2021-06-13 00:10:34 +03:00
Ilya Kirillov
7d7782e8ff Fix FE1.0 intention test 2021-06-12 23:53:46 +03:00
Mark Punzalan
235f4200df FIR IDE: Add descriptions for HLAddAccessorIntentions (copied from FE
1.0 implementations).
2021-06-12 23:53:45 +03:00
Mark Punzalan
9b5f754e75 FIR IDE: Enable add accessors quickfix for MUST_BE_INITIALIZED.
Also added diagnosticFixFactoriesFromIntentionActions() to share
quickfix-creation across multiple diagnostics with the same PSI.
2021-06-12 23:53:44 +03:00
Mark Punzalan
cd6dbd2515 FIR IDE: Assert that the action to invoke in
AbstractHighLevelQuickFixTest is of type QuickFixActionBase.
2021-06-12 23:53:43 +03:00
Mark Punzalan
783e5972d0 FIR IDE: Ensure all fixes provided by HLDiagnosticFixFactory are of type
QuickFixActionBase.

This allows us to verify in the quickfix tests that the action comes
from a diagnostic-based quickfix, and not an available intention. We
are adding APIs that wrap IntentionActions as QuickFixActionBase.
2021-06-12 23:53:42 +03:00
Mark Punzalan
43a8299f48 FIR IDE: Delete AddAccessorsIntention in favor of
HLAddAccessorIntentions.
2021-06-12 23:53:41 +03:00
Mark Punzalan
91e62832ee FIR IDE: Add applicability range to HLAddAccessorIntention (copied from
FE 1.0's logic) and actually check the range in AbstractHLIntention.
2021-06-12 23:53:40 +03:00
Mark Punzalan
a497dd1d31 FIR IDE: Enable add accessor intentions in plugin. 2021-06-12 23:53:39 +03:00
Ilya Kirillov
4f12966d66 FIR IDE: warn about enabled Android plugin 2021-06-12 19:40:43 +03:00
Ilya Kirillov
af7766b3ac FIR IDE: add fir icon to status bar to distinguish fir/fe10 ide 2021-06-12 19:40:42 +03:00
Jinseong Jeon
8977e7766b FIR/UAST: commonize throw expression 2021-06-12 16:00:43 +02:00
Jinseong Jeon
c21fce6cbc FIR/UAST: commonize parenthesized expression 2021-06-12 16:00:42 +02:00
Jinseong Jeon
c089b8ed04 FIR/UAST: commonize labeled expression 2021-06-12 16:00:41 +02:00
Jinseong Jeon
6e1b04e4c9 FIR/UAST: commonize if expression 2021-06-12 16:00:40 +02:00
Jinseong Jeon
50f750187b FIR/UAST: commonize loop/break/continue expressions 2021-06-12 16:00:39 +02:00
Jinseong Jeon
1146f60db3 FIR/UAST: commonize block and return expressions 2021-06-12 16:00:37 +02:00
Jinseong Jeon
16b3d2110e FIR/UAST: commonize literal expressions 2021-06-12 16:00:36 +02:00
Jinseong Jeon
6b5bddeed7 FIR/UAST: commonize KotlinEvaluatableUElement 2021-06-12 16:00:35 +02:00
Jinseong Jeon
ce10410aba FIR UAST: refactor FE1 UAST tests 2021-06-12 16:00:34 +02:00
Jinseong Jeon
e1a99ede09 FIR UAST: introduce values tests 2021-06-12 16:00:32 +02:00
Jinseong Jeon
cf2f36fa49 UAST: utilize values test base 2021-06-12 16:00:31 +02:00
Jinseong Jeon
d17dd4a1e6 FIR/UAST: commonize KotlinUElementWithType 2021-06-12 16:00:30 +02:00
Jinseong Jeon
1025851edd FIR UAST: introduce types tests 2021-06-12 16:00:29 +02:00
Jinseong Jeon
6afb68cec0 UAST: utilize types test base 2021-06-12 16:00:28 +02:00
Vyacheslav Gerasimov
06b4fe1613 Build: Fix kotlin-stdlib-jvm-minimal-for-test usages
Name changed after publishing with main artifacts for external usage
2021-06-12 04:33:32 +03:00
Steffi Stumpos
8baf570ee7 Build: Publish the new compiler test infrastructure 2021-06-12 04:33:31 +03:00
Mikhail Glukhikh
af5e2f3c93 FIR checkers: properly handle annotations with more than one argument 2021-06-11 22:03:33 +03:00
Mikhail Glukhikh
ceb527c5e4 FIR: add OptIn checkers draft + some annotation / SinceKotlin utilities 2021-06-11 22:03:32 +03:00
Mikhail Glukhikh
bd39e457a7 FIR: make ArrayMapOwner.arrayMap really protected 2021-06-11 22:03:32 +03:00
Mikhail Glukhikh
0972020324 Extract common parts from ExperimentalUsageChecker 2021-06-11 22:03:32 +03:00
Mikhail Glukhikh
f0453d2f5c FIR: distinguish qualified access / qualified access expression checkers 2021-06-11 22:03:32 +03:00
Mads Ager
6b6ba77869 [JVM_IR] Trim the expression test string for null assertions.
^KT-47166 Fixed.
2021-06-11 21:54:04 +03:00
Alexander Shabalin
58adfd8488 Disable enum and object isFrozen tests on wasm 2021-06-11 18:12:15 +00:00
Roman Golyshev
3f0cc67f17 Fix converting string GLOB to regexp in TestConfigurationBuilder
This is required when `p1|p2|p3|...|pN` concatenation is used (see `or`
extension function above `toMatchingRegexString`)

This is a follow-up to the 6f4b6c1b5b7bc05557306179e25a79fa234aa77f
commit
2021-06-11 20:06:04 +03:00
Roman Golyshev
30f20cb835 Use more reliable paths matching in TestConfigurationBuilder
Without it, even the slightest difference between the pattern and
testDataPath would cause the path to be excluded, for example:

testDataPath = /some/absolute/path.txt
pattern = absolute/*

The example above didn't match, and it resulted in different
configurations when tests were launched with different testDataPaths

Now, the example above will look like this:

testDataPath = /some/absolute/path.txt
patter = */absolute/*

Now it matches correctly
2021-06-11 20:06:03 +03:00
nataliya.valtman
d42a6771b0 Update statistics that should be sent to ES
Next properties should be set in gradle.properties or via -D option:
systemProp.kotlin.plugin.stat.password
systemProp.kotlin.plugin.stat.user
systemProp.kotlin.plugin.stat.enabled=true
systemProp.kotlin.plugin.stat.label
systemProp.kotlin.plugin.stat.endpoint=es_endpoint/index/_doc
kotlin.build.report.verbose=true
kotlin.build.report.enable=true
2021-06-11 19:12:05 +03:00
Dmitry Petrov
bf077b893c PSI2IR KT-47245 handle declaration statements in control structures 2021-06-11 16:42:31 +03:00
pyos
3be348f910 JVM_IR: fix parentClassId for property accessors 2021-06-11 15:03:13 +02:00
pyos
d4485bc475 JVM: remove unused methodOwner from InlineCodegen 2021-06-11 15:03:13 +02:00
pyos
ed26e97df8 JVM: refactor loading of inline functions from binaries
The IR path no longer does any descriptor unwrapping or old-style type
mapping.
2021-06-11 15:03:13 +02:00
pyos
7bcd738bb1 JVM: inline createInlineMethodNode into InlineCodegenForDefaultBody
Most of it is unused, since there we know the target function will also
need to be compiled from source.
2021-06-11 15:03:13 +02:00
pyos
4c7eb815fc JVM: remove some FunctionDescriptors from SourceCompilerForInline 2021-06-11 15:03:13 +02:00
pyos
a24ad233ee JVM: move PsiSourceCompilerForInline to a separate file 2021-06-11 15:03:13 +02:00
pyos
955b9260d1 JVM: move more old backend code out of InlineCodegen 2021-06-11 15:03:13 +02:00
pyos
043452fb62 JVM: make handling of captured params for default lambdas shorter 2021-06-11 15:03:13 +02:00
pyos
4cae880b44 JVM: remove unused DefaultLambda.parameterOffsetsInDefault 2021-06-11 15:03:13 +02:00
pyos
8a3af851d9 JVM: pregenerate inline lambda bodies as early as possible
Which in JVM_IR is immediately in `genValueAndPut`, but for the old
backend needs to be delayed until `genCallInner` for some reason.
2021-06-11 15:03:13 +02:00
pyos
90412ade8a JVM: remove second parameter of putClosureParametersOnStack
Only used by the old backend.
2021-06-11 15:03:13 +02:00
pyos
d4c8a033b1 JVM: remove BaseExpressionCodegen.pushClosureOnStack
It's only used by the old backend
2021-06-11 15:03:13 +02:00
pyos
b6c3c9942d JVM: move activeLambda to PsiInlineCodegen 2021-06-11 15:03:13 +02:00
pyos
7333abf50d JVM: purge redundant val BaseExpressionCodegen.v 2021-06-11 15:03:13 +02:00
pyos
1f9db7cf25 FE: properly clear the deferred generator stack
Before this commit the stack wasn't cleared for read variable case.
#KT-47168 Fixed
2021-06-11 15:56:20 +03:00
Sergey Bogolepov
2f632ada42 [Native] Remove unused code 2021-06-11 12:18:15 +00:00
Sergey Bogolepov
36386de9a2 [Native] Drop explicit -fPIC flag setup
We don't need to explicitly set -fPIC flag everywhere
because since d82109cc92
it is set by default for all ClangArgs users.
2021-06-11 12:18:14 +00:00
Sergey Bogolepov
7550351702 [Native] Fix runtime code according to Clang 11 warnings 2021-06-11 12:17:00 +00:00
Georgy Bronnikov
91387e644f IR: repair collectAndFilterRealOverrides 2021-06-11 15:05:45 +03:00
Georgy Bronnikov
7e6782d684 JVM_IR: simplify resolveFakeOverride call in SyntheticAccessorLowering 2021-06-11 15:05:45 +03:00
Georgy Bronnikov
fca804de14 IR: properly compute IrProperty.resolveFakeOverride()
Now that IrProperty has its own overriddenSymbols, we can generalize the
search for fake overrides. Also works for fake override properties
derived from Java fields.
2021-06-11 15:05:45 +03:00
Jinseong Jeon
3769fd8e07 FIR UAST: fix import resolve test
The `resolve` failure (or `null` return) of import directive for
`java.lang.Thread.sleep` is legitimate, since there are two static methods
in `java.lang.Thread`:
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html
hence not able to resolve to a single method.

Unless we change `UImportStatement` to be a subtype of `UMultiResolvable`,
instead of `UResolvable`, we can't properly test `resolve` API for that.
2021-06-11 14:51:07 +03:00
Yahor Berdnikau
da25d58fa7 Control cache redirector status in test via project settings.
Test will use project `gradle.properties` file to get current
cache redirector status, so it could be controlled from one place.

^KT-47185 Fixed
2021-06-11 11:44:36 +00:00
Yahor Berdnikau
7b1db6992e Enable cache redirector for old tests setup.
^KT-47185 Fixed
2021-06-11 11:44:35 +00:00
Yahor Berdnikau
e98de36aaa Enable cache redirector for Junit5 tests.
^KT-47185 In Progress
2021-06-11 11:44:34 +00:00
Yahor Berdnikau
5d0abf0e33 Lazily apply cache redirector to all project modules.
Mainly move it from 'afterEvaluate { .. }' block.

^KT-47185 In Progress
2021-06-11 11:44:34 +00:00
Viacheslav Kormushkin
3c0709cf4f A new DSL for framework configuration within cocoapods block
#KT-46479
#KT-35723
2021-06-11 11:10:49 +00:00
Mikhail Glukhikh
5a3f84c8fa Add forgotten test data file 2021-06-11 13:17:01 +03:00
Svyatoslav Scherbina
b13e7d1e28 Native: enable more Obj-C interop tests for new MM 2021-06-11 07:35:50 +00:00
Svyatoslav Scherbina
79d4047e86 Native: improve thread state switching for Obj-C interop 2021-06-11 07:35:49 +00:00
Svyatoslav Scherbina
85ab4f68df Native: support reentrant mode for CalledFromNativeGuard 2021-06-11 07:35:48 +00:00
sebastian.sellmair
1bcafd3cd0 [Gradle] commonizeCInterop task: Require hierarchical commonization to be enabled
^KT-47133 Verification Pending
2021-06-11 07:03:24 +00:00
Roman Golyshev
d781902626 Add possibility to use baseDir in SpecHelpersSourceFilesProvider
In IJ infrastructure we have specific path prefix for compiler testData
2021-06-11 02:28:39 +03:00
Vladimir Dolzhenko
2c8d583d8b Added ad-hoc KtValueArgument.stringTemplateExpression
Use only stub stringTemplateExpression if it is present and don't use ast nodes as it could be unbounded

#KT-47034 Fixed
2021-06-10 21:14:32 +00:00
Yahor Berdnikau
a383c1ce79 Ensure kapt tasks don't capture sources state in configuration cache.
Kapt tasks have captured sources state inside SourceRoots container
internal collection, that was cached by configuration cache.
This lead to the compilation errors whenever sources files
were changed (deleted or renamed), because kapt still expected
previous file state to exist.

Now SourceRoots will not create internal collection, but rather
reuse standard Gradle FileCollection methods that perform required
calculations dynamically.

^KT-46651 Fixed
2021-06-10 20:00:39 +00:00
Yahor Berdnikau
3d36e11e80 Make 'kapt.verbose' property compatible with configuration cache.
^KT-46651 In Progress
2021-06-10 20:00:38 +00:00
Ilya Kirillov
c4b1fa8ec0 Fix FE1.0 plugin testdata after adding // IGNORE_FIR directive 2021-06-10 19:05:33 +02:00
Ilya Kirillov
bc306a5195 FIR IDE: Regenerate quickfix tests 2021-06-10 19:05:33 +02:00
Tianyu Geng
90a0c9bb25 FIR IDE: quickfix to add override keyword
Also enables more tests that covers previous quickfixes
2021-06-10 19:05:33 +02:00
Alexander Likhachev
1658f4433d [Build] Update Gradle Enterprise plugin to 3.6.2 2021-06-10 18:39:21 +03:00
Alexander Likhachev
17991c5b6e [Build] Update common-custom-user-data-gradle-plugin to 1.4
Now the plugin detects IDEA via system properties using Gradle providers and shoudn't cause undeclared system property reads issue
#KT-44611 In Progress
2021-06-10 18:39:20 +03:00
Nikita Bobko
debc0d2b93 Add .idea/libraries-with-intellij-classes.xml to .gitignore 2021-06-10 17:37:50 +02:00
Vladimir Dolzhenko
1eb04d5440 Support Kotlin 1.5 / 1.6 language versions come from external sources
#KTIJ-15743 Fixed

Original commit: 784f77a2b98b0c9719f4919e45a193f35d7d9875
2021-06-10 13:12:36 +00:00
Dmitriy Novozhilov
1a0516e2c8 Fix codebase according to KT-47225 2021-06-10 16:01:18 +03:00
Tianyu Geng
baa3a3c81d FIR IDE: ignore smartcast if it's unstable in HL API 2021-06-10 16:01:17 +03:00
Tianyu Geng
78401b3ae0 FIR: add helper to check if a smartcast expressioin is stable 2021-06-10 16:01:16 +03:00
Tianyu Geng
3c8693758b FIR: handle synthetic properties with unstable smartcast
Synthetic properties from Java getter/setters need to be specially
handled so that candidates from such symbols are marked with unstable.
2021-06-10 16:01:14 +03:00
Tianyu Geng
ce767046eb FIR checkers: report SMARTCAST_IMPOSSIBLE 2021-06-10 16:01:13 +03:00
Tianyu Geng
2bb7ef9747 FIR DFA: store stability in RealVariable
As part of this change, we also extend the usage of RealVariable in more
places during DFA. Now mutable properties, property with custom getters,
delegated properties, etc are also treatd as a `RealVariable`. In
general this is needed in order to carry out smartcast computation in
order to report `SMARTCAST_IMPOSSIBLE`. It seems to also have side
effects that improves behavior of some test files.
2021-06-10 16:01:11 +03:00
Tianyu Geng
97ea37c82f FIR: add smartcast stability to FIR 2021-06-10 16:01:09 +03:00
Nikita Bobko
02bd17a4e2 Add compiler/fir/raw-fir/psi2fir/testData to testdata which is used by Kotlin plugin in IJ infra 2021-06-10 12:16:16 +02:00
Alexander Shabalin
cf47d95aa5 Rename SingleThreadMarkAndSweep into SameThreadMarkAndSweep 2021-06-10 09:59:38 +00:00
Alexander Shabalin
9ebba93dd9 Make SingleThreadMarkAndSweep support multiple threads 2021-06-10 09:59:37 +00:00
Alexander Shabalin
10ae9c511b Allow filtering of gtest tests 2021-06-10 09:59:37 +00:00
Svyatoslav Scherbina
11fb8677c6 Update kotlin-native/gradlew to 6.8.3
to match gradlew at repo root directory
2021-06-10 09:24:15 +00:00
Sebastian Sellmair
4e7460d91f Merge KT-MR-3320 from rra/sellmair/kt-46957-enable_linuxMips32_in_tests 2021-06-10 09:14:17 +00:00
Andrey Zinovyev
371452d49a [FIR] Fix CANNOT_BE_IMPORTED for java static methods/variables 2021-06-10 11:28:34 +03:00
Dmitriy Dolovov
2b161581ca K/N: Use class FQN in default toString() implementation
^KT-47167
2021-06-10 11:02:21 +03:00
Dmitriy Dolovov
d42ff069f6 [Native][IR] Move verbose RTTI for local classes and anonymous objects
^KT-45304
2021-06-10 11:02:16 +03:00
Dmitriy Dolovov
6bac016b3a [IR] Support top-level callables in InventNamesForLocalClasses lowering
^KT-45304
2021-06-10 11:02:10 +03:00
Dmitriy Dolovov
9861cb0438 [IR] Commonize InventNamesForLocalClasses lowering
^KT-45304
2021-06-10 11:02:04 +03:00
Yaroslav Chernyshev
6f8b3f22ca Fix adding non-directory to resources for Android source set
#KTIJ-17113 Fixed
2021-06-10 10:26:42 +03:00
Ilya Kirillov
e12f3ff88a FIR IDE: fix compilation 2021-06-09 22:49:57 +03:00
Mark Punzalan
befa8aaac7 FIR IDE: Enable add initializer quickfix for MUST_BE_INITIALIZED. 2021-06-09 22:49:56 +03:00
Mark Punzalan
bb2246ebaf FIR IDE: Add diagnosticFixFactories() API to share quickfix-creation
across multiple diagnostics with the same PSI.
2021-06-09 22:49:55 +03:00
Mark Punzalan
2773506f4c FIR IDE: Don't offer AddExclExclCallFix when expression is definitely
null.
2021-06-09 22:49:52 +03:00
Mark Punzalan
97ea901507 FIR IDE: Add isDefinitelyNull() and isDefinitelyNotNull() to
KtExpressionTypeProvider.
2021-06-09 22:49:51 +03:00
Mark Punzalan
c6427d57f1 FIR IDE: Enable AddExclExclCallFix for ASSIGNMENT_TYPE_MISMATCH and
INITIALIZER_TYPE_MISMATCH.
2021-06-09 22:49:50 +03:00
Mark Punzalan
eddc590aaf FIR: Rename parameters for (ASSIGNMENT|RESULT)_TYPE_MISMATCH. 2021-06-09 22:49:49 +03:00
Nikolay Krasko
b6b983aa2a Update kotlin:kotlin-build-gradle-plugin 0.0.29 -> 0.0.30 (KTI-563)
Remove ultimate mentioning
2021-06-09 22:19:53 +03:00
Nikolay Krasko
ee3fe6c605 Add dependency on dist in tests of kotlin.core.descriptors.runtime
JvmRuntimeDescriptorLoaderTestGenerated fails without stdlib.
2021-06-09 20:05:27 +03:00
Nikolay Krasko
85bc1d6aa2 Remove org.jfrog.buildinfo:build-info-extractor-gradle
There were some conflicts that shouldn't be an issue anymore.

Revert: 713f6e1ed3
2021-06-09 20:05:25 +03:00
Nikolay Krasko
965eff66ce Add information about protected branches 2021-06-09 20:05:24 +03:00
Nikita Bobko
3aebd0315f Make it possible to run DiagnosisCompilerTestDataSpecTestGenerated from fir-low-level-api in IJ infra 2021-06-09 19:44:08 +03:00
Nikita Bobko
294ec3905b [cleanup] Remove unused AbstractSymbolByFqNameTest 2021-06-09 19:44:06 +03:00
Andrey Uskov
446eb390ef Update Gradle version used in project to 6.9 2021-06-09 19:06:18 +03:00
Alexander Shabalin
b1e0e43ba4 Add isFrozen test on object 2021-06-09 15:03:15 +00:00
Nikolay Krasko
48a4d7d418 Build: drop maven publication for Kotlin plugin artifacts 2021-06-09 17:43:54 +03:00
Nikolay Krasko
32f811e0ec Build: Cleanup old platforms from the build 2021-06-09 17:43:53 +03:00
Nikolay Krasko
a4005cef19 Build: Drop ultimate, cidr and kmm from the build (KTI-563) 2021-06-09 17:43:52 +03:00
Alexander Likhachev
9a4ff6e201 [Gradle, JS] Add libraries filter caching in compile task
Previously any compile task was honestly reading dependency metadata from filesystem to check whether it's K/JS module even if another compile task already tested this dependency. Now the result of check is cached in build service that is cleared after build finish. It can save many rebuild time on incremental compilation of complex projects.
#KT-47154 Fixed
2021-06-09 17:25:56 +03:00
Dmitry Petrov
dbb933e6a6 JVM use instruction liveness analysis instead of DFA in DCE 2021-06-09 17:04:47 +03:00
Dmitry Petrov
3d8735c978 Minor: add excluded path to CodeConformanceTest 2021-06-09 17:04:46 +03:00
Nikita Bobko
2c92a60878 Fix obvious 'disableKotlinPluginModules' logging mistake 2021-06-09 15:44:10 +02:00
Nikita Bobko
a7894a6298 Introduce 'disableKotlinPluginModules' flag
We are about to drop Kotlin plugin sources from Kotlin repo
(since they are merged into intellij-commmunity repo).
Let's introduce the flag which we could use for testing
2021-06-09 15:41:37 +02:00
Tianyu Geng
32f55a2269 FIR checker: report VIRTUAL_MEMBER_HIDDEN 2021-06-09 16:27:49 +03:00
Tianyu Geng
d3dfb33f89 FIR: consolidate duplicated logic in FirOverrideChecker 2021-06-09 16:27:26 +03:00
Nikita Bobko
8bb98f8f86 [imltogradle] Do not resolve transitive dependencies in gralde if don't resolve them in JPS
This fixes problems of Gradle not being possible to find transitive maven artifacts
if actually we don't need them
2021-06-09 15:16:18 +02:00
Pavel Kirpichenkov
d76bb45716 [Commonizer] Add CommonizerHierarchicalIT
Test platform dependencies on leaf source sets
^KT-46716 Verification pending
2021-06-09 12:49:07 +00:00
Pavel Kirpichenkov
5f7576e546 [Commonizer] Use original K/N distribution libraries for leaf targets
^KT-46716
2021-06-09 12:49:04 +00:00
Mikhail Glukhikh
c33608e009 FIR: don't render resolved type annotations in favor of attributes 2021-06-09 15:42:43 +03:00
Mikhail Glukhikh
06379ec587 FIR: handle varargs properly during annotation serialization 2021-06-09 15:42:42 +03:00
Mikhail Glukhikh
da671eedc9 FIR: avoid CCE in constants during annotation serialization 2021-06-09 15:42:41 +03:00
Mikhail Glukhikh
3127fad23d FIR: more precise annotation argument serialization 2021-06-09 15:42:39 +03:00
Mikhail Glukhikh
491267b4f7 FIR2IR: convert annotations on local variables 2021-06-09 15:42:38 +03:00
Mikhail Glukhikh
77dd0ad396 FIR: handle custom attributes more precise 2021-06-09 15:42:37 +03:00
Mikhail Glukhikh
4f70f47fa6 FIR2IR: convert annotations on type parameters #KT-46967 Fixed 2021-06-09 15:42:36 +03:00
Svyatoslav Scherbina
3412c0bc53 Update kotlin-native/samples to 1.5.10 2021-06-09 12:35:05 +00:00
Andrey Zinovyev
ddc9c1bd1b [FIR] Fix extension property reference resolution
On type with star projection
#KT-44372 Fixed
2021-06-09 15:15:28 +03:00
Mikhail Glukhikh
2b4ea8e6e7 Add forgotten test data 2021-06-09 14:59:57 +03:00
Vasily Levchenko
89b589846b Merge KT-MR-3224 from rrn/minamoto/kt-33364 2021-06-09 11:50:28 +00:00
Ilya Goncharov
dd9ea9f9eb [Gradle, JS] Actualize versions of npm dependencies
^KT-46608 fixed
^KT-47176 fixed
2021-06-09 14:49:33 +03:00
pyos
ade8b0a7d3 JVM_IR: box bound receiver before calling the reference constructor
This is needed for the inliner: since the information about Kotlin type
of the bound receiver is nowhere in the output binary, the inliner will
have no clue how to box inline class values. Moving the boxing outside
the object means the inliner doesn't need to know about it; from its
point of view, the captured value has type `Any`.
2021-06-09 14:36:07 +03:00
nataliya.valtman
117c99aee6 send build stat to ES 2021-06-09 13:25:10 +03:00
Sergey Igushkin
14a7e90c69 KT-38954: Filter Android attributes during publishing
* Always filter out the variant name attribute: it is never requested
  by consumers, while its presence makes Gradle count it as an
  unmatched attribute, sometimes leading to ambiguity;

* Filter out the build type attribute: if all variants have the same
  build type, then remove the build type attribute from all variants;
  Otherwise, remove the build type attribute from the release variants
  in order to make them compatible with all other consumer's build 
  types.

  * Add an opt-out flat for always keeping the attribute:
    "kotlin.android.buildTypeAttribute.keep" Gradle property

Issue #KT-38954 Fixed
2021-06-09 10:18:15 +00:00
sebastian.sellmair
4e508c6d9c Update K/N version to 1.5.30-dev-1916
^KT-46957
2021-06-09 11:53:58 +02:00
sebastian.sellmair
f9901a5d50 [Commonizer] CommonizerIT: Enable linuxMips32 target
^KT-46957
2021-06-09 11:47:57 +02:00
Vasily Levchenko
79600f32d2 [codegenerator][refactor] extract method for tramboline generation 2021-06-09 11:39:57 +02:00
Vasily Levchenko
0651f7de20 [kotlin-native][tests] kt-33364 test added 2021-06-09 11:39:56 +02:00
Vasily Levchenko
bebede9e4f [codegeneration][debug info] enchance debugger behaviour for paramterless when
- generates tramboline like a11b07f6c3 on -Xg-generate-when-marker=enable
- fixes issue KT-33364
2021-06-09 11:39:55 +02:00
Vladimir Dolzhenko
de76aeb9d1 Optimize SdkInfo lookup for a huge monorepo with no SdkInfo
DFS of SdkInfo on moduleInfo and reuse cached libraryInfo dependencies
fix traverse order

#KT-47065 Fixed
Relates to #KT-46622
2021-06-09 08:31:46 +00:00
Andrey Zinovyev
972cd9e9e7 [FIR] Fix PACKAGE_CANNOT_BE_IMPORTED diagnostic
Don't report it when there is a function/property with the same name as
package
2021-06-09 09:02:49 +03:00
Yahor Berdnikau
ec705d88a5 Allow to enable Gradle debug for particular builds.
^KT-45745 In Progress
2021-06-08 21:05:39 +02:00
Yahor Berdnikau
90238978ee Update block to print build info on error.
^KT-45745 In Progress
2021-06-08 21:05:38 +02:00
Yahor Berdnikau
b0b646037e Print build output on build result assertion failure.
^KT-45745 In Progress
2021-06-08 21:05:38 +02:00
Yahor Berdnikau
5b60ef7d54 Allow to enable force output for specific builds.
^KT-45745 In Progress
2021-06-08 21:05:38 +02:00
Yahor Berdnikau
8b17888a18 Fix typo in annotation name.
^KT-45745 In Progress
2021-06-08 21:05:35 +02:00
Aleksei.Cherepanov
35c067b215 Fix import for JPS build of Kotlin repo
Changed link of configuration on TC for getting artifacts
from "Compiler Dist (202) and Maven Artifacts"
to "Kotlin / Kotlin Public / Aggregate"
2021-06-08 22:01:31 +03:00
Denis.Zharkov
2653565f56 FIR: Support exhaustive whens on subjects of intersection type 2021-06-08 18:59:48 +03:00
Anton Lakotka
c8b9a3a6f0 Disallow unsafe reads of KPM PluginData from Compile Task 2021-06-08 15:49:05 +00:00
Anton Lakotka
52abecab43 Rename sensitive flag to isTransient and inverse logic, add file outputs
isTransient with default value as false makes it a bit more readable
Some Compiler Plugins can use file outputs properties to dump some data
there and gradle can support incremental build
with file outputs.
2021-06-08 15:49:05 +00:00
Anton Lakotka
70a2678bbc Add integration test for kpm compiler plugin sensitive options 2021-06-08 15:49:04 +00:00
Anton Lakotka
c01be75f47 Reuse code in MetadataCompilationTasksConfigurator for native task 2021-06-08 15:49:03 +00:00
Anton Lakotka
28fe070a2f Track plugin options with indices 2021-06-08 15:49:02 +00:00
Anton Lakotka
bc7ff04f1f Store sensitive plugin options in Task inputs 2021-06-08 15:49:01 +00:00
Anton Lakotka
9e084a7256 Fix overload call of project.files in abstractVariants.kt 2021-06-08 15:49:01 +00:00
Anton Lakotka
26a2509ebb Add basic test for Kotlin Project Model compiler plugins 2021-06-08 15:49:00 +00:00
Anton Lakotka
a0fb5c31ea Don't configure runtimeDependencyFiles during variant instantiation 2021-06-08 15:48:59 +00:00
Anton Lakotka
5a58c1c437 [Kotlin Project Model] Add compiler plugin support 2021-06-08 15:48:58 +00:00
Nikita Bobko
16e6fe0e08 Fix compilation for some Kotlin plugin modules when IJ infra is attached to kotlin repo
For example it fixes compilation of `:kotlin-ide.kotlin.generators:testClasses`

This commit fixes that Gradle tries to find jars of 202 IDEA in ivy repo of 211 IDEA:
```
* What went wrong:
Execution failed for task ':kotlin-ide.kotlin.tests-common:compileTestKotlin'.
> Could not resolve all files for configuration ':kotlin-ide.kotlin.tests-common:testCompileClasspath'.
   > Could not find extensions-211.6693.111.jar (kotlin.build:ideaIC:211.6693.111).
     Searched in the following locations:
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/ideaIC/211.6693.111/artifacts/lib/extensions.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/ideaIC/211.6693.111/artifacts/extensions.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/intellij-core/211.6693.111/artifacts/extensions.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/ideaIC/211.6693.111/artifacts/plugins/ideaIC/lib/extensions.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/sources/extensions-211.6693.111.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/ideaIC/211.6693.111/extensions.jar
   > Could not find guava-29.0-jre-211.6693.111.jar (kotlin.build:ideaIC:211.6693.111).
     Searched in the following locations:
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/ideaIC/211.6693.111/artifacts/lib/guava-29.0-jre.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/ideaIC/211.6693.111/artifacts/guava-29.0-jre.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/intellij-core/211.6693.111/artifacts/guava-29.0-jre.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/ideaIC/211.6693.111/artifacts/plugins/ideaIC/lib/guava-29.0-jre.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/sources/guava-29.0-jre-211.6693.111.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/ideaIC/211.6693.111/guava-29.0-jre.jar
   > Could not find asm-all-8.0.1-211.6693.111.jar (kotlin.build:ideaIC:211.6693.111).
     Searched in the following locations:
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/ideaIC/211.6693.111/artifacts/lib/asm-all-8.0.1.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/ideaIC/211.6693.111/artifacts/asm-all-8.0.1.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/intellij-core/211.6693.111/artifacts/asm-all-8.0.1.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/ideaIC/211.6693.111/artifacts/plugins/ideaIC/lib/asm-all-8.0.1.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/sources/asm-all-8.0.1-211.6693.111.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/ideaIC/211.6693.111/asm-all-8.0.1.jar
   > Could not find streamex-0.7.2-211.6693.111.jar (kotlin.build:ideaIC:211.6693.111).
     Searched in the following locations:
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/ideaIC/211.6693.111/artifacts/lib/streamex-0.7.2.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/ideaIC/211.6693.111/artifacts/streamex-0.7.2.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/intellij-core/211.6693.111/artifacts/streamex-0.7.2.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/ideaIC/211.6693.111/artifacts/plugins/ideaIC/lib/streamex-0.7.2.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/sources/streamex-0.7.2-211.6693.111.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/ideaIC/211.6693.111/streamex-0.7.2.jar
```
2021-06-08 17:18:35 +02:00
Nikita Bobko
bf287c0b85 [imltogradle] Don't generate unnecessary tests-jar with real dependencies when a module doesn't have any source root
This helps to prevent "fake" circular dependencies when
module A depends on tests of module B but module B doesn't have test source roots

In particular this commit fixes when running `:kotlin-ide.kotlin.generators:testClasses` task:
```
Circular dependency between the following tasks:
:kotlin-ide.kotlin.gradle.gradle-tooling:compileTestJava
+--- :kotlin-ide.kotlin.gradle.gradle-tooling:compileTestKotlin
|    \--- :kotlin-ide.kotlin.test-framework:testJar
|         +--- :kotlin-ide.kotlin.test-framework:compileTestKotlin
|         |    +--- :kotlin-ide.kotlin.idea:testJar
|         |    |    +--- :kotlin-ide.kotlin.idea:compileTestKotlin
|         |    |    |    \--- :kotlin-ide.kotlin.gradle.gradle-tooling:testJar
|         |    |    |         +--- :kotlin-ide.kotlin.gradle.gradle-tooling:compileTestKotlin (*)
|         |    |    |         \--- :kotlin-ide.kotlin.gradle.gradle-tooling:testClasses
|         |    |    |              \--- :kotlin-ide.kotlin.gradle.gradle-tooling:compileTestJava (*)
|         |    |    \--- :kotlin-ide.kotlin.idea:testClasses
|         |    |         \--- :kotlin-ide.kotlin.idea:compileTestJava
|         |    |              +--- :kotlin-ide.kotlin.gradle.gradle-tooling:testJar (*)
|         |    |              \--- :kotlin-ide.kotlin.idea:compileTestKotlin (*)
|         |    \--- :kotlin-ide.kotlin.jvm:testJar
|         |         +--- :kotlin-ide.kotlin.jvm:compileTestKotlin
|         |         |    +--- :kotlin-ide.kotlin.gradle.gradle-tooling:testJar (*)
|         |         |    +--- :kotlin-ide.kotlin.idea:testJar (*)
|         |         |    \--- :kotlin-ide.kotlin.repl:testJar
|         |         |         +--- :kotlin-ide.kotlin.repl:compileTestKotlin
|         |         |         |    \--- :kotlin-ide.kotlin.idea:testJar (*)
|         |         |         \--- :kotlin-ide.kotlin.repl:testClasses
|         |         |              \--- :kotlin-ide.kotlin.repl:compileTestJava
|         |         |                   +--- :kotlin-ide.kotlin.idea:testJar (*)
|         |         |                   \--- :kotlin-ide.kotlin.repl:compileTestKotlin (*)
|         |         \--- :kotlin-ide.kotlin.jvm:testClasses
|         |              \--- :kotlin-ide.kotlin.jvm:compileTestJava
|         |                   +--- :kotlin-ide.kotlin.gradle.gradle-tooling:testJar (*)
|         |                   +--- :kotlin-ide.kotlin.idea:testJar (*)
|         |                   +--- :kotlin-ide.kotlin.jvm:compileTestKotlin (*)
|         |                   \--- :kotlin-ide.kotlin.repl:testJar (*)
|         \--- :kotlin-ide.kotlin.test-framework:testClasses
|              \--- :kotlin-ide.kotlin.test-framework:compileTestJava
|                   +--- :kotlin-ide.kotlin.idea:testJar (*)
|                   +--- :kotlin-ide.kotlin.jvm:testJar (*)
|                   \--- :kotlin-ide.kotlin.test-framework:compileTestKotlin (*)
\--- :kotlin-ide.kotlin.test-framework:testJar (*)
```
2021-06-08 17:15:17 +02:00
Sergey Bogolepov
bcd28615a6 [Native] Add initial version of LLVM buildscript
Previously there was no determined way to build LLVM for Kotlin/Native.
This commits adds a Python script that allows to do so on all hosts.
2021-06-08 14:42:43 +00:00
Ilya Matveev
1530a0823f [K/N] Use finalization task to generate report for runtime tests
The approach with doLast doesn't work if the test binary failed.
This patch uses a finalization task instead to ensure that we
process the XML report regardless of whether the tests pass
or fail.
2021-06-08 12:44:14 +00:00
Ilya Matveev
f08d473d3c [K/N][Runtime tests] Support << operator for thread states 2021-06-08 12:44:13 +00:00
Elena Lepilkina
7ed22360f9 [K/N] Use in array varargs optimized implementations of set operators without bound checks 2021-06-08 11:59:56 +00:00
Elena Lepilkina
2cb3a20733 [K/N] Added functions for set/get array operatorswithout bounds check 2021-06-08 11:59:56 +00:00
Leonid Startsev
dd21326425 Create a copy of incorrectly deserialized parent's writeSelf function
To avoid problems during code generation when INVOKEDYNAMIC
is used instead of static

#KT-47161 Fixed
2021-06-08 11:53:47 +00:00
Vladimir Ivanov
7c7905b55c [Native] Disable unaligned float test (not supported yet) (#4434) 2021-06-08 13:18:58 +03:00
Dmitriy Novozhilov
773fc25587 Fix compilation after 3572a96b 2021-06-08 12:16:03 +03:00
Sergey Bogolepov
1ae8e01b32 [Native][MIPS] Add stddef.h to platform.posix on linux
For some reason, ptrdiff_t is missing in platform.posix on MIPS,
yet referenced from platform.linux.__morecore. Fixed by adding parent
header.
This fix is ABI for MIPS targets breaking because some declarations move
from platform.linux to platform.posix package.

^KT-46957 Fixed
2021-06-08 09:02:49 +00:00
Mikhail Glukhikh
0e63484738 Fix OptIn marker usages in code according to new limitation 2021-06-08 11:37:35 +03:00
Mikhail Glukhikh
63bc3f9708 Forbid experimental markers on various targets #KT-45845 Fixed
In this commit we forbid experimental markers on:
- local variables
- value parameters
- fields, including delegate fields
- property getters
2021-06-08 11:37:34 +03:00
Mikhail Glukhikh
eb9c658c1c OptIn: handle usages via type aliases properly 2021-06-08 11:37:33 +03:00
Mikhail Glukhikh
b4ee116de7 Experimental checkers: simplify visiting code a bit 2021-06-08 11:37:32 +03:00
Mikhail Glukhikh
702d839c66 Forbid TYPE and TYPE_PARAMETER as possible OptIn targets 2021-06-08 11:37:31 +03:00
Mikhail Glukhikh
603afe89a2 Forbid using experimental markers on override declarations
#KT-45844 Fixed
2021-06-08 11:37:30 +03:00
Mikhail Glukhikh
bb9efab3c4 Forbid experimental markers on getter #KT-45845 Fixed 2021-06-08 11:37:29 +03:00
Mikhail Glukhikh
0a670bf055 Report EXPERIMENTAL_API diagnostics on various implicit usages
#KT-32443 Fixed
#KT-22852 Fixed
2021-06-08 11:37:28 +03:00
Mikhail Glukhikh
d8d38862d9 Introduce EXPERIMENTAL_ANNOTATION_WITH_WRONG_RETENTION diagnostic
#KT-22941 Fixed
2021-06-08 11:37:27 +03:00
Mikhail Glukhikh
7393465696 Don't report EXPERIMENTAL_OVERRIDE_ERROR on annotated local functions
#KT-31728 Fixed
2021-06-08 11:37:26 +03:00
Mikhail Glukhikh
cb232725f0 FoldConstantLowering: drop unnecessary experimental annotation 2021-06-08 11:37:25 +03:00
Mikhail Glukhikh
fa307a5f75 Drop LocalCallableIdConstructor OptIn-annotation 2021-06-08 11:37:24 +03:00
Andrey Zinovyev
3572a96bb9 [FIR] Lookup in local sources in default imports based on the flag
Reuse ALLOW_KOTLIN_PACKAGE for that
2021-06-08 08:23:25 +00:00
Andrey Zinovyev
3eeddf7077 [FIR] Use member scope to look up function/property by name 2021-06-08 08:18:57 +00:00
Andrey Zinovyev
c507d1c938 [FIR] Implement OPERATOR_RENAMED_ON_IMPORT diagnostic 2021-06-08 08:18:56 +00:00
Andrey Zinovyev
7c669b65c3 [FIR] Implement CONFLICTING_IMPORT diagnostic 2021-06-08 08:18:55 +00:00
Andrey Zinovyev
14789cb9e5 [FIR] Implement CANNOT_BE_IMPORTED diagnostic 2021-06-08 08:18:54 +00:00
Andrey Zinovyev
bf153ab0f0 [FIR] Implement CANNOT_ALL_UNDER_IMPORT_FROM_SINGLETON diagnostic 2021-06-08 08:18:54 +00:00
Abduqodiri Qurbonzoda
fdd9287836 Get rid of platform differences in Regex.split() doc 2021-06-08 00:32:33 +00:00
Abduqodiri Qurbonzoda
0b521b5183 Get rid of platform differences in Regex.findAll() doc 2021-06-08 00:32:32 +00:00
Abduqodiri Qurbonzoda
53b6c25533 Get rid of platform differences in Grouping<T, K>.eachCount() doc 2021-06-08 00:32:31 +00:00
Abduqodiri Qurbonzoda
91d1baf3b5 Get rid of platform differences in Array.orEmpty() doc 2021-06-08 00:32:30 +00:00
Abduqodiri Qurbonzoda
cc3c33b8ae Get rid of platform differences in Collection<T>.toTypedArray() doc 2021-06-08 00:32:29 +00:00
Abduqodiri Qurbonzoda
c64592665b Get rid of platform differences in MutableList.sortWith() doc 2021-06-08 00:32:29 +00:00
Abduqodiri Qurbonzoda
a9946b01e6 Get rid of platform differences in MutableList.sort() doc 2021-06-08 00:32:28 +00:00
Abduqodiri Qurbonzoda
225be54c61 Get rid of platform differences in Regex.find doc 2021-06-08 00:32:27 +00:00
Abduqodiri Qurbonzoda
7fdd1154ee Add default value for K/N actual functions #KT-46183 2021-06-08 00:32:26 +00:00
konrad.sztenderski
e338c5651b Expose some methods and properties related to Cocoapods dependencies to access them in Apple gradle plugin 2021-06-07 21:28:07 +02:00
Dmitry Petrov
81b09ca09f KT-46267 JVM_IR don't generate unnecessary ATHROW in lateinit var read 2021-06-07 20:02:24 +03:00
Simon Ogorodnik
d3453e98b0 FIR Tests: Add async-profiler per-pass sampling to full pipeline 2021-06-07 19:43:28 +03:00
Simon Ogorodnik
718e9c11f5 FIR Tests: Fix FirMetaModularizedTest to run properly on Windows 2021-06-07 19:43:10 +03:00
Elena Lepilkina
97a38ba0a9 [K/N] Added benchmarks for KT-46482 and KT-46425 2021-06-07 14:35:32 +00:00
Ilya Kirillov
74567f4b02 FIR IDE: restore fir ide spec tests with shorten test class name to make TC happy
Otherwise, TC will complain about too long fq test method names
2021-06-07 16:48:56 +03:00
Ivan Kylchik
cc169613c1 Drop result of finally block after interpretation
This change is needed due to using FIR as frontend for tests. In this
case finally block doesn't has coercion to unit so it's result must
be dropped manually.
2021-06-07 15:35:20 +03:00
Ivan Kylchik
61d65436f4 Fix interpreter files provider to make tests work on windows 2021-06-07 15:35:19 +03:00
Ivan Kylchik
5596e1e1e1 Properly support char and boolean arrays in interpreter
For now boolean array will expect proper Boolean instead of any value.
This change just unify logic of working with primitive arrays.
2021-06-07 15:35:18 +03:00
Ivan Kylchik
25989b36c5 Allow to create object in interpreter only if it is compile time 2021-06-07 15:35:16 +03:00
Ivan Kylchik
6e12cee626 Extract common checker logic into accessesTopLevelOrObjectField 2021-06-07 15:35:15 +03:00
Ivan Kylchik
49d8bd5845 Remove unnecessary property message from interpreter exceptions 2021-06-07 15:35:14 +03:00
Ivan Kylchik
e28ab45c51 Add ir interpreter tests 2021-06-07 15:35:12 +03:00
Ivan Kylchik
cc2d7340dc Implement simple test system to check ir interpreter correctness 2021-06-07 15:35:11 +03:00
Ivan Kylchik
3b250132d0 Put all logic of working with expect/actual declarations inside Wrapper
For now decision of how to work with class or function is made by their
signatures.
2021-06-07 15:35:09 +03:00
Ivan Kylchik
0cc866a2fb Support Enum class as intrinsic in ir interpreter
Methods of Enum class don't have bodies, so must be treated as
intrinsics
2021-06-07 15:35:08 +03:00
Ivan Kylchik
e5617ede7e Add Throwable class into interpreter builtins map
Methods of Throwable class doesn't have bodies using FIR, so they must
be handled as builtins
2021-06-07 15:35:07 +03:00
Ivan Kylchik
8234c9cec1 Add toString function with nullable receiver into builtins map
On JVM we don't have body for this function, so we must process it as
intrinsic or builtin
2021-06-07 15:35:06 +03:00
Ivan Kylchik
7882fdf232 Simplify logic of checking that IrGetField can be interpreted 2021-06-07 15:35:04 +03:00
Ivan Kylchik
ca1932b3a5 Set proper fir type for deserialized annotation's arguments 2021-06-07 15:35:03 +03:00
Ivan Kylchik
b3fa7b25cf Optimize Utils.kt by removing unused functions 2021-06-07 15:35:02 +03:00
Ivan Kylchik
877832ef8c Optimize some methods of CallStack and Frame 2021-06-07 15:35:01 +03:00
Ivan Kylchik
e0438d1123 Implement better workflow of interpretation with callable reference 2021-06-07 15:34:59 +03:00
Ivan Kylchik
9a8e0f3fb3 Add new builtins methods for some interfaces into IrBuiltInsMapGenerated
This change allow us to skip looking for override when evaluate call
for some primitive.
2021-06-07 15:34:58 +03:00
Ivan Kylchik
b4463b948c Rewrite unfoldValueParameters to take into account recursive calls
The workflow of evaluation value arguments is now like this:
1. Calculate not null arguments
2. Add them into intermediate stack
3. Calculate defaults for those parameters that have no argument
This flow allow us to avoid early addition of variable onto stack.
2021-06-07 15:34:57 +03:00
Ivan Kylchik
6411d09579 Rewrite wrap function to take into account function name
This is needed to understand whenever arrays must be unwrapped or not.
For now, in case of kotlin.Array.set and kotlin.Pair.<init> calls it is
considered to remain arrays as Primitive class to save their irType
info.
2021-06-07 15:34:55 +03:00
Ivan Kylchik
04b36ff19e Make interpreted functions implicitly return Unit as result 2021-06-07 15:34:54 +03:00
Ivan Kylchik
0e8ca12499 Add callback to methods of CallInterceptor to specify default behaviour 2021-06-07 15:34:53 +03:00
Ivan Kylchik
285929ad07 Add new intercept method in CallInterceptor for proxy 2021-06-07 15:34:52 +03:00
Ivan Kylchik
25d01099d8 Add CallInterceptor interface and implement its default realization
CallInterceptor will handle calls, constructor calls, getting enum
entries and objects. It will make a decision for interpreter: this call
must be handled as intrinsic or it must be interpreted.
2021-06-07 15:34:50 +03:00
Ivan Kylchik
c8b268a789 Refactor entire IrInterpreter to achieve better code quality 2021-06-07 15:34:49 +03:00
Ivan Kylchik
3294af5e49 Get correct irClass from class reference in case of reified parameter 2021-06-07 15:34:47 +03:00
Ivan Kylchik
fe99b235d3 Implement more precise control flow in ir interpreter
"More precise" in terms of the number of passing tests.
In this case ControlStructures test block was used.
2021-06-07 15:34:46 +03:00
Ivan Kylchik
c3ad319c13 Implement correct processing for receivers of IrFunctionReference 2021-06-07 15:34:44 +03:00
Ivan Kylchik
a73173e480 Fix interpretation of arguments with default value 2021-06-07 15:34:43 +03:00
Ivan Kylchik
38f4e6e8bf Implement interpretation of assert method 2021-06-07 15:34:42 +03:00
Ivan Kylchik
8617809528 Rename expression value parameter to declaration 2021-06-07 15:34:40 +03:00
Alexander Udalov
e6254b51e1 Rewrite generator for IrBuiltInsMapGenerated
Similarly to 742fef9042 with OperationsMapGenerated, use optimized
`when` over strings instead of lambdas because lambdas lead to a lot of
bytecode.

The change in `IrConst.toPrimitive` is needed because for operations
like `Byte.plus(Int)` the IrConst instance would have the IR type for
kotlin.Byte, but the actual runtime value of type Int
(java.lang.Integer), which would lead to CCE from
`interpretBinaryFunction`. Previously it didn't fail because of
unchecked cast before calling the lambda, which allowed a value of
runtime type java.lang.Integer to sneak through to the lambda parameter
and be "unboxed" to the correct type via the `(... as Number).toByte()`
conversion which backend generates.

The main benefit of this change is that it reduces the size of the
proguarded compiler jar by ~0.69%.
2021-06-07 15:34:39 +03:00
Ivan Kylchik
ac7a1c7762 Add new intrinsic handler for sourceLocation function 2021-06-07 15:34:38 +03:00
Ivan Kylchik
7fe776fe10 Simplify work with stack by adding additional newFrame method 2021-06-07 15:34:37 +03:00
Ivan Kylchik
d578aa0ec5 Pass irFile in interpreter method in IrConstTransformer 2021-06-07 15:34:35 +03:00
Ivan Kylchik
ec16c40bf4 Save right entry point for expression 2021-06-07 15:34:34 +03:00
Ivan Kylchik
9d9ab498aa Remove typeArguments field in State interface 2021-06-07 15:34:33 +03:00
Ivan Kylchik
a10d88924f Simplify getIrFunctionByIrCall method in KFunctionState
Removed check of invoke symbols equality. Without this check it is
possible to store init functions in KFunctionState
2021-06-07 15:34:32 +03:00
Ivan Kylchik
3d1d86e9cb Change call method of KProperty1Proxy to invoke corresponding accessors 2021-06-07 15:34:30 +03:00
Ivan Kylchik
64d5cea337 Implement getter and setter for KPropertyProxy 2021-06-07 15:34:29 +03:00
Ivan Kylchik
f89b75e387 Implement interpretation of KParameter interface 2021-06-07 15:34:28 +03:00
Ivan Kylchik
a4edddaa6e Extract all reflection state classes into separate files 2021-06-07 15:34:26 +03:00
Ivan Kylchik
aa321f2333 Move ReflectionState.kt into separate package "reflection" 2021-06-07 15:34:25 +03:00
Ivan Kylchik
5a95e5b45f Implement interpretation for KType and KTypeParameter 2021-06-07 15:34:24 +03:00
Ivan Kylchik
88b5b5f702 Implement interpretation of KVisibility class
For now it is interpreted as Wrapper, but maybe further it will be
converted to Common
2021-06-07 15:34:23 +03:00
Ivan Kylchik
40bf4fafc9 Implement basic interpretation of IrClassReference 2021-06-07 15:34:22 +03:00
Ivan Kylchik
002804941f Replace Lambda state with KFunctionState 2021-06-07 15:34:21 +03:00
Ivan Kylchik
749200d518 Fix constructor call checker
Forget to check constructor for availability of compile time annotation
2021-06-07 15:34:19 +03:00
Ivan Kylchik
41ea1525d1 Implement basic interpretation for KProperty 2021-06-07 15:34:18 +03:00
Ivan Kylchik
c3d0438405 Allow to interpret property reference 2021-06-07 15:34:16 +03:00
Ivan Kylchik
ac858f760a Forbid vararg flattening in place there array was expected 2021-06-07 15:34:15 +03:00
Ivan Kylchik
8b2706aaee Change interpretConstructor method to be able to init object single time 2021-06-07 15:34:13 +03:00
Ivan Kylchik
903e883809 Add additional type arguments to stack from super types 2021-06-07 15:34:12 +03:00
Ivan Kylchik
a9d686b9f9 Add outer object to stack when interpreting constructor of inner class 2021-06-07 15:34:11 +03:00
Ivan Kylchik
b570d3f7fd Fix interpreter error related to recreating Unit object 2021-06-07 15:34:09 +03:00
Ivan Kylchik
b98f680d65 Fix interpreter error related to incorrect work of get value for objects 2021-06-07 15:34:08 +03:00
Ivan Kylchik
d931e2eead Implement simple proxy for non interface structures like kotlin.Pair 2021-06-07 15:34:07 +03:00
Ivan Kylchik
1e5096294e Implement proxy for custom interfaces 2021-06-07 15:34:06 +03:00
Ivan Kylchik
96a090f2ab Implement LambdaProxy class 2021-06-07 15:34:04 +03:00
Ivan Kylchik
1d0acedc48 Rewrite Complex class as interface
This change allow ExceptionState to be both: State and Throwable
2021-06-07 15:34:03 +03:00
Ivan Kylchik
6808151af7 Remove method getOriginal from Complex class
Common class no longer contains Common super classes,
all fields are now inside one single object.
2021-06-07 15:34:02 +03:00
Ivan Kylchik
4c75576414 Implement basic proxy for Common state
For now proxy works only for Any class methods and only for Common
state.
2021-06-07 15:34:01 +03:00
Ivan Kylchik
3c0c8d97cc Add possibility to interpret spread operator on unsigned arrays 2021-06-07 15:33:59 +03:00
Ivan Kylchik
ca231ccc53 Rethrow InterpreterTimeOutError as UserException 2021-06-07 15:33:58 +03:00
Ivan Kylchik
c23e8517b3 Fix type arguments saving for arrays 2021-06-07 15:33:57 +03:00
Ivan Kylchik
7ecf4b17b6 Change evaluation function for arrayOf
For now it will get only elements variable from stack instead of all
2021-06-07 15:33:56 +03:00
Ivan Kylchik
4010eb11bd Implement method to calculate EQEQ ir builtin function 2021-06-07 15:33:54 +03:00
Ivan Kylchik
9b1f11b22b Extend compile time checker to check constructors body 2021-06-07 15:33:53 +03:00
Ivan Kylchik
cc0bbac354 Support isSubtypeOf check for functional type 2021-06-07 15:33:52 +03:00
Ivan Kylchik
c1aa39065f Add handler for setters in getIrFunction method 2021-06-07 15:33:49 +03:00
Ivan Kylchik
6a483a8464 Add simple handler for StackOverflowError in ir interpreter 2021-06-07 15:33:48 +03:00
Ivan Kylchik
f3d7dc5f22 Rewrite exceptions handler in ir interpreter
For now there are 2 types of exceptions:
1. UserExceptions - express user and jvm like exceptions
2. InterpreterError - thrown only if something is wrong with interpreter
2021-06-07 15:33:47 +03:00
Ivan Kylchik
c3b0c9c6b2 Support multiple nested try blocks 2021-06-07 15:33:46 +03:00
Ivan Kylchik
ad6ba0cf11 Support lateinit var interpretation 2021-06-07 15:33:45 +03:00
Ivan Kylchik
b45df06680 Forbid to interpret non const top level properties 2021-06-07 15:33:43 +03:00
Ivan Kylchik
393ad9ae9b Fix compile time checker for get and set field expressions 2021-06-07 15:33:42 +03:00
Ivan Kylchik
a084dabdde Return Unit value from block if statements count is equal to zero 2021-06-07 15:33:41 +03:00
Ivan Kylchik
13ab7eafca Move out compile time function checker logic to EvaluationMode.kt 2021-06-07 15:33:40 +03:00
Ivan Kylchik
84e6e1e305 Add WITH_ANNOTATIONS evaluation mode
This mode means that function can be executed if it has
CompileTimeCalculation annotation. FULL mode for now will mean deep
check without annotation help
2021-06-07 15:33:39 +03:00
Ivan Kylchik
1151c6177b Move IrCompileTimeChecker to separate checker package 2021-06-07 15:33:37 +03:00
Ivan Kylchik
47ed6789d2 Fix interpreting of java static members such as Boolean.TRUE 2021-06-07 15:33:36 +03:00
Denis.Zharkov
592256976e FIR: Fix inference of builder-inference function from expect type
Previously, such calls were being completed with FULL mode and incorrect
INFERENCE_NO_INFORMATION_FOR_PARAMETER has been reported
2021-06-07 15:25:57 +03:00
Denis.Zharkov
18e93b50d9 FIR: Fix loading read-only collection Java types with incorrect variance 2021-06-07 15:25:56 +03:00
Denis.Zharkov
5ade831665 FIR: Fix INFERENCE_NO_INFORMATION_FOR_PARAMETER on type alias with generic expansion
^KT-46996 Fixed
2021-06-07 15:25:55 +03:00
Denis.Zharkov
d76db0e011 FIR: Mute backend tests relevant to new INFERENCE_NO_INFORMATION_FOR_PARAMETER
See KT-46967 and KT-46996
2021-06-07 15:25:53 +03:00
Denis.Zharkov
d932d5b0a5 FIR: Support adding expect type to calls in foo() as R position
See https://kotlinlang.org/docs/whatsnew12.html#support-for-foo-as-a-shorthand-for-this-foo
2021-06-07 15:25:51 +03:00
Denis.Zharkov
6136526a3a FIR: Avoid reporting inference errors from DelegatedPropertyConstraintPosition
All necessary diagnostics have already been reported through the checkers
2021-06-07 15:25:50 +03:00
Denis.Zharkov
43f3fe1ebe FIR: Avoid missing errors during delegation resolution
Merge inference errors from delegation partially resolved calls to the main system
2021-06-07 15:25:49 +03:00
Denis.Zharkov
0aca3a3737 FIR: Adjust test data after introduction of INFERENCE_NO_INFORMATION_FOR_PARAMETER
See previous commits for details
2021-06-07 15:25:47 +03:00
Denis.Zharkov
c420957eac FIR: Report INFERENCE_NO_INFORMATION_FOR_PARAMETER diagnostic 2021-06-07 15:25:45 +03:00
Pavel Punegov
6e901e3785 Filter out JRE installations on MacOS
java_home tool shows also JRE installations located at
"/Library/Internet Plug-Ins/JavaAppletPlugin.plugin" path.
They should not be used as there are no javac and other tools there.
2021-06-07 11:03:08 +00:00
Anton Yalyshev
9b8ae8ce4f 1.5.20-RC Change-notes correction. 2021-06-07 13:51:46 +03:00
Anton Yalyshev
503700d60b Add change notes for 1.5.20-RC 2021-06-07 13:51:44 +03:00
sebastian.sellmair
70924f6c15 [Commonizer] Link ticket ^KT-47100 in HierarchicalPropertyCommonizationTest 2021-06-07 09:07:43 +00:00
sebastian.sellmair
ffcd57cb31 [Commonizer] TypeCommonizer: Support commonizing typeAlias and their underlying types 2021-06-07 09:07:43 +00:00
sebastian.sellmair
92093bbabd [Commonizer] HierarchicalPropertyCommonizationTest.test differently typeAliased property - * 2021-06-07 09:07:42 +00:00
sebastian.sellmair
0cf1618960 [Commonizer] Implement CirNodeRelationship over CommonizerCondition 2021-06-07 09:07:41 +00:00
sebastian.sellmair
8272564ca0 [Commonizer] Prototype: Commonize TypeAliases with Classes
^KT-45992 Fixed
^KT-46061 Fixed
2021-06-07 09:07:40 +00:00
sebastian.sellmair
b394dde339 [Commonizer] Implement HierarchicalClassAndTypeAliasCommonizationTest
^KT-45992
^KT-46061
2021-06-07 09:07:39 +00:00
pyos
d5200e3688 JVM_IR: box returned Result if overriding Any?
This is only relevant with MangleClassMembersReturningInlineClasses
disabled, as otherwise returning Result causes name mangling and thus
bridges.
2021-06-07 09:57:42 +02:00
pyos
0bd8d16fe2 JVM_IR: fix Result types in continuations & remove more codegen hacks
#KT-47129 Fixed
2021-06-07 09:57:42 +02:00
Pavel Punegov
e8490f950a Chose archive name depending on the version of the compiler 2021-06-06 14:44:34 +00:00
Pavel Punegov
ca3150163d Use old archive naming in the NativePlatformLibsIT test 2021-06-06 14:44:33 +00:00
Ilya Muradyan
8be5f009f1 [REPL] Fix completion for function arguments 2021-06-06 09:00:52 +03:00
Nikolay Krasko
0bc34f0ff9 Add information about 211.6693.111 Community idea to verification 2021-06-04 21:39:33 +03:00
Nikolay Krasko
17f042a4a3 Add information about 211.6693.111 Ultimate idea to verification 2021-06-04 21:39:32 +03:00
Nikolay Krasko
2401c37795 Fix double registration of NodeJSPlugin tasks
Can be reproduced when both ``intellijVersionForIde` and `installIntellijUltimate` are enabled
2021-06-04 21:39:31 +03:00
Nikolay Krasko
07be073e7f Minor: regenerate verification-metadata.xml 2021-06-04 21:39:30 +03:00
Dmitry Petrov
7fd033adae JVM_IR KT-47073 use type parameter upper bound for default value 2021-06-04 20:54:01 +03:00
Svyatoslav Scherbina
e4b723fe4a Native: enable some of ObjCExport tests with new GC 2021-06-04 16:58:27 +00:00
Svyatoslav Scherbina
fa36ccedeb Native: improve ObjCExport thread state switching 2021-06-04 16:58:26 +00:00
Svyatoslav Scherbina
388538be60 Native: minor exception handling refactoring
Move parts of exception handling implementation from IrToBitcode
to CodeGenerator, to allow using filteringExceptionHandler in ObjCExport.
2021-06-04 16:58:25 +00:00
Nikolay Krasko
2801704ad3 Temporary remove DiagnosisCompilerTestDataSpecTestGenerated.java tests
Buildserver fails because of too long path names
2021-06-04 18:25:45 +03:00
Nikolay Krasko
478b1f65fb Fix builds: ideaIC might be absent in the build 2021-06-04 15:15:13 +03:00
Ilya Kirillov
febc4986d1 FIR IDE: mute spec testdata based test failing in FIR IDE 2021-06-04 13:16:18 +02:00
Ilya Kirillov
d474ff2b03 FIR IDE: generate tests based on compiler spec tests for ide 2021-06-04 13:16:18 +02:00
Ilya Kirillov
335a2d7b71 FIR IDE: add tests based on compiler spec tests for ide 2021-06-04 13:16:17 +02:00
Ilya Kirillov
a8a31231f7 Get rid of duplicated file names in spec tests
Otherwise, corresponding IDE tests would fail on creation duplicated
files in the same directory
2021-06-04 13:16:17 +02:00
Victor Petukhov
2d3ed4b7da Update FIR test data 2021-06-04 13:25:10 +03:00
Alexander Gorshenev
f5d656ec4f [Native] Revert klib printer change 2021-06-04 02:36:54 +03:00
Ivan Kochurkin
c4c2fbb5a0 [FIR] Implement RECURSIVE_TYPEALIAS_EXPANSION, CYCLIC_INHERITANCE_HIERARCHY diagnostics, fix stackoverlow exception in case if typealias points to type with type arguments 2021-06-03 20:41:58 +03:00
Mark Punzalan
d1531f9cdd FIR: Choose a resolved candidate for augmented assignment when both
assign and operator candidates are unsuccessful.
2021-06-03 20:18:04 +03:00
Mark Punzalan
32bb64a225 FIR: Report UNSAFE_OPERATOR_CALL for augmented assignments (was
reporting UNSAFE_CALL).
2021-06-03 20:18:03 +03:00
Mark Punzalan
ef923d4cfe FIR IDE: Enable ReplaceInfixOrOperatorCallFix for
UNSAFE_IMPLICIT_INVOKE_CALL.
2021-06-03 20:18:02 +03:00
Mark Punzalan
6de1000818 FIR: Report UNSAFE_INFIX_CALL for all infix-style calls, even if the
candidate is not an infix function.

This mirrors FE 1.0 (see
`AbstractTracingStrategy.reportUnsafeCallOnBinaryExpression()`) and
allows consistent handling for quickfixes on infix calls.
2021-06-03 20:18:01 +03:00
Mark Punzalan
ca7649edbb FIR IDE: Enable ReplaceInfixOrOperatorCallFix for UNSAFE_CALL,
UNSAFE_INFIX_CALL, UNSAFE_OPERATOR_CALL.
2021-06-03 20:17:59 +03:00
Mark Punzalan
5a7f4ffc99 FIR IDE: Enable tests for ReplaceInfixOrOperatorCallFix. 2021-06-03 20:17:58 +03:00
Mark Punzalan
afeeec3091 IDE: Move ReplaceInfixOrOperatorCallFix to idea-frontend-independent. 2021-06-03 20:17:57 +03:00
Mark Punzalan
5a6d543fba IDE: Don't do any resolution in ReplaceInfixOrOperatorCallFix.invoke(). 2021-06-03 20:17:56 +03:00
Mark Punzalan
06adb405e1 IDE: Remove duplicate quickfix message in resources. 2021-06-03 20:17:54 +03:00
Ilya Kirillov
e5f6e4e1e8 FIR IDE: do not fail on FirDeclarationOrigin.ImportedFromObject for symbol 2021-06-03 19:39:16 +03:00
Ilya Kirillov
be99f24278 FIR IDE: fix uast import test after fixing import references 2021-06-03 19:39:15 +03:00
Ilya Kirillov
ae7a6dc742 FIR IDE: remove error handling from function completion 2021-06-03 19:39:13 +03:00
Ilya Kirillov
a1fcc34bbc FIR IDE: choose better name for completion helpers 2021-06-03 19:39:12 +03:00
Ilya Kirillov
2e57361457 FIR IDE: add type arguments and -> symbol to when conditions completion 2021-06-03 19:39:11 +03:00
Ilya Kirillov
fa2f2c34cb FIR IDE: fix flaky completion test 2021-06-03 19:39:09 +03:00
Ilya Kirillov
108176d0b6 FIR IDE: enable passing completion tests 2021-06-03 19:39:08 +03:00
Ilya Kirillov
88129c3354 FIR IDE: implement completion inside string templates 2021-06-03 19:39:07 +03:00
Ilya Kirillov
59b22fadad FIR IDE: add tests for completion where clause 2021-06-03 19:39:06 +03:00
Ilya Kirillov
edbfff71e9 FIR IDE: fix shortenings for enums 2021-06-03 19:39:05 +03:00
Ilya Kirillov
0da488058d FIR IDE: add tests for completion in sealed when 2021-06-03 19:39:03 +03:00
Ilya Kirillov
9af0885e82 FIR IDE: implement completion in sealed when 2021-06-03 19:39:02 +03:00
Ilya Kirillov
4bdf46e0a4 FIR IDE: fix icon for enum entry 2021-06-03 19:39:01 +03:00
Ilya Kirillov
1e1ce3067f FIR IDE: implement basic classifier name contributor 2021-06-03 19:39:00 +03:00
Ilya Kirillov
58d5907041 FIR IDE: do not complete after where constraint type param with qualifier 2021-06-03 19:38:59 +03:00
Ilya Kirillov
ff369b1917 IDE/FIR IDE: fix not showed following type parameters in completion 2021-06-03 19:38:57 +03:00
Ilya Kirillov
0f13359229 FIR IDE: implement completion in where clause 2021-06-03 19:38:56 +03:00
Ilya Kirillov
5b5bbdd113 FIR IDE: add receiver parameter for callable lookup elements in completion 2021-06-03 19:38:55 +03:00
Ilya Kirillov
aef071691f FIR IDE: refactor: separate lookup element factories into different files 2021-06-03 19:38:54 +03:00
Ilya Kirillov
62e4b53d03 FIR IDE: fix not added import for functions 2021-06-03 19:38:52 +03:00
Ilya Kirillov
0534d3fb98 fix after rebase 2021-06-03 19:38:51 +03:00
Ilya Kirillov
a926a1f534 FIR IDE: handle . after package name in completion tests 2021-06-03 19:38:50 +03:00
Ilya Kirillov
4785f36d8d FIR IDE: implement completion for packages 2021-06-03 19:38:49 +03:00
Ilya Kirillov
943ae108f5 FIR IDE: introduce import statement completion 2021-06-03 19:38:48 +03:00
Ilya Kirillov
c998d0f026 FIR: make FirStaticScope to be name aware 2021-06-03 19:38:47 +03:00
Ilya Kirillov
b81ef157b2 FIR IDE: fix reference resolve in import statement 2021-06-03 19:38:45 +03:00
Ilya Kirillov
55621b7aad FIR IDE: do not complete callables for classifier without companion 2021-06-03 19:38:44 +03:00
Ilya Kirillov
365bc5712b FIR IDE: do not add internal packages to completion 2021-06-03 19:38:42 +03:00
Ilya Kirillov
48b69b4f3f FIR IDE: add test for super keyword completion with qualifier 2021-06-03 19:38:41 +03:00
Ilya Kirillov
0a6243fc67 FIR IDE: implement super qualifier completion 2021-06-03 19:38:40 +03:00
Ilya Kirillov
7d351ca6b1 FIR IDE: add possibility to have different testdata for fir & fe10 keyword tests 2021-06-03 19:38:39 +03:00
Ilya Kirillov
c81a9c9d18 FIR IDE: mute test which fails as we have no decalration name completion 2021-06-03 19:38:37 +03:00
Ilya Kirillov
0739f6974f FIR IDE: fix completion of type arguments without closing > 2021-06-03 19:38:36 +03:00
Ilya Kirillov
d510f0809a FIR IDE: do not break formatting of reference shortenner 2021-06-03 19:38:35 +03:00
Ilya Kirillov
11e77d464d FIR IDE: add completion with package receiver 2021-06-03 19:38:34 +03:00
Ilya Kirillov
e77783a0e5 FIR IDE: add packages name completion 2021-06-03 19:38:32 +03:00
Ilya Kirillov
df93dc91d1 FIR IDE: fix package reference resolve 2021-06-03 19:38:31 +03:00
Ilya Kirillov
d76ec9db50 FIR IDE: add completion for annotations 2021-06-03 19:38:30 +03:00
Ilya Kirillov
6b450e6fdf FIR: make FirOnlyClassifiersScope/FirOnlyCallablesScope to be name aware 2021-06-03 19:38:29 +03:00
Ilya Kirillov
fcc5af99f3 FIR IDE: enable passing keyword tests 2021-06-03 19:38:27 +03:00
Ilya Kirillov
f7cf80b8e9 FIR IDE: render short names as for completion lookup element types 2021-06-03 19:38:26 +03:00
Ilya Kirillov
a718a2c2d8 FIR IDE: fix completion of top level type aliases 2021-06-03 19:38:25 +03:00
Ilya Kirillov
bcf7116955 FIR IDE: add type completion with dot 2021-06-03 19:38:24 +03:00
Ilya Kirillov
e03916e7fb FIR IDE: add index helper to FirBasicCompletionContext 2021-06-03 19:38:22 +03:00
Ilya Kirillov
6c9831f7d4 FIR IDE: separate callable and type completion 2021-06-03 19:38:21 +03:00
Ilya Kirillov
e7288b3293 FIR IDE: extract FirCallableCompletionContributor 2021-06-03 19:38:20 +03:00
Ilya Kirillov
8dda232ae3 FIR IDE: move CompletionVisibilityChecker/ExtensionApplicabilityChecker to dedicated package 2021-06-03 19:38:19 +03:00
Ilya Kirillov
a437cd9d86 FIR IDE: do not capture KtAnalysisSession receiver for CompletionVisibilityChecker/ExtensionApplicabilityChecker 2021-06-03 19:38:18 +03:00
Ilya Kirillov
3df075061c FIR IDE: extract classifier completion separate completion provider 2021-06-03 19:38:17 +03:00
Victor Petukhov
1e5998e0ba Add constraints between two different stub variables instead of creating constraint error due to T1 isn't subtype of T2
^KT-44241 Fixed
2021-06-03 19:18:09 +03:00
Nikita Bobko
071ae301b4 Add possibility to use baseDir in AdditionalDiagnosticsSourceFilesProvider
In IJ infrastructure we have specific path prefix for compiler testData
2021-06-03 19:05:47 +03:00
Jinseong Jeon
10f19c8f4a FIR UAST: invalidate caches between tests 2021-06-03 17:56:16 +02:00
Jinseong Jeon
37d8e6ddc3 FIR UAST: relocate render/log test data 2021-06-03 17:56:16 +02:00
Jinseong Jeon
80b94a43b0 FIR/UAST: split KotlinUIdentifier into a separate file 2021-06-03 17:56:16 +02:00
Jinseong Jeon
68766024b3 FIR/UAST: commonize Identifier implementations 2021-06-03 17:56:16 +02:00
Jinseong Jeon
6af930f6df FIR UAST: convert LeafPsiElement to UIdentifier 2021-06-03 17:56:16 +02:00
Jinseong Jeon
83256ef3bd FIR UAST: introduce identifiers and refNames tests 2021-06-03 17:56:16 +02:00
Jinseong Jeon
c37123603c UAST: utilize identifier test base 2021-06-03 17:56:16 +02:00
Ivan Kochurkin
da15f0ffe8 [FIR] Consider fullyExpandedType instead of original type in isSubtypeForTypeMismatch, consider lookupTag in isError method 2021-06-03 18:24:36 +03:00
Ivan Kochurkin
0b0a96a1d3 [FIR] Fix processing of nested type arguments, extract extractTypeRefAndSourceFromTypeArgument method to FirHelpers and use it from FirClassVarianceChecker and FirConflictingProjectionChecker 2021-06-03 18:24:35 +03:00
Ivan Kochurkin
f081a6b4fa [FIR] Implement REDUNDANT_PROJECTION diagnostics, rename FirConflictingProjectionChecker -> FirProjectionRelationChecker, fix tests 2021-06-03 18:24:34 +03:00
Ivan Kochurkin
03e577bf98 [FIR] Implement CONFLICTING_PROJECTION_IN_TYPEALIAS_EXPANSION diagnostics, fix tests 2021-06-03 18:24:32 +03:00
Ivan Kochurkin
ca970f0a8b [FIR] Add ConeKotlinTypeConflictingProjection, return it from substituteArgument instead of ConeStarProjection in appropriate cases, remove plus operator from ProjectionKind 2021-06-03 18:24:30 +03:00
Ivan Kochurkin
b85846c0c0 [FIR] Fix location for CONFLICTING_PROJECTION diagnostics, extend conflictingProjection.kt with test sample 2021-06-03 18:24:29 +03:00
Ilya Goncharov
ce78457eaa [Gradle, JS] Use replace by just string, not regexp in webpack config
^KT-43379 fixed
2021-06-03 17:55:05 +03:00
Ilya Goncharov
8c38c4a8e7 [Gradle, JS] Add dependency from packageJson task on included build's rootPackageJson 2021-06-03 17:55:04 +03:00
Victor Petukhov
19c07e048a Don't check suitability of a builder inference call if unrestricted builder inference is enabled
^KT-42139 Fixed
2021-06-03 17:28:40 +03:00
Dmitry Savvinov
f8fbbc01b6 Don't append 'is a module' suffix to ModuleDescriptor debug text 2021-06-03 17:22:00 +03:00
Dmitry Savvinov
708fead1cc Add debug strings to frontend scopes-related structures
Such as:
- PackageFragmentProviders, and, in particular,
CompositePackageFragmentProviders
- JavaPackageFragments
- Scopes produced by those providers

The rationale is that a lot of frontend-facing bugs (like red code) are
easily recognizeable in resolution. But at that point you just see a
bunch of scopes, without meaningful toStrings, you don't know who has
produced them, and what's exactly wrong.

With this commit it should make debugging slightly easier: now at least
you'll be able to see that "this scope is a scope of package fragment
for foo.bar of module baz" and decide whether the declaration should or
should not have been resolved from such scope.
2021-06-03 17:21:59 +03:00
Alexander Dudinsky
a51c65ed60 Update test data for MultiModuleHighlightingTest.testLanguageVersionsViaFacets
Add `Resolved to error element` markers
2021-06-03 16:42:24 +03:00
Nikita Bobko
e4205e5aa7 Pack 'compiler/testData/diagnostics/helpers' into kotlin-compiler-testdata-for-ide
This testdata is required for AbstractDiagnosisCompilerTestDataTest in FIR IDE in IJ infrastructure
2021-06-03 15:34:46 +02:00
Mikhail Glukhikh
2bf0e6744d FIR2IR: optimize coerceToUnitIfNeeded in implicit cast inserter 2021-06-03 16:14:42 +03:00
Mikhail Glukhikh
13d91837be FIR: cache functional type symbols in type resolver 2021-06-03 16:14:42 +03:00
Mikhail Glukhikh
1294c8de53 FIR: don't get class symbol if it's unnecessary (Java type conversion) 2021-06-03 16:14:41 +03:00
Nikita Bobko
3c7b07b90f Include tests-compiler-utils into kotlin-compiler-tests-for-ide artifact
It fixes:
```
java.lang.NoClassDefFoundError: org/jetbrains/kotlin/fir/FirCfgConsistencyChecker

	at org.jetbrains.kotlin.test.frontend.fir.handlers.FirCfgConsistencyHandler.processModule(FirCfgConsistencyHandler.kt:15)
	at org.jetbrains.kotlin.test.frontend.fir.handlers.FirCfgConsistencyHandler.processModule(FirCfgConsistencyHandler.kt:13)
	at org.jetbrains.kotlin.test.TestRunnerKt.processModule(TestRunner.kt:236)
	at org.jetbrains.kotlin.test.TestRunnerKt.hackyProcess(TestRunner.kt:231)
	at org.jetbrains.kotlin.test.TestRunnerKt.access$hackyProcess(TestRunner.kt:1)
```
while running `DiagnosisCompilerTestFE10TestdataTestGenerated.Tests#testBinaryCallsOnNullableValues` (and probably other tests) in new infrastructure
2021-06-03 15:04:10 +02:00
Dmitry Petrov
107e71acb0 Minor: fix Android tests 2021-06-03 13:05:23 +03:00
pyos
4128d27510 JVM_IR: do not use invokedynamic for inline fun references 2021-06-03 13:05:23 +03:00
Mads Ager
5d53d34d85 Fix regression test for KT-46962. 2021-06-03 13:05:23 +03:00
Victor Petukhov
124a14c8df Use separate constraint position during call substitution as part of inferring postponed type variables
^KT-47052 Fixed
^KT-47082 Fixed
2021-06-03 12:37:17 +03:00
Ilmir Usmanov
7a2ecc58d4 Minor. Regenerate tests 2021-06-03 12:35:26 +03:00
pyos
d5d3d9f112 Add regression tests for KT-46890 and other stuff 2021-06-03 12:35:25 +03:00
pyos
ada4c48eba JVM_IR: correctly (?) unbox Result when needed
and don't unbox when not needed.

 #KT-46890 Fixed
2021-06-03 12:35:24 +03:00
pyos
288451db4d JVM_IR: remove an unnecessary hack from BridgeLowering
Correct IR is more important than whether some inaccessible members
precisely match what was generated by the old backend.
2021-06-03 12:35:23 +03:00
Dmitriy Novozhilov
6f54e9fd5c Revert "FIR: add smartcast stability to FIR"
This reverts commit 96bd2c54
2021-06-03 09:54:02 +03:00
Dmitriy Novozhilov
0497f60af3 Revert "FIR DFA: store stability in RealVariable"
This reverts commit 62f7e8f7
2021-06-03 09:53:57 +03:00
Dmitriy Novozhilov
796f8e6bce Revert "FIR checkers: report SMARTCAST_IMPOSSIBLE"
This reverts commit 84334b08
2021-06-03 09:48:50 +03:00
Ilya Kirillov
20d1a84002 FIR/FIR IDE: fix FirFailingTestSuppressor for IDE
We need to have IdeTestIgnoreHandler executed after FirFailingTestSuppressor,
otherwise IdeTestIgnoreHandler will suppress exceptions
and FirFailingTestSuppressor will throw error
saying that file .fir.fail exists but test passes
2021-06-03 00:19:52 +03:00
Ilya Kirillov
948d9390d6 FIR: "//TODO make thread safe" comment from FirBuiltinSymbolProvider 2021-06-03 00:09:03 +03:00
Ilya Kirillov
f361312e45 FIR: use FirCachesFactory in BuiltInsPackageFragment.tryGetSyntheticFunctionalInterface 2021-06-03 00:09:02 +03:00
Ilya Kirillov
ba2315430b FIR: get rid of lateinit var in FirBuiltinSymbolProvider for thread safety 2021-06-03 00:09:01 +03:00
Ilya Kirillov
863156679d FIR: use FirCachesFactory in BuiltInsPackageFragment.getClassLikeSymbolByFqName 2021-06-03 00:09:00 +03:00
Dmitry Petrov
7a43c2de79 JVM remove dead code during constant condition elimination
This avoids an extra call to 'analyze', which is rather costly.

Update debugger testData: Constant condition
elimination now performs DCE more consistently.
2021-06-03 00:08:27 +03:00
Dmitry Petrov
1fd94d1bc2 JVM Minor: cleanup RedundantNullCheckMethodTransformer 2021-06-03 00:08:25 +03:00
Mads Ager
0b5ec5535c [JVM_IR] Add String.plus(Any) to intrinsics list.
This filters it out for use in SAM wrapper generation with
invoke-dynamic.

The intrinsic is not actually used for code generation so
it is added to the list of intrinsics that should have been
lowered away before codegen.

^KT-45779 Fixed
2021-06-03 00:04:47 +03:00
Alexander Udalov
c1021623e8 Do not use ClassLoader.getResourceAsStream in reflection
Use ClassLoader.getResource + openStream instead, to workaround an issue
in URLClassLoader.

Also set useCaches to false because kotlin-reflect only reads builtins
metadata once per class loader, and doesn't need it to be cached. Using
caches here might also lead to the problem of closed input streams when
protobuf is read in parallel. The test doesn't check exactly this,
though (it seems to succeed even if cached connections are used).

Note that BuiltInsResourceLoader has a JDK 9+ specialization at
libraries/reflect/api/src/java9, but that implementation does not need
any changes because it uses Module.getResourceAsStream which is not
affected by this issue in URLClassLoader.

 #KT-18277 Fixed
2021-06-02 22:54:16 +02:00
Vasily Levchenko
a0503aa2d7 [kotlin-native][test][debugger] exclude non constant part of stack trace from gold values
(cherry picked from commit ac072d3cc0aea0d311062f58fb5382cac6912deb)
2021-06-02 18:36:59 +00:00
Nikita Bobko
ea24da117b Publish compiler testdata which is required for Kotlin plugin 2021-06-02 21:30:03 +03:00
Sergey Shanshin
71c9e62d64 Added support serialization of local classes in IR backend
Resolves Kotlin/kotlinx.serialization#1427
2021-06-02 16:43:31 +00:00
Pavel Punegov
ac0dc94800 Since 1.5.30-dev-1466 a new archive naming schema was introduced
Support both names in NativeCompilerDownloader
2021-06-02 18:30:52 +03:00
Pavel Punegov
789799ac17 Revert simpleOsName in HostManager
Support old naming in simpleOsName.
Introduce new platformName method for the new archive naming.
2021-06-02 18:30:52 +03:00
Leonid Startsev
1f837134bb Support for @EncodeDefault annotation 2021-06-02 13:43:39 +00:00
Alexander Dudinsky
e6e3c9b236 Use master name for tests with snapshot version Kotlin Gradle Plugin 2021-06-02 15:23:31 +03:00
Roman Artemev
5f65b46dfc [JS IR] Unmute fixed tests 2021-06-02 13:42:35 +03:00
Roman Artemev
a36135baf1 [JS IR] Fix reflection generation 2021-06-02 13:42:35 +03:00
Roman Artemev
974779e91b [JS IR] Support function reference to array inline constructor 2021-06-02 13:42:34 +03:00
Tianyu Geng
84334b087c FIR checkers: report SMARTCAST_IMPOSSIBLE 2021-06-02 13:19:12 +03:00
Tianyu Geng
62f7e8f71f FIR DFA: store stability in RealVariable
As part of this change, we also extend the usage of RealVariable in more
places during DFA. Now mutable properties, property with custom getters,
delegated properties, etc are also treatd as a `RealVariable`. In
general this is needed in order to carry out smartcast computation in
order to report `SMARTCAST_IMPOSSIBLE`. It seems to also have side
effects that improves behavior of some test files.
2021-06-02 13:19:12 +03:00
Tianyu Geng
96bd2c54f0 FIR: add smartcast stability to FIR 2021-06-02 13:19:12 +03:00
Tianyu Geng
931a637bdd FIR: use isReal() and isSynthetic() helper consistently 2021-06-02 13:19:11 +03:00
Vladimir Ivanov
2165cc8f0d [Native] Fix test data for testObjCExportNoGeneric (#4424) 2021-06-02 11:13:07 +03:00
Vladimir Ivanov
e06a60bda5 [Native] Clean up nested comment when exporting kdoc to objc header (#4410)
* [Native] Clean up nested comment when exporting kdoc to objc header

* [kdoc-export] Add test witg nested comment block

* Remove redundant assert

Co-authored-by: Vladimir Ivanov <vladimir.d.ivanov@jetbrains.com>
2021-06-02 10:18:32 +03:00
Alexander Udalov
61d5595790 Remove dependency of ir.serialization.common on frontend 2021-06-01 20:28:23 +02:00
Alexander Udalov
dfea915f92 Remove dependency of frontend on compiler.common.jvm
Looks like it was added accidentally in 564d382b9d; common frontend
shouldn't depend on JVM-specific modules.

Since then, it has been accidentally used in two places in
ir.serialization.common to refer to JVM specifics, and that should be
abstracted away in the future.
2021-06-01 20:28:23 +02:00
Alexander Udalov
81ce1da352 Move PsiSourceElement to psi 2021-06-01 20:28:23 +02:00
Alexander Udalov
bcf47ddc94 Move optional annotation utilities to module 'resolution'
To avoid depending on a heavy module 'frontend' in parts of the compiler
where checking for optional annotations is needed, such as in
'ir.serialization.common'.
2021-06-01 20:28:22 +02:00
Alexander Udalov
e790fa8ac9 Remove dependency of serialization on frontend
Move ApplicationExtensionDescriptor and ProjectExtensionDescriptor to
:compiler:util.
2021-06-01 20:28:22 +02:00
Alexander Udalov
8b3769b88e Remove dependency of ir.serialization.common on ir.backend.common 2021-06-01 20:28:22 +02:00
Alexander Udalov
a3ad03d1ad Slightly refactor module dependencies of backend.js/serialization.js
The comment in serialization.js/build.gradle.kts is not needed because
such dependency cannot be introduced accidentally, since Gradle does not
support cycles in module dependencies.
2021-06-01 20:28:22 +02:00
Leonid Startsev
b43e5a5e7d fixup! Fix tests and review notes 2021-06-01 16:41:56 +00:00
Leonid Startsev
6a5cf00d7a Optimize serializer instantiation: use Companion.serializer() when possible
Add test for sealed hierarchy
2021-06-01 16:41:55 +00:00
Leonid Startsev
b61277df97 Support annotations in constructor signatures of special serializers 2021-06-01 16:41:55 +00:00
Leonid Startsev
229085f3d1 Support default parameter values in @SerialInfo annotations
#KT-46739 Fixed
Fixes https://github.com/Kotlin/kotlinx.serialization/issues/1461
2021-06-01 16:41:54 +00:00
Mads Ager
f846dd8ea2 [JVM_IR] Avoid using special names in static inline class replacements.
Fixes KT-46952
2021-06-01 16:22:14 +02:00
Aleksei.Cherepanov
b1ab597616 Fix FIR tests after ee45aa6b 2021-06-01 15:59:17 +03:00
Pavel Punegov
3293a888ca [native] Archive naming: use $os-$arch convention 2021-06-01 10:20:05 +00:00
Pavel Punegov
48ef739525 [native] Rename Apple MacOS targets in simpleOsName
Use Arm64 suffix for Apple Arm arch and X64 for Intel X86_64
2021-06-01 10:20:04 +00:00
Alexander Shabalin
825b77cc82 Remove unused ostream 2021-06-01 07:01:11 +00:00
Mikhael Bogdanov
b72aa76415 Support class type parameters annotation checking 2021-06-01 06:33:51 +02:00
Mikhael Bogdanov
a8186d19d6 Support annotations on class type parameters
#KT-43714
2021-06-01 06:33:50 +02:00
Dmitry Petrov
9091ca7b51 JVM_IR KT-46864 handle "unused" LDC instructions properly 2021-05-31 21:12:35 +03:00
Andrey Uskov
be097244d4 fixup synchronizations 2021-05-31 20:23:54 +03:00
Aleksei.Cherepanov
b0d721c9d0 Fix synchronization in translation-result map
#KT-27660 Fixed
2021-05-31 20:23:53 +03:00
Aleksei.Cherepanov
290d424111 Fix synchronization in source-to-classes table 2021-05-31 20:23:52 +03:00
Aleksei.Cherepanov
ee45aa6b08 Fixed closing of cache storage
#KTIJ-7680 Fixed
#KT-45843 Fixed
2021-05-31 20:23:51 +03:00
Mads Ager
886ce055f5 [JVM_IR] Do not use invoke-dynamic for targeting inline-only methods.
Fixes https://youtrack.jetbrains.com/issue/KT-46962
2021-05-31 18:11:50 +03:00
pyos
5c2753b5d1 JVM_IR: use substituted return type in function reference invoke
#KT-46982 Fixed
2021-05-31 16:01:22 +03:00
Vasily Levchenko
84c10079e4 [kotlin-native][tests] kt-42208 test added. 2021-05-31 11:45:32 +00:00
Vasily Levchenko
1ff6dc1275 [kotlin][tests][compiler/testData/debug/stepping] kt-42208 test added. 2021-05-31 11:45:31 +00:00
Vasily Levchenko
ecbae02f17 [IR][provisional function expression] another line information provider added for func_expression -> function_reference conversion 2021-05-31 11:45:31 +00:00
Dmitriy Novozhilov
c6a2d85c87 [Build] Remove incorrect dependency
`intellijDep()` includes jars with JUnit3 and JUnit4. JUnit5 runner
  which is used in compiler tests sees old junit on classpath and checks
  if this version can be ran using Vintage test engine. Looks like recent
  changes in platform changed order of this jars on classpath, so now
  jar with JUnit3 is closer than JUnit4 (and they have same classes inside),
  so version checker from JUnit5 observes JUnit3 and fails with error
  of incompatible versions. Since old JUnits are not needed at all in those
  modules now only required jars from intellijDep are included
2021-05-31 14:03:37 +03:00
Dmitriy Novozhilov
6121d156a1 [Build] Add workarounds for JPS build
Compilation of `:kotlin-gradle-statistics:test` is broken in gradle
  too, so this module is removed from JPS to allow build project with
  "Rebuild project" action

Dependency on `:kotlin-uast-base` changed to `implementation` because
  project import assumes `shadow` dependency as _Provided_ instead of
  _Compile_ in module structure which leads to problem that this
  dependency is missing during build (this is bug inside JPS itself)
2021-05-31 14:03:37 +03:00
Abduqodiri Qurbonzoda
d934c97bf5 Equivalize isLowerCase and isUpperCase behavior in all platforms #KT-46184 2021-05-31 13:42:46 +03:00
Yahor Berdnikau
0b10f255d7 Update 'kotlinOptions.jdkHome' deprecation message.
Also mention java toolchains approach.

^KT-43095 Fixed
2021-05-31 10:22:50 +00:00
Yahor Berdnikau
c5e6215d27 Set UsesKotlinJavaToolchain interface to extend Task interface.
Limit use-case of UsesKotlinJavaToolchain interface to only Gradle tasks
and allow to query all tasks using
 'taskContainer.withType(UsesKotlinJavaToolchain.class)'.

^KT-43095 In Progress
2021-05-31 10:22:50 +00:00
Yahor Berdnikau
4c943e7cd1 Allow to configure non-default JDK using toolchain via extension.
Add method into "kotlin" extension to set toolchain for all tasks.
This will also set toolchain for java compile tasks. Also user may
set toolchain via "java" extension and it will be applied to Kotlin
tasks as well.

^KT-43092 In Progress
2021-05-31 10:22:49 +00:00
Yahor Berdnikau
8e1c420c9f Allow to set non-default JDK for tasks via java toolchain.
Has to split jdk/toolchain setters, because, when toolchain setter is
in the 'UsesKotlinJavaToolchain', Groovy fails to create meta class
on <Gradle 6.7 with ClassNotFoundException.

^KT-43092 In Progress
2021-05-31 10:22:48 +00:00
Ilya Matveev
de5dcfcbd8 [K/N][Runtime] Support suspending mutators in the new MM 2021-05-31 09:48:46 +00:00
Alexander Likhachev
94a94a557d [Gradle, JS] Add test for KT-47045 2021-05-31 11:43:18 +03:00
Alexander Likhachev
89f8c5a651 [Gradle, JS] Prevent adding unintended implicit dependencies
The way JS compilations are mapped to task requirements were changed from `compilation` objects to compilations's `disambiguatedName` in order to support Gradle configuration cache. This may lead to implicitly adding unwanted dependencies in multi-module projects since compilation's `disambiguatedName` is unique within a module, not within a whole multi-module project.
#KT-47045 Fixed
2021-05-31 11:43:18 +03:00
Andrey Zinovyev
78e20c1098 [KAPT] Keep original expressions in annotations vararg
#KT-29929 Fixed
2021-05-31 08:08:37 +00:00
Dmitriy Dolovov
e927764aaf [IR][Native] Fix invalid IR return statement generation
^KT-46836
2021-05-29 19:31:13 +00:00
Victor Petukhov
15b6a3c88c Temporary don't fail fir tests if a test passes but *.fir.fail exists (needs for DiagnosisCompilerTestFE10TestdataTestGenerated) 2021-05-29 11:30:55 +03:00
Nikita Bobko
3e892d3184 'idea-fir-fe10-binding' move fir tests into subpackage 'org.jetbrains.kotlin.idea.fir'
In intellij infrastructure we run tests by matching package pattern.
So in order to be able run FIR tests we need to place them into unique package
2021-05-29 00:11:28 +03:00
Nikita Bobko
65972fa64c 'idea-frontend-fir' move fir tests into subpackage 'org.jetbrains.kotlin.idea.fir'
In intellij infrastructure we run tests by matching package pattern.
So in order to be able run FIR tests we need to place them into unique package
2021-05-29 00:11:27 +03:00
Nikita Bobko
1ba6845b59 'idea-fir' move fir tests into subpackage 'org.jetbrains.kotlin.idea.fir'
In intellij infrastructure we run tests by matching package pattern.
So in order to be able run FIR tests we need to place them into unique package
2021-05-29 00:11:26 +03:00
Alexander Udalov
e7275a7cb0 Revert "Enable JVM IR for stdlib/reflect/test libraries"
This reverts commit 15e978dbd3.

Together with the previous revert, this led to multiple failures in
Gradle integration tests:

    ConfigurationCacheIT.testIncrementalKaptProject
    ConfigurationCacheForAndroidIT.testAndroidKaptProject
    KotlinAndroid34GradleIT.testParcelize
    KotlinAndroid34GradleIT.testAndroidExtensionsManyVariants
    KotlinAndroid36GradleIT.testAndroidWithNewMppApp
    KotlinAndroid36GradleIT.testParcelize
    KotlinAndroid36GradleIT.testAndroidIcepickProject
2021-05-28 21:36:24 +02:00
Alexander Udalov
e0cc6d44a7 Revert "Remove obsolete kotlin.build.useIR flag"
This reverts commit 91e47f1fd7.
2021-05-28 21:35:57 +02:00
Victor Petukhov
67d48d0150 Fix failing test 2021-05-28 21:38:27 +03:00
Alexander Udalov
96f0b53761 IR: get overridden directly from IrProperty when resolving fake override
The previous way of getting them either via getter or setter failed on
Java properties which only have a backing field. Now that IrProperty has
overriddenSymbols (after 53c1de172f), it makes sense to use it directly
instead. Use it only in SyntheticAccessorLowering though to avoid
breaking Kotlin/Native (see KT-47019).

 #KT-46900 Fixed
2021-05-28 17:24:20 +02:00
Mark Punzalan
af35892007 FIR IDE: Enable RemoveUselessIsCheckFix and
RemoveUselessIsCheckFixForWhen.
2021-05-28 18:21:32 +03:00
Mark Punzalan
639b7537da FIR IDE: Enable RemoveUselessCastFix. 2021-05-28 18:21:31 +03:00
Pavel Kirpichenkov
f5a53c82c5 Don't write type arguments of types replaced with Any to metadata
Anonymous types are not approximated by frontend for private declarations.
Class IDs for such types are replaced by StringTable before being written
to metadata. JVM string table mangles such types and keeps them generic
for reflection. For other purposes the types are replaced with `Any`.
Type arguments of the replaced type should be ignored in the latter case.
Otherwise decompiled text builder crashes on an attempt to restore `Any`
type with non-zero number of type arguments.

The code pretending to replace a type with its first supertype was dropped
from ApproximatingStringTable for two reasons:
- the first type from `getAllSuperClassifiers` is the original type itself
which doens't provide a ClassId for anonymous type, so it was a noop
- tracking potential type arguments of the first anonymous type's supertype
would be a complication with almost no practical value (types in decompiled
text would be slightly closer to the real type of a private declaration).

^KT-46393 Fixed
2021-05-28 14:42:47 +00:00
sebastian.sellmair
fefc6f9b53 [Gradle] :kotlin-test-js-runner: Update nodejs to 16.2.0
^KT-45302
2021-05-28 14:27:36 +00:00
sebastian.sellmair
d3b1ee42be [Gradle] Test project 'commonizeHierarchically': Use new 'macos' target shortcut
^KT-45302
2021-05-28 14:27:36 +00:00
sebastian.sellmair
cc571a876a [Gradle] Implement AppleSiliconIT
^KT-45302
2021-05-28 14:27:35 +00:00
sebastian.sellmair
242d79ded6 [Gradle] :kotlin-gradle-plugin-integration-tests: Include Commonizer tests into 'native' tests
^KT-45302
2021-05-28 14:27:34 +00:00
sebastian.sellmair
b9018e8888 [Gradle] :kotlin-gradle-plugin-integration-tests: Add 'includeTestsWithPattern' util function
^KT-45302
2021-05-28 14:27:33 +00:00
sebastian.sellmair
5dcaaf47cb [Gradle] Support for Apple Silicon targets
^KT-45302 Verification Pending
2021-05-28 14:27:32 +00:00
Alexander Udalov
91e47f1fd7 Remove obsolete kotlin.build.useIR flag 2021-05-28 15:41:57 +02:00
Alexander Udalov
15e978dbd3 Enable JVM IR for stdlib/reflect/test libraries 2021-05-28 15:41:56 +02:00
Alexander Udalov
1dfcec3a93 Build: add temporary option to suppress jdkHome warning 2021-05-28 15:41:17 +02:00
Victor Petukhov
aaffd73feb Take into account FE exceptions built as FromFrontendHandler to proper mute corresponding tests for DiagnosisCompilerTestFE10TestdataTestGenerated 2021-05-28 15:48:59 +03:00
Victor Petukhov
54b9f39b3a Update tests after rebase 2021-05-28 15:36:24 +03:00
Victor Petukhov
f4788b479c Fix incorrect builder inference usage 2021-05-28 15:36:23 +03:00
Victor Petukhov
76c15e4444 Don't update null recorded type prematurely in ResolvedAtomCompleter 2021-05-28 15:36:23 +03:00
Victor Petukhov
bd7fb56a24 Fix builder inference tests 2021-05-28 15:36:23 +03:00
Victor Petukhov
4a767c597e Don't report the same diagnsotics several times 2021-05-28 15:36:23 +03:00
Victor Petukhov
e942052eb6 Substitute stub type variables in local variable descriptors 2021-05-28 15:36:22 +03:00
Victor Petukhov
758eb8f851 Fix builder inference tests 2021-05-28 15:36:22 +03:00
Victor Petukhov
be22078bd1 Return empty NotFixedToInferredTypesSubstitutor if the current substitutor is empty 2021-05-28 15:36:22 +03:00
Victor Petukhov
d8c68aacdd Split setting substitutor descriptor for entire resolved call into two parts: setting resulting substitutor and setting substitutor for resolved call's types 2021-05-28 15:36:22 +03:00
Victor Petukhov
fd5169186e Update test for the builder inference and add new ones 2021-05-28 15:36:21 +03:00
Victor Petukhov
31ed1ad5d9 Use recorded into descriptor inferred callable reference input/output types, to prevent leaking raw type parameter's types of reflectionCandidateType into the back-end 2021-05-28 15:36:21 +03:00
Victor Petukhov
84bd580f92 Complete block expressions to substitute stub type variables into last callable references there 2021-05-28 15:36:21 +03:00
Victor Petukhov
472ab09511 Do stub types substitution for property initializer's type 2021-05-28 15:36:20 +03:00
Victor Petukhov
ac222fdb41 Update type for both version of expression: parenthesis and not 2021-05-28 15:36:20 +03:00
Victor Petukhov
c0ad1c9b18 Do substitution of stub types inside smartcast types to further write it into trace and prevent dealing with that in the back-end 2021-05-28 15:36:20 +03:00
Victor Petukhov
26cbb020db Use resulting descriptor for old callable references to substitute stub type variables 2021-05-28 15:36:20 +03:00
Victor Petukhov
3ff22b67f7 Substitute type arguments of old callable references as well 2021-05-28 15:36:20 +03:00
Victor Petukhov
d5be258291 Do substitution for receivers of old (by passing though OI) callable references properly, with avoiding premature returning from the method 2021-05-28 15:36:19 +03:00
Victor Petukhov
9fd1cbd2e7 Inject stub type variables of a different builder inference call properly 2021-05-28 15:36:19 +03:00
Victor Petukhov
d486f7e188 Don't report TYPE_INFERENCE_POSTPONED_VARIABLE_IN_RECEIVER_TYPE if unrestricted build inference was enabled 2021-05-28 15:36:19 +03:00
Victor Petukhov
0c427555cf Support definitely not null stub types and proper subtyping on them 2021-05-28 15:36:19 +03:00
Victor Petukhov
0f317b01b4 Rename language feature StableBuilderInference to UnrestrictedBuilderInference 2021-05-28 15:36:19 +03:00
Victor Petukhov
0b37b2be6a Add addtional tests for builder inference 2021-05-28 15:36:19 +03:00
Victor Petukhov
ecde5414dc Reuse error type constructor for stub types 2021-05-28 15:36:18 +03:00
Victor Petukhov
ee927a15a9 Compute nullability for stub types properly 2021-05-28 15:36:18 +03:00
Victor Petukhov
afbda75581 Set member scope for builder inference stub types equivalent to Any 2021-05-28 15:36:18 +03:00
Victor Petukhov
6356b9d501 Put removing builder inference restrictions under the compiler flag 2021-05-28 15:36:17 +03:00
Victor Petukhov
5a11450d77 Split stub types into stub type for subtyping and for builder inference and use them in the proper way 2021-05-28 15:36:17 +03:00
Victor Petukhov
703a353d2e Determine empty constraint system for a builder inference call by presense of not fixed type variables 2021-05-28 15:36:17 +03:00
Victor Petukhov
c5faf532f5 Allow builder inference calls with labeled lambda
^KT-24993 Fixed
2021-05-28 15:36:16 +03:00
Victor Petukhov
90066d7e50 Add expected type constraints in a builder inference call 2021-05-28 15:36:16 +03:00
Victor Petukhov
7da47dcde8 Add type variables into common system of a builder inference call properly 2021-05-28 15:36:15 +03:00
Victor Petukhov
ac7b459f2a Do subtyping with stub types properly
1) Return stub type if we are calculating super type between two same stub types
2) Return nullable Any if those stub types are different
2021-05-28 15:36:15 +03:00
Victor Petukhov
5d0461c722 Remove restrictions for builder inference internal calls 2021-05-28 15:36:14 +03:00
Victor Petukhov
26b8e86fe1 Render stub types properly 2021-05-28 15:36:14 +03:00
Nikita Bobko
af12b2fdf0 [imltogradle] Replace "Exported transitive dependency" with original module name reference 2021-05-28 14:03:07 +02:00
Nikita Bobko
6a7770573c [imltogradle] Support attaching 211 IDEA 2021-05-28 14:03:07 +02:00
Roman Artemev
8a856e440e [KLIB] Fix linker diagnostic message 2021-05-28 13:37:30 +03:00
Roman Artemev
720edfa6aa [IR] Fix branch offests
Seems logic that right bound of branch is result's right bound,
not condition's.
2021-05-28 13:23:52 +03:00
Andrey Zinovyev
ebf6ce133b [FIR] Fix kotlin version check in annotations
@RequireKotlin has more than one string parameter, so you need to check
 'version' only
2021-05-28 12:24:58 +03:00
Elena Lepilkina
3a22761d02 [K/N] Fix MutationCheck calls for inlined property accessors 2021-05-28 06:45:53 +00:00
Elena Lepilkina
b6f35ac44d [K/N] Fix inlining of property setters by replacing ReturnsInsertion lowering 2021-05-28 06:45:52 +00:00
Yahor Berdnikau
3387615d4a Fix test requires more later Gradle version. 2021-05-27 18:12:02 +00:00
Yahor Berdnikau
cdb04f9cd7 Add 'kgpSimpleTests' task.
This task run all JUnit5 tests with annotated with '@SimpleKGPTests`
annotation and also will be used in CI configuration.

^KT-45745 In Progress
2021-05-27 18:12:02 +00:00
Alexander Shabalin
af1f57007a https://channel9.msdn.com/Shows/Going+Deep/Cpp-and-Beyond-2012-Herb-Sutter-atomic-Weapons-2-of-2 2021-05-27 17:18:55 +00:00
Nikolay Krasko
0b1884c994 Print memory consumption in the failure for GradleDaemonMemoryIT test 2021-05-27 20:13:10 +03:00
Nikolay Krasko
166f0a597b Run tests only for unique gradle versions 2021-05-27 20:13:09 +03:00
Nikolay Krasko
b5f71bacaf Never spam to log during the normal test execution in Gradle tests 2021-05-27 20:13:08 +03:00
Nikolay Krasko
9d1a6ebb18 Minor: narrow extracting functions scope 2021-05-27 20:13:07 +03:00
Mark Punzalan
d12a24418e FIR IDE: Remove multiple nested params in RemoveUselessElvisFix and
RemoveUselessCastFix.
2021-05-27 19:32:03 +03:00
Mark Punzalan
a778cc673e FIR IDE: Enable RemoveUselessElvisFix. 2021-05-27 19:32:01 +03:00
Ilya Goncharov
157046153f [Gradle, JS] Add test with dynamic webpack.config.d 2021-05-27 19:18:13 +03:00
Hung Nguyen
01c14a709a KotlinCompile: Add kotlin.incremental.useClasspathSnapshot flag
We are planning to improve incremental Kotlin compile with a new
approach using classpath snapshot (see
https://youtrack.jetbrains.com/issue/KT-45777 for more details).

The estimated steps will be as follows:
  [x] Add a flag for the new approach, disabled by default
  [ ] Add tests for the new approach, and update them as we go
  [ ] Add computation of classpath snapshot using artifact transforms
  [ ] Add computation of classpath snapshot changes
  [ ] Ensure incremental compile is fully functional with the new approach
  [ ] Measure performance + optimize: Repeat until we see evidence that
      the new approach is clearly better than the current approach
  [ ] Advertise the flag, and later on enable it by default

This commit is the first step. Although it's simple, it allows further
changes to be made safely without impacting the current approach.

Bug: KT-45777
Test: N/A (will be added in a subsequent change)
2021-05-27 19:05:26 +03:00
Nikita Bobko
1abf3a39d4 Fix kotlin-compiler-tests-for-ide. tests jars should be published 2021-05-27 17:23:46 +02:00
Nikita Bobko
2d015da1ea Make it possible to depend on the rest of :prepare:ide-plugin-dependencies modules
Those modules used as "aggregate" modules. kotlin-ide modules depend on them in coop-dev
2021-05-27 16:32:14 +02:00
Sergey Shanshin
961ee92c15 Fix bytecode for serializable enums in generated tests 2021-05-27 15:35:12 +03:00
Alexander Shabalin
e0c7cda1cf Adjust test expectations for the new MM 2021-05-27 11:39:56 +00:00
Ilya Goncharov
f2a067eda0 [Gradle, JS] In KotlinWebpack configDirectory as getter not lazy
It is useful to dynamically creating config directory during build execution

^KT-46976 fixed
2021-05-27 14:07:04 +03:00
Viacheslav Kormushkin
3709616baa Fixed failing cocoapods integration test 2021-05-27 10:47:45 +00:00
pyos
34878d17eb JVM: be more careful when removing unused constants
1. if an argument of a `pop` cannot be removed, then all other potential
   arguments of that `pop` can't be removed either, and the same applies
   to other `pop`s that touch them;
2. the same is true for primitive conversions, but this is even trickier
   to implement correctly, so I simply did the same thing as with
   boxing operators: replace the conversion itself with a `pop` and keep
   the argument as-is.

Somehow this actually removes *more* redundant primitive type conversions
than the old code in a couple bytecode text tests, so I've patched them
to kind of use the value, forcing the instructions to stay.

 #KT-46921 Fixed
2021-05-27 12:24:22 +02:00
pyos
2f60ce21a0 JVM: remove CHECKCAST handling from PopBackwardPropagationTransformer
Redundant CHECKCASTs should've been removed by a previous pass.
2021-05-27 12:24:22 +02:00
pyos
535934dc28 JVM: do not remove NOPs in PopBackwardPropagationTransformer
There is a pass that removes NOPs and runs afterwards anyway.
2021-05-27 12:24:22 +02:00
Aleksei.Cherepanov
5f4be07225 [JPS] Fix JS incremental compilation
Disable Idea JPS build mechanism for marking all sources of common output if one of them is dirty
Add source-to-outputs map for correctly removing Kotlin/JS outputs

#KT-45763 Fixed
#KT-44351 Fixed
2021-05-27 13:00:56 +03:00
Andrey Zinovyev
c2389a94fa [FIR] Resolve annotations in when expressions 2021-05-27 12:41:16 +03:00
Sergey Bogolepov
b541721a79 Deprecate Architecture.bitness property
There is no such thing as "bitness" of CPU achitecture.
Something more appropriate and correct (e.g. ABI) should be
introduced instead.
2021-05-27 10:09:25 +03:00
Sergey Bogolepov
bed42e9ab2 Revert "Drop useless bitness property from Architecture"
As it turn outs, `Architecture.bitness` leaks to public Gradle API and
we need to deprecate it gracefully.
This reverts commit 79bf2a1f.
2021-05-27 10:09:24 +03:00
sebastian.sellmair
14eca72913 Implement 'CommonizerTarget.fileName' and limit fileName length
^KT-46856 Fixed
2021-05-27 06:48:34 +00:00
sebastian.sellmair
0749443f7e Implement CommonizerIT.test KT-46856 filename too long - all native targets configured
Covers ^KT-46856
2021-05-27 06:48:33 +00:00
Abduqodiri Qurbonzoda
54994a289f Support all digit chars on JS and Native #KT-46002 2021-05-27 06:56:52 +03:00
Anton Lakotka
8481f4a9d2 Set kotlin-project-model as api dependency for kotlin-gradle-plugin-api
LanguageSettingsBuilder depends on LanguageSetting interface from KPM
which forces api dependency scope

^KT-46517 Fixed
2021-05-26 18:11:39 +00:00
Anton Lakotka
3e2b8a8898 Test Gradle buildSrc with kotlin-gradle-plugin-api dependency
For ^KT-46517
2021-05-26 18:11:39 +00:00
Anton Bannykh
b3bb033fe4 JS IR: fix plain module reference 2021-05-26 17:53:21 +03:00
Dmitriy Novozhilov
b63770bc7b Add workaround for KT-46902 2021-05-26 17:53:20 +03:00
Dmitriy Novozhilov
89e52cb780 Add workaround for KT-46900 2021-05-26 17:53:19 +03:00
Dmitriy Novozhilov
8eca31e867 Advance bootstrap to 1.5.30-dev-1023 2021-05-26 17:53:17 +03:00
pyos
d37ceb47be JVM_IR: use correct dispatch receiver type in more references
#KT-46902 Fixed
2021-05-26 15:23:19 +02:00
Sergey Shanshin
16dbafced1 Add .serializer() to enum companion and object with custom serializer
Fixes Kotlin/kotlinx.serialization#1386
2021-05-26 16:07:59 +03:00
Igor Chevdar
f431b4b171 [K/N][codegen] Escape analysis: increased a bit the number of iterations
This helps the algorithm to converge in more situations and increases
the number of stack allocated objects
2021-05-26 17:48:20 +05:00
Igor Chevdar
29584edcdd [K/N][codegen] Escape analysis: handled nulls more optimally
Helps with https://youtrack.jetbrains.com/issue/KT-44148
2021-05-26 17:46:22 +05:00
Igor Chevdar
426ac1281d [K/N][codegen] Removed square graph swelling during escape analysis
Helps with https://youtrack.jetbrains.com/issue/KT-44148
2021-05-26 17:46:15 +05:00
Konstantin Tskhovrebov
2129a762a5 Change assemble AppleFrameworkTask name to using framework name prefix
#KT-46892
2021-05-26 14:59:30 +03:00
Elena Lepilkina
a006f35df3 [K/N][build] Removed extra konanVersion variable as far as it's now same as kotlinVersion 2021-05-26 11:49:49 +00:00
Tianyu Geng
61475c48e2 FIR: fix VALUE_ARGUMENTS position strategy 2021-05-26 14:46:18 +03:00
Margarita Bobova
3bd6bf1432 Add changelog for 1.5.10 2021-05-26 13:51:48 +03:00
Margarita Bobova
e31173ca73 Add changelog for 1.5.0 2021-05-26 13:51:06 +03:00
pyos
33ddeffcfd JVM_IR: box inline class values returned by suspend inline lambdas
The call site inside the inline function expects them to return a boxed
value, like FunctionN.invoke would.

 #KT-46915 Fixed
2021-05-26 08:33:55 +02:00
pyos
117fad2018 JVM: refactor inline ExpressionLambda initialization 2021-05-26 08:33:55 +02:00
Mads Ager
d023966054 [JVM] Fix various undefined locals issues.
CoroutineTransformermethodVisitor attempts to extend the ranges
of local variables in various situations. Probably in an attempt
to give a better debugging experience. However, all of these
range extensions lead to invalid local variable tables where
something is in the local variable table where nothing is in the
corresponding slot.

The code that extends variables to the next suspension point
instead of ending them when they are no longer live has issues
with loops. When resuming and reentering the loop, the locals
table will mention a local that we did not spill and which
is therefore not restored when resuming.

The code that extends local variable table entries if there
are no suspension points between two entries doesn't work
for code such as:

```
var s: String
if (suspendHere() == "OK") {
  s = "OK"
} else {
  s = "FAIL"
}
```

If the local variable ranges are collapsed into one, one of
the branches will have the local defined in the local variable
table before the slot is initialized.
2021-05-26 08:33:34 +02:00
Nikita Bobko
14ed660f4f [cleanup] Remove unused AbstractFirMultiModuleResolveTest 2021-05-25 23:53:08 +03:00
Anton Lakotka
5d9915e133 Don't copy extendsFrom configs for resolvableMetadataConfiguration
Gradle's detached configurations doesn't respect extends from relation
to other configurations due to gradle bug.
In fact extendsFrom isn't required for resolvableMetadataConfiguration
business logic. It is enough to include all originalDependencies to
freshly created detached configuration.

^KT-46417 Fixed
2021-05-25 23:31:23 +03:00
sebastian.sellmair
e8bd8a938f Implement HierarchicalMppIT.testNativeLeafTestSourceSetsKt46417 to cover ^KT-46417 2021-05-25 23:31:22 +03:00
Ilya Goncharov
c62a965180 [IR] Not try Null constant in fold constant
^KT-46859 fixed
2021-05-25 22:29:58 +03:00
Ilya Kirillov
b18d4af37b fix fe1.0 plugin testdata 2021-05-25 20:39:37 +03:00
Mark Punzalan
2c18406632 IDE: Add test for message of VAL_OR_VAR_ON_*_PARAMETER diagnostic.
Also fall back to getting parameter descriptor if property descriptor
not found for `val/var` parameters.

^KTIJ-13030 Fixed
2021-05-25 20:39:36 +03:00
Mark Punzalan
23605e08be FIR IDE: Enable RemoveValVarFromParameterFix for
VAL_OR_VAR_ON_*_PARAMETER.
2021-05-25 20:39:35 +03:00
Mark Punzalan
af99ad0736 FIR checker: Report VAL_OR_VAR_ON_*_PARAMETER. 2021-05-25 20:39:34 +03:00
Tianyu Geng
71c5c9f6c5 FIR IDE: add quickfix to change function return type 2021-05-25 20:39:32 +03:00
Stanislav Erokhin
b5994fa3a9 Remove the Kotlin online event link 2021-05-25 19:19:26 +02:00
Andrey Zinovyev
ae079d9bdd [FIR] Move unsigned types constructor evaluation from intrinsics 2021-05-25 19:23:31 +03:00
Andrey Zinovyev
64b45e6d1b Add comments to skipped FIR tests 2021-05-25 19:23:30 +03:00
Andrey Zinovyev
dce8bd4e62 [FIR] Support constructor call of unsigned in checker 2021-05-25 19:23:29 +03:00
Andrey Zinovyev
7f2eaab02b [FIR] Support for constructor calls of unsigned types in constants 2021-05-25 19:23:27 +03:00
Dmitriy Novozhilov
f9eba6e842 [FIR] Fix determining dependencies for modular jdk in CLI 2021-05-25 15:08:47 +03:00
teamcityserver
d530344eda Merge branch 'push/zharkov-fixes-4' 2021-05-25 14:57:51 +03:00
Jinseong Jeon
5effbce363 UAST: cleanup plugin file to have only plugin definition 2021-05-25 13:09:57 +02:00
Jinseong Jeon
8b93727f64 UAST: split KotlinConverter into a separate file 2021-05-25 13:09:57 +02:00
Jinseong Jeon
0395294933 UAST: split KotlinUastResolveProviderService into a separate file 2021-05-25 13:09:57 +02:00
Jinseong Jeon
f16f9a13fd FIR/UAST: enforce the existence of BaseKotlinUastResolveProviderService 2021-05-25 13:09:57 +02:00
Jinseong Jeon
240f86b109 FIR UAST: use analyseWithCustomToken in lieu of analyse 2021-05-25 13:09:57 +02:00
Jinseong Jeon
741fdee59e FIR/UAST: commonize UnknownKotlinExpression 2021-05-25 13:09:57 +02:00
Jinseong Jeon
15a4649675 FIR/UAST: commonize UImportStatement 2021-05-25 13:09:57 +02:00
Jinseong Jeon
3c3b5aa4ac FIR/UAST: commonize abstract UElement and UExpression 2021-05-25 13:09:57 +02:00
Jinseong Jeon
a54a807dc9 FIR/UAST base: clarify what module we should not depend on
This should be part of commit bbe5cf0a
2021-05-25 13:09:57 +02:00
Denis.Zharkov
dac9d7b17a FIR: Mark a pack of tests (53) as FIR_IDENTICAL 2021-05-25 13:28:29 +03:00
Denis.Zharkov
ddbdfafa79 Remove OI/NI attributes from test data 2021-05-25 13:28:27 +03:00
Denis.Zharkov
2ecba6ac39 Remove WITH_NEW_INFERENCE directive from all tests
This directive anyway does not make test run twice with OI, and with NI
It only once run the test with specific settings (// LANGUAGE)
and ignores irrelevant (OI or NI tags)
2021-05-25 13:28:26 +03:00
Denis.Zharkov
d4586cefb4 FIR: Properly deserialize upper bounds of classes type parameters
^KT-46661 Fixed
2021-05-25 13:28:25 +03:00
Alexander Shabalin
858e3584a9 Disable escape analysis with the new MM 2021-05-25 10:06:40 +00:00
Ivan Gavrilovic
4f64431f10 KT-46820: Kotlin gradle plugin - prevent multiple threads from registering task
... as that is not supported by the underlying mechanism.
Build service that holds info about the incremnetal compilation
may be instantiated only during execution, and multiple tasks may
try to do that. Because the container which holds info about all
build services is not thread-safe, this change adds synchronization.

Fixes #KT-46820
2021-05-25 12:49:07 +03:00
Mikhail Glukhikh
1b7425f428 FIR mangler: handle situation with invisible type in f/o signature
Before this commit, FIR mangler effectively dropped f/o parameter with
invisible type from this module. It could lead to signature clashes.
Now we insert classId in mangler string instead.
This fixes FIR bootstrap.
2021-05-25 11:38:48 +03:00
Denis.Zharkov
924678a00d FIR: Mark a pack of tests (53) as FIR_IDENTICAL 2021-05-25 10:25:05 +03:00
Denis.Zharkov
26002a040f Remove OI/NI attributes from test data 2021-05-25 10:25:05 +03:00
Denis.Zharkov
fe1d540c95 Remove WITH_NEW_INFERENCE directive from all tests
This directive anyway does not make test run twice with OI, and with NI
It only once run the test with specific settings (// LANGUAGE)
and ignores irrelevant (OI or NI tags)
2021-05-25 10:25:04 +03:00
Denis.Zharkov
accd48de8c FIR: Properly deserialize upper bounds of classes type parameters
^KT-46661 Fixed
2021-05-25 10:25:04 +03:00
Ivan Kochurkin
cf531dbbe6 [FIR] Implement TYPE_VARIANCE_CONFLICT, TYPE_VARIANCE_CONFLICT_IN_EXPANDED_TYPE diagnostics, fix tests 2021-05-25 00:07:33 +03:00
Ivan Kochurkin
ef53f0e0b3 [FIR] Render diagnostics parameters instead of full text in debug messages (closer to old tests) 2021-05-25 00:07:32 +03:00
Ivan Kochurkin
6de97e17fe [FIR] Fix max parameters count in diagnostics from 3 to 4 2021-05-25 00:07:30 +03:00
Elena Lepilkina
7f591bcfd4 [K/N] Changed llvmInlineThreshold for new form of bitcode 2021-05-24 15:46:21 +00:00
Elena Lepilkina
2320eb8b44 [K/N] Replace invokes with combination of calls and branch instructions 2021-05-24 15:46:20 +00:00
Nikita Bobko
0be5602363 Move ':plugins:lombok:lombok-ide-plugin' module under 'attachedIntellijVersion' the flag 2021-05-24 17:02:46 +02:00
Dmitriy Dolovov
9ab764e9fd [Native] Disable debug mode in KonanLocalTest (-g) 2021-05-24 13:23:51 +00:00
nataliya.valtman
1db09d78b3 KT-46833: print correct message when history files are unavailable 2021-05-24 13:51:43 +03:00
Ilya Muradyan
23faacd21b [Scripting] Expose scripting-dependencies as API of Maven resolver 2021-05-22 04:10:39 +03:00
Ilya Muradyan
0e7d690923 [Scripting] Change compile to implementation in Maven resolver 2021-05-22 00:38:46 +03:00
Ilya Muradyan
bead0e3412 [Scripting] Fix Maven resolver dependencies 2021-05-22 00:38:44 +03:00
Dmitry Petrov
261b42f5c5 JVM_IR KT-46822 don't generate too deep StringBuilder.append trees 2021-05-21 22:28:54 +03:00
Dmitry Petrov
ba00709e4d JVM_IR KT-46839 lower varargs for *arrayOf function references 2021-05-21 22:06:52 +03:00
Alexander Udalov
6ca7b39f6a Psi2ir: do not load abbreviated types with not found classifier
This is not an ideal fix of the problem since the fact that
AbbreviatedType's classifier should be a TypeAliasDescriptor is a
reasonable assumption that might fail somewhere else, later in the
pipeline.

Previous attempts to fix this issue that were unsuccessful:

1) Do not load abbreviations for such types in deserialization at all.
   Unfortunately, it broke quite a few things like reflection and
   decompiler, where types frequently refer to symbols not reachable
   from the point where they're requested, yet we have the FQ name of
   the typealias, which is enough to render the abbreviation properly in
   both these use cases.

2) Load classifiers for unresolved abbreviations as
   MockTypeAliasDescriptor instead of MockClassDescriptor in
   NotFoundClasses. Technically this was a revert of
   e19c1b5364. But this failed because we
   don't have enough information about such typealias to correctly set
   its `expandedType`/`underlyingType` (just using nullable Any as
   before that commit is not good enough). We only know its underlying
   class (from one usage of such typealias), and even supporting that
   would involve a major refactoring of TypeDeserializer which is
   painful.

 #KT-45308 Fixed
2021-05-21 19:36:30 +02:00
Alexander Udalov
ceec451f3f Minor, slightly refactor TypeDeserializer.typeConstructor 2021-05-21 19:36:30 +02:00
Dmitriy Dolovov
ab6f577964 [Native] Support suspend functions as supertypes (remove debug code)
^KT-46777
2021-05-21 17:31:46 +00:00
Hung Nguyen
c0977dd638 Build report: Print task name instead of TaskRecord@hashCode
Previously when kotlin.build.report.enable=true, the build report
contained lines such as:
  org.jetbrains.kotlin.gradle.report.TaskRecord@2db49688 was skipped

This commit prints the task name instead of TaskRecord@hashCode so that
it is more readable, like this:
  Task ':app:compileDebugKotlin' was skipped

Bug: N/A (Clean up)
Test: Existing tests + manually checked the build report output
2021-05-21 19:35:25 +03:00
Dmitriy Novozhilov
478a512b24 [FIR] Expand type of const val in FirConstPropertyChecker 2021-05-21 17:38:26 +03:00
Vasily Levchenko
669985f853 [debug][stacktrace][mac] more tracing for stacktrace debugging 2021-05-21 11:52:08 +00:00
Dmitriy Dolovov
0be542fd33 [Native] Always enable assertions in KonanLocalTest 2021-05-21 14:37:30 +03:00
Dmitriy Novozhilov
a1ae108ce5 [FIR] Properly generate IDE diagnostics from multiple diagnostics lists 2021-05-21 14:18:58 +03:00
Dmitriy Novozhilov
09e3629d5d [FIR] Move common checkers container from :entrypoint to :checkers module 2021-05-21 14:18:57 +03:00
Dmitriy Novozhilov
a9838131ad [FIR] Move jvm specific checkers to checkers.jvm module 2021-05-21 14:18:56 +03:00
Dmitriy Novozhilov
f3c58a1df7 [FIR] Add separate diagnostic list for JVM specific diagnostics 2021-05-21 14:18:55 +03:00
Dmitriy Novozhilov
7f18d147c1 [FIR] Introduce new module for jvm specific checkers 2021-05-21 14:18:54 +03:00
Dmitriy Novozhilov
9825babc23 [FIR] Move model classes of diagnostics generation DSL to separate package 2021-05-21 14:18:52 +03:00
Denis.Zharkov
f0c85e0935 FIR: Add comments to freshly muted tests 2021-05-21 13:53:55 +03:00
Andrey Zinovyev
617d99faac [FIR] Don't keep ref to whole class proto
Store module name only
2021-05-21 12:49:59 +03:00
Andrey Zinovyev
a121061df7 [FIR] Get module name for deserialized fir2ir classes 2021-05-21 12:49:58 +03:00
Svyatoslav Scherbina
dc8934ab22 Native: fix crash in custom LLVM diagnostics handler
48a684c0 added custom LLVM diagnostic handler, using JvmCallbacks machinery,
thus triggered a bug in the latter: callbacks are cached and outlive the compilation session,
but rely on memory that is reclaimed at the end of the compilation session.
So during a subsequent compilation in the same process (e.g. when the compiler runs in the
Gradle daemon process), LLVM might call the callback which accesses the reclaimed memory, 
which in turn causes the crash.

Fix this by forcing JvmCallbacks to allocate memory that doesn't "expire" at the end of the compilation session.
2021-05-21 07:34:34 +00:00
Elena Lepilkina
573191251e [K/N] Remove redundant update of debug info 2021-05-21 06:55:07 +00:00
Alexander Shabalin
73533e4b19 Make NoOp GC support multiple mutators 2021-05-21 06:31:09 +00:00
Ilya Kirillov
792ac6ab63 FIR IDE: update resolve call testdata after adding targetFunction to KtFunctionalTypeVariableCall 2021-05-21 00:04:48 +02:00
Ilya Kirillov
c72b2caf3e Fix wrapWithSafeLetCall quickfix testdata 2021-05-21 00:01:20 +02:00
Ilya Kirillov
be4632c2fe FIR: add missing ArgumentTypeMismatch.isMismatchDueToNullability after rebase 2021-05-20 21:05:41 +02:00
Ilya Kirillov
acda71cc90 FIR IDE: restore test generator after rebase 2021-05-20 20:33:01 +02:00
Tianyu Geng
e1b542314a FIR IDE: quickfix for WrapWithSafeLetCall
There is some behavior change regarding the new WrapWithSafeLetCall quickfix

1. it now works correctly on binary expressions by wrapping it with `()`
2. it now looks for a nullable position upward and do the modification there,
   if possible. For example, consider the following code

   ```
   fun bar(s: String): String = s

   fun test(s: String?) {
     bar(bar(bar(<caret>s)))
   }
   ```

   After applying this fix, FE1.0 yields

   ```
   bar(bar(s?.let { bar(it) }))
   ```

   while the new implementation yields

   ```
   s?.let { bar(bar(bar(it))) }
   ```

   This behavior aligns with FE1.0 if `bar` accepts nullable values.
2021-05-20 20:33:00 +02:00
Tianyu Geng
0eaab6d8a2 FIR: extract common logic from KotlinNameSuggester and share 2021-05-20 20:33:00 +02:00
Tianyu Geng
00ffa69cb3 FIR: add receiver expression to UNSAFE_CALL diagnostic and its variances 2021-05-20 20:32:59 +02:00
Tianyu Geng
9106ae4f5f FIR: store in ARGUMENT_TYPE_MISMATCH whether it's due to nullability 2021-05-20 20:32:59 +02:00
Tianyu Geng
cceb7197a5 FIR: allow nullable types in diagnostic parameters 2021-05-20 20:32:59 +02:00
Tianyu Geng
594fbbb4ef FIR: Allow 4 parameters for diagnostics 2021-05-20 20:32:58 +02:00
Mark Punzalan
d2b8204fdc FIR/FIR IDE: Use entire FirVariableAssignment when reporting UNSAFE_CALL
(e.g., `nullable.a = b`), and use positioning strategies to locate the
dot in the LHS expression.

Without it, only the callee reference is reported on, which makes the
highlighting of the error and application of quickfixes incorrect in the
IDE.

Also fixed issue with annotated and/or labeled expressions on LHS of
assignment (e.g., `(@Ann label@ i) = 34`).
2021-05-20 20:32:58 +02:00
Mark Punzalan
1d9247ae0f FIR IDE: Offer AddExclExclCallFix for nullable types with an
`iterator()` function that does NOT have `operator` modifier.

This is different from FE1.0. Adding `!!` will then surface the error
that `operator` modifier needs to be added (with corresponding fix).
2021-05-20 20:32:58 +02:00
Mark Punzalan
9e01a608b2 FIR IDE: Add ability in test infra to have a "before" file different in
FIR vs FE1.0, and made file naming convention more consistent.
2021-05-20 20:32:57 +02:00
Mark Punzalan
efa3bf9c69 FIR IDE: Consolidate tests for AddExclExclFix in one directory.
I found these tests only _after_ the previous changes, so I needed to
merge and/or remove redundant tests.
2021-05-20 20:32:57 +02:00
Mark Punzalan
db82797f58 FIR IDE: Enable AddExclExclCallFix for UNSAFE_CALL,
UNSAFE_OPERATOR_CALL, UNSAFE_INFIX_CALL, ITERATOR_ON_NULLABLE,
ARGUMENT_TYPE_MISMATCH, RETURN_TYPE_MISMATCH.

TODO: Don't offer fix when target is known to be null (from data flow
analysis).
2021-05-20 20:32:56 +02:00
Mark Punzalan
71a8d9c0bb FIR quickfix: Enable addExclExclCall tests for FIR, move typeMismatch
tests for addExclExclCall to addExclExclCall directory.
2021-05-20 20:32:56 +02:00
Mark Punzalan
85cbea70bf IDE: Don't do any resolution in AddExclExclExclFix (i.e., in
isAvailable and in invoke) by moving computation of element to modify
to before instantiation (i.e., to the factories or equivalent).

This lets us to move it to idea-frontend-independent and re-use it FIR.
2021-05-20 20:32:56 +02:00
Mark Punzalan
c472c9facd IDE: Don't add this!! in AddExclExclCallFix for nullable member
access in extension function.

^KTIJ-10052 Fixed
2021-05-20 20:32:55 +02:00
Dmitry Petrov
c0fbdb1535 JVM_IR KT-46840 don't generate special function references with indy 2021-05-20 21:13:17 +03:00
Dmitriy Novozhilov
3fc7e0ed03 [FIR] Remove COMPARE_WITH_LIGHT_TREE from default directives of fir diagnostic tests 2021-05-20 20:20:40 +03:00
Nikita Bobko
f7aabf03f8 Fix kotlin-native compilation
This commit fixes:
```
org.gradle.internal.metaobject.AbstractDynamicObject$CustomMessageMissingMethodException:
Could not find method intellijDep() for arguments [] on object of type
org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler
```
2021-05-20 17:02:00 +02:00
Viacheslav Kormushkin
d10910e553 Added support of custom Xcode configurations to cocoapods plugin
#KT-42023
2021-05-20 17:36:08 +03:00
Denis.Zharkov
a801eccf66 FIR: Report ARGUMENT_TYPE_MISMATCH instead of TYPE_MISMATCH for arguments 2021-05-20 17:24:51 +03:00
Denis.Zharkov
db500fab94 FIR: Avoid reporting redundant TYPE_MISMATCH (for assignments) 2021-05-20 17:24:50 +03:00
Denis.Zharkov
36c9418d55 FIR: Convert couple of methods to block-body 2021-05-20 17:24:49 +03:00
Denis.Zharkov
7c05c6420a FIR: Update test data (incorrect NEW_INFERENCE_ERROR with self types)
^KT-46661 Relates
2021-05-20 17:24:48 +03:00
Denis.Zharkov
4433dffbd3 FIR: Mute test that should be disabled since 1.6 2021-05-20 17:24:47 +03:00
Denis.Zharkov
8f41badf74 Minor. Regenerate tests 2021-05-20 17:24:46 +03:00
Denis.Zharkov
c3646b11ac FIR: Fix inference when unit value should be cast to Any 2021-05-20 17:24:44 +03:00
Denis.Zharkov
d3fc22fc6a FIR: Mute suspicious test relevant to safe-call and increment
See KT-46658
2021-05-20 17:24:43 +03:00
Denis.Zharkov
c4862fb124 FIR: Unwrap type aliases in type arguments 2021-05-20 17:24:42 +03:00
Denis.Zharkov
4f08e1550d FIR: Update test data (overload resolution by lambda return type) 2021-05-20 17:24:41 +03:00
Denis.Zharkov
be68dd5c11 FIR: Update test data (suspicious UPPER_BOUND_VIOLATED) 2021-05-20 17:24:40 +03:00
Denis.Zharkov
9265377d51 FIR: Update test data (SAM conversions)
See KT-46372
2021-05-20 17:24:39 +03:00
Denis.Zharkov
601500fd99 FIR: Update test data (extension function type -> function type)
See KT-46371
2021-05-20 17:24:38 +03:00
Denis.Zharkov
e46199d28b FIR: Update test data (nested type aliases)
It's not consistent with FE 1.0, but behavior
for nested type alias is undefined, yet.
2021-05-20 17:24:37 +03:00
Denis.Zharkov
da3233c47d FIR: Update test data (NEW_INFERENCE_ERROR)
Though these diagnostics look correct (the calls or constraint
systems indeed contain errors), more precise diagnostic kinds should be
chosen later.
2021-05-20 17:24:36 +03:00
Denis.Zharkov
010a0c6cdc FIR: Update test data (delegate inference)
Changed data looks correct
2021-05-20 17:24:35 +03:00
Denis.Zharkov
7c5c744e87 FIR: Update test data (suspicious diagnostic on return statement)
There should be errors, but different: cannot infer parameter type

^KT-46422 Relates
2021-05-20 17:24:34 +03:00
Denis.Zharkov
00821bbc63 FIR: Update test data (repeated diagnostics)
They are a bit redundant, but it needs additional work to be done
to avoid them
2021-05-20 17:24:33 +03:00
Denis.Zharkov
dbc0ebd861 FIR: Update test data
changed INAPPLICABLE_CANDIDATE -> ARGUMENT_TYPE_MISMATCH
2021-05-20 17:24:32 +03:00
Denis.Zharkov
b94335dd1c FIR: Update diagnostics test data
Green code correctly became red
2021-05-20 17:24:30 +03:00
Denis.Zharkov
829f80179c FIR: Update rendered tree in test data 2021-05-20 17:24:29 +03:00
Denis.Zharkov
faa5e46396 FIR: Fix inference case with flexible captured types
Previsously, errors have been ignored because we ignored errors raised
from the completion phase

See the comment above the createConstraintPartForLowerBoundAndFlexibleTypeVariable
2021-05-20 17:24:28 +03:00
Denis.Zharkov
c758069d7c FIR: Rework reporting COMPONENT_FUNCTION_RETURN_TYPE_MISMATCH
Previously, it was reported via additional check on successful calls
But now it's contained within FirErrorNamedReference
2021-05-20 17:24:27 +03:00
Denis.Zharkov
c46d049394 FIR: Implement more precise reporting diagnostics from new inference 2021-05-20 17:24:26 +03:00
Denis.Zharkov
c67ae8a0a3 FIR: Replicate coercion-to-unit behavior from FE 1.0 2021-05-20 17:24:25 +03:00
Denis.Zharkov
dac5c31993 Minor. Simplify ConstraintSystemUtilContext::createArgumentConstraintPosition 2021-05-20 17:24:23 +03:00
Denis.Zharkov
9c7982673b FIR: Support substitution of inner class constructor capturing outer type parameters 2021-05-20 17:24:22 +03:00
Denis.Zharkov
91806c0a68 FIR: Refine diagnostics in case argument type mismatch on lambda
Report ArgumentTypeMismatch instead of imprecise NEW_INFERENCE_ERROR
2021-05-20 17:24:21 +03:00
Denis.Zharkov
2b806e717d FIR: Avoid adding new constraints when system already has contradictions 2021-05-20 17:24:20 +03:00
Denis.Zharkov
571c16be52 FIR: Fix computing dispatch receiver for property-delegation operators 2021-05-20 17:24:19 +03:00
Denis.Zharkov
35c754c27c FIR-DFA: Ignore FinallyBlockExitNode when computing return arguments 2021-05-20 17:24:17 +03:00
Denis.Zharkov
d0a0739d10 FIR: Mute builder-inference related tests
They started failing once we began reporting diagnostics from completion

^KT-46421 Relates
2021-05-20 17:24:16 +03:00
Denis.Zharkov
78ec4b5248 FIR: Mute property-delegation-inference related tests
They started failing once we began reporting diagnostics from completion
The main reason is that we resolve `delegate()` call
from `delegate().getValue()` in the independent context, while in FE 1.0
it's being resolved within the same system as getValue

^KT-46420 Relates
2021-05-20 17:24:15 +03:00
Denis.Zharkov
cd401b5b8a FIR: Update integer literal-related tests
They started failing once we began reporting diagnostics from completion

^KT-46419 Relates
2021-05-20 17:24:14 +03:00
Denis.Zharkov
42d387925d FIR: Refine makesSenseToBeDefinitelyNotNull
Make it work just the same as the analogue from FE 1.0
This change is necessary since many tests start failing after
we began reporting diagnostics after call completion
2021-05-20 17:24:12 +03:00
Denis.Zharkov
a700fdc312 FIR: Report diagnostics introduced during call completion 2021-05-20 17:24:10 +03:00
Nikita Bobko
09321e5e41 Implement ide-iml-to-gradle-generator
This module is used to generate build.gradle.kts files
of Kotlin IDE plugin
2021-05-20 16:09:14 +02:00
Nikita Bobko
61bf6bc447 Remove ':idea:idea-jps-common' from 'compiler-components-for-jps' artifact
It seems that it was added by mistake 'compiler-components-for-jps' artifact is used in IDE.
And in IDE we have our own jps-common module
2021-05-20 16:05:38 +02:00
Nikita Bobko
0fc31bc9c7 Disable IDE modules if 'attachedIntellijVersion' flag is specified 2021-05-20 16:05:37 +02:00
Nikita Bobko
897dafc7f3 GenerateTests: extract IDE part into separate module
It's refactoring-preparation commit. In later commits I will add possibility
to disable IDE modules with flags in gradle build (first step towards
removing IDE modules from kotlin repo). Thus, we need to extract IDE tests
generator in separate module for being possible to disable it with flags
2021-05-20 16:05:37 +02:00
Nikita Bobko
ac6c810d25 Make it possible to attach platforms with different versions to kotlin repo 2021-05-20 16:05:37 +02:00
Nikita Bobko
cc34f65392 [cleanup] Remove unused variable 2021-05-20 16:05:37 +02:00
Nikita Bobko
1fa4874426 Create 'installIdeArtifacts' task
This task is used for cooperative compilation with intellij.
See 'Install compiler-for-ide jars' run configuration in
intellij/kotlin-ide/intellij-kotlin repo
2021-05-20 16:05:37 +02:00
Nikita Bobko
8dec62de2b [kotlin + intellij combined] Add one more artifact url
This commit fixes:
```
* What went wrong:
Execution failed for task ':kotlin-ide.intellij.platform.testExtensions:compileKotlin'.
> Could not resolve all files for configuration ':kotlin-ide.intellij.platform.testExtensions:compileClasspath'.
   > Could not find intellij-core-analysis-deprecated-202.7660.26.jar (kotlin.build:ideaIC:202.7660.26).
     Searched in the following locations:
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/ideaIC/202.7660.26/artifacts/lib/intellij-core-analysis-deprecated.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/ideaIC/202.7660.26/artifacts/intellij-core-analysis-deprecated.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/ideaIC/202.7660.26/artifacts/plugins/ideaIC/lib/intellij-core-analysis-deprecated.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/sources/intellij-core-analysis-deprecated-202.7660.26.jar
         file:/home/bobko/.gradle/kotlin-build-dependencies/repo/kotlin.build/ideaIC/202.7660.26/intellij-core-analysis-deprecated.jar
```
2021-05-20 16:05:37 +02:00
Nikita Bobko
54f7633738 build.gradle.kts: exclude :kotlin-ide from allprojects
We don't need to setup compiler args and JDK version for kotlin-ide modules.
Generated build.gradle.kts will do it themselves
2021-05-20 16:05:37 +02:00
Nikita Bobko
6d125e0880 Initial implementation of kotlin + intellij combined repo 2021-05-20 16:05:36 +02:00
Nikita Bobko
cedafedfb0 Add kotlin-ide/ to .gitignore 2021-05-20 16:05:36 +02:00
Alexander Udalov
e0b0df01da Rename fields in KotlinIr.proto according to protobuf style guide
Field names should use snake_case, and names of repeated fields should
use the singular form: https://developers.google.com/protocol-buffers/docs/style#message_and_field_names
2021-05-20 15:59:42 +02:00
Alexander Udalov
8dee36d420 Tests: do not add transitive dependencies in multi-module tests
Prefer to have all module dependencies, including dependencies on
stdlib/reflect, declared explicitly. This allows to have tests on
situations like the one in KT-45308: three modules A<-B<-C, where C
doesn't depend on A, which was compiling correctly with the old JVM
backend before 1.5, but started to fail with JVM IR in 1.5.

Also simplify the code a bit, remove duplicated logic.
2021-05-20 15:58:05 +02:00
Alexander Shabalin
eac3f507b6 Make Kotlin_initRuntimeIfNeeded switch to native state 2021-05-20 13:48:49 +00:00
Ilya Goncharov
f40110eb83 [JS IR] Fixes after rebase 2021-05-20 16:37:52 +03:00
Ilya Goncharov
d65cbdf44d [JS IR] Fixes in tests
- Compilation of tests
- add arguments to extra help
2021-05-20 16:37:50 +03:00
Ilya Goncharov
b76f5547e4 [JS IR] Remove unnecessary overrides in IrNamer 2021-05-20 16:37:48 +03:00
Ilya Goncharov
0921235637 [JS IR] Remove redundant file after rebase 2021-05-20 16:37:47 +03:00
Ilya Goncharov
18cb8a1b9b [JS IR] Add flag with writing base class to metadata 2021-05-20 16:37:45 +03:00
Ilya Goncharov
228c6879f5 [JS IR] Add per-module output module name 2021-05-20 16:37:44 +03:00
Ilya Goncharov
4d7f7fc50f [Gradle, JS] Use jsOutputName as module name 2021-05-20 16:37:43 +03:00
Ilya Goncharov
eaf25b517d [JS IR] Use module name instead of output file wo extension 2021-05-20 16:37:41 +03:00
Ilya Goncharov
0e00186ca1 [JS IR] Fix compilation after rebase 2021-05-20 16:37:39 +03:00
Anton Bannykh
0182c09318 [JS IR] fix name clashes for imported external declarations 2021-05-20 16:37:38 +03:00
Anton Bannykh
6e40c814c8 [JS IR] add a flag which prepends a custom prefix to the per-module .js files 2021-05-20 16:37:37 +03:00
Anton Bannykh
7bd9462ffb [JS IR] save the desired JS output file name in the klib.
This is only usedful for code splitting. The output .js file name
is provided by the build system during the module compilation.
It is desirable to keep the .js output file names same as in old BE,
but calculating those name during the klib -> js phase is tricky.

Thus the desired names are saved in the klib, and used later on.
2021-05-20 16:37:35 +03:00
Anton Bannykh
6633a9edc0 [JS IR] add a flag which enable safe property access
If an accessor is not available at runtime we fall back
to the property access.

This is useful in cases when JS objects are casted to Kotlin
classes implicitly. This pattern did work in the old BE, which
lead to a significant amount of code which doesn't work anymore.
2021-05-20 16:37:34 +03:00
Anton Bannykh
8b18818bcc [JS IR] add base class to the $metadata$.interfaces list
This is needed for better compatibility with the old BE.
Some code in Space relies on the $metadata$ format.
2021-05-20 16:37:32 +03:00
Steven Schäfer
984e912f8d JVM IR: Do not unbox Results in suspend lambda invoke methods (KT-46813) 2021-05-20 14:40:00 +02:00
Dmitriy Novozhilov
ff3f3d2f9b [FIR] Properly setup search scope for IC symbol provider 2021-05-20 14:21:49 +03:00
Dmitriy Novozhilov
6e4cc49f1d [FIR] Cleanup IC provider creation in FirSessionFactory 2021-05-20 14:21:47 +03:00
Dmitriy Novozhilov
6d38a236c1 [FIR] Extract FIR related part of KotlinToJVMBytecodeCompiler to separate file 2021-05-20 14:21:46 +03:00
Jinseong Jeon
f0f1e2d945 FIR checker: report CAPTURED_VAL_INITIALIZATION 2021-05-20 13:59:13 +03:00
Andrey Zinovyev
d38effcbbe Use camel-case in FirFunctionCallOrigin
Also componentCall is operator call
2021-05-20 13:46:35 +03:00
Andrey Zinovyev
419aa65381 [FIR] Fix more tests because of modifier usage in resolution 2021-05-20 13:46:34 +03:00
Andrey Zinovyev
07a8ae7e71 [FIR] Mark more calls origin as OPERATOR 2021-05-20 13:46:32 +03:00
Andrey Zinovyev
0a45b3a50b [FIR] Set Function call origin to assign operators' functions 2021-05-20 13:46:31 +03:00
Andrey Zinovyev
cd22255ab7 [FIR] Set Function call origin in light tree too
Plus actualize some tests
2021-05-20 13:46:30 +03:00
Andrey Zinovyev
e021e25d6c [FIR] Resolve operator calls to operator functions only 2021-05-20 13:46:29 +03:00
Andrey Zinovyev
b1c8669b43 [FIR] Resolve infix calls to infix functions only
Implements INFIX_MODIFIER_REQUIRED diagnostics
2021-05-20 13:46:27 +03:00
Hung Nguyen
df14deb5a0 Organize integration tests for incremental Kotlin compile
Refactor common code into new abstract class
IncrementalCompilationBaseIT to make the code cleaner and easier to
evolve.

Also add a few missing key scenarios for ABI and non-ABI changes in
Kotlin files, and make it consistent with the test for changes in Java
files.

Bug: KT-45777
Test: Updating them
2021-05-20 12:59:07 +03:00
Mikhail Glukhikh
f3c9bd16ee Fix FIR IDE overrideImplement/androidxNotNull test 2021-05-20 12:22:23 +03:00
Mikhail Glukhikh
eac6da62d6 Fix FIR IDE highlighting tests 2021-05-20 12:22:22 +03:00
Mikhail Glukhikh
6dd41b617a FIR: position INAPPLICABLE_FILE_TARGET on file use-site (when possible) 2021-05-20 12:22:22 +03:00
Mikhail Glukhikh
6572010eed Introduce use-site annotation target checks for FIR 2021-05-20 12:22:22 +03:00
Mikhail Glukhikh
9a13ec9b76 FIR: report WRONG_ANNOTATION_TARGET on types 2021-05-20 12:22:22 +03:00
Mikhail Glukhikh
2a33a6927c FIR: report WRONG_ANNOTATION_TARGET(_WITH_USE_SITE_TARGET) on declarations 2021-05-20 12:22:21 +03:00
Mikhail Glukhikh
95f2c52659 FirAnnotationHelpers: use KotlinTarget instead of AnnotationTarget 2021-05-20 12:22:21 +03:00
Mikhail Glukhikh
7675ea3c23 Move AnnotationTargetLists & KotlinTarget to common compiler code 2021-05-20 12:22:21 +03:00
Mikhail Glukhikh
d11092ae3c FIR: support WRONG_ANNOTATION_TARGET on expressions 2021-05-20 12:22:21 +03:00
Mikhail Glukhikh
92ab600081 FIR: add check of SOURCE retention for EXPRESSION-targeted annotation 2021-05-20 12:22:21 +03:00
Mikhail Glukhikh
4b00a43b22 FIR: add ANNOTATION_ON_SUPERCLASS diagnostic 2021-05-20 12:22:20 +03:00
Mikhail Glukhikh
0d6bc7e7b2 FIR: report ANNOTATION_CLASS_CONSTRUCTOR_CALL diagnostic 2021-05-20 12:22:20 +03:00
Mikhail Glukhikh
3663884db2 FIR: support CONDITION_TYPE_MISMATCH diagnostic
We report CONDITION_TYPE_MISMATCH on
- loop conditions
- when branch conditions
- binary logic arguments
2021-05-20 12:22:20 +03:00
Mikhail Glukhikh
e85d97b894 FIR: introduce separate THROWABLE_TYPE_MISMATCH 2021-05-20 12:22:20 +03:00
Mikhail Glukhikh
f0ce311fc6 Drop unused ConeTypeMismatchError 2021-05-20 12:22:19 +03:00
Toshiaki Kameyama
b9a4b60b93 Unnecessary local variable: highlight with INFORMATION level when initializer has any multi-line blocks (#3359)
#KT-26752 Fixed
2021-05-20 11:12:41 +02:00
Andrey Zinovyev
e82857996f [lombok] Resolve to absolute path when import from maven
#KT-46723 Fixed
2021-05-20 11:57:07 +03:00
Pavel Kunyavskiy
2680111125 [K/N] Fix order of lowerings to enable when on enum optimisation
EnumWhenLowering searches for pattern, which is destroyed by
BuiltinOperatorLowering, so first one should happen before second.
2021-05-20 08:34:15 +00:00
Pavel Kunyavskiy
43b91589a1 [K/N] Create lowering for optimising when, with lowered enums support 2021-05-20 08:34:14 +00:00
Pavel Kunyavskiy
1dd6dcdeef [K/N] Store ordinal value in lowered enum 2021-05-20 08:34:13 +00:00
Pavel Kunyavskiy
8a418161f6 [K/N] Support pre-creating for objects with only constant properties 2021-05-20 08:29:23 +00:00
Pavel Kunyavskiy
e4ecb3745b [K/N] Debug util for checking if object is global constant 2021-05-20 08:29:22 +00:00
Ilya Goncharov
5d36264660 Add Node.js 14.17.0 with verification metadata 2021-05-19 21:22:32 +03:00
Ilya Goncharov
f0044516d1 [Gradle, JS] Update Node.js version on latest stable (14.17.0)
^KT-46693 fixed
2021-05-19 21:22:31 +03:00
Igor Yakovlev
b0df70dbfe [ULC] Fix delegate field type resolve
Fixed #KT-46519
2021-05-19 20:49:55 +03:00
Alexander Shabalin
a02cecec20 Disable interop_cleaners_leak 2021-05-19 15:51:05 +00:00
Ilya Muradyan
9412fe094b [REPL] Copy findLabelAndCall to scripting-ide-services to fix problems with embeddable artifact 2021-05-19 18:32:50 +03:00
Ilya Muradyan
7caadd87a2 [Scripting] Get rid of unneeded dependencies in Maven resolver 2021-05-19 18:32:48 +03:00
Alexander Udalov
2fe498149e Psi2ir: add file name to exception when generating synthetic declarations 2021-05-19 17:12:12 +02:00
Alexander Udalov
6581d222cd Fix accidental usage of ASM from jdk.internal in jvm-debugger
Similarly to ee6586fe4f.
2021-05-19 17:11:08 +02:00
Dmitriy Novozhilov
99cdb86145 [FIR] Move createSessionWithDependencies to FirSessionFactory 2021-05-19 16:29:20 +03:00
Dmitriy Novozhilov
2ee54c2201 [FIR] Remove way to create FirSession using Module
The problem is that Module may not contain some default dependencies in
  classpath roots, so it's incorrect to take them from it
2021-05-19 16:29:19 +03:00
pyos
b2ef854aa1 JVM_IR: support @JvmStatic transformations in LateinitLowering
#KT-46759 Fixed
2021-05-19 16:23:01 +03:00
pyos
f1f13b6e97 JVM_IR: do not evaluate receiver of static calls if it is pure
#KT-46802 Fixed
2021-05-19 16:22:59 +03:00
Dmitriy Dolovov
ae1590d3cf [Native] Support multiple suspend lambdas as class supertypes
Drop the backend check. Eveything else is already fixed in
3b3318ab06

^KT-46775
2021-05-19 16:09:47 +03:00
Dmitriy Dolovov
896929cb21 [Native] Support suspend functions as supertypes
^KT-46777
2021-05-19 16:09:38 +03:00
Ilmir Usmanov
9fe503eeb3 Minor. Add regression test
#KT-45685 Fixed
2021-05-19 12:45:26 +02:00
Andrey Uskov
41dd6250d4 Implemented collecting use-old-backend flag from Gradle
#KT-46689 Fixed
2021-05-19 13:25:26 +03:00
Alexander Shabalin
3388ca2536 Support ObjC blocks in the new MM 2021-05-19 07:31:12 +00:00
Alexander Shabalin
94076300ec Implement a bit more of GC object interface 2021-05-19 07:29:27 +00:00
Jinseong Jeon
a3105da32e FIR checker: more specific type for CONFLICTIONG_PROJECTION 2021-05-19 01:04:21 +03:00
Jinseong Jeon
8d474c0e7e FIR checker: more specific type for containing class in diagnostics
about abstract members in non-abstract class
2021-05-19 01:04:20 +03:00
Jinseong Jeon
864ab2cadd FIR checker: clearer parameter names in diagnostics 2021-05-19 01:04:19 +03:00
Dmitriy Novozhilov
e08df2c530 [Test] Add diagnostics and codegen tests with hmpp module structure 2021-05-19 00:52:31 +03:00
Dmitriy Novozhilov
73a63359df [Test] Add new directive for specifying target platform for module 2021-05-19 00:52:28 +03:00
Dmitriy Novozhilov
06b2efe65f [Test] Introduce new syntax for dependsOn dependencies 2021-05-19 00:52:27 +03:00
Dmitriy Novozhilov
47e258ef6e [Test] Enable reporting errors from fronted to testdata of codegen tests 2021-05-19 00:52:25 +03:00
Dmitriy Novozhilov
df60e7368a [Test] Fix syntax errors in few boxInline tests 2021-05-19 00:52:24 +03:00
Dmitriy Novozhilov
27f0d938c9 [Test] Add wrapping of failures from different parts of test pipeline 2021-05-19 00:52:22 +03:00
Dmitriy Novozhilov
6aca0bb374 [Test] Add ability to disable DEBUG_INFO diagnostics except explicitly defined 2021-05-19 00:52:21 +03:00
Dmitriy Novozhilov
d44782f49f [Test] Allow to enable/disable all diagnostics with specific severity 2021-05-19 00:52:19 +03:00
Yahor Berdnikau
7fc23a1647 Deprecate 'kotlin.parallel.tasks.in.project' build property.
Default value will use Gradle parallel execution option value.

^KT-46401 Fixed
2021-05-18 21:02:02 +00:00
Dmitry Petrov
851980e36f JVM_IR KT-45103 optimize direct invoke for lambdas and callable refs 2021-05-18 22:20:12 +03:00
pyos
bfb1a06f3d FIR: resolve conflicts between overloads with platform integer types 2021-05-18 22:11:33 +03:00
Victor Petukhov
a27d428573 Regenerate tests 2021-05-18 21:26:10 +03:00
Dmitriy Novozhilov
38fe917141 [FIR] Change order of IC symbol provider and dependency symbol provider
This is semantically incorrect, but current behavior leads to problems
  in FIR bootstrap due to incorrect setup of IC provider. So this ordering
  change is a workaround for now
2021-05-18 20:56:07 +03:00
Dmitriy Novozhilov
7d5fa2830d [FIR] Properly create source search scope in FIR CLI compiler 2021-05-18 20:56:05 +03:00
Dmitriy Novozhilov
dbccd4d459 [FIR] Properly acquire module data in FirSignatureEnhancement 2021-05-18 20:56:04 +03:00
Steven Schäfer
bf7db84451 Parcelize: Handle class hierarchies of Parcelers (KT-46567) 2021-05-18 18:52:15 +02:00
Andrey Zinovyev
709c127f1b [IR] Distinguish super calls from other calls
Otherwise super call and virtual call to the same method get the same
map key in case of Fir2Ir IR generation
2021-05-18 19:32:23 +03:00
Steven Schäfer
60bc0f4baf IR: Lower shared variables in enum entries (KT-46605) 2021-05-18 16:55:38 +02:00
Victor Petukhov
b78c645fb0 Report warnings by enhanced base types 2021-05-18 17:52:39 +03:00
Victor Petukhov
2239404085 Extract type preparation during type checking to a separate component 2021-05-18 17:52:23 +03:00
Victor Petukhov
cba221c18a Add test for enhancement in usages of annotated type parameter 2021-05-18 17:52:21 +03:00
Victor Petukhov
fd6475c804 Update tests 2021-05-18 17:52:19 +03:00
Victor Petukhov
8602d1fcf0 Merge foreign annotation tests for sources and binaries into single directory 2021-05-18 17:52:16 +03:00
Victor Petukhov
df2c95e444 [Jspecify] Use bounds of type parameters for warnings reporting as well 2021-05-18 17:52:14 +03:00
Victor Petukhov
0c4cba549d [Jspecify] Use arguments of enhancement of type instead of arguments of base type during getting enhancement of type deeply 2021-05-18 17:52:12 +03:00
Victor Petukhov
21dada4d2d [Jspecify] Use enhancement of type with enhancement if possible during substitution 2021-05-18 17:52:10 +03:00
Victor Petukhov
12f6146bdf [Jspecify] Substitute enhancement of type instead of type itself directly 2021-05-18 17:52:09 +03:00
Victor Petukhov
2479655708 [Jspecify] Do preserving flexibility when adding equality constraints by taking into account type with enhancement 2021-05-18 17:52:07 +03:00
Victor Petukhov
937e82db46 [Jspecify] Report warnings on violated bounds of method type parameters 2021-05-18 17:52:06 +03:00
Victor Petukhov
0d6764efc5 Process raw types during erasion properly
^KT-46670 Fixed
^KT-46476 Fixed
2021-05-18 17:38:52 +03:00
Svyatoslav Scherbina
570d860217 Native: deprecate SymbolName annotation 2021-05-18 17:29:00 +03:00
Igor Chevdar
3b3318ab06 [K/N][codegen] Refactored interface calls
Removed old impl for debug builds
Fixes https://youtrack.jetbrains.com/issue/KT-44547 as a side effect
2021-05-18 18:58:14 +05:00
Alexander Likhachev
3df45f9651 [Build] Bump kotlin-build-gradle-plugin version to 0.0.29 2021-05-18 16:37:36 +03:00
Alexander Likhachev
8a3a60caae [Build] Bump kotlinx-benchmark version to 0.3.1
kotlinx-benchmark Gradle plugin 0.3.1 now reads system property `idea.active` in compatible with configuration cache way
#KT-44611 In Progress
2021-05-18 16:37:36 +03:00
Alexander Likhachev
cf00bc8243 [Build] Remove outdated IDEA sync detection 2021-05-18 16:37:35 +03:00
Alexander Likhachev
b6670f5cc8 [Build] Replace build scan config script with plugin
See 129e82c556/common-custom-user-data-gradle-plugin
2021-05-18 16:37:35 +03:00
Alexander Likhachev
8ddbf542f3 [Gradle] Declare IDEA-related system properties reads
#KT-44611 In Progress
2021-05-18 16:37:34 +03:00
Alexander Likhachev
091b2129e7 [Build] Make GE build scan configuration compatible with conf cache
#KT-44611 In Progress
2021-05-18 16:37:34 +03:00
Alexander Likhachev
ca2051e1d4 [Build] Disable custom normalization when conf cache is enabled
Custom input normalizations currently isn't supported by Gracle configuration cache
#KT-44611 In Progress
2021-05-18 16:37:34 +03:00
Alexander Likhachev
cc183e96a4 [Build] Fix configuration cache undeclared system property read issues
#KT-44611 In Progress
2021-05-18 16:37:29 +03:00
Andrei Klunnyi
f0a6d9f33f VFS: reset KOTLIN_IS_COMPILED_FILE_ATTRIBUTE
This commit resets mentioned file attribute from Kotlin binary files.
It finalizes the fix 929b6dd9 - users might have mistakenly set 'false'
value left on their file systems.
2021-05-18 15:34:26 +03:00
Vladimir Ivanov
5a0f113e6d [cinterop] Fix type annotation for struct containing anonymous union … (#4289) 2021-05-18 14:34:56 +03:00
Vladimir Dolzhenko
b01478746c Cache all module dependencies to avoid O(n^2) calc complexity
Quite noticeable when there is a big module that has 100+ libraries and many modules depends on it

#KT-46622 Fixed
2021-05-18 09:20:18 +00:00
Andrey Zinovyev
82b7f589ad Add missing base-compiler-plugins-ide-support dependencies 2021-05-18 11:49:04 +03:00
pyos
21f2b3fa2b JVM: expect a continuation parameter in default suspend references 2021-05-18 10:48:31 +02:00
pyos
7eedcf75f9 Add tests for default inline suspend lambdas
Broken on JVM and JVM_IR
2021-05-18 10:48:31 +02:00
pyos
57c934987c JVM_IR: try to load mangled invoke from default lambdas
Old compiler versions still won't be able to load default lambdas
generated by JVM_IR, but this way we avoid incorrect behavior of
function references taking inline class types that unbox to Any.

 #KT-46601 Fixed
2021-05-18 10:48:31 +02:00
pyos
34ac232a82 Add a test for KT-46601 2021-05-18 10:48:31 +02:00
pyos
c32ccbb39a JVM: move descriptors from DefaultLambda to PsiDefaultLambda
Also, produce more correct results in IrDefaultLambda's
`invokeMethodParameters` and `invokeMethodReturnType`. This affects
whether the inliner inserts inline class boxings/unboxings around lambda
calls; while this doesn't matter now due to KT-46601, it would if the
naming was fixed.
2021-05-18 10:48:31 +02:00
pyos
7c168d663a JVM: move PSI-based LambdaInfo to PsiInlineCodegen 2021-05-18 10:48:31 +02:00
pyos
493b4e6c27 JVM: rearrange some LambdaInfo stuff 2021-05-18 10:48:31 +02:00
pyos
14e1417ea8 JVM: expect consistent signatures from LambdaInfo 2021-05-18 10:48:31 +02:00
Yahor Berdnikau
aae5cc5574 Update AGP versions to the latest stable one.
Kotlin Gradle Plugin should run against the latest stable one versions.
2021-05-18 10:37:41 +03:00
Ivan Kochurkin
73fb851864 [FIR] Commit incorrect test data that should be restored after fix of https://youtrack.jetbrains.com/issue/KT-41794 2021-05-17 22:33:19 +03:00
Ivan Kochurkin
c3b8f3e859 [FIR] Add lValueTypeRef to FirVariableAssignment, fix tests with ASSIGNMENT_TYPE_MISMATCH 2021-05-17 22:33:18 +03:00
Ivan Kochurkin
e57108d4e8 [FIR] Implement ASSIGNMENT_TYPE_MISMATCH, RESULT_TYPE_MISMATCH diagnostics, fix tests 2021-05-17 22:33:16 +03:00
Ilya Kirillov
aa70c952eb FIR IDE: fix SOE on opening project
Kotlin library may contain cycles which causes SOE in FirModuleInfoBasedModuleData.dependencies
2021-05-17 20:56:57 +02:00
Ilya Chernikov
d365d7c784 Fix IR compilation for empty script
#KT-46646 fixed
2021-05-17 20:15:14 +03:00
Dmitry Petrov
3a0e3798ec JVM_IR KT-46597 fix receiver type for inlined callable reference
Receiver type is used by SyntheticAccessorLowering to determine class in
which a synthetic accessor should be generated.
2021-05-17 20:12:58 +03:00
Konstantin Tskhovrebov
80ce3a5cf8 Delete umbrella Apple framework tasks and register concrete tasks.
#KT-46680
2021-05-17 19:45:02 +03:00
Ilya Muradyan
55a9f1a910 [Scripting] Make AetherResolveSession internal and do related refactorings 2021-05-17 18:22:29 +03:00
Ilya Muradyan
a0cc88ab5a [Scripting] Add transitive support for Maven Resolver 2021-05-17 18:22:28 +03:00
Ilya Muradyan
b77a822822 [Scripting] Add authorization for Maven Resolver 2021-05-17 18:22:26 +03:00
Ilya Muradyan
78c65ab802 [Scripting] Bump up Maven resolver JARs version 2021-05-17 18:22:25 +03:00
Yahor Berdnikau
800e382ba9 Warn on using 'jdkHome' option in Gradle builds.
User should instead use KotlinJavaToolchain that will take care of
tracking major java version and provide nicer API.

Gradle will still pass jdkHome value to the compiler, but it should
be changed in Kotlin 1.6 release.

^KT-45611 Fixed
2021-05-17 16:57:01 +03:00
Ilya Goncharov
74d1812461 [JS IR] Review remarks
- Move origin to common place
- Add comments and todo about solution
- Remove MODULE directive from tests
- Add test with in-place using of js function
2021-05-17 16:51:22 +03:00
Ilya Goncharov
507516e44d [JS IR] Add tests with reified generic and with KType on DCE to leave class 2021-05-17 16:51:20 +03:00
Ilya Goncharov
f0b3ee0e35 [JS IR] Add test with class reference using from js 2021-05-17 16:51:19 +03:00
Ilya Goncharov
137532bfa6 [JS IR] Use separate origin for class reference to preserve constructors 2021-05-17 16:51:17 +03:00
Leonid Startsev
796d2fd210 Respect explicit api mode state when generating actual declarations
#KT-44067 Fixed
2021-05-17 12:40:49 +00:00
Leonid Startsev
8cd704b6db Exclude public API symbols in explicit mode from unused symbol inspection
#KT-41659 Fixed
2021-05-17 12:40:48 +00:00
Leonid Startsev
19dece01f6 Add support of explicit API mode to 'Make public' intention
#KT-41902 Fixed

Do not check languageVersionSettings for fake elements
because this leads to an exception
2021-05-17 12:40:47 +00:00
Igor Yakovlev
d34c23914a [FIR IDE] Fix invalid designation collecting for local classes 2021-05-14 23:06:04 +03:00
Igor Yakovlev
207bad5d5f [FIR IDE] Implementation of KtUserType resolve 2021-05-14 23:06:03 +03:00
Igor Yakovlev
a5f701bac7 [FIR IDE] OnAir resolve for annotations with file site 2021-05-14 23:06:02 +03:00
Igor Yakovlev
dedcaf1eab [FIR IDE] Fixed annotation application completion 2021-05-14 23:06:00 +03:00
Igor Yakovlev
3275165619 [FIR IDE] Fix resolve for incomplete or invalid references 2021-05-14 23:05:59 +03:00
Igor Yakovlev
2bfacaaed2 [FIR IDE] Rename and move refactorings, codereview refactorings 2021-05-14 23:05:58 +03:00
Igor Yakovlev
c5372be267 [FIR IDE] Move and rename RawFirFragmentForLazyBodiesBuilder into Fir Ide module 2021-05-14 23:05:57 +03:00
Igor Yakovlev
0569f810cf [FIR IDE] Add OnAir resolve tests 2021-05-14 23:05:55 +03:00
Igor Yakovlev
633e03b710 [FIR IDE] LowLevel api refactoring 2021-05-14 23:05:54 +03:00
Igor Yakovlev
445f13d1bf [FIR IDE] Fix invalid body lazy resolve 2021-05-14 23:05:53 +03:00
Igor Yakovlev
cfc0bfd64a [FIR IDE] Refactoring of designated IDE transformers 2021-05-14 23:05:52 +03:00
Igor Yakovlev
384b2ad048 [FIR IDE] Rename refactoring and speed improvements 2021-05-14 23:05:50 +03:00
Igor Yakovlev
966743c704 [FIR IDE] Enable passing completion tests 2021-05-14 23:05:49 +03:00
Igor Yakovlev
37ccab4e23 [FIR] Fixed supertypes resolve for invalid code with class without ClassId 2021-05-14 23:05:48 +03:00
Igor Yakovlev
2e7eedd3f2 [FIR IDE] Correct in-body supertype resolve of fake nodes 2021-05-14 23:05:46 +03:00
Igor Yakovlev
959ff50fa7 [FIR IDE] Collect tower contexts for local declarations 2021-05-14 23:05:45 +03:00
Igor Yakovlev
ae63ad0b6d [FIR] Fix annotations invalid references diagnostics 2021-05-14 23:05:44 +03:00
Igor Yakovlev
261098a122 [FIR IDE] Implement on-air resolve of non-local declarations 2021-05-14 23:05:42 +03:00
Igor Yakovlev
779a06e86f [FIR IDE] Add types, supertypes and status lazy designated transformers 2021-05-14 23:05:41 +03:00
Igor Yakovlev
95acb6121b [FIR IDE] Fixed property and parameter creation/replacement and fixed invalid source on annotation type 2021-05-14 23:05:40 +03:00
Igor Yakovlev
38242bee75 [FIR] Fixed invalid real psi source fir fir annotation name reference 2021-05-14 23:05:38 +03:00
Igor Yakovlev
aaefe94763 [FIR IDE] Refactor low level resolve state for completion
Rename refactorings
Remove redundant methods and implementations
Increase code-logic locality
Removed redundant entities
2021-05-14 23:05:37 +03:00
Alexander Udalov
aa13936cb2 Move GenerateProtoBuf to separate source set with no dependencies
Also move GenerateProtoBufCompare to a new source set with a dependency
only on build-common.

 #KTI-79 Fixed
2021-05-14 21:08:56 +02:00
Ilya Kirillov
8b722cfc47 Separate uast-idea modules into fir and fe10 implementations 2021-05-14 20:57:20 +03:00
Svyatoslav Scherbina
ba6c3c7fe0 Add workaround for KT-35001
Just suppress the warning.
The accident it describes is generally harmless and totally expected.
2021-05-14 20:05:30 +03:00
Svyatoslav Scherbina
48a684c024 Native: implement custom handling for LLVM diagnostics
Apply it when linking LLVM modules, because otherwise LLVM would
terminate the entire compiler process on link errors, which isn't ok,
e.g. when embedding the compiler into Gradle daemon (see KT-46358).
2021-05-14 20:05:29 +03:00
Alexander Udalov
ee6586fe4f Fix accidental usage of ASM from jdk.internal
#KT-46402 Fixed
2021-05-14 15:23:08 +02:00
Dmitry Petrov
d1322280dd JVM_IR KT-46578 resolve fake overrides for fields 2021-05-14 16:20:22 +03:00
Mikhail Glukhikh
a255f44d6e FIR2IR KT-46578 add overridden properties generation 2021-05-14 16:20:20 +03:00
Dmitry Petrov
53c1de172f IR KT-46578 add IrProperty#overriddenSymbols 2021-05-14 16:20:18 +03:00
Andrey Zinovyev
dc9d5cdf35 [FIR] Handle of special getters when there is a kotlin super type
Special getter names (like Collection.size()) can be used only in Java
classes with all-java super-types
Because if there is a kotlin class (not interface) in
 the middle, we 'materialize' special getters to properties.
2021-05-14 15:38:09 +03:00
Dmitriy Novozhilov
7066a5b3dc [FIR-IDE] Questionable testdata update 2021-05-14 14:30:46 +03:00
Dmitriy Novozhilov
c652a9e7b1 [FIR-IDE] Use correct session in member scope provider 2021-05-14 14:30:45 +03:00
Dmitriy Novozhilov
194252e5a1 [FIR-IDE] Properly setup moduleDataProvider for ide library session 2021-05-14 14:30:44 +03:00
Dmitriy Novozhilov
43b075d452 [FIR] Add path normalization to LibraryPathFilter 2021-05-14 14:30:43 +03:00
Dmitriy Novozhilov
cf5af0f7ea [FIR] Add KDoc to FirModuleData 2021-05-14 14:30:42 +03:00
Dmitriy Novozhilov
f02a4a6b1f [FIR-IDE] Add workaround hack for building raw FIR with libraries session 2021-05-14 14:30:41 +03:00
Dmitriy Novozhilov
0427066558 [FIR-IDE] Fix compilation after changes in API of FirSessionFactory 2021-05-14 14:30:40 +03:00
Dmitriy Novozhilov
af307bd55d [FIR] Fix compilation of AbstractFirBaseDiagnosticsTest 2021-05-14 14:30:38 +03:00
Dmitriy Novozhilov
28be3a0dbc [FIR] Replace Path with String in KotlinJvmBinaryClass.containingLibrary
This is needed because :core:deserialization.common.jvm uses JDK 6
2021-05-14 14:30:37 +03:00
Dmitriy Novozhilov
2abed7161b [FIR] Get rid of FirJvmModuleInfo 2021-05-14 14:30:36 +03:00
Dmitriy Novozhilov
28e4721a89 [FIR] Check internal visibility in FirJvmModuleVisibilityChecker using module data 2021-05-14 14:30:35 +03:00
Dmitriy Novozhilov
02c58b7a8f [FIR] Refactor deserialized dependency providers and session factories with FirModuleData 2021-05-14 14:30:33 +03:00
Dmitriy Novozhilov
24f1f7b7b2 [FIR] Unify FirLibrarySession and FirJavaModuleBasedSession into single FirCliSession 2021-05-14 14:30:32 +03:00
Dmitriy Novozhilov
f16194e60d [FIR] Get rid of FirSession.moduleInfo 2021-05-14 14:30:31 +03:00
Dmitriy Novozhilov
57a8642f5a [FIR] Add analyzer services to FirModuleData 2021-05-14 14:30:29 +03:00
Dmitriy Novozhilov
92d6b39ffe [FIR] Add late initialization of session in FirModuleData 2021-05-14 14:30:28 +03:00
Dmitriy Novozhilov
5cfa8694d4 [FIR] Fix all usages of declarationSiteSession 2021-05-14 14:30:27 +03:00
Dmitriy Novozhilov
a15316de24 [FIR] Replace declarationSiteSession with moduleData 2021-05-14 14:30:26 +03:00
Dmitriy Novozhilov
fa8d8ad503 [FIR] Add cache for top-level functions and properties to AbstractFirDeserializedSymbolsProvider 2021-05-14 14:30:25 +03:00
Dmitriy Novozhilov
c523379e6a [FIR] Move out all JVM specific deserialization logic from AbstractFirDeserializedSymbolsProvider 2021-05-14 14:30:23 +03:00
Dmitriy Novozhilov
e8c4b0e947 [FIR] Rename KotlinScopeProvider to FirKotlinScopeProvider 2021-05-14 14:30:22 +03:00
Dmitriy Novozhilov
4ad7a4a2d1 [FIR] Split KotlinDeserializedJvmSymbolsProvider to common and JVM specific parts 2021-05-14 14:30:21 +03:00
Dmitriy Novozhilov
e5b7cf23d6 Drop min functions from addToStdlib.kt 2021-05-14 14:30:20 +03:00
Dmitriy Novozhilov
d114913cd2 Replace usages of addToStdlib.firstNotNullResult with firstNotNullOfOrNull 2021-05-14 14:30:19 +03:00
Dmitriy Novozhilov
24b6c5df56 Add regression test for KT-45905 2021-05-14 14:30:14 +03:00
Anton Yalyshev
c386b10f04 Add change notes for 1.5.20-M1 2021-05-14 14:05:44 +03:00
Tianyu Geng
3c4e3e8db6 FIR: remove obsolete DataFlowVariablev.isStable 2021-05-14 13:34:33 +03:00
Andrey Zinovyev
84a7bdffe5 [FIR] Don't report MUST_BE_INITIALIZED* on unreachable properties 2021-05-14 12:41:18 +03:00
Alexander Udalov
8308f5d7d3 Create array instances of correct types in reflection
Based on #4168.

 #KT-44977 Fixed

Co-authored-by: Arkady Bazhanov <arkady.bazhanov@gmail.com>
2021-05-14 11:16:29 +02:00
Roman Golyshev
ec6c25ef7e FIR IDE: Remove names duplicates in createImportTypeFix 2021-05-13 21:41:57 +03:00
Roman Golyshev
9504488acb FIR IDE: Do not show hint from ImportQuickFix if the PSI have changed
Without this check, the import hint will be available even after the
quickfix is applied; this happens because the element to which the
quickfix is attached is not invalidated by the quickfix execution

Since the quickfix is still considered as available some time after
the import have been added, the hint is also generated. And the hint
stays even after the quickfix itself is discarded

`isOutdated` function prevents this
2021-05-13 21:41:56 +03:00
Alexander Udalov
8991ce53f4 Regenerate tests 2021-05-13 19:16:09 +02:00
Steven Schäfer
b2378620c3 JVM IR: Fix handling of anonymous initializers in inline classes (#4372)
Fixes KT-46554
2021-05-13 18:40:26 +02:00
Yan Zhulanow
cc4c61d2b3 Remove dependency on parcelize-runtime in the Parcelize compiler plugin 2021-05-14 01:06:39 +09:00
Yan Zhulanow
e90cc30edb Remove CLI and some of daemon-related modules from compiler-for-ide
These modules is not required by the plugin, and the plugin verifier
warns about unsatisfied dependencies of the modules.

CLI is needed in tests so a separate artifact is created instead.
2021-05-14 01:06:39 +09:00
Yan Zhulanow
26f71c33c0 IDE: Publish JS IR klib artifact 2021-05-14 01:06:39 +09:00
Andrey Zinovyev
58c7aa9937 [FIR] Don't replace custom compareTo with default one in primitives 2021-05-13 18:04:43 +03:00
Mikhail Glukhikh
1a3aa1bff0 FIR: report ANNOTATION_PARAMETER_DEFAULT_VALUE_MUST_BE_CONSTANT 2021-05-13 16:13:44 +03:00
Mikhail Glukhikh
55104a594c FIR: fix WRONG_GETTER(SETTER)_RETURN_TYPE associated PSI types 2021-05-13 16:13:44 +03:00
Mikhail Glukhikh
0f9f63400e FirSupertypesChecker: implement six more diagnostics 2021-05-13 16:13:43 +03:00
Mikhail Glukhikh
db828a6aad Generalize FirInterfaceWithSuperclassChecker to FirSupertypesChecker 2021-05-13 16:13:43 +03:00
Mikhail Glukhikh
632a9d66d1 FIR: introduce isPrimitive / isPrimitiveOrNullablePrimitive helpers 2021-05-13 16:13:42 +03:00
Mikhail Glukhikh
6d82aa0bc9 Drop duplicating FirPropertyAccessorChecker 2021-05-13 16:13:08 +03:00
Mikhail Glukhikh
d2cbf941db Collect all accessor checks in FirPropertyAccessorChecker 2021-05-13 16:13:08 +03:00
Mikhail Glukhikh
243114ef29 FIR: add 'withSuppressedDiagnostics' call to property checkers 2021-05-13 16:13:08 +03:00
Mikhail Glukhikh
6618b4ea57 FirPropertyAccessorChecker: add three new diagnostics 2021-05-13 16:13:07 +03:00
Dmitriy Novozhilov
1a3b5657c7 [FIR] Fix overload conflicts resolution for callable references with defaults 2021-05-13 15:31:18 +03:00
Alexander Udalov
e3b92fd561 Update instructions to run protoc on Windows and Linux 2021-05-13 13:58:43 +02:00
Alexander Udalov
b5af93c8b4 Fix IR proto backward compatibility for InlineClassRepresentation
This is important only if any backend which uses IR serialization will
(accidentally or voluntarily) use `IrClass.inlineClassRepresentation`,
which is missing in IR of klibs serialized with 1.5.20 or earlier.

Note that at the moment only JVM IR is using
`IrClass.inlineClassRepresentation`, but ideally we'd like to change
that (if needed).
2021-05-13 13:58:43 +02:00
Alexander Udalov
0a18174165 IR: remove hack related to inline class representation in lazy IR
This commit effectively reverts changes from
b5f9b1dfc0, fixing the problem from
KT-44723 in a stabler way. It is possible because we now serialize
inline class representation to metadata and after previous changes, we
have that representation as a field in IrClass.
2021-05-13 13:56:59 +02:00
Alexander Udalov
da06faa57e JVM IR: use inlineClassRepresentation in more utilities
Remove any logic related to finding the single parameter of the primary
constructor, and use inlineClassRepresentaton from IrClass or
ClassDescriptor instead.
2021-05-13 13:56:59 +02:00
Alexander Udalov
54befa769f IR: add IrClass.getInlineClassRepresentation, serialize/deserialize it
The change in FirDeclarationUtil is needed because in case of unsigned
types loaded from the standard library, the primary constructor for some
reason is not the first, but the second in the list of constructors.
2021-05-13 13:56:59 +02:00
Alexander Udalov
4c7f207309 Use new getInlineClassRepresentation in some utilities 2021-05-13 13:54:02 +02:00
Alexander Udalov
7fb3f48c67 Add ClassDescriptor.getInlineClassRepresentation
This will be used at least in the JVM backend instead of the current
approach where we're loading the primary constructor's first parameter,
which isn't good enough since primary constructor can be private, and
we can't rely on private declarations in case they're declared in
another module.
2021-05-13 13:54:02 +02:00
Steven Schäfer
6aaff9dfb7 JVM IR: Handle overloaded values functions in MappedEnumWhenLowering
Fixes KT-46579.
2021-05-13 13:24:32 +02:00
Andrey Zinovyev
5d30576d28 [FIR] Report not-a-constant diagnostics inside function calls
When function calls are not fully resolved
2021-05-13 10:15:26 +03:00
Andrey Zinovyev
e74141ded6 [FIR] Properly check spread constant argument 2021-05-13 10:13:21 +03:00
Andrey Zinovyev
07e47140a6 [FIR] Treat unsigned numbers as primitives in constant checker 2021-05-13 10:11:59 +03:00
Roman Golyshev
9cadd1c8a7 Remove IGNORE_FIR from test data of already green test 2021-05-13 03:22:07 +03:00
Pavel Punegov
238ada04c0 Use newer version of Kotlin/Native in the testNativeCompilerDownloading 2021-05-13 03:19:23 +03:00
Yahor Berdnikau
13fd2a24ea Fix exposing provided by Gradle Kotlin dependencies.
Ensure that Gradle plugin dependencies do not include kotlin-stdlib,
kotlin-reflect and other dependencies that are provided by Gradle
runtime.

^KT-41142 Fixed
2021-05-12 23:28:37 +03:00
Steven Schäfer
1198b40c11 Parcelize: Port the fix for KT-41553 to android-extensions
Fixes KT-46590.
2021-05-12 21:18:15 +02:00
Ilya Kirillov
4ef81e93ef FIR IDE: properly implement FirKeywordCompletionContributor.keywordCompletion 2021-05-12 21:40:22 +03:00
Ilya Kirillov
ca320f2f8d FIR IDE: add this labels to keyword completion 2021-05-12 21:40:20 +03:00
Ilya Kirillov
47a596c214 FIR IDE: add return target to tail in keyword completion
The same do FE10 completion and we need it to have consistent tests
2021-05-12 21:40:19 +03:00
Ilya Kirillov
f8fc43f1e9 FIR IDE: add AbstractKeywordCompletionTest 2021-05-12 21:40:18 +03:00
Ilya Kirillov
96117fc1eb FIR IDE: cleanup FirPositionCompletionContextDetector.detect 2021-05-12 21:40:16 +03:00
Ilya Kirillov
597d64b81d FIR IDE: do not ignore passing tests from AbstractFirKeywordCompletionHandlerTest 2021-05-12 21:40:15 +03:00
Ilya Kirillov
f18bcdb88c FIR IDE: add AbstractFirKeywordCompletionHandlerTest 2021-05-12 21:40:14 +03:00
Ilya Kirillov
e5202f44d7 Refactor keyword completion handlers
- Separate completion keyword handlers stuff into files
- Introduce CompletionKeywordHandlerProvider as a common way to provide handlers
- Move CompletionKeywordHandler factory out of companion object
2021-05-12 21:40:12 +03:00
Ilya Kirillov
8983bde73e FIR IDE: implement override completion 2021-05-12 21:40:11 +03:00
Ilya Kirillov
ae212f36f5 FIR IDE: move addElementToCompletion to FirCompletionContributorBase 2021-05-12 21:40:10 +03:00
Ilya Kirillov
e624f2c136 FIR IDE: do not pass resultSet in KotlinWithNameReferenceCompletionProvider as it is already available 2021-05-12 21:40:09 +03:00
Ilya Kirillov
49aba39ae8 Make OverridesCompletionLookupElementDecorator available for FIR IDE 2021-05-12 21:40:07 +03:00
Ilya Kirillov
8f399652d7 FIR IDE: add expressions to return keyword completion
Also, adds return targets for return with labels while FE1.0 plugin don't
2021-05-12 21:40:06 +03:00
Ilya Kirillov
8cfa85df6b FIR IDE: make FirKeywordCompletion to be a completion contributor 2021-05-12 21:40:04 +03:00
Ilya Kirillov
ca1fd185dc FIR IDE: introduce base class for completion provider 2021-05-12 21:40:03 +03:00
Ilya Kirillov
81c6f38f79 FIR IDE: move context creation out of KotlinFirCompletionContributor 2021-05-12 21:40:02 +03:00
Ilya Kirillov
8eff865277 FIR IDE: encapsulate basic completion parameters into class 2021-05-12 21:40:01 +03:00
Ilya Kirillov
a08c267c37 FIR IDE: mute a few completion tests as they now fails because of unexpected keywords 2021-05-12 21:39:59 +03:00
Ilya Kirillov
98becc9a50 FIR IDE: remove FIR_IGNORE from passing completion test after implementing basic keyword completion 2021-05-12 21:39:58 +03:00
Ilya Kirillov
36068d0b94 FIR IDE: reuse keyword completion handlers which do not require resovle 2021-05-12 21:39:57 +03:00
Ilya Kirillov
1f93eb0841 FIR IDE: add basic keyword completion 2021-05-12 21:39:56 +03:00
Ilya Kirillov
62fe3930ff Move keyword completion stuff to frontend-independent module 2021-05-12 21:39:54 +03:00
Roman Golyshev
d7a91cb05e Remove IGNORE_FIR directive from already green tests 2021-05-12 16:28:31 +00:00
Roman Golyshev
4adb291a12 Mute failing AutoImportQuickFix tests 2021-05-12 16:28:30 +00:00
Roman Golyshev
03a1439cc0 Make IgnoreTests fail correctly when directive is outdated
`Outdated` means green test with `IGNORE_FIR` directive, or
red test with `FIR_COMPARISON` directive

Also, invoke directive insertion only when it is appropriate
2021-05-12 16:28:29 +00:00
Roman Golyshev
22db894076 FIR IDE: Add Add Import quickfix
This quickfix can import unresolved types and callables

It currently does not support Java types and is not as advanced as in
the old plugin

Also, enable tests that now pass
2021-05-12 16:28:28 +00:00
Roman Golyshev
3ad9e4cb5c Use Import instead of action FQN
This way test data can be used both in the old plugin and in the
FIR plugin
2021-05-12 16:28:27 +00:00
Roman Golyshev
eadd7ac034 Generate multi-file quickfix tests for FIR plugin
Currently generate only for `Import` quickfix
2021-05-12 16:28:27 +00:00
Roman Golyshev
24642a7c9f Add KtTypeElement.unwrapNullability() extension function
Replace similar functions with its usage
2021-05-12 16:28:26 +00:00
Roman Golyshev
cc41592969 Add possibility to compute additional files for IgnoreTests
It is more flexible then just passing additional prefixes, since in some
cases test data have some weird naming conventions
2021-05-12 16:28:25 +00:00
Roman Golyshev
e50d643213 Add possibility to use ModuleLibrariesSearchScope in other modules
The type is made private to avoid direct usage of it
2021-05-12 16:28:24 +00:00
Ivan Kochurkin
598501aaf0 [FIR] Improve locations for DEPRECATED_SINCE_KOTLIN_WITHOUT_DEPRECATED, DEPRECATED_SINCE_KOTLIN_WITH_DEPRECATED_LEVEL, DEPRECATED_SINCE_KOTLIN_OUTSIDE_KOTLIN_SUBPACKAGE and other diagnostics, refactor 2021-05-12 18:42:44 +03:00
Ivan Kochurkin
52c32d3d85 [FIR] Implement DEPRECATED_SINCE_KOTLIN_OUTSIDE_KOTLIN_SUBPACKAGE, fix tests 2021-05-12 18:42:43 +03:00
Ivan Kochurkin
177394f6ef [FIR] Implement DEPRECATED_SINCE_KOTLIN_WITH_DEPRECATED_LEVEL, fix tests 2021-05-12 18:42:42 +03:00
Ivan Kochurkin
77c137df22 [FIR] Add DEPRECATED_SINCE_KOTLIN_WITHOUT_DEPRECATED diagnostics, fix tests 2021-05-12 18:42:41 +03:00
Ivan Kochurkin
3191e0b925 [FIR] Implement DEPRECATED_SINCE_KOTLIN_WITHOUT_ARGUMENTS diagnostics, fix tests, merge and refactor annotation checkers 2021-05-12 18:42:40 +03:00
Ivan Kochurkin
dc99a673a5 [FIR] Implement DEPRECATED_SINCE_KOTLIN_WITH_UNORDERED_VERSIONS diagnostics, fix tests 2021-05-12 18:42:38 +03:00
Ivan Kochurkin
5c086e2321 [FIR] Implement NEWER_VERSION_IN_SINCE_KOTLIN diagnostics, fix tests 2021-05-12 18:42:37 +03:00
Ivan Kochurkin
1be02e3ac4 [FIR] Implement ILLEGAL_KOTLIN_VERSION_STRING_VALUE diagnostics, fix tests 2021-05-12 18:42:36 +03:00
Jinseong Jeon
cb0b80253c FIR/UAST: make a fat jar with the base module 2021-05-12 17:36:35 +02:00
Ilya Muradyan
bab5d16001 [REPL] Stop old classpath calculation on the base classloader
The mechanism of the recursive classpath checking is intended
 for the "inner" scripting/REPL classloaders and should not touch
 anything beyond.
2021-05-12 18:30:43 +03:00
Mikhail Glukhikh
4608ca15eb FIR: don't allow SEALED callable modality anymore 2021-05-12 17:50:29 +03:00
Mikhail Glukhikh
67d1c35f19 FIR: report MANY_INTERFACES_MEMBER_NOT_IMPLEMENTED also on interfaces 2021-05-12 17:50:27 +03:00
pyos
3fc2cc410c JVM_IR: propagate reified type parameter usages from inline lambdas
...to whichever class they are inlined into, not the class they are
declared in (which is not the same if the lambda is crossinline).

 #KT-46584 Fixed
2021-05-12 15:09:35 +03:00
Alexander Udalov
e079fb665e JVM IR: fix inheritance from mutable collections of Int
For subclasses of `AbstractMutableList<Int>` which are not inline
classes, the special bridge `remove` had a parameter of type `Int`
(mapped to JVM primitive int) before this fix. The hack in
`MethodSignatureMapper` changed this type to `Int?`, yet the body of the
special bridge still loaded it as non-nullable, which resulted in
incorrect bytecode.

It looks like a part of this hack in `BridgeLowering` was made only for
inline classes which are subclasses of mutable collections. Supposedly
it should be extended to non-inline classes, so that `remove` special
bridge would have consistent IR by the time it reaches codegen.

 #KT-46516 Fixed
2021-05-12 13:58:40 +02:00
Nikolay Krasko
f30980806f Read process streams to avoid hanging on Windows in parcelize tests
Could be reproduced with ParcelizeBoxTestGenerated.testKt36658 test.
2021-05-12 12:58:02 +03:00
Nikolay Krasko
818bbbbb83 Don't print to log in successful parcelize tests 2021-05-12 12:58:01 +03:00
Nikolay Krasko
b41fdd2705 Leave a clue about muted tests with directive for manual processing 2021-05-12 12:57:59 +03:00
Mads Ager
2c5a4dcb98 [JVM IR] Fix constant folding to use basic types always.
Fixes KT-46540.
2021-05-12 11:57:20 +02:00
Svyatoslav Scherbina
ad18d5984b Expand comment for unsupported nested generics when exporting to Swift
Add links to Swift and Kotlin issue trackers.
2021-05-12 09:06:28 +00:00
Elena Lepilkina
18462445b7 [K/N][stdlib] Fixed lookaround regexes (KT-45932) 2021-05-12 09:02:24 +00:00
Ilya Goncharov
d7a87a8552 [Gradle, JS] Fixes after rebase 2021-05-12 11:57:14 +03:00
Ilya Goncharov
9412b7236e [Gradle, JS] Refactor cacheBuilder to reuse one instance 2021-05-12 11:57:14 +03:00
Ilya Goncharov
19393948d7 [Gradle, JS] irBuildCache means ir compiler enabled 2021-05-12 11:57:14 +03:00
Ilya Goncharov
b9fc97b44f [Gradle, JS] Add arguments for building caches 2021-05-12 11:57:14 +03:00
Ilya Goncharov
c23376f040 [Gradle, JS] Use associated compilation's caches 2021-05-12 11:57:14 +03:00
Ilya Goncharov
9723d45d27 [Gradle, JS] Add associateWith compilations to CacheBuilder 2021-05-12 11:57:14 +03:00
Ilya Goncharov
194175d2d0 [Gradle, JS] Use multiple arguments for ignoring 2021-05-12 11:57:14 +03:00
Ilya Goncharov
2d3c13f8a2 [Gradle, JS] Everytime run compiler to build caches 2021-05-12 11:57:13 +03:00
Ilya Goncharov
d66d0fd4e4 [Gradle, JS] CacheBuilder before callCompiler 2021-05-12 11:57:13 +03:00
Ilya Goncharov
249fb8393c [Gradle, JS] Add compiler args serialization to consider in caching 2021-05-12 11:57:13 +03:00
Ilya Goncharov
c283c76130 [Gradle, JS] Add CacheBuilder for precache libraries 2021-05-12 11:57:13 +03:00
pyos
420bc6cbe8 JVM_IR: use correct types for generated inline reference wrappers
Doesn't change anything, but still.
2021-05-12 11:37:49 +03:00
pyos
d5d6736e67 PSI2IR/FIR2IR: do not approximate T!! before translation
This leads to weird effects when it's in a contravariant position,
because it's approximated by Nothing.
2021-05-12 11:37:48 +03:00
pyos
a37db99841 JVM_IR: remove a hack from InlineCallableReferenceToLambda
It breaks other things, the same problem is hit by FunctionReference,
and it's the translation layer's fault anyway.

 #KT-46555 Fixed
2021-05-12 11:37:47 +03:00
pyos
cff74b31d4 JVM_IR: get unbound property reference receiver type from KProperty1 2021-05-12 11:37:45 +03:00
Pavel Punegov
53bf0b1c42 Update Build gradle plugin to 0.0.28 2021-05-12 10:34:36 +03:00
Pavel Punegov
540c69ab89 [native] VersionGenerator: fix error string 2021-05-12 10:34:36 +03:00
Pavel Punegov
86041096fd Return milestone property back to support older versions of plugins
Older gradle plugin's NativeCompilerDownloader uses milestone property.
2021-05-12 10:34:36 +03:00
Pavel Punegov
f82c28bd79 Revert "[kotlin-gradle-plugin] workaround for old k/n artifacts"
This reverts commit 5c80dbfd
2021-05-12 10:34:36 +03:00
Pavel Punegov
a0d35e56a9 Revert "[tests][kotlin-gradle-plugin] workaround for old k/n artifacts"
This reverts commit f051119c to drop obsolete native version support
2021-05-12 10:34:35 +03:00
Pavel Punegov
fa525a8359 [native] Support milestones in meta versions
Add milestones to MetaVersion to replace standalone parameter in
compiler version generator. This makes native version match Kotlin one.
2021-05-12 10:34:35 +03:00
Ilmir Usmanov
c4ddf3530d Use GETFIELD instead of unbox-impl inside inline classes
#KT-36783 Fixed
2021-05-12 06:50:06 +00:00
Jinseong Jeon
e5f3091f2c FIR/UAST: commonize KotlinUFile
We can avoid explicit creation of UAnnotation and UImportStatement if we
use languagePlugin as a UAST element factory.
2021-05-11 21:43:02 +02:00
Jinseong Jeon
5dc0b52e38 FIR UAST: fix/test allCommentsInFile in UFile 2021-05-11 21:43:02 +02:00
Jinseong Jeon
03b5c14944 FIR UAST: enable remaining legacy test data
This should have been part of commit 7f627ab4
2021-05-11 21:43:02 +02:00
Tianyu Geng
302e0fa46b FIR IDE: add quickfix AddWhenElseBranchFix 2021-05-11 21:42:45 +02:00
Jinseong Jeon
8e10b5fdec FIR: introduce FirExpressionWithSmartcastToNull
This new kind of expression encompasses the nullability of the original
expression after null check (or equivalent `is Nothing?` check).

Unlike FirExpressionWithSmartcast, this expression won't be materialized
during conversion to backend IR. Also, Nothing? is discarded when
computing the intersection of possible types from smartcast info.
In that way, Nothing? is not used during resolution, while such
smartcast info is stored in it (and the expression kind itself).
2021-05-11 21:28:44 +03:00
Jinseong Jeon
8da183e4f4 FIR DFA: filter out unwanted implcations from processEqNull
^KT-41015 fixed
2021-05-11 21:28:43 +03:00
Xin Wang
b9209962cd CLI: Add documentation for -J argument in kotlinc -help 2021-05-11 19:50:24 +02:00
Dmitriy Novozhilov
1407af6301 [Test] Sort failed exceptions in JUnit5Assertions.assertAll
This is needed to throw FileComparisonFailure first, because idea
  test UI can not show multiple diff windows for multiple assertions
  and shows only first, which is not useful
2021-05-11 20:07:35 +03:00
Dmitriy Novozhilov
2530ae6b3d [Test] Split IR verification and IR dump to different handlers 2021-05-11 20:07:34 +03:00
Dmitriy Novozhilov
c9cd49d34f [Test] Temporary remove test for KT-22379
This is needed because this test breaks IDE when whit file is indexed.
This test will be returned after release of new kotlin plugins for IDEA
2021-05-11 19:45:43 +03:00
Andrey Zinovyev
89f0a790c9 [lombok] Map lombok MODULE to java PackageVisibility
Because that's what lombok does
#KT-46469 Fixed
2021-05-11 19:18:39 +03:00
Andrey Zinovyev
468fc86a3f [lombok] Fix fallback to config for array annotation's parameter
If annotation's parameter is not explicitly defined, it should be
taken from config
#KT-46529 Fixed
2021-05-11 19:18:37 +03:00
Andrey Zinovyev
57d3f98ece [lombok] Config keys are case-insensitive
#KT-46531 Fixed
2021-05-11 19:18:36 +03:00
Alexander Udalov
c898805ac5 CLI: improve path relativization for compiler messages
On Windows, the absolute file for the root of the drive is `"C:\"`,
which differs from the absolute file for any other directory, which
doesn't end with `\`. This resulted in incorrect trimming of the first
character of the path name in `descendantRelativeTo`.

Also, do not use canonicalPath because there is no point in expanding
symbolic links here.

 #KT-40979 Fixed
2021-05-11 18:44:14 +03:00
Alexander Udalov
f63dac26e6 Minor, extract ProgramWithDependencyOnCompiler for tests
Also use ProcessBuilder instead of GeneralCommandLine for simplicity.
2021-05-11 18:44:12 +03:00
Mads Ager
d397efb2bd [JVM IR] Copy attributes for JVM_STATIC_WRAPPERS. 2021-05-11 16:26:04 +02:00
Mads Ager
3db5ba98ad [JVM IR] Do not insert Nothing handling in JvmStatic wrapper.
Fixes KT-46568.
2021-05-11 16:26:04 +02:00
Dmitriy Novozhilov
3532ce7fbc [Parser] Fix OOM in parsing of incorrect string literals
^KT-46455 Fixed
KT-34410
KT-46564
2021-05-11 16:43:29 +03:00
Mikhail Glukhikh
c284eab2dd FIR / FE 1.0: fix exception for lambda with unresolved name
#KT-46515 Fixed
2021-05-11 15:41:06 +03:00
Stanislav Erokhin
eb4bb9554d Add ReplaceInvoke adn ReplaceCallWithUnaryOperator intention support
Surprisingly all test passed
2021-05-11 12:48:18 +02:00
Stanislav Erokhin
85d9e96632 Partially support call with errors
Cases with no candidates or with Ambiguity is not supported yet
2021-05-11 12:48:17 +02:00
Stanislav Erokhin
080a832605 Fix argument mapping for lambda arguments and default arguments
Maybe for other elements ValueArgument itself used as SourceElement
2021-05-11 12:48:17 +02:00
Stanislav Erokhin
335c5a03b6 Add correct equals/hashCode to KtSymbolBasedAbstractTypeConstructor
Previously there were no equals/hashCode implementation.
Because of that subtyping not working properly. That is because in
subtyping we have checks that type constructors are equals

Also toString was added so now it is a bit easier to debug code
involving the KtSymbolBasedAbstractTypeConstructor
2021-05-11 12:48:16 +02:00
Stanislav Erokhin
dc1ce19db9 Extract some logic from AbstractTypeConstructor to reuse it later
In FE10-binding I would like to re-use equal and hashCode mechanics
that was implemented in AbstractTypeConstructor, but I don't need
the supertype implementation, because it already there in FIR
2021-05-11 12:48:16 +02:00
Nikita Bobko
bee8c0bb90 Publish :compiler:test-infrastructure for ide 2021-05-11 12:36:59 +02:00
Vasily Levchenko
c2a46baa77 [build][kotlin-native][test] fix dist dependencies for test targets 2021-05-11 05:47:17 +00:00
Ilmir Usmanov
640d263ae1 Do not unbox nullable Result, since before usage it is coerced
#KT-46505
2021-05-11 05:49:24 +02:00
pyos
656c2496a6 JVM_IR: omit bound receiver in IrExpressionLambdaImpl parameters
and remove a hack intended to replace the missing type conversions this
caused.

 #KT-46505 Fixed
2021-05-11 05:49:20 +02:00
pyos
614d529168 JVM: remove LambdaInfo.invokeMethodDescriptor 2021-05-11 05:49:17 +02:00
Ilya Kirillov
47dc524763 FIR IDE: remove KtUnsubstitutedScope/KtSubstitutedScope as it designed wrong 2021-05-11 01:36:13 +03:00
Ilya Kirillov
90798d8857 FIR IDE: add KDoc for KtScope, choose better names for KtScope members 2021-05-11 01:36:11 +03:00
Ilya Kirillov
f9087a8ab1 FIR IDE: update testdata after changes in symbols 2021-05-11 01:36:10 +03:00
Ilya Kirillov
accc0e3761 FIR IDE: make KtCallableSymbol to be always KtPossiblyExtensionSymbol 2021-05-11 01:36:09 +03:00
Ilya Kirillov
0ba6412f96 FIR IDE: remove KtTypedSymbol interface as all its inheritors are KtCallableSymbol 2021-05-11 01:36:07 +03:00
Jinseong Jeon
bbe5cf0a70 FIR/UAST: clarify what module we should not depend on 2021-05-10 20:23:19 +02:00
Ilya Kirillov
e14848740a FIR IDE: forbid executing write action inside analyse call 2021-05-10 20:44:23 +03:00
Ilya Muradyan
626c1d3b48 [Scripting] Fix repository ID generation for Maven resolver 2021-05-10 19:40:32 +03:00
Ilya Muradyan
7cea639209 chore: fix typo in comment 2021-05-10 19:40:31 +03:00
Dmitry Petrov
ac0aaff611 JVM_IR KT-46562 don't use LambdaMetafactory for Serializable SAMs
TODO support serializable lambdas creation with LambdaMetafactory
2021-05-10 14:54:14 +03:00
Jinseong Jeon
bdfc879f00 FIR checker: report UNINITIALIZED_PARAMETER 2021-05-10 14:26:14 +03:00
Stanislav Erokhin
d2f831b635 Handle exception during intention background computation in tests
Our test infrastructure (in particular, muting mechanics) rely on
thrown exception during doTestFor function call. But if the
exception happened on background thread, then here we'll get only
TimeOutException but the actual exception won't be reported during
doTestFor call. It would be reported later by the common IDEA test
framework and bypass our mute mechanics
2021-05-10 14:04:04 +03:00
Stanislav Erokhin
7ac599520e Add first prototype of BindingContext implementation by FIR
Add ImportMemberIntention intention as a test.
In this commit all failed test were disabled, necessary fixes will be
added in the following commits
2021-05-10 14:04:03 +03:00
Stanislav Erokhin
6919f3dbb5 Move KotlinCacheServiceImpl to plugin-common.xml
This was done to prevent fir plugin from loading FE 1.0 services
2021-05-10 14:04:02 +03:00
Jinseong Jeon
bf85b110da FIR DFA: remove updatedAliasDiff from PersistentFlow
It is no longer used after element-wise join (a5389b06)
2021-05-10 12:16:04 +03:00
Mikhael Bogdanov
cd7841ceed Generate type annotations on class type parameters bounds
#KT-13228
 #KT-46539 Fixed
2021-05-10 12:12:21 +03:00
Mikhael Bogdanov
f574f89f78 Generate class annotation in AbstractAsmLikeInstructionListingTest 2021-05-10 12:12:20 +03:00
Mikhael Bogdanov
40eeee48b6 Extract generation of type parameters annotations and annotation on their bounds into utils 2021-05-10 12:12:19 +03:00
Mikhael Bogdanov
cbe3c66156 Generate function type parameter annotations and type annotations on their bounds into bytecode
Generate type parameter annotation by default for `-Xjvm-target 1.8` and above

 #KT-46539
 #KT-13228
 #KT-46545 Fixed
2021-05-10 12:12:18 +03:00
Mikhael Bogdanov
209ec68591 Make copy for disabled ir tests 2021-05-10 12:12:16 +03:00
Mikhael Bogdanov
5ff4d648f4 Render generic signature in type parameters tests 2021-05-10 12:12:15 +03:00
Mikhael Bogdanov
6182228de8 Render all annotations in type parameters tests 2021-05-10 12:12:14 +03:00
Vladimir Dolzhenko
c98dba6aea Do not set diagnostics callback if it is already set
Relates to #KT-37702
2021-05-10 09:59:16 +02:00
Vladimir Dolzhenko
cf5e6b242b Wrap exception with file details
Relates to #KT-39776
2021-05-07 23:48:12 +02:00
Ilya Muradyan
e9af2849ef Add Kotlin DeprecationLevel into the REPL completion 2021-05-07 19:56:21 +03:00
Mads Ager
6bc4e124fb [JVM_IR] Guard against infinite recursion in JvmIrCodegenFactory.
Fixed KTIJ-11580.
2021-05-07 17:58:49 +02:00
n-p-s
d70b889004 Update declarations to be searchable by their JvmName annotation
Relates to #KT-23653
2021-05-07 17:43:26 +03:00
pyos
36a25353e9 JVM_IR: permit @NoArg if super constructor is already zero-argument
#KT-46537 Fixed
2021-05-07 16:22:30 +02:00
Mikhail Glukhikh
ac9e8f667d Simplify code in Fir2IrConversionScope.returnTarget 2021-05-07 17:06:34 +03:00
Mikhail Glukhikh
05872fc6a8 Support captured types in ConeTypeCompatibilityChecker 2021-05-07 17:06:34 +03:00
Mikhail Glukhikh
df815a64cf FirEqualityCompatibilityChecker: rename file 2021-05-07 17:06:34 +03:00
Mikhail Glukhikh
6a51ddf755 FirEqualityCompatibilityChecker: add exception wrapper 2021-05-07 17:06:34 +03:00
Andrei Klunnyi
b7eded6e48 KT-46146 no 'protected' for final classes
Intention to change final class constructor visibility to 'protected'
was erroneous. This commit removes it.
2021-05-07 12:47:40 +00:00
Andrei Klunnyi
e56a3b3c30 KT-46146 'protected' and 'private' only for sealed constructors
Prior to this commit we suggested two invalid intentions for sealed
class constructors: change visibility to 'public' and 'internal'.

^KT-46146 Fixed
2021-05-07 12:47:39 +00:00
Andrei Klunnyi
686368749a KT-46146 'protected' is unavailable for primary constructors
Prior to this commit intention to change primary constructor visibility
to 'protected' was filtered out.
2021-05-07 12:47:38 +00:00
Alina Dolgikh
7388e60869 Add link to Kotlin 1.5 Event registration
As an experiment, we would like to try promotion in the Github repository.
2021-05-07 14:40:14 +02:00
Ilya Muradyan
042ac5555c Merge pull request #4342 from JetBrains/rr/ileasile/completion-for-function-params
[REPL] Add completion for the call named parameters
2021-05-07 15:11:12 +03:00
Mikhail Glukhikh
27903b4cd6 Configuration fix: make fir2ir tests depend on 'dist' 2021-05-07 10:32:47 +03:00
Alexander Udalov
d306d8a90e JVM IR: cast indy-SAM receiver type from KFunctionN to FunctionN
#KT-46512 Fixed
2021-05-07 00:53:31 +03:00
Ilya Kirillov
124bd559de FIR IDE: fix failing AbstractOverrideImplementTest tests on Windows
Before the System.lineSeparator() was used for splitting KtFile.text into lines.
In IJ all lines has UNIX file endings, so it failed on Windows TC agent
2021-05-07 00:40:52 +03:00
Mikhail Glukhikh
f83841a34f Cleanup FirHelpers (inline / remove / reduce visibility) 2021-05-07 00:40:51 +03:00
Tianyu Geng
9273c6326e FIR IDE: workaround deadlock when resolving class members
When listing members in a class, we need to resolve super types. But if
a super type is defined in another file, this file may not have been
resolved. In this case, listing the members would require resolving the
unresolved file, which can only be done in a write lock.

Before this change, KtFirScopeProvider only acquire the read lock, which
then causes read/write deadlock when the logic tries to further resolve
super types defined in other files. This change makes KtFirScopeProvider
acquire a write lock in the beginning so resolving can happen correctly
later.
2021-05-07 00:40:50 +03:00
Tianyu Geng
7a745cfe5c FIR IDE: Remove unnecessary renderAnnotations option 2021-05-07 00:40:48 +03:00
Tianyu Geng
417c841f77 FIR IDE: Move write actions out of analyze block 2021-05-07 00:40:47 +03:00
Tianyu Geng
e56b39bbd8 FIR IDE: fix typo in package name 2021-05-07 00:40:46 +03:00
Tianyu Geng
d09be811f0 FIR: make class delegation field a fake source
Previously, the FirFieldImpl generated from class delegation has a real
source. This causes troubles in the IDE. This change adds a new fake
source kind for class delegation fields.
2021-05-07 00:40:44 +03:00
Tianyu Geng
0b8b20eda0 FIR IDE: fix KtFirScopeProvider
Currently FIR IDE throws exceptions when enumerating members in this
scope if the class has delegate super types.

java.lang.IllegalStateException: Expected FirResolvedTypeRef with ConeKotlinType but was FirUserTypeRefImpl Tjava.lang.IllegalStateException: java.lang.IllegalStateException: Expected FirResolvedTypeRef with ConeKotlinType but was FirUserTypeRefImpl T
	at org.jetbrains.kotlin.test.KotlinTestUtils.lambda$runTestWithThrowable$3(KotlinTestUtils.java:498)
	at org.jetbrains.kotlin.test.MuteWithDatabaseKt.runTest(muteWithDatabase.kt:96)
	at org.jetbrains.kotlin.test.KotlinTestUtils.runTestWithThrowable(KotlinTestUtils.java:493)
	at org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCaseBase.runTest(KotlinLightCodeInsightFixtureTestCaseBase.java:93)
	at com.intellij.testFramework.UsefulTestCase.defaultRunBare(UsefulTestCase.java:394)
	at com.intellij.testFramework.EdtTestUtil$Companion$runInEdtAndWait$1.invoke(EdtTestUtil.kt:18)
	at com.intellij.testFramework.EdtTestUtil$Companion$runInEdtAndWait$1.invoke(EdtTestUtil.kt:13)
	at com.intellij.testFramework.EdtTestUtilKt$runInEdtAndWait$1.run(EdtTestUtil.kt:50)
	at com.intellij.openapi.application.TransactionGuardImpl$2.run(TransactionGuardImpl.java:201)
	at com.intellij.openapi.application.impl.ApplicationImpl.runIntendedWriteActionOnCurrentThread(ApplicationImpl.java:802)
	at com.intellij.openapi.application.impl.ApplicationImpl.lambda$invokeAndWait$8(ApplicationImpl.java:475)
	at com.intellij.openapi.application.impl.LaterInvocator$1.run(LaterInvocator.java:126)
	at com.intellij.openapi.application.impl.FlushQueue.doRun(FlushQueue.java:84)
	at com.intellij.openapi.application.impl.FlushQueue.runNextEvent(FlushQueue.java:132)
	at com.intellij.openapi.application.impl.FlushQueue.flushNow(FlushQueue.java:47)
	at com.intellij.openapi.application.impl.FlushQueue$FlushNow.run(FlushQueue.java:188)
	at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
	at java.awt.EventQueue.access$500(EventQueue.java:97)
	at java.awt.EventQueue$3.run(EventQueue.java:709)
	at java.awt.EventQueue$3.run(EventQueue.java:703)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
	at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:971)
	at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:841)
	at com.intellij.ide.IdeEventQueue.lambda$dispatchEvent$8(IdeEventQueue.java:452)
	at com.intellij.openapi.progress.impl.CoreProgressManager.computePrioritized(CoreProgressManager.java:744)
	at com.intellij.ide.IdeEventQueue.lambda$dispatchEvent$9(IdeEventQueue.java:451)
	at com.intellij.openapi.application.impl.ApplicationImpl.runIntendedWriteActionOnCurrentThread(ApplicationImpl.java:802)
	at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:499)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: java.lang.IllegalStateException: Expected FirResolvedTypeRef with ConeKotlinType but was FirUserTypeRefImpl T
	at org.jetbrains.kotlin.fir.types.FirTypeUtilsKt.getConeType(FirTypeUtils.kt:33)
	at org.jetbrains.kotlin.fir.scopes.KotlinScopeProviderKt.scopeForSupertype(KotlinScopeProvider.kt:111)
	at org.jetbrains.kotlin.fir.scopes.KotlinScopeProvider.getUseSiteMemberScope(KotlinScopeProvider.kt:42)
	at org.jetbrains.kotlin.fir.scopes.KotlinScopeProviderKt.unsubstitutedScope(KotlinScopeProvider.kt:83)
	at org.jetbrains.kotlin.idea.frontend.api.fir.components.KtFirScopeProvider$getMemberScope$lambda-3$lambda-2$$inlined$withFirForScope$1.invoke(FirRefWithValidityCheck.kt:83)
	at org.jetbrains.kotlin.idea.frontend.api.fir.components.KtFirScopeProvider$getMemberScope$lambda-3$lambda-2$$inlined$withFirForScope$1.invoke(FirRefWithValidityCheck.kt:41)
	at org.jetbrains.kotlin.idea.fir.low.level.api.api.LowLevelFirApiFacadeKt.withFirDeclaration(LowLevelFirApiFacade.kt:209)
	at org.jetbrains.kotlin.idea.frontend.api.fir.components.KtFirScopeProvider.getMemberScope(KtFirScopeProvider.kt:323)
	at org.jetbrains.kotlin.idea.frontend.api.components.KtScopeProviderMixIn$DefaultImpls.getMemberScope(KtScopeProvider.kt:34)
	at org.jetbrains.kotlin.idea.frontend.api.KtAnalysisSession.getMemberScope(KtAnalysisSession.kt:26)
	at org.jetbrains.kotlin.idea.core.overrideImplement.KtOverrideMembersHandler.getOverridableMembers(KtOverrideMembersHandler.kt:54)
	at org.jetbrains.kotlin.idea.core.overrideImplement.KtOverrideMembersHandler.collectMembers(KtOverrideMembersHandler.kt:35)
	at org.jetbrains.kotlin.idea.core.overrideImplement.KtOverrideMembersHandler.collectMembersToGenerate(KtOverrideMembersHandler.kt:28)
	at org.jetbrains.kotlin.idea.codeInsight.AbstractOverrideImplementTest.doMultiOverrideImplement(AbstractOverrideImplementTest.kt:141)
	at org.jetbrains.kotlin.idea.codeInsight.AbstractOverrideImplementTest.doMultiFileTest(AbstractOverrideImplementTest.kt:98)
	at org.jetbrains.kotlin.idea.codeInsight.AbstractOverrideImplementTest.doMultiOverrideFileTest(AbstractOverrideImplementTest.kt:54)
	at org.jetbrains.kotlin.idea.codeInsight.OverrideImplementTest.testDelegatedMembers(OverrideImplementTest.kt:121)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at junit.framework.TestCase.runTest(TestCase.java:176)
	at com.intellij.testFramework.UsefulTestCase.lambda$runTest$9(UsefulTestCase.java:331)
	at com.intellij.openapi.application.impl.ApplicationImpl.invokeAndWait(ApplicationImpl.java:462)
	at com.intellij.openapi.application.impl.ApplicationImpl.invokeAndWait(ApplicationImpl.java:480)
	at com.intellij.testFramework.UsefulTestCase.invokeTestRunnable(UsefulTestCase.java:378)
	at com.intellij.testFramework.UsefulTestCase.runTest(UsefulTestCase.java:350)
	at org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCaseBase.lambda$runTest$0(KotlinLightCodeInsightFixtureTestCaseBase.java:93)
	at org.jetbrains.kotlin.test.KotlinTestUtils.lambda$runTestWithThrowable$3(KotlinTestUtils.java:495)
	... 36 more
.. 112 more
2021-05-07 00:40:42 +03:00
Tianyu Geng
53aafbd7d9 FIR IDE: enable override implement test for FIR 2021-05-07 00:40:41 +03:00
Tianyu Geng
00031c8eb1 FIR IDE: add action to override/implement missing members
This commit adds the following actions:

- quickfix to implement missing members
- quickfix to implement missing members as constructor parameters
- action to implement members (Code - Generate - Implement)
- action to override members (Code - Generate - Override)

The current implementation is still missing some pieces, which will be
addressed in future changes.

- fully qualified names are not shorten
- some Kotlin types are not rendered correctly
2021-05-07 00:40:40 +03:00
Tianyu Geng
34387e228f FIR IDE: extract common logic idea.core.overrideImplement
Also rename OverrideImplementMemberHandler to GenerateMemberHandler to
align with the naming of its member functions.
2021-05-07 00:40:38 +03:00
Tianyu Geng
06ba143afe FIR IDE: quickfix to make class abstract if member not implemented 2021-05-07 00:40:37 +03:00
Alexander Udalov
6e3009b82e JVM IR: generate adapted callable references as synthetic
As well as suspend conversion adapters, which are unsupported by default
right now.

 #KT-46259 Fixed
2021-05-06 22:58:18 +03:00
Leonid Startsev
d60a8f9baa Use correct type in KClassReference
Make sure that writeSelf function remains static
2021-05-06 19:53:21 +00:00
Leonid Startsev
a58f29aa06 Remove unnecessary ignoreIndexTo outside writeSelf
It never worked: descriptor.declaresDefaultValue used by property.isOptional
works only for current module
(since it looks up psi), so we never access default value initializers
outside current module
2021-05-06 19:53:21 +00:00
Leonid Startsev
66f39ca185 Use SerializerFactory interface and generate function
for sealed and abstract serializable classes.

Fixes https://github.com/Kotlin/kotlinx.serialization/issues/1116
Fixes https://github.com/Kotlin/kotlinx.serialization/issues/1078
2021-05-06 19:53:20 +00:00
Jinseong Jeon
ebbef484ad FIR UAST: add utils to clean up identical render/log files 2021-05-06 20:19:29 +02:00
Jinseong Jeon
1385a4690e Revert "UAST Kotlin: update test data"
This reverts commit 291cd842

A directive to ignore FIR UAST is removed after facade support.
2021-05-06 20:19:29 +02:00
Jinseong Jeon
7f627ab480 FIR UAST: track all legacy test data since facade class is converted
These are mostly mechanical changes.
2021-05-06 20:19:29 +02:00
Jinseong Jeon
939740d26e FIR UAST: convert (light) class for facade 2021-05-06 20:19:29 +02:00
Ilya Goncharov
9baa24e626 [Gradle, JS] Fix with beta version of webpack-dev-server to work with webpack 5
^KT-46162 fixed
^KT-46331 fixed
2021-05-06 18:45:45 +03:00
Mads Ager
b6fa28ea81 [JVM_IR] Deal with inline-class arguments in large arity lambdas.
FunctionNVarargBridgeLowering checked the name of the method instead
of whether the method overrides an invoke method. That doesn't work
when the name of the function gets mangled because of inline class
arguments.

Fixed KT-45084.
2021-05-06 17:27:59 +02:00
pyos
1181854bd6 Add a couple more tests for array constructors and references 2021-05-06 18:25:56 +03:00
pyos
a30cfc332d JVM_IR: remove JvmArrayConstructorLowering
ExpressionCodegen already spills the stack before any loop, so it has
no effect.
2021-05-06 18:25:55 +03:00
pyos
9f53d70109 JVM_IR: move ArrayConstructor below function reference phases
This allows taking function references to inline array constructors.

Also, redundant classes are no longer generated when function references
are passed as arguments to the array constructors.

 #KT-46426 Fixed
2021-05-06 18:25:53 +03:00
Mikhail Glukhikh
776920f77d Cleanup code in FirAnnotationArgumentChecker 2021-05-06 17:51:24 +03:00
Mark Punzalan
18f617a582 FIR: Make FirAnnotationArgumentChecker a FirAnnotationCallChecker, to
run on all annotation calls, including those inside type annotations.
2021-05-06 17:51:22 +03:00
Mikhail Glukhikh
87d05bcf83 Fix spec test data after rebase 2021-05-06 17:50:37 +03:00
Mikhail Glukhikh
e451ecf000 Regenerate FIR IDE tests 2021-05-06 17:50:36 +03:00
Mikhail Glukhikh
1936a815e2 ConeTypeCompatibilityChecker: add temporary workaround for KT-46383 2021-05-06 17:50:35 +03:00
Tianyu Geng
db55a973d4 FIR: fix infinite recursion with equality operator checker 2021-05-06 17:50:34 +03:00
Tianyu Geng
d4717569b9 Fix inferred type of FirGetClassCall
The inferred type should be `KClass<out Blah>` for `FirGetClassCall`
invoked on expressions.
2021-05-06 17:50:33 +03:00
Tianyu Geng
7bb81ef157 FIR: add equality call checker
Added checker for FirEqualityOperatorCall. It's surfaced as one of the
following diagnostics depending on the PSI structure and types under
comparison:

* INCOMPATIBLE_TYPES(_WARNING)
* EQUALITY_NOT_APPLICABLE(_WARNING)
* INCOMPATIBLE_ENUM_COMPARISON_ERROR

Comparing with FE1.0, the current implementation is more conservative
and only highlights error if the types are known to follow certain
contracts with `equals` method. Otherwise, the checker reports warnings
instead.

However, the current checker is more strict in the following situations:
1. it now rejects incompatible enum types like `Enum<E1>` and
  `Enum<E2>`, which was previously accepted
2. it now rejects incompatible class types like `Class<String>` and
  `Class<Int>`, which was previously accepted
3. the check now takes smart cast into consideration, so
  `if (x is String) x == 3` is now rejected
2021-05-06 17:50:32 +03:00
Andrey Zinovyev
787c743333 [FIR] Syntax checkers
Introduce base class for checkers that dive into source trees.
2021-05-06 17:38:04 +03:00
Ilya Matveev
1be39cb505 [K/N] Replace thread_local with THREAD_LOCAL_VARIABLE
For some reason using C++'s thread_local modifier
causes crashes during TLS access on runtime initialization
Kotlin dlls on Windows. This patch replaces the thread_local
modifier with __thread which doesn't have this problem
2021-05-06 14:10:22 +00:00
Ilya Matveev
e2e173b92c [K/N][New MM] Disable tests for ObjC interop 2021-05-06 14:10:22 +00:00
Ilya Matveev
4d346d3735 [K/N][New MM] Support thread state switching
Including

* Support thread state switching in codegen
* Introduce and use GCUnsafeCall annotation
* Switch thread state in C++ runtime code

Also

* Register current thread in Mark&Sweep tests
* Store MemoryState in Worker instance
* Set worker tid in WorkerInit
2021-05-06 14:10:21 +00:00
Ilya Matveev
0b46ed3cde [K/N][New MM] Add thread state asserts to reference updates 2021-05-06 14:10:20 +00:00
Ilya Matveev
08688670b1 [K/N] Adjust repository root in K/N's .idea directory 2021-05-06 14:10:19 +00:00
Yahor Berdnikau
c6fc393417 Enable kotlin java toolchain support for kapt task.
With this change 'KaptWithoutKotlincTask' will also support overriding
default Gradle JDK to run kapt. In such case only 'in-process' kapt
 worker isolation mode is supported.

If user does not provide custom JDK, kapt worker isolation mode will
be 'no-isolation' as before.

^KT-45611 In Progress
2021-05-06 16:04:23 +02:00
Mads Ager
afa1b8bfdc [JVM] Extend boxing/unboxing optimizations to coroutine boxing. 2021-05-06 15:35:49 +02:00
Ivan Gavrilovic
4994cb3774 [Gradle] Create kotlinOptions during task init and keep outputFile for js
This is so that existing build scripts using
withType() do not break. Also, fix the failing
test.

It was necessary to keep outputFile for the js compile task
as it was accessed from the build scripts. Instead, a new
property is introduced which uses Gradle lazy properties.
2021-05-06 13:54:18 +03:00
Ivan Gavrilovic
80181c1091 [Gradle] Add Android bootclasspath lazily 2021-05-06 13:54:17 +03:00
Ivan Gavrilovic
1c0d40055e [Gradle] Support getting the sourceSet name from tasks when...
...Gradle property is being used, instead of the direct String
value.
2021-05-06 13:54:16 +03:00
Ivan Gavrilovic
98cc99e36b [Gradle] Fix adding KAPT generated classess to the compilation classes output 2021-05-06 13:54:15 +03:00
Ivan Gavrilovic
f5caa49c31 [Gradle] Use Gradle properties for KAPT tasks
Use lazy properties to configure KAPT tasks and in the model builder.
Also, avoid eager dependency resolution of the kaptExternalClasspath
file collection.
2021-05-06 13:54:14 +03:00
Ivan Gavrilovic
0882da1788 [Gradle] Introduce classes to configure KAPT tasks
Avoid storing references to KotlinCompile task and use lazy properties
to configure task. Values are kept in-sync with the
Kotlin compile task (for the stub generation) using this mechanism.
2021-05-06 13:54:13 +03:00
Ivan Gavrilovic
01dd15cc3e [Gradle] Use task properties to modify task configuration
This change migrates to using properties of KGP tasks and Gradle
built-in tasks. Also, in TaskProvider class, Configurator instances are
created to configure KGP tasks.
2021-05-06 13:54:12 +03:00
Ivan Gavrilovic
ad9f6e63b6 [Gradle] Extract configuration of KotlinJsIrLink to a class
Migrate KotlinJsIrLink to properties create Configurator class
to configure the task properties.
2021-05-06 13:54:11 +03:00
Ivan Gavrilovic
5eed9a4e6e [Gradle] Extract configuration of KotlinCompileCommon to a class
Migrate KotlinCompileCommon to properties create Configurator class
to configure the task properties.
2021-05-06 13:54:10 +03:00
Ivan Gavrilovic
ff27a61252 [Gradle] Use ConfigurableFileCollection for task local state
Use ConfigurableFileCollection so that tasks can simply append to the
file collection and tasks that do not need this, can simply do nothing.
2021-05-06 13:54:09 +03:00
Ivan Gavrilovic
571c9c10d4 [Gradle] Update compile tasks to use properties and clean up code
Update AbstractKotlinCompile, KotlinCompile, and Kotlin2JsCompile to
use Gradle properties, and introduce Configurator classes that are
using configuration-time data to configure task. Also, introduce
TaskConfigurator interface that should be implemented by classes that
are used to configure tasks.
2021-05-06 13:54:08 +03:00
Ivan Gavrilovic
56cad96718 [Gradle] Remove KotlinCompileTaskData
When getting the incremental compilation information use the
task graph which processes all tasks present in it. Tasks have
all information that is needed to get IncrementalModuleInfo for all
compilations.
2021-05-06 13:54:06 +03:00
Ivan Gavrilovic
b3d8187df4 [Gradle] Remove deprecated ways to specify compiler classpath
This change removes options to specify compiler classpath using
deprecated properties that were deprecated for more than 2 years.
2021-05-06 13:54:05 +03:00
Jinseong Jeon
61e21ef6a2 FIR: ensure the absence of FirResolvedTypeRef with erroneous type 2021-05-06 12:22:40 +03:00
Andrey Zinovyev
cba21c68a3 [lombok] Actualize README 2021-05-06 11:27:51 +03:00
Jinseong Jeon
e2dc21da90 FIR checker: warn useless as and is 2021-05-05 18:20:51 +03:00
Jinseong Jeon
19d939c36e TEST: remove redundant diagnostic directive (w/ syntax error) 2021-05-05 18:20:50 +03:00
Mikhail Glukhikh
7ee6597873 FIR: make inference context mandatory in withNullability() etc. 2021-05-05 17:35:50 +03:00
Jinseong Jeon
bb37728e4f FIR: use withNullability with type context whenever possible
It could simplify flexible type cases.
2021-05-05 17:35:48 +03:00
Anton Lakotka
f94ed1a00c Fail only when KotlinPm20ProjectExtension is passed
to buildKotlinProjectStructureMetadata
#Fixes KTIJ-11586
2021-05-05 16:53:20 +03:00
Jinseong Jeon
291cd842b9 UAST Kotlin: update test data
Addition of directive IGNORE_FIR alters synthetic local variable names.
2021-05-05 14:22:40 +02:00
Jinseong Jeon
dad198cb67 UAST Kotlin: make super type lookup test robust
Newly added directive IGNORE_FIR bothers lookup for object "O".
2021-05-05 14:22:40 +02:00
Jinseong Jeon
03d4cb0dfa FIR UAST: use uast-kotlin/testData for legecy tests 2021-05-05 14:22:40 +02:00
Jinseong Jeon
eac875b5d6 FIR UAST: commonize utils from UAST Kotlin 2021-05-05 14:22:40 +02:00
Jinseong Jeon
f37c722c76 UAST Kotlin: fix typos 2021-05-05 14:22:40 +02:00
Jinseong Jeon
40eaabdbb5 FIR UAST: prototype plugin entrypoint, declarations, test infra 2021-05-05 14:22:40 +02:00
Jinseong Jeon
225e3a747c LC: introduce light class interface for facade
so that FIR-based light class for facade can work well in LC utils
2021-05-05 14:11:48 +02:00
Jinseong Jeon
efba90c6f1 LC: rename KtLightClassForFacade to ...Impl
before introducing a common interface for light class for facade

This is a mechanical refactoring.
2021-05-05 14:11:48 +02:00
Alexander Udalov
c14a890e7e IR: fix capturing of type parameters in local functions
collectPotentiallyCapturedTypeParameters no longer stops on the first
class when going through parents. This is needed because otherwise type
parameters of the containing class, and its outer classes, were never
considered "captured", and thus not duplicated/remapped later in
LocalDeclarationsLowering.

This led to the IR where a local function referenced generic type
parameters of the outer class. On JVM, local function is generated into
a private static function in that container class, and static functions
can't use generic type parameters, which crashed some bytecode
processing tools.

Also, add another explicit call to `seeType` to cover references to
generic type parameters in function return types.

 #KT-45941 Fixed
2021-05-04 21:10:56 +02:00
Vasily Levchenko
b389fd6667 [performance][build][kotlin-build-gradle-plugin] version 0.0.27 (fix) 2021-05-04 15:44:19 +00:00
Stanislav Erokhin
d9be05fea8 Support getContainer for the synthetic it value parameter
Also fixed incorrect KtSymbolOrigin:
it was SOURCE instead of SOURCE_MEMBER_GENERATED
2021-05-04 17:25:34 +02:00
Stanislav Erokhin
c24ad0ba51 Use KtFunctionLiteral as key for KtAnonymousFunctionSymbol retrieving
It seems logical to do, because KtFunctionLiteral is KtDeclaration
and KtLambdaExpression is not. Also FirAnonymousFunction use it as
realPsi reference
2021-05-04 14:01:30 +02:00
Dmitriy Dolovov
75d2e415e1 [K/N][IR] Generate missing return statement, p. 2
^KT-42832
2021-05-04 13:26:02 +03:00
Alexander Shabalin
5e456ed82b Put GC implementations into separate modules.
The mm module now compiles separately for each GC implementation.
2021-05-04 10:23:16 +00:00
Ilya Kirillov
41ab97ff1f FIR IDE: introduce single function for checking if declaration can be lazily resolved 2021-05-04 08:19:50 +02:00
Ilya Kirillov
babf079c31 FIR IDE: fix resolving of inner type aliases 2021-05-04 08:19:50 +02:00
Ilya Kirillov
9e1bc5680d FIR IDE: do not consider KtEnumEntry as ktClassOrObject 2021-05-04 08:19:50 +02:00
Ilya Kirillov
ef5f0e77ec FIR IDE: use KtClassLikeDeclaration.classId instead of hacks 2021-05-04 08:19:50 +02:00
Ilya Kirillov
aff807e3af Stubs: bump stubs version 2021-05-04 08:19:50 +02:00
Ilya Kirillov
4942f5eb66 Stubs: add classId to KtTypeAlias stubs 2021-05-04 08:19:50 +02:00
Ilya Kirillov
fdb091d98e Stubs: add classId to KtClassOrObject stubs 2021-05-04 08:19:49 +02:00
Ilya Kirillov
09a94f3200 FIR IDE: ignore non-passing tests in compiler based tests 2021-05-04 08:19:49 +02:00
Ilya Kirillov
3503a54437 FIR IDE: run tests in parallel in module idea-fir-low-level-api 2021-05-04 08:19:49 +02:00
Ilya Kirillov
65ce641b22 FIR IDE: introduce diagnostics tests bases on FIR diagnostics tests 2021-05-04 08:19:49 +02:00
Ilya Muradyan
b771f9eea4 [REPL] Add completion for the call named parameters 2021-05-04 04:40:00 +03:00
Mads Ager
0c77565104 JVM_IR: Add more local variable tests for finally code. 2021-05-03 07:43:38 +02:00
Mads Ager
6095d8a7fa [JVM] Split the variable range for external finally blocks in inliner
When external finally blocks are inlined none of the current locals
are in scope of the finally block.
2021-05-03 07:43:37 +02:00
Mads Ager
6d9f02cfc6 [JVM_IR] Fix range of locals in connection with finally blocks.
For code such as:

```
try {
  var y = "y"
  for (i in 0 until 1) {
    return y
  }
} finally {
  println("finally")
}
```

The local variables `y` and `i` ended up covering the finally block as
well in the debugger.

This change splits the range of the locals so that they do
not cover the finally block.

This change does not change the inliner to do similar transformations,
so the range of locals is still wrong win finally blocks when inlined
into an inline function. Added a failing test to that effect.
2021-05-03 07:43:37 +02:00
Mikhail Glukhikh
0764a0601c Fix FIR IDE test data broken by 80a44986 2021-05-01 19:12:05 +03:00
sebastian.sellmair
a1ed81146e [Commonizer] Logging: NativeDistributionCommonizationCache: Log in level 'quite' on cache misses
^KT-36679 Verification Pending
2021-05-01 14:36:18 +03:00
sebastian.sellmair
b48850c993 [Commonizer] Logging: Implement CommonizerLogLevel and hide verbose output by default
^KT-36679 Fixed
2021-05-01 14:36:18 +03:00
sebastian.sellmair
7349ec8f2f [Commonizer] Logging: Implement ProgressLogger.fork
^KT-36679
2021-05-01 14:36:16 +03:00
sebastian.sellmair
ec440aecf6 [Commonizer] Logging: Remove 'COMMONIZATION' prologue
^KT-36679
2021-05-01 14:36:15 +03:00
sebastian.sellmair
9d9e11d6d8 [Commonizer] Logging: 'Preparing commonized Kotlin/Native libraries': show outputTarget instead of flat list of targets
^KT-36679
2021-05-01 14:36:14 +03:00
sebastian.sellmair
0d9e32f963 [Commonizer] Logging: Show [Step x of y] only when more than one task is scheduled
^KT-36679
2021-05-01 14:36:13 +03:00
Victor Petukhov
9eaec8d919 Use platform-independent line separator in jspecify tests handler 2021-05-01 13:39:28 +03:00
Nikolay Krasko
2a2fa31577 Allow emulate sonatype publishing when publishing to folder (KTI-552) 2021-05-01 01:41:30 +03:00
Nikolay Krasko
624740a80a Force usage of passed deploy url for sonatype publication (KTI-552) 2021-05-01 01:41:28 +03:00
Nikolay Krasko
2eda82f178 Allow in memory signing (KTI-552) 2021-05-01 01:41:27 +03:00
Nikolay Krasko
8f97d8a78e Drop legacy publishing 2021-05-01 01:37:09 +03:00
Mads Ager
df225c0c7f [JVM] Fix uninitialized locals after coroutine transformation.
The coroutine transformation would leave locals in the local
variable table across the code that reloads local variables from
the continuation on reentry. However, when reentering the function
the local has no value until after the reloads from the
continuation.

This change splits the locals in the local variable table to
avoid such uninitialized locals. A local alive across a
suspension point has its range split in two. One that goes
from the original start to the state label for the restart
after the suspension. The other goes from after the local
has been reloaded from the continuation until the previous
end of the local.
2021-04-30 22:24:03 +02:00
Dmitry Petrov
83e3a702c5 JVM_IR KT-46408 properly map fake overrides in method handles 2021-04-30 22:24:02 +03:00
Vasily Levchenko
ef2c2c2c9e [kotlin][tests][compiler/testData/debug/stepping] kt-42208 test added. 2021-04-30 18:44:55 +00:00
Vasily Levchenko
3160fc84fa [kotlin-native][tests] kt-42208 test added. 2021-04-30 18:44:54 +00:00
Vasily Levchenko
a6a7da31c9 [IR][provisional function expression] do generate function reference with offset of call site. 2021-04-30 18:44:54 +00:00
Tianyu Geng
b6bd4ae8e6 FIR: check DELEGATE_SPECIAL_FUNCTION_RETURN_TYPE_MISMATCH 2021-04-30 19:58:50 +03:00
Mikhael Bogdanov
84e67da2af Mute test on JDK 6 2021-04-30 18:24:10 +02:00
Mikhael Bogdanov
95d95f9a9b Put reification markers came from super object signature
#KT-44770 Fixed
  #KT-30696 Open
2021-04-30 17:34:16 +02:00
Sergey Shanshin
8dd307573a Fix IR compilation of external serializers in native 2021-04-30 18:17:08 +03:00
Mikhail Glukhikh
80a449862e FIR: implement diagnostics for qualifier as stand-alone expression case 2021-04-30 17:59:45 +03:00
Mikhail Glukhikh
84ccf7bbb1 FIR: use Java 8 rules in not implemented checker 2021-04-30 17:59:38 +03:00
Mikhail Glukhikh
5de8401494 Reset FirQualifiedNameResolver properly 2021-04-30 17:59:32 +03:00
Victor Petukhov
4fb78fab93 Temporary disable failing jspecify tests on Windows 2021-04-30 17:50:56 +03:00
Victor Petukhov
c9568c0744 Fix FIR tests 2021-04-30 16:49:56 +03:00
Victor Petukhov
7c62e9aecd Introduce warnings reporting by missed constraints because of incorrect optimization in the constraints processor 2021-04-30 15:46:04 +03:00
Victor Petukhov
e110b49cab Revert "Don't stop constraints processing if all type variables have proper equality constraints"
This reverts commit b87c2a15
2021-04-30 15:46:03 +03:00
Andrey Zinovyev
287ff3ed55 [FIR] Fix for AugmentedArraySetCall expression type
Hacky fix so it's type is Unit and not error
2021-04-30 15:25:44 +03:00
Simon Ogorodnik
6365164c21 FIR: Fix gradle integration tests broken by c6fa3634 2021-04-30 15:19:58 +03:00
Sergey Bogolepov
13464cce68 [Native] Adapt Skia interop to ClangArgs refactoring. 2021-04-30 12:07:46 +00:00
Victor Petukhov
f330d67740 Mute foreign annotations tests with compiled java through psi class files reading 2021-04-30 14:43:28 +03:00
Victor Petukhov
78ffefe107 Add jspecify license 2021-04-30 14:43:27 +03:00
Victor Petukhov
909f0d8bdb Implement caching module annotations per class id 2021-04-30 14:43:27 +03:00
Victor Petukhov
2e57ff25ee Leave KotlinCliJavaFileManager::findClass only passing JavaClassFinder.Request 2021-04-30 14:43:27 +03:00
Victor Petukhov
072bba109f Move foreign annotations logic into the corresponding configurator for the tests 2021-04-30 14:43:27 +03:00
Victor Petukhov
e93133a28f Implement jspecify marks processing in the tests properly, by adding specific handler and cleanuper 2021-04-30 14:43:27 +03:00
Victor Petukhov
b9536a25d6 Support type enhancement on freshly supported module level annotations
^KT-45189 Fixed
2021-04-30 14:43:27 +03:00
Victor Petukhov
bc5e92033b Support reading annotations on java 9 module on sources and binaries 2021-04-30 14:43:27 +03:00
Victor Petukhov
24685ee9d6 Add directive ALL_JAVA_AS_BINARIES and use it explicitly for foreign annotations tests with compiled java 2021-04-30 14:43:27 +03:00
Victor Petukhov
89270399db Update some third-party annotations 2021-04-30 14:43:26 +03:00
Victor Petukhov
cdcde634e8 Add basic Java 9 module tests 2021-04-30 14:43:26 +03:00
Victor Petukhov
757fdb2b32 Add Java 9 jspecify annotations including module level ones 2021-04-30 14:43:26 +03:00
Victor Petukhov
71755b7a5e Support java 9 modules in the diagnostic tests both in sources and binaries 2021-04-30 14:43:26 +03:00
Victor Petukhov
1f0616439c Introduce special common directives for tests based on foreign annotation tests 2021-04-30 14:43:26 +03:00
Victor Petukhov
6065f0e2d0 [Jspecify] Move diagnostic tests against compiled java under the new tests infrastructure 2021-04-30 14:43:26 +03:00
Victor Petukhov
8f097b14cc [Jspecify] Move jspecify test runner under the new tests infrastructure 2021-04-30 14:43:26 +03:00
Victor Petukhov
6f9694174f Move foreign annotation tests into diagnostics folder 2021-04-30 14:43:25 +03:00
Victor Petukhov
57bd4d3a98 [Jspecify] Remove Kotlin use sites generator: consider manually picking changes from the jspecify repo 2021-04-30 14:43:25 +03:00
Victor Petukhov
49e838781c Clean-up JavaModuleInfo.kt 2021-04-30 14:43:25 +03:00
Vasily Levchenko
788d3c022a [build][kotlin-build-gradle-plugin] version 0.0.27
- reading konanVersion and konanMetaVersion from project properties
2021-04-30 10:26:36 +00:00
Vasily Levchenko
9cbcafa8d1 [dependencies][kotlin-build-gradle-plugin] version 0.0.27
- reading konanVersion and konanMetaVersion from project properties
2021-04-30 10:26:35 +00:00
Dmitry Petrov
72804d2e8c JVM_IR KT-45779 don't generate intrinsic method refs via invokedynamic 2021-04-30 12:45:11 +03:00
Sergey Bogolepov
f3a935adb9 Support explicit C++ flags in run_konan tool 2021-04-30 08:39:27 +00:00
Sergey Bogolepov
25ebb3fa75 Remove obsolete Gradle native plugin configuration 2021-04-30 08:39:27 +00:00
Sergey Bogolepov
274d18a141 [Kotlin/Native] Add a workaround for Xcode 12.5
SDKs from Xcode 12.5 contain C++ stdlib and it
breaks compilation of C++ parts of compiler.
Mitigate this problem by explicitly specifying
path to C++ stdlib.
2021-04-30 08:39:26 +00:00
Victor Petukhov
8dd71ec5c8 Build recursive raw types and raw types which contain type parameters properly
1) Substitute erasure of other type parameters
2) Use star projection at top level for recursive raw types

^KT-46126 Fixed
2021-04-30 10:49:47 +03:00
Andi Wenger
f9d2ca68ce KJS IR: Fix KT-45738 - Consider recursive checkForPrimitiveOrPattern
Recursive results from checkForPrimitiveOrPattern were ignored. If it found a case/condition that could not be optimized the resulting "false" was not propagated. This would lead to a "optimized" when without all conditions.
- see KT-45738
- The return is now lifted out of the when to make it more obvious what is going on.
- New test for mixed multiple conditions in when
2021-04-29 23:52:01 +03:00
Ilya Kirillov
caff279255 FIR IDE: add missing binary extensions
This also reveals and error in find usages for fir: it does not work for library source files
So, corresponding tests are muted
2021-04-29 23:31:05 +03:00
Andrey Zinovyev
e4a5775570 Remove duplicated code in annotation-based-compiler-plugins-ide-support 2021-04-29 23:14:16 +03:00
Andrey Zinovyev
8afb6d2761 [lombok] Support import from gradle to IDE
Introduce base module for ide compiler plugins
2021-04-29 23:14:15 +03:00
Andrey Zinovyev
b58bea6fa1 [lombok] IDE plugin with maven import handler 2021-04-29 23:14:14 +03:00
Andrey Zinovyev
07daf2165a [lombok] Rename maven subplugin to 'lombok' 2021-04-29 23:14:13 +03:00
Andrey Zinovyev
b88f54b31a [lombok] Add maven plugin integration test with kapt 2021-04-29 23:14:12 +03:00
Andrey Zinovyev
3e883120dd [lombok] Simple maven plugin to enable lombok support 2021-04-29 23:14:11 +03:00
Ivan Kochurkin
7ec709cf46 FIR: fix incorrect reporting of underscores, simplify code, fix test data file 2021-04-29 22:31:39 +03:00
Jinseong Jeon
9b39a8abc2 FIR: avoid wrapping an erroneous type as FirResolvedTypeRef
Instead, use FirErrorTypeRef, a subtype of FirResolvedTypeRef
2021-04-29 22:31:38 +03:00
Alexander Gorshenev
887032667d [Kotlin/Native][Interop] Skia interop plugin for cinterop 2021-04-29 21:43:26 +03:00
Vladimir Ivanov
5f582ad28a [Kotlin/Native][Interop] Provide pure c wrappers over cpp for skia interop 2021-04-29 21:43:25 +03:00
Yahor Berdnikau
61825e9aec Made GradleCompileTaskProvder compative with configuration cache.
After moving compilerRunner() method evaluation into execution phase,
creation of GradleCompileTaskProvider class started to violate
configuration cache.

^KT-45611 In Progress
2021-04-29 20:43:59 +03:00
Yahor Berdnikau
816e955c61 Introduce KotlinJavaToolchain compile tasks input.
This task input provides a way to set different from current Gradle
JDK and use it for Kotlin files compilation. By default it provides
current Gradle JDK.

Provided JDK major version is used as task input, so on providing
different JDK user will see cache miss.

All required interfaces are located inside api module.

^KT-45611 In Progress
2021-04-29 20:43:58 +03:00
Yahor Berdnikau
201b6dfa60 Print path to java executable Kotlin daemon was started with.
Useful for tests to validate toolchain correct behaviour.

^KT-45611 In Progress
2021-04-29 20:43:57 +03:00
Yahor Berdnikau
85456bd6d8 Add helper methods simplifying working with lazy properties from Kotlin.
Just allow to write Kotlin code easier and nicer when using Gradle
lazy properties.

^KT-45611 In Progress
2021-04-29 20:43:55 +03:00
Yahor Berdnikau
007f11e22e Add initial test setup to enable and test Gradle build cache.
This will allow to write JUnit5 tests to verify tasks are re-using
build cache on rebuilding same project from clean state.

^KT-45611 In Progress
2021-04-29 20:43:54 +03:00
Ilya Kirillov
ddf451739b FIR IDE: add member type-alias test for FileStructureTest 2021-04-29 17:51:28 +02:00
Ilya Kirillov
d438d2db40 FIR IDE: do not remove duplicated diagnostics
This hides the real problem why diagnostics are duplicated
2021-04-29 17:51:28 +02:00
Ilya Kirillov
77ae1fa1f2 FIR IDE: run lazy resolve phases in ContextIndependent ResolutionMode 2021-04-29 17:51:28 +02:00
Ilya Kirillov
663c0d975d FIR IDE: add cases for diagnostics traversal test 2021-04-29 17:51:27 +02:00
Ilya Kirillov
602be42b24 FIR IDE: fix lazy resolve for generated synthetic accessors 2021-04-29 17:51:27 +02:00
Nikolay Krasko
66683d2952 Unwrap both parts of light element in KtLightElementBase.isEquivalentTo
Even if origins are same, wrapped light elements are not equivalent.

Revealed by running bunch of JavaAgainstKotlinBinariesCheckerTestGenerated
tests.

com.intellij.testFramework.LoggedErrorProcessor$TestLoggerAssertionError: Non-idempotent computation:
it returns different results when invoked multiple times or on different threads:

  KtLightMethodForDecompiledDeclaration of KtLightClassForDecompiledDeclaration of PsiFile:A.class != KtLightMethodForDecompiledDeclaration of KtLightClassForDecompiledDeclaration of PsiFile:A.class
2021-04-29 18:20:38 +03:00
Andrey Zinovyev
c8a81911c0 [lombok] Add message about experimental status of the plugin 2021-04-29 18:05:27 +03:00
Ivan Gavrilovic
f0199d7277 [Gradle] Simplify Parcelize Gradle plugin
Do not iterate over all configurations, just
add the dependency to the compile and runtime classpath.
2021-04-29 17:26:36 +03:00
Ilmir Usmanov
cb89bd0e13 Generate SuspendFunction marker interface if supertype is suspend
Otherwise, is/as checks will not work.
 #KT-18707
2021-04-29 17:11:31 +03:00
Margarita Bobova
5d296a01c2 Add changelog for 1.4.31 and 1.4.32 2021-04-29 16:13:13 +03:00
Dmitriy Novozhilov
dbaaf081d7 Fix warning in Kotlin/Native build 2021-04-29 16:07:24 +03:00
Dmitriy Novozhilov
df51856e65 Advance bootstrap to 1.5.20-dev-5753 2021-04-29 16:07:22 +03:00
Mikhail Glukhikh
8147a88353 Cleanup: OverrideResolver.kt 2021-04-29 15:24:57 +03:00
Mikhail Glukhikh
cc05d91bda FE 1.0: add deprecation ABSTRACT_CLASS_MEMBER_NOT_IMPLEMENTED_WARNING
#KT-45508 Fixed
2021-04-29 15:24:49 +03:00
Svyatoslav Scherbina
59b5475350 Fix WITH_COROUTINES tests compilation on Native after 5617d83c 2021-04-29 11:16:02 +00:00
Steven Schäfer
84d78035e4 JVM IR: Avoid double mangling of function reference invoke methods 2021-04-29 13:10:43 +02:00
Alexander Udalov
276ffd5a4b JVM IR: fix ::class reference and type mapping for scripts
#KT-46284 Fixed
2021-04-29 00:33:34 +03:00
Alexander Udalov
d10f734594 Fix warnings after making getKotlinPluginVersion non-null
See 4cb6303fa8.
2021-04-29 00:18:07 +03:00
Ilya Kirillov
7149d08995 FIR IDE: resolve supertypes before retrieving them 2021-04-28 22:11:05 +03:00
Ilya Kirillov
cccf9b7d54 FIR IDE: add JVM checkers 2021-04-28 17:57:45 +02:00
Ilya Kirillov
81a7271009 FIR: Decouple AbstractDiagnosticCollectorComponent and AbstractDiagnosticCollector 2021-04-28 17:57:45 +02:00
Nikolay Krasko
e43835c9f5 Bump konanVersion: 1.5.30 2021-04-28 17:58:40 +03:00
Ivan Kochurkin
525cc6df97 [FIR] Implement MANY_LAMBDA_EXPRESSION_ARGUMENTS diagnostics, fix tests 2021-04-28 16:21:48 +03:00
Udi Cohen
b8002cb54f [Kapt] Support dumping processors stats to a file
Using the option -Kapt-dump-processor-timings
2021-04-28 11:48:19 +03:00
sebastian.sellmair
beba85a848 [Commonizer] Calculate 'commonModuleNames' in hierarchical context
^KT-46330 Verification Pending
2021-04-28 02:03:20 +03:00
Nikolay Krasko
f7fdffefd6 Add an explicit dependency on dist for UAST tests 2021-04-27 22:00:18 +03:00
Dmitry Petrov
b34e2c1474 JVM_IR KT-36646 fuze primitive equality with safe call 2021-04-27 19:41:31 +03:00
Dmitry Petrov
72849a3dc3 JVM_IR update test for KT-36637 2021-04-27 19:41:29 +03:00
Dmitry Petrov
bdf914e8d5 JVM_IR use static 'hashCode' for boxed primitives on JVM 1.8+ 2021-04-27 19:41:28 +03:00
Dmitriy Novozhilov
07b15f9de6 [FIR] Support effective visibility with @PublishedApi
#KT-46270 Fixed
2021-04-27 18:39:10 +03:00
Dmitriy Novozhilov
32c3f85679 [FIR] Add inline checker for bodies of inline functions
This checker doesn't support `@PublishedAPI` yet, so some BB tests for it
 were muted. #KT-46270
2021-04-27 18:39:09 +03:00
Dmitriy Novozhilov
7e052c1eb1 [FIR] Fix suppressing diagnostics for some expressions 2021-04-27 18:39:07 +03:00
Dmitriy Novozhilov
2a08923c51 [FIR] Add more utilities for builtin functional types 2021-04-27 18:39:06 +03:00
Dmitriy Novozhilov
8925b8c922 [FIR] Fix leaking mutable map type of resolved argument mapping 2021-04-27 18:39:05 +03:00
Dmitriy Novozhilov
1afb844e1a [FIR] Fix FirExpressionWithSmartcastImpl.acceptChildren 2021-04-27 18:39:03 +03:00
Dmitriy Novozhilov
12331cb10c [FIR] Build resolved declaration status for all non-raw declarations 2021-04-27 18:39:02 +03:00
Ivan Kochurkin
d54808e33f [FIR] Implement CREATING_AN_INSTANCE_OF_ABSTRACT_CLASS diagnostics, fix tests 2021-04-27 18:27:39 +03:00
Alexander Likhachev
f2f2df90aa [Gradle] Prevent early resolve of compiler classpath
#KT-45834 Fixed
2021-04-27 18:21:19 +03:00
Dmitry Petrov
660208740e PSI2IR KT-44013 WA: function interface constructor call accepted by FE 2021-04-27 17:35:37 +03:00
Ivan Kochurkin
704b5a0e13 [FIR] Implement UNDERSCORE_IS_RESERVED, UNDERSCORE_USAGE_WITHOUT_BACKTICKS diagnostics (lighttree) 2021-04-27 17:03:53 +03:00
Ivan Kochurkin
ea2d9f7c0c [FIR] Implement UNDERSCORE_IS_RESERVED, UNDERSCORE_USAGE_WITHOUT_BACKTICKS diagnostics (psi only) 2021-04-27 17:03:52 +03:00
Sergey Bogolepov
cc4adb798f Add cacheable targets for macos_arm64 host. 2021-04-27 13:47:20 +00:00
11047 changed files with 275381 additions and 79492 deletions

3
.gitignore vendored
View File

@@ -12,6 +12,7 @@
/android-studio/sdk
out/
/tmp
kotlin-ide/
workspace.xml
*.versionsBackup
/idea/testData/debugger/tinyApp/classes*
@@ -57,7 +58,7 @@ build/
.idea/artifacts/kotlin_stdlib_wasm_*
.idea/jarRepositories.xml
.idea/csv-plugin.xml
kotlin-ultimate/
.idea/libraries-with-intellij-classes.xml
node_modules/
.rpt2_cache/
libraries/tools/kotlin-test-js-runner/lib/

8
.idea/dictionaries/igor.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<component name="ProjectDictionaryState">
<dictionary name="igor">
<words>
<w>descr</w>
<w>exprs</w>
</words>
</dictionary>
</component>

View File

@@ -11,7 +11,7 @@
<option name="taskNames">
<list>
<option value=":compiler:fir:checkers:generateCheckersComponents" />
<option value=":idea:idea-frontend-fir:generateCode" />
<option value=":idea-frontend-fir:generateCode" />
</list>
</option>
<option name="vmOptions" value="" />

12
.idea/vcs.xml generated
View File

@@ -8,6 +8,18 @@
<inspection_tool class="SubjectLimit" enabled="true" level="WARNING" enabled_by_default="true" />
</profile>
</component>
<component name="GithubSharedProjectSettings">
<option name="branchProtectionPatterns">
<list>
<option value="master" />
<option value="1\.5\.0-M2" />
<option value="1\.5\.0" />
<option value="1\.5\.20" />
<option value="1\.5\.20-M1-release" />
<option value="1\.5\.20-RC-release" />
</list>
</option>
</component>
<component name="IssueNavigationConfiguration">
<option name="links">
<list>

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +1,11 @@
import kotlinx.benchmark.gradle.benchmark
val benchmarks_version = "0.3.0"
val benchmarks_version = "0.3.1"
plugins {
java
kotlin("jvm")
id("org.jetbrains.kotlinx.benchmark") version "0.3.0"
id("org.jetbrains.kotlinx.benchmark") version "0.3.1"
}
dependencies {

View File

@@ -12,6 +12,7 @@ import com.intellij.psi.PsiFileFactory
import com.intellij.psi.impl.PsiFileFactoryImpl
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.testFramework.LightVirtualFile
import org.jetbrains.kotlin.ObsoleteTestInfrastructure
import org.jetbrains.kotlin.asJava.finder.JavaElementFinder
import org.jetbrains.kotlin.builtins.jvm.JvmBuiltIns
import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
@@ -147,6 +148,7 @@ abstract class AbstractSimpleFileBenchmark {
bh.consume(result.shouldGenerateCode)
}
@OptIn(ObsoleteTestInfrastructure::class)
private fun analyzeGreenFileIr(bh: Blackhole) {
val scope = GlobalSearchScope.filesScope(env.project, listOf(file.virtualFile))
.uniteWith(TopDownAnalyzerFacadeForJVM.AllJavaSourcesInProjectScope(env.project))

View File

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

View File

@@ -39,4 +39,4 @@ class GeneratedJvmClass(
}
}
fun File.isModuleMappingFile() = extension == ModuleMapping.MAPPING_FILE_EXT && parentFile.name == "META-INF"
fun File.isModuleMappingFile() = extension == ModuleMapping.MAPPING_FILE_EXT && parentFile.name == "META-INF"

View File

@@ -17,6 +17,7 @@ enum class BuildAttributeKind : Serializable {
enum class BuildAttribute(val kind: BuildAttributeKind) : Serializable {
NO_BUILD_HISTORY(BuildAttributeKind.REBUILD_REASON),
NO_ABI_SNAPSHOT(BuildAttributeKind.REBUILD_REASON),
CACHE_CORRUPTION(BuildAttributeKind.REBUILD_REASON),
UNKNOWN_CHANGES_IN_GRADLE_INPUTS(BuildAttributeKind.REBUILD_REASON),
JAVA_CHANGE_UNTRACKED_FILE_IS_REMOVED(BuildAttributeKind.REBUILD_REASON),

View File

@@ -9,6 +9,7 @@ import java.io.Serializable
@Suppress("Reformat")
enum class BuildTime(val parent: BuildTime? = null) : Serializable {
GRADLE_TASK_ACTION,
GRADLE_TASK,
CLEAR_OUTPUT(GRADLE_TASK),
BACKUP_OUTPUT(GRADLE_TASK),
@@ -20,6 +21,10 @@ enum class BuildTime(val parent: BuildTime? = null) : Serializable {
NON_INCREMENTAL_COMPILATION_OUT_OF_PROCESS(RUN_COMPILER),
NON_INCREMENTAL_COMPILATION_DAEMON(RUN_COMPILER),
INCREMENTAL_COMPILATION(RUN_COMPILER),
STORE_BUILD_INFO(INCREMENTAL_COMPILATION),
JAR_SNAPSHOT(INCREMENTAL_COMPILATION),
SET_UP_ABI_SNAPSHOTS(JAR_SNAPSHOT),
IC_ANALYZE_JAR_FILES(JAR_SNAPSHOT),
IC_CALCULATE_INITIAL_DIRTY_SET(INCREMENTAL_COMPILATION),
IC_ANALYZE_CHANGES_IN_DEPENDENCIES(IC_CALCULATE_INITIAL_DIRTY_SET),
IC_FIND_HISTORY_FILES(IC_ANALYZE_CHANGES_IN_DEPENDENCIES),

View File

@@ -30,6 +30,28 @@ class ChangesCollector {
private val changedMembers = hashMapOf<FqName, MutableSet<String>>()
private val areSubclassesAffected = hashMapOf<FqName, Boolean>()
//TODO for test only: ProtoData or ProtoBuf
private val storage = hashMapOf<FqName, ProtoData>()
private val removed = ArrayList<FqName>()
//TODO change to immutable map
fun protoDataChanges(): Map<FqName, ProtoData> = storage
fun protoDataRemoved(): List<FqName> = removed
companion object {
fun <T> T.getNonPrivateNames(nameResolver: NameResolver, vararg members: T.() -> List<MessageLite>) =
members.flatMap { this.it().filterNot { it.isPrivate }.names(nameResolver) }.toSet()
fun ClassProtoData.getNonPrivateMemberNames(): Set<String> {
return proto.getNonPrivateNames(
nameResolver,
ProtoBuf.Class::getConstructorList,
ProtoBuf.Class::getFunctionList,
ProtoBuf.Class::getPropertyList
) + proto.enumEntryList.map { nameResolver.getString(it.name) }
}
}
fun changes(): List<ChangeInfo> {
val changes = arrayListOf<ChangeInfo>()
@@ -57,7 +79,7 @@ class ChangesCollector {
}
private fun <T, R> MutableMap<T, MutableSet<R>>.getSet(key: T) =
getOrPut(key) { HashSet() }
getOrPut(key) { HashSet() }
private fun collectChangedMember(scope: FqName, name: String) {
changedMembers.getSet(scope).add(name)
@@ -79,11 +101,35 @@ class ChangesCollector {
}
}
fun collectProtoChanges(oldData: ProtoData?, newData: ProtoData?, collectAllMembersForNewClass: Boolean = false) {
fun collectProtoChanges(oldData: ProtoData?, newData: ProtoData?, collectAllMembersForNewClass: Boolean = false, packageProtoKey: String? = null) {
if (oldData == null && newData == null) {
throw IllegalStateException("Old and new value are null")
}
if (newData != null) {
when (newData) {
is ClassProtoData -> {
val fqName = newData.nameResolver.getClassId(newData.proto.fqName).asSingleFqName()
storage[fqName] = newData
}
is PackagePartProtoData -> {
//TODO fqName is not unique. It's package and can be present in both java and kotlin
val fqName = newData.packageFqName
storage[packageProtoKey?.let { FqName(it) } ?: fqName] = newData
}
}
} else {
when (oldData) {
is ClassProtoData -> {
removed.add(oldData.nameResolver.getClassId(oldData.proto.fqName).asSingleFqName())
}
is PackagePartProtoData -> {
//TODO fqName is not unique. It's package and can be present in both java and kotlin
removed.add(packageProtoKey?.let { FqName(it) } ?: oldData.packageFqName)
}
}
}
if (oldData == null) {
newData!!.collectAll(isRemoved = false, isAdded = true, collectAllMembersForNewClass = collectAllMembersForNewClass)
return
@@ -125,8 +171,8 @@ class ChangesCollector {
}
}
private fun <T> T.getNonPrivateNames(nameResolver: NameResolver, vararg members: T.() -> List<MessageLite>): Set<String> =
members.flatMap { this.it().filterNot { it.isPrivate }.names(nameResolver) }.toSet()
fun <T> T.getNonPrivateNames(nameResolver: NameResolver, vararg members: T.() -> List<MessageLite>) =
members.flatMap { this.it().filterNot { it.isPrivate }.names(nameResolver) }.toSet()
//TODO remember all sealed parent classes
private fun ProtoData.collectAll(isRemoved: Boolean, isAdded: Boolean, collectAllMembersForNewClass: Boolean = false) =
@@ -137,16 +183,15 @@ class ChangesCollector {
private fun PackagePartProtoData.collectAllFromPackage(isRemoved: Boolean) {
val memberNames =
proto.getNonPrivateNames(
nameResolver,
ProtoBuf.Package::getFunctionList,
ProtoBuf.Package::getPropertyList
)
proto.getNonPrivateNames(
nameResolver,
ProtoBuf.Package::getFunctionList,
ProtoBuf.Package::getPropertyList
)
if (isRemoved) {
collectRemovedMembers(packageFqName, memberNames)
}
else {
} else {
collectChangedMembers(packageFqName, memberNames)
}
}
@@ -161,8 +206,7 @@ class ChangesCollector {
val collectMember = if (isRemoved) this@ChangesCollector::collectRemovedMember else this@ChangesCollector::collectChangedMember
collectMember(classFqName.parent(), classFqName.shortName().asString())
memberNames.forEach { collectMember(classFqName, it) }
}
else {
} else {
if (!isRemoved && collectAllMembersForNewClass) {
val memberNames = getNonPrivateMemberNames()
memberNames.forEach { this@ChangesCollector.collectChangedMember(classFqName, it) }
@@ -189,15 +233,6 @@ class ChangesCollector {
addChangedParents(fqName, changedParentsFqNames)
}
private fun ClassProtoData.getNonPrivateMemberNames(): Set<String> {
return proto.getNonPrivateNames(
nameResolver,
ProtoBuf.Class::getConstructorList,
ProtoBuf.Class::getFunctionList,
ProtoBuf.Class::getPropertyList
) + proto.enumEntryList.map { nameResolver.getString(it.name) }
}
fun collectMemberIfValueWasChanged(scope: FqName, name: String, oldValue: Any?, newValue: Any?) {
if (oldValue == null && newValue == null) {
throw IllegalStateException("Old and new value are null for $scope#$name")
@@ -205,8 +240,7 @@ class ChangesCollector {
if (oldValue != null && newValue == null) {
collectRemovedMember(scope, name)
}
else if (oldValue != newValue) {
} else if (oldValue != newValue) {
collectChangedMember(scope, name)
}
}

View File

@@ -17,6 +17,7 @@
package org.jetbrains.kotlin.incremental
import com.intellij.util.io.DataExternalizer
import org.jetbrains.kotlin.build.GeneratedFile
import org.jetbrains.kotlin.incremental.js.IncrementalResultsConsumerImpl
import org.jetbrains.kotlin.incremental.js.IrTranslationResultValue
import org.jetbrains.kotlin.incremental.js.TranslationResultValue
@@ -48,6 +49,7 @@ open class IncrementalJsCache(
private const val INLINE_FUNCTIONS = "inline-functions"
private const val HEADER_FILE_NAME = "header.meta"
private const val PACKAGE_META_FILE = "packages-meta"
private const val SOURCE_TO_JS_OUTPUT = "source-to-js-output"
fun hasHeaderFile(cachesDir: File) = File(cachesDir, HEADER_FILE_NAME).exists()
}
@@ -60,6 +62,7 @@ open class IncrementalJsCache(
private val irTranslationResults = registerMap(IrTranslationResultMap(IR_TRANSLATION_RESULT_MAP.storageFile, pathConverter))
private val inlineFunctions = registerMap(InlineFunctionsMap(INLINE_FUNCTIONS.storageFile, pathConverter))
private val packageMetadata = registerMap(PackageMetadataMap(PACKAGE_META_FILE.storageFile))
private val sourceToJsOutputsMap = registerMap(SourceToJsOutputMap(SOURCE_TO_JS_OUTPUT.storageFile, pathConverter))
private val dirtySources = hashSetOf<File>()
@@ -75,6 +78,7 @@ open class IncrementalJsCache(
override fun markDirty(removedAndCompiledSources: Collection<File>) {
removedAndCompiledSources.forEach { sourceFile ->
sourceToJsOutputsMap.remove(sourceFile)
// The common prefix of all FQN parents has to be the file package
sourceToClassesMap[sourceFile].map { it.parentOrNull()?.asString() ?: "" }.minByOrNull { it.length }?.let {
packageMetadata.remove(it)
@@ -95,6 +99,10 @@ open class IncrementalJsCache(
}
}
fun getOutputsBySource(sourceFile: File): Collection<File> {
return sourceToJsOutputsMap.get(sourceFile)
}
fun compareAndUpdate(incrementalResults: IncrementalResultsConsumerImpl, changesCollector: ChangesCollector) {
val translatedFiles = incrementalResults.packageParts
@@ -129,8 +137,8 @@ open class IncrementalJsCache(
}
for ((srcFile, irData) in incrementalResults.irFileData) {
val (fileData, types, signatures, strings, declarations, bodies, fqn) = irData
irTranslationResults.put(srcFile, fileData, types, signatures, strings, declarations, bodies, fqn)
val (fileData, types, signatures, strings, declarations, bodies, fqn, debugInfos) = irData
irTranslationResults.put(srcFile, fileData, types, signatures, strings, declarations, bodies, fqn, debugInfos)
}
}
@@ -175,6 +183,17 @@ open class IncrementalJsCache(
}
}
}
fun updateSourceToOutputMap(
generatedFiles: Iterable<GeneratedFile>,
) {
for (generatedFile in generatedFiles) {
for (source in generatedFile.sourceFiles) {
if (dirtySources.contains(source))
sourceToJsOutputsMap.add(source, generatedFile.outputFile)
}
}
}
}
private object TranslationResultValueExternalizer : DataExternalizer<TranslationResultValue> {
@@ -215,17 +234,20 @@ private class TranslationResultMap(
override fun dumpValue(value: TranslationResultValue): String =
"Metadata: ${value.metadata.md5()}, Binary AST: ${value.binaryAst.md5()}, InlineData: ${value.inlineData.md5()}"
@Synchronized
fun put(sourceFile: File, newMetadata: ByteArray, newBinaryAst: ByteArray, newInlineData: ByteArray) {
storage[pathConverter.toPath(sourceFile)] =
TranslationResultValue(metadata = newMetadata, binaryAst = newBinaryAst, inlineData = newInlineData)
}
@Synchronized
operator fun get(sourceFile: File): TranslationResultValue? =
storage[pathConverter.toPath(sourceFile)]
fun keys(): Collection<File> =
storage.keys.map { pathConverter.toFile(it) }
@Synchronized
fun remove(sourceFile: File, changesCollector: ChangesCollector) {
val path = pathConverter.toPath(sourceFile)
val protoBytes = storage[path]!!.metadata
@@ -247,6 +269,7 @@ private object IrTranslationResultValueExternalizer : DataExternalizer<IrTransla
output.writeArray(value.declarations)
output.writeArray(value.bodies)
output.writeArray(value.fqn)
value.debugInfo?.let { output.writeArray(it) }
}
private fun DataOutput.writeArray(array: ByteArray) {
@@ -261,6 +284,17 @@ private object IrTranslationResultValueExternalizer : DataExternalizer<IrTransla
return filedata
}
private fun DataInput.readArrayOrNull(): ByteArray? {
try {
val dataSize = readInt()
val filedata = ByteArray(dataSize)
readFully(filedata)
return filedata
} catch (e: Throwable) {
return null
}
}
override fun read(input: DataInput): IrTranslationResultValue {
val fileData = input.readArray()
val types = input.readArray()
@@ -269,8 +303,9 @@ private object IrTranslationResultValueExternalizer : DataExternalizer<IrTransla
val declarations = input.readArray()
val bodies = input.readArray()
val fqn = input.readArray()
val debugInfos = input.readArrayOrNull()
return IrTranslationResultValue(fileData, types, signatures, strings, declarations, bodies, fqn)
return IrTranslationResultValue(fileData, types, signatures, strings, declarations, bodies, fqn, debugInfos)
}
}
@@ -295,10 +330,11 @@ private class IrTranslationResultMap(
newStrings: ByteArray,
newDeclarations: ByteArray,
newBodies: ByteArray,
fqn: ByteArray
fqn: ByteArray,
debugInfos: ByteArray?
) {
storage[pathConverter.toPath(sourceFile)] =
IrTranslationResultValue(newFiledata, newTypes, newSignatures, newStrings, newDeclarations, newBodies, fqn)
IrTranslationResultValue(newFiledata, newTypes, newSignatures, newStrings, newDeclarations, newBodies, fqn, debugInfos)
}
operator fun get(sourceFile: File): IrTranslationResultValue? =
@@ -359,6 +395,7 @@ private class InlineFunctionsMap(
storageFile: File,
private val pathConverter: FileToPathConverter
) : BasicStringMap<Map<String, Long>>(storageFile, StringToLongMapExternalizer) {
@Synchronized
fun process(srcFile: File, newMap: Map<String, Long>, changesCollector: ChangesCollector) {
val key = pathConverter.toPath(srcFile)
val oldMap = storage[key] ?: emptyMap()
@@ -376,6 +413,7 @@ private class InlineFunctionsMap(
}
}
@Synchronized
fun remove(sourceFile: File) {
storage.remove(pathConverter.toPath(sourceFile))
}

View File

@@ -185,7 +185,7 @@ open class IncrementalJvmCache(
sourceToClassesMap.add(source, jvmClassName)
val (proto, nameResolver) = serializedJavaClass.toProtoData()
addToClassStorage(proto, nameResolver, source)
// collector.addJavaProto(ClassProtoData(proto, nameResolver))
dirtyOutputClassesMap.notDirty(jvmClassName)
}
@@ -308,7 +308,7 @@ open class IncrementalJvmCache(
storage[key] = newData
val packageFqName = kotlinClass.className.packageFqName
changesCollector.collectProtoChanges(oldData?.toProtoData(packageFqName), newData.toProtoData(packageFqName))
changesCollector.collectProtoChanges(oldData?.toProtoData(packageFqName), newData.toProtoData(packageFqName), packageProtoKey = key)
}
operator fun contains(className: JvmClassName): Boolean =

View File

@@ -12,7 +12,8 @@ data class IncrementalModuleEntry(
private val projectPath: String,
val name: String,
val buildDir: File,
val buildHistoryFile: File
val buildHistoryFile: File,
val abiSnapshot: File
) : Serializable {
companion object {
private const val serialVersionUID = 0L
@@ -26,7 +27,9 @@ class IncrementalModuleInfo(
val nameToModules: Map<String, Set<IncrementalModuleEntry>>,
val jarToClassListFile: Map<File, File>,
// only for js and mpp
val jarToModule: Map<File, IncrementalModuleEntry>
val jarToModule: Map<File, IncrementalModuleEntry>,
//for JVM only
val jarToAbiSnapshot: Map<File, File>
) : Serializable {
companion object {
private const val serialVersionUID = 1L

View File

@@ -41,7 +41,7 @@ open class LookupStorage(
private val countersFile = "counters".storageFile
private val idToFile = registerMap(IdToFileMap("id-to-file".storageFile, pathConverter))
private val fileToId = registerMap(FileToIdMap("file-to-id".storageFile, pathConverter))
private val lookupMap = registerMap(LookupMap("lookups".storageFile))
val lookupMap = registerMap(LookupMap("lookups".storageFile))
@Volatile
private var size: Int = 0

View File

@@ -255,22 +255,23 @@ fun withSubtypes(
typeFqName: FqName,
caches: Iterable<IncrementalCacheCommon>
): Set<FqName> {
val types = LinkedHashSet(listOf(typeFqName))
val subtypes = hashSetOf<FqName>()
val typesToProccess = LinkedHashSet(listOf(typeFqName))
val proccessedTypes = hashSetOf<FqName>()
while (types.isNotEmpty()) {
val iterator = types.iterator()
while (typesToProccess.isNotEmpty()) {
val iterator = typesToProccess.iterator()
val unprocessedType = iterator.next()
iterator.remove()
caches.asSequence()
.flatMap { it.getSubtypesOf(unprocessedType) }
.filter { it !in subtypes }
.forEach { types.add(it) }
.filter { it !in proccessedTypes }
.forEach { typesToProccess.add(it) }
subtypes.add(unprocessedType)
proccessedTypes.add(unprocessedType)
}
return subtypes
return proccessedTypes
}

View File

@@ -47,10 +47,16 @@ abstract class BasicMap<K : Comparable<K>, V>(
storage.flush(memoryCachesOnly)
}
// avoid unsynchronized close
fun close() {
storage.close()
}
@TestOnly
fun closeForTest() {
close()
}
@TestOnly
fun dump(): String {
return with(StringBuilder()) {

View File

@@ -34,7 +34,6 @@ class CachingLazyStorage<K, V>(
) : LazyStorage<K, V> {
private var storage: PersistentHashMap<K, V>? = null
@Synchronized
private fun getStorageIfExists(): PersistentHashMap<K, V>? {
if (storage != null) return storage
@@ -46,32 +45,36 @@ class CachingLazyStorage<K, V>(
return null
}
@Synchronized
private fun getStorageOrCreateNew(): PersistentHashMap<K, V> {
if (storage == null) {
storage = createMap()
}
return storage!!
}
override val keys: Collection<K>
@Synchronized
get() = getStorageIfExists()?.allKeysWithExistingMapping ?: listOf()
@Synchronized
override operator fun contains(key: K): Boolean =
getStorageIfExists()?.containsMapping(key) ?: false
@Synchronized
override operator fun get(key: K): V? =
getStorageIfExists()?.get(key)
@Synchronized
override operator fun set(key: K, value: V) {
getStorageOrCreateNew().put(key, value)
}
@Synchronized
override fun remove(key: K) {
getStorageIfExists()?.remove(key)
}
@Synchronized
override fun append(key: K, value: V) {
getStorageOrCreateNew().appendData(key, { valueExternalizer.save(it, value) })
}
@@ -103,7 +106,11 @@ class CachingLazyStorage<K, V>(
@Synchronized
override fun close() {
storage?.close()
try {
storage?.close()
} finally {
storage = null
}
}
private fun createMap(): PersistentHashMap<K, V> = PersistentHashMap(storageFile, keyDescriptor, valueExternalizer)

View File

@@ -28,6 +28,7 @@ internal open class ClassOneToManyMap(storageFile: File) : BasicStringMap<Collec
storage.append(key.asString(), listOf(value.asString()))
}
@Synchronized
operator fun get(key: FqName): Collection<FqName> =
storage[key.asString()]?.map(::FqName) ?: setOf()

View File

@@ -18,7 +18,7 @@ package org.jetbrains.kotlin.incremental.storage
import java.io.File
internal class LookupMap(storage: File) : BasicMap<LookupSymbolKey, Collection<Int>>(storage, LookupSymbolKeyDescriptor, IntCollectionExternalizer) {
class LookupMap(storage: File) : BasicMap<LookupSymbolKey, Collection<Int>>(storage, LookupSymbolKeyDescriptor, IntCollectionExternalizer) {
override fun dumpKey(key: LookupSymbolKey): String = key.toString()
override fun dumpValue(value: Collection<Int>): String = value.toString()

View File

@@ -31,7 +31,6 @@ class NonCachingLazyStorage<K, V>(
) : LazyStorage<K, V> {
private var storage: PersistentHashMap<K, V>? = null
@Synchronized
private fun getStorageIfExists(): PersistentHashMap<K, V>? {
if (storage != null) return storage
@@ -43,7 +42,6 @@ class NonCachingLazyStorage<K, V>(
return null
}
@Synchronized
private fun getStorageOrCreateNew(): PersistentHashMap<K, V> {
if (storage == null) {
storage = createMap()
@@ -53,22 +51,28 @@ class NonCachingLazyStorage<K, V>(
}
override val keys: Collection<K>
@Synchronized
get() = getStorageIfExists()?.allKeysWithExistingMapping ?: listOf()
@Synchronized
override operator fun contains(key: K): Boolean =
getStorageIfExists()?.containsMapping(key) ?: false
@Synchronized
override operator fun get(key: K): V? =
getStorageIfExists()?.get(key)
@Synchronized
override operator fun set(key: K, value: V) {
getStorageOrCreateNew().put(key, value)
}
@Synchronized
override fun remove(key: K) {
getStorageIfExists()?.remove(key)
}
@Synchronized
override fun append(key: K, value: V) {
getStorageOrCreateNew().appendData(key) { dataOutput -> valueExternalizer.save(dataOutput, value) }
}
@@ -100,7 +104,11 @@ class NonCachingLazyStorage<K, V>(
@Synchronized
override fun close() {
storage?.close()
try {
storage?.close()
} finally {
storage = null
}
}
private fun createMap(): PersistentHashMap<K, V> =

View File

@@ -0,0 +1,43 @@
/*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.incremental.storage
import org.jetbrains.kotlin.incremental.dumpCollection
import java.io.File
class SourceToJsOutputMap(storageFile: File, private val pathConverter: FileToPathConverter) : BasicStringMap<Collection<String>>(storageFile, StringCollectionExternalizer) {
override fun dumpValue(value: Collection<String>): String = value.dumpCollection()
@Synchronized
fun add(key: File, value: File) {
storage.append(pathConverter.toPath(key), listOf(pathConverter.toPath(value)))
}
operator fun get(sourceFile: File): Collection<File> =
storage[pathConverter.toPath(sourceFile)]?.map { pathConverter.toFile(it) } ?: setOf()
@Synchronized
operator fun set(key: File, values: Collection<File>) {
if (values.isEmpty()) {
remove(key)
return
}
storage[pathConverter.toPath(key)] = values.map { pathConverter.toPath(it) }
}
@Synchronized
fun remove(key: File) {
storage.remove(pathConverter.toPath(key))
}
@Synchronized
fun removeValues(key: File, removed: Set<File>) {
val notRemoved = this[key].filter { it !in removed }
this[key] = notRemoved
}
}

View File

@@ -21,23 +21,49 @@ import com.intellij.util.io.DataExternalizer
import com.intellij.util.io.EnumeratorStringDescriptor
import com.intellij.util.io.IOUtil
import com.intellij.util.io.KeyDescriptor
import org.jetbrains.kotlin.cli.common.CompilerSystemProperties
import org.jetbrains.kotlin.cli.common.toBooleanLenient
import java.io.DataInput
import java.io.DataInputStream
import java.io.DataOutput
import java.io.File
import java.util.*
/**
* Storage versioning:
* 0 - only name and value hashes are saved
* 1 - name and scope are saved
*/
object LookupSymbolKeyDescriptor : KeyDescriptor<LookupSymbolKey> {
override fun read(input: DataInput): LookupSymbolKey {
val first = input.readInt()
val second = input.readInt()
return LookupSymbolKey(first, second)
val version = input.readByte()
return when (version.toInt()) {
0 -> {
val name = input.readUTF()
val scope = input.readUTF()
LookupSymbolKey(name.hashCode(), scope.hashCode(), name, scope)
}
1 -> {
val first = input.readInt()
val second = input.readInt()
LookupSymbolKey(first, second, "", "")
}
else -> throw RuntimeException("Unknown version of LookupSymbolKeyDescriptor=${version}")
}
}
private val storeFullFqName = CompilerSystemProperties.COMPILE_INCREMENTAL_WITH_CLASSPATH_SHAPSHOTS.value.toBooleanLenient() ?: false
override fun save(output: DataOutput, value: LookupSymbolKey) {
output.writeInt(value.nameHash)
output.writeInt(value.scopeHash)
if (storeFullFqName) {
output.writeByte(0)
output.writeUTF(value.name)
output.writeUTF(value.scope)
} else {
output.writeByte(1)
output.writeInt(value.nameHash)
output.writeInt(value.scopeHash)
}
}
override fun getHashCode(value: LookupSymbolKey): Int = value.hashCode()

View File

@@ -16,8 +16,8 @@
package org.jetbrains.kotlin.incremental.storage
data class LookupSymbolKey(val nameHash: Int, val scopeHash: Int) : Comparable<LookupSymbolKey> {
constructor(name: String, scope: String) : this(name.hashCode(), scope.hashCode())
data class LookupSymbolKey(val nameHash: Int, val scopeHash: Int, val name:String, val scope:String) : Comparable<LookupSymbolKey> {
constructor(name: String, scope: String) : this(name.hashCode(), scope.hashCode(), name, scope)
override fun compareTo(other: LookupSymbolKey): Int {
val nameCmp = nameHash.compareTo(other.nameHash)
@@ -26,6 +26,26 @@ data class LookupSymbolKey(val nameHash: Int, val scopeHash: Int) : Comparable<L
return scopeHash.compareTo(other.scopeHash)
}
override fun hashCode(): Int {
var result = nameHash
result = 31 * result + scopeHash
return result
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LookupSymbolKey
if (nameHash != other.nameHash) return false
if (scopeHash != other.scopeHash) return false
return true
}
}
data class ProtoMapValue(val isPackageFacade: Boolean, val bytes: ByteArray, val strings: Array<String>)

View File

@@ -14,8 +14,11 @@ buildscript {
if (cacheRedirectorEnabled) {
maven("https://cache-redirector.jetbrains.com/plugins.gradle.org/m2")
maven("https://cache-redirector.jetbrains.com/repo.maven.apache.org/maven2")
} else {
maven("https://plugins.gradle.org/m2")
mavenCentral()
}
}
@@ -27,18 +30,13 @@ buildscript {
dependencies {
bootstrapCompilerClasspath(kotlin("compiler-embeddable", bootstrapKotlinVersion))
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.26")
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.30")
classpath(kotlin("gradle-plugin", bootstrapKotlinVersion))
classpath(kotlin("serialization", bootstrapKotlinVersion))
classpath("org.jetbrains.dokka:dokka-gradle-plugin:0.9.17")
classpath("org.jfrog.buildinfo:build-info-extractor-gradle:4.17.2")
}
}
if (kotlinBuildProperties.buildScanServer != null) {
apply(from = "gradle/buildScanUserData.gradle")
}
plugins {
base
idea
@@ -90,10 +88,8 @@ val distKotlinHomeDir by extra("$distDir/kotlinc")
val distLibDir = "$distKotlinHomeDir/lib"
val commonLocalDataDir = "$rootDir/local"
val ideaSandboxDir = "$commonLocalDataDir/ideaSandbox"
val ideaUltimateSandboxDir = "$commonLocalDataDir/ideaUltimateSandbox"
val artifactsDir = "$distDir/artifacts"
val ideaPluginDir = "$artifactsDir/ideaPlugin/Kotlin"
val ideaUltimatePluginDir = "$artifactsDir/ideaUltimatePlugin/Kotlin"
extra["ktorExcludesForDaemon"] = listOf(
"org.jetbrains.kotlin" to "kotlin-reflect",
@@ -111,9 +107,7 @@ extra["distLibDir"] = project.file(distLibDir)
extra["libsDir"] = project.file(distLibDir)
extra["commonLocalDataDir"] = project.file(commonLocalDataDir)
extra["ideaSandboxDir"] = project.file(ideaSandboxDir)
extra["ideaUltimateSandboxDir"] = project.file(ideaUltimateSandboxDir)
extra["ideaPluginDir"] = project.file(ideaPluginDir)
extra["ideaUltimatePluginDir"] = project.file(ideaUltimatePluginDir)
extra["isSonatypeRelease"] = false
val kotlinNativeVersionObject = project.kotlinNativeVersionValue()
subprojects {
@@ -183,7 +177,7 @@ extra["versions.jflex"] = "1.7.0"
extra["versions.markdown"] = "0.1.25"
extra["versions.trove4j"] = "1.0.20181211"
extra["versions.completion-ranking-kotlin"] = "0.1.3"
extra["versions.r8"] = "2.1.96"
extra["versions.r8"] = "2.2.64"
val immutablesVersion = "0.3.1"
extra["versions.kotlinx-collections-immutable"] = immutablesVersion
extra["versions.kotlinx-collections-immutable-jvm"] = immutablesVersion
@@ -192,10 +186,9 @@ extra["versions.kotlinx-collections-immutable-jvm"] = immutablesVersion
extra["versions.ktor-network"] = "1.0.1"
if (!project.hasProperty("versions.kotlin-native")) {
extra["versions.kotlin-native"] = "1.5.20-dev-5613"
extra["versions.kotlin-native"] = "1.6.0-dev-248"
}
val intellijUltimateEnabled by extra(project.kotlinBuildProperties.intellijUltimateEnabled)
val effectSystemEnabled by extra(project.getBooleanProperty("kotlin.compiler.effectSystemEnabled") ?: false)
val newInferenceEnabled by extra(project.getBooleanProperty("kotlin.compiler.newInferenceEnabled") ?: false)
val useJvmIrBackend by extra(project.kotlinBuildProperties.useIR)
@@ -207,15 +200,11 @@ extra["intellijSeparateSdks"] = intellijSeparateSdks
extra["IntellijCoreDependencies"] =
listOf(
when {
Platform[202].orHigher() -> "asm-all-8.0.1"
else -> "asm-all-7.0.1"
},
"asm-all-8.0.1",
"guava",
"jdom",
"jna",
"log4j",
if (Platform[201].orHigher()) null else "picocontainer",
"snappy-in-java",
"streamex",
"trove4j"
@@ -263,6 +252,7 @@ extra["compilerModules"] = arrayOf(
":compiler:incremental-compilation-impl",
":compiler:compiler.version",
":js:js.ast",
":js:js.sourcemap",
":js:js.serializer",
":js:js.parser",
":js:js.config",
@@ -298,6 +288,7 @@ extra["compilerModules"] = arrayOf(
":compiler:fir:java",
":compiler:fir:jvm",
":compiler:fir:checkers",
":compiler:fir:checkers:checkers.jvm",
":compiler:fir:entrypoint",
":compiler:fir:analysis-tests",
":compiler:fir:analysis-tests:legacy-fir-tests",
@@ -317,7 +308,6 @@ extra["compilerModulesForJps"] = listOf(
":core:compiler.common.jvm",
":core:descriptors",
":core:descriptors.jvm",
":idea:idea-jps-common",
":kotlin-preloader",
":compiler:util",
":compiler:config",
@@ -327,13 +317,54 @@ extra["compilerModulesForJps"] = listOf(
":compiler:compiler.version"
)
extra["compilerArtifactsForIde"] = listOf(
":prepare:ide-plugin-dependencies:android-extensions-compiler-plugin-for-ide",
":prepare:ide-plugin-dependencies:allopen-compiler-plugin-for-ide",
":prepare:ide-plugin-dependencies:incremental-compilation-impl-tests-for-ide",
":prepare:ide-plugin-dependencies:js-ir-runtime-for-ide",
":prepare:ide-plugin-dependencies:kotlin-build-common-tests-for-ide",
":prepare:ide-plugin-dependencies:kotlin-compiler-for-ide",
":prepare:ide-plugin-dependencies:kotlin-compiler-cli-for-ide",
":prepare:ide-plugin-dependencies:kotlin-gradle-statistics-for-ide",
":prepare:ide-plugin-dependencies:kotlinx-serialization-compiler-plugin-for-ide",
":prepare:ide-plugin-dependencies:noarg-compiler-plugin-for-ide",
":prepare:ide-plugin-dependencies:sam-with-receiver-compiler-plugin-for-ide",
":prepare:ide-plugin-dependencies:compiler-components-for-jps",
":prepare:ide-plugin-dependencies:parcelize-compiler-plugin-for-ide",
":prepare:ide-plugin-dependencies:lombok-compiler-plugin-for-ide",
":prepare:ide-plugin-dependencies:kotlin-compiler-tests-for-ide",
":prepare:ide-plugin-dependencies:kotlin-compiler-testdata-for-ide",
":prepare:ide-plugin-dependencies:kotlin-stdlib-minimal-for-test-for-ide",
":prepare:ide-plugin-dependencies:low-level-api-fir-for-ide",
":prepare:ide-plugin-dependencies:high-level-api-for-ide",
":prepare:ide-plugin-dependencies:high-level-api-fir-for-ide",
":prepare:ide-plugin-dependencies:high-level-api-fir-tests-for-ide",
":kotlin-script-runtime",
":kotlin-script-util",
":kotlin-scripting-common",
":kotlin-scripting-jvm",
":kotlin-scripting-compiler",
":kotlin-scripting-compiler-impl",
":kotlin-android-extensions-runtime",
":kotlin-stdlib-common",
":kotlin-stdlib",
":kotlin-stdlib-jdk7",
":kotlin-stdlib-jdk8",
":kotlin-reflect",
":kotlin-main-kts"
)
// TODO: fix remaining warnings and remove this property.
extra["tasksWithWarnings"] = listOf(
":kotlin-stdlib:compileTestKotlin",
":kotlin-stdlib-jdk7:compileTestKotlin",
":kotlin-stdlib-jdk8:compileTestKotlin",
":plugins:uast-kotlin-base:compileKotlin",
":plugins:uast-kotlin-base:compileTestKotlin",
":plugins:uast-kotlin:compileKotlin",
":plugins:uast-kotlin:compileTestKotlin"
":plugins:uast-kotlin:compileTestKotlin",
":plugins:uast-kotlin-fir:compileKotlin",
":plugins:uast-kotlin-fir:compileTestKotlin"
)
val tasksWithWarnings: List<String> by extra
@@ -378,7 +409,7 @@ apply {
}
apply {
if (extra["isSonatypeRelease"] as? Boolean == true) {
if (extra["isDeployStagingRepoGenerationRequired"] as? Boolean == true) {
logger.info("Applying configuration for sonatype release")
from("libraries/prepareSonatypeStaging.gradle")
}
@@ -397,6 +428,29 @@ val defaultJavaHome = jdkPath(if (Platform[203].orHigher()) "11" else defaultJvm
val ignoreTestFailures by extra(project.kotlinBuildProperties.ignoreTestFailures)
allprojects {
val mirrorRepo: String? = findProperty("maven.repository.mirror")?.toString()
repositories {
kotlinBuildLocalRepo(project)
mirrorRepo?.let(::maven)
internalBootstrapRepo?.let(::maven)
bootstrapKotlinRepo?.let(::maven)
maven(protobufRepo)
maven(intellijRepo)
mavenCentral()
maven("https://maven.pkg.jetbrains.space/kotlin/p/kotlin/kotlin-dependencies")
maven("https://dl.google.com/dl/android/maven2")
maven("https://packages.jetbrains.team/maven/p/ij/intellij-dependencies")
jcenter()
}
if (path.startsWith(":kotlin-ide.")) {
return@allprojects
}
configurations.maybeCreate("embedded").apply {
isCanBeConsumed = false
@@ -425,25 +479,6 @@ allprojects {
// therefore it is disabled by default
// buildDir = File(commonBuildDir, project.name)
val mirrorRepo: String? = findProperty("maven.repository.mirror")?.toString()
repositories {
kotlinBuildLocalRepo(project)
mirrorRepo?.let(::maven)
internalBootstrapRepo?.let(::maven)
bootstrapKotlinRepo?.let(::maven)
maven(protobufRepo)
maven(intellijRepo)
mavenCentral()
maven("https://maven.pkg.jetbrains.space/kotlin/p/kotlin/kotlin-dependencies")
maven("https://dl.google.com/dl/android/maven2")
maven("https://packages.jetbrains.team/maven/p/ij/intellij-dependencies")
jcenter()
}
configureJvmProject(javaHome!!, jvmTarget!!)
@@ -476,7 +511,7 @@ allprojects {
useIR = true
}
if (useJvmFir && this@allprojects.name !in projectsWithDisabledFirBootstrap) {
if (useJvmFir && this@allprojects.path !in projectsWithDisabledFirBootstrap) {
freeCompilerArgs += "-Xuse-fir"
freeCompilerArgs += "-Xabi-stability=stable"
}
@@ -519,12 +554,16 @@ allprojects {
outputs.doNotCacheIf("https://youtrack.jetbrains.com/issue/KTI-112") { true }
}
normalization {
runtimeClasspath {
ignore("META-INF/MANIFEST.MF")
ignore("META-INF/compiler.version")
ignore("META-INF/plugin.xml")
ignore("kotlin/KotlinVersionCurrentValue.class")
if (isConfigurationCacheDisabled) {
// Custom input normolization isn't supported by configuration cache at the moment
// See https://github.com/gradle/gradle/issues/13706
normalization {
runtimeClasspath {
ignore("META-INF/MANIFEST.MF")
ignore("META-INF/compiler.version")
ignore("META-INF/plugin.xml")
ignore("kotlin/KotlinVersionCurrentValue.class")
}
}
}
@@ -539,6 +578,8 @@ allprojects {
register("checkBuild")
}
apply(from = "$rootDir/gradle/cacheRedirector.gradle.kts")
afterEvaluate {
if (javaHome != defaultJavaHome || jvmTarget != defaultJvmTarget) {
logger.info("configuring project $name to compile to the target jvm version $jvmTarget using jdk: $javaHome")
@@ -573,7 +614,6 @@ allprojects {
?.exclude("org.jetbrains.kotlin", "kotlin-scripting-compiler-embeddable")
}
apply(from = "$rootDir/gradle/cacheRedirector.gradle.kts")
apply(from = "$rootDir/gradle/testRetry.gradle.kts")
}
}
@@ -736,8 +776,14 @@ tasks {
dependsOn(":kotlin-scripting-jsr223-test:embeddableTest")
dependsOn(":kotlin-main-kts-test:test")
dependsOn(":kotlin-main-kts-test:testWithIr")
dependsOn(":kotlin-scripting-ide-services-test:test")
dependsOn(":kotlin-scripting-ide-services-test:embeddableTest")
if (kotlinBuildProperties.getOrNull("attachedIntellijVersion") == null &&
!kotlinBuildProperties.getBoolean("disableKotlinPluginModules", false)
) {
dependsOn(":kotlin-scripting-ide-services-test:test")
dependsOn(":kotlin-scripting-ide-services-test:embeddableTest")
}
dependsOn(":kotlin-scripting-js-test:test")
}
@@ -781,6 +827,7 @@ tasks {
register("distTest") {
dependsOn("compilerTest")
dependsOn("frontendApiTests")
dependsOn("toolsTest")
dependsOn("gradlePluginTest")
dependsOn("examplesTest")
@@ -842,12 +889,22 @@ tasks {
dependsOn("dist")
dependsOn(
":idea:idea-fir:test",
":idea:idea-frontend-api:test",
":idea:idea-frontend-fir:test",
":idea:idea-frontend-fir:idea-fir-low-level-api:test"
":idea:idea-frontend-fir:fir-low-level-api-ide-impl:test",
":plugins:uast-kotlin-fir:test",
":idea:idea-fir-fe10-binding:test"
)
}
register("frontendApiTests") {
dependsOn("dist")
dependsOn(
":idea-frontend-api:test",
":idea-frontend-fir:test",
":idea-frontend-fir:idea-fir-low-level-api:test"
)
}
register("android-ide-tests") {
dependsOn("dist")
@@ -894,7 +951,6 @@ tasks {
}
}
register("kaptIdeTest") {
dependsOn(":kotlin-annotation-processing:test")
dependsOn(":kotlin-annotation-processing-base:test")
@@ -908,22 +964,6 @@ tasks {
)
}
register("kmmTest", AggregateTest::class) {
dependsOn(
":idea:idea-gradle:test",
":idea:test",
":compiler:test",
":compiler:container:test",
":js:js.tests:test"
)
dependsOn(":kotlin-gradle-plugin-integration-tests:test")
if (Ide.AS40.orHigher())
dependsOn(":kotlin-ultimate:ide:android-studio-native:test")
testPatternFile = file("tests/mpp/kmm-patterns.csv")
}
register("test") {
doLast {
throw GradleException("Don't use directly, use aggregate tasks *-check instead")
@@ -950,32 +990,13 @@ tasks {
register("publishIdeArtifacts") {
idePluginDependency {
dependsOn(
":prepare:ide-plugin-dependencies:android-extensions-compiler-plugin-for-ide:publish",
":prepare:ide-plugin-dependencies:allopen-compiler-plugin-for-ide:publish",
":prepare:ide-plugin-dependencies:incremental-compilation-impl-tests-for-ide:publish",
":prepare:ide-plugin-dependencies:kotlin-build-common-tests-for-ide:publish",
":prepare:ide-plugin-dependencies:kotlin-compiler-for-ide:publish",
":prepare:ide-plugin-dependencies:kotlin-gradle-statistics-for-ide:publish",
":prepare:ide-plugin-dependencies:kotlinx-serialization-compiler-plugin-for-ide:publish",
":prepare:ide-plugin-dependencies:noarg-compiler-plugin-for-ide:publish",
":prepare:ide-plugin-dependencies:sam-with-receiver-compiler-plugin-for-ide:publish",
":prepare:ide-plugin-dependencies:compiler-components-for-jps:publish",
":prepare:ide-plugin-dependencies:parcelize-compiler-plugin-for-ide:publish",
":kotlin-script-runtime:publish",
":kotlin-script-util:publish",
":kotlin-scripting-common:publish",
":kotlin-scripting-jvm:publish",
":kotlin-scripting-compiler:publish",
":kotlin-scripting-compiler-impl:publish",
":kotlin-android-extensions-runtime:publish",
":kotlin-stdlib-common:publish",
":kotlin-stdlib:publish",
":kotlin-stdlib-jdk7:publish",
":kotlin-stdlib-jdk8:publish",
":kotlin-reflect:publish",
":kotlin-main-kts:publish"
)
dependsOn((rootProject.extra["compilerArtifactsForIde"] as List<String>).map { "$it:publish" })
}
}
register("installIdeArtifacts") {
idePluginDependency {
dependsOn((rootProject.extra["compilerArtifactsForIde"] as List<String>).map { "$it:install" })
}
}
}
@@ -1027,8 +1048,7 @@ val zipTestData by task<Zip> {
val zipPlugin by task<Zip> {
val src = when (project.findProperty("pluginArtifactDir") as String?) {
"Kotlin" -> ideaPluginDir
"KotlinUltimate" -> ideaUltimatePluginDir
null -> if (project.hasProperty("ultimate")) ideaUltimatePluginDir else ideaPluginDir
null -> ideaPluginDir
else -> error("Unsupported plugin artifact dir")
}
val destPath = project.findProperty("pluginZipPath") as String?
@@ -1113,7 +1133,7 @@ fun Project.configureJvmProject(javaHome: String, javaVersion: String) {
}
tasks.withType<KotlinCompile> {
kotlinOptions.jdkHome = javaHome
kotlinOptions.jdkHome = javaHome.takeUnless { kotlinBuildProperties.suppressJdkHomeWarning }
kotlinOptions.jvmTarget = javaVersion
kotlinOptions.freeCompilerArgs += "-Xjvm-default=compatibility"
}
@@ -1212,3 +1232,9 @@ if (disableVerificationTasks) {
}
}
}
plugins.withType(org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootPlugin::class) {
extensions.configure(org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootExtension::class.java) {
nodeVersion = "16.2.0"
}
}

View File

@@ -22,7 +22,7 @@ buildscript {
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.26")
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.30")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${project.bootstrapKotlinVersion}")
classpath("org.jetbrains.kotlin:kotlin-sam-with-receiver:${project.bootstrapKotlinVersion}")
}
@@ -69,7 +69,6 @@ rootProject.apply {
}
val isTeamcityBuild = kotlinBuildProperties.isTeamcityBuild
val intellijUltimateEnabled by extra(kotlinBuildProperties.intellijUltimateEnabled)
val intellijSeparateSdks by extra(project.getBooleanProperty("intellijSeparateSdks") ?: false)
extra["intellijReleaseType"] = when {
@@ -144,7 +143,7 @@ java {
dependencies {
implementation(kotlin("stdlib", embeddedKotlinVersion))
implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:${project.bootstrapKotlinVersion}")
implementation("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.26")
implementation("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.30")
implementation("com.gradle.publish:plugin-publish-plugin:0.14.0")
implementation("net.rubygrapefruit:native-platform:${property("versions.native-platform")}")
@@ -159,7 +158,7 @@ dependencies {
implementation("gradle.plugin.org.jetbrains.gradle.plugin.idea-ext:gradle-idea-ext:0.5")
implementation("org.gradle:test-retry-gradle-plugin:1.2.0")
implementation("com.gradle.enterprise:test-distribution-gradle-plugin:1.2.1")
implementation("com.gradle.enterprise:test-distribution-gradle-plugin:2.1")
compileOnly(gradleApi())

View File

@@ -15,30 +15,28 @@ plugins {
base
}
val intellijUltimateEnabled: Boolean by rootProject.extra
val intellijReleaseType: String by rootProject.extra
val intellijVersion = rootProject.extra["versions.intellijSdk"] as String
val intellijVersionForIde = rootProject.intellijSdkVersionForIde()
val asmVersion = rootProject.findProperty("versions.jar.asm-all") as String?
val androidStudioRelease = rootProject.findProperty("versions.androidStudioRelease") as String?
val androidStudioBuild = rootProject.findProperty("versions.androidStudioBuild") as String?
val intellijSeparateSdks: Boolean by rootProject.extra
val installIntellijCommunity = !intellijUltimateEnabled || intellijSeparateSdks
val installIntellijUltimate = intellijUltimateEnabled && androidStudioRelease == null
val intellijVersionDelimiterIndex = intellijVersion.indexOfAny(charArrayOf('.', '-'))
if (intellijVersionDelimiterIndex == -1) {
error("Invalid IDEA version $intellijVersion")
fun checkIntellijVersion(intellijVersion: String) {
val intellijVersionDelimiterIndex = intellijVersion.indexOfAny(charArrayOf('.', '-'))
if (intellijVersionDelimiterIndex == -1) {
error("Invalid IDEA version $intellijVersion")
}
}
checkIntellijVersion(intellijVersion)
intellijVersionForIde?.let { checkIntellijVersion(it) }
val platformBaseVersion = intellijVersion.substring(0, intellijVersionDelimiterIndex)
logger.info("intellijUltimateEnabled: $intellijUltimateEnabled")
logger.info("intellijVersion: $intellijVersion")
logger.info("intellijVersionForIde: $intellijVersionForIde")
logger.info("androidStudioRelease: $androidStudioRelease")
logger.info("androidStudioBuild: $androidStudioBuild")
logger.info("intellijSeparateSdks: $intellijSeparateSdks")
logger.info("installIntellijCommunity: $installIntellijCommunity")
logger.info("installIntellijUltimate: $installIntellijUltimate")
val androidStudioOs by lazy {
when {
@@ -73,11 +71,14 @@ repositories {
}
val intellij by configurations.creating
val intellijUltimate by configurations.creating
val intellijForIde by configurations.creating
val androidStudio by configurations.creating
val sources by configurations.creating
val sourcesForIde by configurations.creating
val jpsStandalone by configurations.creating
val jpsStandaloneForIde by configurations.creating
val intellijCore by configurations.creating
val intellijCoreForIde by configurations.creating
val nodeJSPlugin by configurations.creating
/**
@@ -93,7 +94,6 @@ val dependenciesDir = (findProperty("kotlin.build.dependencies.dir") as String?)
val customDepsRepoDir = dependenciesDir.resolve("repo")
val customDepsOrg: String by rootProject.extra
val customDepsRevision = intellijVersion
val repoDir = File(customDepsRepoDir, customDepsOrg)
dependencies {
@@ -105,12 +105,8 @@ dependencies {
androidStudio("google:android-studio-ide:$androidStudioBuild@$extension")
} else {
if (installIntellijCommunity) {
intellij("com.jetbrains.intellij.idea:ideaIC:$intellijVersion")
}
if (installIntellijUltimate) {
intellijUltimate("com.jetbrains.intellij.idea:ideaIU:$intellijVersion")
}
intellij("com.jetbrains.intellij.idea:ideaIC:$intellijVersion")
intellijVersionForIde?.let { intellijForIde("com.jetbrains.intellij.idea:ideaIC:$it") }
}
if (asmVersion != null) {
@@ -118,102 +114,104 @@ dependencies {
}
sources("com.jetbrains.intellij.idea:ideaIC:$intellijVersion:sources@jar")
intellijVersionForIde?.let { sourcesForIde("com.jetbrains.intellij.idea:ideaIC:$it:sources@jar") }
jpsStandalone("com.jetbrains.intellij.idea:jps-standalone:$intellijVersion")
intellijVersionForIde?.let { jpsStandaloneForIde("com.jetbrains.intellij.idea:jps-standalone:$it") }
intellijCore("com.jetbrains.intellij.idea:intellij-core:$intellijVersion")
if (intellijUltimateEnabled) {
nodeJSPlugin("com.jetbrains.plugins:NodeJS:${rootProject.extra["versions.idea.NodeJS"]}@zip")
}
intellijVersionForIde?.let { intellijCoreForIde("com.jetbrains.intellij.idea:intellij-core:$it") }
}
val makeIntellijCore = buildIvyRepositoryTask(intellijCore, customDepsOrg, customDepsRepoDir)
fun prepareDeps(
intellij: Configuration,
intellijCore: Configuration,
sources: Configuration,
jpsStandalone: Configuration,
intellijVersion: String
) {
val makeIntellijCore = buildIvyRepositoryTask(intellijCore, customDepsOrg, customDepsRepoDir)
val makeIntellijAnnotations by tasks.registering(Copy::class) {
dependsOn(makeIntellijCore)
val makeIntellijAnnotations = tasks.register("makeIntellijAnnotations${intellij.name.capitalize()}", Copy::class) {
dependsOn(makeIntellijCore)
val intellijCoreRepo = CleanableStore[repoDir.resolve("intellij-core").absolutePath][intellijVersion].use()
from(intellijCoreRepo.resolve("artifacts/annotations.jar"))
val intellijCoreRepo = CleanableStore[repoDir.resolve("intellij-core").absolutePath][intellijVersion].use()
from(intellijCoreRepo.resolve("artifacts/annotations.jar"))
val annotationsStore = CleanableStore[repoDir.resolve(intellijRuntimeAnnotations).absolutePath]
val targetDir = annotationsStore[intellijVersion].use()
into(targetDir)
val annotationsStore = CleanableStore[repoDir.resolve(intellijRuntimeAnnotations).absolutePath]
val targetDir = annotationsStore[intellijVersion].use()
into(targetDir)
val ivyFile = File(targetDir, "$intellijRuntimeAnnotations.ivy.xml")
outputs.files(ivyFile)
val ivyFile = File(targetDir, "$intellijRuntimeAnnotations.ivy.xml")
outputs.files(ivyFile)
doFirst {
annotationsStore.cleanStore()
doFirst {
annotationsStore.cleanStore()
}
doLast {
writeIvyXml(
customDepsOrg,
intellijRuntimeAnnotations,
intellijVersion,
intellijRuntimeAnnotations,
targetDir,
targetDir,
targetDir,
allowAnnotations = true
)
}
}
doLast {
writeIvyXml(
val mergeSources = tasks.create("mergeSources${intellij.name.capitalize()}", Jar::class.java) {
dependsOn(sources)
isPreserveFileTimestamps = false
isReproducibleFileOrder = true
isZip64 = true
if (!kotlinBuildProperties.isTeamcityBuild) {
from(provider { sources.map(::zipTree) })
}
destinationDirectory.set(File(repoDir, sources.name))
archiveBaseName.set("intellij")
archiveClassifier.set("sources")
archiveVersion.set(intellijVersion)
}
val sourcesFile = mergeSources.outputs.files.singleFile
val makeIde = if (androidStudioBuild != null) {
buildIvyRepositoryTask(
androidStudio,
customDepsOrg,
intellijRuntimeAnnotations,
intellijVersion,
intellijRuntimeAnnotations,
targetDir,
targetDir,
targetDir,
allowAnnotations = true
customDepsRepoDir,
if (androidStudioOs == "mac")
::skipContentsDirectory
else
::skipToplevelDirectory
)
} else {
val task = buildIvyRepositoryTask(intellij, customDepsOrg, customDepsRepoDir, null, sourcesFile)
task.configure {
dependsOn(mergeSources)
}
task
}
val buildJpsStandalone = buildIvyRepositoryTask(jpsStandalone, customDepsOrg, customDepsRepoDir, null, sourcesFile)
tasks.named("build") {
dependsOn(
makeIntellijCore,
makeIde,
buildJpsStandalone,
makeIntellijAnnotations
)
}
}
val mergeSources by tasks.creating(Jar::class.java) {
dependsOn(sources)
isPreserveFileTimestamps = false
isReproducibleFileOrder = true
isZip64 = true
if (!kotlinBuildProperties.isTeamcityBuild) {
from(provider { sources.map(::zipTree) })
}
destinationDirectory.set(File(repoDir, sources.name))
archiveBaseName.set("intellij")
archiveClassifier.set("sources")
archiveVersion.set(intellijVersion)
}
val sourcesFile = mergeSources.outputs.files.singleFile
val makeIde = if (androidStudioBuild != null) {
buildIvyRepositoryTask(
androidStudio,
customDepsOrg,
customDepsRepoDir,
if (androidStudioOs == "mac")
::skipContentsDirectory
else
::skipToplevelDirectory
)
} else {
val task = if (installIntellijUltimate) {
buildIvyRepositoryTask(intellijUltimate, customDepsOrg, customDepsRepoDir, null, sourcesFile)
} else {
buildIvyRepositoryTask(intellij, customDepsOrg, customDepsRepoDir, null, sourcesFile)
}
task.configure {
dependsOn(mergeSources)
}
task
}
val buildJpsStandalone = buildIvyRepositoryTask(jpsStandalone, customDepsOrg, customDepsRepoDir, null, sourcesFile)
tasks.named("build") {
dependsOn(
makeIntellijCore,
makeIde,
buildJpsStandalone,
makeIntellijAnnotations
)
}
if (installIntellijUltimate) {
val buildNodeJsPlugin =
buildIvyRepositoryTask(nodeJSPlugin, customDepsOrg, customDepsRepoDir, ::skipToplevelDirectory, sourcesFile)
tasks.named("build") { dependsOn(buildNodeJsPlugin) }
prepareDeps(intellij, intellijCore, sources, jpsStandalone, intellijVersion)
if (intellijVersionForIde != null) {
prepareDeps(intellijForIde, intellijCoreForIde, sourcesForIde, jpsStandaloneForIde, intellijVersionForIde)
}
tasks.named<Delete>("clean") {
@@ -400,6 +398,11 @@ fun skipToplevelDirectory(path: String) = path.substringAfter('/')
fun skipContentsDirectory(path: String) = path.substringAfter("Contents/")
fun Project.intellijSdkVersionForIde(): String? {
val majorVersion = kotlinBuildProperties.getOrNull("attachedIntellijVersion") as? String ?: return null
return rootProject.findProperty("versions.intellijSdk.forIde.$majorVersion") as? String
}
class XMLWriter(private val outputStreamWriter: OutputStreamWriter) : Closeable {
private val xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(outputStreamWriter)

View File

@@ -18,55 +18,11 @@ buildscript {
} else {
maven { url "https://maven.pkg.jetbrains.space/kotlin/p/kotlin/kotlin-dependencies" }
}
mavenCentral()
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.26")
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.30")
}
}
def buildProperties = BuildPropertiesKt.getKotlinBuildPropertiesForSettings(settings)
def projectVersions = file("../gradle/versions.properties").text
include "prepare-deps"
def target_AppCode_Clion = buildProperties.includeCidrPlugins && !projectVersions.contains("versions.androidStudioRelease")
def target_AndroidStudio = buildProperties.includeCidrPlugins && projectVersions.contains("versions.androidStudioRelease")
def target_IdeaUltimate = buildProperties.includeUltimate
if (target_AppCode_Clion) {
logger.info("Including modules for AC and CL in buildSrc/settings.gradle")
include ":prepare-deps:kotlin-native-platform-deps"
include ":prepare-deps:native-debug-plugin"
project(":prepare-deps:kotlin-native-platform-deps").projectDir =
file("${buildProperties.propertiesProvider.rootProjectDir}/kotlin-ultimate/buildSrc/prepare-deps/kotlin-native-platform-deps")
project(":prepare-deps:native-debug-plugin").projectDir =
file("${buildProperties.propertiesProvider.rootProjectDir}/kotlin-ultimate/buildSrc/prepare-deps/native-debug-plugin")
} else if (target_AndroidStudio) {
logger.info("Including modules for AS (mobile plugin) in buildSrc/settings.gradle")
include ":prepare-deps:appcode-binaries"
include ":prepare-deps:lldb-framework"
include ":prepare-deps:lldb-frontend"
project(":prepare-deps:appcode-binaries").projectDir =
file("${buildProperties.propertiesProvider.rootProjectDir}/kotlin-ultimate/buildSrc/prepare-deps/appcode-binaries")
project(":prepare-deps:lldb-framework").projectDir =
file("${buildProperties.propertiesProvider.rootProjectDir}/kotlin-ultimate/buildSrc/prepare-deps/lldb-framework")
project(":prepare-deps:lldb-frontend").projectDir =
file("${buildProperties.propertiesProvider.rootProjectDir}/kotlin-ultimate/buildSrc/prepare-deps/lldb-frontend")
} else if (target_IdeaUltimate) {
logger.info("Including modules for IU in buildSrc/settings.gradle")
include ":prepare-deps:lldb-frontend"
include ":prepare-deps:native-debug-plugin"
project(":prepare-deps:lldb-frontend").projectDir =
file("${buildProperties.propertiesProvider.rootProjectDir}/kotlin-ultimate/buildSrc/prepare-deps/lldb-frontend")
project(":prepare-deps:native-debug-plugin").projectDir =
file("${buildProperties.propertiesProvider.rootProjectDir}/kotlin-ultimate/buildSrc/prepare-deps/native-debug-plugin")
} else {
logger.info("Not including extra modules in buildSrc/settings.gradle")
}
include "prepare-deps"

View File

@@ -20,3 +20,5 @@ val KotlinBuildProperties.jarCompression: Boolean get() = getBoolean("kotlin.bui
val KotlinBuildProperties.ignoreTestFailures: Boolean get() = getBoolean("ignoreTestFailures", isTeamcityBuild)
val KotlinBuildProperties.disableWerror: Boolean get() = getBoolean("kotlin.build.disable.werror", false)
val KotlinBuildProperties.suppressJdkHomeWarning: Boolean get() = getBoolean("kotlin.suppress.jdkHome.warning", false)

View File

@@ -81,3 +81,12 @@ fun Task.singleOutputFile(): File = when (this) {
is ProGuardTask -> project.file(outJarFiles.single()!!)
else -> outputs.files.singleFile
}
val Project.isConfigurationCacheDisabled
get() = (gradle.startParameter as? org.gradle.api.internal.StartParameterInternal)?.isConfigurationCache != true
val Project.isIdeaActive
get() = providers.systemProperty("idea.active").forUseAtConfigurationTime().isPresent
val Project.intellijCommunityDir: File
get() = rootDir.resolve("kotlin-ide/intellij/community").takeIf { it.isDirectory } ?: rootDir.resolve("kotlin-ide/intellij")

View File

@@ -26,7 +26,7 @@ fun CompatibilityPredicate.or(other: CompatibilityPredicate): CompatibilityPredi
}
enum class Platform : CompatibilityPredicate {
P183, P191, P192, P193, P201, P202, P203;
P202, P203;
val version: Int = name.drop(1).toInt()
@@ -43,17 +43,9 @@ enum class Platform : CompatibilityPredicate {
}
enum class Ide(val platform: Platform) : CompatibilityPredicate {
IJ191(Platform.P191),
IJ192(Platform.P192),
IJ193(Platform.P193),
IJ201(Platform.P201),
IJ202(Platform.P202),
IJ203(Platform.P203),
AS35(Platform.P183),
AS36(Platform.P192),
AS40(Platform.P193),
AS41(Platform.P201),
AS42(Platform.P202);
val kind = Kind.values().first { it.shortName == name.take(2) }

View File

@@ -1,6 +1,6 @@
@file:Suppress("unused") // usages in build scripts are not tracked properly
import org.gradle.api.GradleException
import com.gradle.publish.PublishTask
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.artifacts.ConfigurablePublishArtifact
@@ -22,12 +22,12 @@ import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.publish.tasks.GenerateModuleMetadata
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.Upload
import org.gradle.api.tasks.javadoc.Javadoc
import org.gradle.jvm.tasks.Jar
import org.gradle.kotlin.dsl.*
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSetContainer
import plugins.KotlinBuildPublishingPlugin
import plugins.mainPublicationName
private const val MAGIC_DO_NOT_CHANGE_TEST_JAR_TASK_NAME = "testJar"
@@ -62,8 +62,6 @@ fun Project.removeArtifacts(configuration: Configuration, task: Task) {
fun Project.noDefaultJar() {
tasks.named("jar").configure {
enabled = false
actions = emptyList()
configurations.forEach { cfg ->
removeArtifacts(cfg, this)
}
@@ -112,6 +110,8 @@ fun <T : Jar> Project.runtimeJar(task: TaskProvider<T>, body: T.() -> Unit = {})
addVariantsFromConfiguration(runtimeJar) { }
}
(components.findByName("java") as AdhocComponentWithVariants?)?.addVariantsFromConfiguration(runtimeJar) { }
return task
}
@@ -225,24 +225,20 @@ fun Project.publish(moduleMetadata: Boolean = false, configure: MavenPublication
val publication = extensions.findByType<PublishingExtension>()
?.publications
?.findByName(KotlinBuildPublishingPlugin.PUBLICATION_NAME) as MavenPublication
?.findByName(mainPublicationName) as MavenPublication
publication.configure()
}
fun Project.publishWithLegacyMavenPlugin(body: Upload.() -> Unit = {}): Upload {
apply<plugins.PublishedKotlinModule>()
if (artifactsRemovedDiagnosticFlag) {
error("`publish()` should be called before removing artifacts typically done in `noDefaultJar()` or `runtimeJar()` call")
}
fun Project.publishGradlePlugin() {
mainPublicationName = "pluginMaven"
publish()
afterEvaluate {
if (configurations.findByName("classes-dirs") != null)
throw GradleException("classesDirsArtifact() is incompatible with publish(), see sources comments for details")
}
return (tasks.getByName("uploadArchives") as Upload).apply {
body()
tasks.withType<PublishTask> {
// Makes plugin publication task reuse poms and metadata from publication named "pluginMaven"
useAutomatedPublishing()
useGradleModuleMetadataIfAvailable()
}
}
}
@@ -253,6 +249,41 @@ fun Project.idePluginDependency(block: () -> Unit) {
}
}
fun Project.publishJarsForIde(projects: List<String>, libraryDependencies: List<String> = emptyList()) {
idePluginDependency {
publishProjectJars(projects, libraryDependencies)
}
configurations.all {
// Don't allow `ideaIC` from compiler to leak into Kotlin plugin modules. Compiler and
// plugin may depend on different versions of IDEA and it will lead to version conflict
exclude(module = ideModuleName())
}
dependencies {
projects.forEach {
jpsLikeJarDependency(project(it), JpsDepScope.COMPILE, { isTransitive = false }, exported = true)
}
libraryDependencies.forEach {
jpsLikeJarDependency(it, JpsDepScope.COMPILE, exported = true)
}
}
}
fun Project.publishTestJarsForIde(projectNames: List<String>) {
idePluginDependency {
publishTestJar(projectNames)
}
configurations.all {
// Don't allow `ideaIC` from compiler to leak into Kotlin plugin modules. Compiler and
// plugin may depend on different versions of IDEA and it will lead to version conflict
exclude(module = ideModuleName())
}
dependencies {
for (projectName in projectNames) {
jpsLikeJarDependency(projectTests(projectName), JpsDepScope.COMPILE, exported = true)
}
}
}
fun Project.publishProjectJars(projects: List<String>, libraryDependencies: List<String> = emptyList()) {
apply<JavaPlugin>()
@@ -291,13 +322,15 @@ fun Project.publishProjectJars(projects: List<String>, libraryDependencies: List
javadocJar()
}
fun Project.publishTestJar(projectName: String) {
fun Project.publishTestJar(projects: List<String>) {
apply<JavaPlugin>()
val fatJarContents by configurations.creating
dependencies {
fatJarContents(project(projectName, configuration = "tests-jar")) { isTransitive = false }
for (projectName in projects) {
fatJarContents(project(projectName, configuration = "tests-jar")) { isTransitive = false }
}
}
publish()
@@ -314,7 +347,7 @@ fun Project.publishTestJar(projectName: String) {
sourcesJar {
from {
project(projectName).testSourceSet.allSource
projects.map { project(it).testSourceSet.allSource }
}
}

View File

@@ -9,13 +9,13 @@
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.ExternalModuleDependency
import org.gradle.api.artifacts.ProjectDependency
import org.gradle.api.artifacts.*
import org.gradle.api.artifacts.dsl.DependencyHandler
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.FileCollection
import org.gradle.kotlin.dsl.accessors.runtime.addDependencyTo
import org.gradle.kotlin.dsl.closureOf
import org.gradle.kotlin.dsl.exclude
import org.gradle.kotlin.dsl.extra
import org.gradle.kotlin.dsl.project
import java.io.File
@@ -34,7 +34,7 @@ val Project.internalBootstrapRepo: String? get() =
when {
bootstrapKotlinRepo?.startsWith("https://buildserver.labs.intellij.net") == true ->
bootstrapKotlinRepo!!.replace("artifacts/content/maven", "artifacts/content/internal/repo")
else -> "https://teamcity.jetbrains.com/guestAuth/app/rest/builds/buildType:(id:Kotlin_KotlinPublic_Compiler),number:$bootstrapKotlinVersion," +
else -> "https://teamcity.jetbrains.com/guestAuth/app/rest/builds/buildType:(id:Kotlin_KotlinPublic_Aggregate),number:$bootstrapKotlinVersion," +
"branch:default:any/artifacts/content/internal/repo/"
}
@@ -89,12 +89,6 @@ fun Project.preloadedDeps(
return files(*matchingFiles.map { it.canonicalPath }.toTypedArray())
}
fun Project.ideaUltimatePreloadedDeps(vararg artifactBaseNames: String, subdir: String? = null): ConfigurableFileCollection {
val ultimateDepsDir = fileFrom(rootDir, "ultimate", "dependencies")
return if (ultimateDepsDir.isDirectory) preloadedDeps(*artifactBaseNames, baseDir = ultimateDepsDir, subdir = subdir)
else files()
}
fun Project.kotlinDep(artifactBaseName: String, version: String, classifier: String? = null): String =
listOfNotNull("org.jetbrains.kotlin:kotlin-$artifactBaseName:$version", classifier).joinToString(":")
@@ -115,6 +109,95 @@ fun DependencyHandler.projectTests(name: String): ProjectDependency = project(na
fun DependencyHandler.projectRuntimeJar(name: String): ProjectDependency = project(name, configuration = "runtimeJar")
fun DependencyHandler.projectArchives(name: String): ProjectDependency = project(name, configuration = "archives")
enum class JpsDepScope {
COMPILE, TEST, RUNTIME, PROVIDED
}
fun DependencyHandler.add(configurationName: String, dependencyNotation: Any, configure: (ModuleDependency.() -> Unit)?) {
// Avoid `dependencyNotation` to `ModuleDependency` class cast exception if possible
if (configure != null) {
add(configurationName, dependencyNotation, closureOf(configure))
} else {
add(configurationName, dependencyNotation)
}
}
fun Project.disableDependencyVerification() {
configurations.all {
resolutionStrategy {
disableDependencyVerification()
}
}
}
fun DependencyHandler.jpsLikeJarDependency(
dependencyNotation: Any,
scope: JpsDepScope,
dependencyConfiguration: (ModuleDependency.() -> Unit)? = null,
exported: Boolean = false
) {
when (scope) {
JpsDepScope.COMPILE -> {
if (exported) {
add("api", dependencyNotation, dependencyConfiguration)
add("testCompile", dependencyNotation, dependencyConfiguration)
} else {
add("implementation", dependencyNotation, dependencyConfiguration)
}
}
JpsDepScope.TEST -> {
if (exported) {
add("testCompile", dependencyNotation, dependencyConfiguration)
} else {
add("testImplementation", dependencyNotation, dependencyConfiguration)
}
}
JpsDepScope.RUNTIME -> {
add("testRuntimeOnly", dependencyNotation, dependencyConfiguration)
}
JpsDepScope.PROVIDED -> {
if (exported) {
add("compileOnlyApi", dependencyNotation, dependencyConfiguration)
add("testCompile", dependencyNotation, dependencyConfiguration)
} else {
add("compileOnly", dependencyNotation, dependencyConfiguration)
add("testImplementation", dependencyNotation, dependencyConfiguration)
}
}
}
}
fun DependencyHandler.jpsLikeModuleDependency(moduleName: String, scope: JpsDepScope, exported: Boolean = false) {
jpsLikeJarDependency(project(moduleName), scope, exported = exported)
when (scope) {
JpsDepScope.COMPILE -> {
if (exported) {
add("testCompile", projectTests(moduleName))
} else {
add("testImplementation", projectTests(moduleName))
}
}
JpsDepScope.TEST -> {
if (exported) {
add("testCompile", projectTests(moduleName))
} else {
add("testImplementation", projectTests(moduleName))
}
}
JpsDepScope.RUNTIME -> {
add("runtimeOnly", projectTests(moduleName))
}
JpsDepScope.PROVIDED -> {
if (exported) {
add("testCompile", projectTests(moduleName))
} else {
add("testImplementation", projectTests(moduleName))
}
}
}
}
fun Project.testApiJUnit5(
vintageEngine: Boolean = false,
runner: Boolean = false,

View File

@@ -93,7 +93,6 @@ fun Project.compilerDummyForDependenciesRewriting(
exclude(packagesToExcludeFromDummy)
body()
}
const val COMPILER_DUMMY_JAR_CONFIGURATION_NAME = "compilerDummyJar"
fun Project.compilerDummyJar(task: TaskProvider<out Jar>, body: Jar.() -> Unit = {}) {

View File

@@ -0,0 +1,51 @@
/*
* Copyright 2010-2021 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.
*/
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm")
}
publishGradlePlugin()
standardPublicJars()
extensions.extraProperties["kotlin.stdlib.default.dependency"] = "false"
dependencies {
compileOnly(kotlinStdlib())
compileOnly(gradleApi())
}
// These dependencies will be provided by Gradle and we should prevent version conflict
fun Configuration.excludeGradleCommonDependencies() {
exclude(group = "org.jetbrains.kotlin", module = "kotlin-stdlib")
exclude(group = "org.jetbrains.kotlin", module = "kotlin-stdlib-jdk7")
exclude(group = "org.jetbrains.kotlin", module = "kotlin-stdlib-jdk8")
exclude(group = "org.jetbrains.kotlin", module = "kotlin-stdlib-common")
exclude(group = "org.jetbrains.kotlin", module = "kotlin-reflect")
exclude(group = "org.jetbrains.kotlin", module = "kotlin-script-runtime")
}
configurations {
"implementation" {
excludeGradleCommonDependencies()
}
"api" {
excludeGradleCommonDependencies()
}
}
tasks.withType<KotlinCompile> {
kotlinOptions.languageVersion = "1.3"
kotlinOptions.apiVersion = "1.3"
kotlinOptions.freeCompilerArgs += listOf(
"-Xskip-prerelease-check",
"-Xskip-runtime-version-check",
"-Xsuppress-version-warnings"
)
}
tasks.named<Jar>("jar") {
callGroovy("manifestAttributes", manifest, project)
}

View File

@@ -117,8 +117,13 @@ fun MutableCollection<JdkId>.discoverJdksOnMacOS(project: Project) {
for (rex in macOsJavaHomeOutRegexes) {
val matchResult = rex.matchEntire(line)
if (matchResult != null) {
addIfBetter(project, matchResult.groupValues[1], matchResult.groupValues[0], File(matchResult.groupValues[3]))
break
val jdkHomeDir = File(matchResult.groupValues[3])
// Filter out JRE installed at /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/
// and shown by the java_home tool
if (!jdkHomeDir.path.contains("JavaAppletPlugin.plugin")) {
addIfBetter(project, matchResult.groupValues[1], matchResult.groupValues[0], jdkHomeDir)
break
}
}
}
}

View File

@@ -35,16 +35,26 @@ private fun Project.kotlinBuildLocalDependenciesDir(): File =
private fun Project.kotlinBuildLocalRepoDir(): File = kotlinBuildLocalDependenciesDir().resolve("repo")
private fun Project.ideModuleName() = when (IdeVersionConfigurator.currentIde.kind) {
fun Project.ideModuleName() = when (IdeVersionConfigurator.currentIde.kind) {
Ide.Kind.AndroidStudio -> "android-studio-ide"
Ide.Kind.IntelliJ -> "ideaIC"
}
private fun Project.ideModuleVersion(forIde: Boolean) = when (IdeVersionConfigurator.currentIde.kind) {
Ide.Kind.AndroidStudio -> rootProject.findProperty("versions.androidStudioBuild")
Ide.Kind.IntelliJ -> {
if (kotlinBuildProperties.intellijUltimateEnabled) "ideaIU" else "ideaIC"
if (forIde) {
intellijSdkVersionForIde()
?: error("Please specify 'attachedIntellijVersion' in your local.properties")
} else {
rootProject.findProperty("versions.intellijSdk")
}
}
}
private fun Project.ideModuleVersion() = when (IdeVersionConfigurator.currentIde.kind) {
Ide.Kind.AndroidStudio -> rootProject.findProperty("versions.androidStudioBuild")
Ide.Kind.IntelliJ -> rootProject.findProperty("versions.intellijSdk")
fun Project.intellijSdkVersionForIde(): String? {
val majorVersion = kotlinBuildProperties.getOrNull("attachedIntellijVersion") as? String ?: return null
return rootProject.findProperty("versions.intellijSdk.forIde.$majorVersion") as? String
}
fun RepositoryHandler.kotlinBuildLocalRepo(project: Project): IvyArtifactRepository = ivy {
@@ -58,6 +68,7 @@ fun RepositoryHandler.kotlinBuildLocalRepo(project: Project): IvyArtifactReposit
artifact("[organisation]/[module]/[revision]/artifacts/lib/[artifact](-[classifier]).[ext]")
artifact("[organisation]/[module]/[revision]/artifacts/[artifact](-[classifier]).[ext]")
artifact("[organisation]/intellij-core/[revision]/artifacts/[artifact](-[classifier]).[ext]")
artifact("[organisation]/${project.ideModuleName()}/[revision]/artifacts/plugins/[module]/lib/[artifact](-[classifier]).[ext]") // bundled plugins
artifact("[organisation]/sources/[artifact]-[revision](-[classifier]).[ext]")
artifact("[organisation]/[module]/[revision]/[artifact](-[classifier]).[ext]")
@@ -68,7 +79,9 @@ fun RepositoryHandler.kotlinBuildLocalRepo(project: Project): IvyArtifactReposit
}
}
fun Project.intellijDep(module: String? = null) = "kotlin.build:${module ?: ideModuleName()}:${ideModuleVersion()}"
@JvmOverloads
fun Project.intellijDep(module: String? = null, forIde: Boolean = false) =
"kotlin.build:${module ?: ideModuleName()}:${ideModuleVersion(forIde)}"
fun Project.intellijCoreDep() = "kotlin.build:intellij-core:${rootProject.extra["versions.intellijSdk"]}"
@@ -93,11 +106,7 @@ fun Project.kotlinxCollectionsImmutable() = "org.jetbrains.kotlinx:kotlinx-colle
*/
fun Project.intellijRuntimeAnnotations() = "kotlin.build:intellij-runtime-annotations:${rootProject.extra["versions.intellijSdk"]}"
fun Project.intellijPluginDep(plugin: String) = intellijDep(plugin)
fun Project.intellijUltimateDep() = intellijDep("ideaIU")
fun Project.intellijUltimatePluginDep(plugin: String) = intellijDep(plugin)
fun Project.intellijPluginDep(plugin: String, forIde: Boolean = false) = intellijDep(plugin, forIde)
fun ModuleDependency.includeJars(vararg names: String, rootProject: Project? = null) {
names.forEach {
@@ -125,7 +134,7 @@ object IntellijRootUtils {
fun getIntellijRootDir(project: Project): File = with(project.rootProject) {
return File(
getRepositoryRootDir(this),
"${ideModuleName()}/${ideModuleVersion()}/artifacts"
"${ideModuleName()}/${ideModuleVersion(forIde = false)}/artifacts"
)
}
}
@@ -137,19 +146,8 @@ fun ModuleDependency.includeIntellijCoreJarDependencies(project: Project, jarsFi
rootProject = project.rootProject
)
fun Project.isIntellijCommunityAvailable() =
!(rootProject.extra["intellijUltimateEnabled"] as Boolean) || rootProject.extra["intellijSeparateSdks"] as Boolean
fun Project.isIntellijUltimateSdkAvailable() = (rootProject.extra["intellijUltimateEnabled"] as Boolean)
fun Project.intellijRootDir() = IntellijRootUtils.getIntellijRootDir(project)
fun Project.intellijUltimateRootDir() =
if (isIntellijUltimateSdkAvailable())
File(kotlinBuildLocalRepoDir(), "kotlin.build/ideaIU/${rootProject.extra["versions.intellijSdk"]}/artifacts")
else
throw GradleException("intellij ultimate SDK is not available")
fun DependencyHandlerScope.excludeInAndroidStudio(rootProject: Project, block: DependencyHandlerScope.() -> Unit) {
if (!rootProject.extra.has("versions.androidStudioRelease")) {
block()
@@ -183,9 +181,7 @@ fun Project.runIdeTask(name: String, ideaPluginDir: File, ideaSandboxDir: File,
"-Dplugin.path=${ideaPluginDir.absolutePath}"
)
if (Platform[201].orHigher() && !isIntellijUltimateSdkAvailable()) {
jvmArgs("-Didea.platform.prefix=Idea")
}
jvmArgs("-Didea.platform.prefix=Idea")
if (rootProject.findProperty("versions.androidStudioRelease") != null) {
jvmArgs("-Didea.platform.prefix=AndroidStudio")

View File

@@ -14,6 +14,7 @@ import org.gradle.api.tasks.bundling.Jar
import org.gradle.kotlin.dsl.*
import plugins.KotlinBuildPublishingPlugin
import plugins.configureRepository
import plugins.mainPublicationName
import java.util.*
internal const val PLUGIN_MARKER_SUFFIX = ".gradle.plugin"
@@ -26,7 +27,7 @@ fun Project.publishPluginMarkers(withEmptyJars: Boolean = true) {
val pluginDevelopment = extensions.getByType<PluginBundleExtension>()
val publishingExtension = extensions.getByType<PublishingExtension>()
val mainPublication = publishingExtension.publications[KotlinBuildPublishingPlugin.PUBLICATION_NAME] as MavenPublication
val mainPublication = publishingExtension.publications[mainPublicationName] as MavenPublication
pluginDevelopment.plugins.forEach { declaration ->
val markerPublication = createMavenMarkerPublication(declaration, mainPublication, publishingExtension.publications)

View File

@@ -68,7 +68,7 @@ class KotlinBuildPublishingPlugin @Inject constructor(
configure<PublishingExtension> {
publications {
create<MavenPublication>(PUBLICATION_NAME) {
create<MavenPublication>(project.mainPublicationName) {
from(kotlinLibraryComponent)
configureKotlinPomAttributes(project)
@@ -79,16 +79,26 @@ class KotlinBuildPublishingPlugin @Inject constructor(
}
companion object {
const val PUBLICATION_NAME = "Main"
const val DEFAULT_MAIN_PUBLICATION_NAME = "Main"
const val MAIN_PUBLICATION_NAME_PROPERTY = "MainPublicationName"
const val REPOSITORY_NAME = "Maven"
const val ADHOC_COMPONENT_NAME = "kotlinLibrary"
const val COMPILE_CONFIGURATION = "publishedCompile"
const val RUNTIME_CONFIGURATION = "publishedRuntime"
}
}
var Project.mainPublicationName: String
get() {
return if (project.extra.has(KotlinBuildPublishingPlugin.MAIN_PUBLICATION_NAME_PROPERTY))
project.extra.get(KotlinBuildPublishingPlugin.MAIN_PUBLICATION_NAME_PROPERTY) as String
else KotlinBuildPublishingPlugin.DEFAULT_MAIN_PUBLICATION_NAME
}
set(value) {
project.extra.set(KotlinBuildPublishingPlugin.MAIN_PUBLICATION_NAME_PROPERTY, value)
}
@OptIn(ExperimentalStdlibApi::class)
private fun humanReadableName(name: String) =
name.split("-").joinToString(separator = " ") { it.capitalize(Locale.ROOT) }
@@ -164,7 +174,17 @@ fun Project.configureDefaultPublishing() {
private fun Project.configureSigning() {
configure<SigningExtension> {
sign(extensions.getByType<PublishingExtension>().publications) // all publications
useGpgCmd()
val signKeyId = project.findProperty("signKeyId") as? String
if (!signKeyId.isNullOrBlank()) {
val signKeyPrivate = project.findProperty("signKeyPrivate") as? String
?: error("Parameter `signKeyPrivate` not found")
val signKeyPassphrase = project.findProperty("signKeyPassphrase") as? String
?: error("Parameter `signKeyPassphrase` not found")
useInMemoryPgpKeys(signKeyId, signKeyPrivate, signKeyPassphrase)
} else {
useGpgCmd()
}
}
}

View File

@@ -1,173 +0,0 @@
@file:Suppress("DEPRECATION")
package plugins
import org.codehaus.groovy.runtime.InvokerHelper
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.maven.Conf2ScopeMappingContainer
import org.gradle.api.artifacts.maven.MavenDeployment
import org.gradle.api.artifacts.maven.MavenResolver
import org.gradle.api.plugins.MavenPluginConvention
import org.gradle.api.plugins.MavenRepositoryHandlerConvention
import org.gradle.api.publication.maven.internal.deployer.MavenRemoteRepository
import org.gradle.api.tasks.Upload
import org.gradle.kotlin.dsl.*
import org.gradle.plugins.signing.Sign
import org.gradle.plugins.signing.SigningExtension
import kotlin.properties.Delegates
/**
* Configures a Kotlin module for publication.
*/
open class PublishedKotlinModule : Plugin<Project> {
private fun String.toBooleanOrNull() = listOf(true, false).firstOrNull { it.toString().equals(this, ignoreCase = true) }
override fun apply(project: Project) {
project.run {
plugins.apply("maven")
configurations.maybeCreate("publishedRuntime").apply {
the<MavenPluginConvention>()
.conf2ScopeMappings
.addMapping(0, this, Conf2ScopeMappingContainer.RUNTIME)
}
configurations.maybeCreate("publishedCompile").apply {
the<MavenPluginConvention>()
.conf2ScopeMappings
.addMapping(0, this, Conf2ScopeMappingContainer.COMPILE)
}
if (!project.hasProperty("prebuiltJar")) {
plugins.apply("signing")
val signingRequired = project.findProperty("signingRequired")?.toString()?.toBooleanOrNull()
?: project.property("isSonatypeRelease") as Boolean
configure<SigningExtension> {
isRequired = signingRequired
sign(configurations["archives"])
useGpgCmd()
}
tasks.named<Sign>("signArchives").configure {
enabled = signingRequired
}
}
fun MavenResolver.configurePom() {
pom.project {
withGroovyBuilder {
"licenses" {
"license" {
"name"("The Apache Software License, Version 2.0")
"url"("http://www.apache.org/licenses/LICENSE-2.0.txt")
"distribution"("repo")
}
}
"name"("${project.group}:${project.name}")
"packaging"("jar")
// optionally artifactId can be defined here
"description"(project.description)
"url"("https://kotlinlang.org/")
"licenses" {
"license" {
"name"("The Apache License, Version 2.0")
"url"("http://www.apache.org/licenses/LICENSE-2.0.txt")
}
}
"scm" {
"url"("https://github.com/JetBrains/kotlin")
"connection"("scm:git:https://github.com/JetBrains/kotlin.git")
"developerConnection"("scm:git:https://github.com/JetBrains/kotlin.git")
}
"developers" {
"developer" {
"name"("Kotlin Team")
setProperty("organization", "JetBrains")
"organizationUrl"("https://www.jetbrains.com")
}
}
}
}
pom.whenConfigured {
dependencies.removeIf {
InvokerHelper.getMetaClass(it).getProperty(it, "scope") == "test"
}
dependencies
.find {
InvokerHelper.getMetaClass(it).getProperty(it, "groupId") == "org.jetbrains.kotlin"
&& InvokerHelper.getMetaClass(it).getProperty(it, "artifactId") == "kotlin-stdlib"
}
?.also {
InvokerHelper.getMetaClass(it).setProperty(it, "exclusions", emptyList<Any>())
logger.warn("WARNING! Removed exclusions from kotlin-stdlib dependency of ${this.artifactId} artifact's maven metadata, check kotlin-stdlib dependency of ${project.path} project")
}
}
}
tasks.named<Upload>("uploadArchives").configure {
val preparePublication = project.rootProject.tasks.named("preparePublication").get()
dependsOn(preparePublication)
val username: String? by preparePublication.extra
val password: String? by preparePublication.extra
val repoUrl: String by preparePublication.extra
var repository by Delegates.notNull<MavenRemoteRepository>()
repositories {
withConvention(MavenRepositoryHandlerConvention::class) {
mavenDeployer {
withGroovyBuilder {
"beforeDeployment" {
val signing = project.the<SigningExtension>()
if (signing.isRequired)
signing.signPom(delegate as MavenDeployment)
}
"repository"("url" to repoUrl)!!.also { repository = it as MavenRemoteRepository }.withGroovyBuilder {
if (username != null && password != null) {
"authentication"("userName" to username, "password" to password)
}
}
}
configurePom()
}
}
}
doFirst {
repository.url = repoUrl
}
}
val install = if (tasks.names.contains("install")) tasks.getByName("install") as Upload
else tasks.create("install", Upload::class.java)
install.apply {
configuration = project.configurations.getByName(Dependency.ARCHIVES_CONFIGURATION)
description = "Installs the 'archives' artifacts into the local Maven repository."
repositories {
withConvention(MavenRepositoryHandlerConvention::class) {
mavenInstaller {
configurePom()
}
}
}
}
tasks.register("publish") {
dependsOn(tasks.named("uploadArchives"))
}
}
}
}

View File

@@ -194,9 +194,7 @@ fun Project.projectTest(
systemProperty("kotlin.ni", if (project.rootProject.hasProperty("newInferenceTests")) "true" else "false")
systemProperty("org.jetbrains.kotlin.skip.muted.tests", if (project.rootProject.hasProperty("skipMutedTests")) "true" else "false")
if (Platform[202].orHigher()) {
systemProperty("idea.ignore.disabled.plugins", "true")
}
systemProperty("idea.ignore.disabled.plugins", "true")
var subProjectTempRoot: Path? = null
val projectName = project.name

View File

@@ -9,13 +9,13 @@ import org.gradle.internal.os.OperatingSystem
fun Test.configureTestDistribution(configure: TestDistributionExtension.() -> Unit = {}) {
if (extensions.findByType(TestDistributionExtension::class.java) == null) return
val isTeamcityBuild = project.kotlinBuildProperties.isTeamcityBuild
val testDistributionEnabled =
project.findProperty("kotlin.build.test.distribution.enabled")?.toString()?.toBoolean() ?: false
useJUnitPlatform()
extensions.configure(TestDistributionExtension::class.java) {
enabled.set(true)
enabled.set(testDistributionEnabled)
maxRemoteExecutors.set(20)
if (isTeamcityBuild) {
requirements.set(setOf("os=${OperatingSystem.current().familyName}"))

View File

@@ -24,24 +24,17 @@ dependencies {
testApi(projectTests(":compiler:tests-compiler-utils"))
testApi(projectTests(":compiler:tests-common-new"))
testCompile(projectTests(":jps-plugin"))
testCompile(commonDep("junit:junit"))
Platform[193].orLower {
testCompile(intellijDep()) { includeJars("openapi", rootProject = rootProject) }
}
testCompile(intellijDep()) { includeJars("util", "idea", "idea_rt", rootProject = rootProject) }
Platform[202].orHigher {
testCompile(intellijDep()) { includeJars("groovy", rootProject = rootProject) }
}
Platform[201].orLower {
testCompile(intellijDep()) { includeJars("groovy-all", rootProject = rootProject) }
}
testCompile(intellijDep()) { includeJars("groovy", rootProject = rootProject) }
testCompile(intellijPluginDep("java")) { includeJars("jps-builders") }
testCompile(jpsStandalone()) { includeJars("jps-model") }
testCompile(jpsBuildTest())
testRuntimeOnly(compile(intellijCoreDep()) { includeJars("intellij-core") })
testCompile("org.junit.platform:junit-platform-launcher:${commonVer("org.junit.platform", "")}")
}

View File

@@ -354,8 +354,8 @@ class CodegenTestsOnAndroidGenerator private constructor(private val pathManager
extractor.provideConfigurationKeys()
extractor.configure(keyConfiguration, module.directives)
}
val kind = configuratorForFlags.extractConfigurationKind(module.directives)
val jdkKind = configuratorForFlags.extractJdkKind(module.directives)
val kind = JvmEnvironmentConfigurator.extractConfigurationKind(module.directives)
val jdkKind = JvmEnvironmentConfigurator.extractJdkKind(module.directives)
keyConfiguration.languageVersionSettings = module.languageVersionSettings

View File

@@ -5,13 +5,10 @@
package org.jetbrains.kotlin.backend.common
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.resolve.sam.getAbstractMembers
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.typeUtil.replaceArgumentsWithNothing
import org.jetbrains.kotlin.types.KotlinType
class SamType constructor(val type: KotlinType) {
@@ -37,54 +34,3 @@ class SamType constructor(val type: KotlinType) {
}
}
open class SamTypeFactory {
fun createByValueParameter(valueParameter: ValueParameterDescriptor): SamType? {
val singleArgumentType: KotlinType
val originalSingleArgumentType: KotlinType?
val varargElementType = valueParameter.varargElementType
if (varargElementType != null) {
singleArgumentType = varargElementType
originalSingleArgumentType = valueParameter.original.varargElementType
assert(originalSingleArgumentType != null) {
"Value parameter and original value parameter have inconsistent varargs: " +
valueParameter + "; " + valueParameter.original
}
} else {
singleArgumentType = valueParameter.type
originalSingleArgumentType = valueParameter.original.type
}
if (singleArgumentType.isError || originalSingleArgumentType!!.isError) {
return null
}
// This can be true in case when the value parameter is in the method of a generic type with out-projection.
// We approximate Inv<Captured#1> to Nothing, while Inv itself can be a SAM interface safe to call here
// (see testData genericSamProjectedOut.kt for details)
// In such a case we can't have a proper supertype since wildcards are not allowed there,
// so we use Nothing arguments instead that leads to a raw type used for a SAM wrapper.
// See org.jetbrains.kotlin.codegen.state.KotlinTypeMapper#writeGenericType to understand how
// raw types and Nothing arguments relate.
val originalTypeToUse =
if (KotlinBuiltIns.isNothing(singleArgumentType))
originalSingleArgumentType.replaceArgumentsWithNothing()
else singleArgumentType
return create(originalTypeToUse.removeExternalProjections())
}
open fun isSamType(type: KotlinType): Boolean {
val descriptor = type.constructor.declarationDescriptor
return descriptor is ClassDescriptor && descriptor.isFun
}
fun create(originalType: KotlinType): SamType? {
return if (isSamType(originalType)) SamType(originalType) else null
}
private fun KotlinType.removeExternalProjections(): KotlinType {
val newArguments = arguments.map { TypeProjectionImpl(Variance.INVARIANT, it.type) }
return replace(newArguments)
}
companion object {
val INSTANCE = SamTypeFactory()
}
}

View File

@@ -0,0 +1,76 @@
/*
* Copyright 2010-2021 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.backend.common
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.checker.intersectWrappedTypes
import org.jetbrains.kotlin.types.typeUtil.replaceArgumentsWithNothing
class SamTypeApproximator(builtIns: KotlinBuiltIns, languageVersionSettings: LanguageVersionSettings) {
private val typeApproximator = TypeApproximator(builtIns, languageVersionSettings)
fun getSamTypeForValueParameter(valueParameter: ValueParameterDescriptor): KotlinType? {
val singleArgumentType: KotlinType
val originalSingleArgumentType: KotlinType?
val varargElementType = valueParameter.varargElementType
if (varargElementType != null) {
singleArgumentType = varargElementType
originalSingleArgumentType = valueParameter.original.varargElementType
assert(originalSingleArgumentType != null) {
"Value parameter and original value parameter have inconsistent varargs: " +
valueParameter + "; " + valueParameter.original
}
} else {
singleArgumentType = valueParameter.type
originalSingleArgumentType = valueParameter.original.type
}
if (singleArgumentType.isError || originalSingleArgumentType!!.isError) {
return null
}
// This can be true in case when the value parameter is in the method of a generic type with out-projection.
// We approximate Inv<Captured#1> to Nothing, while Inv itself can be a SAM interface safe to call here
// (see testData genericSamProjectedOut.kt for details)
// In such a case we can't have a proper supertype since wildcards are not allowed there,
// so we use Nothing arguments instead that leads to a raw type used for a SAM wrapper.
// See org.jetbrains.kotlin.codegen.state.KotlinTypeMapper#writeGenericType to understand how
// raw types and Nothing arguments relate.
val originalTypeToUse =
if (KotlinBuiltIns.isNothing(singleArgumentType))
originalSingleArgumentType.replaceArgumentsWithNothing()
else
singleArgumentType
val approximatedOriginalTypeToUse =
typeApproximator.approximateToSubType(
originalTypeToUse,
TypeApproximatorConfiguration.UpperBoundAwareIntersectionTypeApproximator
) ?: originalTypeToUse
approximatedOriginalTypeToUse as KotlinType
return approximatedOriginalTypeToUse.removeExternalProjections()
}
private fun KotlinType.removeExternalProjections(): KotlinType {
val newArguments = arguments.map { TypeProjectionImpl(Variance.INVARIANT, it.type) }
return replace(newArguments)
}
}
open class SamTypeFactory {
open fun isSamType(type: KotlinType): Boolean {
val descriptor = type.constructor.declarationDescriptor
return descriptor is ClassDescriptor && descriptor.isFun
}
fun create(originalType: KotlinType): SamType? {
return if (isSamType(originalType)) SamType(originalType) else null
}
}

View File

@@ -18,7 +18,10 @@ interface TypeMappingContext<Writer : JvmDescriptorTypeWriter<Type>> {
val typeContext: TypeSystemCommonBackendContextForTypeMapping
fun getClassInternalName(typeConstructor: TypeConstructorMarker): String
fun Writer.writeGenericType(type: SimpleTypeMarker, asmType: Type, mode: TypeMappingMode)
fun getScriptInternalName(typeConstructor: TypeConstructorMarker): String
// NB: The counterpart, [KotlinTypeMapper#writeGenericType], doesn't have restriction on [type]
fun Writer.writeGenericType(type: KotlinTypeMarker, asmType: Type, mode: TypeMappingMode)
}
object AbstractTypeMapper {
@@ -43,6 +46,7 @@ object AbstractTypeMapper {
sw: Writer? = null
): Type = context.typeContext.mapType(context, type, mode, sw)
// NB: The counterpart, [descriptorBasedTypeSignatureMapping#mapType] doesn't have restriction on [type].
@OptIn(ExperimentalStdlibApi::class)
private fun <Writer : JvmDescriptorTypeWriter<Type>> TypeSystemCommonBackendContextForTypeMapping.mapType(
context: TypeMappingContext<Writer>,
@@ -50,10 +54,7 @@ object AbstractTypeMapper {
mode: TypeMappingMode = TypeMappingMode.DEFAULT,
sw: Writer? = null
): Type {
if (type !is SimpleTypeMarker) {
error("Unexpected type: $type (original Kotlin type=$type of ${type.let { it::class }})")
}
if (type.isSuspendFunction()) {
if (type is SimpleTypeMarker && type.isSuspendFunction()) {
val argumentsCount = type.argumentsCount()
val argumentsList = type.asArgumentList()
@@ -78,7 +79,7 @@ object AbstractTypeMapper {
val typeConstructor = type.typeConstructor()
when {
type.isArrayOrNullableArray() -> {
type is SimpleTypeMarker && type.isArrayOrNullableArray() -> {
val typeArgument = type.asArgumentList()[0]
val (variance, memberType) = when {
typeArgument.isStarProjection() -> Variance.OUT_VARIANCE to nullableAnyType()
@@ -98,7 +99,7 @@ object AbstractTypeMapper {
return AsmUtil.getArrayType(arrayElementType)
}
typeConstructor.isClassTypeConstructor() -> {
type is SimpleTypeMarker && typeConstructor.isClassTypeConstructor() -> {
if (typeConstructor.isInlineClass() && !mode.needInlineClassWrapping) {
val expandedType = computeExpandedTypeForInlineClass(type)
require(expandedType is SimpleTypeMarker?)
@@ -117,9 +118,7 @@ object AbstractTypeMapper {
}
typeConstructor.isScript() -> {
val asmType = AsmTypes.JAVA_CLASS_TYPE
with(context) { sw?.writeGenericType(type, asmType, mode) }
return asmType
return Type.getObjectType(context.getScriptInternalName(typeConstructor))
}
typeConstructor.isTypeParameter() -> {

View File

@@ -34,10 +34,10 @@ import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.resolve.AnnotationChecker;
import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.resolve.InlineClassesUtilsKt;
import org.jetbrains.kotlin.resolve.checkers.ExpectedActualDeclarationChecker;
import org.jetbrains.kotlin.resolve.constants.*;
import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt;
import org.jetbrains.kotlin.resolve.jvm.annotations.JvmAnnotationUtilKt;
import org.jetbrains.kotlin.resolve.multiplatform.OptionalAnnotationUtil;
import org.jetbrains.kotlin.types.FlexibleType;
import org.jetbrains.kotlin.types.FlexibleTypesKt;
import org.jetbrains.kotlin.types.KotlinType;
@@ -376,7 +376,7 @@ public abstract class AnnotationCodegen {
// We do not generate annotations whose classes are optional (annotated with `@OptionalExpectation`) because if an annotation entry
// is resolved to the expected declaration, this means that annotation has no actual class, and thus should not be generated.
// (Otherwise we would've resolved the entry to the actual annotation class.)
if (ExpectedActualDeclarationChecker.isOptionalAnnotationClass(classDescriptor)) {
if (OptionalAnnotationUtil.isOptionalAnnotationClass(classDescriptor)) {
return null;
}

View File

@@ -20,14 +20,12 @@ import org.jetbrains.kotlin.codegen.inline.NameGenerator
import org.jetbrains.kotlin.codegen.inline.ReifiedTypeInliner.Companion.putReifiedOperationMarker
import org.jetbrains.kotlin.codegen.inline.ReifiedTypeInliner.OperationKind
import org.jetbrains.kotlin.codegen.inline.ReifiedTypeParametersUsages
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.types.TypeSystemCommonBackendContext
import org.jetbrains.kotlin.types.model.KotlinTypeMarker
import org.jetbrains.kotlin.types.model.TypeParameterMarker
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
interface BaseExpressionCodegen {
val frameMap: FrameMapBase<*>
val visitor: InstructionAdapter
@@ -40,24 +38,14 @@ interface BaseExpressionCodegen {
fun propagateChildReifiedTypeParametersUsages(reifiedTypeParametersUsages: ReifiedTypeParametersUsages)
fun pushClosureOnStack(
classDescriptor: ClassDescriptor,
putThis: Boolean,
callGenerator: CallGenerator,
functionReferenceReceiver: StackValue?
)
fun markLineNumberAfterInlineIfNeeded(registerLineNumberAfterwards: Boolean)
fun consumeReifiedOperationMarker(typeParameter: TypeParameterMarker)
fun putReifiedOperationMarkerIfTypeIsReifiedParameter(type: KotlinTypeMarker, operationKind: OperationKind) {
with(typeSystem) {
val (typeParameter, second) = extractReificationArgument(type) ?: return
if (typeParameter.isReified()) {
consumeReifiedOperationMarker(typeParameter)
putReifiedOperationMarker(operationKind, second, visitor)
}
}
}
}
fun BaseExpressionCodegen.putReifiedOperationMarkerIfTypeIsReifiedParameter(type: KotlinTypeMarker, operationKind: OperationKind): Boolean {
val (typeParameter, second) = typeSystem.extractReificationArgument(type) ?: return false
consumeReifiedOperationMarker(typeParameter)
putReifiedOperationMarker(operationKind, second, visitor)
return true
}

View File

@@ -18,7 +18,6 @@ enum class ValueKind {
DEFAULT_MASK,
METHOD_HANDLE_IN_DEFAULT,
CAPTURED,
DEFAULT_LAMBDA_CAPTURED_PARAMETER,
NON_INLINEABLE_ARGUMENT_FOR_INLINE_PARAMETER_CALLED_IN_SUSPEND,
NON_INLINEABLE_ARGUMENT_FOR_INLINE_SUSPEND_PARAMETER
}
@@ -40,13 +39,9 @@ interface CallGenerator {
}
}
override fun processAndPutHiddenParameters(justProcess: Boolean) {
override fun processHiddenParameters() {}
}
override fun putHiddenParamsIntoLocals() {
}
override fun putHiddenParamsIntoLocals() {}
override fun genValueAndPut(
valueParameterDescriptor: ValueParameterDescriptor?,
@@ -141,9 +136,8 @@ interface CallGenerator {
paramIndex: Int
)
fun processAndPutHiddenParameters(justProcess: Boolean)
fun processHiddenParameters()
/*should be called if justProcess = true in processAndPutHiddenParameters*/
fun putHiddenParamsIntoLocals()
fun reorderArgumentsIfNeeded(actualArgsWithDeclIndex: List<ArgumentAndDeclIndex>, valueParameterTypes: List<Type>)

View File

@@ -12,6 +12,7 @@ import kotlin.Unit;
import kotlin.collections.CollectionsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.backend.common.SamType;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.codegen.binding.CalculatedClosure;
import org.jetbrains.kotlin.codegen.context.ClosureContext;
@@ -31,7 +32,6 @@ import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader;
import org.jetbrains.kotlin.metadata.ProtoBuf;
import org.jetbrains.kotlin.psi.KtElement;
import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.resolve.InlineClassesUtilsKt;
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall;
import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt;
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKt;
@@ -40,7 +40,7 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.TransientReceiver;
import org.jetbrains.kotlin.serialization.DescriptorSerializer;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.kotlin.types.SimpleType;
import org.jetbrains.kotlin.backend.common.SamType;
import org.jetbrains.kotlin.types.TypeUtils;
import org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils;
import org.jetbrains.kotlin.util.OperatorNameConventions;
import org.jetbrains.org.objectweb.asm.MethodVisitor;
@@ -376,10 +376,12 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
value = StackValue.local(slot, type, bridgeParameterKotlinTypes.get(i));
slot += type.getSize();
}
if (InlineClassesCodegenUtilKt.isInlineClassWithUnderlyingTypeAnyOrAnyN(parameterType) &&
functionReferenceCall == null
) {
parameterType = InlineClassesUtilsKt.unsubstitutedUnderlyingParameter(parameterType).getType();
if (InlineClassesCodegenUtilKt.isInlineClassWithUnderlyingTypeAnyOrAnyN(parameterType) && functionReferenceCall == null) {
ClassDescriptor descriptor = TypeUtils.getClassDescriptor(parameterType);
InlineClassRepresentation<SimpleType> representation =
descriptor != null ? descriptor.getInlineClassRepresentation() : null;
assert representation != null : "Not an inline class type: " + parameterType;
parameterType = representation.getUnderlyingType();
}
value.put(typeMapper.mapType(calleeParameter), parameterType, iv);
}

View File

@@ -6,19 +6,17 @@
package org.jetbrains.kotlin.codegen
import org.jetbrains.kotlin.codegen.binding.CodegenBinding
import org.jetbrains.kotlin.codegen.inline.InlineCodegen
import org.jetbrains.kotlin.codegen.optimization.nullCheck.isCheckParameterIsNotNull
import org.jetbrains.kotlin.codegen.inline.loadCompiledInlineFunction
import org.jetbrains.kotlin.codegen.optimization.nullCheck.usesLocalExceptParameterNullCheck
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.VariableDescriptorWithAccessors
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.FunctionImportedFromObject
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.jvm.requiresFunctionNameManglingForReturnType
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DescriptorWithContainerSource
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.tree.AbstractInsnNode
import org.jetbrains.org.objectweb.asm.tree.MethodNode
import org.jetbrains.org.objectweb.asm.tree.VarInsnNode
class DelegatedPropertiesCodegenHelper(private val state: GenerationState) {
@@ -65,27 +63,15 @@ class DelegatedPropertiesCodegenHelper(private val state: GenerationState) {
this
private fun isDelegatedPropertyMetadataRequiredForFunctionFromBinaries(calleeDescriptor: FunctionDescriptor): Boolean {
assert(calleeDescriptor is DescriptorWithContainerSource) {
require(calleeDescriptor is DescriptorWithContainerSource) {
"Function descriptor from binaries expected: $calleeDescriptor"
}
val metadataParameterIndex = getMetadataParameterIndex(calleeDescriptor)
val methodNode = InlineCodegen.createSpecialInlineMethodNodeFromBinaries(calleeDescriptor, state)
return isMetadataParameterUsedInCompiledMethodBody(metadataParameterIndex, methodNode)
}
private fun isMetadataParameterUsedInCompiledMethodBody(metadataParameterIndex: Int, methodNode: MethodNode): Boolean =
methodNode.instructions.toArray().any { insn ->
insn is VarInsnNode && insn.opcode == Opcodes.ALOAD && insn.`var` == metadataParameterIndex &&
!isParameterNullCheckArgument(insn)
}
private fun isParameterNullCheckArgument(insn: AbstractInsnNode): Boolean {
val next1 = insn.next
val next2 = next1.next
return next1 != null && next2 != null &&
next1.opcode == Opcodes.LDC && next2.isCheckParameterIsNotNull()
val containerId = KotlinTypeMapper.getContainingClassesForDeserializedCallable(calleeDescriptor).implClassId
val asmMethod = state.typeMapper.mapAsmMethod(calleeDescriptor)
val isMangled = requiresFunctionNameManglingForReturnType(calleeDescriptor)
val methodNode = loadCompiledInlineFunction(containerId, asmMethod, calleeDescriptor.isSuspend, isMangled, state).node
return methodNode.usesLocalExceptParameterNullCheck(metadataParameterIndex)
}
private fun getMetadataParameterIndex(calleeDescriptor: FunctionDescriptor): Int {

View File

@@ -72,7 +72,7 @@ class ErasedInlineClassBodyCodegen(
}
private fun generateUnboxMethod() {
val boxMethodDescriptor = InlineClassDescriptorResolver.createBoxFunctionDescriptor(descriptor) ?: return
val boxMethodDescriptor = InlineClassDescriptorResolver.createBoxFunctionDescriptor(descriptor)
functionCodegen.generateMethod(
Synthetic(null, boxMethodDescriptor), boxMethodDescriptor, object : FunctionGenerationStrategy.CodegenBased(state) {
@@ -103,7 +103,7 @@ class ErasedInlineClassBodyCodegen(
}
private fun generateSpecializedEqualsStub() {
val specializedEqualsDescriptor = InlineClassDescriptorResolver.createSpecializedEqualsDescriptor(descriptor) ?: return
val specializedEqualsDescriptor = InlineClassDescriptorResolver.createSpecializedEqualsDescriptor(descriptor)
functionCodegen.generateMethod(
Synthetic(null, specializedEqualsDescriptor), specializedEqualsDescriptor, object : FunctionGenerationStrategy.CodegenBased(state) {

View File

@@ -20,6 +20,7 @@ import kotlin.text.StringsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.backend.common.CodegenUtil;
import org.jetbrains.kotlin.backend.common.SamType;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.codegen.binding.CalculatedClosure;
import org.jetbrains.kotlin.codegen.binding.CodegenBinding;
@@ -92,7 +93,6 @@ import org.jetbrains.kotlin.types.model.KotlinTypeMarker;
import org.jetbrains.kotlin.types.model.TypeParameterMarker;
import org.jetbrains.kotlin.types.typesApproximation.CapturedTypeApproximationKt;
import org.jetbrains.kotlin.util.OperatorNameConventions;
import org.jetbrains.kotlin.backend.common.SamType;
import org.jetbrains.org.objectweb.asm.Label;
import org.jetbrains.org.objectweb.asm.MethodVisitor;
import org.jetbrains.org.objectweb.asm.Opcodes;
@@ -107,6 +107,7 @@ import java.util.stream.Collectors;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isInt;
import static org.jetbrains.kotlin.codegen.AsmUtil.boxType;
import static org.jetbrains.kotlin.codegen.AsmUtil.*;
import static org.jetbrains.kotlin.codegen.BaseExpressionCodegenKt.putReifiedOperationMarkerIfTypeIsReifiedParameter;
import static org.jetbrains.kotlin.codegen.CodegenUtilKt.*;
import static org.jetbrains.kotlin.codegen.DescriptorAsmUtil.boxType;
import static org.jetbrains.kotlin.codegen.DescriptorAsmUtil.*;
@@ -265,13 +266,23 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
);
}
private static void addReifiedParametersFromSignature(@NotNull MemberCodegen member, @NotNull ClassDescriptor descriptor) {
private static void addReifiedParametersFromSignature(@NotNull MemberCodegen<?> member, @NotNull ClassDescriptor descriptor) {
for (KotlinType type : descriptor.getTypeConstructor().getSupertypes()) {
for (TypeProjection supertypeArgument : type.getArguments()) {
TypeParameterDescriptor parameterDescriptor = TypeUtils.getTypeParameterDescriptorOrNull(supertypeArgument.getType());
if (parameterDescriptor != null && parameterDescriptor.isReified()) {
processTypeArguments(member, type);
}
}
private static void processTypeArguments(@NotNull MemberCodegen<?> member, KotlinType type) {
for (TypeProjection supertypeArgument : type.getArguments()) {
if (supertypeArgument.isStarProjection()) continue;
TypeParameterDescriptor parameterDescriptor = TypeUtils.getTypeParameterDescriptorOrNull(supertypeArgument.getType());
if (parameterDescriptor != null) {
if (parameterDescriptor.isReified()) {
member.getReifiedTypeParametersUsages().addUsedReifiedParameter(parameterDescriptor.getName().asString());
}
} else {
processTypeArguments(member, supertypeArgument.getType());
}
}
}
@@ -1251,8 +1262,8 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
if (closure.isSuspendLambda()) {
// When inlining crossinline lambda, the ACONST_NULL is never popped.
// Thus, do not generate it. Otherwise, it leads to VerifyError on run-time.
boolean isCrossinlineLambda = (callGenerator instanceof InlineCodegen<?>) &&
Objects.requireNonNull(((InlineCodegen) callGenerator).getActiveLambda(),
boolean isCrossinlineLambda = (callGenerator instanceof PsiInlineCodegen) &&
Objects.requireNonNull(((PsiInlineCodegen) callGenerator).getActiveLambda(),
"no active lambda found").isCrossInline;
if (!isCrossinlineLambda) {
v.aconst(null);
@@ -2014,10 +2025,12 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
// Do not unbox parameters of suspend lambda, they are unboxed in `invoke` method
!CoroutineCodegenUtilKt.isInvokeSuspendOfLambda(context.getFunctionDescriptor())
) {
KotlinType underlyingType = InlineClassesUtilsKt.underlyingRepresentation(
(ClassDescriptor) inlineClassType.getConstructor().getDeclarationDescriptor()).getType();
return StackValue.underlyingValueOfInlineClass(
typeMapper.mapType(underlyingType), underlyingType, localOrCaptured);
ClassDescriptor inlineClass = (ClassDescriptor) inlineClassType.getConstructor().getDeclarationDescriptor();
InlineClassRepresentation<SimpleType> representation =
inlineClass != null ? inlineClass.getInlineClassRepresentation() : null;
assert representation != null : "Not an inline class: " + inlineClassType;
KotlinType underlyingType = representation.getUnderlyingType();
return StackValue.underlyingValueOfInlineClass(typeMapper.mapType(underlyingType), underlyingType, localOrCaptured);
}
}
return localOrCaptured;
@@ -2768,7 +2781,8 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
putReceiverAndInlineMarkerIfNeeded(callableMethod, resolvedCall, receiver, maybeSuspensionPoint, isConstructor);
}
callGenerator.processAndPutHiddenParameters(false);
callGenerator.processHiddenParameters();
callGenerator.putHiddenParamsIntoLocals();
List<ResolvedValueArgument> valueArguments = resolvedCall.getValueArgumentsByIndex();
assert valueArguments != null : "Failed to arrange value arguments by index: " + resolvedCall.getResultingDescriptor();
@@ -2937,13 +2951,12 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
bindingContext, state
);
PsiSourceCompilerForInline sourceCompiler = new PsiSourceCompilerForInline(this, callElement);
FunctionDescriptor functionDescriptor =
InlineUtil.isArrayConstructorWithLambda(original)
? FictitiousArrayConstructor.create((ConstructorDescriptor) original) : original.getOriginal();
PsiSourceCompilerForInline sourceCompiler = new PsiSourceCompilerForInline(this, callElement, functionDescriptor);
sourceCompiler.initializeInlineFunctionContext(functionDescriptor);
JvmMethodSignature signature = typeMapper.mapSignatureWithGeneric(functionDescriptor, sourceCompiler.getContextKind());
JvmMethodSignature signature = typeMapper.mapSignatureWithGeneric(functionDescriptor, sourceCompiler.getContext().getContextKind());
if (signature.getAsmMethod().getName().contains("-") &&
!state.getConfiguration().getBoolean(JVMConfigurationKeys.USE_OLD_INLINE_CLASSES_MANGLING_SCHEME)
) {
@@ -2951,17 +2964,15 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
InlineClassesCodegenUtilKt.classFileContainsMethod(functionDescriptor, state, signature.getAsmMethod());
if (classFileContainsMethod != null && !classFileContainsMethod) {
typeMapper.setUseOldManglingRulesForFunctionAcceptingInlineClass(true);
signature = typeMapper.mapSignatureWithGeneric(functionDescriptor, sourceCompiler.getContextKind());
signature = typeMapper.mapSignatureWithGeneric(functionDescriptor, sourceCompiler.getContext().getContextKind());
typeMapper.setUseOldManglingRulesForFunctionAcceptingInlineClass(false);
}
}
Type methodOwner = typeMapper.mapImplementationOwner(functionDescriptor);
if (isDefaultCompilation) {
return new InlineCodegenForDefaultBody(functionDescriptor, this, state, methodOwner, signature, sourceCompiler);
}
else {
return new PsiInlineCodegen(this, state, functionDescriptor, methodOwner, signature, typeParameterMappings, sourceCompiler,
typeMapper.mapOwner(descriptor));
return new InlineCodegenForDefaultBody(functionDescriptor, this, state, signature, sourceCompiler);
} else {
return new PsiInlineCodegen(this, state, functionDescriptor, signature, typeParameterMappings, sourceCompiler,
typeMapper.mapImplementationOwner(functionDescriptor), typeMapper.mapOwner(descriptor));
}
}
@@ -3545,7 +3556,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
if (TypeUtils.isTypeParameter(type)) {
assert TypeUtils.isReifiedTypeParameter(type) :
"Non-reified type parameter under ::class should be rejected by type checker: " + type;
putReifiedOperationMarkerIfTypeIsReifiedParameter(type, ReifiedTypeInliner.OperationKind.JAVA_CLASS);
putReifiedOperationMarkerIfTypeIsReifiedParameter(this, type, ReifiedTypeInliner.OperationKind.JAVA_CLASS);
}
putJavaLangClassInstance(v, typeMapper.mapType(type), type, typeMapper);
@@ -4918,10 +4929,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
public void newArrayInstruction(@NotNull KotlinType arrayType) {
if (KotlinBuiltIns.isArray(arrayType)) {
KotlinType elementJetType = arrayType.getArguments().get(0).getType();
putReifiedOperationMarkerIfTypeIsReifiedParameter(
elementJetType,
ReifiedTypeInliner.OperationKind.NEW_ARRAY
);
putReifiedOperationMarkerIfTypeIsReifiedParameter(this, elementJetType, ReifiedTypeInliner.OperationKind.NEW_ARRAY);
v.newarray(boxType(typeMapper.mapTypeAsDeclaration(elementJetType)));
}
else {
@@ -5225,7 +5233,7 @@ The "returned" value of try expression with no finally is either the last expres
boolean safeAs = opToken == KtTokens.AS_SAFE;
if (TypeUtils.isReifiedTypeParameter(rightKotlinType)) {
putReifiedOperationMarkerIfTypeIsReifiedParameter(rightKotlinType,
putReifiedOperationMarkerIfTypeIsReifiedParameter(this, rightKotlinType,
safeAs ? ReifiedTypeInliner.OperationKind.SAFE_AS
: ReifiedTypeInliner.OperationKind.AS);
v.checkcast(boxedRightType);
@@ -5282,7 +5290,7 @@ The "returned" value of try expression with no finally is either the last expres
Type type = boxType(typeMapper.mapTypeAsDeclaration(rhsKotlinType));
if (TypeUtils.isReifiedTypeParameter(rhsKotlinType)) {
putReifiedOperationMarkerIfTypeIsReifiedParameter(rhsKotlinType, ReifiedTypeInliner.OperationKind.IS);
putReifiedOperationMarkerIfTypeIsReifiedParameter(this, rhsKotlinType, ReifiedTypeInliner.OperationKind.IS);
v.instanceOf(type);
return null;
}
@@ -5534,11 +5542,4 @@ The "returned" value of try expression with no finally is either the last expres
parentCodegen.getReifiedTypeParametersUsages().addUsedReifiedParameter(typeParameterDescriptor.getName().asString());
}
}
@Override
public void putReifiedOperationMarkerIfTypeIsReifiedParameter(
@NotNull KotlinTypeMarker type, @NotNull ReifiedTypeInliner.OperationKind operationKind
) {
BaseExpressionCodegen.DefaultImpls.putReifiedOperationMarkerIfTypeIsReifiedParameter(this, type, operationKind);
}
}

View File

@@ -68,6 +68,13 @@ open class FrameMapBase<T : Any> {
return Mark(currentSize)
}
fun skipTo(target: Int): Mark {
return mark().also {
if (currentSize < target)
currentSize = target
}
}
inner class Mark(private val myIndex: Int) {
fun dropTo() {

View File

@@ -53,6 +53,7 @@ import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodParameterKind;
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodParameterSignature;
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.kotlin.types.SimpleType;
import org.jetbrains.kotlin.types.TypeUtils;
import org.jetbrains.org.objectweb.asm.Label;
import org.jetbrains.org.objectweb.asm.MethodVisitor;
@@ -369,23 +370,22 @@ public class FunctionCodegen {
public static void generateMethodInsideInlineClassWrapper(
@NotNull JvmDeclarationOrigin origin,
@NotNull FunctionDescriptor functionDescriptor,
@NotNull ClassDescriptor containingDeclaration,
@NotNull ClassDescriptor inlineClass,
@NotNull MethodVisitor mv,
@NotNull KotlinTypeMapper typeMapper
) {
mv.visitCode();
Type fieldOwnerType = typeMapper.mapClass(containingDeclaration);
Type fieldOwnerType = typeMapper.mapClass(inlineClass);
Method erasedMethodImpl = typeMapper.mapAsmMethod(functionDescriptor.getOriginal(), OwnerKind.ERASED_INLINE_CLASS);
ValueParameterDescriptor valueRepresentation = InlineClassesUtilsKt.underlyingRepresentation(containingDeclaration);
if (valueRepresentation == null) return;
Type fieldType = typeMapper.mapType(valueRepresentation);
InlineClassRepresentation<SimpleType> representation = inlineClass.getInlineClassRepresentation();
assert representation != null : "Not an inline class: " + inlineClass;
generateDelegateToStaticErasedVersion(
mv, erasedMethodImpl,
fieldOwnerType, valueRepresentation.getName().asString(), fieldType
mv, erasedMethodImpl, fieldOwnerType,
representation.getUnderlyingPropertyName().asString(),
typeMapper.mapType(representation.getUnderlyingType())
);
endVisit(mv, null, origin.getElement());

View File

@@ -55,6 +55,7 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver;
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue;
import org.jetbrains.kotlin.serialization.DescriptorSerializer;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.kotlin.types.SimpleType;
import org.jetbrains.org.objectweb.asm.FieldVisitor;
import org.jetbrains.org.objectweb.asm.MethodVisitor;
import org.jetbrains.org.objectweb.asm.Type;
@@ -274,26 +275,25 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
@Override
protected void generateUnboxMethodForInlineClass() {
if (!(myClass instanceof KtClass)) return;
if (!InlineClassesUtilsKt.isInlineClass(descriptor)) return;
InlineClassRepresentation<SimpleType> inlineClassRepresentation = descriptor.getInlineClassRepresentation();
if (inlineClassRepresentation == null) return;
Type ownerType = typeMapper.mapClass(descriptor);
ValueParameterDescriptor inlinedValue = InlineClassesUtilsKt.underlyingRepresentation(this.descriptor);
if (inlinedValue == null) return;
Type valueType = typeMapper.mapType(inlinedValue.getType());
Type valueType = typeMapper.mapType(inlineClassRepresentation.getUnderlyingType());
SimpleFunctionDescriptor functionDescriptor = InlineClassDescriptorResolver.createUnboxFunctionDescriptor(this.descriptor);
assert functionDescriptor != null : "FunctionDescriptor for unbox method should be not null during codegen";
functionCodegen.generateMethod(
JvmDeclarationOriginKt.UnboxMethodOfInlineClass(functionDescriptor), functionDescriptor,
new FunctionGenerationStrategy.CodegenBased(state) {
@Override
public void doGenerateBody(
@NotNull ExpressionCodegen codegen, @NotNull JvmMethodSignature signature
) {
public void doGenerateBody(@NotNull ExpressionCodegen codegen, @NotNull JvmMethodSignature signature) {
InstructionAdapter iv = codegen.v;
iv.load(0, OBJECT_TYPE);
iv.getfield(ownerType.getInternalName(), inlinedValue.getName().asString(), valueType.getDescriptor());
iv.getfield(
ownerType.getInternalName(),
inlineClassRepresentation.getUnderlyingPropertyName().asString(),
valueType.getDescriptor()
);
iv.areturn(valueType);
}
}

View File

@@ -5,10 +5,11 @@
package org.jetbrains.kotlin.codegen
import org.jetbrains.kotlin.backend.common.SamTypeFactory
import org.jetbrains.kotlin.load.java.sam.JavaSingleAbstractMethodUtils
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.backend.common.SamTypeFactory
object JvmSamTypeFactory : SamTypeFactory() {
override fun isSamType(type: KotlinType) = JavaSingleAbstractMethodUtils.isSamType(type)
class JvmSamTypeFactory : SamTypeFactory() {
override fun isSamType(type: KotlinType) =
JavaSingleAbstractMethodUtils.isSamType(type)
}

View File

@@ -35,9 +35,9 @@ import org.jetbrains.kotlin.progress.ProgressIndicatorAndCompilationCanceledStat
import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.psi.psiUtil.PsiUtilsKt;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.checkers.ExpectedActualDeclarationChecker;
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKt;
import org.jetbrains.kotlin.resolve.lazy.descriptors.PackageDescriptorUtilKt;
import org.jetbrains.kotlin.resolve.multiplatform.OptionalAnnotationUtil;
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments;
import org.jetbrains.org.objectweb.asm.Type;
@@ -91,8 +91,8 @@ public class PackageCodegenImpl implements PackageCodegen {
if (declaration instanceof KtClassOrObject) {
ClassDescriptor descriptor = state.getBindingContext().get(BindingContext.CLASS, declaration);
if (PsiUtilsKt.hasExpectModifier(declaration)) {
if (descriptor != null && ExpectedActualDeclarationChecker.shouldGenerateExpectClass(descriptor)) {
assert ExpectedActualDeclarationChecker.isOptionalAnnotationClass(descriptor) :
if (descriptor != null && OptionalAnnotationUtil.shouldGenerateExpectClass(descriptor)) {
assert OptionalAnnotationUtil.isOptionalAnnotationClass(descriptor) :
"Expect class should be generated only if it's an optional annotation: " + descriptor;
state.getFactory().getPackagePartRegistry().getOptionalAnnotations().add(descriptor);
}

View File

@@ -45,7 +45,6 @@ import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodParameterSignature
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.kotlin.types.SimpleType;
import org.jetbrains.kotlin.types.TypeUtils;
import org.jetbrains.kotlin.types.model.KotlinTypeMarker;
import org.jetbrains.org.objectweb.asm.Label;
import org.jetbrains.org.objectweb.asm.Opcodes;
@@ -1329,8 +1328,8 @@ public abstract class StackValue {
StackValue newReceiver = StackValue.receiver(call, receiver, codegen, callable);
ArgumentGenerator generator = createArgumentGenerator();
newReceiver.put(newReceiver.type, newReceiver.kotlinType, v);
callGenerator.processAndPutHiddenParameters(false);
callGenerator.processHiddenParameters();
callGenerator.putHiddenParamsIntoLocals();
defaultArgs = generator.generate(valueArguments, valueArguments, call.getResultingDescriptor());
}
@@ -1748,7 +1747,8 @@ public abstract class StackValue {
assert getterDescriptor != null : "Getter descriptor should be not null for " + descriptor;
if (resolvedCall != null && getterDescriptor.isInline()) {
CallGenerator callGenerator = codegen.getOrCreateCallGenerator(resolvedCall, ((PropertyDescriptor)resolvedCall.getResultingDescriptor()).getGetter());
callGenerator.processAndPutHiddenParameters(false);
callGenerator.processHiddenParameters();
callGenerator.putHiddenParamsIntoLocals();
callGenerator.genCall(getter, resolvedCall, false, codegen);
}
else {
@@ -1832,7 +1832,7 @@ public abstract class StackValue {
if (!skipReceiver) {
putReceiver(v, false);
}
callGenerator.processAndPutHiddenParameters(true);
callGenerator.processHiddenParameters();
callGenerator.putValueIfNeeded(new JvmKotlinType(
CollectionsKt.last(setter.getValueParameters()).getAsmType(),
CollectionsKt.last(setterDescriptor.getValueParameters()).getType()),

View File

@@ -22,7 +22,9 @@ import java.lang.StringBuilder
class StringConcatGenerator(val mode: JvmStringConcat, val mv: InstructionAdapter) {
private val template = StringBuilder("")
private val specialSymbolsInTemplate = arrayListOf<String>()
private val paramTypes = arrayListOf<Type>()
private var paramSlots = 0
private var justFlushed = false
@JvmOverloads
@@ -42,7 +44,16 @@ class StringConcatGenerator(val mode: JvmStringConcat, val mv: InstructionAdapte
if (mode == JvmStringConcat.INDY_WITH_CONSTANTS) {
when (stackValue) {
is StackValue.Constant -> {
template.append(stackValue.value)
val value = stackValue.value
if (value is String && (value.contains("\u0001") || value.contains("\u0002"))) {
template.append("\u0002") //reference to special symbols added on next line
specialSymbolsInTemplate.add(value)
} else if (value is Char && (value == 1.toChar() || value == 2.toChar())) {
template.append("\u0002") //reference to special symbols added on next line
specialSymbolsInTemplate.add(value.toString())
} else {
template.append(value)
}
return
}
TRUE -> {
@@ -74,8 +85,9 @@ class StringConcatGenerator(val mode: JvmStringConcat, val mv: InstructionAdapte
} else {
justFlushed = false
paramTypes.add(type)
paramSlots += type.size
template.append("\u0001")
if (paramTypes.size == 200) {
if (paramSlots >= 200) {
// Concatenate current arguments into string
// because of `StringConcatFactory` limitation add use it as new argument for further processing:
// "The number of parameter slots in {@code concatType} is less than or equal to 200"
@@ -104,7 +116,7 @@ class StringConcatGenerator(val mode: JvmStringConcat, val mv: InstructionAdapte
"makeConcatWithConstants",
Type.getMethodDescriptor(JAVA_STRING_TYPE, *paramTypes.toTypedArray()),
bootstrap,
arrayOf(template.toString())
arrayOf(template.toString()) + specialSymbolsInTemplate
)
} else {
val bootstrap = Handle(
@@ -122,10 +134,15 @@ class StringConcatGenerator(val mode: JvmStringConcat, val mv: InstructionAdapte
arrayOf()
)
}
//clear old template
template.clear()
specialSymbolsInTemplate.clear()
paramTypes.clear()
//add just flushed string
paramTypes.add(JAVA_STRING_TYPE)
template.append("\u0001")
paramSlots = JAVA_STRING_TYPE.size
}
}

View File

@@ -15,6 +15,7 @@ import kotlin.Pair;
import kotlin.collections.CollectionsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.backend.common.SamTypeApproximator;
import org.jetbrains.kotlin.builtins.FunctionTypesKt;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.builtins.ReflectionTypes;
@@ -34,6 +35,7 @@ import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor;
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor;
import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil;
import org.jetbrains.kotlin.load.java.JvmAbi;
import org.jetbrains.kotlin.load.java.sam.JavaSingleAbstractMethodUtils;
import org.jetbrains.kotlin.name.ClassId;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.psi.*;
@@ -90,6 +92,7 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
private final ClassBuilderMode classBuilderMode;
private final DelegatedPropertiesCodegenHelper delegatedPropertiesCodegenHelper;
private final JvmDefaultMode jvmDefaultMode;
private final SamTypeApproximator samTypeApproximator;
public CodegenAnnotatingVisitor(@NotNull GenerationState state) {
this.bindingTrace = state.getBindingTrace();
@@ -100,7 +103,8 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
this.languageVersionSettings = state.getLanguageVersionSettings();
this.classBuilderMode = state.getClassBuilderMode();
this.delegatedPropertiesCodegenHelper = new DelegatedPropertiesCodegenHelper(state);
jvmDefaultMode = state.getJvmDefaultMode();
this.jvmDefaultMode = state.getJvmDefaultMode();
this.samTypeApproximator = new SamTypeApproximator(state.getModule().getBuiltIns(), state.getLanguageVersionSettings());
}
@NotNull
@@ -855,6 +859,20 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
}
}
@Nullable
private SamType createSamType(KotlinType kotlinType) {
if (!JavaSingleAbstractMethodUtils.isSamType(kotlinType)) return null;
return new SamType(kotlinType);
}
@Nullable
private SamType createSamTypeByValueParameter(ValueParameterDescriptor valueParameterDescriptor) {
KotlinType kotlinSamType = samTypeApproximator.getSamTypeForValueParameter(valueParameterDescriptor);
if (kotlinSamType == null) return null;
if (!JavaSingleAbstractMethodUtils.isSamType(kotlinSamType)) return null;
return new SamType(kotlinSamType);
}
private void writeSamValueForValueParameters(
@NotNull Collection<ValueParameterDescriptor> valueParametersWithSAMConversion,
@Nullable List<ResolvedValueArgument> valueArguments
@@ -862,7 +880,7 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
if (valueArguments == null) return;
for (ValueParameterDescriptor valueParameter : valueParametersWithSAMConversion) {
SamType samType = JvmSamTypeFactory.INSTANCE.createByValueParameter(valueParameter);
SamType samType = createSamTypeByValueParameter(valueParameter);
if (samType == null) continue;
ResolvedValueArgument resolvedValueArgument = valueArguments.get(valueParameter.getIndex());
@@ -874,7 +892,7 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
}
private void recordSamTypeOnArgumentExpression(ValueParameterDescriptor valueParameter, ValueArgument valueArgument) {
SamType samType = JvmSamTypeFactory.INSTANCE.createByValueParameter(valueParameter);
SamType samType = createSamTypeByValueParameter(valueParameter);
if (samType == null) return;
recordSamTypeOnArgumentExpression(samType, valueArgument);
@@ -955,8 +973,7 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
KtExpression argumentExpression = argument.getArgumentExpression();
bindingTrace.record(SAM_CONSTRUCTOR_TO_ARGUMENT, expression, argumentExpression);
//noinspection ConstantConditions
SamType samType = JvmSamTypeFactory.INSTANCE.create(callableDescriptor.getReturnType());
SamType samType = createSamType(callableDescriptor.getReturnType());
bindingTrace.record(SAM_VALUE, argumentExpression, samType);
}
@@ -973,7 +990,7 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
FunctionDescriptor original = SamCodegenUtil.getOriginalIfSamAdapter((FunctionDescriptor) operationDescriptor);
if (original == null) return;
SamType samType = JvmSamTypeFactory.INSTANCE.createByValueParameter(original.getValueParameters().get(0));
SamType samType = createSamTypeByValueParameter(original.getValueParameters().get(0));
if (samType == null) return;
IElementType token = expression.getOperationToken();
@@ -1002,7 +1019,7 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
List<KtExpression> indexExpressions = expression.getIndexExpressions();
List<ValueParameterDescriptor> parameters = original.getValueParameters();
for (ValueParameterDescriptor valueParameter : parameters) {
SamType samType = JvmSamTypeFactory.INSTANCE.createByValueParameter(valueParameter);
SamType samType = createSamTypeByValueParameter(valueParameter);
if (samType == null) continue;
if (isSetter && valueParameter.getIndex() == parameters.size() - 1) {

View File

@@ -393,13 +393,12 @@ fun TypeSystemCommonBackendContext.extractReificationArgument(initialType: Kotli
while (type.isArrayOrNullableArray()) {
arrayDepth++
val argument = type.getArgument(0)
type =
if (argument.isStarProjection()) nullableAnyType()
else argument.getType()
if (argument.isStarProjection()) return null
type = argument.getType()
}
val typeParameter = type.typeConstructor().getTypeParameterClassifier() ?: return null
if (!typeParameter.isReified()) return null
return Pair(typeParameter, ReificationArgument(typeParameter.getName().asString(), isNullable, arrayDepth))
}

View File

@@ -7,9 +7,7 @@ package org.jetbrains.kotlin.codegen.coroutines
import com.intellij.util.ArrayUtil
import org.jetbrains.kotlin.backend.common.CodegenUtil
import org.jetbrains.kotlin.builtins.isSuspendFunctionTypeOrSubtype
import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.binding.CalculatedClosure
import org.jetbrains.kotlin.codegen.binding.CodegenBinding
import org.jetbrains.kotlin.codegen.binding.CodegenBinding.CAPTURES_CROSSINLINE_LAMBDA
import org.jetbrains.kotlin.codegen.binding.CodegenBinding.CLOSURE
@@ -601,21 +599,6 @@ class CoroutineCodegenForLambda private constructor(
}
}
fun isCapturedSuspendLambda(closure: CalculatedClosure, name: String, bindingContext: BindingContext): Boolean {
for ((param, value) in closure.captureVariables) {
if (param !is ValueParameterDescriptor) continue
if (value.fieldName != name) continue
return param.type.isSuspendFunctionTypeOrSubtype
}
val classDescriptor = closure.capturedOuterClassDescriptor ?: return false
return isCapturedSuspendLambda(classDescriptor, name, bindingContext)
}
fun isCapturedSuspendLambda(classDescriptor: ClassDescriptor, name: String, bindingContext: BindingContext): Boolean {
val closure = bindingContext[CLOSURE, classDescriptor] ?: return false
return isCapturedSuspendLambda(closure, name, bindingContext)
}
private class AddEndLabelMethodVisitor(
delegate: MethodVisitor,
access: Int,

View File

@@ -650,7 +650,7 @@ class CoroutineTransformerMethodVisitor(
val livenessFrames = analyzeLiveness(methodNode)
// References shall be cleaned up after uspill (during spill in next suspension point) to prevent memory leaks,
// References shall be cleaned up after unspill (during spill in next suspension point) to prevent memory leaks,
val referencesToSpillBySuspensionPointIndex = arrayListOf<List<ReferenceToSpill>>()
// while primitives shall not
val primitivesToSpillBySuspensionPointIndex = arrayListOf<List<PrimitiveToSpill>>()
@@ -759,6 +759,35 @@ class CoroutineTransformerMethodVisitor(
referencesToCleanBySuspensionPointIndex += currentSpilledReferencesCount to predSpilledReferencesCount
}
// Calculate debug metadata mapping before modifying method node to make it easier to locate
// locals alive across suspension points.
fun calculateSpilledVariableAndField(
suspension: SuspensionPoint,
slot: Int,
spillableVariable: SpillableVariable?
): SpilledVariableAndField? {
if (spillableVariable == null) return null
val name = localVariableName(methodNode, slot, suspension.suspensionCallBegin.index()) ?: return null
return SpilledVariableAndField(spillableVariable.fieldName, name)
}
val spilledToVariableMapping = arrayListOf<List<SpilledVariableAndField>>()
for (suspensionPointIndex in suspensionPoints.indices) {
val suspension = suspensionPoints[suspensionPointIndex]
val spilledToVariable = arrayListOf<SpilledVariableAndField>()
referencesToSpillBySuspensionPointIndex[suspensionPointIndex].mapNotNullTo(spilledToVariable) { (slot, spillableVariable) ->
calculateSpilledVariableAndField(suspension, slot, spillableVariable)
}
primitivesToSpillBySuspensionPointIndex[suspensionPointIndex].mapNotNullTo(spilledToVariable) { (slot, spillableVariable) ->
calculateSpilledVariableAndField(suspension, slot, spillableVariable)
}
spilledToVariableMapping += spilledToVariable
}
// Mutate method node
fun generateSpillAndUnspill(suspension: SuspensionPoint, slot: Int, spillableVariable: SpillableVariable?) {
@@ -772,6 +801,22 @@ class CoroutineTransformerMethodVisitor(
return
}
// Find and remove the local variable node, if any, in the local variable table corresponding to the slot that is spilled.
var local: LocalVariableNode? = null
val localRestart = LabelNode().linkWithLabel()
val iterator = methodNode.localVariables.listIterator()
while (iterator.hasNext()) {
val node = iterator.next()
if (node.index == slot &&
methodNode.instructions.indexOf(node.start) <= methodNode.instructions.indexOf(suspension.suspensionCallBegin) &&
methodNode.instructions.indexOf(node.end) > methodNode.instructions.indexOf(suspension.tryCatchBlockEndLabelAfterSuspensionCall)
) {
local = node
iterator.remove()
break
}
}
with(instructions) {
// store variable before suspension call
insertBefore(suspension.suspensionCallBegin, withInstructionAdapter {
@@ -795,8 +840,31 @@ class CoroutineTransformerMethodVisitor(
)
StackValue.coerce(spillableVariable.normalizedType, spillableVariable.type, this)
store(slot, spillableVariable.type)
if (local != null) {
visitLabel(localRestart.label)
}
})
}
// Split the local variable range for the local so that it is visible until the next state label, but is
// not visible until it has been unspilled from the continuation on the reentry path.
if (local != null) {
val previousEnd = local.end
local.end = suspension.stateLabel
// Add the local back, but end it at the next state label.
methodNode.localVariables.add(local)
// Add a new entry that starts after the local variable is restored from the continuation.
methodNode.localVariables.add(
LocalVariableNode(
local.name,
local.desc,
local.signature,
localRestart,
previousEnd,
local.index
)
)
}
}
fun cleanUpField(suspension: SuspensionPoint, fieldIndex: Int) {
@@ -839,33 +907,6 @@ class CoroutineTransformerMethodVisitor(
}
}
// Calculate debug metadata mapping
fun calculateSpilledVariableAndField(
suspension: SuspensionPoint,
slot: Int,
spillableVariable: SpillableVariable?
): SpilledVariableAndField? {
if (spillableVariable == null) return null
val name = localVariableName(methodNode, slot, suspension.suspensionCallEnd.next.index()) ?: return null
return SpilledVariableAndField(spillableVariable.fieldName, name)
}
val spilledToVariableMapping = arrayListOf<List<SpilledVariableAndField>>()
for (suspensionPointIndex in suspensionPoints.indices) {
val suspension = suspensionPoints[suspensionPointIndex]
val spilledToVariable = arrayListOf<SpilledVariableAndField>()
referencesToSpillBySuspensionPointIndex[suspensionPointIndex].mapNotNullTo(spilledToVariable) { (slot, spillableVariable) ->
calculateSpilledVariableAndField(suspension, slot, spillableVariable)
}
primitivesToSpillBySuspensionPointIndex[suspensionPointIndex].mapNotNullTo(spilledToVariable) { (slot, spillableVariable) ->
calculateSpilledVariableAndField(suspension, slot, spillableVariable)
}
spilledToVariableMapping += spilledToVariable
}
return spilledToVariableMapping
}
@@ -901,7 +942,6 @@ class CoroutineTransformerMethodVisitor(
suspendMarkerVarIndex: Int,
suspendPointLineNumber: LineNumberNode?
): LabelNode {
val stateLabel = LabelNode().linkWithLabel()
val continuationLabelAfterLoadedResult = LabelNode()
val suspendElementLineNumber = lineNumber
var nextLineNumberNode = nextDefinitelyHitLineNumber(suspension)
@@ -929,7 +969,7 @@ class CoroutineTransformerMethodVisitor(
load(suspendMarkerVarIndex, AsmTypes.OBJECT_TYPE)
areturn(AsmTypes.OBJECT_TYPE)
// Mark place for continuation
visitLabel(stateLabel.label)
visitLabel(suspension.stateLabel.label)
})
// After suspension point there is always three nodes: L1, NOP, L2
@@ -985,7 +1025,7 @@ class CoroutineTransformerMethodVisitor(
}
}
return stateLabel
return suspension.stateLabel
}
// Find the next line number instruction that is defintely hit. That is, a line number
@@ -1154,6 +1194,7 @@ internal class SuspensionPoint(
) {
lateinit var tryCatchBlocksContinuationLabel: LabelNode
val stateLabel = LabelNode().linkWithLabel()
val unboxInlineClassInstructions: List<AbstractInsnNode> = findUnboxInlineClassInstructions()
private fun findUnboxInlineClassInstructions(): List<AbstractInsnNode> {
@@ -1235,16 +1276,13 @@ private fun updateLvtAccordingToLiveness(method: MethodNode, isForNamedFunction:
fun isAlive(insnIndex: Int, variableIndex: Int): Boolean =
liveness[insnIndex].isAlive(variableIndex)
fun nextSuspensionPointEndLabel(insn: AbstractInsnNode): LabelNode {
val suspensionPoint =
InsnSequence(insn, method.instructions.last).firstOrNull { isAfterSuspendMarker(it) } ?: method.instructions.last
return suspensionPoint as? LabelNode ?: suspensionPoint.findNextOrNull { it is LabelNode } as LabelNode
}
fun nextSuspensionPointStartLabel(insn: AbstractInsnNode): LabelNode {
val suspensionPoint =
InsnSequence(insn, method.instructions.last).firstOrNull { isBeforeSuspendMarker(it) } ?: method.instructions.last
return suspensionPoint as? LabelNode ?: suspensionPoint.findPreviousOrNull { it is LabelNode } as LabelNode
fun nextLabel(node: AbstractInsnNode?): LabelNode? {
var current = node
while (current != null) {
if (current is LabelNode) return current
current = current.next
}
return null
}
fun min(a: LabelNode, b: LabelNode): LabelNode =
@@ -1253,9 +1291,6 @@ private fun updateLvtAccordingToLiveness(method: MethodNode, isForNamedFunction:
fun max(a: LabelNode, b: LabelNode): LabelNode =
if (method.instructions.indexOf(a) < method.instructions.indexOf(b)) b else a
fun containsSuspensionPoint(a: LabelNode, b: LabelNode): Boolean =
InsnSequence(min(a, b), max(a, b)).none { isBeforeSuspendMarker(it) }
val oldLvt = arrayListOf<LocalVariableNode>()
for (record in method.localVariables) {
oldLvt += record
@@ -1276,35 +1311,40 @@ private fun updateLvtAccordingToLiveness(method: MethodNode, isForNamedFunction:
// No variable in LVT -> do not add one
val lvtRecord = oldLvt.findRecord(insnIndex, variableIndex) ?: continue
if (lvtRecord.name == CONTINUATION_VARIABLE_NAME) continue
// Extend lvt record to the next suspension point
val endLabel = min(lvtRecord.end, nextSuspensionPointEndLabel(insn))
// End the local when it is no longer live. Since it is not live, we will not spill and unspill it across
// suspension points. It is tempting to keep it alive until the next suspension point to leave it visible in
// the debugger for as long as possible. However, in the case of loops, the resumption after suspension can
// have a backwards edge targeting instruction between the point of death and the next suspension point.
//
// For example, code such as the following:
//
// listOf<String>.forEach {
// yield(it)
// }
//
// Generates code of this form with a back edge after resumption that will lead to invalid locals tables
// if the local range is extended to the next suspension point.
//
// iterator = iterable.iterator()
// L1: (iterable dies here)
// load iterator.next if there
// yield suspension point
//
// L2: (resumption point)
// restore live variables (not including iterable)
// goto L1 (iterator not restored here, so we cannot not have iterator live at L1)
val endLabel = nextLabel(insn.next)?.let { min(lvtRecord.end, it) } ?: lvtRecord.end
// startLabel can be null in case of parameters
@Suppress("NAME_SHADOWING") val startLabel = startLabel ?: lvtRecord.start
// Attempt to extend existing local variable node corresponding to the record in
// the original local variable table.
val recordToExtend: LocalVariableNode? = oldLvtNodeToLatestNewLvtNode[lvtRecord]
if (recordToExtend != null && containsSuspensionPoint(recordToExtend.end, startLabel)) {
recordToExtend.end = endLabel
} else {
val node = LocalVariableNode(lvtRecord.name, lvtRecord.desc, lvtRecord.signature, startLabel, endLabel, lvtRecord.index)
if (lvtRecord !in oldLvtNodeToLatestNewLvtNode) {
method.localVariables.add(node)
}
oldLvtNodeToLatestNewLvtNode[lvtRecord] = node
val node = LocalVariableNode(lvtRecord.name, lvtRecord.desc, lvtRecord.signature, startLabel, endLabel, lvtRecord.index)
if (lvtRecord !in oldLvtNodeToLatestNewLvtNode) {
method.localVariables.add(node)
}
oldLvtNodeToLatestNewLvtNode[lvtRecord] = node
}
}
}
val deadVariables = arrayListOf<Int>()
outer@for (variableIndex in start until method.maxLocals) {
if (oldLvt.none { it.index == variableIndex }) continue
for (insnIndex in 0 until (method.instructions.size() - 1)) {
if (isAlive(insnIndex, variableIndex)) continue@outer
}
deadVariables += variableIndex
}
for (variable in oldLvt) {
// $continuation and $result are dead, but they are used by debugger, as well as fake inliner variables
// For example, $continuation is used to create async stack trace
@@ -1320,19 +1360,5 @@ private fun updateLvtAccordingToLiveness(method: MethodNode, isForNamedFunction:
method.localVariables.add(variable)
continue
}
// Shrink LVT records of dead variables to the next suspension point
if (variable.index in deadVariables) {
method.localVariables.add(
LocalVariableNode(
variable.name,
variable.desc,
variable.signature,
variable.start,
min(variable.end, nextSuspensionPointStartLabel(variable.start)),
variable.index
)
)
}
}
}

View File

@@ -189,7 +189,7 @@ fun ResolvedCall<*>.replaceSuspensionFunctionWithRealDescriptor(
Pair(it, typeArguments[candidateDescriptor.typeParameters[it.index]]!!.asTypeProjection())
}.toMap()
newCall.setResultingSubstitutor(
newCall.setSubstitutor(
TypeConstructorSubstitution.createByParametersMap(newTypeArguments).buildSubstitutor()
)

View File

@@ -9,7 +9,6 @@ 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.isCoroutineSuperClass
import org.jetbrains.kotlin.codegen.coroutines.isResumeImplMethodName
import org.jetbrains.kotlin.codegen.inline.coroutines.CoroutineTransformer
import org.jetbrains.kotlin.codegen.inline.coroutines.FOR_INLINE_SUFFIX
import org.jetbrains.kotlin.codegen.serialization.JvmCodegenStringTable
@@ -27,6 +26,7 @@ import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin.Companion.NO_ORIGIN
import org.jetbrains.org.objectweb.asm.*
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
import org.jetbrains.org.objectweb.asm.commons.Method
import org.jetbrains.org.objectweb.asm.tree.*
import java.util.*
@@ -272,7 +272,7 @@ class AnonymousObjectTransformer(
// Since $$forInline functions are not generated if retransformation is the last one (i.e. call site is not inline)
// link to the function in OUTERCLASS field becomes invalid. However, since $$forInline function always has no-inline
// companion without the suffix, use it.
visitor.visitOuterClass(info.ownerClassName, info.functionName?.removeSuffix(FOR_INLINE_SUFFIX), info.functionDesc)
visitor.visitOuterClass(info.ownerClassName, info.method.name.removeSuffix(FOR_INLINE_SUFFIX), info.method.descriptor)
}
private fun inlineMethodAndUpdateGlobalResult(
@@ -314,11 +314,10 @@ class AnonymousObjectTransformer(
SourceMapCopier(sourceMapper, sourceMap),
InlineCallSiteInfo(
transformationInfo.oldClassName,
sourceNode.name,
if (isConstructor) transformationInfo.newConstructorDescriptor else sourceNode.desc,
Method(sourceNode.name, if (isConstructor) transformationInfo.newConstructorDescriptor else sourceNode.desc),
inliningContext.callSiteInfo.isInlineOrInsideInline,
isSuspendFunctionOrLambda(sourceNode),
inliningContext.root.sourceCompilerForInline.inlineCallSiteInfo.lineNumber
inliningContext.callSiteInfo.file,
inliningContext.callSiteInfo.lineNumber
), null
)
@@ -328,12 +327,6 @@ class AnonymousObjectTransformer(
return result
}
private fun isSuspendFunctionOrLambda(sourceNode: MethodNode): Boolean =
(sourceNode.desc.endsWith(";Lkotlin/coroutines/Continuation;)Ljava/lang/Object;") ||
sourceNode.desc.endsWith(";Lkotlin/coroutines/experimental/Continuation;)Ljava/lang/Object;")) &&
(CoroutineTransformer.findFakeContinuationConstructorClassName(sourceNode) != null ||
languageVersionSettings.isResumeImplMethodName(sourceNode.name.removeSuffix(FOR_INLINE_SUFFIX)))
private fun generateConstructorAndFields(
classBuilder: ClassBuilder,
allCapturedBuilder: ParametersBuilder,
@@ -547,7 +540,7 @@ class AnonymousObjectTransformer(
capturedParamBuilder.addCapturedParam(desc, desc.fieldName, !capturedOuterThisTypes.add(desc.type.className))
else
capturedParamBuilder.addCapturedParam(desc, addUniqueField(desc.fieldName + INLINE_TRANSFORMATION_SUFFIX), false)
if (info is ExpressionLambda && info.isCapturedSuspend(desc)) {
if (desc.isSuspend) {
recapturedParamInfo.functionalArgument = NonInlineableArgumentForInlineableParameterCalledInSuspend
}
val composed = StackValue.field(

View File

@@ -18,8 +18,6 @@ package org.jetbrains.kotlin.codegen.inline
import org.jetbrains.org.objectweb.asm.Type
class CapturedParamDesc(private val containingLambdaType: Type, val fieldName: String, val type: Type) {
val containingLambdaName: String
get() = containingLambdaType.internalName
class CapturedParamDesc(containingLambdaType: Type, val fieldName: String, val type: Type, val isSuspend: Boolean = false) {
val containingLambdaName: String = containingLambdaType.internalName
}

View File

@@ -23,7 +23,7 @@ import org.jetbrains.org.objectweb.asm.commons.Method
data class MethodId(val ownerInternalName: String, val method: Method)
class InlineCache {
val classBytes: SLRUMap<ClassId, ByteArray> = SLRUMap(30, 20)
val classBytes: SLRUMap<String, ByteArray> = SLRUMap(30, 20)
val methodNodeById: SLRUMap<MethodId, SMAPAndMethodNode> = SLRUMap(60, 50)
}

View File

@@ -1,15 +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.codegen.inline
class InlineCallSiteInfo(
val ownerClassName: String,
val functionName: String?,
val functionDesc: String?,
val isInlineOrInsideInline: Boolean,
val isSuspend: Boolean,
val lineNumber: Int
)

View File

@@ -6,213 +6,83 @@
package org.jetbrains.kotlin.codegen.inline
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.AsmUtil.isPrimitive
import org.jetbrains.kotlin.codegen.context.ClosureContext
import org.jetbrains.kotlin.codegen.inline.coroutines.FOR_INLINE_SUFFIX
import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicArrayConstructors
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper
import org.jetbrains.kotlin.config.CommonConfigurationKeys
import org.jetbrains.kotlin.config.JVMConfigurationKeys
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.incremental.components.Position
import org.jetbrains.kotlin.incremental.components.ScopeKind
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
import org.jetbrains.kotlin.descriptors.ParameterDescriptor
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.ImportedFromObjectCallableDescriptor
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.inline.InlineUtil
import org.jetbrains.kotlin.resolve.inline.isInlineOnly
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature
import org.jetbrains.kotlin.resolve.jvm.requiresFunctionNameManglingForReturnType
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DescriptorWithContainerSource
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeSystemCommonBackendContext
import org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils.isFunctionLiteral
import org.jetbrains.kotlin.types.expressions.LabelResolver
import org.jetbrains.kotlin.types.model.TypeParameterMarker
import org.jetbrains.org.objectweb.asm.Label
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.commons.Method
import org.jetbrains.org.objectweb.asm.tree.*
import kotlin.math.max
abstract class InlineCodegen<out T : BaseExpressionCodegen>(
protected val codegen: T,
protected val state: GenerationState,
protected val functionDescriptor: FunctionDescriptor,
protected val methodOwner: Type,
protected val jvmSignature: JvmMethodSignature,
private val typeParameterMappings: TypeParameterMappings<*>,
protected val sourceCompiler: SourceCompilerForInline,
private val reifiedTypeInliner: ReifiedTypeInliner<*>
) {
init {
assert(InlineUtil.isInline(functionDescriptor)) {
"InlineCodegen can inline only inline functions: $functionDescriptor"
}
}
// TODO: implement AS_FUNCTION inline strategy
private val asFunctionInline = false
private val initialFrameSize = codegen.frameMap.currentSize
private val isSameModule: Boolean
protected val invocationParamBuilder = ParametersBuilder.newBuilder()
protected val expressionMap = linkedMapOf<Int, FunctionalArgument>()
var activeLambda: LambdaInfo? = null
protected set
private val sourceMapper = sourceCompiler.lazySourceMapper
protected var delayedHiddenWriting: Function0<Unit>? = null
protected val maskValues = ArrayList<Int>()
protected var maskStartIndex = -1
protected var methodHandleInDefaultMethodIndex = -1
init {
isSameModule = sourceCompiler.isCallInsideSameModuleAsDeclared(functionDescriptor)
if (functionDescriptor !is FictitiousArrayConstructor) {
//track changes for property accessor and @JvmName inline functions/property accessors
if (jvmSignature.asmMethod.name != functionDescriptor.name.asString()) {
trackLookup(functionDescriptor)
}
}
}
protected fun throwCompilationException(
nodeAndSmap: SMAPAndMethodNode?, e: Exception, generateNodeText: Boolean
): CompilationException {
val contextDescriptor = sourceCompiler.compilationContextDescriptor
val element = DescriptorToSourceUtils.descriptorToDeclaration(contextDescriptor)
val node = nodeAndSmap?.node
throw CompilationException(
"Couldn't inline method call '" + functionDescriptor.name + "' into\n" +
DescriptorRenderer.DEBUG_TEXT.render(contextDescriptor) + "\n" +
(element?.text ?: "<no source>") +
if (generateNodeText) "\nCause: " + node.nodeText else "",
e, sourceCompiler.callElement as? PsiElement
)
}
protected fun generateStub(text: String, codegen: BaseExpressionCodegen) {
leaveTemps()
AsmUtil.genThrow(codegen.v, "java/lang/UnsupportedOperationException", "Call is part of inline cycle: $text")
AsmUtil.genThrow(codegen.visitor, "java/lang/UnsupportedOperationException", "Call is part of inline cycle: $text")
}
protected fun endCall(result: InlineResult, registerLineNumberAfterwards: Boolean) {
leaveTemps()
codegen.propagateChildReifiedTypeParametersUsages(result.reifiedTypeParametersUsages)
state.factory.removeClasses(result.calcClassesToRemove())
codegen.markLineNumberAfterInlineIfNeeded(registerLineNumberAfterwards)
}
fun performInline(
typeArguments: List<TypeParameterMarker>?,
inlineDefaultLambdas: Boolean,
mapDefaultSignature: Boolean,
typeSystem: TypeSystemCommonBackendContext,
registerLineNumberAfterwards: Boolean,
) {
fun performInline(registerLineNumberAfterwards: Boolean, isInlineOnly: Boolean) {
var nodeAndSmap: SMAPAndMethodNode? = null
try {
nodeAndSmap = createInlineMethodNode(mapDefaultSignature, typeArguments, typeSystem)
endCall(inlineCall(nodeAndSmap, inlineDefaultLambdas), registerLineNumberAfterwards)
nodeAndSmap = sourceCompiler.compileInlineFunction(jvmSignature).apply {
node.preprocessSuspendMarkers(forInline = true, keepFakeContinuation = false)
}
val result = inlineCall(nodeAndSmap, isInlineOnly)
leaveTemps()
codegen.propagateChildReifiedTypeParametersUsages(result.reifiedTypeParametersUsages)
codegen.markLineNumberAfterInlineIfNeeded(registerLineNumberAfterwards)
state.factory.removeClasses(result.calcClassesToRemove())
} catch (e: CompilationException) {
throw e
} catch (e: InlineException) {
throw throwCompilationException(nodeAndSmap, e, false)
throw CompilationException(
"Couldn't inline method call: ${sourceCompiler.callElementText}",
e, sourceCompiler.callElement as? PsiElement
)
} catch (e: Exception) {
throw throwCompilationException(nodeAndSmap, e, true)
throw CompilationException(
"Couldn't inline method call: ${sourceCompiler.callElementText}\nMethod: ${nodeAndSmap?.node?.nodeText}",
e, sourceCompiler.callElement as? PsiElement
)
}
}
private fun canSkipStackSpillingOnInline(methodNode: MethodNode): Boolean {
// Stack spilling before inline function 'f' call is required if:
// - 'f' is a suspend function
// - 'f' has try-catch blocks
// - 'f' has loops
//
// Instead of checking for loops precisely, we just check if there are any backward jumps -
// that is, a jump from instruction #i to instruction #j where j < i
if (functionDescriptor.isSuspend) return false
if (methodNode.tryCatchBlocks.isNotEmpty()) return false
fun isBackwardJump(fromIndex: Int, toLabel: LabelNode) =
methodNode.instructions.indexOf(toLabel) < fromIndex
val insns = methodNode.instructions.toArray()
for (i in insns.indices) {
val insn = insns[i]
when (insn) {
is JumpInsnNode ->
if (isBackwardJump(i, insn.label)) return false
is LookupSwitchInsnNode -> {
insn.dflt?.let {
if (isBackwardJump(i, it)) return false
}
if (insn.labels.any { isBackwardJump(i, it) }) return false
}
is TableSwitchInsnNode -> {
insn.dflt?.let {
if (isBackwardJump(i, it)) return false
}
if (insn.labels.any { isBackwardJump(i, it) }) return false
}
}
}
return true
}
private fun continuationValue(): StackValue {
assert(codegen is ExpressionCodegen) { "Expected ExpressionCodegen in coroutineContext inlining" }
codegen as ExpressionCodegen
val parentContext = codegen.context.parentContext
return if (parentContext is ClosureContext) {
val originalSuspendLambdaDescriptor =
parentContext.originalSuspendLambdaDescriptor ?: error("No original lambda descriptor found")
codegen.genCoroutineInstanceForSuspendLambda(originalSuspendLambdaDescriptor)
?: error("No stack value for coroutine instance of lambda found")
} else
codegen.getContinuationParameterFromEnclosingSuspendFunctionDescriptor(codegen.context.functionDescriptor)
?: error("No stack value for continuation parameter of suspend function")
}
private fun inlineCall(nodeAndSmap: SMAPAndMethodNode, inlineDefaultLambda: Boolean): InlineResult {
assert(delayedHiddenWriting == null) { "'putHiddenParamsIntoLocals' should be called after 'processAndPutHiddenParameters(true)'" }
private fun inlineCall(nodeAndSmap: SMAPAndMethodNode, isInlineOnly: Boolean): InlineResult {
val node = nodeAndSmap.node
if (inlineDefaultLambda) {
if (maskStartIndex != -1) {
for (lambda in extractDefaultLambdas(node)) {
invocationParamBuilder.buildParameters().getParameterByDeclarationSlot(lambda.offset).functionalArgument = lambda
val prev = expressionMap.put(lambda.offset, lambda)
assert(prev == null) { "Lambda with offset ${lambda.offset} already exists: $prev" }
if (lambda.needReification) {
lambda.reifiedTypeParametersUsages.mergeAll(reifiedTypeInliner.reifyInstructions(lambda.node.node))
}
rememberCapturedForDefaultLambda(lambda)
}
}
val reificationResult = reifiedTypeInliner.reifyInstructions(node)
generateClosuresBodies()
//through generation captured parameters will be added to invocationParamBuilder
putClosureParametersOnStack()
val reificationResult = reifiedTypeInliner.reifyInstructions(node)
val parameters = invocationParamBuilder.buildParameters()
@@ -221,13 +91,14 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
sourceCompiler, sourceCompiler.inlineCallSiteInfo, reifiedTypeInliner, typeParameterMappings
)
val sourceMapper = sourceCompiler.sourceMapper
val sourceInfo = sourceMapper.sourceInfo!!
val callSite = SourcePosition(codegen.lastLineNumber, sourceInfo.sourceFileName!!, sourceInfo.pathOrCleanFQN)
val inliner = MethodInliner(
node, parameters, info, FieldRemapper(null, null, parameters), isSameModule,
node, parameters, info, FieldRemapper(null, null, parameters), sourceCompiler.isCallInsideSameModuleAsCallee,
"Method inlining " + sourceCompiler.callElementText,
SourceMapCopier(sourceMapper, nodeAndSmap.classSMAP, callSite),
info.callSiteInfo, if (functionDescriptor.isInlineOnly()) InlineOnlySmapSkipper(codegen) else null,
info.callSiteInfo, if (isInlineOnly) InlineOnlySmapSkipper(codegen) else null,
!isInlinedToInlineFunInKotlinRuntime()
) //with captured
@@ -242,43 +113,45 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
val infos = MethodInliner.processReturns(adapter, sourceCompiler.getContextLabels(), null)
generateAndInsertFinallyBlocks(
adapter, infos, (remapper.remap(parameters.argsSizeOnStack + 1).value as StackValue.Local).index
adapter, infos, (remapper.remap(parameters.argsSizeOnStack).value as StackValue.Local).index
)
if (!sourceCompiler.isFinallyMarkerRequired()) {
if (!sourceCompiler.isFinallyMarkerRequired) {
removeFinallyMarkers(adapter)
}
// In case `codegen.v` is `<clinit>`, initializer for the `$assertionsDisabled` field
// In case `codegen.visitor` is `<clinit>`, initializer for the `$assertionsDisabled` field
// needs to be inserted before the code that actually uses it.
generateAssertFieldIfNeeded(info)
val shouldSpillStack = !canSkipStackSpillingOnInline(node)
val shouldSpillStack = node.requiresEmptyStackOnEntry()
if (shouldSpillStack) {
addInlineMarker(codegen.v, true)
addInlineMarker(codegen.visitor, true)
}
adapter.accept(MethodBodyVisitor(codegen.v))
adapter.accept(MethodBodyVisitor(codegen.visitor))
if (shouldSpillStack) {
addInlineMarker(codegen.v, false)
addInlineMarker(codegen.visitor, false)
}
return result
}
abstract fun extractDefaultLambdas(node: MethodNode): List<DefaultLambda>
abstract fun descriptorIsDeserialized(memberDescriptor: CallableMemberDescriptor): Boolean
protected inline fun <T> extractDefaultLambdas(
node: MethodNode, parameters: Map<Int, T>, block: ExtractedDefaultLambda.(T) -> DefaultLambda
): List<DefaultLambda> = expandMaskConditionsAndUpdateVariableNodes(
node, maskStartIndex, maskValues, methodHandleInDefaultMethodIndex, parameters.keys
).map {
it.block(parameters[it.offset]!!)
}
fun generateAndInsertFinallyBlocks(
private fun generateAndInsertFinallyBlocks(
intoNode: MethodNode,
insertPoints: List<MethodInliner.PointForExternalFinallyBlocks>,
offsetForFinallyLocalVar: Int
) {
if (!sourceCompiler.hasFinallyBlocks()) return
val extensionPoints = HashMap<AbstractInsnNode, MethodInliner.PointForExternalFinallyBlocks>()
for (insertPoint in insertPoints) {
extensionPoints.put(insertPoint.beforeIns, insertPoint)
}
val extensionPoints = insertPoints.associateBy { it.beforeIns }
val processor = DefaultProcessor(intoNode, offsetForFinallyLocalVar)
var curFinallyDepth = 0
@@ -292,46 +165,32 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
val extension = extensionPoints[curInstr]
if (extension != null) {
val start = Label()
var nextFreeLocalIndex = processor.nextFreeLocalIndex
for (local in processor.localVarsMetaInfo.currentIntervals) {
val size = Type.getType(local.node.desc).size
nextFreeLocalIndex = max(offsetForFinallyLocalVar + local.node.index + size, nextFreeLocalIndex)
}
val start = Label()
val finallyNode = createEmptyMethodNode()
finallyNode.visitLabel(start)
val finallyCodegen =
sourceCompiler.createCodegenForExternalFinallyBlockGenerationOnNonLocalReturn(finallyNode, curFinallyDepth)
val frameMap = finallyCodegen.frameMap
val mark = frameMap.mark()
var marker = -1
val intervals = processor.localVarsMetaInfo.currentIntervals
for (interval in intervals) {
marker = max(interval.node.index + 1, marker)
}
while (frameMap.currentSize < max(processor.nextFreeLocalIndex, offsetForFinallyLocalVar + marker)) {
frameMap.enterTemp(Type.INT_TYPE)
}
sourceCompiler.generateFinallyBlocksIfNeeded(
finallyCodegen, extension.returnType, extension.finallyIntervalEnd.label, extension.jumpTarget
val mark = codegen.frameMap.skipTo(nextFreeLocalIndex)
sourceCompiler.generateFinallyBlocks(
finallyNode, curFinallyDepth, extension.returnType, extension.finallyIntervalEnd.label, extension.jumpTarget
)
//Exception table for external try/catch/finally blocks will be generated in original codegen after exiting this method
mark.dropTo()
insertNodeBefore(finallyNode, intoNode, curInstr)
val splitBy = SimpleInterval(start.info as LabelNode, extension.finallyIntervalEnd)
processor.tryBlocksMetaInfo.splitAndRemoveCurrentIntervals(splitBy, true)
//processor.getLocalVarsMetaInfo().splitAndRemoveIntervalsFromCurrents(splitBy);
mark.dropTo()
processor.localVarsMetaInfo.splitAndRemoveCurrentIntervals(splitBy, true)
}
curInstr = curInstr.next
}
processor.substituteTryBlockNodes(intoNode)
//processor.substituteLocalVarTable(intoNode);
processor.substituteLocalVarTable(intoNode)
}
protected abstract fun generateAssertFieldIfNeeded(info: RootInliningContext)
@@ -347,90 +206,50 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
}
}
private fun generateClosuresBodies() {
for (info in expressionMap.values) {
if (info is LambdaInfo) {
info.generateLambdaBody(sourceCompiler, reifiedTypeInliner)
}
protected fun rememberClosure(parameterType: Type, index: Int, lambdaInfo: LambdaInfo) {
val closureInfo = invocationParamBuilder.addNextValueParameter(parameterType, true, null, index)
closureInfo.functionalArgument = lambdaInfo
expressionMap[closureInfo.index] = lambdaInfo
}
protected fun putCapturedToLocalVal(stackValue: StackValue, capturedParam: CapturedParamDesc, kotlinType: KotlinType?) {
val info = invocationParamBuilder.addCapturedParam(capturedParam, capturedParam.fieldName, false)
if (stackValue.isLocalWithNoBoxing(JvmKotlinType(info.type, kotlinType))) {
info.remapValue = stackValue
} else {
stackValue.put(info.type, kotlinType, codegen.visitor)
val local = StackValue.local(codegen.frameMap.enterTemp(info.type), info.type)
local.store(StackValue.onStack(info.type), codegen.visitor)
info.remapValue = local
info.isSynthetic = true
}
}
protected fun putArgumentOrCapturedToLocalVal(
jvmKotlinType: JvmKotlinType,
stackValue: StackValue,
capturedParamIndex: Int,
parameterIndex: Int,
kind: ValueKind
) {
val isDefaultParameter = kind === ValueKind.DEFAULT_PARAMETER
val jvmType = jvmKotlinType.type
val kotlinType = jvmKotlinType.kotlinType
if (!isDefaultParameter && shouldPutGeneralValue(jvmType, kotlinType, stackValue)) {
stackValue.put(jvmType, kotlinType, codegen.v)
protected fun putArgumentToLocalVal(jvmKotlinType: JvmKotlinType, stackValue: StackValue, parameterIndex: Int, kind: ValueKind) {
if (kind === ValueKind.DEFAULT_MASK || kind === ValueKind.METHOD_HANDLE_IN_DEFAULT) {
return processDefaultMaskOrMethodHandler(stackValue, kind)
}
if (!asFunctionInline && Type.VOID_TYPE !== jvmType) {
//TODO remap only inlinable closure => otherwise we could get a lot of problem
val couldBeRemapped = !shouldPutGeneralValue(jvmType, kotlinType, stackValue) && kind !== ValueKind.DEFAULT_PARAMETER
val remappedValue = if (couldBeRemapped) stackValue else null
val info: ParameterInfo
if (capturedParamIndex >= 0) {
val capturedParamInfoInLambda = activeLambda!!.capturedVars[capturedParamIndex]
info = invocationParamBuilder.addCapturedParam(capturedParamInfoInLambda, capturedParamInfoInLambda.fieldName, false)
info.remapValue = remappedValue
} else {
info = invocationParamBuilder.addNextValueParameter(jvmType, false, remappedValue, parameterIndex)
info.functionalArgument = when (kind) {
ValueKind.NON_INLINEABLE_ARGUMENT_FOR_INLINE_PARAMETER_CALLED_IN_SUSPEND ->
NonInlineableArgumentForInlineableParameterCalledInSuspend
ValueKind.NON_INLINEABLE_ARGUMENT_FOR_INLINE_SUSPEND_PARAMETER -> NonInlineableArgumentForInlineableSuspendParameter
else -> null
}
}
recordParameterValueInLocalVal(
false,
isDefaultParameter || kind === ValueKind.DEFAULT_LAMBDA_CAPTURED_PARAMETER,
info
)
val info = invocationParamBuilder.addNextValueParameter(jvmKotlinType.type, false, null, parameterIndex)
info.functionalArgument = when (kind) {
ValueKind.NON_INLINEABLE_ARGUMENT_FOR_INLINE_PARAMETER_CALLED_IN_SUSPEND ->
NonInlineableArgumentForInlineableParameterCalledInSuspend
ValueKind.NON_INLINEABLE_ARGUMENT_FOR_INLINE_SUSPEND_PARAMETER ->
NonInlineableArgumentForInlineableSuspendParameter
else -> null
}
}
protected fun recordParameterValueInLocalVal(
delayedWritingToLocals: Boolean,
skipStore: Boolean,
vararg infos: ParameterInfo
): Function0<Unit>? {
val index = IntArray(infos.size) { i ->
if (!infos[i].isSkippedOrRemapped) {
codegen.frameMap.enterTemp(infos[i].type)
} else -1
}
val possibleLazyTask = {
for (i in infos.indices.reversed()) {
val info = infos[i]
if (!info.isSkippedOrRemapped) {
val type = info.type
val local = StackValue.local(index[i], type)
if (!skipStore) {
local.store(StackValue.onStack(info.typeOnStack), codegen.v)
}
if (info is CapturedParamInfo) {
info.remapValue = local
info.isSynthetic = true
}
}
when {
kind === ValueKind.DEFAULT_PARAMETER ->
codegen.frameMap.enterTemp(info.type) // the inline function will put the value into this slot
stackValue.isLocalWithNoBoxing(jvmKotlinType) ->
info.remapValue = stackValue
else -> {
stackValue.put(info.type, jvmKotlinType.kotlinType, codegen.visitor)
codegen.visitor.store(codegen.frameMap.enterTemp(info.type), info.type)
}
}
if (delayedWritingToLocals) return possibleLazyTask
possibleLazyTask()
return null
}
private fun leaveTemps() {
invocationParamBuilder.listAllParams().asReversed().forEach { param ->
if (!param.isSkippedOrRemapped || CapturedParamInfo.isSynthetic(param)) {
@@ -439,45 +258,19 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
}
}
private fun putClosureParametersOnStack() {
for (next in expressionMap.values) {
//closure parameters for bounded callable references are generated inplace
if (next is LambdaInfo) {
if (next is ExpressionLambda && next.isBoundCallableReference) continue
putClosureParametersOnStack(next, null)
}
private fun rememberCapturedForDefaultLambda(defaultLambda: DefaultLambda) {
for (captured in defaultLambda.capturedVars) {
val info = invocationParamBuilder.addCapturedParam(captured, captured.fieldName, false)
info.remapValue = StackValue.local(codegen.frameMap.enterTemp(info.type), info.type)
info.isSynthetic = true
}
}
abstract protected fun putClosureParametersOnStack(next: LambdaInfo, functionReferenceReceiver: StackValue?)
protected fun rememberCapturedForDefaultLambda(defaultLambda: DefaultLambda) {
for ((paramIndex, captured) in defaultLambda.capturedVars.withIndex()) {
putArgumentOrCapturedToLocalVal(
JvmKotlinType(captured.type),
//HACK: actually parameter would be placed on stack in default function
// also see ValueKind.DEFAULT_LAMBDA_CAPTURED_PARAMETER check
StackValue.onStack(captured.type),
paramIndex,
paramIndex,
ValueKind.DEFAULT_LAMBDA_CAPTURED_PARAMETER
)
defaultLambda.parameterOffsetsInDefault.add(invocationParamBuilder.nextParameterOffset)
}
}
protected fun processDefaultMaskOrMethodHandler(value: StackValue, kind: ValueKind): Boolean {
if (kind !== ValueKind.DEFAULT_MASK && kind !== ValueKind.METHOD_HANDLE_IN_DEFAULT) {
return false
}
assert(value is StackValue.Constant) {
"Additional default method argument should be constant, but " + value
}
private fun processDefaultMaskOrMethodHandler(value: StackValue, kind: ValueKind) {
assert(value is StackValue.Constant) { "Additional default method argument should be constant, but $value" }
val constantValue = (value as StackValue.Constant).value
if (kind === ValueKind.DEFAULT_MASK) {
assert(constantValue is Int) { "Mask should be of Integer type, but " + constantValue }
assert(constantValue is Int) { "Mask should be of Integer type, but $constantValue" }
maskValues.add(constantValue as Int)
if (maskStartIndex == -1) {
maskStartIndex = invocationParamBuilder.listAllParams().sumOf {
@@ -488,228 +281,40 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
assert(constantValue == null) { "Additional method handle for default argument should be null, but " + constantValue!! }
methodHandleInDefaultMethodIndex = maskStartIndex + maskValues.size
}
return true
}
private fun trackLookup(functionOrAccessor: FunctionDescriptor) {
val functionOrAccessorName = jvmSignature.asmMethod.name
val lookupTracker = state.configuration.get(CommonConfigurationKeys.LOOKUP_TRACKER) ?: return
val location = sourceCompiler.lookupLocation.location ?: return
val position = if (lookupTracker.requiresPosition) location.position else Position.NO_POSITION
val classOrPackageFragment = functionOrAccessor.containingDeclaration
lookupTracker.record(
location.filePath,
position,
DescriptorUtils.getFqName(classOrPackageFragment).asString(),
ScopeKind.CLASSIFIER,
functionOrAccessorName
)
}
internal fun createInlineMethodNode(
callDefault: Boolean,
typeArguments: List<TypeParameterMarker>?,
typeSystem: TypeSystemCommonBackendContext
): SMAPAndMethodNode {
val intrinsic = generateInlineIntrinsic(state, functionDescriptor, typeArguments, typeSystem)
if (intrinsic != null) {
return SMAPAndMethodNode(intrinsic, createDefaultFakeSMAP())
}
var asmMethod = mapMethod(callDefault)
if (asmMethod.name.contains("-") &&
!state.configuration.getBoolean(JVMConfigurationKeys.USE_OLD_INLINE_CLASSES_MANGLING_SCHEME) &&
classFileContainsMethod(functionDescriptor, state, asmMethod) == false
) {
state.typeMapper.useOldManglingRulesForFunctionAcceptingInlineClass = true
asmMethod = mapMethod(callDefault)
state.typeMapper.useOldManglingRulesForFunctionAcceptingInlineClass = false
}
val directMember = getDirectMemberAndCallableFromObject(functionDescriptor)
if (!isBuiltInArrayIntrinsic(functionDescriptor) && !descriptorIsDeserialized(directMember)) {
val node = sourceCompiler.doCreateMethodNodeFromSource(functionDescriptor, jvmSignature, callDefault, asmMethod)
node.node.preprocessSuspendMarkers(forInline = true, keepFakeContinuation = false)
return node
}
return getCompiledMethodNodeInner(functionDescriptor, directMember, asmMethod, methodOwner, state, jvmSignature)
}
private fun mapMethod(callDefault: Boolean): Method =
if (callDefault) state.typeMapper.mapDefaultMethod(functionDescriptor, sourceCompiler.contextKind)
else mangleSuspendInlineFunctionAsmMethodIfNeeded(functionDescriptor, jvmSignature.asmMethod)
companion object {
private fun StackValue.isLocalWithNoBoxing(expected: JvmKotlinType): Boolean =
isPrimitive(expected.type) == isPrimitive(type) &&
!StackValue.requiresInlineClassBoxingOrUnboxing(type, kotlinType, expected.type, expected.kotlinType) &&
(this is StackValue.Local || isCapturedInlineParameter())
internal fun createSpecialInlineMethodNodeFromBinaries(functionDescriptor: FunctionDescriptor, state: GenerationState): MethodNode {
val directMember = getDirectMemberAndCallableFromObject(functionDescriptor)
assert(directMember is DescriptorWithContainerSource) {
"Function is not in binaries: $functionDescriptor"
}
assert(directMember is FunctionDescriptor && directMember.isOperator) {
"Operator function expected: $directMember"
}
val methodOwner = state.typeMapper.mapImplementationOwner(functionDescriptor)
val jvmSignature = state.typeMapper.mapSignatureWithGeneric(functionDescriptor, OwnerKind.IMPLEMENTATION)
val asmMethod = mangleSuspendInlineFunctionAsmMethodIfNeeded(functionDescriptor, jvmSignature.asmMethod)
return getCompiledMethodNodeInner(functionDescriptor, directMember, asmMethod, methodOwner, state, jvmSignature).node
private fun StackValue.isCapturedInlineParameter(): Boolean {
val field = if (this is StackValue.FieldForSharedVar) receiver else this
return field is StackValue.Field && field.descriptor is ParameterDescriptor &&
InlineUtil.isInlineParameter(field.descriptor) &&
InlineUtil.isInline(field.descriptor.containingDeclaration)
}
private fun getCompiledMethodNodeInner(
functionDescriptor: FunctionDescriptor,
directMember: CallableMemberDescriptor,
asmMethod: Method,
methodOwner: Type,
state: GenerationState,
jvmSignature: JvmMethodSignature
): SMAPAndMethodNode {
val methodId = MethodId(methodOwner.internalName, asmMethod)
// Stack spilling before inline function call is required if the inlined bytecode has:
// 1. try-catch blocks - otherwise the stack spilling before and after them will not be correct;
// 2. suspension points - again, the stack spilling around them is otherwise wrong;
// 3. loops - OpenJDK cannot JIT-optimize between loop iterations if the stack is not empty.
// Instead of checking for loops precisely, we just check if there are any backward jumps -
// that is, a jump from instruction #i to instruction #j where j < i.
private fun MethodNode.requiresEmptyStackOnEntry(): Boolean = tryCatchBlocks.isNotEmpty() ||
instructions.toArray().any { isBeforeSuspendMarker(it) || isBeforeInlineSuspendMarker(it) || isBackwardsJump(it) }
val resultInCache = state.inlineCache.methodNodeById.getOrPut(methodId) {
val result = doCreateMethodNodeFromCompiled(directMember, state, asmMethod)
?: if (functionDescriptor.isSuspend)
doCreateMethodNodeFromCompiled(directMember, state, jvmSignature.asmMethod)
else
null
result ?:
throw IllegalStateException("Couldn't obtain compiled function body for $functionDescriptor")
}
return SMAPAndMethodNode(cloneMethodNode(resultInCache.node), resultInCache.classSMAP)
private fun MethodNode.isBackwardsJump(insn: AbstractInsnNode): Boolean = when (insn) {
is JumpInsnNode -> isBackwardsJump(insn, insn.label)
is LookupSwitchInsnNode ->
insn.dflt?.let { to -> isBackwardsJump(insn, to) } == true || insn.labels.any { to -> isBackwardsJump(insn, to) }
is TableSwitchInsnNode ->
insn.dflt?.let { to -> isBackwardsJump(insn, to) } == true || insn.labels.any { to -> isBackwardsJump(insn, to) }
else -> false
}
private fun createDefaultFakeSMAP() = SMAPParser.parseOrCreateDefault(null, null, "fake", -1, -1)
// For suspend inline functions we generate two methods:
// 1) normal one: with state machine to call directly
// 2) for inliner: with mangled name and without state machine
private fun mangleSuspendInlineFunctionAsmMethodIfNeeded(functionDescriptor: FunctionDescriptor, asmMethod: Method): Method {
if (!functionDescriptor.isSuspend) return asmMethod
return Method("${asmMethod.name}$FOR_INLINE_SUFFIX", asmMethod.descriptor)
}
private fun getDirectMemberAndCallableFromObject(functionDescriptor: FunctionDescriptor): CallableMemberDescriptor {
val directMember = JvmCodegenUtil.getDirectMember(functionDescriptor)
return (directMember as? ImportedFromObjectCallableDescriptor<*>)?.callableFromObject ?: directMember
}
private fun doCreateMethodNodeFromCompiled(
callableDescriptor: CallableMemberDescriptor,
state: GenerationState,
asmMethod: Method
): SMAPAndMethodNode? {
if (isBuiltInArrayIntrinsic(callableDescriptor)) {
val body = when {
callableDescriptor is FictitiousArrayConstructor -> IntrinsicArrayConstructors.generateArrayConstructorBody(asmMethod)
callableDescriptor.name.asString() == "emptyArray" -> IntrinsicArrayConstructors.generateEmptyArrayBody(asmMethod)
callableDescriptor.name.asString() == "arrayOf" -> IntrinsicArrayConstructors.generateArrayOfBody(asmMethod)
else -> throw UnsupportedOperationException("Not an array intrinsic: $callableDescriptor")
}
return SMAPAndMethodNode(body, SMAP(listOf()))
}
assert(callableDescriptor is DescriptorWithContainerSource) { "Not a deserialized function or proper: $callableDescriptor" }
val containingClasses =
KotlinTypeMapper.getContainingClassesForDeserializedCallable(callableDescriptor as DescriptorWithContainerSource)
val containerId = containingClasses.implClassId
val bytes = state.inlineCache.classBytes.getOrPut(containerId) {
findVirtualFile(state, containerId)?.contentsToByteArray()
?: throw IllegalStateException("Couldn't find declaration file for $containerId")
}
val classType = AsmUtil.asmTypeByClassId(containerId)
val methodNode = getMethodNode(bytes, asmMethod.name, asmMethod.descriptor, classType)
if (methodNode == null && requiresFunctionNameManglingForReturnType(callableDescriptor)) {
val nameWithoutManglingSuffix = asmMethod.name.stripManglingSuffixOrNull()
if (nameWithoutManglingSuffix != null) {
val methodWithoutMangling = getMethodNode(bytes, nameWithoutManglingSuffix, asmMethod.descriptor, classType)
if (methodWithoutMangling != null) return methodWithoutMangling
}
return getMethodNode(bytes, "$nameWithoutManglingSuffix-impl", asmMethod.descriptor, classType)
}
return methodNode
}
private fun String.stripManglingSuffixOrNull(): String? {
val dashIndex = indexOf('-')
return if (dashIndex < 0) null else substring(0, dashIndex)
}
private fun isBuiltInArrayIntrinsic(callableDescriptor: CallableMemberDescriptor): Boolean {
if (callableDescriptor is FictitiousArrayConstructor) return true
val name = callableDescriptor.name.asString()
return (name == "arrayOf" || name == "emptyArray") && callableDescriptor.containingDeclaration.let { container ->
container is PackageFragmentDescriptor && container.fqName == StandardNames.BUILT_INS_PACKAGE_FQ_NAME
}
}
/*descriptor is null for captured vars*/
private fun shouldPutGeneralValue(type: Type, kotlinType: KotlinType?, stackValue: StackValue): Boolean {
//remap only inline functions (and maybe non primitives)
//TODO - clean assertion and remapping logic
// don't remap boxing/unboxing primitives
if (isPrimitive(type) != isPrimitive(stackValue.type)) {
return true
}
// don't remap boxing/unboxing inline classes
if (StackValue.requiresInlineClassBoxingOrUnboxing(stackValue.type, stackValue.kotlinType, type, kotlinType)) {
return true
}
if (stackValue is StackValue.Local) {
return false
}
var field = stackValue
if (stackValue is StackValue.FieldForSharedVar) {
field = stackValue.receiver
}
//check that value corresponds to captured inlining parameter
if (field is StackValue.Field) {
val varDescriptor = field.descriptor
//check that variable is inline function parameter
return !(varDescriptor is ParameterDescriptor &&
InlineUtil.isInlineParameter(varDescriptor) &&
InlineUtil.isInline(varDescriptor.containingDeclaration))
}
return true
}
fun getDeclarationLabels(lambdaOrFun: PsiElement?, descriptor: DeclarationDescriptor): Set<String> {
val result = HashSet<String>()
if (lambdaOrFun != null) {
val label = LabelResolver.getLabelNameIfAny(lambdaOrFun)
if (label != null) {
result.add(label.asString())
}
}
if (!isFunctionLiteral(descriptor)) {
if (!descriptor.name.isSpecial) {
result.add(descriptor.name.asString())
}
result.add(FIRST_FUN_LABEL)
}
return result
}
private fun MethodNode.isBackwardsJump(from: AbstractInsnNode, to: LabelNode): Boolean =
instructions.indexOf(to) < instructions.indexOf(from)
}
}
val BaseExpressionCodegen.v: InstructionAdapter
get() = visitor

View File

@@ -15,15 +15,13 @@ import org.jetbrains.kotlin.resolve.inline.InlineUtil
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature
import org.jetbrains.org.objectweb.asm.Label
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.tree.MethodNode
class InlineCodegenForDefaultBody(
private val function: FunctionDescriptor,
codegen: ExpressionCodegen,
val state: GenerationState,
private val methodOwner: Type,
private val jvmSignature: JvmMethodSignature,
private val sourceCompilerForInline: SourceCompilerForInline
private val sourceCompilerForInline: PsiSourceCompilerForInline
) : CallGenerator {
private val sourceMapper: SourceMapper = codegen.parentCodegen.orCreateSourceMapper
@@ -39,32 +37,22 @@ class InlineCodegenForDefaultBody(
}
override fun genCallInner(callableMethod: Callable, resolvedCall: ResolvedCall<*>?, callDefault: Boolean, codegen: ExpressionCodegen) {
val nodeAndSmap = PsiInlineCodegen(
codegen, state, function, methodOwner, jvmSignature, TypeParameterMappings(), sourceCompilerForInline
).createInlineMethodNode(
callDefault, null, codegen.typeSystem
)
val childSourceMapper = SourceMapCopier(sourceMapper, nodeAndSmap.classSMAP)
val node = nodeAndSmap.node
val transformedMethod = MethodNode(
node.access,
node.name,
node.desc,
node.signature,
node.exceptions.toTypedArray()
)
assert(!callDefault) { "inlining default stub into another default stub" }
val (node, smap) = sourceCompilerForInline.compileInlineFunction(jvmSignature)
val childSourceMapper = SourceMapCopier(sourceMapper, smap)
val argsSize =
(Type.getArgumentsAndReturnSizes(jvmSignature.asmMethod.descriptor) ushr 2) - if (callableMethod.isStaticCall()) 1 else 0
node.accept(object : InlineAdapter(transformedMethod, 0, childSourceMapper) {
override fun visitLocalVariable(name: String, desc: String, signature: String?, start: Label, end: Label, index: Int) {
val startLabel = if (index < argsSize) methodStartLabel else start
super.visitLocalVariable(name, desc, signature, startLabel, end, index)
}
})
// `$default` is only for Kotlin use so it has no `$$forInline` version - this *is* what the inliner will use.
node.preprocessSuspendMarkers(forInline = true, keepFakeContinuation = false)
node.accept(object : MethodBodyVisitor(codegen.visitor) {
// The LVT was not generated at all, so move the start of parameters to the start of the method.
override fun visitLocalVariable(name: String, desc: String, signature: String?, start: Label, end: Label, index: Int) =
super.visitLocalVariable(name, desc, signature, if (index < argsSize) methodStartLabel else start, end, index)
transformedMethod.accept(MethodBodyVisitor(codegen.visitor))
override fun visitLineNumber(line: Int, start: Label) =
super.visitLineNumber(childSourceMapper.mapLineNumber(line), start)
})
}
override fun genValueAndPut(
@@ -85,7 +73,7 @@ class InlineCodegenForDefaultBody(
throw UnsupportedOperationException("Shouldn't be called")
}
override fun processAndPutHiddenParameters(justProcess: Boolean) {
override fun processHiddenParameters() {
throw UnsupportedOperationException("Shouldn't be called")
}

View File

@@ -5,35 +5,14 @@
package org.jetbrains.kotlin.codegen.inline
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.codegen.DescriptorAsmUtil
import org.jetbrains.kotlin.codegen.PropertyReferenceCodegen
import org.jetbrains.kotlin.codegen.StackValue
import org.jetbrains.kotlin.codegen.binding.CalculatedClosure
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
import org.jetbrains.kotlin.coroutines.isSuspendLambda
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.psi.KtCallableReferenceExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCallWithAssert
import org.jetbrains.kotlin.resolve.jvm.AsmTypes.*
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.org.objectweb.asm.*
import org.jetbrains.org.objectweb.asm.ClassReader
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.Label
import org.jetbrains.org.objectweb.asm.commons.Method
import org.jetbrains.org.objectweb.asm.tree.FieldInsnNode
import kotlin.properties.Delegates
interface FunctionalArgument
@@ -47,7 +26,9 @@ abstract class LambdaInfo(@JvmField val isCrossInline: Boolean) : FunctionalArgu
abstract val invokeMethod: Method
abstract val invokeMethodDescriptor: FunctionDescriptor
abstract val invokeMethodParameters: List<KotlinType?>
abstract val invokeMethodReturnType: KotlinType?
abstract val capturedVars: List<CapturedParamDesc>
@@ -56,7 +37,7 @@ abstract class LambdaInfo(@JvmField val isCrossInline: Boolean) : FunctionalArgu
lateinit var node: SMAPAndMethodNode
abstract fun generateLambdaBody(sourceCompiler: SourceCompilerForInline, reifiedTypeInliner: ReifiedTypeInliner<*>)
val reifiedTypeParametersUsages = ReifiedTypeParametersUsages()
open val hasDispatchReceiver = true
@@ -67,7 +48,7 @@ abstract class LambdaInfo(@JvmField val isCrossInline: Boolean) : FunctionalArgu
val field = remapper.findField(FieldInsnNode(0, info.containingLambdaName, info.fieldName, ""))
?: error("Captured field not found: " + info.containingLambdaName + "." + info.fieldName)
val recapturedParamInfo = builder.addCapturedParam(field, info.fieldName)
if (this is ExpressionLambda && isCapturedSuspend(info)) {
if (info.isSuspend) {
recapturedParamInfo.functionalArgument = NonInlineableArgumentForInlineableParameterCalledInSuspend
}
}
@@ -75,14 +56,9 @@ abstract class LambdaInfo(@JvmField val isCrossInline: Boolean) : FunctionalArgu
return builder.buildParameters()
}
companion object {
fun LambdaInfo.getCapturedParamInfo(descriptor: EnclosedValueDescriptor): CapturedParamDesc {
return capturedParamDesc(descriptor.fieldName, descriptor.type)
}
fun LambdaInfo.capturedParamDesc(fieldName: String, fieldType: Type): CapturedParamDesc {
return CapturedParamDesc(lambdaClassType, fieldName, fieldType)
fun LambdaInfo.capturedParamDesc(fieldName: String, fieldType: Type, isSuspend: Boolean): CapturedParamDesc {
return CapturedParamDesc(lambdaClassType, fieldName, fieldType, isSuspend)
}
}
}
@@ -90,114 +66,76 @@ abstract class LambdaInfo(@JvmField val isCrossInline: Boolean) : FunctionalArgu
object NonInlineableArgumentForInlineableParameterCalledInSuspend : FunctionalArgument
object NonInlineableArgumentForInlineableSuspendParameter : FunctionalArgument
class PsiDefaultLambda(
lambdaClassType: Type,
capturedArgs: Array<Type>,
parameterDescriptor: ValueParameterDescriptor,
offset: Int,
needReification: Boolean
) : DefaultLambda(lambdaClassType, capturedArgs, parameterDescriptor, offset, needReification) {
override fun mapAsmSignature(sourceCompiler: SourceCompilerForInline): Method {
return sourceCompiler.state.typeMapper.mapSignatureSkipGeneric(invokeMethodDescriptor).asmMethod
abstract class ExpressionLambda(isCrossInline: Boolean) : LambdaInfo(isCrossInline) {
fun generateLambdaBody(sourceCompiler: SourceCompilerForInline) {
node = sourceCompiler.generateLambdaBody(this, reifiedTypeParametersUsages)
node.node.preprocessSuspendMarkers(forInline = true, keepFakeContinuation = false)
}
override fun findInvokeMethodDescriptor(): FunctionDescriptor =
parameterDescriptor.type.memberScope
.getContributedFunctions(OperatorNameConventions.INVOKE, NoLookupLocation.FROM_BACKEND)
.single()
}
abstract class DefaultLambda(
override val lambdaClassType: Type,
private val capturedArgs: Array<Type>,
val parameterDescriptor: ValueParameterDescriptor,
final override val lambdaClassType: Type,
capturedArgs: Array<Type>,
isCrossinline: Boolean,
val offset: Int,
val needReification: Boolean
) : LambdaInfo(parameterDescriptor.isCrossinline) {
val needReification: Boolean,
sourceCompiler: SourceCompilerForInline
) : LambdaInfo(isCrossinline) {
final override val isSuspend
get() = false // TODO: it should probably be true sometimes, but it never was
final override val isBoundCallableReference: Boolean
final override val capturedVars: List<CapturedParamDesc>
final override var isBoundCallableReference by Delegates.notNull<Boolean>()
private set
final override val invokeMethod: Method
get() = Method(node.node.name, node.node.desc)
val parameterOffsetsInDefault: MutableList<Int> = arrayListOf()
val originalBoundReceiverType: Type?
final override lateinit var invokeMethod: Method
private set
protected val isPropertyReference: Boolean
protected val isFunctionReference: Boolean
override lateinit var invokeMethodDescriptor: FunctionDescriptor
final override lateinit var capturedVars: List<CapturedParamDesc>
private set
var originalBoundReceiverType: Type? = null
private set
override val isSuspend = parameterDescriptor.isSuspendLambda
override fun generateLambdaBody(sourceCompiler: SourceCompilerForInline, reifiedTypeInliner: ReifiedTypeInliner<*>) {
val classBytes = loadClassBytesByInternalName(sourceCompiler.state, lambdaClassType.internalName)
val classReader = ClassReader(classBytes)
var isPropertyReference = false
var isFunctionReference = false
classReader.accept(object : ClassVisitor(Opcodes.API_VERSION) {
override fun visit(
version: Int,
access: Int,
name: String,
signature: String?,
superName: String?,
interfaces: Array<out String>?
) {
isPropertyReference = superName in PROPERTY_REFERENCE_SUPER_CLASSES
isFunctionReference = superName == FUNCTION_REFERENCE.internalName || superName == FUNCTION_REFERENCE_IMPL.internalName
super.visit(version, access, name, signature, superName, interfaces)
}
}, ClassReader.SKIP_CODE or ClassReader.SKIP_FRAMES or ClassReader.SKIP_DEBUG)
invokeMethodDescriptor = findInvokeMethodDescriptor().let {
//property reference generates erased 'get' method
if (isPropertyReference) it.original else it
}
val descriptor = Type.getMethodDescriptor(Type.VOID_TYPE, *capturedArgs)
val constructor = getMethodNode(classBytes, "<init>", descriptor, lambdaClassType)?.node
init {
val classBytes = loadClass(sourceCompiler)
val superName = ClassReader(classBytes).superName
isPropertyReference = superName in PROPERTY_REFERENCE_SUPER_CLASSES
isFunctionReference = superName == FUNCTION_REFERENCE.internalName || superName == FUNCTION_REFERENCE_IMPL.internalName
val constructorDescriptor = Type.getMethodDescriptor(Type.VOID_TYPE, *capturedArgs)
val constructor = getMethodNode(classBytes, "<init>", constructorDescriptor, lambdaClassType)?.node
assert(constructor != null || capturedArgs.isEmpty()) {
"Can't find non-default constructor <init>$descriptor for default lambda $lambdaClassType"
"Can't find non-default constructor <init>$constructorDescriptor for default lambda $lambdaClassType"
}
// This only works for primitives but not inline classes, since information about the Kotlin type of the bound
// receiver is not present anywhere. This is why with JVM_IR the constructor argument of bound references
// is already `Object`, and this field is never used.
originalBoundReceiverType =
capturedArgs.singleOrNull()?.takeIf { (isFunctionReference || isPropertyReference) && AsmUtil.isPrimitive(it) }
capturedVars =
if (isFunctionReference || isPropertyReference)
constructor?.desc?.let { Type.getArgumentTypes(it) }?.singleOrNull()?.let {
originalBoundReceiverType = it
listOf(capturedParamDesc(AsmUtil.RECEIVER_PARAMETER_NAME, it.boxReceiverForBoundReference()))
capturedArgs.singleOrNull()?.let {
listOf(capturedParamDesc(AsmUtil.RECEIVER_PARAMETER_NAME, AsmUtil.boxType(it), isSuspend = false))
} ?: emptyList()
else
constructor?.findCapturedFieldAssignmentInstructions()?.map { fieldNode ->
capturedParamDesc(fieldNode.name, Type.getType(fieldNode.desc))
capturedParamDesc(fieldNode.name, Type.getType(fieldNode.desc), isSuspend = false)
}?.toList() ?: emptyList()
isBoundCallableReference = (isFunctionReference || isPropertyReference) && capturedVars.isNotEmpty()
val methodName = (if (isPropertyReference) OperatorNameConventions.GET else OperatorNameConventions.INVOKE).asString()
val signature = mapAsmSignature(sourceCompiler)
node = getMethodNode(classBytes, methodName, signature.descriptor, lambdaClassType, signatureAmbiguity = true)
?: error("Can't find method '$methodName$signature' in '${classReader.className}'")
invokeMethod = Method(node.node.name, node.node.desc)
if (needReification) {
//nested classes could also require reification
reifiedTypeInliner.reifyInstructions(node.node)
}
}
protected abstract fun mapAsmSignature(sourceCompiler: SourceCompilerForInline): Method
private fun loadClass(sourceCompiler: SourceCompilerForInline): ByteArray =
sourceCompiler.state.inlineCache.classBytes.getOrPut(lambdaClassType.internalName) {
loadClassBytesByInternalName(sourceCompiler.state, lambdaClassType.internalName)
}
protected abstract fun findInvokeMethodDescriptor(): FunctionDescriptor
// Returns whether the loaded invoke is erased, i.e. the name equals the fallback and all types are `Object`.
protected fun loadInvoke(sourceCompiler: SourceCompilerForInline, erasedName: String, actualMethod: Method): Boolean {
val classBytes = loadClass(sourceCompiler)
// TODO: `signatureAmbiguity = true` ignores the argument types from `invokeMethod` and only looks at the count.
node = getMethodNode(classBytes, actualMethod.name, actualMethod.descriptor, lambdaClassType, signatureAmbiguity = true)
?: getMethodNode(classBytes, erasedName, actualMethod.descriptor, lambdaClassType, signatureAmbiguity = true)
?: error("Can't find method '$actualMethod' in '${lambdaClassType.internalName}'")
return invokeMethod.run { name == erasedName && returnType == OBJECT_TYPE && argumentTypes.all { it == OBJECT_TYPE } }
}
private companion object {
val PROPERTY_REFERENCE_SUPER_CLASSES =
@@ -208,131 +146,3 @@ abstract class DefaultLambda(
.mapTo(HashSet(), Type::getInternalName)
}
}
internal fun Type.boxReceiverForBoundReference() =
AsmUtil.boxType(this)
internal fun Type.boxReceiverForBoundReference(kotlinType: KotlinType, typeMapper: KotlinTypeMapper) =
DescriptorAsmUtil.boxType(this, kotlinType, typeMapper)
abstract class ExpressionLambda(isCrossInline: Boolean) : LambdaInfo(isCrossInline) {
override fun generateLambdaBody(sourceCompiler: SourceCompilerForInline, reifiedTypeInliner: ReifiedTypeInliner<*>) {
node = sourceCompiler.generateLambdaBody(this)
node.node.preprocessSuspendMarkers(forInline = true, keepFakeContinuation = false)
}
abstract fun getInlineSuspendLambdaViewDescriptor(): FunctionDescriptor
abstract fun isCapturedSuspend(desc: CapturedParamDesc): Boolean
}
class PsiExpressionLambda(
expression: KtExpression,
private val typeMapper: KotlinTypeMapper,
private val languageVersionSettings: LanguageVersionSettings,
isCrossInline: Boolean,
override val isBoundCallableReference: Boolean
) : ExpressionLambda(isCrossInline) {
override val lambdaClassType: Type
override val invokeMethod: Method
override val invokeMethodDescriptor: FunctionDescriptor
val classDescriptor: ClassDescriptor
val propertyReferenceInfo: PropertyReferenceInfo?
val functionWithBodyOrCallableReference: KtExpression = (expression as? KtLambdaExpression)?.functionLiteral ?: expression
override val returnLabels: Map<String, Label?>
override val isSuspend: Boolean
var closure: CalculatedClosure
private set
init {
val bindingContext = typeMapper.bindingContext
val function =
bindingContext.get<PsiElement, SimpleFunctionDescriptor>(BindingContext.FUNCTION, functionWithBodyOrCallableReference)
if (function == null && expression is KtCallableReferenceExpression) {
val variableDescriptor =
bindingContext.get(BindingContext.VARIABLE, functionWithBodyOrCallableReference) as? VariableDescriptorWithAccessors
?: throw AssertionError("Reference expression not resolved to variable descriptor with accessors: ${expression.getText()}")
classDescriptor = bindingContext.get(CLASS_FOR_CALLABLE, variableDescriptor)
?: throw IllegalStateException("Class for callable not found: $variableDescriptor\n${expression.text}")
lambdaClassType = typeMapper.mapClass(classDescriptor)
val getFunction = PropertyReferenceCodegen.findGetFunction(variableDescriptor)
invokeMethodDescriptor = PropertyReferenceCodegen.createFakeOpenDescriptor(getFunction, classDescriptor)
val resolvedCall = expression.callableReference.getResolvedCallWithAssert(bindingContext)
propertyReferenceInfo = PropertyReferenceInfo(
resolvedCall.resultingDescriptor as VariableDescriptor, getFunction
)
} else {
propertyReferenceInfo = null
invokeMethodDescriptor = function ?: throw AssertionError("Function is not resolved to descriptor: " + expression.text)
classDescriptor = bindingContext.get(CLASS_FOR_CALLABLE, invokeMethodDescriptor)
?: throw IllegalStateException("Class for invoke method not found: $invokeMethodDescriptor\n${expression.text}")
lambdaClassType = asmTypeForAnonymousClass(bindingContext, invokeMethodDescriptor)
}
bindingContext.get<ClassDescriptor, MutableClosure>(CLOSURE, classDescriptor).let {
assert(it != null) { "Closure for lambda should be not null " + expression.text }
closure = it!!
}
returnLabels = InlineCodegen.getDeclarationLabels(expression, invokeMethodDescriptor).associateWith { null }
invokeMethod = typeMapper.mapAsmMethod(invokeMethodDescriptor)
isSuspend = invokeMethodDescriptor.isSuspend
}
override val capturedVars: List<CapturedParamDesc> by lazy {
arrayListOf<CapturedParamDesc>().apply {
val captureThis = closure.capturedOuterClassDescriptor
if (captureThis != null) {
val kotlinType = captureThis.defaultType
val type = typeMapper.mapType(kotlinType)
val descriptor = EnclosedValueDescriptor(
AsmUtil.CAPTURED_THIS_FIELD, null,
StackValue.field(type, lambdaClassType, AsmUtil.CAPTURED_THIS_FIELD, false, StackValue.LOCAL_0),
type, kotlinType
)
add(getCapturedParamInfo(descriptor))
}
val capturedReceiver = closure.capturedReceiverFromOuterContext
if (capturedReceiver != null) {
val type = typeMapper.mapType(capturedReceiver).let {
if (isBoundCallableReference) it.boxReceiverForBoundReference() else it
}
val fieldName = closure.getCapturedReceiverFieldName(typeMapper.bindingContext, languageVersionSettings)
val descriptor = EnclosedValueDescriptor(
fieldName, null,
StackValue.field(type, capturedReceiver, lambdaClassType, fieldName, false, StackValue.LOCAL_0),
type, capturedReceiver
)
add(getCapturedParamInfo(descriptor))
}
closure.captureVariables.values.forEach { descriptor ->
add(getCapturedParamInfo(descriptor))
}
}
}
val isPropertyReference: Boolean
get() = propertyReferenceInfo != null
override fun getInlineSuspendLambdaViewDescriptor(): FunctionDescriptor {
return getOrCreateJvmSuspendFunctionView(
invokeMethodDescriptor,
languageVersionSettings.isReleaseCoroutines(),
typeMapper.bindingContext
)
}
override fun isCapturedSuspend(desc: CapturedParamDesc): Boolean =
isCapturedSuspendLambda(closure, desc.fieldName, typeMapper.bindingContext)
}

View File

@@ -9,7 +9,6 @@ import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.coroutines.continuationAsmType
import org.jetbrains.kotlin.codegen.inline.FieldRemapper.Companion.foldName
import org.jetbrains.kotlin.codegen.inline.coroutines.CoroutineTransformer
import org.jetbrains.kotlin.codegen.inline.coroutines.isSuspendLambdaCapturedByOuterObjectOrLambda
import org.jetbrains.kotlin.codegen.inline.coroutines.markNoinlineLambdaIfSuspend
import org.jetbrains.kotlin.codegen.inline.coroutines.surroundInvokesWithSuspendMarkersIfNeeded
import org.jetbrains.kotlin.codegen.optimization.ApiVersionCallsPreprocessingMethodTransformer
@@ -23,13 +22,9 @@ import org.jetbrains.kotlin.codegen.optimization.fixStack.top
import org.jetbrains.kotlin.codegen.optimization.nullCheck.isCheckParameterIsNotNull
import org.jetbrains.kotlin.codegen.pseudoInsns.PseudoInsn
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ParameterDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.resolve.jvm.AsmTypes.OBJECT_TYPE
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.SmartList
import org.jetbrains.kotlin.utils.SmartSet
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
@@ -233,52 +228,34 @@ class MethodInliner(
return
}
// in case of inlining suspend lambda reference as ordinary parameter of inline function:
// suspend fun foo (...) ...
// inline fun inlineMe(c: (...) -> ...) ...
// builder {
// inlineMe(::foo)
// }
// we should create additional parameter for continuation.
var coroutineDesc = desc
val actualInvokeDescriptor: FunctionDescriptor
if (info.isSuspend) {
actualInvokeDescriptor = (info as ExpressionLambda).getInlineSuspendLambdaViewDescriptor()
val parametersSize = actualInvokeDescriptor.valueParameters.size +
(if (actualInvokeDescriptor.extensionReceiverParameter != null) 1 else 0)
// And here we expect invoke(...Ljava/lang/Object;) be replaced with invoke(...Lkotlin/coroutines/Continuation;)
// if this does not happen, insert fake continuation, since we could not have one yet.
val argumentTypes = Type.getArgumentTypes(desc)
if (argumentTypes.size != parametersSize &&
// But do not add it in IR. In IR we already have lowered lambdas with additional parameter, while in Old BE we don't.
!inliningContext.root.state.isIrBackend
) {
val nullableAnyType = inliningContext.state.module.builtIns.nullableAnyType
val expectedParameters = info.invokeMethod.argumentTypes
val expectedKotlinParameters = info.invokeMethodParameters
val argumentCount = Type.getArgumentTypes(desc).size.let {
if (!inliningContext.root.state.isIrBackend && info.isSuspend && it < expectedParameters.size) {
// Inlining suspend lambda into a function that takes a non-suspend lambda.
// In the IR backend, this cannot happen as inline lambdas are not lowered.
addFakeContinuationMarker(this)
coroutineDesc = Type.getMethodDescriptor(Type.getReturnType(desc), *argumentTypes, AsmTypes.OBJECT_TYPE)
}
} else {
actualInvokeDescriptor = info.invokeMethodDescriptor
it + 1
} else it
}
assert(argumentCount == expectedParameters.size && argumentCount == expectedKotlinParameters.size) {
"inconsistent lambda arguments: $argumentCount on stack, ${expectedParameters.size} expected, " +
"${expectedKotlinParameters.size} Kotlin types"
}
val valueParameters =
listOfNotNull(actualInvokeDescriptor.extensionReceiverParameter) + actualInvokeDescriptor.valueParameters
val erasedInvokeFunction = ClosureCodegen.getErasedInvokeFunction(actualInvokeDescriptor)
val invokeParameters = erasedInvokeFunction.valueParameters
val valueParamShift = max(nextLocalIndex, markerShift)//NB: don't inline cause it changes
val parameterTypesFromDesc = info.invokeMethod.argumentTypes
putStackValuesIntoLocalsForLambdaOnInvoke(
listOf(*parameterTypesFromDesc), valueParameters, invokeParameters, valueParamShift, this, coroutineDesc
)
if (parameterTypesFromDesc.isEmpty()) {
// There won't be no parameters processing and line call can be left without actual instructions.
// Note: if function is called on the line with other instructions like 1 + foo(), 'nop' will still be generated.
visitInsn(Opcodes.NOP)
var valueParamShift = max(nextLocalIndex, markerShift) + expectedParameters.sumOf { it.size }
for (index in argumentCount - 1 downTo 0) {
val type = expectedParameters[index]
StackValue.coerce(AsmTypes.OBJECT_TYPE, nullableAnyType, type, expectedKotlinParameters[index], this)
valueParamShift -= type.size
store(valueParamShift, type)
}
if (expectedParameters.isEmpty()) {
nop() // add something for a line number to bind onto
}
inlineOnlySmapSkipper?.onInlineLambdaStart(remappingMethodAdapter, info, sourceMapper.parent)
inlineOnlySmapSkipper?.onInlineLambdaStart(remappingMethodAdapter, info.node.node, sourceMapper.parent)
addInlineMarker(this, true)
val lambdaParameters = info.addAllParameters(nodeRemapper)
@@ -303,10 +280,9 @@ class MethodInliner(
val lambdaResult = inliner.doInline(localVariablesSorter, varRemapper, true, info.returnLabels, invokeCall.finallyDepthShift)
result.mergeWithNotChangeInfo(lambdaResult)
result.reifiedTypeParametersUsages.mergeAll(lambdaResult.reifiedTypeParametersUsages)
result.reifiedTypeParametersUsages.mergeAll(info.reifiedTypeParametersUsages)
StackValue
.onStack(info.invokeMethod.returnType, info.invokeMethodDescriptor.returnType)
.put(OBJECT_TYPE, erasedInvokeFunction.returnType, this)
StackValue.coerce(info.invokeMethod.returnType, info.invokeMethodReturnType, OBJECT_TYPE, nullableAnyType, this)
setLambdaInlining(false)
addInlineMarker(this, false)
inlineOnlySmapSkipper?.onInlineLambdaEnd(remappingMethodAdapter)
@@ -447,10 +423,10 @@ class MethodInliner(
if (DEFAULT_LAMBDA_FAKE_CALL == owner) {
val index = name.substringAfter(DEFAULT_LAMBDA_FAKE_CALL).toInt()
val lambda = getFunctionalArgumentIfExists(index) as DefaultLambda
lambda.parameterOffsetsInDefault.zip(lambda.capturedVars).asReversed().forEach { (_, captured) ->
val originalBoundReceiverType = lambda.originalBoundReceiverType
if (lambda.isBoundCallableReference && AsmUtil.isPrimitive(originalBoundReceiverType)) {
StackValue.onStack(originalBoundReceiverType!!).put(captured.type, InstructionAdapter(this))
for (captured in lambda.capturedVars.asReversed()) {
lambda.originalBoundReceiverType?.let {
// The receiver is the only captured value; it needs to be boxed.
StackValue.onStack(it).put(captured.type, InstructionAdapter(this))
}
super.visitFieldInsn(
Opcodes.PUTSTATIC,
@@ -847,7 +823,7 @@ class MethodInliner(
getFunctionalArgumentIfExists((insnNode as VarInsnNode).`var`)
insnNode is FieldInsnNode && insnNode.name.startsWith(CAPTURED_FIELD_FOLD_PREFIX) ->
findCapturedField(insnNode, nodeRemapper).functionalArgument
insnNode is FieldInsnNode && insnNode.isSuspendLambdaCapturedByOuterObjectOrLambda(inliningContext) ->
insnNode is FieldInsnNode && inliningContext.root.sourceCompilerForInline.isSuspendLambdaCapturedByOuterObjectOrLambda(insnNode.name) ->
NonInlineableArgumentForInlineableParameterCalledInSuspend
else ->
null
@@ -1073,46 +1049,6 @@ class MethodInliner(
}
}
private fun putStackValuesIntoLocalsForLambdaOnInvoke(
directOrder: List<Type>,
directOrderOfArguments: List<ParameterDescriptor>,
directOrderOfInvokeParameters: List<ValueParameterDescriptor>,
shift: Int,
iv: InstructionAdapter,
descriptor: String
) {
val actualParams = Type.getArgumentTypes(descriptor)
assert(actualParams.size == directOrder.size) {
"Number of expected and actual parameters should be equal, but ${actualParams.size} != ${directOrder.size}!"
}
var currentShift = shift + directOrder.sumOf { it.size }
val safeToUseArgumentKotlinType =
directOrder.size == directOrderOfArguments.size && directOrderOfArguments.size == directOrderOfInvokeParameters.size
for (index in directOrder.lastIndex downTo 0) {
val type = directOrder[index]
currentShift -= type.size
val typeOnStack = actualParams[index]
val argumentKotlinType: KotlinType?
val invokeParameterKotlinType: KotlinType?
if (safeToUseArgumentKotlinType) {
argumentKotlinType = directOrderOfArguments[index].type
invokeParameterKotlinType = directOrderOfInvokeParameters[index].type
} else {
argumentKotlinType = null
invokeParameterKotlinType = null
}
if (typeOnStack != type || invokeParameterKotlinType != argumentKotlinType) {
StackValue.onStack(typeOnStack, invokeParameterKotlinType).put(type, argumentKotlinType, iv)
}
iv.store(currentShift, type)
}
}
//process local and global returns (local substituted with goto end-label global kept unchanged)
@JvmStatic
fun processReturns(

View File

@@ -37,7 +37,7 @@ abstract class ObjectTransformer<out T : TransformationInfo>(@JvmField val trans
val classBuilder = state.factory.newVisitor(
JvmDeclarationOrigin.NO_ORIGIN,
Type.getObjectType(transformationInfo.newClassName),
inliningContext.root.sourceCompilerForInline.callsiteFile!!
inliningContext.callSiteInfo.file!!
)
return RemappingClassBuilder(

View File

@@ -5,44 +5,47 @@
package org.jetbrains.kotlin.codegen.inline
import org.jetbrains.kotlin.builtins.isSuspendFunctionType
import org.jetbrains.kotlin.builtins.isSuspendFunctionTypeOrSubtype
import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.DescriptorAsmUtil.getMethodAsmFlags
import org.jetbrains.kotlin.codegen.binding.CalculatedClosure
import org.jetbrains.kotlin.codegen.binding.CodegenBinding
import org.jetbrains.kotlin.codegen.coroutines.getOrCreateJvmSuspendFunctionView
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
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.descriptors.*
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.load.kotlin.TypeMappingMode
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCallWithAssert
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.inline.InlineUtil
import org.jetbrains.kotlin.resolve.inline.InlineUtil.isInlinableParameterExpression
import org.jetbrains.kotlin.resolve.inline.isInlineOnly
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodParameterKind
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DescriptorWithContainerSource
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.org.objectweb.asm.Label
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.commons.Method
import org.jetbrains.org.objectweb.asm.tree.MethodNode
class PsiInlineCodegen(
codegen: ExpressionCodegen,
state: GenerationState,
function: FunctionDescriptor,
methodOwner: Type,
private val functionDescriptor: FunctionDescriptor,
signature: JvmMethodSignature,
typeParameterMappings: TypeParameterMappings<KotlinType>,
sourceCompiler: SourceCompilerForInline,
private val actualDispatchReceiver: Type = methodOwner
private val methodOwner: Type,
private val actualDispatchReceiver: Type
) : InlineCodegen<ExpressionCodegen>(
codegen, state, function, methodOwner, signature, typeParameterMappings, sourceCompiler,
codegen, state, signature, typeParameterMappings, sourceCompiler,
ReifiedTypeInliner(
typeParameterMappings, PsiInlineIntrinsicsSupport(state), codegen.typeSystem,
state.languageVersionSettings, state.unifiedNullChecks
@@ -60,13 +63,26 @@ class PsiInlineCodegen(
callDefault: Boolean,
codegen: ExpressionCodegen
) {
(sourceCompiler as PsiSourceCompilerForInline).callDefault = callDefault
assert(hiddenParameters.isEmpty()) { "putHiddenParamsIntoLocals() should be called after processHiddenParameters()" }
if (!state.globalInlineContext.enterIntoInlining(functionDescriptor, resolvedCall?.call?.callElement)) {
generateStub(resolvedCall?.call?.callElement?.text ?: "<no source>", codegen)
return
}
try {
val registerLineNumber = registerLineNumberAfterwards(resolvedCall)
performInline(resolvedCall?.typeArguments?.keys?.toList(), callDefault, callDefault, codegen.typeSystem, registerLineNumber)
for (info in expressionMap.values) {
if (info is PsiExpressionLambda) {
// Can't be done immediately in `rememberClosure` for some reason:
info.generateLambdaBody(sourceCompiler)
// Requires `generateLambdaBody` first if the closure is non-empty (for bound callable references,
// or indeed any callable references, it *is* empty, so this was done in `rememberClosure`):
if (!info.isBoundCallableReference) {
putClosureParametersOnStack(info, null)
}
}
}
performInline(registerLineNumber, functionDescriptor.isInlineOnly())
} finally {
state.globalInlineContext.exitFromInlining()
}
@@ -78,38 +94,30 @@ class PsiInlineCodegen(
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)
}
private val hiddenParameters = mutableListOf<Pair<ParameterInfo, Int>>()
override fun processHiddenParameters() {
val contextKind = (sourceCompiler as PsiSourceCompilerForInline).context.contextKind
if (getMethodAsmFlags(functionDescriptor, contextKind, state) and Opcodes.ACC_STATIC == 0) {
hiddenParameters += invocationParamBuilder.addNextParameter(methodOwner, false, actualDispatchReceiver) to
codegen.frameMap.enterTemp(methodOwner)
}
for (param in jvmSignature.valueParameters) {
if (param.kind == JvmMethodParameterKind.VALUE) {
break
}
invocationParamBuilder.addNextParameter(param.asmType, false)
hiddenParameters += invocationParamBuilder.addNextParameter(param.asmType, false) to
codegen.frameMap.enterTemp(param.asmType)
}
invocationParamBuilder.markValueParametersStart()
val hiddenParameters = invocationParamBuilder.buildParameters().parameters
delayedHiddenWriting = recordParameterValueInLocalVal(justProcess, false, *hiddenParameters.toTypedArray())
}
override fun putClosureParametersOnStack(next: LambdaInfo, functionReferenceReceiver: StackValue?) {
activeLambda = next
when (next) {
is PsiExpressionLambda -> codegen.pushClosureOnStack(next.classDescriptor, true, this, functionReferenceReceiver)
is DefaultLambda -> rememberCapturedForDefaultLambda(next)
else -> throw RuntimeException("Unknown lambda: $next")
override fun putHiddenParamsIntoLocals() {
for (i in hiddenParameters.indices.reversed()) {
val (param, offset) = hiddenParameters[i]
StackValue.local(offset, param.type).store(StackValue.onStack(param.typeOnStack), codegen.visitor)
}
activeLambda = null
}
private fun getBoundCallableReferenceReceiver(argumentExpression: KtExpression): ReceiverValue? {
val deparenthesized = KtPsiUtil.deparenthesize(argumentExpression) as? KtCallableReferenceExpression ?: return null
val resolvedCall = deparenthesized.callableReference.getResolvedCallWithAssert(state.bindingContext)
return JvmCodegenUtil.getBoundCallableReferenceReceiver(resolvedCall)
hiddenParameters.clear()
}
/*lambda or callable reference*/
@@ -132,23 +140,7 @@ class PsiInlineCodegen(
}
if (isInliningParameter(argumentExpression, valueParameterDescriptor)) {
val lambdaInfo = rememberClosure(argumentExpression, parameterType.type, valueParameterDescriptor)
val receiverValue = getBoundCallableReferenceReceiver(argumentExpression)
if (receiverValue != null) {
val receiver = codegen.generateReceiverValue(receiverValue, false)
val receiverKotlinType = receiver.kotlinType
val boxedReceiver =
if (receiverKotlinType != null)
receiver.type.boxReceiverForBoundReference(receiverKotlinType, state.typeMapper)
else
receiver.type.boxReceiverForBoundReference()
putClosureParametersOnStack(
lambdaInfo,
StackValue.coercion(receiver, boxedReceiver, receiverKotlinType)
)
}
rememberClosure(argumentExpression, parameterType.type, valueParameterDescriptor)
} else {
val value = codegen.gen(argumentExpression)
val kind = when {
@@ -167,50 +159,176 @@ class PsiInlineCodegen(
private fun isCallSiteIsSuspend(descriptor: ValueParameterDescriptor): Boolean =
state.bindingContext[CodegenBinding.CALL_SITE_IS_SUSPEND_FOR_CROSSINLINE_LAMBDA, descriptor] == true
private fun rememberClosure(expression: KtExpression, type: Type, parameter: ValueParameterDescriptor): LambdaInfo {
private fun rememberClosure(expression: KtExpression, type: Type, parameter: ValueParameterDescriptor) {
val ktLambda = KtPsiUtil.deparenthesize(expression)
assert(isInlinableParameterExpression(ktLambda)) { "Couldn't find inline expression in ${expression.text}" }
return PsiExpressionLambda(
ktLambda!!, state.typeMapper, state.languageVersionSettings,
parameter.isCrossinline, getBoundCallableReferenceReceiver(expression) != null
).also { lambda ->
val closureInfo = invocationParamBuilder.addNextValueParameter(type, true, null, parameter.index)
closureInfo.functionalArgument = lambda
expressionMap[closureInfo.index] = lambda
val boundReceiver = if (ktLambda is KtCallableReferenceExpression) {
val resolvedCall = ktLambda.callableReference.getResolvedCallWithAssert(state.bindingContext)
JvmCodegenUtil.getBoundCallableReferenceReceiver(resolvedCall)
} else null
val lambda = PsiExpressionLambda(ktLambda!!, state, parameter.isCrossinline, boundReceiver != null)
rememberClosure(type, parameter.index, lambda)
if (boundReceiver != null) {
// Has to be done immediately to preserve evaluation order.
val receiver = codegen.generateReceiverValue(boundReceiver, false)
val receiverKotlinType = receiver.kotlinType
val boxedReceiver =
if (receiverKotlinType != null)
DescriptorAsmUtil.boxType(receiver.type, receiverKotlinType, state.typeMapper)
else
AsmUtil.boxType(receiver.type)
val receiverValue = StackValue.coercion(receiver, boxedReceiver, receiverKotlinType)
putClosureParametersOnStack(lambda, receiverValue)
}
}
override fun putValueIfNeeded(parameterType: JvmKotlinType, value: StackValue, kind: ValueKind, parameterIndex: Int) {
if (processDefaultMaskOrMethodHandler(value, kind)) return
var activeLambda: LambdaInfo? = null
private set
assert(maskValues.isEmpty()) { "Additional default call arguments should be last ones, but $value" }
putArgumentOrCapturedToLocalVal(parameterType, value, -1, parameterIndex, kind)
private fun putClosureParametersOnStack(next: PsiExpressionLambda, receiverValue: StackValue?) {
activeLambda = next
codegen.pushClosureOnStack(next.classDescriptor, true, this, receiverValue)
activeLambda = null
}
override fun putCapturedValueOnStack(stackValue: StackValue, valueType: Type, paramIndex: Int) {
putArgumentOrCapturedToLocalVal(
JvmKotlinType(stackValue.type, stackValue.kotlinType), stackValue, paramIndex, paramIndex, ValueKind.CAPTURED
)
}
override fun putValueIfNeeded(parameterType: JvmKotlinType, value: StackValue, kind: ValueKind, parameterIndex: Int) =
putArgumentToLocalVal(parameterType, value, parameterIndex, kind)
override fun putCapturedValueOnStack(stackValue: StackValue, valueType: Type, paramIndex: Int) =
putCapturedToLocalVal(stackValue, activeLambda!!.capturedVars[paramIndex], stackValue.kotlinType)
override fun reorderArgumentsIfNeeded(actualArgsWithDeclIndex: List<ArgumentAndDeclIndex>, valueParameterTypes: List<Type>) = Unit
override fun putHiddenParamsIntoLocals() {
assert(delayedHiddenWriting != null) { "processAndPutHiddenParameters(true) should be called before putHiddenParamsIntoLocals" }
delayedHiddenWriting!!.invoke()
delayedHiddenWriting = null
}
override fun extractDefaultLambdas(node: MethodNode): List<DefaultLambda> {
return expandMaskConditionsAndUpdateVariableNodes(
node, maskStartIndex, maskValues, methodHandleInDefaultMethodIndex,
extractDefaultLambdaOffsetAndDescriptor(jvmSignature, functionDescriptor),
::PsiDefaultLambda
)
}
override fun descriptorIsDeserialized(memberDescriptor: CallableMemberDescriptor): Boolean =
memberDescriptor is DescriptorWithContainerSource
override fun extractDefaultLambdas(node: MethodNode): List<DefaultLambda> =
extractDefaultLambdas(node, extractDefaultLambdaOffsetAndDescriptor(jvmSignature, functionDescriptor)) { parameter ->
PsiDefaultLambda(type, capturedArgs, parameter, offset, needReification, sourceCompiler)
}
}
private val FunctionDescriptor.explicitParameters
get() = listOfNotNull(extensionReceiverParameter) + valueParameters
class PsiExpressionLambda(
expression: KtExpression,
private val state: GenerationState,
isCrossInline: Boolean,
override val isBoundCallableReference: Boolean
) : ExpressionLambda(isCrossInline) {
override val lambdaClassType: Type
override val invokeMethod: Method
val invokeMethodDescriptor: FunctionDescriptor
override val invokeMethodParameters: List<KotlinType?>
get() {
val actualInvokeDescriptor = if (isSuspend)
getOrCreateJvmSuspendFunctionView(invokeMethodDescriptor, state)
else
invokeMethodDescriptor
return actualInvokeDescriptor.explicitParameters.map { it.returnType }
}
override val invokeMethodReturnType: KotlinType?
get() = invokeMethodDescriptor.returnType
val classDescriptor: ClassDescriptor
val propertyReferenceInfo: PropertyReferenceInfo?
val functionWithBodyOrCallableReference: KtExpression = (expression as? KtLambdaExpression)?.functionLiteral ?: expression
override val returnLabels: Map<String, Label?>
override val isSuspend: Boolean
val closure: CalculatedClosure
init {
val bindingContext = state.bindingContext
val function = bindingContext.get(BindingContext.FUNCTION, functionWithBodyOrCallableReference)
if (function == null && expression is KtCallableReferenceExpression) {
val variableDescriptor =
bindingContext.get(BindingContext.VARIABLE, functionWithBodyOrCallableReference) as? VariableDescriptorWithAccessors
?: throw AssertionError("Reference expression not resolved to variable descriptor with accessors: ${expression.getText()}")
classDescriptor = bindingContext.get(CodegenBinding.CLASS_FOR_CALLABLE, variableDescriptor)
?: throw IllegalStateException("Class for callable not found: $variableDescriptor\n${expression.text}")
lambdaClassType = state.typeMapper.mapClass(classDescriptor)
val getFunction = PropertyReferenceCodegen.findGetFunction(variableDescriptor)
invokeMethodDescriptor = PropertyReferenceCodegen.createFakeOpenDescriptor(getFunction, classDescriptor)
val resolvedCall = expression.callableReference.getResolvedCallWithAssert(bindingContext)
propertyReferenceInfo = PropertyReferenceInfo(resolvedCall.resultingDescriptor as VariableDescriptor, getFunction)
} else {
propertyReferenceInfo = null
invokeMethodDescriptor = function ?: throw AssertionError("Function is not resolved to descriptor: " + expression.text)
classDescriptor = bindingContext.get(CodegenBinding.CLASS_FOR_CALLABLE, invokeMethodDescriptor)
?: throw IllegalStateException("Class for invoke method not found: $invokeMethodDescriptor\n${expression.text}")
lambdaClassType = CodegenBinding.asmTypeForAnonymousClass(bindingContext, invokeMethodDescriptor)
}
closure = bindingContext.get(CodegenBinding.CLOSURE, classDescriptor)
?: throw AssertionError("null closure for lambda ${expression.text}")
returnLabels = getDeclarationLabels(expression, invokeMethodDescriptor).associateWith { null }
invokeMethod = state.typeMapper.mapAsmMethod(invokeMethodDescriptor)
isSuspend = invokeMethodDescriptor.isSuspend
}
// This can only be computed after generating the body, hence `lazy`.
override val capturedVars: List<CapturedParamDesc> by lazy {
arrayListOf<CapturedParamDesc>().apply {
val captureThis = closure.capturedOuterClassDescriptor
if (captureThis != null) {
add(capturedParamDesc(AsmUtil.CAPTURED_THIS_FIELD, state.typeMapper.mapType(captureThis.defaultType), isSuspend = false))
}
val capturedReceiver = closure.capturedReceiverFromOuterContext
if (capturedReceiver != null) {
val fieldName = closure.getCapturedReceiverFieldName(state.typeMapper.bindingContext, state.languageVersionSettings)
val type = if (isBoundCallableReference)
state.typeMapper.mapType(capturedReceiver, null, TypeMappingMode.GENERIC_ARGUMENT)
else
state.typeMapper.mapType(capturedReceiver)
add(capturedParamDesc(fieldName, type, isSuspend = false))
}
closure.captureVariables.forEach { (parameter, value) ->
val isSuspend = parameter is ValueParameterDescriptor && parameter.type.isSuspendFunctionTypeOrSubtype
add(capturedParamDesc(value.fieldName, value.type, isSuspend))
}
}
}
val isPropertyReference: Boolean
get() = propertyReferenceInfo != null
}
class PsiDefaultLambda(
lambdaClassType: Type,
capturedArgs: Array<Type>,
parameterDescriptor: ValueParameterDescriptor,
offset: Int,
needReification: Boolean,
sourceCompiler: SourceCompilerForInline
) : DefaultLambda(lambdaClassType, capturedArgs, parameterDescriptor.isCrossinline, offset, needReification, sourceCompiler) {
private val invokeMethodDescriptor: FunctionDescriptor
override val invokeMethodParameters: List<KotlinType?>
get() = invokeMethodDescriptor.explicitParameters.map { it.returnType }
override val invokeMethodReturnType: KotlinType?
get() = invokeMethodDescriptor.returnType
init {
val name = if (isPropertyReference) OperatorNameConventions.GET else OperatorNameConventions.INVOKE
val descriptor = parameterDescriptor.type.memberScope
.getContributedFunctions(OperatorNameConventions.INVOKE, NoLookupLocation.FROM_BACKEND)
.single()
.let { if (parameterDescriptor.type.isSuspendFunctionType) getOrCreateJvmSuspendFunctionView(it, sourceCompiler.state) else it }
// This is technically wrong as it always uses `invoke`, but `loadInvoke` will fall back to `get` which is never mangled...
val asmMethod = sourceCompiler.state.typeMapper.mapAsmMethod(descriptor)
val invokeIsErased = loadInvoke(sourceCompiler, name.asString(), asmMethod)
invokeMethodDescriptor = if (invokeIsErased) descriptor.original else descriptor
}
}

View File

@@ -5,12 +5,14 @@
package org.jetbrains.kotlin.codegen.inline
import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMap
import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.jvm.AsmTypes.*
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.model.TypeParameterMarker
@@ -19,7 +21,7 @@ import org.jetbrains.org.objectweb.asm.Type.INT_TYPE
import org.jetbrains.org.objectweb.asm.Type.VOID_TYPE
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
class PsiInlineIntrinsicsSupport(private val state: GenerationState) : ReifiedTypeInliner.IntrinsicsSupport<KotlinType> {
class PsiInlineIntrinsicsSupport(override val state: GenerationState) : ReifiedTypeInliner.IntrinsicsSupport<KotlinType> {
override fun putClassInstance(v: InstructionAdapter, type: KotlinType) {
DescriptorAsmUtil.putJavaLangClassInstance(v, state.typeMapper.mapType(type), type, state.typeMapper)
}
@@ -56,5 +58,10 @@ class PsiInlineIntrinsicsSupport(private val state: GenerationState) : ReifiedTy
)
}
override fun isMutableCollectionType(type: KotlinType): Boolean {
val classifier = type.constructor.declarationDescriptor
return classifier is ClassDescriptor && JavaToKotlinClassMap.isMutable(classifier.fqNameUnsafe)
}
override fun toKotlinType(type: KotlinType): KotlinType = type
}

View File

@@ -0,0 +1,443 @@
/*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.codegen.inline
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.backend.common.CodegenUtil
import org.jetbrains.kotlin.builtins.isSuspendFunctionTypeOrSubtype
import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.binding.CodegenBinding
import org.jetbrains.kotlin.codegen.context.*
import org.jetbrains.kotlin.codegen.coroutines.getOrCreateJvmSuspendFunctionView
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper
import org.jetbrains.kotlin.config.JVMConfigurationKeys
import org.jetbrains.kotlin.config.isReleaseCoroutines
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.incremental.KotlinLookupLocation
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.ImportedFromObjectCallableDescriptor
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCallWithAssert
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.isInlineClass
import org.jetbrains.kotlin.resolve.jvm.annotations.isCallableMemberCompiledToJvmDefault
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature
import org.jetbrains.kotlin.resolve.jvm.requiresFunctionNameManglingForReturnType
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DescriptorWithContainerSource
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils
import org.jetbrains.kotlin.types.expressions.LabelResolver
import org.jetbrains.kotlin.utils.addIfNotNull
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.Method
import org.jetbrains.org.objectweb.asm.tree.MethodNode
class PsiSourceCompilerForInline(
private val codegen: ExpressionCodegen,
override val callElement: KtElement,
private val functionDescriptor: FunctionDescriptor
) : SourceCompilerForInline {
override val state
get() = codegen.state
private val additionalInnerClasses = mutableListOf<ClassDescriptor>()
val context = getContext(
functionDescriptor,
functionDescriptor,
codegen.state,
DescriptorToSourceUtils.descriptorToDeclaration(functionDescriptor)?.containingFile as? KtFile,
additionalInnerClasses
) as MethodContext
override val callElementText: String by lazy { callElement.text }
override val inlineCallSiteInfo: InlineCallSiteInfo
get() {
var context = codegen.getContext()
var parentCodegen = codegen.parentCodegen
while (context is InlineLambdaContext) {
val closureContext = context.getParentContext()
assert(closureContext is ClosureContext) { "Parent context of inline lambda should be closure context" }
assert(closureContext.parentContext is MethodContext) { "Closure context should appear in method context" }
context = closureContext.parentContext as MethodContext
assert(parentCodegen is FakeMemberCodegen) { "Parent codegen of inlined lambda should be FakeMemberCodegen" }
parentCodegen = (parentCodegen as FakeMemberCodegen).delegate
}
val signature = codegen.state.typeMapper.mapSignatureSkipGeneric(context.functionDescriptor, context.contextKind)
return InlineCallSiteInfo(
parentCodegen.className,
signature.asmMethod,
context.functionDescriptor.isInlineOrInsideInline(),
callElement.containingFile,
CodegenUtil.getLineNumberForElement(callElement, false) ?: 0
)
}
override val sourceMapper
get() = codegen.parentCodegen.orCreateSourceMapper
override fun generateLambdaBody(lambdaInfo: ExpressionLambda, reifiedTypeParameters: ReifiedTypeParametersUsages): SMAPAndMethodNode {
require(lambdaInfo is PsiExpressionLambda)
val invokeMethodDescriptor = lambdaInfo.invokeMethodDescriptor
val jvmMethodSignature = state.typeMapper.mapSignatureSkipGeneric(invokeMethodDescriptor)
val asmMethod = jvmMethodSignature.asmMethod
val methodNode = MethodNode(
Opcodes.API_VERSION, DescriptorAsmUtil.getMethodAsmFlags(invokeMethodDescriptor, OwnerKind.IMPLEMENTATION, state),
asmMethod.name, asmMethod.descriptor, null, null
)
val adapter = wrapWithMaxLocalCalc(methodNode)
val closureContext = when {
lambdaInfo.isPropertyReference ->
codegen.getContext().intoAnonymousClass(lambdaInfo.classDescriptor, codegen, OwnerKind.IMPLEMENTATION)
invokeMethodDescriptor.isSuspend ->
codegen.getContext().intoCoroutineClosure(
getOrCreateJvmSuspendFunctionView(invokeMethodDescriptor, state), invokeMethodDescriptor, codegen, state.typeMapper
)
else -> codegen.getContext().intoClosure(invokeMethodDescriptor, codegen, state.typeMapper)
}
val context = closureContext.intoInlinedLambda(invokeMethodDescriptor, lambdaInfo.isCrossInline, lambdaInfo.isPropertyReference)
val smap = generateMethodBody(
adapter, invokeMethodDescriptor, context,
lambdaInfo.functionWithBodyOrCallableReference,
jvmMethodSignature, lambdaInfo
)
adapter.visitMaxs(-1, -1)
return SMAPAndMethodNode(methodNode, smap)
}
private fun generateMethodBody(
adapter: MethodVisitor,
descriptor: FunctionDescriptor,
context: MethodContext,
expression: KtExpression,
jvmMethodSignature: JvmMethodSignature,
lambdaInfo: PsiExpressionLambda?
): SMAP {
val isLambda = lambdaInfo != null
// Wrapping for preventing marking actual parent codegen as containing reified markers
val parentCodegen = FakeMemberCodegen(
codegen.parentCodegen, expression, context.parentContext as FieldOwnerContext<*>,
if (isLambda)
codegen.parentCodegen.className
else
state.typeMapper.mapImplementationOwner(descriptor).internalName,
if (isLambda) emptyList() else additionalInnerClasses,
isLambda
)
val strategy = when (expression) {
is KtCallableReferenceExpression -> {
val resolvedCall = expression.callableReference.getResolvedCallWithAssert(state.bindingContext)
val receiverKotlinType = JvmCodegenUtil.getBoundCallableReferenceReceiver(resolvedCall)?.type
val receiverType = receiverKotlinType?.let(state.typeMapper::mapType)
val boundReceiverJvmKotlinType = receiverType?.let { JvmKotlinType(receiverType, receiverKotlinType) }
if (isLambda && lambdaInfo!!.isPropertyReference) {
val asmType = state.typeMapper.mapClass(lambdaInfo.classDescriptor)
val info = lambdaInfo.propertyReferenceInfo
PropertyReferenceCodegen.PropertyReferenceGenerationStrategy(
true, info!!.getFunction, info.target, asmType,
boundReceiverJvmKotlinType,
lambdaInfo.functionWithBodyOrCallableReference, state, true
)
} else {
FunctionReferenceGenerationStrategy(state, descriptor, resolvedCall, boundReceiverJvmKotlinType, null, true)
}
}
is KtFunctionLiteral -> ClosureGenerationStrategy(state, expression as KtDeclarationWithBody)
else -> FunctionGenerationStrategy.FunctionDefault(state, expression as KtDeclarationWithBody)
}
FunctionCodegen.generateMethodBody(
adapter, descriptor, context, jvmMethodSignature, strategy, parentCodegen, state.jvmDefaultMode,
state.languageVersionSettings.isReleaseCoroutines()
)
if (isLambda) {
codegen.propagateChildReifiedTypeParametersUsages(parentCodegen.reifiedTypeParametersUsages)
}
return SMAP(parentCodegen.orCreateSourceMapper.resultMappings)
}
@Suppress("UNCHECKED_CAST")
private class FakeMemberCodegen(
val delegate: MemberCodegen<*>,
declaration: KtElement,
codegenContext: FieldOwnerContext<*>,
private val className: String,
private val parentAsInnerClasses: List<ClassDescriptor>,
private val isInlineLambdaCodegen: Boolean
) : MemberCodegen<KtPureElement>(delegate as MemberCodegen<KtPureElement>, declaration, codegenContext) {
override fun generateDeclaration() {
throw IllegalStateException()
}
override fun generateBody() {
throw IllegalStateException()
}
override fun generateKotlinMetadataAnnotation() {
throw IllegalStateException()
}
override fun getInlineNameGenerator(): NameGenerator {
return delegate.inlineNameGenerator
}
override //TODO: obtain name from context
fun getClassName(): String {
return className
}
override fun addParentsToInnerClassesIfNeeded(innerClasses: MutableCollection<ClassDescriptor>) {
if (isInlineLambdaCodegen) {
super.addParentsToInnerClassesIfNeeded(innerClasses)
} else {
innerClasses.addAll(parentAsInnerClasses)
}
}
override fun generateAssertField() {
delegate.generateAssertField()
}
}
private fun getDirectMemberAndCallableFromObject(): CallableMemberDescriptor {
val directMember = JvmCodegenUtil.getDirectMember(functionDescriptor)
return (directMember as? ImportedFromObjectCallableDescriptor<*>)?.callableFromObject ?: directMember
}
internal var callDefault: Boolean = false
private fun mapDefault(): Method {
// This is all available in the `Callable` passed to `PsiInlineCodegen.genCallInner`, but it's not forwarded through the inliner...
var result = state.typeMapper.mapDefaultMethod(functionDescriptor, context.contextKind)
if (result.name.contains("-") &&
!state.configuration.getBoolean(JVMConfigurationKeys.USE_OLD_INLINE_CLASSES_MANGLING_SCHEME) &&
classFileContainsMethod(functionDescriptor, state, result) == false
) {
state.typeMapper.useOldManglingRulesForFunctionAcceptingInlineClass = true
result = state.typeMapper.mapDefaultMethod(functionDescriptor, context.contextKind)
state.typeMapper.useOldManglingRulesForFunctionAcceptingInlineClass = false
}
return result
}
override fun compileInlineFunction(jvmSignature: JvmMethodSignature): SMAPAndMethodNode {
generateInlineIntrinsic(state.languageVersionSettings, functionDescriptor, jvmSignature.asmMethod, codegen.typeSystem)?.let {
return it
}
val asmMethod = if (callDefault) mapDefault() else jvmSignature.asmMethod
if (asmMethod.name != functionDescriptor.name.asString()) {
KotlinLookupLocation(callElement).location?.let {
state.trackLookup(DescriptorUtils.getFqNameSafe(functionDescriptor.containingDeclaration), asmMethod.name, it)
}
}
val directMember = getDirectMemberAndCallableFromObject()
if (directMember is DescriptorWithContainerSource) {
val containerId = KotlinTypeMapper.getContainingClassesForDeserializedCallable(directMember).implClassId
val isMangled = requiresFunctionNameManglingForReturnType(functionDescriptor)
return loadCompiledInlineFunction(containerId, asmMethod, functionDescriptor.isSuspend, isMangled, state)
}
val element = DescriptorToSourceUtils.descriptorToDeclaration(functionDescriptor) as? KtDeclarationWithBody
?: throw IllegalStateException("Couldn't find declaration for function $functionDescriptor")
val node = MethodNode(
Opcodes.API_VERSION,
DescriptorAsmUtil.getMethodAsmFlags(functionDescriptor, context.contextKind, state) or
if (callDefault) Opcodes.ACC_STATIC else 0,
asmMethod.name,
asmMethod.descriptor, null, null
)
//for maxLocals calculation
val maxCalcAdapter = wrapWithMaxLocalCalc(node)
val smap = if (callDefault) {
val implementationOwner = state.typeMapper.mapImplementationOwner(functionDescriptor)
val parentCodegen = FakeMemberCodegen(
codegen.parentCodegen, element, context.parentContext as FieldOwnerContext<*>,
implementationOwner.internalName,
additionalInnerClasses,
false
)
if (element !is KtNamedFunction) {
throw IllegalStateException("Property accessors with default parameters not supported $functionDescriptor")
}
FunctionCodegen.generateDefaultImplBody(
context, functionDescriptor, maxCalcAdapter, DefaultParameterValueLoader.DEFAULT,
element as KtNamedFunction?, parentCodegen, asmMethod
)
SMAP(parentCodegen.orCreateSourceMapper.resultMappings)
} else {
generateMethodBody(maxCalcAdapter, functionDescriptor, context, element, jvmSignature, null)
}
maxCalcAdapter.visitMaxs(-1, -1)
maxCalcAdapter.visitEnd()
return SMAPAndMethodNode(node, smap)
}
override fun hasFinallyBlocks() = codegen.hasFinallyBlocks()
override fun generateFinallyBlocks(finallyNode: MethodNode, curFinallyDepth: Int, returnType: Type, afterReturnLabel: Label, target: Label?) {
// TODO use the target label for non-local break/continue
ExpressionCodegen(
finallyNode, codegen.frameMap, codegen.returnType,
codegen.getContext(), codegen.state, codegen.parentCodegen
).also {
it.addBlockStackElementsForNonLocalReturns(codegen.blockStackElements, curFinallyDepth)
}.generateFinallyBlocksIfNeeded(returnType, null, afterReturnLabel)
}
override val isCallInsideSameModuleAsCallee: Boolean
get() = JvmCodegenUtil.isCallInsideSameModuleAsDeclared(functionDescriptor, codegen.getContext(), codegen.state.outDirectory)
override val isFinallyMarkerRequired: Boolean
get() = isFinallyMarkerRequired(codegen.getContext())
override fun isSuspendLambdaCapturedByOuterObjectOrLambda(name: String): Boolean {
// We cannot find the lambda in captured parameters: it came from object outside of the our reach:
// this can happen when the lambda capture by non-transformed closure:
// inline fun inlineMe(crossinline c: suspend() -> Unit) = suspend { c() }
// inline fun inlineMe2(crossinline c: suspend() -> Unit) = suspend { inlineMe { c() }() }
// Suppose, we inline inlineMe into inlineMe2: the only knowledge we have about inlineMe$1 is captured receiver (this$0)
// Thus, transformed lambda from inlineMe, inlineMe3$$inlined$inlineMe2$1 contains the following bytecode
// ALOAD 0
// GETFIELD inlineMe2$1$invokeSuspend$$inlined$inlineMe$1.this$0 : LScratchKt$inlineMe2$1;
// GETFIELD inlineMe2$1.$c : Lkotlin/jvm/functions/Function1;
// Since inlineMe2's lambda is outside of reach of the inliner, find crossinline parameter from compilation context:
var container: DeclarationDescriptor = codegen.getContext().functionDescriptor
while (container !is ClassDescriptor) {
container = container.containingDeclaration ?: return false
}
var classDescriptor: ClassDescriptor? = container
while (classDescriptor != null) {
val closure = state.bindingContext[CodegenBinding.CLOSURE, classDescriptor] ?: return false
for ((param, value) in closure.captureVariables) {
if (param is ValueParameterDescriptor && value.fieldName == name) {
return param.type.isSuspendFunctionTypeOrSubtype
}
}
classDescriptor = closure.capturedOuterClassDescriptor
}
return false
}
override fun getContextLabels(): Map<String, Label?> {
val context = codegen.getContext()
val parentContext = context.parentContext
val descriptor = if (parentContext is ClosureContext && parentContext.originalSuspendLambdaDescriptor != null) {
parentContext.originalSuspendLambdaDescriptor!!
} else context.contextDescriptor
val labels = getDeclarationLabels(DescriptorToSourceUtils.descriptorToDeclaration(descriptor), descriptor)
return labels.associateWith { null } // TODO add break/continue labels
}
override fun reportSuspensionPointInsideMonitor(stackTraceElement: String) {
org.jetbrains.kotlin.codegen.coroutines.reportSuspensionPointInsideMonitor(callElement, state, stackTraceElement)
}
companion object {
fun getContext(
descriptor: DeclarationDescriptor,
innerDescriptor: DeclarationDescriptor,
state: GenerationState,
sourceFile: KtFile?,
additionalInners: MutableList<ClassDescriptor>
): CodegenContext<*> {
if (descriptor is PackageFragmentDescriptor) {
//no inners
return PackageContext(descriptor, state.rootContext, null, sourceFile)
}
val container = descriptor.containingDeclaration ?: error("No container for descriptor: $descriptor")
val containerContext = getContext(
container,
descriptor,
state,
sourceFile,
additionalInners
)
return when (descriptor) {
is ScriptDescriptor -> {
val earlierScripts = state.scriptSpecific.earlierScriptsForReplInterpreter
containerContext.intoScript(
descriptor,
earlierScripts ?: emptyList(),
descriptor as ClassDescriptor, state.typeMapper
)
}
is ClassDescriptor -> {
val kind =
when {
DescriptorUtils.isInterface(descriptor) &&
innerDescriptor !is ClassDescriptor &&
!innerDescriptor.isCallableMemberCompiledToJvmDefault(state.jvmDefaultMode) ->
OwnerKind.DEFAULT_IMPLS
else ->
OwnerKind.IMPLEMENTATION
}
additionalInners.addIfNotNull(
InnerClassConsumer.classForInnerClassRecord(descriptor, kind == OwnerKind.DEFAULT_IMPLS)
)
if (descriptor.isInlineClass()) {
containerContext.intoClass(descriptor, OwnerKind.IMPLEMENTATION, state)
.intoClass(descriptor, OwnerKind.ERASED_INLINE_CLASS, state)
} else {
containerContext.intoClass(descriptor, kind, state)
}
}
is FunctionDescriptor -> {
containerContext.intoFunction(descriptor)
}
else -> {
throw IllegalStateException("Couldn't build context for $descriptor")
}
}
}
}
}
fun DeclarationDescriptor.isInlineOrInsideInline(): Boolean =
if (this is FunctionDescriptor && isInline) true
else containingDeclaration?.isInlineOrInsideInline() == true
fun getDeclarationLabels(lambdaOrFun: PsiElement?, descriptor: DeclarationDescriptor): Set<String> {
val result = HashSet<String>()
if (lambdaOrFun != null) {
val label = LabelResolver.getLabelNameIfAny(lambdaOrFun)
if (label != null) {
result.add(label.asString())
}
}
if (!ExpressionTypingUtils.isFunctionLiteral(descriptor)) {
if (!descriptor.name.isSpecial) {
result.add(descriptor.name.asString())
}
result.add(FIRST_FUN_LABEL)
}
return result
}

View File

@@ -20,6 +20,7 @@ import org.jetbrains.kotlin.codegen.generateAsCast
import org.jetbrains.kotlin.codegen.generateIsCheck
import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicMethods
import org.jetbrains.kotlin.codegen.optimization.common.intConstant
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.config.isReleaseCoroutines
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
@@ -63,10 +64,14 @@ class ReifiedTypeInliner<KT : KotlinTypeMarker>(
}
interface IntrinsicsSupport<KT : KotlinTypeMarker> {
val state: GenerationState
fun putClassInstance(v: InstructionAdapter, type: KT)
fun generateTypeParameterContainer(v: InstructionAdapter, typeParameter: TypeParameterMarker)
fun isMutableCollectionType(type: KT): Boolean
fun toKotlinType(type: KT): KotlinType
}

View File

@@ -6,428 +6,110 @@
package org.jetbrains.kotlin.codegen.inline
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.backend.common.CodegenUtil
import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.context.*
import org.jetbrains.kotlin.codegen.coroutines.getOrCreateJvmSuspendFunctionView
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.codegen.inline.coroutines.FOR_INLINE_SUFFIX
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.config.isReleaseCoroutines
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.incremental.KotlinLookupLocation
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCallWithAssert
import org.jetbrains.kotlin.resolve.isInlineClass
import org.jetbrains.kotlin.resolve.jvm.annotations.isCallableMemberCompiledToJvmDefault
import org.jetbrains.kotlin.config.CommonConfigurationKeys
import org.jetbrains.kotlin.incremental.components.LocationInfo
import org.jetbrains.kotlin.incremental.components.Position
import org.jetbrains.kotlin.incremental.components.ScopeKind
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature
import org.jetbrains.kotlin.utils.addIfNotNull
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.Method
import org.jetbrains.org.objectweb.asm.tree.MethodNode
import kotlin.properties.Delegates
class InlineCallSiteInfo(
val ownerClassName: String,
val method: Method,
val isInlineOrInsideInline: Boolean,
val file: PsiFile?,
val lineNumber: Int
)
interface SourceCompilerForInline {
val state: GenerationState
val callElement: Any
val lookupLocation: LookupLocation
val callElementText: String
val callsiteFile: PsiFile?
val contextKind: OwnerKind
val inlineCallSiteInfo: InlineCallSiteInfo
val lazySourceMapper: SourceMapper
val sourceMapper: SourceMapper
fun generateLambdaBody(lambdaInfo: ExpressionLambda): SMAPAndMethodNode
fun generateLambdaBody(lambdaInfo: ExpressionLambda, reifiedTypeParameters: ReifiedTypeParametersUsages): SMAPAndMethodNode
fun doCreateMethodNodeFromSource(
callableDescriptor: FunctionDescriptor,
jvmSignature: JvmMethodSignature,
callDefault: Boolean,
asmMethod: Method
): SMAPAndMethodNode
fun compileInlineFunction(jvmSignature: JvmMethodSignature): SMAPAndMethodNode
fun hasFinallyBlocks(): Boolean
fun createCodegenForExternalFinallyBlockGenerationOnNonLocalReturn(
finallyNode: MethodNode,
curFinallyDepth: Int
): BaseExpressionCodegen
fun generateFinallyBlocks(finallyNode: MethodNode, curFinallyDepth: Int, returnType: Type, afterReturnLabel: Label, target: Label?)
fun generateFinallyBlocksIfNeeded(codegen: BaseExpressionCodegen, returnType: Type, afterReturnLabel: Label, target: Label?)
val isCallInsideSameModuleAsCallee: Boolean
fun isCallInsideSameModuleAsDeclared(functionDescriptor: FunctionDescriptor): Boolean
val isFinallyMarkerRequired: Boolean
fun isFinallyMarkerRequired(): Boolean
val compilationContextDescriptor: DeclarationDescriptor
val compilationContextFunctionDescriptor: FunctionDescriptor
fun isSuspendLambdaCapturedByOuterObjectOrLambda(name: String): Boolean
fun getContextLabels(): Map<String, Label?>
fun reportSuspensionPointInsideMonitor(stackTraceElement: String)
}
class PsiSourceCompilerForInline(private val codegen: ExpressionCodegen, override val callElement: KtElement) :
SourceCompilerForInline {
override val state = codegen.state
private var context by Delegates.notNull<CodegenContext<*>>()
private var additionalInnerClasses = mutableListOf<ClassDescriptor>()
override val lookupLocation = KotlinLookupLocation(callElement)
override val callElementText: String by lazy {
callElement.text
}
override val callsiteFile by lazy {
callElement.containingFile
}
override val contextKind
get () = context.contextKind
override val inlineCallSiteInfo: InlineCallSiteInfo
get() {
var context = codegen.getContext()
var parentCodegen = codegen.parentCodegen
while (context is InlineLambdaContext) {
val closureContext = context.getParentContext()
assert(closureContext is ClosureContext) { "Parent context of inline lambda should be closure context" }
assert(closureContext.parentContext is MethodContext) { "Closure context should appear in method context" }
context = closureContext.parentContext as MethodContext
assert(parentCodegen is FakeMemberCodegen) { "Parent codegen of inlined lambda should be FakeMemberCodegen" }
parentCodegen = (parentCodegen as FakeMemberCodegen).delegate
}
val signature = codegen.state.typeMapper.mapSignatureSkipGeneric(context.functionDescriptor, context.contextKind)
return InlineCallSiteInfo(
parentCodegen.className,
signature.asmMethod.name,
signature.asmMethod.descriptor,
compilationContextFunctionDescriptor.isInlineOrInsideInline(),
compilationContextFunctionDescriptor.isSuspend,
CodegenUtil.getLineNumberForElement(callElement, false) ?: 0
)
}
override val lazySourceMapper
get() = codegen.parentCodegen.orCreateSourceMapper
override fun generateLambdaBody(lambdaInfo: ExpressionLambda): SMAPAndMethodNode {
lambdaInfo as? PsiExpressionLambda ?: error("TODO")
val invokeMethodDescriptor = lambdaInfo.invokeMethodDescriptor
val jvmMethodSignature = state.typeMapper.mapSignatureSkipGeneric(invokeMethodDescriptor)
val asmMethod = jvmMethodSignature.asmMethod
val methodNode = MethodNode(
Opcodes.API_VERSION, DescriptorAsmUtil.getMethodAsmFlags(invokeMethodDescriptor, OwnerKind.IMPLEMENTATION, state),
asmMethod.name, asmMethod.descriptor, null, null
)
val adapter = wrapWithMaxLocalCalc(methodNode)
val closureContext = when {
lambdaInfo.isPropertyReference ->
codegen.getContext().intoAnonymousClass(lambdaInfo.classDescriptor, codegen, OwnerKind.IMPLEMENTATION)
invokeMethodDescriptor.isSuspend ->
codegen.getContext().intoCoroutineClosure(
getOrCreateJvmSuspendFunctionView(invokeMethodDescriptor, state), invokeMethodDescriptor, codegen, state.typeMapper
)
else -> codegen.getContext().intoClosure(invokeMethodDescriptor, codegen, state.typeMapper)
}
val context = closureContext.intoInlinedLambda(invokeMethodDescriptor, lambdaInfo.isCrossInline, lambdaInfo.isPropertyReference)
val smap = generateMethodBody(
adapter, invokeMethodDescriptor, context,
lambdaInfo.functionWithBodyOrCallableReference,
jvmMethodSignature, lambdaInfo
)
adapter.visitMaxs(-1, -1)
return SMAPAndMethodNode(methodNode, smap)
}
private fun generateMethodBody(
adapter: MethodVisitor,
descriptor: FunctionDescriptor,
context: MethodContext,
expression: KtExpression,
jvmMethodSignature: JvmMethodSignature,
lambdaInfo: PsiExpressionLambda?
): SMAP {
val isLambda = lambdaInfo != null
// Wrapping for preventing marking actual parent codegen as containing reified markers
val parentCodegen = FakeMemberCodegen(
codegen.parentCodegen, expression, context.parentContext as FieldOwnerContext<*>,
if (isLambda)
codegen.parentCodegen.className
else
state.typeMapper.mapImplementationOwner(descriptor).internalName,
if (isLambda) emptyList<ClassDescriptor>() else additionalInnerClasses,
isLambda
)
val strategy = when (expression) {
is KtCallableReferenceExpression -> {
val resolvedCall = expression.callableReference.getResolvedCallWithAssert(state.bindingContext)
val receiverKotlinType = JvmCodegenUtil.getBoundCallableReferenceReceiver(resolvedCall)?.type
val receiverType = receiverKotlinType?.let(state.typeMapper::mapType)
val boundReceiverJvmKotlinType = receiverType?.let { JvmKotlinType(receiverType, receiverKotlinType) }
if (isLambda && lambdaInfo!!.isPropertyReference) {
val asmType = state.typeMapper.mapClass(lambdaInfo.classDescriptor)
val info = lambdaInfo.propertyReferenceInfo
PropertyReferenceCodegen.PropertyReferenceGenerationStrategy(
true, info!!.getFunction, info.target, asmType,
boundReceiverJvmKotlinType,
lambdaInfo.functionWithBodyOrCallableReference, state, true
)
} else {
FunctionReferenceGenerationStrategy(state, descriptor, resolvedCall, boundReceiverJvmKotlinType, null, true)
}
}
is KtFunctionLiteral -> ClosureGenerationStrategy(state, expression as KtDeclarationWithBody)
else -> FunctionGenerationStrategy.FunctionDefault(state, expression as KtDeclarationWithBody)
}
FunctionCodegen.generateMethodBody(
adapter, descriptor, context, jvmMethodSignature, strategy, parentCodegen, state.jvmDefaultMode,
state.languageVersionSettings.isReleaseCoroutines()
)
if (isLambda) {
codegen.propagateChildReifiedTypeParametersUsages(parentCodegen.reifiedTypeParametersUsages)
}
return SMAP(parentCodegen.orCreateSourceMapper.resultMappings)
}
@Suppress("UNCHECKED_CAST")
private class FakeMemberCodegen(
internal val delegate: MemberCodegen<*>,
declaration: KtElement,
codegenContext: FieldOwnerContext<*>,
private val className: String,
private val parentAsInnerClasses: List<ClassDescriptor>,
private val isInlineLambdaCodegen: Boolean
) : MemberCodegen<KtPureElement>(delegate as MemberCodegen<KtPureElement>, declaration, codegenContext) {
override fun generateDeclaration() {
throw IllegalStateException()
}
override fun generateBody() {
throw IllegalStateException()
}
override fun generateKotlinMetadataAnnotation() {
throw IllegalStateException()
}
override fun getInlineNameGenerator(): NameGenerator {
return delegate.inlineNameGenerator
}
override //TODO: obtain name from context
fun getClassName(): String {
return className
}
override fun addParentsToInnerClassesIfNeeded(innerClasses: MutableCollection<ClassDescriptor>) {
if (isInlineLambdaCodegen) {
super.addParentsToInnerClassesIfNeeded(innerClasses)
} else {
innerClasses.addAll(parentAsInnerClasses)
}
}
override fun generateAssertField() {
delegate.generateAssertField()
}
}
override fun doCreateMethodNodeFromSource(
callableDescriptor: FunctionDescriptor,
jvmSignature: JvmMethodSignature,
callDefault: Boolean,
asmMethod: Method
): SMAPAndMethodNode {
val element = DescriptorToSourceUtils.descriptorToDeclaration(callableDescriptor)
if (!(element is KtNamedFunction || element is KtPropertyAccessor)) {
throw IllegalStateException("Couldn't find declaration for function $callableDescriptor")
}
val inliningFunction = element as KtDeclarationWithBody?
val node = MethodNode(
Opcodes.API_VERSION,
DescriptorAsmUtil.getMethodAsmFlags(callableDescriptor, context.contextKind, state) or if (callDefault) Opcodes.ACC_STATIC else 0,
asmMethod.name,
asmMethod.descriptor, null, null
)
//for maxLocals calculation
val maxCalcAdapter = wrapWithMaxLocalCalc(node)
val parentContext = context.parentContext ?: error("Context has no parent: " + context)
val methodContext = parentContext.intoFunction(callableDescriptor)
val smap = if (callDefault) {
val implementationOwner = state.typeMapper.mapImplementationOwner(callableDescriptor)
val parentCodegen = FakeMemberCodegen(
codegen.parentCodegen, inliningFunction!!, methodContext.parentContext as FieldOwnerContext<*>,
implementationOwner.internalName,
additionalInnerClasses,
false
)
if (element !is KtNamedFunction) {
throw IllegalStateException("Property accessors with default parameters not supported $callableDescriptor")
}
FunctionCodegen.generateDefaultImplBody(
methodContext, callableDescriptor, maxCalcAdapter, DefaultParameterValueLoader.DEFAULT,
inliningFunction as KtNamedFunction?, parentCodegen, asmMethod
)
SMAP(parentCodegen.orCreateSourceMapper.resultMappings)
} else {
generateMethodBody(maxCalcAdapter, callableDescriptor, methodContext, inliningFunction!!, jvmSignature, null)
}
maxCalcAdapter.visitMaxs(-1, -1)
maxCalcAdapter.visitEnd()
return SMAPAndMethodNode(node, smap)
}
override fun hasFinallyBlocks() = codegen.hasFinallyBlocks()
override fun generateFinallyBlocksIfNeeded(codegen: BaseExpressionCodegen, returnType: Type, afterReturnLabel: Label, target: Label?) {
// TODO use the target label for non-local break/continue
require(codegen is ExpressionCodegen)
codegen.generateFinallyBlocksIfNeeded(returnType, null, afterReturnLabel)
}
override fun createCodegenForExternalFinallyBlockGenerationOnNonLocalReturn(finallyNode: MethodNode, curFinallyDepth: Int) =
ExpressionCodegen(
finallyNode, codegen.frameMap, codegen.returnType,
codegen.getContext(), codegen.state, codegen.parentCodegen
).also {
it.addBlockStackElementsForNonLocalReturns(codegen.blockStackElements, curFinallyDepth)
}
override fun isCallInsideSameModuleAsDeclared(functionDescriptor: FunctionDescriptor): Boolean {
return JvmCodegenUtil.isCallInsideSameModuleAsDeclared(functionDescriptor, codegen.getContext(), codegen.state.outDirectory)
}
override fun isFinallyMarkerRequired(): Boolean = isFinallyMarkerRequired(codegen.getContext())
override val compilationContextDescriptor
get() = codegen.getContext().contextDescriptor
override val compilationContextFunctionDescriptor
get() = codegen.getContext().functionDescriptor
override fun getContextLabels(): Map<String, Label?> {
val context = codegen.getContext()
val parentContext = context.parentContext
val descriptor = if (parentContext is ClosureContext && parentContext.originalSuspendLambdaDescriptor != null) {
parentContext.originalSuspendLambdaDescriptor!!
} else context.contextDescriptor
val labels = InlineCodegen.getDeclarationLabels(DescriptorToSourceUtils.descriptorToDeclaration(descriptor), descriptor)
return labels.associateWith { null } // TODO add break/continue labels
}
fun initializeInlineFunctionContext(functionDescriptor: FunctionDescriptor) {
context = getContext(
functionDescriptor,
functionDescriptor,
state,
DescriptorToSourceUtils.descriptorToDeclaration(functionDescriptor)?.containingFile as? KtFile,
additionalInnerClasses
)
}
override fun reportSuspensionPointInsideMonitor(stackTraceElement: String) {
org.jetbrains.kotlin.codegen.coroutines.reportSuspensionPointInsideMonitor(callElement, state, stackTraceElement)
}
companion object {
fun getContext(
descriptor: DeclarationDescriptor,
innerDescriptor: DeclarationDescriptor,
state: GenerationState,
sourceFile: KtFile?,
additionalInners: MutableList<ClassDescriptor>
): CodegenContext<*> {
if (descriptor is PackageFragmentDescriptor) {
//no inners
return PackageContext(descriptor, state.rootContext, null, sourceFile)
}
val container = descriptor.containingDeclaration ?: error("No container for descriptor: $descriptor")
val containerContext = getContext(
container,
descriptor,
state,
sourceFile,
additionalInners
)
return when (descriptor) {
is ScriptDescriptor -> {
val earlierScripts = state.scriptSpecific.earlierScriptsForReplInterpreter
containerContext.intoScript(
descriptor,
earlierScripts ?: emptyList(),
descriptor as ClassDescriptor, state.typeMapper
)
}
is ClassDescriptor -> {
val kind =
when {
DescriptorUtils.isInterface(descriptor) &&
innerDescriptor !is ClassDescriptor &&
!innerDescriptor.isCallableMemberCompiledToJvmDefault(state.jvmDefaultMode) ->
OwnerKind.DEFAULT_IMPLS
else ->
OwnerKind.IMPLEMENTATION
}
additionalInners.addIfNotNull(
InnerClassConsumer.classForInnerClassRecord(descriptor, kind == OwnerKind.DEFAULT_IMPLS)
)
if (descriptor.isInlineClass()) {
containerContext.intoClass(descriptor, OwnerKind.IMPLEMENTATION, state)
.intoClass(descriptor, OwnerKind.ERASED_INLINE_CLASS, state)
} else {
containerContext.intoClass(descriptor, kind, state)
}
}
is FunctionDescriptor -> {
containerContext.intoFunction(descriptor)
}
else -> {
throw IllegalStateException("Couldn't build context for $descriptor")
}
}
}
}
fun GenerationState.trackLookup(container: FqName, functionName: String, location: LocationInfo) {
val lookupTracker = configuration.get(CommonConfigurationKeys.LOOKUP_TRACKER) ?: return
lookupTracker.record(
location.filePath,
if (lookupTracker.requiresPosition) location.position else Position.NO_POSITION,
container.asString(),
ScopeKind.CLASSIFIER,
functionName
)
}
fun DeclarationDescriptor.isInlineOrInsideInline(): Boolean =
if (this is FunctionDescriptor && isInline) true
else containingDeclaration?.isInlineOrInsideInline() == true
fun loadCompiledInlineFunction(
containerId: ClassId,
asmMethod: Method,
isSuspend: Boolean,
isMangled: Boolean,
state: GenerationState
): SMAPAndMethodNode {
val containerType = AsmUtil.asmTypeByClassId(containerId)
val bytes = state.inlineCache.classBytes.getOrPut(containerType.internalName) {
findVirtualFile(state, containerId)?.contentsToByteArray()
?: throw IllegalStateException("Couldn't find declaration file for $containerId")
}
val resultInCache = state.inlineCache.methodNodeById.getOrPut(MethodId(containerType.descriptor, asmMethod)) {
getMethodNode(containerType, bytes, asmMethod.name, asmMethod.descriptor, isSuspend, isMangled)
}
return SMAPAndMethodNode(cloneMethodNode(resultInCache.node), resultInCache.classSMAP)
}
private fun getMethodNode(
owner: Type,
bytes: ByteArray,
name: String,
descriptor: String,
isSuspend: Boolean,
isMangled: Boolean
): SMAPAndMethodNode {
getMethodNode(owner, bytes, name, descriptor, isSuspend)?.let { return it }
if (isMangled) {
// Compatibility with old inline class ABI versions.
val dashIndex = name.indexOf('-')
val nameWithoutManglingSuffix = if (dashIndex > 0) name.substring(0, dashIndex) else name
if (nameWithoutManglingSuffix != name) {
getMethodNode(owner, bytes, nameWithoutManglingSuffix, descriptor, isSuspend)?.let { return it }
}
getMethodNode(owner, bytes, "$nameWithoutManglingSuffix-impl", descriptor, isSuspend)?.let { return it }
}
throw IllegalStateException("couldn't find inline method $owner.$name$descriptor")
}
// If an `inline suspend fun` has a state machine, it should have a `$$forInline` version without one.
private fun getMethodNode(owner: Type, bytes: ByteArray, name: String, descriptor: String, isSuspend: Boolean) =
(if (isSuspend) getMethodNode(bytes, name + FOR_INLINE_SUFFIX, descriptor, owner) else null)
?: getMethodNode(bytes, name, descriptor, owner)

View File

@@ -2,11 +2,10 @@
* 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("JAVA_MODULE_DOES_NOT_EXPORT_PACKAGE")
package org.jetbrains.kotlin.codegen.inline.coroutines
import com.intellij.util.ArrayUtil
import jdk.internal.org.objectweb.asm.Type
import org.jetbrains.kotlin.codegen.ClassBuilder
import org.jetbrains.kotlin.codegen.coroutines.*
import org.jetbrains.kotlin.codegen.inline.*
@@ -14,12 +13,11 @@ import org.jetbrains.kotlin.codegen.optimization.common.asSequence
import org.jetbrains.kotlin.codegen.optimization.transformer.MethodTransformer
import org.jetbrains.kotlin.config.JVMConfigurationKeys
import org.jetbrains.kotlin.config.isReleaseCoroutines
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
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.tree.*
import org.jetbrains.org.objectweb.asm.tree.analysis.BasicInterpreter
import org.jetbrains.org.objectweb.asm.tree.analysis.BasicValue
@@ -93,8 +91,8 @@ class CoroutineTransformer(
obtainClassBuilderForCoroutineState = { classBuilder },
reportSuspensionPointInsideMonitor = { sourceCompilerForInline.reportSuspensionPointInsideMonitor(it) },
// TODO: this linenumbers might not be correct and since they are used only for step-over, check them.
lineNumber = sourceCompilerForInline.inlineCallSiteInfo.lineNumber,
sourceFile = sourceCompilerForInline.callsiteFile?.name ?: "",
lineNumber = inliningContext.callSiteInfo.lineNumber,
sourceFile = inliningContext.callSiteInfo.file?.name ?: "",
languageVersionSettings = state.languageVersionSettings,
shouldPreserveClassInitialization = state.constructorCallNormalizationMode.shouldPreserveClassInitialization,
containingClassInternalName = classBuilder.thisName,
@@ -127,8 +125,8 @@ class CoroutineTransformer(
createNewMethodFrom(node, name), node.access, name, node.desc, null, null,
obtainClassBuilderForCoroutineState = { (inliningContext as RegeneratedClassContext).continuationBuilders[continuationClassName]!! },
reportSuspensionPointInsideMonitor = { sourceCompilerForInline.reportSuspensionPointInsideMonitor(it) },
lineNumber = sourceCompilerForInline.inlineCallSiteInfo.lineNumber,
sourceFile = sourceCompilerForInline.callsiteFile?.name ?: "",
lineNumber = inliningContext.callSiteInfo.lineNumber,
sourceFile = inliningContext.callSiteInfo.file?.name ?: "",
languageVersionSettings = state.languageVersionSettings,
shouldPreserveClassInitialization = state.constructorCallNormalizationMode.shouldPreserveClassInitialization,
containingClassInternalName = classBuilder.thisName,
@@ -235,24 +233,6 @@ fun surroundInvokesWithSuspendMarkersIfNeeded(node: MethodNode) {
}
}
// We cannot find the lambda in captured parameters: it came from object outside of the our reach:
// this can happen when the lambda capture by non-transformed closure:
// inline fun inlineMe(crossinline c: suspend() -> Unit) = suspend { c() }
// inline fun inlineMe2(crossinline c: suspend() -> Unit) = suspend { inlineMe { c() }() }
// Suppose, we inline inlineMe into inlineMe2: the only knowledge we have about inlineMe$1 is captured receiver (this$0)
// Thus, transformed lambda from inlineMe, inlineMe3$$inlined$inlineMe2$1 contains the following bytecode
// ALOAD 0
// GETFIELD inlineMe2$1$invokeSuspend$$inlined$inlineMe$1.this$0 : LScratchKt$inlineMe2$1;
// GETFIELD inlineMe2$1.$c : Lkotlin/jvm/functions/Function1;
// Since inlineMe2's lambda is outside of reach of the inliner, find crossinline parameter from compilation context:
fun FieldInsnNode.isSuspendLambdaCapturedByOuterObjectOrLambda(inliningContext: InliningContext): Boolean {
var container: DeclarationDescriptor = inliningContext.root.sourceCompilerForInline.compilationContextFunctionDescriptor
while (container !is ClassDescriptor) {
container = container.containingDeclaration ?: return false
}
return isCapturedSuspendLambda(container, name, inliningContext.state.bindingContext)
}
// Interpreter, that keeps track of captured functional arguments
private class PossibleLambdaLoad(val insn: AbstractInsnNode) : BasicValue(AsmTypes.OBJECT_TYPE)
@@ -287,4 +267,4 @@ private class CapturedLambdaInterpreter : BasicInterpreter(Opcodes.API_VERSION)
override fun merge(v: BasicValue?, w: BasicValue?): BasicValue? =
if (v is PossibleLambdaLoad && w is PossibleLambdaLoad && v.insn == w.insn) v else super.merge(v, w)
}
}

View File

@@ -60,15 +60,15 @@ fun extractDefaultLambdaOffsetAndDescriptor(
}
}
class ExtractedDefaultLambda(val type: Type, val capturedArgs: Array<Type>, val offset: Int, val needReification: Boolean)
fun <T, R : DefaultLambda> expandMaskConditionsAndUpdateVariableNodes(
fun expandMaskConditionsAndUpdateVariableNodes(
node: MethodNode,
maskStartIndex: Int,
masks: List<Int>,
methodHandlerIndex: Int,
defaultLambdas: Map<Int, T>,
lambdaConstructor: (Type, Array<Type>, T, Int, Boolean) -> R
): List<R> {
validOffsets: Collection<Int>
): List<ExtractedDefaultLambda> {
fun isMaskIndex(varIndex: Int): Boolean {
return maskStartIndex <= varIndex && varIndex < maskStartIndex + masks.size
}
@@ -111,7 +111,8 @@ fun <T, R : DefaultLambda> expandMaskConditionsAndUpdateVariableNodes(
val toDelete = linkedSetOf<AbstractInsnNode>()
val toInsert = arrayListOf<Pair<AbstractInsnNode, AbstractInsnNode>>()
val defaultLambdasInfo = extractDefaultLambdasInfo(conditions, defaultLambdas, toDelete, toInsert, lambdaConstructor)
val extractable = conditions.filter { it.expandNotDelete && it.varIndex in validOffsets }
val defaultLambdasInfo = extractDefaultLambdasInfo(extractable, toDelete, toInsert)
val indexToVarNode = node.localVariables?.filter { it.index < maskStartIndex }?.associateBy { it.index } ?: emptyMap()
conditions.forEach {
@@ -131,7 +132,7 @@ fun <T, R : DefaultLambda> expandMaskConditionsAndUpdateVariableNodes(
}
node.localVariables.removeIf {
(it.start in toDelete && it.end in toDelete) || defaultLambdas.contains(it.index)
(it.start in toDelete && it.end in toDelete) || validOffsets.contains(it.index)
}
node.remove(toDelete)
@@ -139,16 +140,12 @@ fun <T, R : DefaultLambda> expandMaskConditionsAndUpdateVariableNodes(
return defaultLambdasInfo
}
private fun <T, R : DefaultLambda> extractDefaultLambdasInfo(
private fun extractDefaultLambdasInfo(
conditions: List<Condition>,
defaultLambdas: Map<Int, T>,
toDelete: MutableCollection<AbstractInsnNode>,
toInsert: MutableList<Pair<AbstractInsnNode, AbstractInsnNode>>,
lambdaConstructor: (Type, Array<Type>, T, Int, Boolean) -> R
): List<R> {
val defaultLambdaConditions = conditions.filter { it.expandNotDelete && defaultLambdas.contains(it.varIndex) }
return defaultLambdaConditions.map {
toInsert: MutableList<Pair<AbstractInsnNode, AbstractInsnNode>>
): List<ExtractedDefaultLambda> {
return conditions.map {
val varAssignmentInstruction = it.varInsNode!!
var instanceInstuction = varAssignmentInstruction.previous
if (instanceInstuction is TypeInsnNode && instanceInstuction.opcode == Opcodes.CHECKCAST) {
@@ -190,7 +187,7 @@ private fun <T, R : DefaultLambda> extractDefaultLambdasInfo(
toInsert.add(varAssignmentInstruction to defaultLambdaFakeCallStub(argTypes, it.varIndex))
lambdaConstructor(owner, argTypes, defaultLambdas[it.varIndex]!!, it.varIndex, needReification)
ExtractedDefaultLambda(owner, argTypes, it.varIndex, needReification)
}
}

View File

@@ -579,8 +579,8 @@ class InlineOnlySmapSkipper(codegen: BaseExpressionCodegen) {
const val LOCAL_VARIABLE_INLINE_ARGUMENT_SYNTHETIC_LINE_NUMBER = 1
}
fun onInlineLambdaStart(mv: MethodVisitor, info: LambdaInfo, smap: SourceMapper) {
val firstLine = info.node.node.instructions.asSequence().mapNotNull { it as? LineNumberNode }.firstOrNull()?.line ?: -1
fun onInlineLambdaStart(mv: MethodVisitor, lambda: MethodNode, smap: SourceMapper) {
val firstLine = lambda.instructions.asSequence().mapNotNull { it as? LineNumberNode }.firstOrNull()?.line ?: -1
if (callLineNumber >= 0 && firstLine == callLineNumber) {
// We want the debugger to be able to break both on the inline call itself, plus on each
// invocation of the inline lambda passed to it. For that to happen there needs to be at least

View File

@@ -14,8 +14,9 @@ import org.jetbrains.kotlin.codegen.coroutines.createMethodNodeForCoroutineConte
import org.jetbrains.kotlin.codegen.coroutines.createMethodNodeForIntercepted
import org.jetbrains.kotlin.codegen.coroutines.createMethodNodeForSuspendCoroutineUninterceptedOrReturn
import org.jetbrains.kotlin.codegen.createMethodNodeForAlwaysEnabledAssert
import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicArrayConstructors
import org.jetbrains.kotlin.codegen.isBuiltinAlwaysEnabledAssert
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
import org.jetbrains.kotlin.resolve.calls.checkers.TypeOfChecker
@@ -26,31 +27,42 @@ import org.jetbrains.kotlin.types.model.TypeParameterMarker
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.commons.Method
import org.jetbrains.org.objectweb.asm.tree.MethodNode
internal fun generateInlineIntrinsic(
state: GenerationState,
descriptor: FunctionDescriptor,
typeParameters: List<TypeParameterMarker>?,
typeSystem: TypeSystemCommonBackendContext
): MethodNode? {
val languageVersionSettings = state.languageVersionSettings
return when {
isSpecialEnumMethod(descriptor) ->
createSpecialEnumMethodBody(descriptor.name.asString(), typeParameters!!.single(), typeSystem)
TypeOfChecker.isTypeOf(descriptor) ->
typeSystem.createTypeOfMethodBody(typeParameters!!.single())
fun generateInlineIntrinsicForIr(languageVersionSettings: LanguageVersionSettings, descriptor: FunctionDescriptor): SMAPAndMethodNode? =
when {
// TODO: implement these as codegen intrinsics (see IrIntrinsicMethods)
descriptor.isBuiltInIntercepted(languageVersionSettings) ->
createMethodNodeForIntercepted(languageVersionSettings)
descriptor.isBuiltInCoroutineContext(languageVersionSettings) ->
createMethodNodeForCoroutineContext(descriptor, languageVersionSettings)
descriptor.isBuiltInSuspendCoroutineUninterceptedOrReturn(languageVersionSettings) ->
createMethodNodeForSuspendCoroutineUninterceptedOrReturn(languageVersionSettings)
else -> null
}?.let { SMAPAndMethodNode(it, SMAP(listOf())) }
internal fun generateInlineIntrinsic(
languageVersionSettings: LanguageVersionSettings,
descriptor: FunctionDescriptor,
asmMethod: Method,
typeSystem: TypeSystemCommonBackendContext
): SMAPAndMethodNode? {
return generateInlineIntrinsicForIr(languageVersionSettings, descriptor) ?: when {
isSpecialEnumMethod(descriptor) ->
createSpecialEnumMethodBody(descriptor.name.asString(), descriptor.original.typeParameters.single(), typeSystem)
TypeOfChecker.isTypeOf(descriptor) ->
typeSystem.createTypeOfMethodBody(descriptor.original.typeParameters.single())
descriptor.isBuiltinAlwaysEnabledAssert() ->
createMethodNodeForAlwaysEnabledAssert(descriptor)
descriptor is FictitiousArrayConstructor ->
IntrinsicArrayConstructors.generateArrayConstructorBody(asmMethod)
IntrinsicArrayConstructors.isArrayOf(descriptor) ->
IntrinsicArrayConstructors.generateArrayOfBody(asmMethod)
IntrinsicArrayConstructors.isEmptyArray(descriptor) ->
IntrinsicArrayConstructors.generateEmptyArrayBody(asmMethod)
else -> null
}
}?.let { SMAPAndMethodNode(it, SMAP(listOf())) }
}
private fun isSpecialEnumMethod(descriptor: FunctionDescriptor): Boolean {

View File

@@ -37,7 +37,7 @@ private fun TypeSystemCommonBackendContext.putTypeOfReifiedTypeParameter(
v.aconst(null)
}
internal fun <KT : KotlinTypeMarker> TypeSystemCommonBackendContext.generateTypeOf(
fun <KT : KotlinTypeMarker> TypeSystemCommonBackendContext.generateTypeOf(
v: InstructionAdapter, type: KT, intrinsicsSupport: ReifiedTypeInliner.IntrinsicsSupport<KT>
) {
val typeParameter = type.typeConstructor().getTypeParameterClassifier()
@@ -89,6 +89,21 @@ internal fun <KT : KotlinTypeMarker> TypeSystemCommonBackendContext.generateType
}
v.invokestatic(REFLECTION, methodName, signature, false)
if (intrinsicsSupport.state.stableTypeOf) {
if (intrinsicsSupport.isMutableCollectionType(type)) {
v.invokestatic(REFLECTION, "mutableCollectionType", Type.getMethodDescriptor(K_TYPE, K_TYPE), false)
}
if (type.isFlexible()) {
// If this is a flexible type, we've just generated its lower bound and have it on the stack.
// Let's generate the upper bound now and call the method that takes lower and upper bound and constructs a flexible KType.
@Suppress("UNCHECKED_CAST")
generateTypeOf(v, type.upperBoundIfFlexible() as KT, intrinsicsSupport)
v.invokestatic(REFLECTION, "platformType", Type.getMethodDescriptor(K_TYPE, K_TYPE, K_TYPE), false)
}
}
}
private fun <KT : KotlinTypeMarker> TypeSystemCommonBackendContext.generateNonReifiedTypeParameter(
@@ -103,7 +118,7 @@ private fun <KT : KotlinTypeMarker> TypeSystemCommonBackendContext.generateNonRe
TypeVariance.OUT -> KVariance.OUT
}
v.getstatic(K_VARIANCE.internalName, variance.name, K_VARIANCE.descriptor)
v.aconst(typeParameter.isReified())
v.iconst(if (typeParameter.isReified()) 1 else 0)
v.invokestatic(
REFLECTION, "typeParameter",
Type.getMethodDescriptor(K_TYPE_PARAMETER, OBJECT_TYPE, JAVA_STRING_TYPE, K_VARIANCE, Type.BOOLEAN_TYPE),
@@ -119,11 +134,11 @@ private fun <KT : KotlinTypeMarker> TypeSystemCommonBackendContext.generateNonRe
if (bounds.size == 1) {
generateTypeOf(v, bounds.single(), intrinsicsSupport)
} else {
v.aconst(bounds.size)
v.iconst(bounds.size)
v.newarray(K_TYPE)
for ((i, bound) in bounds.withIndex()) {
v.dup()
v.aconst(i)
v.iconst(i)
generateTypeOf(v, bound, intrinsicsSupport)
v.astore(K_TYPE)
}

View File

@@ -12,8 +12,6 @@ import org.jetbrains.kotlin.load.kotlin.JvmPackagePartSource
import org.jetbrains.kotlin.load.kotlin.VirtualFileFinder
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.resolve.descriptorUtil.classId
import org.jetbrains.kotlin.resolve.isInlineClassType
import org.jetbrains.kotlin.resolve.underlyingRepresentation
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedSimpleFunctionDescriptor
import org.jetbrains.kotlin.types.KotlinType
@@ -26,9 +24,8 @@ import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.commons.Method
fun KotlinType.isInlineClassWithUnderlyingTypeAnyOrAnyN(): Boolean {
if (!isInlineClassType()) return false
val classDescriptor = constructor.declarationDescriptor as? ClassDescriptor ?: return false
return classDescriptor.underlyingRepresentation()?.type?.isAnyOrNullableAny() == true
val classDescriptor = constructor.declarationDescriptor
return classDescriptor is ClassDescriptor && classDescriptor.inlineClassRepresentation?.underlyingType?.isAnyOrNullableAny() == true
}
fun CallableDescriptor.isGenericParameter(): Boolean {
@@ -79,4 +76,4 @@ fun classFileContainsMethod(classId: ClassId, state: GenerationState, method: Me
}
}, ClassReader.SKIP_FRAMES)
return found
}
}

View File

@@ -16,10 +16,14 @@
package org.jetbrains.kotlin.codegen.intrinsics
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.codegen.StackValue
import org.jetbrains.kotlin.codegen.inline.ReificationArgument
import org.jetbrains.kotlin.codegen.inline.ReifiedTypeInliner
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.org.objectweb.asm.Label
@@ -30,6 +34,15 @@ import org.jetbrains.org.objectweb.asm.commons.Method
import org.jetbrains.org.objectweb.asm.tree.MethodNode
internal object IntrinsicArrayConstructors {
fun isArrayOf(descriptor: FunctionDescriptor): Boolean =
descriptor.name.asString() == "arrayOf" && descriptor.containingDeclaration.isBuiltInsPackage
fun isEmptyArray(descriptor: FunctionDescriptor): Boolean =
descriptor.name.asString() == "emptyArray" && descriptor.containingDeclaration.isBuiltInsPackage
private val DeclarationDescriptor.isBuiltInsPackage: Boolean
get() = this is PackageFragmentDescriptor && fqName == StandardNames.BUILT_INS_PACKAGE_FQ_NAME
fun generateArrayConstructorBody(method: Method): MethodNode {
val node = MethodNode(
Opcodes.ASM6, Opcodes.ACC_PUBLIC or Opcodes.ACC_STATIC or Opcodes.ACC_FINAL, method.name, method.descriptor, null, null

View File

@@ -9,6 +9,7 @@ import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.codegen.ExpressionCodegen
import org.jetbrains.kotlin.codegen.StackValue
import org.jetbrains.kotlin.codegen.inline.ReifiedTypeInliner
import org.jetbrains.kotlin.codegen.putReifiedOperationMarkerIfTypeIsReifiedParameter
import org.jetbrains.kotlin.psi.KtClassLiteralExpression
import org.jetbrains.kotlin.resolve.BindingContext.DOUBLE_COLON_LHS
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall

View File

@@ -19,6 +19,7 @@ package org.jetbrains.kotlin.codegen.optimization
import org.jetbrains.kotlin.codegen.inline.insnText
import org.jetbrains.kotlin.codegen.optimization.common.OptimizationBasicInterpreter
import org.jetbrains.kotlin.codegen.optimization.common.StrictBasicValue
import org.jetbrains.kotlin.codegen.optimization.common.removeAll
import org.jetbrains.kotlin.codegen.optimization.fixStack.peek
import org.jetbrains.kotlin.codegen.optimization.fixStack.top
import org.jetbrains.kotlin.codegen.optimization.transformer.MethodTransformer
@@ -31,12 +32,10 @@ import org.jetbrains.org.objectweb.asm.tree.analysis.BasicValue
import org.jetbrains.org.objectweb.asm.tree.analysis.Frame
class ConstantConditionEliminationMethodTransformer : MethodTransformer() {
private val deadCodeElimination = DeadCodeEliminationMethodTransformer()
override fun transform(internalClassName: String, methodNode: MethodNode) {
do {
val changes = ConstantConditionsOptimization(internalClassName, methodNode).run()
if (changes) deadCodeElimination.transform(internalClassName, methodNode)
} while (changes)
}
@@ -49,11 +48,21 @@ class ConstantConditionEliminationMethodTransformer : MethodTransformer() {
private fun collectRewriteActions(): List<() -> Unit> =
arrayListOf<() -> Unit>().also { actions ->
val deadCode = ArrayList<AbstractInsnNode>()
val frames = analyze(internalClassName, methodNode, ConstantPropagationInterpreter())
val insns = methodNode.instructions.toArray()
for (i in frames.indices) {
val frame = frames[i] ?: continue
val insn = insns[i] as? JumpInsnNode ?: continue
val insn = insns[i]
val frame = frames[i]
if (frame == null && insn !is LabelNode) {
deadCode.add(insn)
continue
}
if (insn !is JumpInsnNode) continue
when (insn.opcode) {
in Opcodes.IFEQ..Opcodes.IFLE ->
tryRewriteComparisonWithZero(insn, frame, actions)
@@ -61,6 +70,12 @@ class ConstantConditionEliminationMethodTransformer : MethodTransformer() {
tryRewriteBinaryComparison(insn, frame, actions)
}
}
if (deadCode.isNotEmpty()) {
actions.add {
methodNode.instructions.removeAll(deadCode)
}
}
}
private fun tryRewriteComparisonWithZero(insn: JumpInsnNode, frame: Frame<BasicValue>, actions: ArrayList<() -> Unit>) {

View File

@@ -17,8 +17,9 @@
package org.jetbrains.kotlin.codegen.optimization
import org.jetbrains.kotlin.codegen.inline.remove
import org.jetbrains.kotlin.codegen.optimization.common.OptimizationBasicInterpreter
import org.jetbrains.kotlin.codegen.optimization.common.InstructionLivenessAnalyzer
import org.jetbrains.kotlin.codegen.optimization.common.removeEmptyCatchBlocks
import org.jetbrains.kotlin.codegen.optimization.common.removeUnusedLocalVariables
import org.jetbrains.kotlin.codegen.optimization.transformer.MethodTransformer
import org.jetbrains.org.objectweb.asm.tree.AbstractInsnNode
import org.jetbrains.org.objectweb.asm.tree.LabelNode
@@ -27,21 +28,14 @@ import org.jetbrains.org.objectweb.asm.tree.MethodNode
class DeadCodeEliminationMethodTransformer : MethodTransformer() {
override fun transform(internalClassName: String, methodNode: MethodNode) {
transformWithResult(internalClassName, methodNode)
}
val liveness = InstructionLivenessAnalyzer(methodNode).analyze()
fun transformWithResult(internalClassName: String, methodNode: MethodNode): Result {
val frames = analyze(internalClassName, methodNode, OptimizationBasicInterpreter())
return removeDeadCodeByFrames(methodNode, frames)
}
fun removeDeadCodeByFrames(methodNode: MethodNode, frames: Array<out Any?>): Result {
val insnsToRemove = ArrayList<AbstractInsnNode>()
val insns = methodNode.instructions.toArray()
for (i in insns.indices) {
val insn = insns[i]
if (shouldRemove(insn, i, frames)) {
if (shouldRemove(insn, i, liveness)) {
insnsToRemove.add(insn)
}
}
@@ -51,46 +45,31 @@ class DeadCodeEliminationMethodTransformer : MethodTransformer() {
// Remove empty try-catch blocks to make sure we don't break data flow analysis invariants by dead code elimination.
methodNode.removeEmptyCatchBlocks()
return Result(insnsToRemove.toSet())
methodNode.removeUnusedLocalVariables()
}
private fun shouldRemove(insn: AbstractInsnNode, index: Int, frames: Array<out Any?>): Boolean =
when (insn) {
is LabelNode ->
// Do not remove label nodes because they can be referred by try/catch blocks or local variables table
false
is LineNumberNode ->
isDeadLineNumber(insn, index, frames)
else ->
frames[index] == null
}
private fun shouldRemove(insn: AbstractInsnNode, index: Int, liveness: BooleanArray): Boolean {
if (insn !is LineNumberNode) return !liveness[index]
private fun isDeadLineNumber(insn: LineNumberNode, index: Int, frames: Array<out Any?>): Boolean {
// Line number node is "dead" if the corresponding line number interval
// contains at least one "dead" meaningful instruction and no "live" meaningful instructions.
var finger: AbstractInsnNode = insn
var fingerIndex = index
var hasDeadInsn = false
loop@ while (true) {
while (true) {
finger = finger.next ?: break
fingerIndex++
when (finger) {
is LabelNode ->
continue@loop
continue
is LineNumberNode ->
if (finger.line != insn.line) return hasDeadInsn
else -> {
if (frames[fingerIndex] != null) return false
if (liveness[fingerIndex]) return false
hasDeadInsn = true
}
}
}
return true
}
class Result(private val removedNodes: Set<AbstractInsnNode>) {
fun hasRemovedAnything() = removedNodes.isNotEmpty()
fun isRemoved(node: AbstractInsnNode) = removedNodes.contains(node)
fun isAlive(node: AbstractInsnNode) = !isRemoved(node)
}
}

View File

@@ -18,12 +18,16 @@ package org.jetbrains.kotlin.codegen.optimization.boxing
import com.google.common.collect.ImmutableSet
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.codegen.coroutines.RELEASE_COROUTINES_VERSION_SETTINGS
import org.jetbrains.kotlin.codegen.coroutines.coroutinesJvmInternalPackageFqName
import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicMethods
import org.jetbrains.kotlin.codegen.optimization.common.OptimizationBasicInterpreter
import org.jetbrains.kotlin.codegen.optimization.common.StrictBasicValue
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper
import org.jetbrains.kotlin.codegen.topLevelClassInternalName
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.resolve.jvm.JvmPrimitiveType
import org.jetbrains.org.objectweb.asm.Opcodes
@@ -174,7 +178,7 @@ fun AbstractInsnNode.isUnboxing(state: GenerationState) =
isPrimitiveUnboxing() || isJavaLangClassUnboxing() || isInlineClassUnboxing(state)
fun AbstractInsnNode.isBoxing(state: GenerationState) =
isPrimitiveBoxing() || isJavaLangClassBoxing() || isInlineClassBoxing(state)
isPrimitiveBoxing() || isJavaLangClassBoxing() || isInlineClassBoxing(state) || isCoroutinePrimitiveBoxing()
fun AbstractInsnNode.isPrimitiveUnboxing() =
isMethodInsnWith(Opcodes.INVOKEVIRTUAL) {
@@ -211,6 +215,19 @@ fun AbstractInsnNode.isPrimitiveBoxing() =
isBoxingMethodDescriptor()
}
private val BOXING_CLASS_INTERNAL_NAME =
RELEASE_COROUTINES_VERSION_SETTINGS.coroutinesJvmInternalPackageFqName().child(Name.identifier("Boxing")).topLevelClassInternalName()
private fun isJvmPrimitiveName(name: String) = JvmPrimitiveType.values().any { it.javaKeywordName == name }
fun AbstractInsnNode.isCoroutinePrimitiveBoxing(): Boolean {
return isMethodInsnWith(Opcodes.INVOKESTATIC) {
owner == BOXING_CLASS_INTERNAL_NAME &&
name.startsWith("box") &&
isJvmPrimitiveName(name.substring(3).lowercase())
}
}
private fun MethodInsnNode.isBoxingMethodDescriptor(): Boolean {
val ownerType = Type.getObjectType(owner)
return desc == Type.getMethodDescriptor(ownerType, AsmUtil.unboxType(ownerType))

View File

@@ -17,12 +17,9 @@
package org.jetbrains.kotlin.codegen.optimization.boxing
import org.jetbrains.kotlin.codegen.optimization.OptimizationMethodVisitor
import org.jetbrains.kotlin.codegen.optimization.common.debugText
import org.jetbrains.kotlin.codegen.optimization.common.isLoadOperation
import org.jetbrains.kotlin.codegen.optimization.common.isMeaningful
import org.jetbrains.kotlin.codegen.optimization.fixStack.peekWords
import org.jetbrains.kotlin.codegen.optimization.fixStack.top
import org.jetbrains.kotlin.codegen.optimization.removeNodeGetNext
import org.jetbrains.kotlin.codegen.optimization.transformer.MethodTransformer
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.tree.*
@@ -32,91 +29,66 @@ import org.jetbrains.org.objectweb.asm.tree.analysis.SourceInterpreter
import org.jetbrains.org.objectweb.asm.tree.analysis.SourceValue
import java.util.*
private typealias Transformation = (AbstractInsnNode) -> Unit
class PopBackwardPropagationTransformer : MethodTransformer() {
override fun transform(internalClassName: String, methodNode: MethodNode) {
if (!OptimizationMethodVisitor.canBeOptimizedUsingSourceInterpreter(methodNode)) return
Transformer(methodNode).transform()
if (methodNode.instructions.any { it.isPop() || it.isPurePush() }) {
Transformer(methodNode).transform()
}
}
private class Transformer(val methodNode: MethodNode) {
private interface Transformation {
fun apply(insn: AbstractInsnNode)
}
private inline fun Transformation(crossinline body: (AbstractInsnNode) -> Unit): Transformation =
object : Transformation {
override fun apply(insn: AbstractInsnNode) {
body(insn)
}
}
private val REPLACE_WITH_NOP = Transformation { insnList.set(it, createRemovableNopInsn()) }
private val REPLACE_WITH_POP1 = Transformation { insnList.set(it, InsnNode(Opcodes.POP)) }
private val REPLACE_WITH_POP2 = Transformation { insnList.set(it, InsnNode(Opcodes.POP2)) }
private val INSERT_POP1_AFTER = Transformation { insnList.insert(it, InsnNode(Opcodes.POP)) }
private val INSERT_POP2_AFTER = Transformation { insnList.insert(it, InsnNode(Opcodes.POP2)) }
private val REPLACE_WITH_NOP: Transformation = { insnList.set(it, InsnNode(Opcodes.NOP)) }
private val REPLACE_WITH_POP1: Transformation = { insnList.set(it, InsnNode(Opcodes.POP)) }
private val REPLACE_WITH_POP2: Transformation = { insnList.set(it, InsnNode(Opcodes.POP2)) }
private val INSERT_POP1_AFTER: Transformation = { insnList.insert(it, InsnNode(Opcodes.POP)) }
private val INSERT_POP2_AFTER: Transformation = { insnList.insert(it, InsnNode(Opcodes.POP2)) }
private val insnList = methodNode.instructions
private val insns = insnList.toArray()
private val dontTouchInsnIndices = BitSet(insns.size)
private val transformations = hashMapOf<AbstractInsnNode, Transformation>()
private val removableNops = hashSetOf<InsnNode>()
private val frames by lazy { analyzeMethodBody() }
fun transform() {
if (insns.none { it.isPop() || it.isPurePush() }) return
computeTransformations()
for ((insn, transformation) in transformations.entries) {
transformation.apply(insn)
}
postprocessNops()
}
private fun analyzeMethodBody(): Array<out Frame<SourceValue>?> {
val frames = Analyzer<SourceValue>(HazardsTrackingInterpreter()).analyze("fake", methodNode)
postprocessStackHazards(frames)
return frames
}
private fun postprocessStackHazards(frames: Array<out Frame<SourceValue>?>) {
val insns = methodNode.instructions.toArray()
for (i in frames.indices) {
val frames = Analyzer(HazardsTrackingInterpreter()).analyze("fake", methodNode)
for ((i, insn) in insns.withIndex()) {
val frame = frames[i] ?: continue
val insn = insns[i]
when (insn.opcode) {
Opcodes.POP2 -> {
val top2 = frame.peekWords(2) ?: throwIncorrectBytecode(insn, frame)
top2.forEach { it.insns.markAsDontTouch() }
}
Opcodes.DUP_X1 -> {
val top2 = frame.peekWords(1, 1) ?: throwIncorrectBytecode(insn, frame)
top2.forEach { it.insns.markAsDontTouch() }
}
Opcodes.DUP2_X1 -> {
val top3 = frame.peekWords(2, 1) ?: throwIncorrectBytecode(insn, frame)
top3.forEach { it.insns.markAsDontTouch() }
}
Opcodes.DUP_X2 -> {
val top3 = frame.peekWords(1, 2) ?: throwIncorrectBytecode(insn, frame)
top3.forEach { it.insns.markAsDontTouch() }
}
Opcodes.DUP2_X2 -> {
val top4 = frame.peekWords(2, 2) ?: throwIncorrectBytecode(insn, frame)
top4.forEach { it.insns.markAsDontTouch() }
Opcodes.POP ->
frame.top()?.let { input ->
// If this POP won't be removed, other POPs that touch the same values have to stay as well.
if (input.insns.any { it.shouldKeep() } || input.longerWhenFusedWithPop()) {
input.insns.markAsDontTouch()
}
}
Opcodes.POP2 -> frame.peekWords(2)?.forEach { it.insns.markAsDontTouch() }
Opcodes.DUP_X1 -> frame.peekWords(1, 1)?.forEach { it.insns.markAsDontTouch() }
Opcodes.DUP2_X1 -> frame.peekWords(2, 1)?.forEach { it.insns.markAsDontTouch() }
Opcodes.DUP_X2 -> frame.peekWords(1, 2)?.forEach { it.insns.markAsDontTouch() }
Opcodes.DUP2_X2 -> frame.peekWords(2, 2)?.forEach { it.insns.markAsDontTouch() }
}
}
val transformations = hashMapOf<AbstractInsnNode, Transformation>()
for ((i, insn) in insns.withIndex()) {
val frame = frames[i] ?: continue
if (insn.opcode == Opcodes.POP) {
val input = frame.top() ?: continue
if (input.insns.none { it.shouldKeep() }) {
transformations[insn] = REPLACE_WITH_NOP
input.insns.forEach {
if (it !in transformations) {
transformations[it] = it.combineWithPop(frames, input.size)
}
}
}
}
}
}
private fun throwIncorrectBytecode(insn: AbstractInsnNode?, frame: Frame<SourceValue>): Nothing {
throw AssertionError("Incorrect bytecode at ${methodNode.instructions.indexOf(insn)}: ${insn.debugText} $frame")
for ((insn, transformation) in transformations.entries) {
transformation(insn)
}
}
private inner class HazardsTrackingInterpreter : SourceInterpreter(Opcodes.API_VERSION) {
@@ -133,9 +105,7 @@ class PopBackwardPropagationTransformer : MethodTransformer() {
}
override fun unaryOperation(insn: AbstractInsnNode, value: SourceValue): SourceValue {
if (insn.opcode != Opcodes.CHECKCAST && !insn.isPrimitiveTypeConversion()) {
value.insns.markAsDontTouch()
}
value.insns.markAsDontTouch()
return super.unaryOperation(insn, value)
}
@@ -164,153 +134,48 @@ class PopBackwardPropagationTransformer : MethodTransformer() {
}
}
private fun computeTransformations() {
transformations.clear()
for (i in insns.indices) {
if (frames[i] == null) continue
val insn = insns[i]
if (insn.opcode == Opcodes.POP) {
propagatePopBackwards(insn, 0)
}
}
}
private fun propagatePopBackwards(insn: AbstractInsnNode, poppedValueSize: Int) {
if (transformations.containsKey(insn)) return
private fun SourceValue.longerWhenFusedWithPop() = insns.fold(0) { x, insn ->
when {
insn.opcode == Opcodes.POP -> {
val inputTop = getInputTop(insn)
val sources = inputTop.insns
if (sources.all { !isDontTouch(it) } && sources.any { isTransformablePopOperand(it) }) {
transformations[insn] = replaceWithNopTransformation()
sources.forEach { propagatePopBackwards(it, inputTop.size) }
insn.isPurePush() -> x - 1
insn.isPrimitiveBoxing() || insn.isPrimitiveTypeConversion() -> x
else -> x + 1
}
} > 0
private fun AbstractInsnNode.combineWithPop(frames: Array<out Frame<SourceValue>?>, resultSize: Int): Transformation =
when {
isPurePush() -> REPLACE_WITH_NOP
isPrimitiveBoxing() || isPrimitiveTypeConversion() -> {
val index = insnList.indexOf(this)
val frame = frames[index] ?: throw AssertionError("dead instruction #$index used by non-dead instruction")
val input = frame.top() ?: throw AssertionError("coercion instruction at #$index has no input")
when (input.size) {
1 -> REPLACE_WITH_POP1
2 -> REPLACE_WITH_POP2
else -> throw AssertionError("Unexpected pop value size: ${input.size}")
}
}
insn.opcode == Opcodes.CHECKCAST -> {
val inputTop = getInputTop(insn)
val sources = inputTop.insns
val resultType = (insn as TypeInsnNode).desc
if (sources.all { !isDontTouch(it) } && sources.any { isTransformableCheckcastOperand(it, resultType) }) {
transformations[insn] = replaceWithNopTransformation()
sources.forEach { propagatePopBackwards(it, inputTop.size) }
} else {
transformations[insn] = insertPopAfterTransformation(poppedValueSize)
else ->
when (resultSize) {
1 -> INSERT_POP1_AFTER
2 -> INSERT_POP2_AFTER
else -> throw AssertionError("Unexpected pop value size: $resultSize")
}
}
insn.isPrimitiveBoxing() -> {
val boxedValueSize = getInputTop(insn).size
transformations[insn] = replaceWithPopTransformation(boxedValueSize)
}
insn.isPurePush() -> {
transformations[insn] = replaceWithNopTransformation()
}
insn.isPrimitiveTypeConversion() -> {
val inputTop = getInputTop(insn)
val sources = inputTop.insns
if (sources.all { !isDontTouch(it) }) {
transformations[insn] = replaceWithNopTransformation()
sources.forEach { propagatePopBackwards(it, inputTop.size) }
} else {
transformations[insn] = replaceWithPopTransformation(poppedValueSize)
}
}
else -> {
transformations[insn] = insertPopAfterTransformation(poppedValueSize)
}
}
}
private fun postprocessNops() {
var node: AbstractInsnNode? = insnList.first
var hasRemovableNops = false
while (node != null) {
node = node.next
val begin = node ?: break
while (node != null && node !is LabelNode) {
if (node in removableNops) {
hasRemovableNops = true
}
node = node.next
}
val end = node
if (hasRemovableNops) {
removeUnneededNopsInRange(begin, end)
}
hasRemovableNops = false
}
}
private fun removeUnneededNopsInRange(begin: AbstractInsnNode, end: AbstractInsnNode?) {
var node: AbstractInsnNode? = begin
var keepNop = true
while (node != null && node != end) {
if (node in removableNops && !keepNop) {
node = insnList.removeNodeGetNext(node)
} else {
if (node.isMeaningful) keepNop = false
node = node.next
}
}
}
private fun replaceWithPopTransformation(size: Int): Transformation =
when (size) {
1 -> REPLACE_WITH_POP1
2 -> REPLACE_WITH_POP2
else -> throw AssertionError("Unexpected pop value size: $size")
}
private fun insertPopAfterTransformation(size: Int): Transformation =
when (size) {
1 -> INSERT_POP1_AFTER
2 -> INSERT_POP2_AFTER
else -> throw AssertionError("Unexpected pop value size: $size")
}
private fun replaceWithNopTransformation(): Transformation =
REPLACE_WITH_NOP
private fun createRemovableNopInsn() =
InsnNode(Opcodes.NOP).apply { removableNops.add(this) }
private fun getInputTop(insn: AbstractInsnNode): SourceValue {
val i = insnList.indexOf(insn)
val frame = frames[i] ?: throw AssertionError("Unexpected dead instruction #$i")
return frame.top() ?: throw AssertionError("Instruction #$i has empty stack on input")
}
private fun isTransformableCheckcastOperand(it: AbstractInsnNode, resultType: String) =
it.isPrimitiveBoxing() && (it as MethodInsnNode).owner == resultType
private fun isTransformablePopOperand(insn: AbstractInsnNode) =
insn.opcode == Opcodes.CHECKCAST || insn.isPrimitiveBoxing() || insn.isPurePush()
private fun isDontTouch(insn: AbstractInsnNode) =
dontTouchInsnIndices[insnList.indexOf(insn)]
private fun AbstractInsnNode.shouldKeep() =
dontTouchInsnIndices[insnList.indexOf(this)]
}
}
fun AbstractInsnNode.isPurePush() =
isLoadOperation() ||
opcode in Opcodes.ACONST_NULL..Opcodes.LDC + 2 ||
isUnitInstance()
isLoadOperation() || opcode in Opcodes.ACONST_NULL..Opcodes.LDC + 2 || isUnitInstance()
fun AbstractInsnNode.isPop() =
opcode == Opcodes.POP || opcode == Opcodes.POP2
fun AbstractInsnNode.isUnitInstance() =
opcode == Opcodes.GETSTATIC &&
this is FieldInsnNode && owner == "kotlin/Unit" && name == "INSTANCE"
opcode == Opcodes.GETSTATIC && this is FieldInsnNode && owner == "kotlin/Unit" && name == "INSTANCE"
fun AbstractInsnNode.isPrimitiveTypeConversion() =
opcode in Opcodes.I2L..Opcodes.I2S

View File

@@ -19,14 +19,12 @@ package org.jetbrains.kotlin.codegen.optimization.boxing
import org.jetbrains.kotlin.codegen.optimization.common.findPreviousOrNull
import org.jetbrains.kotlin.codegen.optimization.transformer.MethodTransformer
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.tree.AbstractInsnNode
import org.jetbrains.org.objectweb.asm.tree.InsnList
import org.jetbrains.org.objectweb.asm.tree.InsnNode
import org.jetbrains.org.objectweb.asm.tree.MethodNode
import org.jetbrains.org.objectweb.asm.tree.*
class StackPeepholeOptimizationsTransformer : MethodTransformer() {
override fun transform(internalClassName: String, methodNode: MethodNode) {
while (transformOnce(methodNode)) {
while (true) {
if (!transformOnce(methodNode)) break
}
}
@@ -115,20 +113,26 @@ class StackPeepholeOptimizationsTransformer : MethodTransformer() {
opcode == Opcodes.DUP
private fun AbstractInsnNode.isPurePushOfSize1(): Boolean =
opcode in Opcodes.ACONST_NULL..Opcodes.FCONST_2 ||
opcode in Opcodes.BIPUSH..Opcodes.ILOAD ||
opcode == Opcodes.FLOAD ||
opcode == Opcodes.ALOAD ||
isUnitInstance()
!isLdcOfSize2() && (
opcode in Opcodes.ACONST_NULL..Opcodes.FCONST_2 ||
opcode in Opcodes.BIPUSH..Opcodes.ILOAD ||
opcode == Opcodes.FLOAD ||
opcode == Opcodes.ALOAD ||
isUnitInstance()
)
private fun AbstractInsnNode.isEliminatedByPop2() =
isPurePushOfSize2() ||
opcode == Opcodes.DUP2
private fun AbstractInsnNode.isPurePushOfSize2(): Boolean =
opcode == Opcodes.LCONST_0 || opcode == Opcodes.LCONST_1 ||
isLdcOfSize2() ||
opcode == Opcodes.LCONST_0 || opcode == Opcodes.LCONST_1 ||
opcode == Opcodes.DCONST_0 || opcode == Opcodes.DCONST_1 ||
opcode == Opcodes.LLOAD ||
opcode == Opcodes.DLOAD
private fun AbstractInsnNode.isLdcOfSize2(): Boolean =
opcode == Opcodes.LDC && this is LdcInsnNode && (this.cst is Double || this.cst is Long)
}

View File

@@ -0,0 +1,148 @@
/*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.codegen.optimization.common
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.tree.*
class InstructionLivenessAnalyzer(val method: MethodNode) {
private val instructions = method.instructions
private val nInsns = instructions.size()
private val isLive = BooleanArray(nInsns)
private val handlers: Array<MutableList<TryCatchBlockNode>?> = arrayOfNulls(nInsns)
private val queued = BooleanArray(nInsns)
private val queue = IntArray(nInsns)
private var top = 0
private val AbstractInsnNode.indexOf get() = instructions.indexOf(this)
fun analyze(): BooleanArray {
if (nInsns == 0) return isLive
checkAssertions()
computeExceptionHandlersForEachInsn(method)
initControlFlowAnalysis()
traverseCfg()
// We consider labels referenced by LVs and TCBs always implicitly reachable
// (so that they don't get accidentally removed, producing corrupted class files),
// and let the client code decide what to do with redundant LVs and TCBs.
localVariableAndTryCatchBlockLabelsAreAlwaysLive()
// Last label in a method is always implicitly reachable (preserving our implicit invariants).
if (instructions.last is LabelNode) {
isLive[instructions.last.indexOf] = true
}
return isLive
}
private fun traverseCfg() {
while (top > 0) {
val insn = queue[--top]
val insnNode = method.instructions[insn]
val insnOpcode = insnNode.opcode
when (insnNode.type) {
AbstractInsnNode.LABEL, AbstractInsnNode.LINE, AbstractInsnNode.FRAME ->
visitOpInsn(insn)
AbstractInsnNode.JUMP_INSN ->
visitJumpInsnNode(insnNode as JumpInsnNode, insn, insnOpcode)
AbstractInsnNode.LOOKUPSWITCH_INSN ->
visitLookupSwitchInsnNode(insnNode as LookupSwitchInsnNode)
AbstractInsnNode.TABLESWITCH_INSN ->
visitTableSwitchInsnNode(insnNode as TableSwitchInsnNode)
else -> {
if (insnOpcode != Opcodes.ATHROW && (insnOpcode < Opcodes.IRETURN || insnOpcode > Opcodes.RETURN)) {
visitOpInsn(insn)
}
}
}
handlers[insn]?.forEach { tcb ->
visitControlFlowEdge(tcb.handler.indexOf)
}
}
}
private fun localVariableAndTryCatchBlockLabelsAreAlwaysLive() {
for (localVariable in method.localVariables) {
isLive[localVariable.start.indexOf] = true
isLive[localVariable.end.indexOf] = true
}
for (tcb in method.tryCatchBlocks) {
isLive[tcb.start.indexOf] = true
isLive[tcb.end.indexOf] = true
isLive[tcb.handler.indexOf] = true
}
}
private fun checkAssertions() {
if (instructions.any { it.opcode == Opcodes.JSR || it.opcode == Opcodes.RET })
throw AssertionError("Subroutines are deprecated since Java 6")
}
private fun visitOpInsn(insn: Int) {
visitControlFlowEdge(insn + 1)
}
private fun visitTableSwitchInsnNode(insnNode: TableSwitchInsnNode) {
var jump = insnNode.dflt.indexOf
visitControlFlowEdge(jump)
for (label in insnNode.labels) {
jump = instructions.indexOf(label)
visitControlFlowEdge(jump)
}
}
private fun visitLookupSwitchInsnNode(insnNode: LookupSwitchInsnNode) {
var jump = insnNode.dflt.indexOf
visitControlFlowEdge(jump)
for (label in insnNode.labels) {
jump = label.indexOf
visitControlFlowEdge(jump)
}
}
private fun visitJumpInsnNode(insnNode: JumpInsnNode, insn: Int, insnOpcode: Int) {
if (insnOpcode != Opcodes.GOTO && insnOpcode != Opcodes.JSR) {
visitControlFlowEdge(insn + 1)
}
val jump = insnNode.label.indexOf
visitControlFlowEdge(jump)
}
private fun initControlFlowAnalysis() {
visitControlFlowEdge(0)
}
private fun computeExceptionHandlersForEachInsn(m: MethodNode) {
for (tcb in m.tryCatchBlocks) {
val begin = tcb.start.indexOf
val end = tcb.end.indexOf
for (j in begin until end) {
var insnHandlers = handlers[j]
if (insnHandlers == null) {
insnHandlers = ArrayList<TryCatchBlockNode>()
handlers[j] = insnHandlers
}
insnHandlers.add(tcb)
}
}
}
private fun visitControlFlowEdge(insn: Int) {
val changes = !isLive[insn]
isLive[insn] = true
if (changes && !queued[insn]) {
queued[insn] = true
queue[top++] = insn
}
}
}

View File

@@ -62,7 +62,7 @@ import java.util.*
* @author Dmitry Petrov
*/
open class MethodAnalyzer<V : Value>(
val owner: String,
private val owner: String,
val method: MethodNode,
protected val interpreter: Interpreter<V>
) {

View File

@@ -39,9 +39,9 @@ import org.jetbrains.org.objectweb.asm.tree.*
class RedundantNullCheckMethodTransformer(private val generationState: GenerationState) : MethodTransformer() {
override fun transform(internalClassName: String, methodNode: MethodNode) {
@Suppress("ControlFlowWithEmptyBody")
while (TransformerPass(internalClassName, methodNode, generationState).run()) {
}
do {
val changes = TransformerPass(internalClassName, methodNode, generationState).run()
} while (changes)
}
private class TransformerPass(val internalClassName: String, val methodNode: MethodNode, val generationState: GenerationState) {
@@ -170,14 +170,14 @@ class RedundantNullCheckMethodTransformer(private val generationState: Generatio
}
private fun collectVariableDependentChecks() {
insnLoop@ for (insn in methodNode.instructions) {
for (insn in methodNode.instructions) {
when {
insn.isInstanceOfOrNullCheck() -> {
val previous = insn.previous ?: continue@insnLoop
val previous = insn.previous ?: continue
if (previous.opcode == Opcodes.ALOAD) {
addDependentCheck(insn, previous as VarInsnNode)
} else if (previous.opcode == Opcodes.DUP) {
val previous2 = previous.previous ?: continue@insnLoop
val previous2 = previous.previous ?: continue
if (previous2.opcode == Opcodes.ALOAD) {
addDependentCheck(insn, previous2 as VarInsnNode)
}
@@ -185,36 +185,36 @@ class RedundantNullCheckMethodTransformer(private val generationState: Generatio
}
insn.isCheckNotNull() -> {
val previous = insn.previous ?: continue@insnLoop
val previous = insn.previous ?: continue
val aLoadInsn = if (previous.opcode == Opcodes.DUP) {
previous.previous ?: continue@insnLoop
previous.previous ?: continue
} else previous
if (aLoadInsn.opcode != Opcodes.ALOAD) continue@insnLoop
if (aLoadInsn.opcode != Opcodes.ALOAD) continue
addDependentCheck(insn, aLoadInsn as VarInsnNode)
}
insn.isCheckParameterIsNotNull() -> {
val ldcInsn = insn.previous ?: continue@insnLoop
if (ldcInsn.opcode != Opcodes.LDC) continue@insnLoop
val aLoadInsn = ldcInsn.previous ?: continue@insnLoop
if (aLoadInsn.opcode != Opcodes.ALOAD) continue@insnLoop
val ldcInsn = insn.previous ?: continue
if (ldcInsn.opcode != Opcodes.LDC) continue
val aLoadInsn = ldcInsn.previous ?: continue
if (aLoadInsn.opcode != Opcodes.ALOAD) continue
addDependentCheck(insn, aLoadInsn as VarInsnNode)
}
insn.isCheckExpressionValueIsNotNull() -> {
val ldcInsn = insn.previous ?: continue@insnLoop
if (ldcInsn.opcode != Opcodes.LDC) continue@insnLoop
val ldcInsn = insn.previous ?: continue
if (ldcInsn.opcode != Opcodes.LDC) continue
var aLoadInsn: VarInsnNode? = null
val insn1 = ldcInsn.previous ?: continue@insnLoop
val insn1 = ldcInsn.previous ?: continue
if (insn1.opcode == Opcodes.ALOAD) {
aLoadInsn = insn1 as VarInsnNode
} else if (insn1.opcode == Opcodes.DUP) {
val insn2 = insn1.previous ?: continue@insnLoop
val insn2 = insn1.previous ?: continue
if (insn2.opcode == Opcodes.ALOAD) {
aLoadInsn = insn2 as VarInsnNode
}
}
if (aLoadInsn == null) continue@insnLoop
if (aLoadInsn == null) continue
addDependentCheck(insn, aLoadInsn)
}
}
@@ -436,6 +436,14 @@ internal fun AbstractInsnNode.isCheckNotNull() =
desc == "(Ljava/lang/Object;)V"
}
fun MethodNode.usesLocalExceptParameterNullCheck(index: Int): Boolean =
instructions.toArray().any {
it is VarInsnNode && it.opcode == Opcodes.ALOAD && it.`var` == index && !it.isParameterCheckedForNull()
}
internal fun AbstractInsnNode.isParameterCheckedForNull(): Boolean =
next?.takeIf { it.opcode == Opcodes.LDC }?.next?.isCheckParameterIsNotNull() == true
internal fun AbstractInsnNode.isCheckParameterIsNotNull() =
isInsn<MethodInsnNode>(Opcodes.INVOKESTATIC) {
owner == IntrinsicMethods.INTRINSICS_CLASS_NAME &&

View File

@@ -29,4 +29,7 @@ class JvmCodegenStringTable @JvmOverloads constructor(
ClassId(fqName.parent(), FqName.topLevel(fqName.shortName()), true)
}
}
override val isLocalClassIdReplacementKeptGeneric: Boolean
get() = true
}

View File

@@ -147,16 +147,18 @@ class GenerationState private constructor(
}
}
val languageVersionSettings = configuration.languageVersionSettings
val inlineCache: InlineCache = InlineCache()
val incrementalCacheForThisTarget: IncrementalCache?
val packagesWithObsoleteParts: Set<FqName>
val obsoleteMultifileClasses: List<FqName>
val deserializationConfiguration: DeserializationConfiguration =
CompilerDeserializationConfiguration(configuration.languageVersionSettings)
CompilerDeserializationConfiguration(languageVersionSettings)
val deprecationProvider = DeprecationResolver(
LockBasedStorageManager.NO_LOCKS, configuration.languageVersionSettings, CoroutineCompatibilitySupport.ENABLED,
LockBasedStorageManager.NO_LOCKS, languageVersionSettings, CoroutineCompatibilitySupport.ENABLED,
JavaDeprecationSettings
)
@@ -197,8 +199,6 @@ class GenerationState private constructor(
extraJvmDiagnosticsTrace.bindingContext.diagnostics
}
val languageVersionSettings = configuration.languageVersionSettings
val useOldManglingSchemeForFunctionsWithInlineClassesInSignatures =
configuration.getBoolean(JVMConfigurationKeys.USE_OLD_INLINE_CLASSES_MANGLING_SCHEME) ||
languageVersionSettings.languageVersion.run { major == 1 && minor < 4 }
@@ -260,11 +260,15 @@ class GenerationState private constructor(
val useKotlinNothingValueException =
languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_4 &&
!configuration.getBoolean(JVMConfigurationKeys.NO_KOTLIN_NOTHING_VALUE_EXCEPTION)
// In 1.6, `typeOf` became stable and started to rely on a few internal stdlib functions which were missing before 1.6.
val stableTypeOf = languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_6
val samWrapperClasses: SamWrapperClasses = SamWrapperClasses(this)
val globalInlineContext: GlobalInlineContext = GlobalInlineContext(diagnostics)
val mappingsClassesForWhenByEnum: MappingsClassesForWhenByEnum = MappingsClassesForWhenByEnum(this)
val jvmRuntimeTypes: JvmRuntimeTypes = JvmRuntimeTypes(
module, configuration.languageVersionSettings, generateOptimizedCallableReferenceSuperClasses
module, languageVersionSettings, generateOptimizedCallableReferenceSuperClasses
)
val factory: ClassFileFactory
private var duplicateSignatureFactory: BuilderFactoryForDuplicateSignatureDiagnostics? = null

View File

@@ -30,6 +30,7 @@ dependencies {
compile(project(":compiler:fir:fir2ir"))
compile(project(":compiler:fir:fir2ir:jvm-backend"))
compile(project(":compiler:fir:checkers"))
compile(project(":compiler:fir:checkers:checkers.jvm"))
compile(project(":kotlin-util-klib"))
compile(project(":kotlin-util-io"))

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