Compare commits

...

1903 Commits

Author SHA1 Message Date
Igor Yakovlev
8e885da677 [FIR IDE] Fix exception in FIR LC with special identifier names 2021-08-19 21:26:08 +02:00
Igor Yakovlev
2ce391d317 [FIR IDE] Fix unensured access to the return type 2021-08-19 21:26:08 +02:00
Igor Yakovlev
7a5a2bfcd7 [FIR] Fix invalid source for anonymous object type 2021-08-19 21:26:07 +02:00
Igor Yakovlev
5e6442b475 [FIR IDE] Suppress warnings to build project with warnings-as-errors mode 2021-08-19 21:26:07 +02:00
Igor Yakovlev
5498f40ce7 [FIR IDE] Fix reference resolve for functions call 2021-08-19 21:26:07 +02:00
Igor Yakovlev
42242e198b [FIR IDE] Fix invalid resolve for local declarations that could be outdated while incremental analisys 2021-08-19 21:26:07 +02:00
Igor Yakovlev
6360366ecc [FIR IDE] Fix invalid resolve for local declarations that could be fully replaced with new instance
+small optimisations for IMPORTS phase
2021-08-19 21:26:07 +02:00
Igor Yakovlev
ed0bfabc51 [FIR IDE] Fix invalid reference resolve for null safety operator 2021-08-19 21:26:07 +02:00
Igor Yakovlev
0a5dee567e [FIR IDE] Fix invalid property incremental analisys 2021-08-19 21:26:07 +02:00
Igor Yakovlev
0781156b42 [FIR IDE] Fix invalid reference resolve into companion with custom name 2021-08-19 21:26:07 +02:00
Igor Yakovlev
2ff4f10ff0 [FIR IDE] Fix SOE for FIR deserialized declarations provider 2021-08-19 21:26:07 +02:00
Igor Yakovlev
035f1ff89f [FIR IDE] Add ValueWithPostCompute recursive guard 2021-08-19 21:26:07 +02:00
Igor Yakovlev
d0e25eb987 [FIR IDE] Preprocess cone types in psi type mapper 2021-08-19 21:26:07 +02:00
Igor Yakovlev
79b70a6f98 [FIR IDE] Ensure resolved for status when resolving local declarations 2021-08-19 21:26:07 +02:00
Igor Yakovlev
21f36ef19a [FIR IDE] Fix inner light classes creation 2021-08-19 21:26:07 +02:00
Igor Yakovlev
0ca7fb7af5 [FIR] Fix JvmTypeMapper for generic type aliases 2021-08-19 21:26:06 +02:00
Igor Yakovlev
9bc695e245 [FIR IDE] Make one global lock for resolve 2021-08-19 21:26:06 +02:00
Georgy Bronnikov
b42358f893 JVM_IR: do not index on AttributeOwnerId in AddContinuationLowering 2021-08-19 21:53:47 +03:00
Georgy Bronnikov
32518eee4b JVM_IR: use computeIfAbsent in ClassCodegen.getOrCreate() 2021-08-19 21:53:46 +03:00
Georgy Bronnikov
a5a79215d7 JVM_IR: No need to use ConcurrentHashMap in ClassCodegen 2021-08-19 21:53:45 +03:00
Georgy Bronnikov
07eef9b751 JVM_IR: double call to adjustDefaultArgumentStubs 2021-08-19 21:53:44 +03:00
Alexander Shabalin
a7460e9061 [K/N] Enable lazy property initialization with the new MM 2021-08-19 18:23:01 +00:00
Ilmir Usmanov
b5fa129540 Loosen tail-call optimization check for functions returning Unit
Do not check, that all Unit predecessors are POPs. This is safe for the
same reason, as it is safe to allow some of ARETURN sources not be
suspension point results.
To elaborate, before Unit, the stack is empty. This is because if there
are multiple paths to Unit and at least one of them comes from POP after
suspension point (we are interested in this case only - otherwise, the
call is not tail-call), in path from said POP the stack is empty, since
after suspension point the stack contains only one element. Thus, the
stack in other paths leading to Unit has to be empty, otherwise, merge
operation is not possible and ASM will report error during analysis.
Since the stack is empty in all paths, we can hoist Unit and following
ARETURN to predecessors, effectively turning path from suspension point
to tail-call.
2021-08-19 16:05:21 +00:00
Mads Ager
d33b70af1a [JVM IR] Ensure an instruction for the line number for a break.
This ensures that the debugger always has a bytecode offset for
the line number of a break/continue so that you step there and
so that you can set breakpoints there.

The `nop` instruction is optimized out if it has no line number
information.

^KT-46450 Fixed
2021-08-19 15:40:44 +02:00
Andrey Zinovyev
894a446585 [FIR] Add missing messages for jvm diagnostics and fix some tests 2021-08-19 15:25:51 +03:00
Andrey Zinovyev
3b21759697 [FIR] SUPER_CALL_WITH_DEFAULT_PARAMETERS diagnostic 2021-08-19 15:25:50 +03:00
Andrey Zinovyev
24fbe0f072 [FIR] UPPER_BOUND_CANNOT_BE_ARRAY diagnostic 2021-08-19 15:25:49 +03:00
Andrey Zinovyev
4661656b8c [FIR] JVM_PACKAGE_NAME* diagnostics 2021-08-19 15:25:47 +03:00
Andrey Zinovyev
ae558c0290 [FIR] Add DEPRECATED_JAVA_ANNOTATION diagnostic 2021-08-19 15:25:46 +03:00
Andrey Zinovyev
f9b601edae [FIR] @JvmOverloads related checkers 2021-08-19 15:25:44 +03:00
Andrey Zinovyev
17ae69416c [FIR] Add SYNCHRONIZED_* diagnostics 2021-08-19 15:25:43 +03:00
Andrey Zinovyev
7ba8e0d9cc [FIR] Add VOLATILE_ON_VALUE/VOLATILE_ON_DELEGATE diagnostic 2021-08-19 15:25:43 +03:00
Andrey Zinovyev
f90b534c4c [FIR] Add STRICTFP_ON_CLASS diagnostic 2021-08-19 15:25:41 +03:00
sebastian.sellmair
565ea2c4f5 [Commonizer] Improve iteration performance in transformer and mergeCirTree
An allocation/iterator free `forEach` is used for lists that
are not intended to be modified at the same time.
2021-08-19 12:19:15 +00:00
sebastian.sellmair
e2816ffabb [Commonizer] Rename CirTypeSubstitutor implementations
^KT-48287
^KT-48286
2021-08-19 12:19:14 +00:00
sebastian.sellmair
8aceff3641 [Commonizer] Implement CirUnderscoredTypeAliasSubstitutor
Try substituting TypeAlias types that start with `__` in favour
of TypeAlias without the underscored prefix

^KT-48287 Verification Pending
^KT-48286 Verification Pending
2021-08-19 12:19:14 +00:00
Ilya Goncharov
7d3830ba7d [Gradle, JS] Use stable version of webpack-dev-server 2021-08-19 15:06:16 +03:00
Hung Nguyen
16dfdb620e KT-45777: Add custom serialization for classpath snapshot
Also add a few commonly-used classes/methods to externalizers.kt to
allow reuse.

Bug: KT-45777
Test: New ClasspathSnapshotSerializerTest
2021-08-19 13:50:26 +03:00
Alexander Likhachev
0d2a514a70 [Gradle, JS] Fix NPM resolution skip condition for js compilation
#KT-48241 Fixed
2021-08-19 12:07:23 +03:00
Alexander Likhachev
b74253521e [Gradle, JS] Add test for KT-48241 2021-08-19 12:06:32 +03:00
Igor Chevdar
a576160847 [K/N][IR][codegen] Lazy initialization fix for new GC
A mutable field should be registered in GC even if its initializer is a const
2021-08-19 00:50:28 +05:00
Alexander Udalov
af59955566 IR: minor, refactor code in ExpectDeclarationRemover
Inline unnecessary inline functions to keep stacktraces saner, fix
incorrect "this" in exception message in
findActualForExpect/findExpectForActual (see KT-45628).
2021-08-18 21:27:55 +02:00
Alexander Udalov
a4730dd57e Minor, set JAVA_HOME to JDK 1.8 in LauncherScriptTest
Otherwise the test would invoke the "java" executable from PATH, which
might not be 1.8, and that would cause some tests to fail because error
messages are slightly different in newer Java versions.
2021-08-18 21:27:55 +02:00
Alexander Udalov
b1bce6a29e JVM IR: fix noarg plugin for sealed class with existing noarg ctor
#KT-48111 Fixed
2021-08-18 20:57:19 +02:00
pyos
d3de0109ca Add tests for KT-48180 2021-08-18 18:39:33 +02:00
pyos
ff6de0fe6a JVM: remove InlineCodegen.expressionMap
#KT-48180 Fixed
2021-08-18 16:55:44 +02:00
pyos
47d0211370 FE: do not enhance ? in jspecify NullMarked scope
No clue whether this should be done for `@TypeQualifierDefault` since it
appears to have no specification whatsoever.

 #KT-48262 Fixed
2021-08-18 16:41:00 +03:00
Jinseong Jeon
5819959cce Consolidate arrayOf call names 2021-08-18 16:04:36 +03:00
Andrey Zinovyev
1cd321a90f [FIR] Add INAPPLICABLE_OPERATOR_MODIFIER diagnostic 2021-08-18 16:03:01 +03:00
Ilya Goncharov
16f41bd80c [Gradle, JS] Use webpack-dev-server rc.1 2021-08-18 15:50:38 +03:00
Mikhael Bogdanov
8ab546ba51 [FIR]: Pass special origins for local functions (named and anonymous) 2021-08-18 09:58:27 +00:00
Mikhael Bogdanov
a5e59e09ee Copy methods for lambdas to DefaultImpls without receiver transformation
#KT-48230 Fixed
2021-08-18 09:58:27 +00:00
pyos
6d7eb2bd21 Add test for KT-48230 2021-08-18 09:58:27 +00:00
Sebastian Sellmair
21f7e16ee6 [Gradle] NativeDistributionCommonizationCache: Acquire FileLock
A `.lock` file will be acquired before running the native
distribution commonizer. This is done to protect data corruption
when multiple process try to commonize at the same time.

This could happen when e.g. two new projects are opened that
both trigger the commonizer during syncing.

^KT-46343 Verification Pending
2021-08-18 09:22:46 +00:00
Tianyu Geng
fb1eac0985 FIR: report SMARTCAST_IMPOSSIBLE on inherited alien properties [KT-48101] 2021-08-18 12:02:02 +03:00
Mikhail Glukhikh
0a6e51e47f FirJavaGenericVarianceViolationTypeChecker: make code a bit more clear 2021-08-18 12:02:01 +03:00
Ilya Goncharov
f37d880964 [Gradle, JS] Add test on valid of webpack config
^KT-48273 fixed
2021-08-18 11:56:19 +03:00
Ivan Kochurkin
301f446433 Restore KtModifierKeywordToken instead of String in modifier diagnostics
Remove KeywordType
2021-08-18 00:45:57 +03:00
Denis.Zharkov
a8077aebb0 FIR: Ignore suspicious test on StrictJavaNullabilityAssertions
^KT-48302 Open
2021-08-17 21:38:01 +03:00
Denis.Zharkov
753ba99b04 FIR: Support enhanced types when checking if Java type is primitive 2021-08-17 21:38:01 +03:00
Denis.Zharkov
a0553f4dfd FIR: Do not build synthetic property named with first capital character 2021-08-17 21:38:01 +03:00
Denis.Zharkov
c3a327e118 FIR: Fix ambiguity on Int2IntMap in IC 2021-08-17 21:38:01 +03:00
Mikhail Glukhikh
1a5552bef8 FIR2IR: fix argument mapping for deserialized annotation #KT-48298 Fixed 2021-08-17 18:22:33 +03:00
Mikhail Glukhikh
6660c9b26b FIR: add test repeating a problem with annotation mapping (KT-48298) 2021-08-17 18:22:33 +03:00
Andrey Zinovyev
ab158a53c3 [FIR] ASSIGNING_SINGLE_ELEMENT_TO_VARARG_IN_NAMED_FORM_ANNOTATION diag 2021-08-17 16:05:42 +03:00
Andrey Zinovyev
1cdbbad367 [FIR] ASSIGNING_SINGLE_ELEMENT_TO_VARARG_IN_NAMED_FORM_FUNCTION diag 2021-08-17 16:05:42 +03:00
Nikita Bobko
5e87d753b7 Fix coop-dev project import 2021-08-17 13:55:36 +02:00
Ilya Goncharov
a7cc275c7d [Gradle, JS] Update webpack-dev-server
^KT-48273 fixed
2021-08-17 14:44:29 +03:00
Elena Lepilkina
12d694de46 [K/N] Added returns before building DFG 2021-08-17 16:14:07 +05:00
Igor Chevdar
16f0ba8e46 [K/N][optmz] Reworked a bit work with fields 2021-08-17 16:14:07 +05:00
pyos
49c412b022 JVM_IR: implement view caching in kotlin-android-extensions
#KT-47733 Fixed
2021-08-17 13:46:26 +03:00
Pavel Punegov
6ea2dea28e Fix JDK 16 and 17 env variables to correspond to the TC 2021-08-17 09:51:53 +00:00
Yahor Berdnikau
e7a08b14e3 Fix 'jvmTarget' is not updated on reusing configuration cache.
Before this change 'kotlinOptions.jvmTarget' was updated
on 'providedJvm' property value calculation, but, as configuration
cache reuses property value from the cache - 'jvmTarget' update does not
 happen.

This change adds additional call to set 'jvmTarget' on task execution
 phase to ensure even on configuration cache reuse field is set
 to correct value. Update is based whether 'providedJvm' property is set
 or not.

^KT-48226 Fixed
2021-08-17 09:13:29 +00:00
Pavel Punegov
7e1c776376 [Native][tests] Fix warnings in debugger tests 2021-08-17 08:42:11 +00:00
Dmitriy Dolovov
4049cf94b1 [Gradle][Native] Mute BuildCacheRelocationIT.testRelocation on MinGW 2021-08-17 11:01:08 +03:00
Dmitriy Dolovov
da72f26d94 [IR][Tests] Unmute NativeIrLinkerIssuesIT (as far as K/N version is already updated)
^KT-44626
2021-08-17 07:53:47 +00:00
Dmitriy Dolovov
e18c3517a9 [Gradle] Advance K/N version to 1.6.0-dev-2972 2021-08-17 07:53:46 +00:00
Dmitriy Dolovov
cd08dc49a0 [IR][Tests] Mute NativeIrLinkerIssuesIT until K/N version is updated
^KT-44626
2021-08-17 07:53:46 +00:00
Dmitriy Dolovov
4edc1239ac [IR] Use only ASCII-printable chars in IR linker error reports
^KT-44626
2021-08-17 07:53:46 +00:00
Dmitriy Dolovov
af12d61388 [IR] Enhance error reporting for IR linking issues
^KT-44626

Support correct error reporting both with native static caches and without native static caches.
2021-08-17 07:53:45 +00:00
Dmitriy Dolovov
3cd43dced4 [IR] Fix tests for IR linking error reporting
- Run "ktor 1_5_4 and coroutines 1_5_0-RC-native-mt (KT-46697)" test only on Mac host
- Fix application entry point function FQN
- Use OS-neutral URI for configuration of local Maven repos instead of OS-specific path

^KT-44626
2021-08-17 07:53:45 +00:00
Andrey Zinovyev
a17a61341b [FIR] Fix false positive NON_INTERNAL_PUBLISHED_API on constructor val
#KT-48234 Fixed
2021-08-16 19:12:31 +03:00
Tianyu Geng
68f14fdd87 FIR: PrimitiveTypes -> StandardTypes 2021-08-16 16:54:33 +03:00
Tianyu Geng
5a26e79b08 FIR checker: move JAVA_TYPE_MISMATCH to FirJvmErrors 2021-08-16 16:54:32 +03:00
Tianyu Geng
b77dc4136b FIR checker: fix JAVA_TYPE_MISMATCH again 2021-08-16 16:54:22 +03:00
Tianyu Geng
64ebddcbc6 FIR checker: add convention check for ++ and +=, etc 2021-08-16 15:14:30 +03:00
sebastian.sellmair
68e7476765 [Commonizer] ClassSuperTypeCommonizer: Don't find consumed TypeNodes
This commit will also add some simple documentation
to this class and its implementation.

^KT-47430
2021-08-16 10:44:04 +00:00
sebastian.sellmair
1e95717b8d [Commonizer] Implement SimpleCirSupertypesResolverTest
^KT-47430
2021-08-16 10:44:03 +00:00
sebastian.sellmair
f64a0efa8b [Commonizer] Respect artificial supertypes when loading dependencies
CirProvided.ExportedForwardDeclarationClass will now correctly
report artificial superclasses.

The InlineTypeAliasCirNodeTransformer does not need to know anything
about artificial supertypes anymore. When inlining any
type alias, it is enough to resolve the type-alias's expansions
supertypes.

^KT-47430
2021-08-16 10:44:03 +00:00
sebastian.sellmair
26ede5d885 [Commonizer] Add small documentation on CirSupertypesResolver
^KT-47430
2021-08-16 10:44:03 +00:00
sebastian.sellmair
9fb41b6334 [Commonizer] CirKnownClassifiers: Store indices and target dependencies as 'TargetDependent'
^KT-47430
2021-08-16 10:44:02 +00:00
sebastian.sellmair
367db345a8 [Commonizer] Do not re-calculate classifier indices for transformer
^KT-47430
2021-08-16 10:44:02 +00:00
sebastian.sellmair
dda9bb93f6 [Commonizer] Consider exportForwardDeclarations as dependency
This will make follow-up commits easier:
forward declarations are closer to dependencies than being part
of the library. They will be used in the module, bot not
directly provided.

This commit also enables tracking of provided dependency classifiers
in the CirTreeRoot and CirRootNode

^KT-47430
2021-08-16 10:44:01 +00:00
sebastian.sellmair
3d4e861f05 [Commonizer] ModulesProvider: refactor 'loadModuleInfos()' to property
This is done to signal that accessing this data is indeed lightweight.

^KT-47430
2021-08-16 10:44:01 +00:00
sebastian.sellmair
6c246738a5 [Commonizer] TargetDependent: Support index based access
^KT-47430
2021-08-16 10:44:01 +00:00
sebastian.sellmair
dff392f2cd [Commonizer] ClassSuperTypeCommonizer: Include transitive supertypes
This commit still has some left-over todos that shall be done
in a separate commit.

TODOs:
- CirClassifierIndex is calculated once too often
- Reconsider position of classifierIndices in 'CirKnownClassifiers'
- Add documentation/description to complicated 'ClassSuperTypeCommonizer'
- Add documentation/description to CirSupertypesResolver

^KT-47430 Verification Pending
2021-08-16 10:44:00 +00:00
sebastian.sellmair
1857096071 [Commonizer] Implement ClassSuperTypeCommonizer
This implementation runs as regular part of the commonization.
Previous implementation inside the CommonizationVisitor was fully
replaced by it.

As a side effect: CirClass.supertypes was now marked immutable.

^KT-47430 In Progress
2021-08-16 10:44:00 +00:00
sebastian.sellmair
50a343f91e [Commonizer] Deserialize supertypes from provided dependencies
^KT-47430 In Progress
2021-08-16 10:43:59 +00:00
sebastian.sellmair
cdfe8d60a4 [Commonizer] InlineTypeAliasCirNodeTransformer: add artificial supertypes
When inlining any TypeAlias pointing towards forward declarations,
the inlined class will respect implicit supertypes.

This logic is analog to
KlibResolvedModuleDescriptorsFactoryImpl.createForwardDeclarationsModule

^KT-47430 In Progress
2021-08-16 10:43:59 +00:00
Sergey Bogolepov
0c35a3b699 [K/N] A bit cleaner reflection of code coverage state in docs. 2021-08-16 09:22:32 +00:00
Ilmir Usmanov
486c6b3c15 Remove obsolete experimental coroutines support
in compiler.
2021-08-13 22:31:30 +02:00
Ilmir Usmanov
ebb340fe68 Do not just merge consequent LVT ranges, but also extend them 2021-08-13 23:12:10 +03:00
Ivan Kochurkin
8d764fa50e [FIR] Add FirPropertyAccessExpression that inherits FirQualifiedAccessExpression 2021-08-13 20:05:43 +03:00
Alexander Udalov
0fb398d45e Build: enable Werror for almost all compileKotlin tasks
The only exception at this point is :kotlin-gradle-plugin:compileKotlin.
2021-08-13 17:46:57 +02:00
Ivan Kochurkin
f2ffead881 Reduce allocations in KotlinTarget and modifier checkers 2021-08-13 18:32:29 +03:00
Ivan Kochurkin
2c1c24c042 [FIR] Implement WRONG_MODIFIER_CONTAINING_DECLARATION, DEPRECATED_MODIFIER_CONTAINING_DECLARATION 2021-08-13 18:32:28 +03:00
Ivan Kochurkin
cd6384eb20 [FIR] Fix handling of WRONG_MODIFIER_TARGET
Implement DEPRECATED_MODIFIER, DEPRECATED_MODIFIER_FOR_TARGET, REDUNDANT_MODIFIER_FOR_TARGET
2021-08-13 18:32:27 +03:00
Ivan Kochurkin
e85940a1ac Unbind modifiers checks from psi
Use common code in FE and FIR in modifier checker, refactor
2021-08-13 18:32:26 +03:00
Dmitry Petrov
ed0e3b0fed JVM_IR KT-47984 minor fixes after review 2021-08-13 18:08:55 +03:00
Dmitry Petrov
f8503ba1bf JVM_IR KT-47984 minor avoid using @Deprecated function in tests 2021-08-13 18:08:55 +03:00
Dmitry Petrov
55663a0fb1 JVM_IR KT-47984 allow only limited list of GETSTATICs in arg loading 2021-08-13 18:08:54 +03:00
Dmitry Petrov
32c51cbb45 JVM_IR KT-47984 minor drop unneeded caching 2021-08-13 18:08:53 +03:00
Dmitry Petrov
15c41b2610 JVM_IR KT-47984 add test for argument reordering 2021-08-13 18:08:52 +03:00
Dmitry Petrov
edd2ca775b JVM_IR KT-47984 use stack size calculator from ASM 2021-08-13 18:08:52 +03:00
Dmitry Petrov
5096e8c5c4 JVM_IR KT-47984 transform inplace arguments before inlining 2021-08-13 18:08:49 +03:00
Dmitry Petrov
7a99f9ff2e JVM_IR KT-47984 allow noinline functional inplace args 2021-08-13 18:08:48 +03:00
Dmitry Petrov
9be941def2 JVM_IR KT-47984 don't move inplace arguments with suspension points 2021-08-13 18:08:47 +03:00
Dmitry Petrov
9acdcc7590 JVM_IR KT-47984 minor cleanup 2021-08-13 18:08:47 +03:00
Dmitry Petrov
bf362abb57 JVM_IR KT-47984 update LVT entries for transformed instructions 2021-08-13 18:08:46 +03:00
Dmitry Petrov
6b18f33f92 JVM_IR KT-47984 don't transform calls with non-local jumps in arguments 2021-08-13 18:08:45 +03:00
Dmitry Petrov
b01c13a4df JVM_IR KT-47984 inplace arguments inlining for @InlineOnly functions 2021-08-13 18:08:44 +03:00
Dmitry Petrov
ec90649854 JVM_IR minor cleanup in inliner 2021-08-13 18:08:43 +03:00
Pavel Kunyavskiy
d88a665fa8 [K/N] Implement Lazy for new mm 2021-08-13 13:20:59 +00:00
Ivan Kylchik
2f2e608502 Expand the possibilities of object's interpretation
It is possible to create object in interpreter even if its
receiver symbol came from function parameter instead of object's class.
#KT-48174 Fixed
2021-08-13 16:18:36 +03:00
Ivan Kylchik
492b8acf93 Rename some methods in interpreter's stack to make their purpose clearer 2021-08-13 16:18:34 +03:00
Ivan Kylchik
69fe7e66a5 Introduce some helpful type aliases in interpreter 2021-08-13 16:18:32 +03:00
Ivan Kylchik
1808f14677 Switch from using of MutableList to ArrayDeque in interpreter's stack 2021-08-13 16:18:32 +03:00
Ivan Kylchik
ac2dffa74e Speed up interpreter's stack by using map of variables instead of list 2021-08-13 16:18:31 +03:00
Ivan Kylchik
a630273af2 Speed up interpreter's intrinsic check by introducing map of handlers 2021-08-13 16:18:30 +03:00
Ivan Kylchik
bc9b2fd78b Uncomment some test cases in reflection test data for interpreter 2021-08-13 16:18:29 +03:00
Ivan Kylchik
23b315446f Support sam conversion in ir interpreter 2021-08-13 16:18:28 +03:00
Ivan Kylchik
b85a796492 Support interpretation for floorDiv and mod functions 2021-08-13 16:18:28 +03:00
Ivan Kylchik
f9607292b5 Add additional useful ir classes into IrInterpreterEnvironment 2021-08-13 16:18:26 +03:00
Ivan Kylchik
b46a42be33 Drop toIrConst function with IrBuiltIns parameter 2021-08-13 16:18:25 +03:00
Pavel Kunyavskiy
7bddc2a815 [K/N] Add new exception for CallsChecker 2021-08-13 13:12:21 +00:00
Mikhail Glukhikh
4e4d36f85a FIR: take lower priority into account during references EagerResolve
#KT-48158 Fixed
2021-08-13 11:14:04 +03:00
Mikhail Glukhikh
a21d281c19 FIR: fix capturing on intersection types #KT-48109 Fixed 2021-08-13 11:14:03 +03:00
Mikhail Glukhikh
a04913a197 FIR: use captureFromTypeParameterUpperBoundIfNeeded for argument types
#KT-48161 Fixed
2021-08-13 11:14:02 +03:00
Mikhail Glukhikh
73a8b4544a FIR: don't report EQUALITY_NOT_APPLICABLE for classes from java.*
Workaround for KT-48113
2021-08-13 11:14:01 +03:00
Mikhail Glukhikh
b617aca8ee FIR: fix scope order for super-type resolve #KT-48159 Fixed 2021-08-13 11:14:01 +03:00
Mikhail Glukhikh
ca98417a0c FIR: add test for erroneous type inference in UAST (KT-48159) 2021-08-13 11:14:00 +03:00
Mikhail Glukhikh
b1bcbaf48f FirConstChecks: support "Some string".length case properly
#KT-48165 Fixed
2021-08-13 11:13:59 +03:00
Mikhail Glukhikh
f6413c41a0 FIR: fix serialization of JvmField-properties of local classes
#KT-48175 Fixed
2021-08-13 11:13:58 +03:00
Mikhail Glukhikh
2e2edf398c FIR: consider enum class overridden members non-final #KT-48164 Fixed 2021-08-13 11:13:57 +03:00
Nikolay Krasko
8e32bbbe90 Clean up 203.8084.24 dependencies a bit 2021-08-12 21:15:32 +03:00
Nikolay Krasko
23c438aa03 Clean up 203.6682.168 dependencies 2021-08-12 21:15:31 +03:00
Nikolay Krasko
63d1e195e0 Clean up 202.7660.26 dependencies 2021-08-12 21:15:31 +03:00
Nikolay Krasko
9e0ba8c3d2 Clean up 193.6494.7 mentionings 2021-08-12 21:15:30 +03:00
Nikolay Krasko
c56b6455f1 Clean up 202.7660.3 mentionings 2021-08-12 21:15:29 +03:00
Igor Yakovlev
9b9a529b7f Reflect addition of new 'kotlin.jvm-run-configurations' module in Gradle 2021-08-12 18:16:00 +02:00
Ivan Kochurkin
d346953de9 [FIR] Move FirCommaInWhenConditionChecker to syntax subdirectory 2021-08-12 18:42:26 +03:00
Tianyu Geng
1679da45ab FIR checker: COMMA_IN_WHEN_CONDITION_WITHOUT_ARGUMENT
FIR simply ignores anything after the first comma if the when expression
doesn't have a subject. Hence, the checker has to rely on PSI structure
instead.
2021-08-12 18:42:26 +03:00
Sergey Bogolepov
db12a96e54 Fix test that was broken by e159392d by disabling native caches. 2021-08-12 18:02:23 +03:00
Ting-Yuan Huang
39c6be86cb K2JsIrCompiler: pass right configuration when creating lib module 2021-08-12 18:01:59 +03:00
Ting-Yuan Huang
06d3c6f233 Support repeated analysis and frontend-only-mode in K2JsIrCompiler 2021-08-12 18:01:58 +03:00
Ting-Yuan Huang
e75ca75e3e K2JsIrCompiler: hoist common front-end preparation logic
Instead of creating ModuleStructure and run analysis in each backend,
the common preparation logic is moved into K2JsIrCompiler.doExecute().
2021-08-12 18:01:56 +03:00
Igor Laevsky
94af3adb4b WASM: Disable flaky test 2021-08-12 17:32:35 +03:00
Alexander Udalov
1b98723b3f JVM IR: fix incorrect detection of interface method impls in Java
The problem in the test case was that `JImpl.entrySet` was detected by
ReplaceDefaultImplsOverriddenSymbols as a class fake override, which
overrides non-abstract interface method. Thus, overriddenSymbols of
`MyMap.entrySet` were changed in
`ReplaceDefaultImplsOverriddenSymbols.visitSimpleFunction`.

Later, BridgeLowering tried to determine which special bridges to
generate for `MyMap.<get-entries>`, and for that it inspected existing
methods and their overrides.

Normally we would generate the following special bridge:

    getEntries()Ljava/util/Set;
        invokespecial JImpl.entrySet()Ljava/util/Set;

However, because of incorrect overrides, the generated class method was
selected here instead of the expected `Map.<get-entries>`:
06001fc091/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/BridgeLowering.kt (L282)
and since the JVM signature of the generated class method is the same as
that of the fake override in MyMap, we never got to generating the
special bridge.

The solution is to skip Java classes when looking for class methods
which override non-abstract interface methods. This logic only makes
sense for Kotlin code, because only Kotlin has DefaultImpls, and the
requirement to generate non-abstract fake overrides of interface methods
as actual methods in the bytecode, delegating to DefaultImpls.

 #KT-48167 Fixed
2021-08-12 13:51:33 +02:00
Alexander Udalov
d124239025 JVM IR: do not attempt to mangle function expressions
For some reasons, lambdas and function expressions are represented
slightly differently in psi2ir. Lambdas are translated to a block with a
function of origin LOCAL_FUNCTION_FOR_LAMBDA and name "<anonymous>", but
function expressions are translated to a block with DEFINED function
"<no name provided>".

Tweak the condition for detecting local functions a bit, to avoid
similar situation in the future if we add some other origins for local
functions.

 #KT-48207 Fixed
2021-08-12 13:50:23 +02:00
Mikhail Glukhikh
dd3eb53904 Drop forgotten foreign annotation test data 2021-08-12 14:25:18 +03:00
Yahor Berdnikau
3acb96e474 Allow running KotlinJavaToolchainTest on any user JDK. 2021-08-12 10:00:23 +02:00
Bingran
c57302abba Only check ExternalDependency when customizing kotlin dependencies
This commit fixes the issue where kgp checks group/version of project
dependencies which is uncompatible with project isolation. With this
change, kgp will only check ExternalDependency which should be enough
for setting up kotlin dependencies.

This change also changes the way we apply cache redirector gradle
files to all projects when setting up test projects. To make it
compatible with project isolation, we should move away from using
project.getAllProjects() function.

^KT-47792 Fixed
Test: existing + SimpleKotlinGradleIT.testProjectIsolation
2021-08-12 09:51:20 +02:00
Andrey Zinovyev
1338675833 [FIR] Fix while's label, when condition has lambda
#KT-48116 Fixed
2021-08-12 10:20:45 +03:00
Alexander Shabalin
06001fc091 [K/N] Tweak fronted warning messages for the new MM 2021-08-11 20:06:19 +00:00
Andrey Zinovyev
d3905fd763 Add dist dependency for tests
Because some tests require stdlib
2021-08-11 21:57:16 +03:00
Andrey Zinovyev
3ec9599bc4 [FIR][CFG] Partial support of postponed Nothing calls
In try blocks, last call won't be completed when building node for it
This is workaround to partially reconstruct nothing stub node for such
calls. Should work for non-local returns in try only.
#KT-48160 Fixed
2021-08-11 21:57:14 +03:00
Ivan Kochurkin
445e5122c1 [FIR] Fix conversion of underscored value parameters in functions
Fix false REDECLARATION
2021-08-11 21:52:46 +03:00
Ilya Kirillov
ebe96ec79a FIR IDE: fix reference resolve with invalid number of type args 2021-08-11 18:09:05 +02:00
Ilya Kirillov
a8f7bf5fbc HL API: cleanup reference resolve testdata 2021-08-11 18:09:05 +02:00
Ilya Kirillov
2e3b576342 FIR IDE: change destructing declaration reference behaviour to match FE1.0 plugin behaviour 2021-08-11 18:09:05 +02:00
Pavel Punegov
aef45f0997 [Native] Exclude on wasm initializers tests.
Tests use exceptions and workers that are not supported in wasm
2021-08-11 13:56:48 +00:00
Pavel Punegov
d7f5015faa [Native] wasm: use JS pow method
Replace usage of C pow() function with JS to fix the issue
with stack overflow caused by invocation of missing pow function
2021-08-11 13:56:47 +00:00
Pavel Punegov
cd487efbe9 [Native][test] Exclude FP parsing tests that require exceptions on WASM 2021-08-11 13:56:47 +00:00
pyos
623b289616 Regenerate foreign annotation test data for FIR 2021-08-11 15:58:02 +03:00
pyos
58110709f3 Get rid of lambdas in AbstractForeignAnnotationsTestBase
Also enable the features from the previous two commits
2021-08-11 15:58:01 +03:00
pyos
28c473074c Permit overriding the FIR test in FirTestDataConsistencyHandler 2021-08-11 15:58:01 +03:00
pyos
cd26ef2bb5 Add FIR version of JspecifyDiagnosticComplianceHandler 2021-08-11 15:58:01 +03:00
Mads Ager
608b88996a [JVM_IR] Fix inlining of callable references to extension methods.
Check directly that the referenced function is an extension
function instead of relying on the annotation on the type.

^ KT-47988 Fixed.
2021-08-11 13:29:11 +02:00
Mikhael Bogdanov
1760befa37 [KAPT] Add experimental JDK 17 support
#KT-47583 Fixed
2021-08-11 10:05:24 +02:00
Igor Chevdar
81ce59cf48 [K/N][IR][codegen] Implemented eager initialization
Properties marked with @EagerInitialization will be initialized at program/worker start
even in lazy initialization mode
2021-08-11 11:53:19 +05:00
Sergey Bogolepov
e159392d22 [K/N] Enable caches for iosArm64 and linuxX64 by default 2021-08-11 06:38:59 +00:00
Nikita Bobko
5455800de4 [imltogradle] Exclude 'kotlin.util.compiler-dependencies' module from generation
This module is used as helper module in JPS project module to make sure that IDEA will download
all required dependencies. There are some dependencies which IDEA cannot determine as used so
we force it to download them (kotlinc.kotlin-dist, kotlinc.kotlin-compiler-testdata)

We don't need this module in Gradle project model

This commit fixes:
```
Could not resolve project :prepare:ide-plugin-dependencies:kotlin-compiler-testdata-for-ide.
Required by:
    project :kotlin-ide.kotlin.util.compiler-dependencies
```
2021-08-11 02:17:52 +02:00
Nikita Bobko
747cc7d55d [imltogradle] Fix other kotlinc libraries which don't follow kotlinc.* naming
e.g. kotlin-reflect
2021-08-11 02:17:51 +02:00
Nikita Bobko
784273ac5b [imltogradle] Add additional check for absence of snapshot version in JpsLikeJarDependency 2021-08-11 02:17:51 +02:00
Nikita Bobko
493fdbd418 Fix kotlin stdlib handling for 212 IDEA in ide-iml-to-gradle-generator 2021-08-11 02:17:51 +02:00
Nikita Bobko
8ad368e990 Update verification-metadata.xml with 212.4746.92 artifacts 2021-08-11 02:17:50 +02:00
Ilya Goncharov
40d19b50c5 [Gradle, JS] Use Gradle's hashers 2021-08-10 18:45:09 +00:00
Ilya Goncharov
bfcd954dd3 [Gradle, JS] Add test on not updating Node.JS if it was downloaded
^KT-47845 fixed
2021-08-10 18:45:09 +00:00
Ilya Goncharov
b8330deefa [Gradle, JS] Consider potential hash of nodejs and yarn
^KT-47845 fixed
2021-08-10 18:45:08 +00:00
Ilya Goncharov
5ec19c2417 [Gradle, JS] Up-to-date checks for Node js and yarn
^KT-47845 fixed
2021-08-10 18:45:08 +00:00
Ilya Kirillov
1a1f6b0c0b Regenerate FirIdeSpecTest 2021-08-10 20:06:36 +02:00
Ilya Kirillov
017448e359 FIR IDE: make KtExpression.getKtType() to return null for non-expressions 2021-08-10 18:58:06 +02:00
Roman Artemev
d3ddeef67f [JS IR] Wrap private top level function with internal accessor stub
In case internal inline function references private top level function
after inline such function (T.L.P.) couldn't be referenced
in klib and IC cache. So create internally visible accessors for P.T.L.
function similar to what JVM backend does.

 - add box test
2021-08-10 19:52:08 +03:00
Roman Artemev
b3dbca7ea6 [JS IC] Fix test runner 2021-08-10 19:52:07 +03:00
Tianyu Geng
06ee84f809 FIR checker: report AMBIGUOUS_SUPER 2021-08-10 19:36:44 +03:00
Ivan Kochurkin
5b9ce7e823 [FIR] Use typeArgumentsList from delegatedTypeRef instead of accessing via tree 2021-08-10 19:36:43 +03:00
Tianyu Geng
280c445783 FIR checker: check super reference
This change touches the following diagnostics to make them behave closer
to FE1.0

* SUPER_NOT_AVAILABLE
* SUPER_IS_NOT_AN_EXPRESSION
* INSTANCE_ACCESS_BEFORE_SUPER_CALL
* NOT_A_SUPERTYPE

Other than tweaking the diagnostics, this change also alters resolution
by consider marking `super` with mismatched type parameter as
errorenous. As a result, the following code no longer resolves.

```
class A: B() {
  fun test() {
    super<String>.length
    //            ^^^^^^ FIR currently resolves this to `String.length`.
    //                   With this change, `length` becomes unresolved
    //                   instead
  }
}
```

Also, now we report `UNRESOLVED_LABEL` on unresolved label on `super`
reference, though FE1.0 reports `UNRESOLVED_REFERENCE`.

All the errors above are reported as ConeDiagnostics and hence some
checkers are deleted.

In addition, it also suppresses more downstream (mostly unresolved)
errors if the receiver has errors. FE1.0 doesn't do it for all the cases
we have here. But it seems nicer to reduce these "redundant" unresolved
errors.
2021-08-10 19:36:43 +03:00
Tianyu Geng
bcf6202863 FIR checker: fix position strategy for UNRESOLVED_LABEL 2021-08-10 19:36:04 +03:00
Tianyu Geng
45d31fdba2 FIR: fix atomic qualified acess sharing the same PSI with callee ref
Consider an atomic reference `i`, it's FIR representation is

- FirQualifiedAccessExpression
  - calleeReference : FirNamedReference

Currently, both of the above FIR elements uses the same PSI element as
the source. Such problems are not present with `this` or `super` because
we manually mark them as `ExplicitThisOrSuperReference`.

This change generalizes the previous `ExplicitThisOrSuperReference` as
`ReferenceInAtomicQualifiedAccess` and fixes it for more cases.
2021-08-10 19:35:19 +03:00
Alexander Udalov
3bc0eaff59 Fix warnings in stdlib samples and test modules 2021-08-10 17:57:50 +02:00
Alexander Udalov
0d1380c232 Fix warnings in generator modules 2021-08-10 17:57:50 +02:00
Ivan Kochurkin
2ca3adbcb2 [FIR] Throw REDECLARATION for duplicated type parameters in declarations 2021-08-10 15:09:27 +00:00
Ivan Kochurkin
c19598c2fc [FIR] Throw REDECLARATION for duplicated enum entries 2021-08-10 15:09:26 +00:00
Ivan Kochurkin
9736cc162b [FIR] Throw REDECLARATION for duplicated value parameters in function
Add new test file
2021-08-10 15:09:26 +00:00
Ivan Kochurkin
fd92b851a2 [FIR] Implement PACKAGE_OR_CLASSIFIER_REDECLARATION
Fix REDECLARATION positioning
2021-08-10 15:09:25 +00:00
Nikolay Krasko
1c678be0d3 Drop 202 bunch support 2021-08-10 15:25:46 +03:00
Dmitriy Dolovov
cfc4e715e4 [IR] Tests for IR linking error reporting
^KT-44626
2021-08-10 14:02:45 +03:00
Dmitriy Dolovov
c1fb40a436 [IR] Enhance error reporting for IR linking issues
^KT-44626

Typical use case:
- There are two KLIB libraries: A and B.
- Library A has two versions: A.v1 (older) and A.v2 (newer).
- A.v2 is ABI-incompatible with A.v1.
- B depends on A and was compiled against A.v1.
- An attempt to build the application with A.v2 and B fails with weird error message. It's unclear for end user what's wrong and what needs to be done to fix the issue.

The fix improves error reporting for the following particular cases:
- A symbol that is gone (KT-41378)
- A class that became a typealias (KT-47285, KT-46697)
- A typealias that became a class (KT-46340)
2021-08-10 14:02:40 +03:00
Dmitriy Dolovov
672b972b38 [Native] Add '-Xexternal-dependencies' CLI parameter to pass external deps
^KT-44626
2021-08-10 14:02:35 +03:00
Dmitriy Dolovov
ac387b1f26 [Gradle, Native] Pass external dependencies to Kotlin/Native link tasks
^KT-44626
2021-08-10 14:02:27 +03:00
Mikhail Glukhikh
2c31d2e67d FirTestDataConsistencyHandler: return back FIR files auto-generation 2021-08-10 13:19:28 +03:00
Mikhail Glukhikh
8c51c3c5c3 FirTestDataConsistencyHandler: fix behavior on Windows (partial revert) 2021-08-10 13:19:27 +03:00
Mikhail Glukhikh
512a851c65 Minor fix of test data for consistency with FIR 2021-08-10 13:19:26 +03:00
Mikhail Glukhikh
85a2a3255d Add new SENSELESS_COMPARISON in FIR foreign annotation tests 2021-08-10 13:19:26 +03:00
pyos
cdc0f36859 Permit silencing FIR tests with results depending on configuration 2021-08-10 13:19:25 +03:00
pyos
33251f6d50 Generate foreign annotation test data for FIR 2021-08-10 13:19:23 +03:00
pyos
5873511f64 Generalize AbstractForeignAnnotationsTestBase to FIR 2021-08-10 13:19:22 +03:00
pyos
e2e0358505 Remove "FIR" foreign annotation tests
They do not actually use FIR.
2021-08-10 13:19:21 +03:00
Tianyu Geng
1607a8231a FIR checker: ABSTRACT_PROPERTY_IN_PRIMARY_CONSTRUCTOR_PARAMETERS 2021-08-10 13:02:10 +03:00
Tianyu Geng
927723c766 FIR checker: fix JAVA_TYPE_MISMATCH checker
First, the order of arguments is swapped.
Second, projection erasure for argType was too aggressive. We should
instead retain the projections that are under an invariant position.
2021-08-10 13:00:18 +03:00
Tianyu Geng
cc531149e5 Ignore kotlin-ide directory 2021-08-10 13:00:14 +03:00
Hung Nguyen
eb94167ff2 Move RuntimeModuleData from :core:descriptors.runtime to :core:descriptors.jvm
We are working on a feature in the Kotlin Gradle plugin called
`kotlin.incremental.useClasspathSnapshot` to improve incremental
Kotlin compilation.

To allow reuse when writing this feature, this commit moves most of the
code in RuntimeModuleData (in the ':core:descriptors.runtime' project)
to DeserializationComponentsForJava (in the ':core:descriptors.jvm'
project), so that the API can be accessed from the
':kotlin-gradle-plugin' and ':kotlin-build-common' projects where the
feature is written.

Bug: KT-45777
Test: Existing tests should pass (this is a refactoring-only change)
2021-08-10 12:29:45 +03:00
Hung Nguyen
170184dce4 KT-45777: Refactor RuntimeModuleData to support classpath snapshotting
We are working on a feature in the Kotlin Gradle plugin called
`kotlin.incremental.useClasspathSnapshot` to improve incremental
Kotlin compilation.

In this feature, we need to extract ABI information from a .class file.
If the .class file is a Kotlin class, this info can be found in the
class header data. But if the .class file is a Java class, this info is
not readily available.

The RuntimeModuleData class in the ':core:descriptors.runtime' project
can help with that: It uses reflection to generate `ClassDescriptor`s.

However, reflection requires a full classpath to work correctly, whereas
we want to generate a `ClassDescriptor` directly for each class file
(also, reflection is probably slow).

To address that, this commit refactors RuntimeModuleData so that it can
support a generic Kotlin/JavaClassFinder, which can be based on either
reflection or bytecode analysis. The existing code continues to use
reflection while the new feature will use bytecode analysis (e.g., using
the existing BinaryJavaClass).

Bug: KT-45777
Test: Existing tests should pass (this is a refactoring-only change)
2021-08-10 12:29:44 +03:00
Hung Nguyen
206457d9ff KT-45777: Take snapshots and compute changes for Kotlin classes
Reuse the existing IncrementalJvmCache to take snapshots and compute
changes for Kotlin classes.

Java classes will be handled next.

Bug: KT-45777
Test: New ClasspathSnapshotterTest, ClasspathChangesComputerTest
2021-08-10 12:22:58 +03:00
Alexander Shabalin
7e04bb4bf1 [K/N] Refactor unhandled exception handling API
* Do not reset unhandled exception hook
* Add processUnhandledException to perform default unhandled exception
  processing
* Add terminateWithUnhandledException to report the unhandled exception
  and terminate the program
* Use the default unhandled exception processing in entrypoint, interop
  boundaries and in Worker.executeAfter
* Add -Xworker-exception-handling to control exception processing of
  Worker.executeAfter. By default its the old behaviour with the old MM,
  and new behaviour with the new MM.
2021-08-10 08:22:55 +00:00
Ilya Goncharov
766857881a [JS IR] Review remarks
- Use intrinsic on this
- Enqueue invoke for DCE
- Change transform
- Ignore instead of target backend

^KT-46204 fixed
2021-08-10 07:24:51 +00:00
Ilya Goncharov
2f0f88062a [JS IR] Change global map in context to mapping
^KT-46204 fixed
2021-08-10 07:24:50 +00:00
Ilya Goncharov
a28138eb72 [JS IR] Change js function on Kotlin code
^KT-46204 fixed
2021-08-10 07:24:49 +00:00
Ilya Goncharov
b6c3132614 [JS IR] Ignore test for legacy backend
^KT-46204 fixed
2021-08-10 07:24:49 +00:00
Ilya Goncharov
627af332b1 [JS IR] Use PublishedApi for intrinsic
^KT-46204 fixed
2021-08-10 07:24:48 +00:00
Ilya Goncharov
e6af3ff6a8 [JS IR] Rename and doc new intrinsics, add new intrinsic to call suspend fun as supertype
^KT-46204 fixed
2021-08-10 07:24:48 +00:00
Ilya Goncharov
a70fc99130 [JS IR] Add intrinsic to call suspend functions as super type
^KT-46204 fixed
2021-08-10 07:24:47 +00:00
Ilya Goncharov
22d202e657 [JS IR] Add test on type check of suspend functional interfaces
^KT-46204 fixed
2021-08-10 07:24:47 +00:00
Ilya Goncharov
755f847ab9 [JS IR] Use invoke for coroutines in runtime
^KT-46204 fixed
2021-08-10 07:24:46 +00:00
Ilya Goncharov
3c9dcdbbee [JS IR] Generate suspend function as invoke
[JS IR] Fix type check utils to work with array of arities

[JS IR] Store multiple arities for suspend functional interface implementers

^KT-46204 fixed
2021-08-10 07:24:46 +00:00
Ilya Goncharov
8a812996dd [Frontend, JS] Not report error in for inheritance suspend function interface
^KT-46204 fixed
2021-08-10 07:24:45 +00:00
Georgy Bronnikov
1d913a6bf0 JVM_IR: add test for serialization of raw types 2021-08-10 00:37:46 +03:00
Georgy Bronnikov
3b8cb4b00d ModuleTransformerForTwoFilesBoxTests -> SplittingModuleTransformerForBoxTests
Need to include Java files in IR serialization tests, so generalize
TwoFilesBoxTest for more than two files.
2021-08-10 00:37:44 +03:00
Georgy Bronnikov
13cf9329b2 IR: always serialize constant initializers for fields. 2021-08-10 00:37:42 +03:00
Georgy Bronnikov
7e71bd8f1c Add module dependency to fir/checkers/checkers-component-generator
This is a transitive dependency needed when bootstrapping in
-Xserialize-ir mode.
2021-08-10 00:37:41 +03:00
Georgy Bronnikov
307de0be89 IR: always update deserializedSymbols in referenceLocalIrSymbol
The symbol created in deserializeIrSymbolToDeclare might be discarded
when an existing declaration is used in deserialization (as it happens
when deserializing IR bodies for JVM declarations).
2021-08-10 00:37:37 +03:00
Georgy Bronnikov
eccbf38061 IR: use existing type parameters when deserializing IR 2021-08-10 00:37:36 +03:00
Georgy Bronnikov
fb801bdc33 IR: fix mangling of toplevel properties 2021-08-10 00:37:36 +03:00
Georgy Bronnikov
54957ead5c JVM_IR: add test for signatures of flexible types 2021-08-10 00:37:27 +03:00
Georgy Bronnikov
1d2d1f9e8d IR: change mangling for flexible types in DescriptorMangleComputer
This reverts commit 4af2aaedb1.
2021-08-10 00:37:24 +03:00
Alexander Udalov
afacff326d JVM IR: fix smart cast on argument of 'throw'
#KT-48163 Fixed
2021-08-09 22:34:44 +02:00
Ilya Kirillov
cb37a05b79 Restore LC compiler testdata 2021-08-09 20:29:22 +02:00
Jinseong Jeon
e64f7ffb98 FIR LC: populate ctor in anonymous objects
Note that enum entries are modeled as anonymous objects in FIR too.
2021-08-09 20:29:20 +02:00
Jinseong Jeon
75c76e2b57 FIR IDE: resolve implicit ctor delegation calls 2021-08-09 20:29:19 +02:00
Jinseong Jeon
f7f51cf38e FIR IDE: allow implicit ctor call for psi retrieval 2021-08-09 20:29:19 +02:00
Jinseong Jeon
4396482fed FIR IDE: fix nullability of KtType variants 2021-08-09 20:29:19 +02:00
Jinseong Jeon
46a0c4be4b FIR LC: populate property from primary ctor later 2021-08-09 20:29:18 +02:00
Jinseong Jeon
fba480875f FIR LC: populate constructors after member methods 2021-08-09 20:29:18 +02:00
Jinseong Jeon
edc134ef2d FIR IDE: drop stale test results in kt files 2021-08-09 20:29:17 +02:00
Jinseong Jeon
ba8f2e6bf3 FIR LC: introduce FirLightParameterList
LightParameterListBuilder, as a subtype of PsiParameterList, is good
enough for LightMethod's parameter list abstraction. However, it does
not have a parent link, which bothers upward conversion in UAST
(a.k.a. convertParent APIs). So we need an abstraction similar to
KtLightParameterList (in FE 1.0 LC).
2021-08-09 20:29:17 +02:00
Ivan Kochurkin
c1afb6354b [FIR] Restore UPPER_BOUND_VIOLATED and TYPE_VARIANCE_CONFLICT as errors, fix TestStep.kt 2021-08-09 18:19:58 +03:00
Viacheslav Kormushkin
d670743a2f Cocoapods plugin: error reporting in case CocoaPods is not installed on users machine
#KT-47362
2021-08-09 12:54:29 +00:00
Andrey Zinovyev
1b81018b69 [FIR] Fix overloading of renamed jvm methods
#KT-48102 Fixed
2021-08-09 15:22:06 +03:00
Tianyu Geng
cd99c35649 FIR: instantiate type argument to captured type if needed 2021-08-09 14:38:30 +03:00
Tianyu Geng
bcf6582af7 FIR checker: make TypeApproximatorConfiguration.capturedType consistent with others 2021-08-09 14:38:30 +03:00
Tianyu Geng
758859f198 FIR checker: report JAVA_TYPE_MISMATCH 2021-08-09 14:38:29 +03:00
sebastian.sellmair
eec5f99e35 [Gradle] Support 'KONAN_DATA_DIR' in Commonizer tests 2021-08-09 09:48:44 +00:00
sebastian.sellmair
552a012e65 [Gradle] Add missing mavenCentral repository to test projects 2021-08-09 09:48:44 +00:00
sebastian.sellmair
3625c953ae [Gradle] CInteropCommonizerDependent: Implement 'fromAssociateCompilations'
This additional API and changes in CInteropCommonizerDependencies.kt
will make sure, that test source sets will still receive commonization
results, even when the exact targets are not requested by
any of the main source sets.

^KT-48138 Verification Pending
2021-08-09 09:48:43 +00:00
sebastian.sellmair
9a39b1f4d1 [Gradle] Implement integration test to cover ^KT-48138 2021-08-09 09:48:43 +00:00
sebastian.sellmair
c07dcb27df [Gradle] CommonizerIT: Add assertion on commonMain when jvm target is present 2021-08-09 09:48:42 +00:00
sebastian.sellmair
5485a6d6cd [Gradle] CInteropCommonizerDependent: Drop bad condition on compilations
The dropped condition is bad, since source sets like 'commonMain'
might still participate in a 'compileKotlinMetadata' task,
which is not a shared native compilation.

It is absolutely okay to just rely on the return of
'getCommonizerTarget': If a shared commonizer target is returned,
then the source set is guaranteed to be a shared native source set.

^KT-48118 Verification Pending
2021-08-09 09:48:42 +00:00
sebastian.sellmair
b1c5c10233 [Gradle] Implement test KT-48118 c-interops available in commonMain
Integration Test project was taken from:
https://github.com/4qa/kotlin-multiplatform-issues/tree/cinterop-common

The issue seems to be twofold:
1) The old `compileKotlinMetadata` task is still found, even
when compatibilityMetadataVariant is disabled

2) The shared native compilation for commonMain can't be found, because
it is not listing its default source set:
(see: https://youtrack.jetbrains.com/issue/KT-45412)

Covers ^KT-48118
2021-08-09 09:48:42 +00:00
Mikhail Glukhikh
37d25a58e8 Fix .gitignore (intellij directory) 2021-08-09 10:00:24 +03:00
Ilya Matveev
6c7f04ffc6 [K/N][tests] Fix disabling stress_gc_allocations for No-op GC 2021-08-07 06:28:50 +00:00
Nikita Bobko
a97b4ea4ae Fix UnsupportedClassVersionError when running ./gradlew generateIdePluginGradleFiles
This commit fixes:
```
Exception in thread "main" java.lang.UnsupportedClassVersionError: com/intellij/jps/impl/JpsIdePluginManagerImpl has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:468)
```
2021-08-07 00:07:30 +03:00
Nikita Bobko
dac4fe7507 Adapt coop-dev for 212 platform 2021-08-07 00:07:28 +03:00
Alexander Dudinsky
3d81eba32b New HMPP import and highlighting tests
New tests `testHmppLibAndConsumer` and `testMultiModulesHmpp` were added
The first is a test with MPP library and its consumers, it checks import
and also highlighting before and after the library was published
The second is a project which contains three multiplatform modules and
two platform modules and checks import and highlighting.

Original commit: 15582b0353
2021-08-07 00:07:27 +03:00
Alexander Udalov
bc5a79ffcc Minor, add test on repeatable annotations on property getters
#KT-14392
 #KT-36476
2021-08-06 22:47:44 +02:00
Alexander Udalov
209c0fe819 Revert "[Test] Temporary mute some tests because of problems with RepeatedAnnotationLowering"
This reverts commit 3a210f6c81.
2021-08-06 22:47:44 +02:00
Alexander Udalov
f8af127a4e Do not load Java @Repeatable for Kotlin-repeatable annotations
#KT-48131 Fixed
2021-08-06 22:47:36 +02:00
Alexander Udalov
89b3013294 Build: enable Werror for all compileJava tasks 2021-08-06 22:37:00 +02:00
Alexander Udalov
c821aba3bd Fix warnings in native modules 2021-08-06 22:37:00 +02:00
Alexander Udalov
45ffe58b9c Fix warnings in idea-frontend-fir 2021-08-06 22:37:00 +02:00
Alexander Udalov
069e040af9 Fix warnings in kotlin-klib-commonizer 2021-08-06 22:37:00 +02:00
Alexander Udalov
11902c7f8f Fix warnings in daemon-related modules 2021-08-06 22:36:59 +02:00
Alexander Udalov
ca7334acb9 Fix some warnings in Gradle plugin and related modules 2021-08-06 22:36:58 +02:00
Alexander Udalov
376b420d1a Fix warnings in JS/WASM modules 2021-08-06 22:36:22 +02:00
Alexander Udalov
e0643a4185 Build: use -Xskip-runtime-version-check globally in project 2021-08-06 22:36:22 +02:00
Alexander Udalov
1599a049aa Fix warnings in scripting modules 2021-08-06 22:36:22 +02:00
Dmitriy Novozhilov
b9dd73220c [FIR] Update testdata after rebase 2021-08-06 22:57:19 +03:00
Dmitriy Novozhilov
1d491fdce6 [FIR] Don't create union call node for lambda from one when branch and call from condition of another 2021-08-06 22:57:18 +03:00
Tianyu Geng
684ef871ee FIR: unify common special names scattered around the code base 2021-08-06 22:57:17 +03:00
Tianyu Geng
263b876e6e FIR: extends scope of SENSELESS_COMPARISON
FE1.0 only reports SENSELESS_COMPARISON if one of the operand is `null`.
This change makes FIR reports also in case one of the operand has type
`Nothing?`.

In addition, fix handling of type alias in ConeTypeContext#isNullableType
2021-08-06 22:57:17 +03:00
Tianyu Geng
c7272f6986 FIR checker: SENSELESS_(COMPARISON|NULL_IN_WHEN)
Currently DFA does not set "definitely equal to null" for access to variables that got assigned `null`. For example, FIR should mark the following line as SENSELESS_COMPARISON due to `s = null` above.
 d1531f9cdd/compiler/testData/diagnostics/tests/smartCasts/alwaysNull.fir.kt (L6)

The problem is at 7e9f27436a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/dfa/FirDataFlowAnalyzer.kt (L1104)

For null assignment, ideally the type should be `Nothing?`. This is
addressed in a followup commit instead.
2021-08-06 22:57:16 +03:00
Tianyu Geng
4726dcce40 FIR DFA: smartcast variable to Nothing? on null assignment
In order to make resolution still work for members not available from
`Nothing`, we track the type without `Nothing?` and use that for
resolution instead.
2021-08-06 22:57:15 +03:00
Tianyu Geng
7e2f15f532 FIR DFA: fix logic clear aliasing
The logic should clear back aliases as well. To ensure all back aliases
don't lose any information, statements on the original variable are
copied over to its aliases.
2021-08-06 22:57:15 +03:00
Tianyu Geng
e495c722c7 FIR DFA: fix handling of equality operation 2021-08-06 22:57:14 +03:00
Tianyu Geng
0026560bd7 FIR: substitute the whole lambda body after builder inference 2021-08-06 22:57:13 +03:00
Tianyu Geng
f737d8002e FIR: allow no else branch for when on Nothing(?) 2021-08-06 22:57:12 +03:00
Tianyu Geng
e242ad955b FIR: tolerate comparison of an intersection of incompatible types
Previously, if user compares an `it<String, Int>` with `String`, the
checker reports it since the flattened types `[String, Int, Int]` are
incompatible. But technically, before flattening, the intersection type
actually contain the other side, so they should really be compatible.
2021-08-06 22:57:11 +03:00
Yahor Berdnikau
b5ea811b9f Migrated BuildCacheIT tests to new DSL.
^KT-45745 In Progress
2021-08-06 20:09:05 +02:00
Yahor Berdnikau
20afb268d1 Allow providing specific kapt options.
^KT-45745 In Progress
2021-08-06 20:09:04 +02:00
Yahor Berdnikau
3d4186bdb1 Allow enabling build cache debug information.
^KT-45745 In Progress
2021-08-06 20:09:04 +02:00
Yahor Berdnikau
e949a0d38d Add assertion checking if task was put into build cache.
^KT-45745 In Progress
2021-08-06 20:09:00 +02:00
Roman Artemev
2574c00dd9 Add index() to LocalSignature for more clear access 2021-08-06 20:49:20 +03:00
Roman Artemev
5a7298808e [JVM KLIB] Fix Type Parameter resolve 2021-08-06 20:49:19 +03:00
Roman Artemev
3dcee8fda8 [KLIB] Optimize deserialization a bit 2021-08-06 20:49:19 +03:00
Roman Artemev
7add820f0d [JS IC] Simplify code a bit 2021-08-06 20:49:17 +03:00
Roman Artemev
398b545801 [JS IC] Rollback hack 2021-08-06 20:49:17 +03:00
Roman Artemev
67f814c99f [JS IC] Don't serialize IrTypeAbbreviation in IC cache 2021-08-06 20:49:15 +03:00
Roman Artemev
d174e8c3d2 small optimization 2021-08-06 20:49:14 +03:00
Roman Artemev
9bfe502afd [JS IC] Fix signature finding in some cases
Found in KFSAD
2021-08-06 20:49:13 +03:00
Roman Artemev
15648da2b4 [PIR] Use simple fast hashCode 2021-08-06 20:49:12 +03:00
Roman Artemev
11f70412e7 [KLIB] Don't resolve delegated symbol where it could be existed 2021-08-06 20:49:12 +03:00
Roman Artemev
297e0a9f43 [JS IC] Improve IC deserializer code a bit 2021-08-06 20:49:11 +03:00
Roman Artemev
6ca87dc43f [KLIB] Drop useless set 2021-08-06 20:49:10 +03:00
Roman Artemev
aeea7147fe [JS IC] Simplify code a bit more 2021-08-06 20:49:09 +03:00
Roman Artemev
28cf9898ef [KLIB] Simplify file symbol resolve 2021-08-06 20:49:08 +03:00
Roman Artemev
6cd0d81561 [JS IC] Drop redundant enqueue 2021-08-06 20:49:07 +03:00
Roman Artemev
b1eeb1fb27 [JS IC] Don't persist temporary copies of inline functions
- drop special `IrValueParameterPublicSymbol`
 - drop special `IrAnonymousInitializerPublicSymbolImpl`
 - drop hacky `useGlobalSignatures`
2021-08-06 20:49:06 +03:00
Roman Artemev
b1251c1716 [JS IC] Drop special IdSignatureSerializer for IC 2021-08-06 20:49:04 +03:00
Roman Artemev
4a601ebf95 [JS IC] Eradicate GlobalScopeLocalDeclaration from code
- Normalize proto names
2021-08-06 20:49:03 +03:00
Roman Artemev
74d8e16d09 [JS IC] Eradicate GlobalFileLocalSignature from code
- Reduce usage of global maps
2021-08-06 20:49:02 +03:00
Roman Artemev
a0449892b2 [JS IC] Simplify signatures, don't use GlobalScopeLocalDeclaration 2021-08-06 20:49:01 +03:00
Roman Artemev
3d3c70141c [JS IC] Properly handle type parameters of Functional interfaces
- drop redundant `IrSymbolTable` and `IrIcModuleDeserializerWithBuiltIns`
2021-08-06 20:48:59 +03:00
Roman Artemev
6aed492703 [JS IR] Set proper visibility for static stub of private members 2021-08-06 20:48:58 +03:00
Yahor Berdnikau
bcf08e3293 Set jvm target validation mode to 'error'. 2021-08-06 17:53:45 +02:00
Yahor Berdnikau
d375c52830 Remove deprecated 'kotlin.useFallbackCompilerSearch' property.
^KT-46719 Fixed
2021-08-06 15:36:46 +00:00
Igor Laevsky
331681b40b WASM: Add different debug levels to the test runner 2021-08-06 17:34:22 +03:00
Igor Laevsky
5db8ec6551 WASM: Don't use intrinsics to specify NaN's 2021-08-06 17:34:21 +03:00
Igor Laevsky
4ffed54f76 WASM: Fix JS runner for standalone compiles 2021-08-06 17:34:20 +03:00
Sergey Bogolepov
18bb287d3b [K/N] Switch from cyclone to apple-a7 for Apple AArch64
This change shouldn't affect behaviour, but rather makes bitcode a bit
more consistent with what Xcode generates.
2021-08-06 14:19:42 +00:00
Sergey Bogolepov
d64cb24643 [K/N] Don't pass -target-cpu to clang
It is not supported by bitcode embedding on Apple platforms.
Instead, we set it in function attributes directly as Clang does.
2021-08-06 14:19:41 +00:00
Dmitriy Novozhilov
3a210f6c81 [Test] Temporary mute some tests because of problems with RepeatedAnnotationLowering
^KT-48131
2021-08-06 16:40:16 +03:00
Dmitriy Novozhilov
cbef031780 Advance bootstrap to 1.6.0-dev-2458 2021-08-06 16:40:07 +03:00
Aleksei.Cherepanov
a4a1d35021 Simplify nested errors
Replace incomprehensible IndexOutOfBoundsException with intelligible exception

#KT-47753 Fixed
2021-08-06 15:08:01 +03:00
Dmitriy Novozhilov
afd9b4935a [FIR] Configure language version for FP test via env properties 2021-08-06 14:24:42 +03:00
Ivan Kylchik
4f15bd4817 Introduce a workaround in interpreter tests to make them pass
There is a problem with ranges and iterators. To work properly
they must be resolved firstly, before operator rangeTo.
2021-08-06 13:33:33 +03:00
Ivan Kylchik
44e1b61e6c Move static cache from Wrapper into non-static container in environment
By this change it is possible to run multiple test in parallel
without running out of memory.
2021-08-06 13:33:32 +03:00
Ivan Kylchik
3932acf843 Fix interpretation of default varargs 2021-08-06 13:33:30 +03:00
Ivan Kylchik
0ce3dd117e Drop unnecessary check for not static initializer in interpreter
Apparently initializers can become static only in lowering
2021-08-06 13:33:30 +03:00
Ivan Kylchik
0af918be4f Use IrFactory to create IrFunction in interpreter 2021-08-06 13:33:29 +03:00
Ivan Kylchik
1002d076b3 Use StandardNames whenever it is possible in Wrapper 2021-08-06 13:33:28 +03:00
Ivan Kylchik
3cf4b8b108 Combine two caches from interpreter environment into single one 2021-08-06 13:33:28 +03:00
Ivan Kylchik
3fc5405d57 Implement simple cache for dynamically created wrapper for defaults 2021-08-06 13:33:27 +03:00
Ivan Kylchik
09c31b0900 Implement simple cache for dynamically created wrapper for lambda 2021-08-06 13:33:25 +03:00
Ivan Kylchik
6482abc602 Add CompileTimeCalculation annotation as helper to interpreter's tests 2021-08-06 13:33:25 +03:00
Ivan Kylchik
524189132b Introduce new property fqName to make it easier to take element's name 2021-08-06 13:33:24 +03:00
Ivan Kylchik
fe74dd2689 Mute failing tests for IrInterpreterAfterPsi2IrTestGenerated
These tests are not passing because of the way how test system works.
To works properly interpreter needs source files. For now they are
passed as additional source files, but this method is not working
for old frontend, some conflicts appear in symbol table. Best way to
fix it is to wait until ir serialization.
2021-08-06 13:33:23 +03:00
Ivan Kylchik
295638b26e Allow to interpret non const properties of compile time object 2021-08-06 13:33:22 +03:00
Ivan Kylchik
1978bfcd85 Rewrite rendering of meta info for CHECK_NOT_NULL in interpreter's test
This way it is possible to unify rendering of elements built by psi2ir
and fir2ir.
2021-08-06 13:33:22 +03:00
Ivan Kylchik
a9abf3b9b6 Drop redundant frames after some of exceptions in interpreter
Drop only last frame because it is pointing on function itself.
2021-08-06 13:33:21 +03:00
Ivan Kylchik
334d518aba Change the way of getting name and ordinal for enum entry in interpreter
For now IrProperty doesn't have corresponding overridden symbol, so
it must be taken from getter.
2021-08-06 13:33:20 +03:00
Ivan Kylchik
f815f63fc5 Replace UNDEFINED_OFFSET with SYNTHETIC_OFFSET in IrTreeBuildUtils
This change is needed to avoid exception in `getLineNumber` method.
2021-08-06 13:33:20 +03:00
Ivan Kylchik
0c5fca31ec Support early return from constructor interpretation 2021-08-06 13:33:19 +03:00
Ivan Kylchik
96cc74a752 Fix enum interpretation in case when primary constructor is missing 2021-08-06 13:33:18 +03:00
Ivan Kylchik
668bb4fd71 Fix equals check in interpreter in case when object is wrapped as Proxy 2021-08-06 13:33:18 +03:00
Ivan Kylchik
b9decc3b30 Support type check for deep nested arrays in interpreter 2021-08-06 13:33:17 +03:00
Ivan Kylchik
4ad88679fd Unify logic of creation new ir tree nodes in interpreter 2021-08-06 13:33:17 +03:00
Ivan Kylchik
6ce2f8eb14 Drop unnecessary SubFrame creation from interpreter 2021-08-06 13:33:16 +03:00
Ivan Kylchik
10efbeb0c9 Add synthetic function in interpreter for default args evaluation 2021-08-06 13:33:16 +03:00
Ivan Kylchik
7852d01da6 Rewrite interpreter logic around arguments evaluation
For now calculated arguments will be stored on stack instead of memory.
At first this was done because of problems with default arguments, but
in the next commit this problem will be solved.
2021-08-06 13:33:15 +03:00
Ivan Kylchik
d41c6e900a Place variables in interpreter's memory at the beginning
In case than in single SubFrame can appear several variables with
the same symbol, it is important to get the latest one. It is
relevant for local functions.
2021-08-06 13:33:14 +03:00
Ivan Kylchik
e5ca646de4 Move object creation logic into constructor interpretation
This newly created object is not used in arguments interpretation
so there is no need to create it in InstructionsUnfolder. Moreover
this object can interfere with other objects in memory, for example,
when creating outer object from inner.
2021-08-06 13:33:14 +03:00
Ivan Kylchik
1af1a3c84e Support interpretation of Throwable constructor
For now every subclass of Throwable will be represented as
ExceptionState. This way it is easier to store stack trace and handle
`cause` property in exceptions.
2021-08-06 13:33:13 +03:00
Ivan Kylchik
c8cd000563 Simplify work with fake override methods in interpreter 2021-08-06 13:33:12 +03:00
Ivan Kylchik
8972fc5158 Interpret properties and init blocks in order of appearance 2021-08-06 13:33:12 +03:00
Ivan Kylchik
78475a5d9c Support interpretation of toArray for collections 2021-08-06 13:33:11 +03:00
Ivan Kylchik
b10fdb919f Support cast to array with reified argument in interpreter 2021-08-06 13:33:10 +03:00
Ivan Kylchik
cc56acc2c2 Add configuration into IrInterpreterEnvironment
This configuration will contains all necessary setting for interpreter
and will be replenished over time
2021-08-06 13:33:10 +03:00
Ivan Kylchik
b150cc9537 Implement better support for default args in interpreter
Now supported default args:
1. from super class or interface;
2. with field access, declared in interface;
3. with field access, declared in outer class.
2021-08-06 13:33:09 +03:00
Ivan Kylchik
42ea17b151 Support interpretation of dataClassArrayMemberToString method 2021-08-06 13:33:09 +03:00
Ivan Kylchik
15808cb376 Lower priority of captured variables in interpreter 2021-08-06 13:33:08 +03:00
Ivan Kylchik
4f3d47eed3 Remove unused equals and hashCode methods from Primitive class
They were used only when primitive objects were put in the collection
as they were, in Primitive state wrapper
2021-08-06 13:33:07 +03:00
Ivan Kylchik
0716c557fe Allow inner class to has outer super class in interpreter 2021-08-06 13:33:07 +03:00
Ivan Kylchik
574c607f1c Support proper subtype check in interpreter for KFunction 2021-08-06 13:33:06 +03:00
Ivan Kylchik
9638af042d Support proper behavior in interpreter for cast of null value 2021-08-06 13:33:05 +03:00
Ivan Kylchik
c2fc017d96 Move doubleArrayOf test file to proper place in interpreter test data 2021-08-06 13:33:04 +03:00
Ivan Kylchik
b44fd1a6fe Simplify logic of interpreting invoke method for lambdas
For now will be created separate invoke method that will contains
a call to lambda. This way it is clearer and more intuitive
2021-08-06 13:33:04 +03:00
Ivan Kylchik
06a8156376 Change logic of returning object from constructor in interpreter
For now there is no need to place object on stack before evaluation.
The result will be taken from memory and all unnecessary values on
stack will be removed
2021-08-06 13:33:02 +03:00
Ivan Kylchik
3326cbd9c0 Support passing property as argument to array constructor in interpreter 2021-08-06 13:33:02 +03:00
Ivan Kylchik
59fefb6214 Fix property rendering in interpreter 2021-08-06 13:33:01 +03:00
Ivan Kylchik
af67e950c4 Replace all assert calls in interpreter with internal verify
This swap of methods allow us to handle all asserted errors as
critical and not to process them inside interpreter
2021-08-06 13:33:00 +03:00
Ivan Kylchik
23392b73a9 Simplify the interpretation logic of methods defined in super Wrapper 2021-08-06 13:32:58 +03:00
Ivan Kylchik
cf20e64c61 Support basic interpretation of IrGetClass 2021-08-06 13:32:57 +03:00
Ivan Kylchik
6fe8dd1254 Add ir interpreter tests for ir built from psi 2021-08-06 13:32:57 +03:00
Dmitriy Novozhilov
a9882a86c0 [FIR] Consider extension receiver type in conflicting members checker 2021-08-06 13:31:20 +03:00
Victor Petukhov
cd09c8ba51 Report CANNOT_INFER_PARAMETER_TYPE on any error value parameters of a lambda
^KT-48058 Fixed
2021-08-06 13:27:57 +03:00
Victor Petukhov
1966915e92 Create DONT_CARE type only for dependent lambdas (i.e. to be resolved through the type inference later)
^KT-47493 Fixed
2021-08-06 13:27:56 +03:00
sebastian.sellmair
dbdc6176f0 [Gradle] GradleIT: kotlinToolingMetadataAndroid: Add java 8 support
^KT-48019
2021-08-06 09:25:01 +00:00
Andrey Zinovyev
6dd4164f1e [FIR][CFG] Link finally exit to jump target
Instead of try exit node. So try exit is used only for real exits from
try expressions.
2021-08-06 11:49:35 +03:00
Andrey Zinovyev
32426da625 [FIR][CFG] Support multiple levels of finally blocks in jumps
Jump inside try expressions now goes through all finally blocks between
it and the target
2021-08-06 11:49:35 +03:00
Andrey Zinovyev
06b23d5937 [FIR] Improve the control flow graph around try expressions
1. throw goes to catches instead of main exist block
2. return goes via finally (single level only supported atm)
3. collect non-direct return to retrieve all return expressions easier
2021-08-06 11:49:34 +03:00
Yahor Berdnikau
7b6dddf012 Replace usages of IncrementalTaskInputs with InputChanges.
Gradle IncrementalTaskInputs was long time ago deprecated and not
so flexible as a new proposed way - InputChanges.

^KT-47867 Fixed
2021-08-06 08:44:56 +00:00
Aleksei.Cherepanov
c3344549a8 Avoid overwriting counters file of Lookups storage if it hasn't changed 2021-08-06 02:27:18 +03:00
Aleksei.Cherepanov
cb92413cd8 Change hashcode evaluation for portable caches
Use canonical path and strictly evaluation of hash instead of using insensitive hashcode

#KTIJ-17296 Fixed
2021-08-06 02:27:17 +03:00
Aleksei.Cherepanov
f16b1c2d69 Add flag to cache storage to reduce number of disk accesses 2021-08-06 02:27:15 +03:00
Sergey Igushkin
395b2119a1 Fixup for the fix of KT-47506 interfering with CInterop changes
As the `*Default` configurations are gone, each K/N target now has two
consumable configuration, the `*ApiElements` and the
`*CInteropApiElements`. They have diverging sets of attributes (both
more concrete than `*Default` had).

To make their attribute sets non-diverging, we set the
local-to-project=public on the `*CInteropApiElements` in order to match
the same attribute on the `*ApiElements` configuration

Related to the original fix of KT-47506
2021-08-05 17:53:37 +00:00
Mikhail Glukhikh
11f951e6d1 RawFirBuilder: don't convert scripts to prevent exceptions 2021-08-05 19:24:06 +03:00
Mikhail Glukhikh
8d27f102e7 Fix typo: addCompetedCall -> addCompletedCall 2021-08-05 19:24:06 +03:00
Mikhail Glukhikh
469b3b9d02 Raw FIR: re-use OperatorNameConventions for delegate-related names 2021-08-05 19:24:05 +03:00
Mikhail Glukhikh
22ccb7a943 FIR: discriminate generics during callable reference resolve 2021-08-05 19:24:04 +03:00
Mikhail Glukhikh
e924ee3150 FIR: add test with minOf ambiguity 2021-08-05 19:24:02 +03:00
sebastian.sellmair
ee0b64cb29 [Gradle] BuildKotlinToolingMetadataTask: Ensure clean output directory
This is done to prevent unwanted files from also being located
in the output directory. If the task is executed it is expected
that the output directory only contains this one file.

This is necessary, since *everything* located in the output directory
will potentially be bundled into release apks.

^KT-48019
2021-08-05 16:00:08 +00:00
sebastian.sellmair
e897c60ef1 [Gradle] [Android] Only bundle kotlin tooling metadata for non debuggable variants
^KT-48019
2021-08-05 16:00:08 +00:00
sebastian.sellmair
79565da904 [Gradle] [Android] Implement 'test KotlinToolingMetadataArtifact is bundled into apk'
Covers ^KT-48019
2021-08-05 16:00:08 +00:00
sebastian.sellmair
82a70a205b [Gradle] [Android] Include kotlin-tooling-metadata.json in apk artifact
^KT-48019 Verification Pending
2021-08-05 16:00:07 +00:00
Svyatoslav Scherbina
a22ef02e47 Native: disable compiler caches for experimental memory model
Experimental MM doesn't support compiler caches yet.
2021-08-05 15:22:00 +00:00
Svyatoslav Scherbina
4abbac1ff1 Native: improve code that handles unsupported compiler caches 2021-08-05 15:22:00 +00:00
Dmitry Petrov
02d8c7527e JVM_IR more aggressive if-null expressions fusion
Assume that changing a return type from T to T?
is not a binary-compatible change.
2021-08-05 17:51:49 +03:00
Dmitriy Novozhilov
6f0bf766f2 [Test] Add single service for checking that codegen test is ingored
This approach is better than manual check for `IGNORE_BACKEND` directive
  because it also tracks `IGNORE_BACKEND_FIR` directive and reduces
  duplicating code
2021-08-05 16:59:00 +03:00
Dmitriy Novozhilov
c8386ad1c7 [Test] Properly handle output from separate jvm instance in box tests 2021-08-05 16:58:59 +03:00
Dmitriy Novozhilov
13b5f87f3a [Build] Add gradle properties for different sets of modularized testdata 2021-08-05 15:22:42 +03:00
Dmitriy Novozhilov
d7368c341e [Build] Update kotlin-build-gradle-plugin version to 0.0.32 2021-08-05 15:22:41 +03:00
Dmitriy Novozhilov
adbeda12a6 [Build] Remove pathToKotlinModularizedTestData from kotlin-build-gradle-plugin 2021-08-05 15:22:40 +03:00
Dmitriy Novozhilov
79ff02fd97 [Build] Add documentation for some useful properties in gradle.properties 2021-08-05 15:22:39 +03:00
Alexander Udalov
0925e1b497 Enable JVM IR for stdlib/reflect/test libraries
Changes in Gradle integration tests are needed because:
- in new-mpp-android, kotlin-stdlib-jdk8 is used, and JVM IR generates
  JDK 8-specific bytecode (invokedynamic). D8 needs to be configured to
  desugar it with source/target versions set to 1.8, otherwise it
  reports an error.
- in AndroidExtensionsManyVariants and AndroidIcepickProject, D8 fails
  with assertions enabled if AGP < 4.0.0 is used because of
  https://issuetracker.google.com/issues/148661132. The tests which use
  old AGP versions are probably not relevant anymore anyway.

Changes in kotlin-stdlib-runtime-merged.txt are caused by a slightly
different generation scheme of collection subclasses in JVM IR, and are
harmless.

(Previous attempt was at 15e978dbd311c2ba78ec32b394c21acde9811ccb.)
2021-08-05 12:36:35 +02:00
Abduqodiri Qurbonzoda
29ac9b33ca Add Duration.parse/parseIsoString samples 2021-08-05 10:32:33 +00:00
Abduqodiri Qurbonzoda
5004735366 Add Regex matchAt samples 2021-08-05 10:32:32 +00:00
Abduqodiri Qurbonzoda
d7b10f31b4 Add Regex splitToSequence samples 2021-08-05 10:32:32 +00:00
Sergey Igushkin
e691de6e4c Cleanup configuration to fix corner cases in HMPP dependency resolution
* Set the local-to-project attribute on the compatibility metadata
  variant's "elements" configuration; not setting this attribute could
  lead to ambiguity because of diverging sets of non-matched attributes

* Don't create the `runtimeOnly` configuration for the Kotlin/Native
  targets (or potentially other targets with no runtime dependencies),
  as the K/N target configurator is not aware of the configuration and
  would not set the configuration up properly

* Don't create the legacy `*Default` configurations, as they basically
  duplicate the `*ApiElements` / `*RuntimeElements` configurations but
  don't have all the right attributes, so they are reckoned compatible
  with some consumers unnecessarily and pollute the dependency
  resolution error reports.

Issue #KT-47506
2021-08-05 10:03:13 +00:00
Roman Golyshev
126f6eff28 Add jvm-run-configurations module to the settings.gradle 2021-08-04 22:20:00 +03:00
Dmitriy Novozhilov
8578f0beea [FE 1.0] Check for type mismatch for empty when statements
^KT-47922 Fixed
2021-08-04 19:33:45 +03:00
Dmitriy Novozhilov
60195114c1 [FIR] Properly create class scopes while resolving of annotations arguments 2021-08-04 18:23:06 +03:00
Sergey Bogolepov
4c58954967 [K/N] Don't perform --gc-sections when producing DLL
Due to a bug, lld-link might be a bit too aggressive.
Let's disable --gc-sections for DLL until we update LLD.
Patches:
https://reviews.llvm.org/D101522
https://reviews.llvm.org/D101615
https://reviews.llvm.org/D102138
2021-08-04 14:50:58 +00:00
Victor Petukhov
13cb3c138a Update FE tests 2021-08-04 17:36:53 +03:00
Victor Petukhov
b6cb393796 Check postponed type variables to determine suitability for builder inference (during shouldRunCompletion check) more careful
^KT-42139 Fixed
2021-08-04 17:36:53 +03:00
Victor Petukhov
cf3bd016be Always complete calls not related to the builder inference
^KT-47830 Fixed
2021-08-04 17:36:52 +03:00
Victor Petukhov
dc8dbad0bc Add compiler X-flag to enable self upper bound type inference
^KT-48026 Fixed
2021-08-04 17:36:52 +03:00
Victor Petukhov
7567597be6 Java nullability checker: take type arguments' types from resolution atom if possible, instead of from resolved call directly
^KT-47833 Fixed
2021-08-04 17:36:51 +03:00
Victor Petukhov
93f9d9dacd Check if the intersecting types aren't empty during finding the result type for variable fixation
^KT-47941 Fixed
2021-08-04 17:36:50 +03:00
Victor Petukhov
3eaa452f9e Take into account SimpleTypeWithEnhancement and subtyping related places
^KT-47854 Fixed
2021-08-04 17:36:50 +03:00
Andrey Zinovyev
6ab632f6ad [FIR] Fix mutable context usage in inline diagnostics
Also some minor fixes
2021-08-04 17:33:15 +03:00
Andrey Zinovyev
c46a393a19 [FIR] Add REDUNDANT_INLINE_SUSPEND_FUNCTION_TYPE diagnostic 2021-08-04 17:33:15 +03:00
Andrey Zinovyev
e56deb4525 [FIR] Add INLINE_SUSPEND_FUNCTION_TYPE_UNSUPPORTED diagnostic 2021-08-04 17:33:14 +03:00
Andrey Zinovyev
b2f3485d7c [FIR] Add ILLEGAL_INLINE_PARAMETER_MODIFIER diagnostic 2021-08-04 17:33:14 +03:00
Andrey Zinovyev
dabc983f6a [FIR] Add INVALID_DEFAULT_FUNCTIONAL_PARAMETER_FOR_INLINE diagnostic 2021-08-04 17:33:13 +03:00
Andrey Zinovyev
efce3fc2e0 [FIR] Add NON_INTERNAL_PUBLISHED_API diagnostic 2021-08-04 17:33:12 +03:00
Andrey Zinovyev
46d1b63f70 [FIR] Add INLINE_PROPERTY_WITH_BACKING_FIELD diagnostic 2021-08-04 17:33:11 +03:00
Andrey Zinovyev
38cecf8b12 [FIR] Add REIFIED_TYPE_PARAMETER_IN_OVERRIDE diagnostic 2021-08-04 17:33:10 +03:00
Andrey Zinovyev
29dbaa4ae1 [FIR] Add OVERRIDE_BY_INLINE diagnostic 2021-08-04 17:33:10 +03:00
Andrey Zinovyev
d8b7b7b2dc [FIR] Add DECLARATION_CANT_BE_INLINED diagnostic 2021-08-04 17:33:09 +03:00
Andrey Zinovyev
4e06814bc5 [FIR] Add NULLABLE_INLINE_PARAMETER diagnostic 2021-08-04 17:33:08 +03:00
Andrey Zinovyev
015c2d1875 [FIR] Add NOTHING_TO_INLINE diagnostic 2021-08-04 17:33:08 +03:00
Andrey Zinovyev
28344c8530 [FIR] Add NOT_YET_SUPPORTED_IN_INLINE diagnostic 2021-08-04 17:33:07 +03:00
Denis.Zharkov
bc75a21852 Optimize Strings representation at FastJarHandler 2021-08-04 17:04:50 +03:00
Denis.Zharkov
4e66fd29e0 Minor. Rename properties in FastJarVirtualFile 2021-08-04 17:04:49 +03:00
Denis.Zharkov
6cd3d84e74 Optimize parseCentralDirectory
Avoid creating redundant IntRange
2021-08-04 17:04:47 +03:00
Denis.Zharkov
f81f28569f Get rid of last map in FastJarHandler 2021-08-04 17:04:44 +03:00
Igor Laevsky
d46f7738c6 WASM: NFC. Add reference to the asmscript license 2021-08-04 16:23:39 +03:00
Igor Laevsky
d8569b6a03 WASM: NFC. Remove dead code 2021-08-04 16:23:38 +03:00
Igor Laevsky
af865544ff WASM: Implement string hashcode 2021-08-04 16:23:38 +03:00
Igor Laevsky
c526145a48 WASM: Disable bunch of tests which expose the same issue after switch to the wasm native strings 2021-08-04 16:23:37 +03:00
Igor Laevsky
80140207b5 WASM: Properly handle nullable exported strings 2021-08-04 16:23:36 +03:00
Igor Laevsky
468fe4196d WASM: Implement string.compareTo and string.subSequence 2021-08-04 16:23:35 +03:00
Igor Laevsky
0eba74a9d2 WASM: Impelment float to string conversion operations 2021-08-04 16:23:32 +03:00
Igor Laevsky
f34a079699 WASM: Implement integer to string conversion operations 2021-08-04 16:23:32 +03:00
Igor Laevsky
2538caa84f WASM: NFC. Rename string import/export functions 2021-08-04 16:23:31 +03:00
Igor Laevsky
ebde1e5491 WASM: Crude println implementation with the wasm-native strings 2021-08-04 16:23:30 +03:00
Igor Laevsky
fc0ae851a2 WASM: Don't special case string equality, it now goes through normal .equals method 2021-08-04 16:23:29 +03:00
Igor Laevsky
d90e3618f9 WASM: NFC. Rename WasmReinterpret into WasmNoOpCast. 2021-08-04 16:23:28 +03:00
Igor Laevsky
0f84525bdc WASM: Implement wasm-native strings part 1
There are several changes here but they all required for at least one test to pass.
- Implemented String class and several utility functions using built-in CharArray
- Added new constant memory segment to hold string literals and required funcs to work with them
- Added very crude mostly incorrect rudimentary ability to pass strings back to javascript
2021-08-04 16:23:28 +03:00
Igor Laevsky
9ccdffe8ad WASM: NFC. Rename WasmPrimitive into WasmAutoboxed and add few comments. 2021-08-04 16:23:27 +03:00
Jinseong Jeon
59ad7e0e04 FIR IDE: create call target for super reference 2021-08-04 15:10:04 +02:00
Jinseong Jeon
c597ee0e34 FIR IDE: fix kotlin origin of annotation call 2021-08-04 15:10:03 +02:00
Jinseong Jeon
c559adc0fb FIR IDE: render list of symbols with indentation
Also, render `psi` of annotation call
(to showcase they're always null for now)
2021-08-04 15:10:02 +02:00
Jinseong Jeon
5b40f291bd FIR IDE: resolve KtTypeReference from super type entry to KtType
which will be mapped to delegated constructor call where we can still
find the referred type.
2021-08-04 15:09:58 +02:00
Jinseong Jeon
d4e1ecd9d3 FIR IDE: fix scope processing for enum entry with members 2021-08-04 15:09:57 +02:00
Stanislav Erokhin
748a2d2e7c [MPP] Performance optimization in expect/actual checker
Previously, the checker executed for every declaration i.e. every
declaration was considered as expect declaration. Because of that in
some cases this checker could eat 6% of compilation time.
After this commit only declarations marked with expect or actual
are checked. To achieve that, logic, that do reporting about missing
actual modifier was moved to the Actual part.

Please note, that in cases where there is no expect/actual modifier at
all other errors (like redeclaration and missing body on "actual"
declaration) would be reported.

Useful nodes:
- In this checker reportOn is always the same as
descriptor.sourceElement.ktElement. This is because the only case when
it isn't true is PropertyAccessors and they are filtered
- Annotation constructor descriptor isActual == true all the time
- previously for weak incompatible members ACTUAL_MISSING
was not reported
- the logic here is super complicated and crazy, but I don't think that
there is sense to refactor it in the old FE
2021-08-04 15:19:34 +03:00
Stanislav Erokhin
e9a2997f7e Minor refactoring -- use util function 2021-08-04 15:19:32 +03:00
Andrey Zinovyev
cea6081d36 [FIR] LT positioning strategy for UNREACHABLE_CODE 2021-08-04 14:42:24 +03:00
Andrey Zinovyev
ec4cbfef59 [FIR] UNREACHABLE_CODE diagnostic (wip)
Implementation for PSI only
2021-08-04 14:42:24 +03:00
Elena Lepilkina
dcd61c292d [K/N][perf] Fix kotlin language version in kotlin-dsl plugin for performance subproject 2021-08-04 10:39:53 +00:00
Sergey Bogolepov
d5e2ac0efc Fix KotlinLibraryResolverImpl.kt on Windows
`absoluteFile` is not enough to make path unique. For example, it doesn't
expand things like '..' and 'IDEAPR~1' on Windows. `canonicalFile` seems
to solve the problem.
2021-08-04 05:44:27 +00:00
Ivan Kochurkin
3c3e51c6de [FIR] Temporary change TYPE_VARIANCE_CONFLICT to warning to unblock bootstrap tests 2021-08-04 01:04:22 +03:00
Ivan Kochurkin
5291648d39 [FIR] Temporary change UPPER_BOUND_VIOLATED to warning to unblock bootstrap tests 2021-08-03 23:15:40 +03:00
Dmitry Petrov
bd71fbe982 JVM_IR KT-34594 strip fake variable initialization during inlining 2021-08-03 20:41:31 +03:00
Dmitry Petrov
37050e0616 JVM_IR KT-34594 don't generate fake local variable for @InlineOnly 2021-08-03 20:41:31 +03:00
Simon Ogorodnik
32b380e187 [FP] Fix compiler arguments for intellij-community building 2021-08-03 19:52:23 +03:00
Simon Ogorodnik
872b6b7e81 [FE 1.0 FP] Fix compiler arguments to avoid errors 2021-08-03 19:52:23 +03:00
Simon Ogorodnik
a7961a4a45 [FIR MT] Add reading of packagePrefix from model of java roots 2021-08-03 19:52:22 +03:00
Simon Ogorodnik
97bfc49ed6 [FIR Test] Fix file counting for global passes 2021-08-03 19:52:21 +03:00
Simon Ogorodnik
1188d311b3 [FIR MT] Add sorting by timestamp from model, reading of modularJdkRoot 2021-08-03 19:52:20 +03:00
Mikhail Glukhikh
77f0bd3834 FirOuterClassArgumentsRequiredChecker: read containingClass safely 2021-08-03 19:52:18 +03:00
Nikolay Krasko
bb718f2e0b Allow reading signing parameters from environment variables (KTI-552) 2021-08-03 17:54:09 +03:00
Denis.Zharkov
fa9f0d588d Optimize FastJarHandler
- Do not use normalization as it seems unnecessary
2021-08-03 16:24:51 +03:00
Denis.Zharkov
2266a348c3 Get rid of another map built in FastJarHandler 2021-08-03 16:24:50 +03:00
Denis.Zharkov
42b2605c2a Minor. Rename local vals 2021-08-03 16:24:50 +03:00
Denis.Zharkov
1a262c9c31 Adapt FastJarVirtualFile constructor to its usages 2021-08-03 16:24:49 +03:00
Denis.Zharkov
920d57563b Add fast-path for filename String creation
In most cases, it's encoded with ASCI
2021-08-03 16:24:48 +03:00
Denis.Zharkov
cd51264940 Avoid using FactoryMap at FastJarHandler
It has quite a slow entrySet implementation
2021-08-03 16:24:48 +03:00
Denis.Zharkov
979f5e8443 Rework FastJarHandler
1. Do not inherit from ZipHandler
2. Previously, the following computations have been happening:
- Map<String, ZipEntryDescription> -> Map<String, EntryInfo> (see createEntriesMap)
- Map<String, EntryInfo> -> VirtualFile tree

But the intermediate computations (Map<String, EntryInfo>)
were only used in the constructor, thus they've eliminated in this commit

3. Unclear magic semantic from `getOrCreate` with "/" and "\\" (copy-pasted from CoreJarHandler)
has been replaced with `normalizePath`
2021-08-03 16:24:47 +03:00
Denis.Zharkov
edf9f5e647 FIR: Minor. Clarify name for containingClassForStaticMemberAttr 2021-08-03 16:24:46 +03:00
Denis.Zharkov
956bf22191 FIR: Optimize AbstractAnnotationDeserializer
Do not search for annotation constructors unless we really need it
2021-08-03 16:24:45 +03:00
Viacheslav Kormushkin
1654824467 Commonization of CocoaPods libraries
#KT-41631
2021-08-03 12:50:05 +00:00
Pavel Punegov
73bb6d5d34 [Native] Move JavaLauncher property from global scope to the KonanPlugin 2021-08-03 10:15:08 +00:00
Pavel Punegov
6bbfe0d503 [Native] Add project property that holds JavaLauncher provider
This property is initialized once to make ToolRunner do not query for
the launcher. Also set JDK 11 as a default in case of an unavailable JDK
set as the toolchain, like JDK 17 that is not available in the auto mode
in Gradle and requires environment variable to be set.
2021-08-03 10:15:08 +00:00
Pavel Punegov
2656c94535 [Native] Use common toolchain configuration 2021-08-03 10:15:08 +00:00
Pavel Punegov
ba5bd0b069 [Native] Add java plugin dependency to Konan plugin
Change required version of Gradle to 6.7
2021-08-03 10:15:07 +00:00
Pavel Punegov
ad2fabb7cb Add environments for JDK 16 and 17 2021-08-03 10:15:07 +00:00
Pavel Punegov
afa8e16c25 [Native] JDK toolchains in KonanToolRunner
Use JDK toolchains in KonanToolRunner to make build able to change JDK
Use JDK 17 for MacOS aarch64 hosts
2021-08-03 10:15:06 +00:00
Pavel Punegov
5338705402 [Native] Enable parallel platform libs generation on parameter
Use kotlin.native.platformLibs.parallel to control parallel generation.
Disable parallel execution of platform libs on MacOS aarch64
2021-08-03 10:15:06 +00:00
Ilmir Usmanov
cbe0de6111 Extend local variable ranges
when it is safe. Otherwise, they will not be visible in
debugger as soon as they become dead.
 #KT-47749 Fixed
2021-08-03 08:00:51 +00:00
Dmitriy Novozhilov
ca9cbf7eb7 Fix warnings in K/Native code 2021-08-03 07:40:57 +00:00
Mikhael Bogdanov
0a5991d6e7 Update bootstrap to 1.6.0-dev-2117 2021-08-03 07:40:56 +00:00
Svyatoslav Scherbina
fb27459b2e Native: fix downloading dependencies when producing cache 2021-08-03 07:01:08 +00:00
Sergey Bogolepov
e177cecd50 [K/N] Specify -target-cpu for all targets
Motivation:
1. Avoid things like KT-47911.
2. Generate a bit more effective code in some cases.
3. A bit easier -Xoverride-konan-properties.
2021-08-03 05:54:36 +00:00
Sergey Bogolepov
b37cdae966 [K/N] Fix KT-47911
Specify target-cpu when compiling for AArch64 Darwin targets, because
Apple's CPU might execute "movi.2d vD, #0" incorrectly.

See https://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20171218/511205.html.
2021-08-03 05:54:35 +00:00
Sergey Bogolepov
84d06f35e9 [K/N] Update usages of LLVM bin directory on Windows 2021-08-03 05:42:09 +00:00
Sergey Bogolepov
7d8360f38b [K/N] Set target-features for host targets
Benchmarks on CI show that there are some performance regressions after
LLVM update due to worse inliner results. Explicit specification of
target-features fixes the problem. Interestingly, it seems that this is
not required for Darwin AArch64 target.
2021-08-03 05:42:08 +00:00
Sergey Bogolepov
adc1ca76f4 [K/N] Update requirements in readme
* Updated Windows requirements for building from source
* Removed Linux requirements on ncurses because LLVM is built without it
* Explicitly stated glibc version
2021-08-03 05:42:08 +00:00
Sergey Bogolepov
bfc3f35d94 [K/N] Disable stress_gc_allocations for watchos_simulator_arm64 2021-08-03 05:42:07 +00:00
Sergey Bogolepov
8803a69c9d [K/N] Add ARM Neon intrinsic to CallsChecker whitelist 2021-08-03 05:42:07 +00:00
Sergey Bogolepov
922fcc4049 [K/N] Fix windows dynamic tests for LLD
Adjust compilation and linking flags to workaround absence of direct
DLL linkage in LLD.
2021-08-03 05:42:07 +00:00
Sergey Bogolepov
c7c78e0e1a [K/N] Use LLD 12.0.1 for MinGW targets
Clang-produced and GCC-produced binaries might be ABI-incompatible on
MinGW. Explanation on GitHub: msys2/MINGW-packages/issues/6855#issuecomment-680859662.
TL;DR: GCC-generated sections are 16-byte-padded, while Clang ones are
not. It causes problems during merge of COMDAT sections.
I observed the problem during compilation of runtime tests, but it is
possible that the problem could affect main compilation pipeline as well.
https://reviews.llvm.org/D86659 (which landed in LLVM 12) fixes
the problem. So we have another motivation for switching to LLD besides
https://youtrack.jetbrains.com/issue/KT-47605.

The only known downside is unsupported defsym which causes slight binary
size increase. I think it is doable.
2021-08-03 05:42:06 +00:00
Sergey Bogolepov
6e093b0beb [K/N] Update libffi for Windows
MinGW and MSVC are hardly compatible in case of static linkage, so we
need to use a native libffi.
2021-08-03 05:42:06 +00:00
Sergey Bogolepov
a525f3f357 [K/N] Fix path to ld.gold on Windows
targetToolchain.mingw_x64-linux_* are changed, so we should their usages
Probably, we could switch to LLD, but it requires additional testing.
2021-08-03 05:42:05 +00:00
Sergey Bogolepov
66ddd15798 [K/N] Support compiler compilation in MSVC environment
The right way is to add something like KonanTarget.MSVC_X64, but doing
so requires changes throughout whole compiler. It would be especially
painful in HostManager, where we would need to deprecate
KonanTarget.MINGW_X64 as host. Instead we "hack" ClangArgs to compile
for x86_64-pc-windows-msvc instead of x86_64-pc-windows-gnu in JNI case.

CI may contain custom MSVC and Windows Kit installation path, so we
should support it. Things might break when machine has several MSVC
installed (at custom and default path), but it sounds more like
incorrect environment setup problem than ours.
2021-08-03 05:42:05 +00:00
Sergey Bogolepov
a78fcd6b64 [K/N] Separate ClangArgs for jni and native
Since LLVM for Windows is now native instead on MinGW, we have to
compile code in a different environment in case of JNI. This commits
just separates ClangArgs into two subclasses without actual behavior
changes.
2021-08-03 05:42:05 +00:00
Sergey Bogolepov
fbbbc1c092 [K/N] Drop Configurables interface for ClangArgs
ClangArgs abused delegation mechanism and it complicated its interface.
2021-08-03 05:42:04 +00:00
Sergey Bogolepov
a783ee9ae7 [K/N] Drop -D_GLIBCXX_USE_CXX11_ABI=0 for LLVM
We don't use old glibc++ ABI for LLVM, so this flag have to be dropped.
(Otherwise you'll find yourself fighting sporadic runtime crushes,
trust me).
2021-08-03 05:42:04 +00:00
Sergey Bogolepov
0d39442a5e [K/N] Update linux_arm32_hfp llvm target features
Set of target features has changed between LLVM 8 and LLVM 11.
Update the list for linux_arm32_hfp to make clang stop complaining.
2021-08-03 05:42:03 +00:00
Sergey Bogolepov
1c7a27ce42 [K/N] Fix mxgot flag for MIPS
It was dropped from cc1 interface, so use -target-feature +xgot instead.
2021-08-03 05:42:03 +00:00
Sergey Bogolepov
e8b025f267 [K/N] Drop obsolete --no-threads LLD flags
--no-threads flag was used, because LLD had deadlock long time ago.
This flag is removed from LLD (in favor of --threads=N) and it looks
like that the bug is gone now. So we can just drop --no-threads flag!
2021-08-03 05:42:03 +00:00
Sergey Bogolepov
572f08151a [K/N] Disable code coverage testing
Since LLVM 8, coverage format has changed.
We don't officially provide code coverage for end-users, so it's ok to
disable it for now and fix later.
2021-08-03 05:42:02 +00:00
Sergey Bogolepov
02aebd6565 [K/N] Update LLVM stubs to 11.1.0
Also add necessary changes to CoverageMappingC.cpp to make it compile.
2021-08-03 05:42:02 +00:00
Sergey Bogolepov
601465fa81 [K/N] Change how common polyhash function are included
Recent versions of LLVM complain when caller and callee have
different vector attributes: https://reviews.llvm.org/D82562.

To mitigate this problem this commit changes how we include
polyHashUnroll* and polyHashTail into Traits: we duplicate them
inside each trait with correct attributes by using
```
#pragma clang attribute push(ATTRIBUTE, apply_to = function)
```
This solution is not pretty for sure, but Clang is not complaining
anymore.
2021-08-03 05:42:02 +00:00
Sergey Bogolepov
493fa1c1e3 [K/N] Update Clang stubs for 11.1.0
Removed hacks for CXType_ExtVector type because now it is included in
Clang C API.
2021-08-03 05:42:01 +00:00
Sergey Bogolepov
023c775188 [K/N] Bump macOS minimal version 2021-08-03 05:42:01 +00:00
Sergey Bogolepov
7dda04a1c9 [K/N] Update LLVM distributions to 11.1.0
This commit is important for several reasons:
1. Finally, LLVM update from 8.0.0 to 11.1.0
At the time of writing, LLVM 12.0.0 already came out, but we need to be
compatible with LLVM from Xcode 12.5, so that's why we stick to a bit
older version of LLVM.
2. These LLVM distributions are built with tools/llvm_builder/package.py
We finally managed to introduce an explicit process of building our LLVM
distributions, so we will be able to updated them more frequently and
adapt to our needs.
3. Native Windows LLVM instead of MinGW
Last but not least, we now use native Windows LLVM distribution. While
it might be harder to use (no more posix everywhere), simpler build
process (building msys2 is not that easy) and no need for MinGW-specific
patches makes such distribution way more convenient.
2021-08-03 05:42:00 +00:00
Sergey Bogolepov
44256db824 [K/N] Update minimal Xcode version
The next LLVM version will be 11.1.0, and we need to be sure that
Xcode supports bitcode of this version. So we bump minimal Xcode version
to 12.5, which should be OK, because by the time Kotlin 1.6.0 comes out,
Xcode 12.5 will be around 6 month old.

Also this commit simplifies tarball naming.
2021-08-03 05:42:00 +00:00
Sergey Bogolepov
017c8d8211 [K/N] Drop linuxArm32Hfp from tetris sample
Its sysroot doesn't include SDL2 anymore, so it won't compile anyway.
2021-08-03 05:38:07 +00:00
Sergey Bogolepov
0923d13d55 [K/N] Fix gtk sample compilation on MinGW 2021-08-03 05:38:06 +00:00
Nikolay Krasko
6c49a18770 Fix exhaustive when in HierarchicalStructureOptOutIT.kt 2021-08-03 06:53:33 +03:00
Dmitriy Novozhilov
0ac96b4973 [Test] Remove redundant out variance from TestStep 2021-08-03 00:26:10 +03:00
Dmitriy Novozhilov
b584fed93d [FIR] Migrate warning/error pairs to DiagnosticFactoryForDeprecation 2021-08-03 00:20:11 +03:00
Dmitriy Novozhilov
adfeab1bd0 [FIR] Add ability to generate special diagnostic factories for deprecation warnings
This kind of diagnostic factory has two different factories with warning
  and error severity and language feature with turns on reporting of error
2021-08-03 00:17:33 +03:00
Dmitriy Novozhilov
d17f984edf [FE 1.0] Migrate most of warning/error pairs to DiagnosticFactoryForDeprecation 2021-08-03 00:17:33 +03:00
Dmitriy Novozhilov
7c73840e4a [FE 1.0] Introduce new kind of diagnostic factories for deprecation warnings/errors 2021-08-03 00:17:33 +03:00
sebastian.sellmair
ff9643b70e [Gradle] CInteropCommonizerTask: Refine local variable names
^KT-47775
^KT-47053
2021-08-02 20:38:28 +00:00
sebastian.sellmair
153df1dd1a [Gradle] CommonizerIT: Parameterize test on commonizeMultipleCInteropsWithTests
Testing the project w/ and w/o the commonon mistake
of declaring dependsOn edges from test to main source sets

^KT-47775
^KT-47053
2021-08-02 20:38:27 +00:00
sebastian.sellmair
db10732d6c [Gradle] Add integration test project 'commonizeMultipleCInteropsWithTests'
Implemented `test multiple cinterops with test source sets and compilations`

This test will assert source set dependencies
and shared native compilations.

^KT-47775
^KT-47053
2021-08-02 20:38:27 +00:00
sebastian.sellmair
4ae51e1d02 [Gradle] AbstractCInteropCommonizerTask: Ensure outputDirectory path is unique and short enough
^KT-47056 Verification Pending
2021-08-02 20:38:27 +00:00
sebastian.sellmair
02d4c866ca [Gradle] CInterop commonization: Improve grouping and dependency management
^KT-47775 Verification Pending
This implementation will be lenient toward the common
*Test.dependsOn(*Main) mistake.

^KT-47053 Verification Pending
Support source sets that do not have a dedicated
shared native compilation. Also support additional visible source sets
coming from associate compilations.
2021-08-02 20:38:26 +00:00
Ivan Kochurkin
a7e81d5154 Fix test data OverridenSetterVisibility.kt 2021-08-02 20:43:24 +03:00
Igor Yakovlev
bbd21da835 [FIR] Move ARGUMENTS_OF_ANNOTATIONS on top of STATUS phase 2021-08-02 20:29:09 +03:00
Igor Yakovlev
0f3f56f676 [FIR] Update resolve status of annotations to partially resolved 2021-08-02 20:29:08 +03:00
Igor Yakovlev
8fd2ddad12 [FIR] Downgrade ensure resolves to types instead of status 2021-08-02 20:29:07 +03:00
Igor Yakovlev
c0949fbc18 [FIR] Remove redundant ensure to status in FirPackageMemberScope 2021-08-02 20:29:06 +03:00
Igor Yakovlev
9fdd3dc53f [FIR IDE] Add support of lazy phase for annotation arguments 2021-08-02 20:29:06 +03:00
Dmitriy Novozhilov
71def0666e [FIR] Introduce special phase for resolve of enums and class literals 2021-08-02 20:29:05 +03:00
Ivan Kochurkin
afb85026c4 Revert "[FIR] Implement INVISIBLE_SETTER"
This reverts commit b3d7ed56
2021-08-02 20:10:22 +03:00
Ivan Kochurkin
b264a2e5dd [FIR] Fix Consider getter and setter for CANNOT_WEAKEN_ACCESS_PRIVILEGE
Hash: 0e2d765a2d
2021-08-02 20:10:22 +03:00
Dmitriy Novozhilov
17bbedbc50 [Test] Fix FileComparisonFailureFirst comparator to keep sorting stability 2021-08-02 20:07:49 +03:00
Dmitriy Novozhilov
ca40cbede5 [Test] Get rid of BackendKindExtractor 2021-08-02 20:07:49 +03:00
Dmitriy Novozhilov
d43d0071a4 [Test] Add documentation to test infrastructure 2021-08-02 20:07:48 +03:00
Dmitriy Novozhilov
08a1134fff [Test] Remove abstract MultiModuleInfoDumper 2021-08-02 20:07:47 +03:00
Dmitriy Novozhilov
90e06bf403 [Test] Reformat AbstractIrSerializeCompileKotlinAgainstInlineKotlinTest
- Extract IrInlineBodiesHandler to separate file
- Replace SerializeSetter environment configurator with SERIALIZE_IR
    directive
2021-08-02 20:07:46 +03:00
Dmitriy Novozhilov
a66f3d26fd [Test] Replace three fixed phases of tests with step system
Now each test is just a sequence of any number of different steps. There
  are two kinds of steps:
1. Run some facade
2. Run handlers of specific artifact kind

Through the test each module passed to each step (if it is compatible
  by kinds of artifacts)
2021-08-02 20:07:45 +03:00
Dmitriy Novozhilov
ba48f80e53 [Test] Introduce single interface for all entities which provides directive containers and test services 2021-08-02 20:07:44 +03:00
Sergey Shanshin
b42d6a3e85 Fix creating of lazy delegated property in kotlinx.serialization
Fixes Kotlin/kotlinx.serialization#1616
2021-08-02 16:27:03 +00:00
Alexander Shabalin
4c3fb8697b Add FormatToSpan 2021-08-02 16:07:50 +00:00
Igor Chevdar
2c068b8c5a [K/N][IR] Fix for https://youtrack.jetbrains.com/issue/KT-47814 2021-08-02 19:22:08 +05:00
Igor Chevdar
da4113af88 [K/N][runtime] Lazy initialization fix for wasm 2021-08-02 19:20:33 +05:00
Simon Ogorodnik
ed07e1c778 [FIR] Add missing type-alias unwrap in CompletionModeCalculator 2021-08-02 17:07:15 +03:00
Simon Ogorodnik
8e890eba3e [FIR] Hack-in indirectly nested locals resolution 2021-08-02 17:07:15 +03:00
Simon Ogorodnik
7422571c72 [FIR] Fix cycle when loading nested enum within java annotation 2021-08-02 17:07:15 +03:00
sebastian.sellmair
947e97511b [Gradle] CInteropProcess: Prevent compilation when depending on project without c-interops 2021-08-02 12:26:46 +00:00
sebastian.sellmair
4ce3f87361 [Gradle] CommonizerIT: Add failing test when depending on project without c-interops
Adapted existing `test KT-47641 commonizing c-interops does not depend on any source compilation`
to add a project dependency from a project with c-interops (p2)
to a project without any c-interops (p0)

This leads to compilation of project p0, since the
cinteropApiElements configuration was not created on p0
2021-08-02 12:26:45 +00:00
sebastian.sellmair
329991217a [Gradle] Prevent cinterop's from depending on compile tasks
- KotlinNativeCompilation
Change how associate compilations are connected.
Instead of using the implementation configuration, it now uses
the `compileDependencyFiles` directly. This will keep the
implementation configuration from containing any main compilation's
output. Therefore this configuration can still be forwarded to the
cinterop tool.

- KotlinNativeTargetConfigurator.kt CInteropConfigurations.kt
Create special configurations for cinteropApiElements and
cinterop dependencies. This configuration is tries to resolve
only cinterop dependencies when such variants are offered by a project.

^KT-47641 Verification Pending
2021-08-02 12:26:45 +00:00
sebastian.sellmair
7b5a3f8d1b [Gradle] Remove c-interop dependency to main compilation's output 2021-08-02 12:26:45 +00:00
sebastian.sellmair
8e6f84d5cd [Gradle] CommonizerIT: Add test asserting that cinterop commonization does not depend on any source compilation
^KT-47641
2021-08-02 12:26:44 +00:00
Simon Ogorodnik
a353719a6b [FIR] Add dump for fir blocks 2021-08-02 11:24:56 +03:00
Dmitriy Novozhilov
199ec60742 [JVM] Reduce number of param slots for string concatenation
With paramSlot = 200 those tests fails on JDKs which are newer than JDK 9
- testConcatDynamic200Long
- testConcatDynamicIndy200Long()
2021-08-01 22:23:48 +03:00
Dmitriy Novozhilov
5206b45ce3 [Test] Use JDK 11 instead of JDK 9 in modern jdk tests 2021-08-01 22:23:47 +03:00
Dmitriy Novozhilov
fd537e7d5a [Build] Detect JDK 17 in old way using environment variables
There is a problem that toolchains can not detect JDK 17 EAP
  on windows agents. This commit will be reverted after JDK 17 release
  in adoptopenjdk.net
2021-08-01 22:23:47 +03:00
Dmitriy Novozhilov
17fc1da719 [Reflection] Support java records in kotlin reflection
^KT-47760
2021-08-01 22:23:46 +03:00
Dmitriy Novozhilov
8dad8fa813 [Reflection] Support java sealed classes in kotlin reflection
^KT-46778
2021-08-01 22:23:45 +03:00
Dmitriy Novozhilov
fa1d09c778 [FE 1.0] Support java sealed classes
^KT-46778 Fixed
2021-08-01 22:23:45 +03:00
Dmitriy Novozhilov
972211f8e6 [Test] Add directive which allows to attach debugger to instance of JVM in box test 2021-08-01 22:23:44 +03:00
Dmitriy Novozhilov
1fa74ef939 [Test] Move test on modern jdk to separate test runners
This is needed to avoid problems with installation of proper jdk
  on developer machines. Those tests will be moved back to main box
  suites after migrating our tests on LTS versions of jdk (11 and 17
  instead of 9 and 15)
2021-08-01 22:23:43 +03:00
Dmitriy Novozhilov
89bd52c7d2 [Test] Provide path to JDK 9/15/17 via toolchains 2021-08-01 22:23:42 +03:00
Dmitriy Novozhilov
de73622af9 [Test] Mark BB tests on modern jdks with tag and ignore them in different-jdk tests 2021-08-01 22:23:42 +03:00
Dmitriy Novozhilov
c2e2068682 [Test] Add ability to mark group of tests with specific tags
Currently tags can be applied to all tests in specific testdata
  directory by placing `_tags.txt` file in it, where all tags should
  be listed on separate lines. Test generator adds those tags to
  corresponding generated test classes with `@Tag` annotation

Please note that is applicable only to JUnit 5 tests
2021-08-01 22:23:41 +03:00
Dmitriy Novozhilov
b9c549803d [Test] Replace public fun box() with fun box() in all box tests 2021-08-01 22:23:40 +03:00
Dmitriy Novozhilov
c168a561df [Test] Migrate tests for java 15 to regular test infrastructure 2021-08-01 22:23:39 +03:00
Dmitriy Novozhilov
4f73ebbcbd [Test] Migrate tests for java 9 to regular test infrastructure 2021-08-01 22:23:39 +03:00
Dmitriy Novozhilov
ca214bef30 [Test] Add ability to run box test in separate jvm for common codegen tests 2021-08-01 22:23:36 +03:00
Dmitriy Novozhilov
04d9d243de [Test] Convert TestJdkKind.java to Kotlin 2021-08-01 22:23:35 +03:00
Dmitriy Novozhilov
4a09fba3a4 Rename .java to .kt 2021-08-01 22:23:34 +03:00
Dmitriy Novozhilov
e4d2351e03 [Build] Add JDK_17 to list of toolchains 2021-08-01 22:23:34 +03:00
Igor Chevdar
448376f073 [K/N][IR][optmz] Global analysis for top-level initializers
The analysis' goal is to remove redundant calls to initializers
2021-07-31 01:40:00 +05:00
Igor Chevdar
9c6943b8c4 [K/N][IR] Split Devirtualization onto phases
The analysis itself and applying its results to the IR
2021-07-31 01:40:00 +05:00
Igor Chevdar
b11201be81 [K/N][IR][runtime] Implemented lazy per-file initialization strategy 2021-07-31 01:39:59 +05:00
Mark Punzalan
504449f03e FIR: Report UNSAFE_CALL instead of SMARTCAST_IMPOSSIBLE when smartcast
to null.

Currently the error message shows the expression is impossible to
smartcast to the nullable type, which is nonsensical since it's already
that type.
2021-07-30 21:49:50 +03:00
Mark Punzalan
0627dbcb78 FIR IDE: Check stability of smartcast expressions in
KtFirExpressionTypeProvider.getDefiniteNullability().
2021-07-30 21:49:49 +03:00
Mikhail Glukhikh
5283f7b7c6 Make EXPERIMENTAL_API_USAGE_ERR warning till 1.6 for fake override case 2021-07-30 21:21:51 +03:00
Alexander Udalov
3636118743 Introduce typealias JvmRepeatable for j.l.a.Repeatable
#KT-12794 Fixed
2021-07-30 19:53:44 +02:00
Alexander Udalov
847c58d574 Report error on class named Container inside repeatable annotation
#KT-12794
 #KT-47971
2021-07-30 19:53:44 +02:00
Alexander Udalov
5f7803f2db Use double-checked locking in some reflection internals
Note that `volatile` is not needed because in both cases we initialize
an object with a final field, which is subject to safe initialization.
2021-07-30 19:53:33 +02:00
Alexander Udalov
e20b354dbd Check repeatable annotation container parameters, retention, target
#KT-12794
 #KT-47928
2021-07-30 19:53:33 +02:00
Alexander Udalov
0a6d010d1c Support new repeatable annotations in kotlin-reflect
- Unwrap Kotlin-repeatable annotations (with implicit container)
- Introduce `KAnnotatedElement.findAnnotations` to find instances of
  repeated annotations

 #KT-12794
2021-07-30 19:53:33 +02:00
Alexander Udalov
67128c022a Report error if both repeatable annotation and its container are used
#KT-12794
2021-07-30 19:53:32 +02:00
Alexander Udalov
b2550f69bc Report error if repeated annotation is used with JVM target 1.6
#KT-12794
2021-07-30 19:53:32 +02:00
Alexander Udalov
26043f3968 Generate Java @Repeatable on Kotlin-repeatable annotation classes
#KT-12794
2021-07-30 19:53:32 +02:00
Alexander Udalov
92a73d7636 Generate container class for repeatable annotations
#KT-12794
2021-07-30 19:53:32 +02:00
Alexander Udalov
87130edfa2 Support using Java-repeatable annotations in Kotlin
#KT-12794
2021-07-30 19:53:32 +02:00
Alexander Udalov
f723389565 Remove mapping of java.Repeatable to kotlin.Repeatable in JavaAnnotationMapper
The main motivation for this change is that
java.lang.annotation.Repeatable has a parameter for the container
annotation, which is lost during conversion to
kotlin.annotation.Repeatable. To support j.l.a.Repeatable in backend
properly, it's absolutely necessary to be able to load the container
annotation for any repeatable annotation class, so the original
j.l.a.Repeatable needs to be stored in the descriptor and accessible
from the backend.

Instead of mapping j.l.a.Repeatable -> k.a.Repeatable, add a frontend
service PlatformAnnotationFeaturesSupport that will determine if an
annotation is repeatable "according to the platform rules", which for
JVM means that it's annotated with j.l.a.Repeatable.

Some effects of this change include:
- Usages of j.l.a.Repeatable are no longer reported as "deprecated", the
  corresponding test is deleted
- Usages of repeatable annotations declared in Java with non-SOURCE
  retention with LV 1.5 and earlier will now result in a slightly
  different error (REPEATED_ANNOTATION instead of
  NON_SOURCE_REPEATED_ANNOTATION)

 #KT-12794
2021-07-30 19:53:32 +02:00
Dmitry Petrov
ebf837c135 JVM_IR disable IR and bytecode validation by default 2021-07-30 20:21:41 +03:00
Ivan Kochurkin
1a40164ef0 [FIR] Fix resolving of single underscore _
Now compiler throws `UNRESOLVED_REFERENCE` here:

```
val boo = { _: Exception -> `_`.stackTrace }
```
2021-07-30 16:58:07 +00:00
Ivan Kochurkin
8bfaa39a5c [FIR] Implement RESOLVED_TO_UNDERSCORE_NAMED_CATCH_PARAMETER
Split underscore checkers
2021-07-30 16:58:07 +00:00
Ivan Kochurkin
10d9988824 [FIR] Implement DANGEROUS_CHARACTERS 2021-07-30 16:58:06 +00:00
Ivan Kochurkin
83895c49c5 [FIR] Implement INVALID_CHARACTERS 2021-07-30 16:58:06 +00:00
Ivan Kochurkin
63fc3645ab [FIR] Optimize performance and fix UNDERSCORE_IS_RESERVED, simplify code 2021-07-30 16:58:05 +00:00
Ivan Kochurkin
2fbb700ec6 [FIR] Add nonFatalDiagnostics to FirQualifierAccess 2021-07-30 16:58:05 +00:00
Ivan Kochurkin
b307358f69 [FIR] buildErrorExpression for labels with underscored name
Add ConeDiagnosticWithSource, ConeUnderscoreIsReserved, ConeUnderscoreUsageWithoutBackticks diagnostics
2021-07-30 16:58:05 +00:00
Ivan Kochurkin
f5d8535dc5 [FIR] Add aliasSource to FirImport, FirImportImpl 2021-07-30 16:58:04 +00:00
Mikhail Glukhikh
354a06b94a FirSuspendCallChecker: make infix call check more clear 2021-07-30 19:06:55 +03:00
Mikhail Glukhikh
3c2e266c31 FirSuspendCallChecker: use symbol accessor API instead of symbol.fir 2021-07-30 19:06:54 +03:00
Mikhail Glukhikh
e0b1d0db53 FirSuspendCallChecker: drop support of experimental coroutines 2021-07-30 19:06:53 +03:00
Mikhail Glukhikh
807f031dcc FIR: introduce RETURN_FOR_BUILT_IN_SUSPEND diagnostic 2021-07-30 19:06:53 +03:00
Mikhail Glukhikh
229dfd3f5f FIR: introduce builtin suspend related diagnostics 2021-07-30 19:06:51 +03:00
Mikhail Glukhikh
391c4db87c FIR: introduce ILLEGAL_RESTRICTED_SUSPENDING_FUNCTION_CALL diagnostics 2021-07-30 19:06:49 +03:00
Mikhail Glukhikh
2397650c24 FIR: introduce NON_LOCAL_SUSPENSION_POINT diagnostic 2021-07-30 19:06:48 +03:00
Mikhail Glukhikh
8f1d07084b FIR: introduce ILLEGAL_SUSPEND_FUNCTION_CALL & PROPERTY_ACCESS diagnostics 2021-07-30 19:06:46 +03:00
Ilya Kirillov
e4992176c1 FIR LC: fix inheritance checking for light classes
Before it was not able to check inheritance with type parameters substitutions like

class A<T>
class B: A<Int>
2021-07-30 18:59:21 +03:00
Ilya Kirillov
767af0dae0 HL API: fix super declarations search for local classes 2021-07-30 18:59:19 +03:00
Ivan Kochurkin
0e2d765a2d [FIR] Consider getter and setter for CANNOT_WEAKEN_ACCESS_PRIVILEGE
Fill source with correct value instead of null
for FirDefaultPropertySetter in light tree converter
2021-07-30 18:07:35 +03:00
Ivan Kochurkin
b3d7ed569d [FIR] Implement INVISIBLE_SETTER 2021-07-30 18:07:34 +03:00
Nikolay Krasko
ca4410aa53 Stop auto-generating expected test data on TeamCity in assertEqualsToFile 2021-07-30 17:46:45 +03:00
Sergey Igushkin
edaf925b19 Reorder Gradle -Xplugin=... so that serialization goes first (KT-47921)
Ensure that the serialization plugin's artifact (and, possibly, some
other prioritized plugin artifacts) are put first to the -Xplugin=...
classpath passed to the compiler.

This fixes the conflict of the serialization plugin with some other
plugins altering the IR in unexpected ways.

Issue #KT-47921
2021-07-30 16:20:14 +04:00
Dmitriy Dolovov
033a9f1589 Bump konanVersion: 1.6.0 2021-07-30 14:52:08 +03:00
Ilya Matveev
e45b13d582 [K/N][New MM] Check if asserts are enabled in thread state asserts 2021-07-30 10:30:50 +00:00
Aleksandr Samofalov
5ee87e126d KMA-51 Use local ObjCExportMapper in ObjCExportTranslatorMobile 2021-07-30 13:13:26 +03:00
Aleksandr Samofalov
d72a399982 KMA-51 Create API to use ObjCExportTranslator to translate functions in IDE 2021-07-30 13:13:26 +03:00
Yahor Berdnikau
90d15f156b Fix toolchain may fail to find tools.jar and false-fail the build.
This may happen when build itself is running on JDK9+ and toolchain
is set to <=JDK1.8. CompilerEnvironment gets 'tools.jar' from the
current Gradle Daemon JDK, but there was a check if exception should be
thrown that uses 'javaVersion' from toolchain provided JDK.

Additionally also fixed 'tools.jar' was not provided for
 'KotlinCompileWithWorkers' task.

^KT-47940 Fixed
2021-07-30 09:59:49 +00:00
Yahor Berdnikau
bab5a4a6c9 Allow to specify JDK for build.
For now it disables debug option.

^KT-47940 In progress
2021-07-30 09:59:49 +00:00
Alexander Gorshenev
9148094bbd Garbage collection capable wrappers for skia interop 2021-07-30 12:54:51 +03:00
Alexander Shabalin
d9483ccb08 Enable stacktraces for RuntimeAssert, TODO 2021-07-30 08:22:32 +00:00
Pavel Kunyavskiy
d18ade088d [K/N] Help message for disabling quarantine flag on dylibs in distribution 2021-07-30 08:17:45 +00:00
Elena Lepilkina
9142b03df5 [K/N][Samples] Use unsigned types in videoplayer 2021-07-30 08:05:44 +00:00
Dmitry Petrov
ca5ebdc13c PSI2IR KT-44855 propagate smart cast information for property values 2021-07-29 21:41:50 +03:00
Mikhael Bogdanov
cdbd0eb932 Reopen KT-47920 test and add missed .txt files
#KT-47920 Open
2021-07-29 19:52:59 +02:00
Mikhael Bogdanov
824d6ab5cc Update tests affected by 'ProhibitSimplificationOfNonTrivialConstBooleanExpressions' feature 2021-07-29 19:45:57 +02:00
Mikhael Bogdanov
1e2547d0d0 Temporary mute test-lombok-with-kapt test
#KT-47945
2021-07-29 19:45:57 +02:00
Mikhael Bogdanov
588952bc9a Fix maven tests 2021-07-29 19:45:57 +02:00
Mikhael Bogdanov
a1bd728aef Update SNAPSHOT version in maven projects/tests 2021-07-29 19:45:57 +02:00
Mikhail Glukhikh
55f7bb2756 Fix FIR PSI consistency test (definitely not-null types) 2021-07-29 19:45:57 +02:00
Alexander Udalov
d36c56497e Minor, improve CLI test internalArgOverrideOffLanguageFeature
Avoid disabling language features which cannot be disabled anymore.
2021-07-29 19:45:57 +02:00
Dmitriy Novozhilov
262c9e88d1 [FE 1.0] Fix remaining codegen spec tests 2021-07-29 19:45:57 +02:00
Denis.Zharkov
ee68962c02 Ignore Jvm8RuntimeDescriptorLoaderTestGenerated::testMapRemove
For now, JavaResolverSettings in runtime are different from
default language version, so it might have a little bit different API surface

In future, it's worth considering changing JavaResolverSettings.Default
once default language version is changing

  #KT-47903
2021-07-29 19:45:57 +02:00
Mikhael Bogdanov
4fe846fb81 Fix test affected by InstantiationOfAnnotationClasses feature 2021-07-29 19:45:57 +02:00
Mikhael Bogdanov
1347ee8c7d Update DiagnosicTestGenerated affected by 'PrivateInFileEffectiveVisibility' feature 2021-07-29 19:45:57 +02:00
Denis.Zharkov
d2ad421e0b Fix test data for definitelyNotNullType 2021-07-29 19:45:57 +02:00
Denis.Zharkov
8f484fcf88 Fix propagation of definitelyNotNull types from overrides 2021-07-29 19:45:57 +02:00
Victor Petukhov
cba224b7b8 Update spec black box tests 2021-07-29 19:45:56 +02:00
Mikhael Bogdanov
baaa615e09 Update FirOldFrontendDiagnosticsTestGenerated tests 2021-07-29 19:45:56 +02:00
Mikhael Bogdanov
70e4472c99 Update Fir2IrTextTestGenerated tests 2021-07-29 19:45:56 +02:00
Victor Petukhov
d2a7434cff Update testdata 2021-07-29 19:45:56 +02:00
Denis.Zharkov
f34726ff91 Fix test data for ForeignAnnotations 2021-07-29 19:45:56 +02:00
Dmitriy Novozhilov
2ae546576c [FE 1.0] Update DUPLICATE_LABEL_IN_WHEN testdata
New diagnostics started to report because in 1.6 we assume that
  `1` is typed const of type Int instead of literal const
2021-07-29 19:45:56 +02:00
Dmitriy Novozhilov
b1d17cfd7b [FE 1.0] Force resolve annotations on type arguments
^KT-46173
2021-07-29 19:45:56 +02:00
Dmitriy Novozhilov
e316cd04b6 [FIR] Fix consistency of FE 1.0 and FIR test data 2021-07-29 19:45:56 +02:00
Denis.Zharkov
699d53e7f9 Fix ISE when copying a function with @NotNull bounded type parameters
For example in the case:
<_A extends @NotNull B, B> void f4(_A x, B y) { }

ISE had happened because while substituting the function
we've been creating copies of old type parameters and when initializing
bounds for one of them bounds for other may not be initialized yet
at the same time bounds were necessary for makesSenseToBeDefinitelyNotNull
2021-07-29 19:45:56 +02:00
Mikhael Bogdanov
0c419eac1a Update Java8BuiltInsWithJDKMembersTest tests 2021-07-29 19:45:56 +02:00
Mikhael Bogdanov
0f216f4d37 Update LoadJava8TestGenerated tests 2021-07-29 19:45:56 +02:00
Mikhael Bogdanov
a544d6948b Fix simpleUnaryOperators.kt test 2021-07-29 19:45:56 +02:00
Victor Petukhov
f84adcb378 [FE 1.0] Fix some foreign annotation tests 2021-07-29 19:45:56 +02:00
Victor Petukhov
ca0b8be53b [FE 1.0] Fix some diagnostic spec tests 2021-07-29 19:45:55 +02:00
Alexander Udalov
0ed9b75428 Minor, fix diagnostic test data for FIR 2021-07-29 19:45:55 +02:00
Alexander Udalov
b442e598d3 Fix test data of codegen tests for KT-47328 for 1.6 2021-07-29 19:45:55 +02:00
Alexander Udalov
f1ac5796ed Fix test data of compileJavaAgainstKotlin for 1.6
See LanguageFeature.DefinitelyNotNullTypeParameters.
2021-07-29 19:45:55 +02:00
Alexander Udalov
2d0d83a54b Fix AntTaskTestGenerated.testLanguageVersion for 1.6 2021-07-29 19:45:55 +02:00
Alexander Udalov
6af042c1dd Temporarily disable runtime version consistency checks
To be enabled after the project is fully bootstrapped and default
language version is advanced to 1.6.
2021-07-29 19:45:55 +02:00
Victor Petukhov
95492f7370 [FE 1.0] Fix some diagnostic tests 2021-07-29 19:45:55 +02:00
Dmitriy Novozhilov
7250aed3b5 [FE 1.0] Fix some diagnostic tests 2021-07-29 19:45:55 +02:00
Mikhael Bogdanov
c9c82ab3a6 Update test affected by SafeCallsAreAlwaysNullable feature 2021-07-29 19:45:55 +02:00
Mikhael Bogdanov
c8094f7439 Add readable toString for JavaTypeEnhancementState 2021-07-29 19:45:55 +02:00
Mikhael Bogdanov
f590c3201a Update ScriptingHostTest.testCompileOptionsLanguageVersion test 2021-07-29 19:45:55 +02:00
Mikhael Bogdanov
70fe984738 Update classTypeParameter.kt test 2021-07-29 19:45:55 +02:00
Mikhael Bogdanov
cc5ba4c0af Update diagnostic tests 2021-07-29 19:45:54 +02:00
Mikhael Bogdanov
0cccb76652 Update tests affected by ProperTypeInferenceConstraintsProcessing feature 2021-07-29 19:45:54 +02:00
Mikhael Bogdanov
235359e028 Ignore tests cause of KT-47542
#KT-47542
2021-07-29 19:45:54 +02:00
Mikhael Bogdanov
390eda1b9d Fix CompileKotlinAgainstCustomBinariesTest tests 2021-07-29 19:45:54 +02:00
Mikhael Bogdanov
7854e9c3d7 Update CLI tests 2021-07-29 19:45:54 +02:00
Mikhael Bogdanov
1187e786f4 Fix compilation in MappedExtensionProvider.kt 2021-07-29 19:45:54 +02:00
Mikhael Bogdanov
5f3f2e762a Update JS tests 2021-07-29 19:45:54 +02:00
Mikhael Bogdanov
1fe1c197ee Mute WASM safeAccess.kt test
Update JS tests
2021-07-29 19:45:54 +02:00
Mikhael Bogdanov
29f6ec4f40 Update defaultSnapshotVersion to 1.6.255-SNAPSHOT 2021-07-29 19:45:54 +02:00
Mikhael Bogdanov
38fb5e16ef Update test affected by ApproximateIntegerLiteralTypesInReceiverPosition feature 2021-07-29 19:45:54 +02:00
Mikhael Bogdanov
805778e782 Fix compilation cause of KT-47797 problem
#KT-47797
2021-07-29 19:45:54 +02:00
Mikhael Bogdanov
7cbd6908f9 Update test affected by ProhibitUsingNullableTypeParameterAgainstNotNullAnnotated feature 2021-07-29 19:45:53 +02:00
Mikhael Bogdanov
228100ef09 Upgrade toolchain to api/lv 1.4 2021-07-29 19:45:53 +02:00
Mikhael Bogdanov
a919aab3ab Update metadata related logic after switch to 1.6 2021-07-29 19:45:53 +02:00
Mikhael Bogdanov
ee07ff7982 Switch latest stable version to 1.6 2021-07-29 19:45:53 +02:00
Dmitry Petrov
caa13b33b1 JVM_IR minor: update testdata 2021-07-29 20:45:16 +03:00
Dmitry Petrov
b93dff003f JVM_IR configure loop shape in the backend context 2021-07-29 20:45:15 +03:00
Dmitry Petrov
38d6c8ded0 JVM_IR generate range loops as counter loops when possible 2021-07-29 20:45:14 +03:00
Sergey Igushkin
d0f207071c Prepare for enabling HMPP by default and migrating the flags (KT-40245)
* Add a new single flag for enabling HMPP:
  kotlin.mpp.hierarchicalStructureSupport

  When this flag is enabled:

  * The old HMPP flags gets enabled, too, for old consumers
  * The commonizer gets enabled as well
  * An internal flag is set to indicate that the old flags were set by
    the plugin

* Add an internal flag that we should flip when HMPP becomes the
  default: kotlin.internal.mpp.hierarchicalStructureByDefault

  With this flag is enabled:

  * All MPP projects will use the composite artifact and
    compile metadata with the KLIB compiler
  * The compatibility metadata artifact will be gone
  * The new HMPP flag is enabled by default

* Add consistency checks for new VS old flags

Issue #KT-40245
2021-07-29 19:12:53 +03:00
Pavel Kirpichenkov
352c624601 Provide built-ins module name in IrLinker for debugger 2021-07-29 19:04:25 +03:00
Dmitriy Novozhilov
046730c62c [Test] Integrate AbstractCompileTimeConstantEvaluatorTest to AbstractDiagnosticTest
^KT-47898
2021-07-29 15:25:53 +03:00
pyos
c401582770 FE: do not wrap types with enhancements if they're the same 2021-07-29 14:52:51 +03:00
pyos
8c524c2f89 FE: do not attach enhancements to parts of enhanced flexible types 2021-07-29 14:52:51 +03:00
pyos
6cb6abee98 FE: do not create multiple layers of enhancements for warnings 2021-07-29 14:52:51 +03:00
Victor Petukhov
5684b6977a Do preparation of enhancement as well (for types with enhancement), during subtype checks
^KT-47899 Fixed
2021-07-29 14:23:56 +03:00
Victor Petukhov
c5d783596d Check type parameter bounds by java nullability annotations not only in basic resolution context
^KT-47920 Fixed
2021-07-29 14:23:55 +03:00
Victor Petukhov
20d50cfee7 Prevent leaking of type parameter erasion results cache into static scope 2021-07-29 14:23:55 +03:00
Victor Petukhov
6706ee87ad Introduce TypeParameterUpperBoundEraser to memorize results of type parameters erasion computation
^KT-47785 Fixed
2021-07-29 14:23:54 +03:00
Victor Petukhov
f9cb0d61a8 Don't apply Java defaulting nullability annotations rules to unbounded wildcards
^KT-47396 Fixed
2021-07-29 14:23:53 +03:00
Victor Petukhov
99491014e4 Prefer flexible nullability by Java annotations to nullable one if the corresponding type parameter has nullable bound
^KT-47422 Fixed
2021-07-29 14:23:52 +03:00
Dmitriy Novozhilov
2c9857b880 Assume LV 1.6 ready for preview
^KTIJ-19253 Fixed
2021-07-29 13:28:15 +03:00
Dmitriy Dolovov
59dcef81f7 [K/N][Gradle] Make sure K/N Gradle plugin don't fail when K/N distribution directory has no platform libs 2021-07-29 12:56:55 +03:00
Dmitriy Dolovov
66c9d658e4 [K/N] Keep the Kotlin/Native compiler version inside of the K/N distribution
Restore the behavior that was accidentally disabled.
2021-07-29 12:56:50 +03:00
Dmitriy Dolovov
b505486063 K/N, Minor: Drop unused exception class: KonanIrDeserializationException 2021-07-29 12:56:45 +03:00
Dmitriy Dolovov
50d150ace5 K/N: Avoid reporting excessive "error: compilation failed: null" message
This could happen if the source of the exception is inside of KotlinIrLinker/KonanIrLinker or IR deserializers.
2021-07-29 12:56:40 +03:00
Ilya Matveev
3e823d62a9 [K/N][kotlin.test] Make GeneratedSuites public
Issue #KT-47915 fixed
2021-07-29 08:44:32 +00:00
Ivan Kochurkin
d4e1cded59 [FIR] Implement RESOLUTION_TO_CLASSIFIER 2021-07-28 23:18:38 +03:00
Ivan Kochurkin
2574dc907c [FIR] Implement FUNCTION_EXPECTED 2021-07-28 23:17:31 +03:00
Ivan Kochurkin
263e40e753 [FIR] Implement NO_RECEIVER_ALLOWED 2021-07-28 22:52:06 +03:00
Dmitry Savvinov
45a384bb77 Exclude stdlib-common from non-JVM targets as well
This is a continuation of KT-46936. This commit removes stdlib-common
from platform-specific source sets of JS/Native targets, as well as
Android and 'jvm { withJava() }'

The tests are made on kotlin-ide side, see the KT-46936 for attached
commits.

^KT-46936
^KT-47695 Fixed
^KT-47604 Fixed
2021-07-28 20:02:13 +03:00
Dmitry Petrov
ce79fc77c9 JVM minor cleanup in bytecode analyzers 2021-07-28 19:53:39 +03:00
Hung Nguyen
f95c50064c KT-45777: Refactor IncrementalJvmCache to support classpath snapshotting
Extract minimal required information into the new `KotlinClassInfo`
class. This info will be part of the classpath snapshot of the
`KotlinCompile` task in an upcoming change.

Bug: KT-45777
Test: Existing tests should pass (this is a refactoring-only change)
2021-07-28 19:32:10 +03:00
Pavel Kirpichenkov
19467861c9 [MPP] Fix false positive expect-actual mismatch
Use type refiner to correctly expand actual type alias - expect
class chains, produced by the commonizer. In a case when type
refiner doesn't exist for module create a one-shot thread local
instance. This might happen with modules without source code
in project (coming from build system model).

^KT-46691 Fixed
2021-07-28 18:57:08 +03:00
Pavel Kirpichenkov
2d91917ac7 [MPP] Make type refinement capability aware of HMPP state
Introduce intermediate state for cases when module doens't
have a type refiner even though HMPP is enabled.

KT-46691
2021-07-28 18:57:07 +03:00
Pavel Kirpichenkov
566640aa6d [MPP] Move KotlinTypeRefinerImpl (frontend -> descriptors)
ExpectedActualResolver in certain cases needs an ability
to create a standalone refiner instance, see the following
commits. A direct module dependency (resolution -> frontend)
can't be added, the opposite one already exists which leads
to a dependency cycle. Both modules depend on core.descriptors
module where KotlinTypeRefiner resides.

KT-46691
2021-07-28 18:57:07 +03:00
Pavel Kirpichenkov
1f3004a667 [MPP] Support multiple levels of actual type alias expansions
Commonizer might transform typealias chains into several
expect classes with actual type aliases. In this case
refining a common type once is not enough as the result
will be another expect type from type alias expansion.

KT-46691
2021-07-28 18:57:05 +03:00
Andrey Zinovyev
d84cc4333c [FIR] Add INITIALIZATION_BEFORE_DECLARATION diagnostic 2021-07-28 16:56:54 +03:00
Andrey Zinovyev
b706e776ad [FIR] Add VARIABLE_WITH_NO_TYPE_NO_INITIALIZER diagnostic 2021-07-28 16:56:53 +03:00
Svyatoslav Scherbina
a63f218dd3 Stop using ModuleDescriptor.name for top-level ObjCExport name prefix
^KT-47809 Fixed

Do similar for C export.
2021-07-28 12:46:11 +00:00
Alexander Shabalin
48a2b23b3a Add a separate compiler switch for runtime asserts 2021-07-28 07:43:08 +00:00
Alexander Likhachev
c3515cc338 [Gradle] Use compiler argument -opt-in instead of '-Xopt-in'
#KT-35832 Fixed
2021-07-28 05:58:58 +00:00
Alexander Likhachev
10f9c217fd [Gradle] Advance K/N version to 1.6.0-dev-1728 2021-07-28 05:58:58 +00:00
Dmitry Petrov
4267852030 JVM cleanup bytecode analyzers 2021-07-28 08:04:55 +03:00
pyos
e9b177352c JVM_IR: do not inline reads of constructor arguments into accessors 2021-07-28 02:16:01 +02:00
Vasily Levchenko
2baf344f5f [kotlin gradle plugin] enable to work with embedded k/n compiler. 2021-07-27 19:44:31 +00:00
Vasily Levchenko
1eb951749d [build][kotlin-native] native compiler embeddable 2021-07-27 19:44:31 +00:00
Viacheslav Kormushkin
fa2e787f76 CocoaPods Gradle plugin: Support incremental task execution when switching between Xcode and terminal
#KT-37511
2021-07-27 16:08:32 +00:00
Ilya Kirillov
91ecaa32e3 HL API: render local fqNames in reference resolve tests 2021-07-27 17:58:47 +03:00
Ilya Kirillov
77fcb12af8 Fix project leaking in tests
The project was leaking via MockApplication -> LowMemoryWatcherManager -> List<Project>
It happened due to unregistered disposable provided to the MockApplication
2021-07-27 17:58:47 +03:00
Ilya Kirillov
f19dfd9d2a HL API: restore SymbolByReferenceTest
Now it is possible as references are working in HL API tests now
2021-07-27 17:58:46 +03:00
Ilya Kirillov
c678d4b506 HL API: generate reference resolve tests
The testdata is taken from corresponding IDE reference resolve tests
2021-07-27 17:58:45 +03:00
Ilya Kirillov
7ba8e7d1d3 LL API: fix KtPackageProvider package existent checks for tests
Before it was not able to check nested packages for existence

Also, implement unimplemented getKotlinSubPackageFqNames
2021-07-27 17:58:45 +03:00
Ilya Kirillov
4fe240d1b4 HL API: fix KtUserType kt -> fir mapping for non-IDEA usages
createType(KtTypeElement) requires some access to IJ services which are unavailable to IJ core
2021-07-27 17:58:44 +03:00
Ilya Kirillov
970d7b5a78 HL API: implement tests for reference resolve 2021-07-27 17:58:43 +03:00
Ilya Kirillov
55489b6249 FIR IDE: fix containing KtFirSymbolContainingDeclarationProvider for implicit constructors 2021-07-27 17:58:42 +03:00
Ilya Kirillov
eb69153fbc HL API: fix renderer for package symbols 2021-07-27 17:58:40 +03:00
Mikhail Glukhikh
84bd347841 Make EXPERIMENTAL_API_USAGE_ERR warning till 1.6 for signature type case 2021-07-27 14:58:56 +03:00
Mikhail Glukhikh
810def829c Make EXPERIMENTAL_ANNOTATION_ON_OVERRIDE warning till 1.6 2021-07-27 14:58:55 +03:00
Mikhail Glukhikh
bb38eaae61 Postpone OptIn release to version 1.7 2021-07-27 14:56:54 +03:00
Alexander Udalov
0a9498f7e2 Build: suppress deprecated JVM target warning globally
There seems to be no point in configuring the compiler argument per
project. This argument will be deleted soon anyway, when we remove
support for JDK 1.6 & 1.7.

Also remove `disableDeprecatedJvmTargetWarning`. It didn't have any
effect in all modules where it was applied because these modules
reassign `freeCompilerArgs` anyway, with
`-Xsuppress-deprecated-jvm-target-warning` in it.
2021-07-27 13:35:39 +02:00
Alexander Udalov
91c39ed01c Build: remove obsolete compiler arguments
These compiler arguments enable features which are enabled by default in
the current Kotlin anyway.

The only exception is in :compiler:cli which uses an old language
version.
2021-07-27 13:35:38 +02:00
Steffi Stumpos
707e1c7f8d [Test] Add service to provide additional classpath to box tests 2021-07-27 14:05:51 +03:00
Yahor Berdnikau
a55eacd8db Migrate Gradle daemon memory leak tests to JUnit5.
^KT-45745 In Progress
2021-07-27 11:43:32 +03:00
Pavel Kunyavskiy
be0a0a7784 [K/N] Support escape analysis with new mm 2021-07-27 08:22:02 +00:00
Igor Yakovlev
f671061328 [FIR IDE] Add check resolved type for phase less than Types 2021-07-26 23:08:54 +02:00
Igor Yakovlev
02f2f6c148 [FIR IDE] Code review minor changes 2021-07-26 23:08:54 +02:00
Igor Yakovlev
4eb534e39b [FIR IDE] Remove withFirWithPossibleResolve inside function 2021-07-26 23:08:54 +02:00
Igor Yakovlev
563f8c8541 [FIR IDE] Split names of withRef function to phase and type versions 2021-07-26 23:08:54 +02:00
Igor Yakovlev
66fa624ab7 [FIR IDE] Fix IDE return type calculators 2021-07-26 23:08:54 +02:00
Igor Yakovlev
4711577b17 [FIR IDE] Add containing file workaround for FirLightAnonymousClassForSymbol 2021-07-26 23:08:54 +02:00
Igor Yakovlev
a4426cd40d [FIR IDE] Fix invalid partial resolve of file annotations 2021-07-26 23:08:54 +02:00
Igor Yakovlev
e1c8f302a4 [FIR IDE] Make fir resolve phase volatile and remove locks 2021-07-26 23:08:54 +02:00
Igor Yakovlev
78e249c2d5 [FIR IDE] Fix creating fir light classes for NotUnderContentRootModuleInfo module content 2021-07-26 23:08:53 +02:00
Igor Yakovlev
ab2aaec4fe [FIR IDE] Ensure resolve for status transformer 2021-07-26 23:08:53 +02:00
Igor Yakovlev
4e870b6796 [FIR IDE] Fix invalid resolve for fir synthetic properties and accessors 2021-07-26 23:08:53 +02:00
Igor Yakovlev
6700179ee4 [FIR IDE] Add LibraryModuleSourceInfoBase and filter out light classes for sources from libraries 2021-07-26 23:08:53 +02:00
Igor Yakovlev
a0418c3146 [STUBS] Fix invalid classId calculation for KtObjectLiteralExpression 2021-07-26 23:08:53 +02:00
Igor Yakovlev
6869fbbfe5 [FIR IDE] Insert ensure resolve into checkers and scopes 2021-07-26 23:08:53 +02:00
Igor Yakovlev
2fd6c55fc8 [FIR IDE] Replace FIR phase update to FIR IDE 2021-07-26 23:08:53 +02:00
Ilya Chernikov
df9a3c0300 Restore scripting-ide-services testing, fix coroutines dependency 2021-07-26 21:16:50 +03:00
Ivan Kochurkin
173813f7cf [FIR] Implement REIFIED_TYPE_FORBIDDEN_SUBSTITUTION 2021-07-26 21:13:25 +03:00
Ivan Kochurkin
bade6cb611 [FIR] Improve TYPE_PARAMETER_AS_REIFIED detecting, implement TYPE_PARAMETER_AS_REIFIED_ARRAY, TYPE_PARAMETER_AS_REIFIED_ARRAY_WARNING 2021-07-26 21:13:25 +03:00
Ivan Kochurkin
2333b1bcf6 [FIR] Implement BREAK_OR_CONTINUE_JUMPS_ACROSS_FUNCTION_BOUNDARY 2021-07-26 21:13:23 +03:00
Alexander Udalov
cbdd0f579a Regenerate Gradle options 2021-07-26 19:36:53 +02:00
Alexander Udalov
0083ef053b Remove Gradle option annotation for -Xbuiltins-from-sources
This is an internal compiler argument for FIR which doesn't seem
valuable enough to be exposed in Gradle, because it'd require to perform
some kind of deprecation if it's changed or removed. It'll still be
possible to use it via `freeCompilerArgs += "-Xbuiltins-from-sources"`.

Note that generated Gradle options are not changed because the generator
was not rerun after adding this compiler argument. (And the test that
checks that the generator was run is failing right now.)
2021-07-26 19:36:53 +02:00
Alexander Udalov
fe18e3fa31 Do not use uninterruptible file channels in FileChannelUtil
To avoid illegal access errors from incremental compilation on JDK 16+.

 #KT-45689 Fixed
 #KT-47152 Fixed
2021-07-26 19:27:09 +02:00
Alexander Udalov
2ca241c82c Copy FileChannelUtil from intellij-core
#KT-45689
 #KT-47152
2021-07-26 19:27:09 +02:00
Alexander Udalov
698c0bb2a9 Replace --illegal-access workaround with --add-exports
--illegal-access=permit doesn't work since JDK 17.

 #KT-47152 Fixed
2021-07-26 19:27:09 +02:00
Nikolay Lunyak
a44048e713 Add withBindThis to field configuration 2021-07-26 16:12:16 +00:00
Aleksei.Cherepanov
4003cd2832 Fix backward compatibility of portable caches for 212 idea
Write zero to deletedCount value of counters map instead of removing it in context of LookupStorage performance improving
2021-07-26 18:58:12 +03:00
Alexander Shabalin
a24eab9745 Fix STMS tests 2021-07-26 15:09:59 +00:00
Alexander Udalov
5526281c54 Minor, refactor diagnostic tests on repeatable annotations 2021-07-26 14:33:32 +02:00
Alexander Udalov
56866e6927 JVM IR: move java.lang.annotation symbols to JvmSymbols.javaAnnotations
Since a separate instance of AdditionalClassAnnotationLowering is
created for each source file, symbols for these classes were created as
many times as there were source files in the module.

Also inline some variables in the process and move around some methods.
2021-07-26 14:33:32 +02:00
Alexander Udalov
50f7594d9e Minor, move RepeatableAnnotationChecker to separate file 2021-07-26 14:33:31 +02:00
Alexander Udalov
104188c035 Render annotation arguments in bytecodeListing tests 2021-07-26 14:33:30 +02:00
Yahor Berdnikau
7958307d28 Allow to override build options for particular builds.
^KT-45745 In Progress
2021-07-26 14:27:47 +02:00
Yahor Berdnikau
25192cd639 Fix project options are ignored for builds.
Fix 'forceOutput' and 'enableGradleDebug' project level options are not
taken into account when running particular build.

^KT-45745 In Progress
2021-07-26 14:27:47 +02:00
Yahor Berdnikau
a49b36f6b1 Add additional output assertions.
- check if output contains string exactly times
- check if output does not contain Kotlin warnings
- check expected incremental compilation

^KT-45745 In Progress
2021-07-26 14:27:47 +02:00
Yahor Berdnikau
c816d6f2e5 Modify file exists assertion.
Additionally allow to check if file exists in any location, even outside
of the project.

^KT-45745 In Progress
2021-07-26 14:27:47 +02:00
Yahor Berdnikau
18d74e62a6 Add additional shortcuts for common project files.
^KT-45745 In Progress
2021-07-26 14:27:47 +02:00
Yahor Berdnikau
35677f4727 Add random hash to the tempDir project dir.
This will allow to create several similar projects from one resource
project in a single test.

^KT-45745 In Progress
2021-07-26 14:27:46 +02:00
Andrey Zinovyev
8a0941a85a [FIR] Report deprecations in qualified expressions 2021-07-26 14:50:54 +03:00
Mikhail Glukhikh
98bd6f5d3e Fix "implicit type" exception in FIR OptIn checker 2021-07-26 10:13:13 +03:00
Mikhail Glukhikh
2a6355b64c FIR: use coneType instead of coneTypeSafe in OptIn checkers 2021-07-23 23:59:01 +03:00
Mikhail Glukhikh
73539cf342 FIR: use symbols as base for OptIn-checkers 2021-07-23 23:59:00 +03:00
Mikhail Glukhikh
cb847b945d FIR: use getAnnotationByClassId instead of getAnnotationByFqName 2021-07-23 23:58:59 +03:00
Mikhail Glukhikh
7cbea12c8a FIR: store all annotationContainers in checker context 2021-07-23 23:58:58 +03:00
Mikhail Glukhikh
d020948933 FIR: support EXPERIMENTAL_MARKER_CAN_ONLY_BE_USED_AS_ANNOTATION... 2021-07-23 23:58:57 +03:00
Mikhail Glukhikh
543ce06d85 FIR OptIn: temporarily replace error USAGE with warning
This commit is required for FP test to pass,
because FP test does not see module -Xopt-in=... flags.
2021-07-23 23:58:56 +03:00
Mikhail Glukhikh
82f268d611 FIR: add EXPERIMENTAL_API_USAGE reporting 2021-07-23 23:58:55 +03:00
Mikhail Glukhikh
3235b09a92 FIR: introduce MutableCheckerContext to save performance 2021-07-23 23:48:19 +03:00
Denis.Zharkov
b547870d71 Use unsigned version of short numbers in ZipImplementation
Because some two-byte represented numbers (like amount of files in the zip)
exceed 32767 (but less than 65534)
2021-07-23 21:38:46 +03:00
Denis.Zharkov
ea5157cadc Change type of KotlinCoreEnvironment::projectEnvironment type 2021-07-23 21:38:45 +03:00
Denis.Zharkov
d6adac8dd0 Move FastJarFileSystem to ProjectEnvironment and link to the root disposable 2021-07-23 21:38:45 +03:00
Denis.Zharkov
3afed7f972 Fallback to CoreJarFileSystem when JDK doesn't support buffers unmapping 2021-07-23 21:38:43 +03:00
Denis.Zharkov
c6525974d0 Move handlers cache from static field to the instance of FastJarFileSystem 2021-07-23 21:38:43 +03:00
Denis.Zharkov
03e5dc6117 Force unmapping MappedByteBuffer
Otherwise, on Windows daemon might hold mapped regions for some time
(until those objects are collection) and during the time those file become
locked (it's impossible to modify or remove them)

Reflection/Unsafe of course is not a cool thing to use, but JDK still
(already for 18 years) doesn't have public API for this

See https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4724038
And https://stackoverflow.com/questions/2972986/how-to-unmap-a-file-from-memory-mapped-using-filechannel-in-java
2021-07-23 21:38:42 +03:00
Denis.Zharkov
4e11c670c6 Clear cleanFileAccessorsCache for FastJarFileSystem 2021-07-23 21:38:41 +03:00
Denis.Zharkov
7ca2a83f08 Use native endian mode from MappedByteBuffer 2021-07-23 21:38:40 +03:00
Denis.Zharkov
33cf058b55 Use MappedBuffer for FastJarFileSystem implementation 2021-07-23 21:38:40 +03:00
Denis.Zharkov
8f06e59d3b Implement new faster version of Jar virtual file system
It's only enabled by default in FIR and might be turned on with a CLI flag

The main idea is that default FarFS re-read ZIP file list each time when
class file is requested that is quite slow.
We read it once and them reading bytes from the known offset.

Also, unlike the default version we don't perform attributes check on each access
On the one hand, it works faster on the other it might not notice that one
of the JAR has been changed during compilation process
But looks like it's not supposed to be a frequent even during
compilation of a single module
2021-07-23 21:38:38 +03:00
Dmitriy Novozhilov
559e7d223a [FIR] Add friends path from Module in CLI compiler 2021-07-23 17:28:42 +03:00
Dmitriy Novozhilov
d9d2a9cc31 Move BuildSessionLoggerTest to :kotlin-gradle-plugin tests
There was a problem that :kotlin-gradle-statistics:test can not be
  properly imported and kotlin stdlib wasn't accessible in it. I didn't
  find a way to fix it in :kotlin-gradle-statistics module, so I just
  moved tests from it to others gradle plugin tests
2021-07-23 17:15:55 +03:00
Anton Bannykh
a7549be95e JS IR IC: report cache validataion duration when up-to-date 2021-07-23 17:10:07 +03:00
Anton Bannykh
4cee44cd6e JS IR IC: add a flag for DCE hack
The deserialized PIR does not support declaration mutation.
Until that's fixed the associatedObject removal optimization
has to be disabled.
2021-07-23 17:10:07 +03:00
Anton Bannykh
508d3bd9c0 JS IR IC: IC data may reference additional original declarations
Function types, which are created on the fly from lowerings are one such example.
2021-07-23 17:10:06 +03:00
Anton Bannykh
fa21132704 JS IR IC: fix order storage
Some classes don't survive till the end. Their declaration lists
need to be stored nevertheless.
2021-07-23 17:10:06 +03:00
Anton Bannykh
c6ab195a87 JS IR IC: invalid loops references exist after lowerings 2021-07-23 17:10:04 +03:00
Anton Bannykh
0130d18ea9 JS IR IC: deserialization fix 2021-07-23 17:10:03 +03:00
Anton Bannykh
058ca16af7 JC IR IC: correct signatures for function types created during lowerings 2021-07-23 17:10:02 +03:00
Anton Bannykh
8553c6ef58 JS IR IC: pass through more compiler flags 2021-07-23 17:10:02 +03:00
Yahor Berdnikau
5dc6e1b473 Fix no duplicate strategy was set for compilation with 'withJava()'.
In such case Kotlin jvm compilation has additionally java resource dir
that points to the same location. So ProcessResources task copies same
file twice. Fixed by setting ignore duplicates strategy.

^KT-46978 Fixed
2021-07-23 14:03:57 +00:00
Nikolay Krasko
83023c2073 Remove 202 platform support in build scripts 2021-07-23 16:58:28 +03:00
Nikolay Krasko
ec99585eb9 Remove explicit registration of classFileDecompiler EP and core.xml 2021-07-23 16:58:27 +03:00
Nikolay Krasko
1b3046a61b Cleanup 202 bunch files
Leave 202 in .bunch file to give some time for updating build server
2021-07-23 16:58:26 +03:00
Nikolay Krasko
000a437315 Update .bunch file after 202 -> 203 switch 2021-07-23 16:58:25 +03:00
Nikolay Krasko
bba0dfb469 Cleanup as42 bunch files
We don't build AS42 plugin from main kotlin repo anymore.
2021-07-23 16:58:24 +03:00
Dmitry Petrov
34f5b85ae5 IR KT-47840 fix-point solution for closure conversion 2021-07-23 14:58:23 +03:00
Jinseong Jeon
e9f2d574d5 FIR IDE: simplify HL APIs for PsiType
The idea is to convert `KtType` to `PsiType`, along with the given
`PsiElement` context, instead of providing individual API to convert
different psi source to `PsiType`. To that end, we need to
migrate/rewrite some APIs/implementations that retrieve `KtType` from
different source of `PsiElement`.
2021-07-23 13:28:14 +02:00
Jinseong Jeon
f02f3c76ae FIR IDE: API to resolve KtTypeReference to KtType 2021-07-23 13:28:11 +02:00
Jinseong Jeon
5358d4f07c FIR IDE: construct function type from a function as PsiType 2021-07-23 13:28:05 +02:00
Jinseong Jeon
f19a501cc7 FIR IDE: common super type of given KtExpression's 2021-07-23 13:27:59 +02:00
Jinseong Jeon
5690b4d8c2 FIR IDE: get the return type of KtDeclaration as PsiType 2021-07-23 13:27:57 +02:00
Konstantin Tskhovrebov
de4c2d35ab Assemble fat framework if Xcode requires several architectures.
#KT-47653
2021-07-23 11:00:35 +00:00
Konstantin Tskhovrebov
68a3c5f378 Use 'ARCHS' Xcode env for assembleAppleFramework task registration.
#KT-47653
2021-07-23 11:00:34 +00:00
Konstantin Tskhovrebov
414e735a67 Move native target definition by sdk and arch from Cocoapods to MPP plugin.
#KT-47653
2021-07-23 11:00:34 +00:00
Dmitriy Novozhilov
9b00776dba [FIR] Create CFG node for ::class calls 2021-07-23 12:20:39 +03:00
Yahor Berdnikau
c5ce52eef5 Configure Android SDK in new test dsl. 2021-07-23 08:11:03 +00:00
Yahor Berdnikau
1e758c6767 Toolchain takes into account kotlin options set via Android extension.
This extension updates not common task kotlin options, but special
field in the task. Toolchain will also check this field to decide
whether it should set 'jvmTarget' or not.

^KT-47754 Fixed
2021-07-23 08:11:02 +00:00
Yahor Berdnikau
e3b219b68f Don't produce warning when '-no-jdk' option is present.
Toolchain in such case should avoid setting '-jdk-home' option.

^KT-46626 In Progress
2021-07-23 08:11:02 +00:00
Mads Ager
c0f5d09759 Copy locals in addition to instructions when inlining finally blocks
^KT-46448 Fixed
2021-07-23 09:11:48 +02:00
pyos
d00fba3718 FE: avoid stack overflow on star projection of enhanced type parameter
#KT-47846 Fixed
2021-07-23 10:03:57 +03:00
Sergey Bogolepov
ed44497a9b [K/N] Prepare CallsChecker for LLVM 11.1.0
LLVM 11.1.0 adds a bit more "good" external functions and intrinsics.
2021-07-23 04:52:16 +00:00
Sergey Bogolepov
bce1075fc4 [K/N] Prepare MinGW linker for LLVM 11
Explicitly set sysroot, target and linker when linking MinGW binary
because it won't be the default target after LLVM update.
2021-07-23 04:51:52 +00:00
Sergey Bogolepov
272284680e [K/N] Prepare Windows runtime tests for LLVM update
In the upcoming LLVM update the default target for windows will be
x86_64-pc-windows-msvc and it will break runtime tests. To mitigate this
problem we explicitly set compilation target to x86_64-pc-windows-gnu
as we do in BitcodeCompiler.
2021-07-23 04:46:13 +00:00
Roman Artemev
f768d5b453 [JS TEST] Refactor test runner a bit
Build IC cache for library right after its compilation
2021-07-22 21:56:57 +03:00
Roman Artemev
0310f7cb0b [JS IC] Lot of fixes after rebase 2021-07-22 21:56:57 +03:00
Roman Artemev
8782399ffb [JS IC] Make sure already bound symbol is not being enqueued 2021-07-22 21:56:56 +03:00
Roman Artemev
334e34b70b [JS PIR] Fix inliner. Do not mutate existed statement list
Such list could be part of PIR structures
2021-07-22 21:56:56 +03:00
Anton Bannykh
20088994c1 JS IC: IC lowerings prototype 2021-07-22 21:56:55 +03:00
Anton Bannykh
525c5b886f JS IR gradle plugin: don't run IC for the main module 2021-07-22 21:56:53 +03:00
Anton Bannykh
e03cb372b7 KLIB: don't fail on invalid loops
Temporarily disable assert because this happens in lowered IR
2021-07-22 21:56:52 +03:00
Anton Bannykh
48ce8c049d JS IC: temporarily disable isPublic assert 2021-07-22 21:56:52 +03:00
Anton Bannykh
3833c833ef KLIB: changes in the .proto and linker required for the JS IC
The original behaviour is preserved. All changes should be behind the flags.
2021-07-22 21:56:51 +03:00
Anton Bannykh
002f4210f7 IR: pass information about the declaration being lowered to the infrastructure 2021-07-22 21:56:51 +03:00
Anton Bannykh
5ee865437d JS IC: expose currentDeclaration from StageController 2021-07-22 21:56:50 +03:00
Anton Bannykh
ba541bd53b IR: allow SymbolTable descendants 2021-07-22 21:56:50 +03:00
Anton Bannykh
e0570d98b2 IR: cache IdSignature hashCode for better performance in maps 2021-07-22 21:56:49 +03:00
Anton Bannykh
76f0684d7c IR: .isBound API for F/O declarations
Fake override functions and properties may not be bound to symbols.
This API allows to know if such declaration is actually bound
2021-07-22 21:56:47 +03:00
Dmitry Petrov
6c734289be JVM skip methods without NEW insns in UninitializedStoresProcessor 2021-07-22 21:29:41 +03:00
Dmitry Petrov
eff7c375ce Minor HackedFixStackMethodAnalyzerBase -> FastStackAnalyzer 2021-07-22 21:29:41 +03:00
Dmitry Petrov
aef9701661 JVM use new stack state analyzer in non-local returns preprocessing 2021-07-22 21:29:40 +03:00
Dmitry Petrov
cf2b4dd277 JVM don't use SPBs in FixStack method analyzer (we don't merge) 2021-07-22 21:29:40 +03:00
Dmitry Petrov
ca84aa4f2c JVM don't optimize if there are too many data on exception edges 2021-07-22 21:29:39 +03:00
Dmitry Petrov
c1a5ce6e61 JVM skip redundant boxing optimization in methods without boxing 2021-07-22 21:29:38 +03:00
Tianyu Geng
a8e379a025 FIR: Fix positioning of ENUM_ENTRY_AS_TYPE
The current SELECTOR_BY_QUALIFIED positioning strategy is closely
related what should be done here. But it only works on qualified access
expressions. This change also makes it work for type references.
2021-07-22 20:39:56 +03:00
Tianyu Geng
c648356887 FIR: report ENUM_ENTRY_AS_TYPE and IS_ENUM_TYPE
These two diagnostics are similar: both are reported on type references
to enum entries. But `IS_ENUM_TYPE` is reported if the type ref is an
operand of `is` operator. To pass along this contextual information, a
boolean is added to FirSpecificTypeResolverTransformer.
2021-07-22 20:39:56 +03:00
Tianyu Geng
6dc75c2e51 FIR IDE: allow KtClassOrObject to resolve to null KtSymbol
At PSI level, an enum entry is a `KtClassOrObject`. But the resolved
FIR counterpart `FirEnumEntry` is not an `FirRegularClass`.
2021-07-22 20:39:56 +03:00
Tianyu Geng
bea90e0578 FIR: remove unused diagnsotics
These diagnostics do not exist in FE1.0 and they are not used
anywhere.
2021-07-22 20:39:55 +03:00
Alexander Udalov
3b513ba299 Minor, add test on typeOf subtyping with mutable collections 2021-07-22 15:55:15 +02:00
Alexander Udalov
9ebd665c96 Report error on annotated type inside typeOf on JVM
Since it's not feasible to support annotated types in 1.6, we're making
this an explicit error in 1.6, so that typeOf can become stable and this
feature can be supported in the future without breaking changes to the
existing code.

Note that extension function types are a special case of annotated
types. A separate error is created for them just because the message
"annotated types are not supported" would be confusing, since such types
don't have explicit annotations in the source code.

 #KT-29919
2021-07-22 15:54:48 +02:00
Alexander Udalov
a383d45534 Disable -Werror if test.progressive.mode is enabled
The reason is that when advancing language version, for example from 1.5
to 1.6, there is a brief period between bootstraps where the
bootstrapped compiler has latest stable language version 1.6, yet the
project is still built with 1.5. That leads to a (correct) warning that
progressive mode makes no sense unless the latest language version is
used, which fails the build because of Werror.

When testing bootstrap in progressive mode, we don't actually care about
these warnings, so disable Werror in this case.

The only case where this could matter would be if we were introducing
_warnings_ in progressive mode and checking that there are no new
warnings on Kotlin would be important for us, but so far progressive
mode has only been used to turn already existing warnings to errors.
2021-07-22 15:41:51 +02:00
Mikhael Bogdanov
60458214a5 Update ReadMe.md 2021-07-22 12:41:34 +00:00
Elena Lepilkina
e29a67b3a3 [K/N][perf] Added autoreleasepool in swiftinterop benchmarks 2021-07-22 11:37:55 +00:00
Sergey Bogolepov
f8528c5cca [K/N] Dockerfile for building LLVM
Provide a stable environment for building LLVM for Linux
by using Docker. Note that the base image is Ubuntu 16.04,
so after LLVM update building Kotlin/Native on Linux will
require glibc 2.23 or higher.
2021-07-22 10:44:03 +00:00
Leonid Startsev
83c1a75c1e Revert "Revert "Instantiation of annotations for JVM IR with the corresponding feature flag""
Fix incorrectly rebased ce0a3a57df

This reverts commit 3d0126d5
2021-07-21 18:24:07 +03:00
Philipp Smorygo
54b9ad6bf5 Slightly improve Kotlin library podspec
Add additional parameters to Podspec for clarity.
Add ability to skip building by using an environment variable
2021-07-21 18:07:46 +03:00
Ilya Chernikov
db61665ab8 [minor] IR: clean unnecessary ObsoleteDescriptorBasedAPI opt-ins 2021-07-21 18:05:42 +03:00
Dmitriy Novozhilov
a710a8d10f [FE 1.0] Report warning on non-exhaustive when statements only after 1.6
^KT-47709
2021-07-21 17:53:05 +03:00
Igor Laevsky
865ad3698b WASM: Fix flaky test 2021-07-21 16:53:45 +03:00
Mikhael Bogdanov
d8f839a7e4 Properly process separate process inputStream/outputStream 2021-07-21 13:19:31 +00:00
Leonid Startsev
3d0126d5dd Revert "Instantiation of annotations for JVM IR with the corresponding feature flag"
because of incorrect rebase

This reverts commit ce0a3a57
2021-07-21 15:23:24 +03:00
max-kammerer
5b21444805 Update worker11.kt 2021-07-21 13:36:02 +02:00
Leonid Startsev
ce0a3a57df Instantiation of annotations for JVM IR with the corresponding feature flag
Seperate checker for platforms that do not support this language feature yet

Synthetic implementations of annotations are generated on-demand with proper 
equals, hashCode, and annotationType methods

#KT-47699 Fixed
2021-07-21 10:23:51 +00:00
Leonid Startsev
4bc521249b kotlinx.serialization: Support InheritableSerialInfo 2021-07-21 10:06:12 +00:00
Alexander Dudinsky
8eea749231 Accept android licenses in setUp PureAndroidAndJavaConsumeMppLibIT 2021-07-21 12:33:07 +03:00
Nikolay Krasko
a1a1bda5f3 Drop unused runIdeTask and excludeInAndroidStudio from localDependencies 2021-07-21 11:23:56 +02:00
Nikolay Krasko
6a0b71d3e4 Drop old IDEA run configurations 2021-07-21 11:23:56 +02:00
Nikita Bobko
d1e46e8ce7 Delete Kotlin IntelliJ IDEA plugin modules from settings.gradle 2021-07-21 11:23:53 +02:00
Nikita Bobko
39fa2b0baf Delete Kotlin IntelliJ IDEA plugin sources
Kotlin plugin sources were migrated to intellij-community:
https://github.com/JetBrains/intellij-community/tree/master/plugins/kotlin

Preserve `jps-plugin/testData/incremental`
because it's used in `compiler/incremental-compilation-impl/test`

Preserve `idea/testData/multiModuleHighlighting/multiplatform`
because it's used in `MppHighlightingTestDataWithGradleIT`
2021-07-21 11:23:43 +02:00
Elena Lepilkina
b8d74698f1 [K/N][Docs] Update HACKING.md after repositories merging and adding information about debugging and using CLion 2021-07-21 08:39:10 +00:00
Mads Ager
6436a1686d [JVM_IR] Recursively perform constant lowering.
Otherwise constants in child expressions are not transformed.

^KT-47716 Fixed.
2021-07-21 02:11:41 +02:00
Mads Ager
2877f1cabe [JVM_IR] Fix check for inline class property backing in lowering.
The inline class lowering would attempt to lower a companion object
property backing field.

^KT-47762 Fixed.
2021-07-21 01:56:46 +02:00
Dmitry Petrov
46d2e52543 JVM Minor: move uninitialized value check to stack recovery 2021-07-20 19:51:04 +03:00
Dmitry Petrov
e72d24960d JVM we don't merge frames in stack normalization 2021-07-20 19:51:03 +03:00
Dmitry Petrov
91afa3335c JVM represent uninitialized values explicitly in stack normalization 2021-07-20 19:51:02 +03:00
Dmitry Petrov
bb202318ee Minor: regenerate tests 2021-07-20 19:51:01 +03:00
Dmitry Petrov
35b4a9d4cc JVM treat all variable loads as "initialized" in stack normalization 2021-07-20 19:51:00 +03:00
Dmitry Petrov
c8b705fd2d JVM update license for HackedFixStackMethodAnalyzerBase.kt 2021-07-20 19:50:59 +03:00
Dmitry Petrov
8763235053 JVM specially hacked method analyzer for FixStack 2021-07-20 19:50:58 +03:00
Dmitry Petrov
3ecd612ce7 JVM FixStackValue & FixStackInterpreter 2021-07-20 19:50:57 +03:00
Ilya Chernikov
8eb7e719d3 [minor] fix compiler warnings in scripting modules 2021-07-20 19:42:34 +03:00
Roman Golyshev
59304ba70c FIR IDE: use correct out of block modification tracker
Follow-up to eead868cd2
2021-07-20 19:15:38 +03:00
Roman Golyshev
4e67afcaba FIR IDE: Use write lock in KtFirOverrideInfoProvider implementation
`withFir` takes read lock, but checking visibility or implementation
status actually requires resolving declaration to `STATUS` phase. But
resolve cannot be done in `withFir` function, since resolve requires
write lock, and you cannot take both read and write lock

Now we use `withFirWithPossibleResolveInside`, which takes write lock
and allows to perform resolve in it

This should fix failing `FirOverrideImplementTest` tests
in Kotlin IDE plugin
2021-07-20 19:02:26 +03:00
Roman Golyshev
f3bdadb7d9 FIR IDE: Use correct class symbol in getImplementationStatus
The previous check `if (parentClassSymbol !is FirClassSymbol<*>)`
always succeeded, because `parentClassSymbol` was a declaration,
not a symbol
2021-07-20 19:02:24 +03:00
Abduqodiri Qurbonzoda
b65c477e68 Regex.splitToSequence, CharSequence.splitToSequence(Regex) #KT-23351 2021-07-20 14:09:24 +00:00
Abduqodiri Qurbonzoda
1fee6b191f Fix typo in Sequence.constrainOnce() doc 2021-07-20 14:09:24 +00:00
Mikhael Bogdanov
ff26a471b4 Update diagnostics test affected by ApproximateIntegerLiteralTypesInReceiverPosition and ProhibitSimplificationOfNonTrivialConstBooleanExpressions features 2021-07-20 12:19:57 +00:00
Mikhael Bogdanov
fd605a13d7 Update box tests affected by ApproximateIntegerLiteralTypesInReceiverPosition feature 2021-07-20 11:42:29 +00:00
Andrey Zinovyev
6ef4523555 [FIR] Cache callable names in some composite scopes 2021-07-20 14:25:16 +03:00
Andrey Zinovyev
15be38192b [FIR] Mark implicit types in accessors as fake
To not check their types in deprecation checker
2021-07-20 14:25:14 +03:00
Yahor Berdnikau
caa6b630ab Apply 'kotlin-android' plugin dynamically.
Only apply when one of android plugins are also applied to the project.

If none of AGP plugins are applied and 'kotlin-android' is - exception
 in 'afterEvaluate {..}' will be thrown.

^KT-46626 Fixed
2021-07-20 13:44:45 +03:00
Dmitriy Novozhilov
f3116cb64a Fix NON_EXHAUSTIVE_WHEN_STATEMENT warnings in project code 2021-07-20 13:33:46 +03:00
Dmitriy Novozhilov
a6edd852ff [FIR] Report NON_EXHAUSTIVE_WHEN_STATEMENT/NO_ELSE_IN_WHEN for when's on logical types
^KT-47709 In Progress
2021-07-20 13:33:44 +03:00
Dmitriy Novozhilov
ef635f6a96 [FE 1.0] Report NON_EXHAUSTIVE_WHEN_STATEMENT/NO_ELSE_IN_WHEN for when's on logical types
^KT-47709 In Progress
2021-07-20 13:33:43 +03:00
Dmitriy Novozhilov
85c7f386eb Add Kotlin 1.7 language version 2021-07-20 13:33:41 +03:00
Andrey Zinovyev
4a37de51bb [FIR] Add ANONYMOUS_INITIALIZER_IN_INTERFACE diagnostic 2021-07-20 13:29:00 +03:00
Yahor Berdnikau
304d01127f Fix false positive on Java/Kotlin JVM target validation.
Fix false positive case when java toolchain was set to <JDK1.8. In such
case Java tasks return '8' (or less) for target instead of '1.8'.

^KT-47520 Fixed
2021-07-20 09:25:06 +00:00
nataliya.valtman
f76864260a Log changed files into ES statistic 2021-07-20 11:26:55 +03:00
Dmitriy Novozhilov
9b3b386f0a [FIR IDE] Ignore HMMP compiler test 2021-07-20 10:33:54 +03:00
Dmitriy Novozhilov
749dbf4d44 [FIR] Safe dependency symbol provider in IDE session 2021-07-20 10:33:53 +03:00
Dmitriy Novozhilov
37c096cb10 [FIR] Support creation of IR of common + platform sources in FirAnalyzerFacade 2021-07-20 10:33:52 +03:00
Dmitriy Novozhilov
df11ccf755 [FIR] Fix dependency on jvm descriptors for running fir2ir tests with JPS 2021-07-20 10:33:51 +03:00
Dmitriy Novozhilov
5354e4afe4 [FIR] Ignore some MPP backend tests
FIR doesn't support actual declarations in same module where expect
  declarations lay
2021-07-20 10:33:50 +03:00
Dmitriy Novozhilov
c3060e861f [FIR] Add expect actual checker 2021-07-20 10:33:49 +03:00
Dmitriy Novozhilov
faadb08174 [FIR-IDE] Fix generating conversions for pair with non-trivial converters 2021-07-20 10:33:48 +03:00
Dmitriy Novozhilov
b363d95160 [FIR-IDE] Add conversion for Map type 2021-07-20 10:33:47 +03:00
Dmitriy Novozhilov
3b2df7ade3 [FIR] Inherit expect modifier from outer classes 2021-07-20 10:33:46 +03:00
Dmitriy Novozhilov
18af4155b8 [FIR] Properly infer open modality for functions of expect interfaces 2021-07-20 10:33:45 +03:00
Dmitriy Novozhilov
3991383853 [FIR] Provide compiler light classes from all source modules 2021-07-20 10:33:44 +03:00
Dmitriy Novozhilov
8729421e7a [FIR] Add kind to all FirSessions 2021-07-20 10:33:43 +03:00
Dmitriy Novozhilov
2c1ada131d [FIR] Don't generate implicit primary constructor for expect classes 2021-07-20 10:33:42 +03:00
Dmitriy Novozhilov
b1e47a46cd [FIR] Inherit isExpect flag of members from containing class 2021-07-20 10:33:41 +03:00
Dmitriy Novozhilov
9fd25af1a7 [FIR] Add pretty toString to FirSession and ModuleData 2021-07-20 10:33:40 +03:00
Dmitriy Novozhilov
55775a7beb [FIR] Use proper moduleData in fake override generator 2021-07-20 10:33:38 +03:00
Dmitriy Novozhilov
7f20b83159 [FIR] Use proper moduleData in synthetic properties scope 2021-07-20 10:33:37 +03:00
Dmitriy Novozhilov
7008f02962 [FIR] Create fir classes for java annotations and enums with Final modality 2021-07-20 10:33:34 +03:00
Dmitriy Novozhilov
6e83820f97 Move ExpectActualCompatibility to :compiler:resolution.common 2021-07-20 10:33:33 +03:00
Dmitriy Novozhilov
950db81aa4 [FIR] Split compileModulesUsingFrontendIR to multiple functions 2021-07-20 10:33:32 +03:00
Dmitriy Novozhilov
ec1651df92 [FIR] Store dependencies symbol provider as separate session component 2021-07-20 10:33:31 +03:00
Ilya Matveev
1c5361dacd [K/N] disable throwThroughBridge test for wasm32 2021-07-20 07:19:38 +00:00
Hung Nguyen
ecf6001365 KotlinCompile: Prepare for classpath snapshotting and diffing
This commit prepares necessary components only. The core parts of
classpath snapshotting and diffing will be implemented next.

Bug: KT-45777
Test: Existing IncrementalCompilationClasspathSnapshotJvmMultiProjectIT
      and IncrementalJavaChangeClasspathSnapshotIT
2021-07-20 04:04:43 +03:00
Hung Nguyen
41345b2c50 Pass classpath changes from KotlinCompile task to Kotlin compiler
This commit wires necessary components only. The actual classpath
changes will be provided later.

Bug: KT-45777
Test: Existing IncrementalCompilationClasspathSnapshotJvmMultiProjectIT
      and IncrementalJavaChangeClasspathSnapshotIT
2021-07-20 04:04:43 +03:00
Hung Nguyen
c8b3b6df9c KotlinCompile: Set up artifact transform to take classpath snapshot
This commit sets up the artifact transform only. The actual classpath
snapshotting and computation of classpath changes will be done later.

Bug: KT-45777
Test: Existing IncrementalCompilationClasspathSnapshotJvmMultiProjectIT
      and IncrementalJavaChangeClasspathSnapshotIT
2021-07-20 04:04:43 +03:00
Ilmir Usmanov
5517aa36e1 Minor. Add debugger test
#KT-47749
2021-07-19 22:07:17 +00:00
Ilmir Usmanov
e870a200c4 Merge consequent LVT records
that is, if LVT record starts where previous one ends, merge them.
 #KT-47749 Fixed
2021-07-19 22:07:16 +00:00
Ilmir Usmanov
5ae01c8b2a Do not duplicate $result in LVT
#KT-47749
2021-07-19 22:07:16 +00:00
Ilmir Usmanov
b4d356c5bd Split LVT record for known nulls
Since they are not spilled, the logic for splitting LVT records, that
is applied for spilled variables, was not applied for known nulls.
Fix that by applying the logic to them.
 #KT-47749
2021-07-19 22:07:15 +00:00
Mads Ager
83dddd73b0 Always add a local variable for its live ranges.
There used to be code that extended a previous range instead.
However, that does not work as that extension could have the
local cover code where it does not exists. Since we no longer
extend the range of locals, we should always introduce a new
one even if there was another one for a previous range.
2021-07-19 22:07:14 +00:00
Ilya Muradyan
ae650ef19b Add EPL 1.0 licence text for Eclipse Aether dependencies 2021-07-19 21:31:50 +03:00
Ilya Muradyan
46bbe5b1cb Replace Ivy resolver with Maven resolver in all places 2021-07-19 21:31:49 +03:00
Ilya Muradyan
014765a302 Add dependencies-maven-all artifact 2021-07-19 21:31:48 +03:00
Ilya Muradyan
f7c2adae30 Always use wagon classloader as a plexus class world
In CLI compiler, system classloader doesn't load all classes directly,
so wagons (including HttpWagon) happen to be invisible to
Plexus DI that leads to artifacts download failures.
2021-07-19 21:31:46 +03:00
Alexander Likhachev
b93bd1fe09 [Gradle] Simplify optInAnnotation function name to optIn in DSL
#KT-38111
2021-07-19 19:57:00 +03:00
Dmitry Petrov
e276dec4de JVM don't merge local values in FixStackAnalyzer
We care only about stacks there.
This yields about 10-15% in a pathological case such as KT-41510.
2021-07-19 19:24:57 +03:00
Ilya Kirillov
230fce65e5 LL API: add kt -> fir mapping tests for types 2021-07-19 18:45:44 +03:00
Ilya Kirillov
1423aa2c43 LL API: fix kt -> fir mapping of type inside nullable type 2021-07-19 18:45:43 +03:00
Ilya Kirillov
ddd257adc2 LL API: add test for kt -> fir mapping of qualified calls 2021-07-19 18:45:42 +03:00
Ilya Kirillov
3ae1fe69da LL API: add test for kt -> fir mapping 2021-07-19 18:45:41 +03:00
Ilya Kirillov
b380bcfd99 LL API: add kt -> fir mapping tests for expressions 2021-07-19 18:45:40 +03:00
Ilya Kirillov
0554e2a083 LL API: fix kt -> fir mapping for KtStringTemplateEntryWithExpression 2021-07-19 18:45:38 +03:00
Ilya Kirillov
9d53ad4346 LL API: fix kt -> fir mapping for KtObjectLiteralExpression 2021-07-19 18:45:37 +03:00
Ilya Kirillov
32baac52e6 LL API: add kt -> fir mapping tests for property delegation 2021-07-19 18:45:36 +03:00
Ilya Kirillov
831f05a802 LL API: fix kt -> fir mapping for KtImportList 2021-07-19 18:45:35 +03:00
Ilya Kirillov
c266d3e075 LL API: fix kt -> fir mapping for KtValueArgumentList 2021-07-19 18:45:34 +03:00
Ilya Kirillov
f6a97cdec6 LL API: fix kt -> fir mapping for KtValueArgument 2021-07-19 18:45:32 +03:00
Ilya Kirillov
6139d97b2a LL API: allow getOrBuildFir to return null 2021-07-19 18:45:31 +03:00
Ilya Kirillov
4bca296dc6 LL API: introduce helper function for throwing invalid FirElement exception 2021-07-19 18:45:29 +03:00
Ilya Kirillov
c0eb669191 LL API: add basic tests for kt -> fir mapping 2021-07-19 18:45:28 +03:00
Elena Lepilkina
609296a46b [K/N] Use libclang_rt version for simulator for last Xcode versions (KT-47333 fixed) 2021-07-19 14:12:41 +00:00
Mikhael Bogdanov
03ccbf1b17 Upgrade kotlinx-metadata-jvm and binary-compatibility-validator versions 2021-07-19 13:49:05 +00:00
Ilya Chernikov
0cd29adcc7 Get rid of kotlinx-coroutines usage in scripting libs and plugins
the dependency on the coroutines library caused various problems like
KT-30778, or stdlib/runtime version conflicts.
The only function used was `runBlocking`, so this change replaces it
with the internal implementation based on the similar internal thing
from the stdlib.
#KT-30778 fixed
2021-07-19 16:35:36 +03:00
Alexander Udalov
9b1de90452 Cache async-profiler when using -Xprofile 2021-07-19 15:14:57 +02:00
Igor Chevdar
bea82ba2cd [K/N][stdlib] Added @EagerInitialization annotation
It is needed in the lazy top level properties initialization strategy to
revert to the previous strategy at least for the transition period
2021-07-19 17:23:35 +05:00
Mikhael Bogdanov
4de6fd8be2 Prepare NewMultiplatformIT tests for compiler migration to 1.6 2021-07-19 12:15:26 +00:00
Dmitriy Novozhilov
c304363aea [FE 1.0] Report WRONG_ANNOTATION_TARGET on annotations on type arguments
^KT-47772 Fixed
2021-07-19 14:00:24 +03:00
Andrey Zinovyev
046d886850 [FIR] Fix Nothing returning expressions when checking for not null 2021-07-19 13:40:32 +03:00
Andrey Zinovyev
7e9f27436a [FIR] Fix cfg for safe call inside elvis 2021-07-19 13:40:31 +03:00
Andrey Zinovyev
c160511244 [FIR] Basic support for break inside try-finally blocks
Support single try expression only
2021-07-19 13:40:30 +03:00
Andrey Zinovyev
a6984c5198 [FIR] Add NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY diagnostic 2021-07-19 13:40:28 +03:00
Ilmir Usmanov
151478aa27 Raise deprecations of suspend calls with dangling lambda to error
#KT-22562
2021-07-19 08:36:36 +00:00
Dmitry Petrov
d41fc0b599 PSI2IR fix suspend conversion tests
- support chained suspend conversion + SAM conversion
- support suspend conversion in vararg elements
2021-07-17 09:10:19 +03:00
Victor Petukhov
0cc6fbbc6e Add tests for converting expressions of function types to suspending functional types 2021-07-17 09:10:17 +03:00
Viacheslav Kormushkin
780b9a032b Link CocoaPods frameworks with iosTest binary
#KT-44857 #KT-37513
2021-07-16 19:42:24 +00:00
Mads Ager
b51ff799cb Fix IteratorNext intrinsic to cast its dispatch receiver to
the expected type.

^KT-47741 Fixed.
2021-07-16 21:07:11 +02:00
Ilya Kirillov
f83cc69379 HL API: hacky fix garbage collected diagnostic in call 2021-07-16 21:06:05 +03:00
Ilya Kirillov
d7f1353d3d HL API: update resolve call tests 2021-07-16 21:06:04 +03:00
Ilya Kirillov
44812ae45a HL API: update symbols testdata after adding hasStableParameterNames to function symbol 2021-07-16 21:06:03 +03:00
Mark Punzalan
cb85fd26f5 FIR IDE: Expand KtCall API to include annotation calls and delegated
constructor calls.
2021-07-16 21:06:02 +03:00
Mark Punzalan
d30d8037cf FIR IDE: Add KtFunctionLikeSymbol.hasStableParameterNames. 2021-07-16 21:06:00 +03:00
Mark Punzalan
5c111f8979 FIR IDE: Add argument mapping to KtFunctionCall. 2021-07-16 21:05:59 +03:00
Alexander Likhachev
6fe730a12e [Gradle, JS] Add IT that no tasks configured on help task execution
#KT-47559 Fixed
2021-07-16 20:14:51 +03:00
Alexander Likhachev
0740d11378 [Gradle, JS] Configure run tasks lazily
#KT-47559 In Progress
2021-07-16 20:14:49 +03:00
Victor Petukhov
6a1ec92d39 Introduce specific error for calls which could be resolved only with unrestricted builder inference
^KT-47747 Fixed
2021-07-16 19:32:36 +03:00
Victor Petukhov
357fda2efa Initialize builder inference lambda anyway, even a call is inapplicable
^KT-47744 Fixed
2021-07-16 19:32:35 +03:00
Alexander Likhachev
2b0ba6fa40 [Gradle, MPP] Add test for KT-47611, KT-47612
#KT-47611 Fixed
#KT-47612 Fixed
2021-07-16 18:33:45 +03:00
Alexander Likhachev
8109b66a79 [Gradle, MPP] Make publishing compatible with configuration cache
Capture artifact coordinates more accurately to conform with configuration cache
#KT-47611 In Progress
2021-07-16 18:33:45 +03:00
Alexander Likhachev
77471c0cd8 [Gradle, MPP] Make kotlin tooling metadata task compatible w/ conf cache
The value should be memoized in task, so it can be serialized in a way to not use project in execution time
#KT-47612 In Progress
2021-07-16 18:33:43 +03:00
Mikhael Bogdanov
5f53a2071d Update test affected by ProperTypeInferenceConstraintsProcessing feature 2021-07-16 13:26:37 +00:00
Mikhael Bogdanov
392dce9a40 Update test affected by PrivateInFileEffectiveVisibility feature 2021-07-16 13:26:36 +00:00
Mikhael Bogdanov
c519003e13 Update test affected by ProhibitSimplificationOfNonTrivialConstBooleanExpressions feature 2021-07-16 13:26:36 +00:00
Mikhael Bogdanov
a657e63dbb Update test affected by ForbidUsingExtensionPropertyTypeParameterInDelegate feature 2021-07-16 13:26:35 +00:00
Mikhael Bogdanov
70df4f10c5 Update test affected by AbstractClassMemberNotImplementedWithIntermediateAbstractClass feature 2021-07-16 13:26:34 +00:00
Mikhael Bogdanov
f05d470f6a Update test affected by 'ProhibitJvmFieldOnOverrideFromInterfaceInPrimaryConstructor' feature 2021-07-16 13:26:33 +00:00
pyos
f5dd5ead1f JVM: produce a better error on @JvmStatic external in interface
Java does not permit `static native` methods in interfaces, so this
never worked on any existing JRE.

 #KT-43696 Fixed
2021-07-16 15:24:09 +02:00
pyos
ad7ed483f3 JVM_IR: copy correspondingProperty of static external functions
Required for correctly mapping their names.

 #KT-47715 Fixed
2021-07-16 15:24:05 +02:00
Ilya Goncharov
adeb2f527b [Gradle, JS] Fail incremental test if there is source maps warning
^KT-47751 fixed
2021-07-16 15:39:52 +03:00
Ilya Goncharov
f73726c330 [Gradle, JS] Ignore source maps arguments in cache building
^KT-47751 fixed
2021-07-16 15:39:50 +03:00
Yahor Berdnikau
d82681889b Ignore empty directories on input properties hash calculation.
Annotate all '@InputFiles' and '@InputDirectory' input properties
with '@IgnoreEmptyDirectories' annotation, so empty directories
will be excluded from input hash calculation.

^KT-27687 Fixed
2021-07-16 12:35:15 +00:00
Dmitriy Novozhilov
22f57220c1 [FE 1.0] Report INTEGER_OPERATOR_RESOLVE_WILL_CHANGE on rhs of assign
^KT-47729 Fixed
2021-07-16 15:18:46 +03:00
Dmitriy Novozhilov
afb7625d0c [FE 1.0] Fix false positive INTEGER_OPERATOR_RESOLVE_WILL_CHANGE
^KT-47729 In progress
2021-07-16 15:18:44 +03:00
Dmitriy Novozhilov
2fb5f776d8 [FE 1.0] Report INTEGER_OPERATOR_RESOLVE_WILL_CHANGE on calls in parenthesis
^KT-47729 In progress
2021-07-16 15:18:38 +03:00
Victor Petukhov
ea4ab46765 Report implicit inferred Nothing only for own type parameters and in delegation resolve
^KT-47724 Fixed
2021-07-16 11:21:51 +03:00
Alexander Likhachev
7bb4612149 [Gradle] Add IT that useExperimentalAnnotation produces deprecation warn
#KT-38111 Fixed
2021-07-16 11:01:15 +03:00
Alexander Likhachev
68ced78d89 [Gradle] Rename experimental annotations to opt-in in test data
#KT-38111 In Progress
2021-07-16 11:01:14 +03:00
Alexander Likhachev
fa68dbc736 [Gradle] Rename experimental annotations to opt-in annotations in DSL
Methods and accessors with old names are preserved in public API and marked as deprecated now
#KT-38111 In Progress
2021-07-16 11:01:12 +03:00
Aleksei.Cherepanov
d9701d57bb Fix JPS tests after 2d65383a 2021-07-16 05:35:05 +03:00
Ilya Chernikov
c83614386e [minor] FIR: (temporarily) fix testdata due to different builtins behavior 2021-07-16 02:24:45 +03:00
Ilya Chernikov
02bf745eef IR: Remove some unused IrBuiltIns methods 2021-07-16 02:24:44 +03:00
Ilya Chernikov
51dc829aae IR: Move unsigned classes loading from builtins back to symbols
see #KT-47540 for the motivation
2021-07-16 02:24:43 +03:00
Ilya Chernikov
808f5148f3 IR: implemented generic knownBuiltIns property 2021-07-16 02:24:42 +03:00
Ilya Chernikov
a7d494480c [minor] FIR: minor fixes in FIR-based IrBuiltIns 2021-07-16 02:24:41 +03:00
Ilya Chernikov
56805dded8 [minor] IR: minor builtins infrastructure fixes 2021-07-16 02:24:40 +03:00
Ilya Chernikov
19f52d9aae [minor] FIR: fix irbuiltins implementation after rebase 2021-07-16 02:24:38 +03:00
Ilya Chernikov
873a7c6ef1 FIR: Implement delayed binding of overriddens in the delegated members
fixes the problem when overridden symbols on delegated members were
build on the incomplete fake overrides leading to the incorrect
generation of the function for default parameter and thus to the
codegen error (see withDefaultsMultipleFilesOrder test for an example)
2021-07-16 02:24:37 +03:00
Ilya Chernikov
c9b6847d83 FIR: Add test on delegated member with default param in overridden...
sensitive to the file processing order, therefore failing on the
current fir2ir at least with the new irBuiltIns
2021-07-16 02:24:36 +03:00
Ilya Chernikov
a2385b5edd [minor] FIR: Fix Fir2ir jvmmappedscope functions origins 2021-07-16 02:24:35 +03:00
Ilya Chernikov
6001a81a30 [minor] FIR: Fix IR builtins modality 2021-07-16 02:24:34 +03:00
Ilya Chernikov
5b2acea98f FIR: Add analysis flag for loading IR builtins from sources 2021-07-16 02:24:32 +03:00
Ilya Chernikov
c2c02ddb27 FIR: refactoring IrBuiltIns initialization logic...
to allow to try to load them from dependencies first
and to intialize fake overrides properly
2021-07-16 02:24:31 +03:00
Ilya Chernikov
9de27bc4d8 FIR: Avoid "Mutating Fir2Ir lazy elements" error
for classes came from sources
2021-07-16 02:24:30 +03:00
Ilya Chernikov
8f5d5c3ace FIR: Fixes in testdata after implementing FIR-specific IrBuiltIns 2021-07-16 02:24:29 +03:00
Ilya Chernikov
01f26ec699 FIR: Switch to FIR-based IrBuiltIns in FIR compilation
get rid of using old FE for builtins on FIR compilation
2021-07-16 02:24:28 +03:00
Ilya Chernikov
3b20ec46ef FIR: Set correct modality to default accessors on deserialization
fixes some tests with new IrBuiltIns
2021-07-16 02:24:27 +03:00
Ilya Chernikov
5b677c068f FIR: Refactor JvmMappedScope to fix container-related tests with new builtins 2021-07-16 02:24:25 +03:00
Ilya Chernikov
80a710a5c5 FIR: implementing IrBuiltIns over FIR 2021-07-16 02:24:24 +03:00
Ilya Chernikov
cb4999f23c Native: port native to the new IrBuiltIns 2021-07-16 02:24:22 +03:00
Ilya Chernikov
48a3c64901 IR: Refactor primitive arrays handling in the new IrBuiltIns
for better compatibility e.g. with native
2021-07-16 02:24:20 +03:00
Ilya Chernikov
3b2bb2ba9f IR: Fix error rendering on IR symbol binding conflict
it could be called with uninitialized `owner` parameter, leading
to the NPE on render
2021-07-16 02:24:19 +03:00
Ilya Chernikov
dee0487185 IR: Refactor IrBuiltIns to abstract it from descriptors 2021-07-16 02:24:18 +03:00
Nikolay Lunyak
25d2e61a82 [FIR2IR] Adding 2 new runners for fir2ir-specific tests 2021-07-15 23:15:39 +03:00
Alexander Likhachev
a6e477fa88 [Build] Add dependency verification data for jna 2021-07-15 20:41:59 +03:00
Alexander Likhachev
1a77b57a7b [Gradle] Provide JNA jar to compiler classpath with intellij-core 203+
#KT-47748 Fixed
2021-07-15 20:41:57 +03:00
Yahor Berdnikau
da1d49e622 Add new ways to set Kotlin daemon JVM arguments.
Additionally to inheriting Gradle daemon arguments or configuring via
 Gradle daemon arguments system property, it is also possible now
 to configure arguments either using "kotlin.daemon.jvmargs" property
 or extension DSL.

Extension DSL overrides special gradle property arguments, which
overrides Gradle daemon arguments.

^KT-45747 Fixed
2021-07-15 17:27:38 +00:00
Dmitry Petrov
b98322c1b4 JVM don't optimize methods with too many TCBs 2021-07-15 20:18:18 +03:00
Dmitry Petrov
d65d66c03a JVM reserve 2 slots for node predecessors/successors in CFG 2021-07-15 20:18:15 +03:00
Dmitry Petrov
6c2d93bb8b JVM traverse nodes in reverse order in 'findSafelyReachableReturns' 2021-07-15 20:18:13 +03:00
Mikhael Bogdanov
f080dbb78c Update resolveAnnotations tests in new infrastructure 2021-07-15 17:08:17 +00:00
Mikhael Bogdanov
671ef7dfff Regenerate tests 2021-07-15 17:08:16 +00:00
Mikhael Bogdanov
3aeb9291fe Move resolveAnnotations tests into diagnostics tests 2021-07-15 17:08:16 +00:00
Jinseong Jeon
9ec4d19a3f FIR IDE: avoid finding symbol for function type parameter 2021-07-15 18:29:33 +02:00
Jinseong Jeon
2e502bd01e FIR IDE: fix anonymous function symbol retrieval from function literal 2021-07-15 18:29:32 +02:00
Dmitry Petrov
8ea4916d64 JVM_IR KT-47739 recognize fake override external stubs 2021-07-15 19:20:39 +03:00
Ivan Kochurkin
dd54338ec0 [FIR] Fix positioning and detecting of WRONG_NUMBER_OF_TYPE_ARGUMENTS
Refactor code and fix compilation errors caused by changes to symbol.fir
2021-07-15 19:02:58 +03:00
Ivan Kochurkin
345152d198 [FIR] Add containingDeclarationSymbol to FirTypeParameter 2021-07-15 19:02:56 +03:00
Ivan Kochurkin
0c25d280ee [FIR] Fix calculating of source of TypeArgumentList, add source to FirQualifierPart
Fix positioning for TYPE_ARGUMENTS_NOT_ALLOWED
2021-07-15 19:02:54 +03:00
Ivan Kochurkin
28a6928873 [FIR] Check rest OUTER_CLASS_ARGUMENTS_REQUIRED diagnostics on checkers stage
Add FirOuterClassArgumentsRequiredChecker
2021-07-15 19:02:45 +03:00
Ivan Kochurkin
0fc8be4d60 [FIR] Implement OUTER_CLASS_ARGUMENTS_REQUIRED diagnostics 2021-07-15 19:02:40 +03:00
Yahor Berdnikau
f7ed2f813d Exclude Gradle Kotlin runtime dependencies from 'no-arg' plugin.
This should remove warnings on multiple versions in build classpath
runtime.

^KT-47635 Fixed
2021-07-15 15:27:56 +00:00
Yahor Berdnikau
8db1c52c09 Exclude Gradle Kotlin runtime from 'sam-with-receiver' plugin.
This should remove warnings on multiple dependencies versions
in the build classpath runtime.

^KT-47636 Fixed
2021-07-15 15:27:24 +00:00
Mikhail Glukhikh
40c3c317b2 RawFirBuilder: optimize package name calculation in compiler mode 2021-07-15 12:46:23 +00:00
Ilya Goncharov
dcc54101a7 [Gradle, JS] Add test with icremental JS Ir in parallel build 2021-07-15 11:42:48 +00:00
Svyatoslav Kuzmich
a468792a19 [Wasm] Support Milestone 3 of V8 Wasm GC
Advance V8 version to 9.2.212

Relevant Wasm GC changes:
f9f8ffa445
2021-07-15 10:59:06 +00:00
sebastian.sellmair
9500b2d36e [Commonizer] Add HierarchicalCInteropCallableAnnotationCommonizationTest.test single platform not marked as objc 2021-07-15 10:04:45 +00:00
sebastian.sellmair
17ed498390 [Commonizer] approximationKeys: Fix closing ] for type parameter types' upper bounds 2021-07-15 10:04:45 +00:00
sebastian.sellmair
daa046589e [Commonizer] approximationKeys: Minor cleanup of buildApproximationSignature 2021-07-15 10:04:44 +00:00
sebastian.sellmair
2c8ce2539b [Commonizer] HierarchicalPropertyCommonizationTest: Add test property with and without setter 2021-07-15 10:04:43 +00:00
sebastian.sellmair
8bab6c3076 [Commonizer] Commonize 'val' and 'var' properties
If a setter is not present on all platforms a fallback private setter
shall be emitted.

^KT-47502 Verification Pending
^KT-47691 Verification Pending
2021-07-15 10:04:43 +00:00
sebastian.sellmair
c4d90dc744 [Commonizer] Implement alis type substitution as CirNodeTransformer
This has the advantage, that the substitution only has to run on
functions or properties that are 'incomplete' (missing at least
one other target declaration)

^KT-47433 Verification Pending
2021-07-15 10:04:42 +00:00
sebastian.sellmair
7c450f9884 [Commonizer] Implement CirAliasTypeSubstitutor
This will substitute non-commonizable classifiers with known
type-aliases (which might be commonizable).

A simple example depending on this substitution comes from posix:
Most function and properties use the `FILE` typealias which
is available across all platforms.

Some linux platforms use `__IO_FILE` in their signature, which
is just linux specific. This type substitution will figure out, that
this type can be substituted with `FILE`.

^KT-47433 Verification Pending
2021-07-15 10:04:41 +00:00
sebastian.sellmair
906346b7d9 [Commonizer] Drop CirProperty interface for plain data class 2021-07-15 10:04:41 +00:00
sebastian.sellmair
f0feca286e [Commonizer] Drop CirExtensionReceiver interface for plain data class 2021-07-15 10:04:40 +00:00
sebastian.sellmair
fdee49ee59 [Commonizer] Drop CirTypeParameter interface for plain data class 2021-07-15 10:04:39 +00:00
sebastian.sellmair
4a4516731a [Commonizer] Drop CirValueParameter interface for plain class 2021-07-15 10:04:39 +00:00
sebastian.sellmair
e246a12cd3 [Commonizer] Drop CirFunction interface for plain data class 2021-07-15 10:04:38 +00:00
sebastian.sellmair
0c32abed02 [Commonizer] Remove now unnecessary ArtificialCirDeclaration
This marker interface is not necessary anymore, since no new actuals
will be generated by the Commonizer. It was used to filter declarations
during the serializ
2021-07-15 10:04:37 +00:00
sebastian.sellmair
e041532dd2 [Commonizer] InlineSourceBuilder: Also mark ModuleBuilder functions with InlineSourcesCommonizationTestDsl 2021-07-15 10:04:37 +00:00
sebastian.sellmair
87ac436a35 [Commonizer] Implement HierarchicalCInteropCallableAnnotationCommonizationTest 2021-07-15 10:04:36 +00:00
sebastian.sellmair
8acfeb3e17 [Commonizer] Remove computing signatures from metadata 2021-07-15 10:04:36 +00:00
sebastian.sellmair
f3ff9814a8 [Commonizer] Create approximation keys based on Cir instead of metadata 2021-07-15 10:04:35 +00:00
sebastian.sellmair
09f9a1ce5b [Commonizer] Share Test: Commonizer / Light run configuration
This run configuration can be used to run only light weight/faster tests
2021-07-15 10:04:34 +00:00
Andrey Kuleshov
26a71af6b3 [Native, All platforms] HotFix of the incorrect parsing of long strings to Float and Double (#4492)
### What's done:
- Fixed incorrect logic of String.toFloat() and String.toDouble().
  Long string without any digits were treated as Float or Double:
  "this string does not look as float isn't it?".toFloat() == "Infinity".

- Fixed incorrect parsing of floating point constants "NaN" and "Infinity":
  String values like "NaNPICEZy" or "InfinityN" were treated as valid numbers.

- Merged parsing logic for Double and Float:
  Removed the code duplication, unified methods, made the code more Kotlin-like, not C++-like.

- Updated tests:
  Removed useless tests that checked nothing, updated tests with regression scenarios.
2021-07-15 14:47:55 +07:00
Sergey Bogolepov
118889add5 [K/N] Fix mingw_x86 compilation
It was broken in 9ed97a27f1.
2021-07-15 04:55:36 +00:00
Roman Artemev
447900c3f2 [K/N] Make sure all module names are uniq
In case of klib -> binary compilation there were two different modules
with the same. It breaks invariant about uniqueness if module name.
2021-07-15 03:09:46 +03:00
Georgy Bronnikov
ba61700be6 Regenerate tests 2021-07-14 21:20:49 +03:00
Georgy Bronnikov
4af2aaedb1 IR, temporary: a simpler mangling for flexible types
Mangling for flexible types will need another look.
Complicated cases still do not work.
2021-07-14 21:20:48 +03:00
Georgy Bronnikov
c3f4fcde0b JVM_IR: compute signatures for fake overrides of Java fields 2021-07-14 21:20:47 +03:00
Georgy Bronnikov
8c3386b607 IR: set file in declarationTable when serializing IR 2021-07-14 21:20:46 +03:00
Georgy Bronnikov
05a42b8cd5 IR: handle CompositeSignature in DescriptorByIdSignatureFinder 2021-07-14 21:20:45 +03:00
Georgy Bronnikov
da946e464f Fix compilation after rebase: add debugInfo to JvmIr.proto 2021-07-14 21:20:43 +03:00
Georgy Bronnikov
f4d358069c Fixes after rebase, not related to IrLibraryFile 2021-07-14 21:20:42 +03:00
Georgy Bronnikov
08b950fc2a JVM_IR: Supply fake file name to signatures of file local declarations 2021-07-14 21:20:41 +03:00
Georgy Bronnikov
225705a237 IR: do not serialize nonlocal initializers in inline-only mode 2021-07-14 21:20:40 +03:00
Georgy Bronnikov
28bff2ba4f JVM_IR: add test for calling monitorEnter/Exit from serialized code. 2021-07-14 21:20:38 +03:00
Georgy Bronnikov
dffb22de9d JVM_IR: avoid duplication in declaration lists during deserialization 2021-07-14 21:20:36 +03:00
Georgy Bronnikov
fa4efd3303 JVM_IR: fix deserialization of Java static field symbols 2021-07-14 21:20:35 +03:00
Georgy Bronnikov
955ee07517 IR: compute signature for scripts 2021-07-14 21:20:33 +03:00
Georgy Bronnikov
9d0c6fb157 IR: remove an overly optimistic assert 2021-07-14 21:20:32 +03:00
Georgy Bronnikov
c3a94e1e62 FIR: adapt to changes in IR interface
JvmGeneratorExtensionsImpl, JvmIrCodegenFactory need new arguments.
2021-07-14 21:20:31 +03:00
Georgy Bronnikov
20b76d4149 JVM_IR: reorganize initialization of JvmGeneratorExtensionsImpl
CachedFields are now created at initialization.
Therefore we need CompilerConfiguration as a constructor parameter.
2021-07-14 21:20:30 +03:00
Georgy Bronnikov
7bbc04b6a2 JVM_IR: reconstruct fake overrides after IR deserialization.
We need to keep track of local signatures for deserialized symbols.
2021-07-14 21:20:29 +03:00
Georgy Bronnikov
a63cc95a2a JVM_IR: untangle backend.jvm and serialization.jvm (again) 2021-07-14 21:20:28 +03:00
Georgy Bronnikov
1c4466951f IR: a flag to GeneratorExtensions to control IR deserialization
There is no need to search for IR embedded in toplevel classes when none
is expected (in npon-JVM backends or when -Xserialize-ir is not set).
2021-07-14 21:20:27 +03:00
Georgy Bronnikov
ec1c97c684 JVM_IR: register builtin annotation constructors in SymbolTable
When deserializing IR, these annotations need to be visible.
2021-07-14 21:20:26 +03:00
Georgy Bronnikov
8d15a1d13d JVM_IR: use signatures in AbstractIrSerializeCompileKotlinAgainstInlineKotlinTest
Using signatures allows us to identify calls from a new module to an old
one.
2021-07-14 21:20:24 +03:00
Georgy Bronnikov
49619cda48 Restore Native compilation 2021-07-14 21:20:23 +03:00
Georgy Bronnikov
931733f8cc JVM_IR: deal with JvmStatic in imported IR 2021-07-14 21:20:22 +03:00
Georgy Bronnikov
96ce124268 JVM_IR: serialize fake overrides in IR 2021-07-14 21:20:21 +03:00
Georgy Bronnikov
2d3a558d50 JVM_IR: normalize visibility before serializing 2021-07-14 21:20:20 +03:00
Georgy Bronnikov
a328ebc889 JVM_IR: extract cached fields into a separate class 2021-07-14 21:20:18 +03:00
Georgy Bronnikov
50068607b9 JVM_IR: call serializeIr from a phase
This circumvents the need to run expect/actual resolution on
deserialized IR.
2021-07-14 21:20:17 +03:00
Georgy Bronnikov
0d5fe0b029 JVM_IR: load serialized data for every affected property of IrLazyFunction 2021-07-14 21:20:16 +03:00
Georgy Bronnikov
f4e6eb00fd JVM_IR: generate unbound symbols after deserializing IR 2021-07-14 21:20:15 +03:00
Georgy Bronnikov
6b80c00cc6 JVM_IR: deserialize lazy declarations 2021-07-14 21:20:14 +03:00
Georgy Bronnikov
ad8892f71f JVM_IR: test that inline functions have deserialized bodies 2021-07-14 21:20:12 +03:00
Georgy Bronnikov
7b52a8c07d JVM_IR: deal with facade classes when computing signature 2021-07-14 21:20:11 +03:00
Georgy Bronnikov
97d3eda23c JVM_IR: run Kotlin against Kotlin tests with serialization 2021-07-14 21:20:10 +03:00
Georgy Bronnikov
ab3d6490ed JVM_IR: save auxTables as byte strings 2021-07-14 21:20:09 +03:00
Georgy Bronnikov
7dbdb311e1 JVM_IR: read serialized IR from annotation 2021-07-14 21:20:08 +03:00
Georgy Bronnikov
baaecaa052 JVM_IR: write serialized IR to an annotation 2021-07-14 21:20:06 +03:00
Georgy Bronnikov
b177779b66 IR: compute signatures for fields 2021-07-14 21:20:05 +03:00
Georgy Bronnikov
b2617199bc JVM_IR: call serialization for IR.
Serializer for IR is called when -Xserialize-ir flag is set.
2021-07-14 21:20:04 +03:00
Georgy Bronnikov
9efd0d7589 JVM_IR: JvmIrSerializer 2021-07-14 21:20:02 +03:00
Mikhail Glukhikh
113d2653aa Drop deprecated -Xexperimental flag from compiler and tests 2021-07-14 21:18:23 +03:00
anastasiia.spaseeva
cbcec8d624 Add changelog for 1.5.21 2021-07-14 19:37:14 +03:00
Margarita Bobova
ed3326fd83 Add changelog for 1.5.20 2021-07-14 19:37:12 +03:00
Nikita Bobko
bf6718e0a5 Fix compilation in kotlin-ide 2021-07-14 17:17:19 +02:00
Ilya Goncharov
047041dc6e [Gradle, JS] Await worker which builds cache 2021-07-14 14:46:04 +00:00
Pavel Kunyavskiy
92789984e0 [K/N] Make SafeContinuation thread-safe 2021-07-14 09:03:31 +00:00
pyos
07cb3a5ff8 JVM: do not reify methods of objects in lambdas
All type parameters used in them are not from the inline function
anyway.
2021-07-14 10:11:05 +02:00
pyos
717cf2066a JVM: remove more redundant properties from LambdaInfo 2021-07-14 10:11:05 +02:00
pyos
c1c56ca388 JVM: refactor extraction of default inline lambdas a bit more 2021-07-14 10:11:05 +02:00
pyos
91cf1a1a4d JVM: remove a redundant DefaultLambda field
and add a comment explaining one branch of the inliner... Better than
nothing, I guess?
2021-07-14 10:11:05 +02:00
pyos
100d2d629c JVM: inline default lambda coercions from bridge invoke
The type of the default lambda may be a subtype of the parameter type,
so we can't really generate our own coercions at all as we don't know
the precise Kotlin type of the `invoke` method.
2021-07-14 10:11:05 +02:00
pyos
d0b9c4ae6b JVM: generalize getMethodNode
to allow matching by arbitrary predicates.
2021-07-14 10:11:05 +02:00
Alexander Likhachev
f986591ba9 [Build] Suppress ivy url senseless comparison warning
It's marked as not null in Gradle, but it's still possible to declare Ivy repository with null url which leads to GeneralKotlin2JsGradlePluginIT#testJsBothModeWithTests test false fail (cache redirector script is used in Gradle integration tests)
2021-07-14 10:59:14 +03:00
Ilya Matveev
922aad6865 [K/N] Add exp10 and exp10f to good function list for call checker
Clang may replace a call to `pow (10.0, x)` with a call to `exp10(x)`
(or `__exp10` on MacOS).

We use this function in float parsing logic, so this function should
be added to the good function list.
2021-07-14 04:49:04 +00:00
Nikolay Krasko
0f2e653625 Use cache-redirector for yarn download (KTI-577) 2021-07-13 22:36:51 +03:00
Nikolay Krasko
ec04af9eea Update cache redirector list 2021-07-13 22:36:50 +03:00
Dmitry Petrov
dc16d66fb1 Minor: regenerate tests 2021-07-13 21:23:17 +03:00
pyos
3dc7b6c3ee IR: preserve argument evaluation order more carefully
1. receivers should be evaluated before named arguments;
 2. just because an argument has no side effects doesn't mean it is not
    affected by the other arguments' side effects - in that case it
    should still be evaluated in source order.

 #KT-47660 Fixed
2021-07-13 21:23:15 +03:00
Roman Artemev
b5942204dc [KLIB] Enable accidentally disabled IC for klibs in K/JS 2021-07-13 18:58:57 +03:00
Roman Artemev
ece9307471 [JS IR] Fix destination directory in Incremental compiler runner for JS 2021-07-13 18:58:56 +03:00
Aleksei.Cherepanov
d2881a7920 Improve performance of Lookup storage
Reduce size of lookup map after rebuild, reduce waiting time by replacing operations of read+write with append, also split remove garbage process into smaller operations in get

#KT-46804 Fixed
2021-07-13 18:39:38 +03:00
Alexander Udalov
35f6337de3 Remove obsolete kotlin.build.useIR flag
(cherry picked from commit 91e47f1fd7)
2021-07-13 14:01:19 +02:00
Elena Lepilkina
c401cf961d [K/N][C interop] Support Kotlin special names processing (KT-47209 fixed) 2021-07-13 11:56:31 +00:00
Roman Artemev
0326518fc9 [KLIB] Cutting down usages of moduleDescriptor in linker
Replace map key `ModuleDescriptor` with `String` which is module name
2021-07-13 14:43:42 +03:00
Roman Artemev
eadf252de9 [KLIB] Provide KotlinLibrary for Konan Interop Deserializer 2021-07-13 14:43:41 +03:00
Roman Artemev
0a49b24320 [JS IR] Move klib resolution from cli into compiler
Simplify CLI -> Compiler API
Clean up code
2021-07-13 14:43:40 +03:00
Roman Artemev
103e4ef2a5 [JS IR] Disable ts export check in PIR mode in box tests
Since that feature is not declared as working yet
2021-07-13 14:43:38 +03:00
Elena Lepilkina
025e572462 [K/N] Fixed case with parameter which can be optimized with BCE 2021-07-13 09:22:13 +00:00
Elena Lepilkina
2477ea80c6 Reverted loops order processing in ForLoopsLowering 2021-07-13 09:22:12 +00:00
Elena Lepilkina
c096e6a3eb [K/N] Analyze vals in bounds check elimination 2021-07-13 09:22:11 +00:00
Elena Lepilkina
9503627864 Changed an order of processing loops in ForLoopsLowering 2021-07-13 09:22:11 +00:00
Elena Lepilkina
0e04c21625 [K/N] Bounds check elimination in basic for loops forms 2021-07-13 09:22:10 +00:00
Elena Lepilkina
7975311ca2 [K/N] Added tests for bounds checks 2021-07-13 09:22:09 +00:00
Elena Lepilkina
ac074207c7 [K/N] ForLoopsLowering: Use get without bounds check in ArrayIterationHandler 2021-07-13 09:22:08 +00:00
Dmitriy Novozhilov
f33f3c769f Fix USELESS_IS_CHECK warnings in compiler code 2021-07-13 10:35:05 +03:00
Dmitriy Novozhilov
968f823b72 [JVM IR]Fix detecting annotation retention 2021-07-13 10:35:04 +03:00
Dmitriy Novozhilov
47b0071560 [FE 1.0] Properly handle intersection types in check if cast possible or not
^KT-47685 Fixed
2021-07-13 10:35:03 +03:00
Dmitriy Novozhilov
f0c4d06fc9 [FE 1.0] Cleanup PatternMatchingTypingVisitor.kt 2021-07-13 10:35:02 +03:00
Dmitriy Novozhilov
7b5a5f5682 [FE 1.0] Report USELESS_IS_CHECK if is expression is always false
^KT-47684 Fixed
2021-07-13 10:35:01 +03:00
Dmitriy Novozhilov
785e2f862c [PSI] Ignore when failed to get file text
This is change from 36ff952 which was forgotten when applying 203 bunch
2021-07-13 10:34:59 +03:00
Dmitriy Novozhilov
daa4c708a2 [FIR] Remove unused parameter from ensureResolvedForCalls 2021-07-13 10:31:36 +03:00
Dmitriy Novozhilov
c3b20c9ccb [FIR IDE] Add forgotten space to renderer in diagnostic generator 2021-07-13 10:31:34 +03:00
Dmitriy Novozhilov
22a4da024b [FIR] Fix all illegal usages of symbol.fir in checkers module 2021-07-13 10:31:34 +03:00
Dmitriy Novozhilov
e94d75d433 [FIR] Add opt-in annotation which prevents from using symbol.fir 2021-07-13 10:31:32 +03:00
Dmitriy Novozhilov
c99a02796f [FIR] Replace getContainingClass usages with getContainingClassSymbol 2021-07-13 10:31:31 +03:00
Dmitriy Novozhilov
48a25e2fe6 [FIR] Add some status utils over symbols to addition to utils over fir 2021-07-13 10:31:30 +03:00
Dmitriy Novozhilov
b2c6dd8d53 Convert ClassKind.java to Kotlin 2021-07-13 10:31:29 +03:00
Dmitriy Novozhilov
0062f1ba27 Rename ClassKind.java to ClassKind.kt 2021-07-13 10:31:28 +03:00
Dmitriy Novozhilov
22938522b3 [FIR] Add forgotten updating phase of value parameters 2021-07-13 10:31:27 +03:00
Dmitriy Novozhilov
d3966e8844 [FIR] Add accessors to parts of signatures to symbols 2021-07-13 10:31:26 +03:00
Dmitriy Novozhilov
0f06ab537f [FIR] Remove useSiteSession parameter from ensureResolved 2021-07-13 10:31:25 +03:00
Dmitriy Novozhilov
92cfaf68bb [FIR] Remove unused FirFunctionSymbol.parameters 2021-07-13 10:31:24 +03:00
Dmitriy Novozhilov
4deb935f76 [FIR] Mark value classes as inline in raw fir building 2021-07-13 10:31:23 +03:00
Dmitriy Novozhilov
8df56af068 [FIR] Add forgotten settings of resolve phase 2021-07-13 10:31:22 +03:00
Dmitriy Novozhilov
9f161f16b3 [FIR] Move FirPhaseManager to :compiler:fir:tree 2021-07-13 10:31:21 +03:00
Dmitriy Novozhilov
51fc2e453f [FIR] Unity FirCallableDeclaration and FirCallableMemberDeclaration
After removal of all diamonds in FirDeclaration hierarchy
  FirCallableMemberDeclaration was only one inheritor of
  FirCallableDeclaration, so there is no need to keep them both
2021-07-13 10:31:20 +03:00
Dmitriy Novozhilov
adc45fd3dd [FIR] Remove useless generic parameter from deprecation utils 2021-07-13 10:31:18 +03:00
Dmitriy Novozhilov
c50fe4e399 [FIR] Move some components implementations from :entrypoint to appropriate modules 2021-07-13 10:31:17 +03:00
Alexander Udalov
173e194dac Remove dependency on JVM specifics in serialization.common
Move handling of EnhancedNullability to JVM subclasses in
serialization.jvm. Looks like this was possible because of accidental
dependency of frontend on compiler.common.jvm introduced in 564d382b9d.

Also fix a minor typo in the file name typeEnhancementUtils.kt.
2021-07-13 01:54:41 +02:00
Alexander Udalov
7a42f603f2 JVM IR: rename mangler implementation classes 2021-07-13 01:54:41 +02:00
Alexander Udalov
1e16c7d8d4 Minor, update kotlinx-metadata-jvm changelog
According to changes in 1e7295c6.
2021-07-12 22:40:02 +02:00
pyos
d988853c11 JVM_IR: optimize out redundant delegated property receiver fields
Now this:

    class C {
        val x = something
        val y by x::property
    }

is *exactly* the same as this:

    class C {
        val x = something
        val y get() = x.property
    }

(plus a `getY$delegate` method)
2021-07-12 22:38:45 +02:00
pyos
2fe7cf27ad kotlinp: use JVM_IR backend for compiling tests
Also, test optimized delegated properties.
2021-07-12 22:38:45 +02:00
pyos
791fa411d8 JVM_IR: write correct lambda invoke() signature in metadata 2021-07-12 22:38:45 +02:00
pyos
a7c13db575 JVM_IR: add $delegate methods to a few exclusion lists
1. they don't need type annotations;
 2. internal ones include the module name before the `$delegate` part,
    so further mangling is redundant
 3. they don't need multifile facade bridges.

Unlike `$annotations`, delegated properties don't appear in interfaces,
so exclusions in InterfaceLowering would be redundant.
2021-07-12 22:38:45 +02:00
pyos
6897e89bbc JVM: add tests for optimized getDelegate 2021-07-12 22:38:45 +02:00
pyos
debd58d377 JVM: use $delegate methods in KProperty[0-2].getDelegate
#KT-39055 Fixed
2021-07-12 22:38:44 +02:00
pyos
1e7295c64e JVM: add $delegate method support to kotlinx-metadata
and kotlinp as well -- it is now possible to see the effect of the
previous commit.
2021-07-12 22:38:44 +02:00
pyos
5d0102a966 JVM_IR: generate $delegate methods for val x by ::y 2021-07-12 22:38:44 +02:00
pyos
7ae4303e1b JVM_IR: slightly refactor JvmPropertiesLowering
to make it easier to generate different kinds of synthetic methods.

 #KT-47609 Fixed
2021-07-12 22:38:44 +02:00
pyos
a943cdadef JVM_IR: support generation of bound reflected property references
Not currently used though, since only references for delegated
properties' accessors are reflected, and those are unbound.
2021-07-12 22:38:43 +02:00
pyos
664bb055c8 JVM_IR: support codegen of property delegate methods
The purpose of a property-related method is now determined by its
origin; codegen no longer assumes all methods with Property metadata
source are `getX$annotations`.
2021-07-12 22:38:43 +02:00
pyos
6a3c79bb9e JVM: support on-the-fly generation of property delegates in metadata
Optimizations may remove the `x$delegate` field, in which case there
should be a `getX$delegate` method to reconstruct the value if needed
due to a call to `KProperty{0,1,2}.getDelegate`. We need to know the
signature of this method somehow.
2021-07-12 22:38:43 +02:00
pyos
e49410e07b JVM_IR: optimize delegation by property references
E.g. a statement like

    var x by ::y

is semantically equivalent to

    var x
      get() = y
      set(value) { y = value }

and thus does not need a full property reference object, or even a field
if the receiver is not bound.

 #KT-39054 Fixed
 #KT-47102 Fixed
2021-07-12 22:38:43 +02:00
Ivan Kochurkin
66e052b9b3 [FIR] Implement SPREAD_OF_NULLABLE 2021-07-12 23:16:47 +03:00
Nikita Bobko
83c5c41dd4 Fix that marketplace identifies newly uploaded Kotlin plugin artifacts as Kotlin 1.2 artifacts
This `compiler.xml` is packed into `kotlin-idea.jar` and causes troubles for marketplace
in identifying correct Kotlin plugin version
2021-07-12 22:04:20 +03:00
Mikhail Glukhikh
a997a98054 Commend -Xopt-in deprecation warning (due to bootstrap problems) 2021-07-12 21:26:21 +03:00
Mikhail Glukhikh
a92ab1bc86 Deprecate EXPERIMENTAL_IS_NOT_ENABLED diagnostic #KT-47638 Fixed 2021-07-12 21:26:20 +03:00
Mikhail Glukhikh
5871f3d663 CLI: support -option=value syntax for non-advanced flags #KT-47640 Fixed 2021-07-12 21:26:19 +03:00
Mikhail Glukhikh
d8417fd622 Introduce -opt-in stable compiler option instead of -Xopt-in
#KT-47099 Fixed
2021-07-12 21:26:18 +03:00
Mikhail Glukhikh
47c8bab48e Replace -Xuse-experimental with -Xopt-in in codebase 2021-07-12 21:26:17 +03:00
Mikhail Glukhikh
195b6d1fb1 Deprecate -Xuse-experimental #KT-47623 Fixed 2021-07-12 21:26:16 +03:00
Mikhail Glukhikh
d9531f0c61 Don't report EXPERIMENTAL_ANNOTATION_ON_WRONG_TARGET for forbidden targets
#KT-47589 Fixed
2021-07-12 21:26:15 +03:00
Ilmir Usmanov
ac7538a269 Set receivers for inline class default function stub calls
Default function stubs have dispatch and receiver parameters, but
inline class methods are static by design with receivers as ordinary
parameters. So, take these parameters and set them as receivers during
lowerings.
 #KT-46230: Fixed
2021-07-12 19:46:09 +03:00
Florian Kistner
31420a934c MI-187 Add asserts for module dependencies 2021-07-12 18:23:19 +03:00
Florian Kistner
3fe388bd17 MI-187 Also allow foreign DerivedModuleInfos, if their original module is known to the ResolverForProject 2021-07-12 18:23:17 +03:00
Mikhail Glukhikh
5f6be619c0 FIR: Don't get all*Checkers multiple times 2021-07-12 15:47:59 +03:00
Elena Lepilkina
3cabfb6a85 [K/N][New MM] Rare GC calls to optimize swiftinterop benchmarks 2021-07-12 12:27:05 +00:00
Elena Lepilkina
cdeda58ed4 [K/N][perf] Added opportunity to set up tagged branch and added benchmarks plots for new MM 2021-07-12 12:26:20 +00:00
Victor Petukhov
33a281c637 Introduce separate compiler flag for unrestricted builder inference 2021-07-12 13:57:13 +03:00
Alexander Shabalin
274dabb61d Collect stacktraces without allocating kotlin objects. 2021-07-12 08:49:33 +00:00
Alexander Shabalin
fca89c2118 Backport span from C++20
Does not support ranges and construction from arbitrary contiguous iterators as both need C++20 concepts for an adequate implementation.
2021-07-12 08:48:20 +00:00
Dmitriy Novozhilov
5efde67a0c [FIR IDE] Register java enhancement state in FirIdeSessions
This was forgotten in 6d364a5f
2021-07-12 11:47:25 +03:00
Dmitry Petrov
1f8d6d6edb JVM additional DCE tests 2021-07-12 11:09:30 +03:00
Dmitriy Novozhilov
6d364a5fee [FIR] Register enhancement state in library session too
This is needed for enhancement scopes for deserialized java declarations
2021-07-12 10:15:07 +03:00
Dmitriy Novozhilov
8e0793091a Add @NoInfer to safeAs type
This change will force specify type argument of every safeAs call
2021-07-12 10:11:36 +03:00
Dmitriy Novozhilov
ddc3ef1121 Fix all illegal usages of safeAs function
Call of `safeAs` without specifying explicit type argument is hardly
  readable and may leads to hardly detectable errors
2021-07-12 10:11:36 +03:00
Ilya Gorbunov
5072653957 Duration: parse explicit positive values parenthesized 2021-07-12 04:39:28 +00:00
Ilya Gorbunov
682cb8e34a Duration default toString: use 0, 1, 2, 3, 6, or 9 decimal digits
KT-42851
2021-07-12 04:39:27 +00:00
Ilya Gorbunov
7551719b85 Duration parsing: simplify range checks 2021-07-12 04:39:27 +00:00
Ilya Gorbunov
0427eec20f Quote invalid strings in exception messages 2021-07-12 04:39:26 +00:00
Ilya Gorbunov
3f6e2be687 Duration: do not use scientific format for large values
The largest duration value formatted in ns with maximal decimals
would fit in 40 chars.
2021-07-12 04:39:25 +00:00
Ilya Gorbunov
1be1e5279c Duration: parse and format negative values parenthesized 2021-07-12 04:39:25 +00:00
Ilya Gorbunov
ca1a9e4ca3 Duration: longer than long values in ISO components, test negative cases 2021-07-12 04:39:24 +00:00
Ilya Gorbunov
1c6ab08220 Introduce functions to parse a duration from a string KT-45325 2021-07-12 04:39:23 +00:00
Ilya Gorbunov
7ab6f6c9b2 Change Duration.INFINITE.toIsoString representation 2021-07-12 04:39:23 +00:00
Ilya Gorbunov
ae3d9cc3cd Small durations are formatted with sub-second units KT-42851 2021-07-12 04:39:22 +00:00
Ilya Gorbunov
150ce812f1 Use days component in the default duration format KT-42851 2021-07-12 04:39:21 +00:00
Ilya Gorbunov
255c4b405e Duration: round Double value to Long ns instead of truncating it KT-47675 2021-07-12 04:39:21 +00:00
Ilya Gorbunov
42cd2e65e6 Change Duration.toString format KT-42851 2021-07-12 04:39:20 +00:00
Dmitry Petrov
804db3ce91 JVM KT-47613 custom control flow analyzer for CFG builder 2021-07-11 20:16:09 +03:00
Dmitry Petrov
fe71435104 JVM KT-47613 traverse nodes backwards in backward analysis 2021-07-11 20:16:09 +03:00
Viacheslav Kormushkin
8c021af646 M1 support for cocoapods
#KT-47078
2021-07-10 19:23:51 +00:00
Ilya Gorbunov
455fee29e4 Find correct next match after matchAt and matchEntire KT-47676 2021-07-10 21:31:20 +03:00
Ilya Gorbunov
28a0698463 Regex.matchAt/matchesAt #KT-34021 2021-07-10 21:31:19 +03:00
Dmitry Petrov
d99d25e51e JVM use SPBs in fix stack analyzer 2021-07-10 19:25:25 +03:00
Dmitry Petrov
38f45d2969 JVM update licence for InstructionLivenessAnalyzer.kt 2021-07-10 19:25:24 +03:00
Dmitry Petrov
68560c60f3 JVM use FastMethodAnalyzer when possible 2021-07-10 19:25:22 +03:00
Dmitry Petrov
c54e680021 JVM FastMethodAnalyzer: prune some exception edges 2021-07-10 19:25:21 +03:00
Dmitry Petrov
07b89c6b4b JVM FastMethodAnalyzer 2021-07-10 19:25:20 +03:00
Alexander Udalov
6f72c681ed JVM IR: fix name and parent of JvmSymbols.kClassJava
In contrast to other top-level functions/properties declared in
JvmSymbols (unsafeCoerce, signatureString, etc), kClassJava refers to a
real symbol from the library. Since not all calls to it are intrinsified
(see KClassJavaProperty.kt:30), it makes sense to allow to reference it
when constructing IR. For that, it needs to have the correct file facade
as the parent, and the JvmName annotation so that its name is mapped
correctly in the codegen.

Co-authored-by: Leonid Startsev <leonid.startsev@jetbrains.com>
2021-07-10 15:33:25 +02:00
Alexander Udalov
d33debdf7c IR: minor, cleanup Symbols 2021-07-10 15:33:25 +02:00
Yahor Berdnikau
de22a467a1 Ensure default toolchain is also set to java only modules.
^KT-46972 Fixed
2021-07-09 19:36:27 +03:00
Victor Petukhov
a8e28e4b69 Update compiler tests 2021-07-09 19:21:28 +03:00
Victor Petukhov
967304ffca Don't compute default type for a fixing type variable for self type if the corresponding feature is disabled 2021-07-09 19:21:27 +03:00
Victor Petukhov
584facc95f Fix fir-related problems and tests for inferring self types 2021-07-09 19:21:25 +03:00
Victor Petukhov
9e48ef85ea Add tests for inferring self types from Java 2021-07-09 19:21:22 +03:00
Victor Petukhov
3b16865152 Don't approximate captured types while substitute them in upper bound position 2021-07-09 19:21:17 +03:00
Victor Petukhov
c2cf2f36cd Implement inferring materialized self types through a default type in ResultTypeResolver 2021-07-09 19:21:04 +03:00
Victor Petukhov
3787099a38 Put the type inference on calls with self types under the compiler flag 2021-07-09 19:20:56 +03:00
Victor Petukhov
51c5a54e31 Support type inference for self type materialization calls 2021-07-09 19:20:54 +03:00
Mikhail Zarechenskiy
44cf4be1e5 Inference for some kind of self types 2021-07-09 19:20:52 +03:00
Andrey Zinovyev
db72fd1e93 [FIR] Fix inheritance check for substitution overrides
And delegates
2021-07-09 17:14:37 +03:00
Alexander Udalov
d43ed1cf75 Minor, add test on typeOf with intersection type 2021-07-09 14:53:57 +02:00
Alexander Udalov
a7e48c3af1 Improve toString of platform types created by typeOf
In the stdlib implementation, render "!" if the type is only
nullability-flexible. Otherwise, render "($lower..$upper)".

Note that full kotlin-reflect has a much more complicated logic (see
`DescriptorRendererImpl.renderFlexibleType`) that renders things like
`(Mutable)List` and so on. It is not a goal of the stdlib implementation
to replicate all of that, since it requires copying a large amount of
code, namely the entirety of `JavaToKotlinClassMap` to map Java class
names to Kotlin.
2021-07-09 14:53:56 +02:00
Alexander Udalov
ddfa94e7e9 Support Nothing type in typeOf
The proper support will come in KT-15518, but that would be a breaking
change even for stable Kotlin without kotlin-reflect. Before that issue
is fixed, represent Nothing in types with the Void class, and use a flag
in the no-reflect implementation to remember that it's not actually the
Void class itself.

 #KT-39166 Fixed
2021-07-09 14:40:05 +02:00
Alexander Udalov
02774fae0c Report error on non-reified type parameter with recursive bound in typeOf
Instead of throwing an exception.

 #KT-40173
2021-07-09 14:31:52 +02:00
Alexander Udalov
438ce57183 Report error on typeOf<suspend ...>()
Otherwise an invalid type is constructed which causes kotlin-reflect to
crash, and stdlib implementation to render the type incorrectly. The
reason is that suspend functional types are not properly supported in
reflection. Once they are supported, this error can be removed.

 #KT-47562
2021-07-09 14:31:52 +02:00
Alexander Udalov
68432f0c20 Fix deprecation/unchecked warnings after update to 203 2021-07-09 14:24:07 +02:00
Dmitriy Novozhilov
c6f754cf7a [Build] remove dependency on IDEA classes from :visualizer 2021-07-09 14:38:03 +03:00
Dmitriy Novozhilov
aa3a73c6c2 [FIR] Move JavaTypeEnhancementState to session component 2021-07-09 14:38:02 +03:00
Simon Ogorodnik
e102bdea20 [Build] Fix xerces usage in FIR modularized tests 2021-07-09 11:08:13 +00:00
Victor Petukhov
c3a5a7754d Use proper applicability for constraint warnings
^KT-47316 Fixed
2021-07-09 14:07:01 +03:00
Victor Petukhov
1224d28deb Move java type enhancement stuff to :core:compiler.common.jvm 2021-07-09 13:22:02 +03:00
Nikita Bobko
c112e768de Update ReadMe to point to up-to-date Kotlin IDEA plugin location 2021-07-09 10:14:41 +00:00
Pavel Kunyavskiy
31857f23a3 [K/N] Refactoring: remove copypaste 2021-07-09 08:53:08 +00:00
Pavel Kunyavskiy
594ff1474d [K/N] Make llvm Int1 boolean, not byte 2021-07-09 08:53:08 +00:00
Pavel Kunyavskiy
eec8fdf16a [K/N] Implement isExperimentalMM intrinsic 2021-07-09 08:53:07 +00:00
Ilya Muradyan
55ec6729b0 [REPL] Fix completion after final expressions 2021-07-09 04:06:53 +03:00
Vyacheslav Gerasimov
a915eddf22 Build: Upgrade Idea Ext plugin to 1.0.1 2021-07-08 23:24:09 +03:00
Dmitry Petrov
24fcadb869 JVM don't run CCE on methods without optimizable conditional jumps 2021-07-08 22:11:59 +03:00
Alexander Udalov
25f0beed12 Load async-profiler.jar if possible when using -Xprofile
Instead of requiring it to be on the compiler classpath.

This will make it much easier to profile the Kotlin compiler daemon in
Gradle, by just specifying a compiler argument instead of also manually
patching the compiler jar.
2021-07-08 20:44:45 +02:00
Ilya Muradyan
787ce6335c Change nestedClasses logic to accept classes with nested type aliases
#KT-47650 fixed
2021-07-08 21:04:53 +03:00
Simon Ogorodnik
ca86b7ff7d [Build] Make getToolchainCompilerFor private and fix LibrariesCommon 2021-07-08 17:06:31 +00:00
Simon Ogorodnik
c0e479eadb [Build] Allow to override JDK 10 with JDK 11 2021-07-08 17:06:31 +00:00
Simon Ogorodnik
18eccdbc1f [Build] Allow to override JDK 9 with JDK 11 2021-07-08 17:06:30 +00:00
Simon Ogorodnik
a31bdc6454 [Build] Respect overrides in getToolchainLauncherFor 2021-07-08 17:06:29 +00:00
Simon Ogorodnik
bf25ccfc0e [Build] Allow kotlin.build.isObsoleteJdkOverrideEnabled=true on CI 2021-07-08 17:06:28 +00:00
Ilya Kirillov
eab1a78d48 FIR IDE: mute failing multimodule tests 2021-07-08 18:25:44 +03:00
Roman Golyshev
dcc30cb672 FIR IDE: Mute test with java file in the dependency
The corresponding JavaSymbolProvider currently is unable to
see the `Foo` class, because under the hood it uses
`JvmDependenciesIndexImpl` which doesn't know about the corresponding
.java file because it is created for m2-module `project`

I wasn't able to fix it yet
2021-07-08 18:25:42 +03:00
Roman Golyshev
0d443d526d FIR IDE: Use more correct implementation of TestModuleSourceInfo::dependencies
When only `regularDependencies` were used, multiplatform tests were
failing because `actual` modules did not see the `expected` ones
2021-07-08 18:25:41 +03:00
Ilya Kirillov
a9bb577154 FIR IDE: add ability to run multimodule tests 2021-07-08 18:25:39 +03:00
Andrey Zinovyev
1cb34541bd [FIR] Fixes after delegation scope rework 2021-07-08 18:13:52 +03:00
Andrey Zinovyev
02297d2c75 [FIR] Rollback exposure of j.u.List.sort method 2021-07-08 18:13:51 +03:00
Andrey Zinovyev
221e642d97 [FIR] Fix inheritance diagnostics for new FirDeclaration hierarchy
Plus several small fixes in reporting itself
2021-07-08 18:13:49 +03:00
Andrey Zinovyev
b36f8ed8f5 [FIR] DATA_CLASS_OVERRIDE_CONFLICT diagnostic 2021-07-08 18:13:48 +03:00
Andrey Zinovyev
b44785c24e [FIR] NOTHING_TO_OVERRIDE diagnostic 2021-07-08 18:13:47 +03:00
Andrey Zinovyev
9452b788bf [FIR] Implement CANNOT_OVERRIDE_INVISIBLE_MEMBER diagnostic 2021-07-08 18:13:46 +03:00
Andrey Zinovyev
f4c8108ee0 [FIR] Substitute type parameters in inheritance checker 2021-07-08 18:13:45 +03:00
Andrey Zinovyev
3f7d050f8f [FIR] Implement CONFLICTING_INHERITED_MEMBERS diagnostic 2021-07-08 18:13:44 +03:00
Andrey Zinovyev
78519f851e [FIR] Implement VAR_OVERRIDDEN_BY_VAL_BY_DELEGATION diagnostic 2021-07-08 18:13:43 +03:00
Andrey Zinovyev
c98cd3b190 [FIR] Implement properties types mismatch on inheritence
PROPERTY_TYPE_MISMATCH_ON_INHERITANCE,
VAR_TYPE_MISMATCH_ON_INHERITANCE,
PROPERTY_TYPE_MISMATCH_BY_DELEGATION
2021-07-08 18:13:41 +03:00
Andrey Zinovyev
8c7ee0b714 [FIR] Implement RETURN_TYPE_MISMATCH_BY_DELEGATION diagnostic 2021-07-08 18:13:40 +03:00
Andrey Zinovyev
94da1e37aa [FIR] Implement RETURN_TYPE_MISMATCH_ON_INHERITANCE diagnostic 2021-07-08 18:13:38 +03:00
Konstantin Tskhovrebov
8012eb3214 Add support Apple M1 for KMP embedAndSign task.
#KT-47077
2021-07-08 16:43:59 +03:00
Hung Nguyen
a0e003ac5d Add tests for kotlin.incremental.useClasspathSnapshot feature
This ensures we don't regress when developing the feature.

Bug: KT-45777
Test: New IncrementalCompilationClasspathSnapshotJvmMultiProjectIT
      and IncrementalJavaChangeClasspathSnapshotIT
2021-07-08 15:05:38 +03:00
Dmitriy Novozhilov
d44a2f6fd3 Fix dependency on javac2.jar
In 203.8084.24 this jar was moved from intellij dependencies to
  libraries of intellij java plugin
2021-07-08 13:29:22 +03:00
Dmitriy Novozhilov
30578cfb95 Delete DynamicBundle copy
We can safely use it from IDEA after IDEA-248785 was fixed
2021-07-08 13:29:21 +03:00
Dmitriy Novozhilov
d6a6ec42a2 Use 203.8084.24 as IDEA dependency instead of 203.6682.168 2021-07-08 13:29:21 +03:00
Dmitriy Novozhilov
d473d22d8c [Test] Migrate SpecTestsConsistencyTest to JUnit5 2021-07-08 13:29:21 +03:00
Dmitriy Novozhilov
c0c9e4a114 Update testadata of PSI dump of java records 2021-07-08 13:29:21 +03:00
Dmitriy Novozhilov
955c506294 Update load java testdata with type use annotations 2021-07-08 13:29:21 +03:00
Dmitriy Novozhilov
4d4d3a998b [FIR] Update load java testdata according to new sealed modifier 2021-07-08 13:29:20 +03:00
Dmitriy Novozhilov
5552f5f5b2 [FIR] Update light classes testdata
In 203 platform java.lang.Object in position of type parameter
  bound is not rendered
2021-07-08 13:29:20 +03:00
Dmitriy Novozhilov
a710cdf822 [FIR] Properly unregister java element finder in CLI compiler 2021-07-08 13:29:20 +03:00
Dmitriy Novozhilov
817c4381f5 Fix asm version in kotlinp 2021-07-08 13:29:20 +03:00
Dmitriy Novozhilov
11faf04a4c [Test] Remove dependencies on IDEA classes from test modules
Some of IDEA services (like in `com.intellij/execution`) was copied,
  because they are used in tests but jars with them compiled with
  jdk 11 and we run our tests on jdk 8, so their bytecode can not
  be read
2021-07-08 13:29:19 +03:00
Dmitriy Novozhilov
11dfbd41ac [Test] Delete obsolete descriptor renderer tests 2021-07-08 13:29:19 +03:00
Dmitriy Novozhilov
eb94575c69 Remove redundant usages of IDEA services in CLI 2021-07-08 13:29:19 +03:00
Dmitriy Novozhilov
82e3e00bf5 Fix compilation after migrating to ASM 9 2021-07-08 13:29:19 +03:00
Yan Zhulanow
9e2fb6e25a Add verification metadata for IntelliJ 2020.3 2021-07-08 13:29:18 +03:00
Dmitriy Novozhilov
80971d7b8b ~~~~ switch 203 ~~~~ 2021-07-08 13:29:18 +03:00
Yan Zhulanow
ca8e35e7db Return 203 bunch back 2021-07-08 13:29:18 +03:00
Yan Zhulanow
cf65754ea4 Update 203 bunch 2021-07-08 13:29:18 +03:00
Dmitriy Novozhilov
ccc3e3510c [Test] Remove useless dependencies on IDEA from FIR test modules 2021-07-08 13:29:18 +03:00
Dmitriy Novozhilov
b6bc57fa09 [Test] Remove useless dependencies on IDEA from :compiler:tests-common-new 2021-07-08 13:29:17 +03:00
Dmitriy Novozhilov
88b7694762 [Test] Remove useless dependencies on IDEA from :compiler:tests-common 2021-07-08 13:29:17 +03:00
Nikita Bobko
2a26c29390 Disable kotlin-scripting-ide-common publishing
We don't need this artifact in IDE anymore since we are not
going to move ide-common classes to kotlin repo. See previous commit
2021-07-08 10:01:35 +00:00
Nikita Bobko
3ca0e11dab Add README to scripting-ide-common
Originally, we though that we would move classes from `ide-common` from Kotlin plugin to this
module but it turns that these classes are heavily used in Kotlin plugin and it's better to
keep them with the rest of Kotlin plugin. So now classes in `scripting-ide-common` are copy-pasted
2021-07-08 10:01:34 +00:00
Anton Yalyshev
e32a975814 Add change notes for 1.5.30-M1 2021-07-08 10:25:25 +03:00
Dmitry Petrov
1a0a3df9d2 JVM_IR simplify BridgeLowering
Generate bridges immediately for each class.

No need to compute existing signatures for a given method name unless it
requires a special bridge.
2021-07-07 21:24:55 +03:00
Xin Wang
8317daa00b Don't generate nullability assertions in methods for directly invoked lambdas 2021-07-07 20:32:47 +03:00
Nikita Bobko
fbe062ee64 [refactoring] Move files in scripting-ide-common into unique subpackage
I am afraid of FQN clashes with classes in `ide-common` in kotlin-ide
2021-07-07 16:51:45 +02:00
Nikita Bobko
339231b05e Move KtFunctionLiteral.findLabelAndCall from kotlin-ide.frontend-independent to compiler.psi
I want to be able to use this function in `:kotlin-scripting-ide-common` & `frontend-independent`

This commit also allows to remove copy-pasted `findLabelAndCall` in `scripting-ide-services` module
2021-07-07 16:51:44 +02:00
Dmitry Gridin
a8a6f51a0e [common] fix flexible type approximation in renders
^KTIJ-3030 Fixed

(cherry picked from commit 4855d88a9f6fbce9aeeea6fe1f29dd099a833aed)

KT-CR-2373
2021-07-07 16:51:44 +02:00
Matthew Gharrity
958b0ff24a Ignore diagnostics in ShadowedDeclarationsFilter
During code completion, ShadowedDeclarationsFilter resolves many
synthetic calls (sometimes >1000 for certain projects/scenarios).
By ignoring diagnostics we can avoid running call checkers
during this process (pending a sibling change in the compiler).

Relates to KT-44276 and github.com/JetBrains/kotlin/pull/4027
2021-07-07 16:51:44 +02:00
Matthew Gharrity
e2109c3f8f ShadowedDeclarationsFilter: check for equivalence
If there are multiple copies of the same library on the classpath,
then ShadowedDeclarationsFilter becomes very slow because it
encounters many equal-signature declarations and thus has to resolve
a lot of calls in order to pick among them.

Having multiple copies of the same library on the classpath is
somewhat common in real-world projects. It occurs in the
JetBrains/intellij-kotlin project, for example. In that project,
ShadowedDeclarationsFilter ends up resolving thousands of calls,
accounting for around 80% of completion time when there are
many completion results (see KT-44276).

We can optimize ShadowedDeclarationsFilter by checking whether the
descriptors in an equal-signature group are structurally equivalent.
If they are, we can just pick one rather than running resolve.

Testing on a small project with Kotlin stdlib duplicated on the
classpath, this change reduces overhead in ShadowedDeclarationsFilter
from 1200 ms to 20 ms when running completion on the prefix 'a'.
End-to-end completion time is cut in half.

Test: JvmBasicCompletionTestGenerated.Common.Shadowing
2021-07-07 16:51:43 +02:00
Andrei Klunnyi
decfcd28d2 KT-39398 Wrong import of unrelated object member is suggested for receiver
Receiver of a function call '<receiver>.foo()' (where receiver is a
class/object/alias name) might be specified incorrectly - corresponding
[companion] object might not be declared.

Before this commit '<receiver>' was considered to be undefined (null).
As a consequence, import suggestion included all 'foo()' functions from
the search scope.

Now as a value of '<receiver>' we set class/object/alias itself
resulting in an empty import suggestion list.
See org/jetbrains/kotlin/idea/util/CallType.kt:307
(#extractReceiverTypeFrom(descriptor: ClassDescriptor)).
2021-07-07 16:51:43 +02:00
Nikita Bobko
365821ae54 2/2 Extract code which is required for :kotlin-scripting-ide-services from ide-common into seprate module
Extract the code and keep it in Kotlin repo. See previous preparation commit as well
2021-07-07 16:51:43 +02:00
Nikita Bobko
cf3f35e1c8 1/2 Preparation commit: move ide-common files which are required for scripting to separate directory
This commit is needed to preserve git history
2021-07-07 16:51:43 +02:00
pyos
50797dba8d JVM: do not use crossinline flag when inlining assertions
Crossinline lambdas *can* be inlined into objects, but don't *have* to;
the correct place should be determined from the context, not from the
parameter.
2021-07-07 16:48:01 +02:00
pyos
e64cda61d5 JVM_IR: do not generate $assertionsDisabled twice during inlining 2021-07-07 16:48:01 +02:00
Ilya Matveev
123c76053f [Gradle][tests] Fix running CocoaPods on Apple M1 2021-07-07 17:13:34 +03:00
Ilya Matveev
5fad5e017e [Gradle][tests] Disable workaround for XCode 12.3 2021-07-07 17:13:31 +03:00
Ilya Matveev
53a4187427 [Gradle][tests] Install CocoaPods to a temp dir instead of HOME 2021-07-07 17:13:29 +03:00
Ilya Matveev
aa9ff3d6bb [Gradle][tests] Install cocoapods in MPP plugin tests 2021-07-07 17:13:26 +03:00
Svyatoslav Scherbina
2d0dbf9729 Native: improve ObjCExport thread state switching 2021-07-07 13:53:27 +00:00
Ilya Goncharov
1a27f91a98 [Gradle, JS] Remove redundant suppression 2021-07-07 16:40:22 +03:00
Ilya Goncharov
f7e69fb2ef [Gradle, JS] Update verification data with Yarn 2021-07-07 16:40:20 +03:00
Ilya Goncharov
da1bdf87cb [Gradle, JS] Use injected services of fs 2021-07-07 16:40:19 +03:00
Ilya Goncharov
e2adf9793c [Gradle, JS] Node into PATH during installing of dependencies
^KT-37895 fixed
2021-07-07 16:40:17 +03:00
Ilya Goncharov
065a5d98fb [Gradle, JS] Configuration cache friendly 2021-07-07 16:40:16 +03:00
Ilya Goncharov
81ac48390c [Gradle, JS] Make yarn working without downloading
^KT-32071 fixed
2021-07-07 16:40:15 +03:00
Ilya Goncharov
eb73527b9f [Gradle, JS] No additional checks of setup tasks 2021-07-07 16:40:13 +03:00
Ilya Goncharov
54d47de008 [Gradle, JS] Yarn as a dependency with ivy repository like Node.js
^KT-34985 fixed
2021-07-07 16:40:11 +03:00
Anton Yalyshev
1507f1a9c0 Add change notes for 1.5.21 2021-07-07 16:30:34 +03:00
Andrey Zinovyev
de3f31cf78 [FIR] Partial implementation of DEPRECATION(_ERROR) diagnostics
No support for inheritance deprecations
and deprecations in qualifier's parts
2021-07-07 16:19:28 +03:00
Andrey Zinovyev
9fad55d551 [FIR] Use @DeprecatedSinceKotlin in the resolution 2021-07-07 16:19:27 +03:00
Igor Yakovlev
b64f7909b8 [FIR IDE] Implement own fir light classes support 2021-07-07 14:08:41 +02:00
Yahor Berdnikau
7fff282565 Fix AllOpen plugin exposes common with Gradle runtime dependencies.
^KT-47354 Fixed
2021-07-07 11:31:18 +00:00
Mikhail Glukhikh
fa086d22c2 Don't build kotlin-gradle-statistics in FIR mode at all 2021-07-07 14:28:03 +03:00
Mikhail Glukhikh
863a2c6498 Disable kotlin-gradle-statistics and wasm.ir under FIR 2021-07-07 14:28:02 +03:00
Mikhail Glukhikh
c7877cb440 FIR: fix contract deserialization for assertIs<T> 2021-07-07 14:28:00 +03:00
Ilya Goncharov
e0c1f50f03 [Gradle, JS] Fix node.js repository declaration
^KT-47557 fixed
2021-07-07 08:26:07 +00:00
Sergey Bogolepov
f05110f99b [K/N] Add some tests for https://youtrack.jetbrains.com/issue/KT-47605 2021-07-07 07:50:57 +00:00
Sergey Bogolepov
9ed97a27f1 [K/N] Introduce LLD compatibility checker for MinGW
We are going to switch to LLD linker for MinGW targets.
Right now LLD for MinGW doesn't support all features
of ld.bfd and thus this change might be breaking for some users.
To make transition smoother, we run lld -### to show a warning to user
so they can update their compilation options before LLD will be turned
on by default.

More details: https://youtrack.jetbrains.com/issue/KT-47605
2021-07-07 07:50:57 +00:00
Ilya Kirillov
30d0fea003 FIR IDE: enable explicit API mode in idea-frontend-fir module 2021-07-07 01:40:03 +03:00
Ilya Kirillov
51576c70b6 FIR: introduce package directive
The package directive is needed for KtElement -> FirElement mapping in IDE.
There should be some FirElement which will be result of mapping of elements
inside KtPackageDirective.
2021-07-06 22:49:50 +03:00
Mikhail Glukhikh
bf40c07cc3 FIR: drop questionable DiagnosticKind.NotRootCause 2021-07-06 18:43:16 +03:00
Mikhail Glukhikh
7d583973ab Disable -Werror in FIR mode inside disableDeprecatedJvmTargetWarning 2021-07-06 18:27:53 +03:00
Tianyu Geng
768ddea18f FIR checker: ILLEGAL_DECLARATION_IN_WHEN_SUBJECT 2021-07-06 18:27:47 +03:00
Tianyu Geng
31573a98e8 FIR checker: report EXPECTED_CONDITION 2021-07-06 18:27:23 +03:00
Sergey Bogolepov
e396da0562 [K/N] Update list of targets with stable caches
Enable compiler caches for iosSimulatorArm64 and macosArm64 targets
to make Apple Silicon distribution feature complete with
Intel-based one.
2021-07-06 18:15:30 +03:00
Victor Petukhov
65fd8fc174 Add generated files with descriptors for foreign annotation tests 2021-07-06 18:10:22 +03:00
Ilya Goncharov
c797d38312 [Gradle, JS]Add base dirs and prefix for correct source maps calculating 2021-07-06 12:59:03 +00:00
Alexander Udalov
e7b37d99cb Fix new compiler warnings in daemon and build-common 2021-07-06 13:31:21 +02:00
Sergey Shanshin
0d211a53cb Support serializable classes clash with JVM primitive types by name
Fixes Kotlin/kotlinx.serialization#1353
2021-07-06 12:52:53 +03:00
Ilya Goncharov
7181631051 [Gradle, JS] Add statistics for Kotlin/JS
- source map usages (legacy, ir)
- incremental klib
- incremental JS IR
- property lazy initialization

^KT-47435 fixed
2021-07-06 07:38:56 +00:00
Victor Petukhov
6cfb1f40d6 Specify jspecify mode explicitly for warnings in tests 2021-07-06 09:54:32 +03:00
Victor Petukhov
74aa8e7497 Get rid of singleOrNull of NullabilityAnnotationStates 2021-07-06 09:54:31 +03:00
Victor Petukhov
877ca370c2 Use memoized function to compute and store annotation states cache 2021-07-06 09:54:31 +03:00
Victor Petukhov
50ad5116b5 Add CLI test for -Xnullability-annotations 2021-07-06 09:54:30 +03:00
Victor Petukhov
b0a44705b4 Take into account user defined jsr-305 annotations 2021-07-06 09:54:30 +03:00
Victor Petukhov
b2dff10e32 Implement caching states for nullability annotations 2021-07-06 09:54:30 +03:00
Victor Petukhov
a82772f31a Depend on passed language version explicitly to compute nullability annotation settings 2021-07-06 09:54:29 +03:00
Victor Petukhov
18384788a4 Move type enhancement state stuff into core:descriptors.jvm 2021-07-06 09:54:29 +03:00
Victor Petukhov
8de05691a9 Revert "Move fqname related stuff into core:util.runtime module"
This reverts commit e651e1c6
2021-07-06 09:54:28 +03:00
Victor Petukhov
ea901d81fb Get rid of redundant Jsr305State 2021-07-06 09:54:28 +03:00
Victor Petukhov
f46dc713d7 Support rxjava 3 nullability annotations 2021-07-06 09:54:28 +03:00
Victor Petukhov
6d3badb2cd Support configuring of nullability annotations with their report levels through a test directive 2021-07-06 09:54:27 +03:00
Victor Petukhov
61c2f1b203 Extract building JSR-305 settings to separate function 2021-07-06 09:54:27 +03:00
Victor Petukhov
f92ab691f8 Add explicit enabling of TypeEnhancementImprovementsInStrictMode in jspecify tests 2021-07-06 09:54:26 +03:00
Victor Petukhov
39ffcd3ba6 User proper report level for compatqual nullability annotations 2021-07-06 09:54:26 +03:00
Victor Petukhov
e16033f8d8 Add androidx recently nullability annotations 2021-07-06 09:54:26 +03:00
Victor Petukhov
d5180f79aa Support picking settings of exacter annotations by the length of the matching part of fqname 2021-07-06 09:54:25 +03:00
Victor Petukhov
70dbc50305 Rename JSPECIFY_DEFAULT_NOT_NULL to JSPECIFY_NULL_MARKED 2021-07-06 09:54:25 +03:00
Victor Petukhov
4173f2d294 Don't forget jspecify annotation during extracting nullability from known annotations 2021-07-06 09:54:24 +03:00
Victor Petukhov
46d0b16142 Use new default settings for java nullability annotations in JavaTypeEnhancementState and get rid of all hardcoded defaults 2021-07-06 09:54:24 +03:00
Victor Petukhov
8e7c0e8c61 Describe default settings for java nullability annotations depending on current kotlin version 2021-07-06 09:54:24 +03:00
Victor Petukhov
205087cae3 Move fqname related stuff into core:util.runtime module 2021-07-06 09:54:23 +03:00
Victor Petukhov
c8af1b735f Introduce compiler flag to manage status of specific Java nullability annotations 2021-07-06 09:54:23 +03:00
Yahor Berdnikau
c3a3e99724 Fix toolchain is not applied for modules with 'java' plugin.
Use common base java plugin for configuration action: 'java-base'.

^KT-46972 Fixed
2021-07-05 23:15:44 +02:00
Alexander Udalov
113632c49c Psi2ir: load single-value Java array annotation arguments correctly
#KT-47467 Fixed
2021-07-05 21:49:10 +02:00
Pavel Punegov
269f83f86e Update kotlin-build-gradle-plugin to 0.0.31 2021-07-05 19:43:28 +00:00
Pavel Punegov
c2fe46020e Native: improve CompilerVersion to correspond to the versioning schema
* Add pub and dev-google-pr meta versions
* Allow using release versions with and without build number
* Add tests for version parsing
2021-07-05 19:43:27 +00:00
Yahor Berdnikau
1bd0607b53 Fix toolchain jdk override was not working for all modules.
Now it also considers the case when separate tasks toolchain
are configured or module only has java toolchain.

^KT-46972 Fixed
2021-07-05 21:15:04 +02:00
Pavel Kunyavskiy
70ca222806 [K/N] Disable external calls checker for wasm target 2021-07-05 18:49:09 +00:00
Zalim Bashorov
4c4bcb1e3e [Gradle, JS] Turn on by default sourcemap generation for JS IR
#KT-46551 Fixed
2021-07-05 21:01:45 +03:00
Zalim Bashorov
8da62b56fb [IR] Put correct line numbers on return while inlining
#KT-46551 In Progress
2021-07-05 21:01:44 +03:00
Zalim Bashorov
d1f5ab4b09 [JS IR] Generate correct source locations in sourcemap for inline declarations
* Keep returnable blocks.
* Add a new lowering which simplifies returnable blocks by introducing
  temporary variable for result and changing returnable block's type to Unit.
* Use information from returnable blocks in codegen to generate
  the right source locations in sourcemap.
* Support in namer (LocalNameGenerator).
* Fix some lowerings to work correctly with returnable blocks.

#KT-46551 In Progress
2021-07-05 21:01:43 +03:00
Zalim Bashorov
2460f5f9ae [JS CLI] Support sourcemap generation for IR BE in CLI
#KT-46551 In Progress
2021-07-05 21:01:41 +03:00
Zalim Bashorov
5a3efc1a98 [JS IR] Fill source info in codegen
#KT-46551 In Progress
2021-07-05 21:01:40 +03:00
Zalim Bashorov
64c6d852de [JS IR] Preparing for introducing sourcemap as another compilation output
* Rename `JsCode` to `CompilationOutputs`.
* Rename members of CompilerResult.

#KT-46551 In Progress
2021-07-05 21:01:38 +03:00
Zalim Bashorov
d9b7230144 [JS IR] add dependency to sourcmap module
#KT-46551 In Progress
2021-07-05 21:01:37 +03:00
Zalim Bashorov
aae1057f35 [IR] Support IrReturnableBlock inside IR renderer 2021-07-05 21:01:35 +03:00
Ilya Chernikov
6911860cca Clean-up coroutines usage in scripting libs and plugin
#KT-30778 fixed (again)
2021-07-05 19:26:42 +03:00
Ilya Chernikov
49e0b639f8 Add JSR-223 tests with compilable and bindings 2021-07-05 19:26:40 +03:00
Ilya Chernikov
32b6cfe2ea [Scripting] fix receiver substitution in script JVM IR lowering 2021-07-05 19:26:39 +03:00
Ilya Chernikov
a7b94b398a [minor] Bump serialization lib version in scripting test 2021-07-05 19:26:38 +03:00
Ilya Chernikov
0c2591e938 Bump coroutines version used in scripting to 1.5.0
#KT-43917 fixed
2021-07-05 19:26:37 +03:00
Igor Yakovlev
64afba299f [imltogradle] Don't use deprecated kotlinOptions.jdkHome in generated build.gradle.kts files 2021-07-05 17:52:04 +02:00
Tianyu Geng
4c439bb5d7 FIR: fix DELEGATION_SUPER_CALL_IN_ENUM_CONSTRUCTOR
DELEGATION_SUPER_CALL_IN_ENUM_CONSTRUCTOR should be an error but it's
somehow a warning in FIR.
2021-07-05 18:32:37 +03:00
Tianyu Geng
db1db6c64c FIR: fix CYCLIC_CONSTRUCTOR_DELEGATION_CALL
Somehow it's a warning in FIR, but it should be an error.
2021-07-05 18:32:36 +03:00
Jinseong Jeon
cd78a156c5 FIR checker: apply member checkers to anonymous objects
because they can have member properties/functions too.
2021-07-05 18:32:34 +03:00
Jinseong Jeon
64a275cf83 FIR: fix type comparator
As many other places did, this one is supposed to return the diff value
if the given two intersection types' sizes are different.
2021-07-05 18:32:33 +03:00
Tianyu Geng
cdfb2fb3d9 FIR checker: report SETTER_PROJECTED_OUT 2021-07-05 18:32:32 +03:00
pyos
c3a91efea3 JVM_IR: fix primitive comparison optimizations
1. the `primitive == object?.something` fusion should not apply to
    `primitive.equals(object?.something)` because it can't;

 2. coercions to Int are there for a reason - don't remove them;

 3. better optimize `primitive == object?.something` -- the result
    should be subject to if-null fusion, so it needs to have a specific
    pattern that resembles safe calls.

 #KT-47597 Fixed
2021-07-05 18:13:09 +03:00
Yahor Berdnikau
7e70c93cbf Allow to avoid using JDK 1.6 and JDK 1.7 in the repo.
This behaviour could be enabled via adding
'kotlin.build.isObsoleteJdkOverrideEnabled=true'
to the 'local.properties' file.

^KT-46972 Fixed
2021-07-05 14:11:13 +00:00
Yahor Berdnikau
7789054547 Migrate repo to use JVM toolchains Gradle feature.
^KT-46972 Fixed
2021-07-05 14:11:12 +00:00
Yahor Berdnikau
08d831934a Revert "Build: add temporary option to suppress jdkHome warning"
This reverts commit 1dfcec3a93.
2021-07-05 14:11:11 +00:00
sebastian.sellmair
5b5dddc2d1 [Commonizer] Restore TypeAliasCommonizer's Commutative property & TypeAliasTypeCommonizer: substitute underlying-type arguments
^KT-47574 The fix done here supports only one level of substituting
underlying type-arguments.

HierarchicalTypeAliasCommonizationTest.`KT-47574 - test long typealias chain`
will assert proper behaviour for nested chains.
2021-07-05 09:00:46 +00:00
sebastian.sellmair
448302d19b [Commonizer] CommonizeNativeDistributionTest.commonize - apple platforms(): Require macos 2021-07-05 09:00:45 +00:00
sebastian.sellmair
1e801e77a2 [Commonizer] HierarchicalClassAndTypeAliasCommonizationTest: Remove unnecessary annotations and reformat file 2021-07-05 09:00:44 +00:00
sebastian.sellmair
684e51b0be [Commonizer] Implement TypeCommonizer as AssociativeCommonizer 2021-07-05 09:00:44 +00:00
sebastian.sellmair
b29fd17d26 [Commonizer] Use AssociativeCommonizer signature to implement ClassOrTypeAliasTypeCommonizer
This drastically improves performance for now, since the previous
Adapter implementation was at least O(n^2). While the Adapter
implementation could have been reduced to O(n), the Signature of
StatelessCommonizer was misleading.

StatelessCommonizer will be introduced back later when other
Commonizer implementations are ready to be converted to a new
Signature.
2021-07-05 09:00:43 +00:00
sebastian.sellmair
20f55ef0b7 [Commonizer] Commonize 'const val' and 'val' properties 2021-07-05 09:00:42 +00:00
sebastian.sellmair
9794068f22 [Commonizer] typeAliasUtils: computeSuitableUnderlyingType: Consider commonized type-aliases 2021-07-05 09:00:42 +00:00
sebastian.sellmair
5ca81b01f0 [Commonizer] Improve AbstractCommonizerTest diagnostic message 2021-07-05 09:00:41 +00:00
sebastian.sellmair
d7022cb378 [Commonizer] Move ClassTypeCommonizer and TypeAliasTypeCommonizer into seperate files 2021-07-05 09:00:40 +00:00
sebastian.sellmair
8f73df0f85 [Commonizer] Implement new ClassOrTypeAliasTypeCommonizer
^KT-47432 Verification Pending
^KT-47434 Verification Pending
2021-07-05 09:00:39 +00:00
sebastian.sellmair
8e2780345c [Commonizer] HierarchicalClassAndTypeAliasCommonizationTest: Un-ignore tests fore ^KT-47432 and ^KT-47434 and add additional test's 2021-07-05 09:00:39 +00:00
Pavel Kunyavskiy
fc75486611 [K/N] Debug tool for checking state at call points of unknown functions
After linking runtime, llvm-ir is modified to add checker function
call at all points where unknown function, which can possibly run long
is called. This function checks Native state is set, to avoid long locks
at gc.
2021-07-05 08:35:23 +00:00
Pavel Kunyavskiy
1ba04fdd21 [K/N] Introduce external calls checker compiler option 2021-07-05 08:35:23 +00:00
Pavel Kunyavskiy
271fc35082 [K/N] Minor debug info fix 2021-07-05 08:35:22 +00:00
Pavel Kunyavskiy
4c2d518cf5 [K/N] Move ClearCurrentThreadData() out of TestSupport 2021-07-05 08:35:21 +00:00
Pavel Kunyavskiy
65bebd3058 [K/N] Support AddressToSymbol using dladdr, if availible 2021-07-05 08:35:20 +00:00
Pavel Kunyavskiy
b7707d8755 [K/N] Introduce api for getting existing global by name from StaticData 2021-07-05 08:35:20 +00:00
Pavel Kunyavskiy
1db2903e4f [K/N] Add utilities to check if thread is registered now 2021-07-05 08:35:19 +00: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
56892 changed files with 200128 additions and 1249615 deletions

3
.bunch
View File

@@ -1,2 +1 @@
202
as42
203

3
.gitignore vendored
View File

@@ -12,7 +12,7 @@
/android-studio/sdk
out/
/tmp
kotlin-ide/
/intellij
workspace.xml
*.versionsBackup
/idea/testData/debugger/tinyApp/classes*
@@ -68,3 +68,4 @@ distTmp/
outTmp/
/test.output
/kotlin-native/dist
kotlin-ide/

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

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

View File

@@ -2,6 +2,7 @@
<dictionary name="skuzmich">
<words>
<w>anyref</w>
<w>dataref</w>
<w>ushr</w>
<w>wasm</w>
</words>

2
.idea/kotlinc.xml generated
View File

@@ -13,6 +13,6 @@
</option>
</component>
<component name="KotlinCompilerSettings">
<option name="additionalArguments" value="-version -Xallow-kotlin-package -Xskip-metadata-version-check -Xread-deserialized-contracts" />
<option name="additionalArguments" value="-version -Xallow-kotlin-package -Xskip-metadata-version-check" />
</component>
</project>

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="" />

View File

@@ -1,20 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="IDEA" type="GradleRunConfiguration" factoryName="Gradle" singleton="true" folderName="IDEA">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="runIde" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<method />
</configuration>
</component>

View File

@@ -1,20 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="IDEA Ultimate" type="GradleRunConfiguration" factoryName="Gradle" folderName="IDEA">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="-P intellijUltimateEnabled" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="runUltimate" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<method />
</configuration>
</component>

View File

@@ -1,20 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="IDEA Ultimate (No ProcessCanceledException) " type="GradleRunConfiguration" factoryName="Gradle" folderName="IDEA">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="-PnoPCE" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="runUltimate" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<method />
</configuration>
</component>

View File

@@ -1,20 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="IDEA (No ProcessCanceledException)" type="GradleRunConfiguration" factoryName="Gradle" folderName="IDEA">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="-PnoPCE" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="runIde" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<method />
</configuration>
</component>

View File

@@ -1,19 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="IDEA (Not Internal)" type="GradleRunConfiguration" factoryName="Gradle" folderName="IDEA">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="-Pidea.is.internal=false" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="runIde" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
</configuration>
</component>

View File

@@ -4,7 +4,7 @@
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="--tests &quot;org.jetbrains.kotlin.gradle.CommonizerHierarchicalIT&quot; --tests &quot;org.jetbrains.kotlin.gradle.CommonizerIT&quot; --tests &quot;org.jetbrains.kotlin.commonizer.**&quot;" />
<option name="scriptParameters" value="--tests &quot;org.jetbrains.kotlin.gradle.CommonizerHierarchicalIT&quot; --tests &quot;org.jetbrains.kotlin.gradle.CommonizerIT&quot; --tests &quot;org.jetbrains.kotlin.commonizer.**&quot; --tests &quot;org.jetbrains.kotlin.gradle.native.CocoaPodsIT.testCinteropCommonization*&quot;" />
<option name="taskDescriptions">
<list />
</option>

View File

@@ -0,0 +1,23 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Test: Commonizer / Light" type="GradleRunConfiguration" factoryName="Gradle" folderName="Tests">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value=":native:kotlin-klib-commonizer-api:test" />
<option value=":native:kotlin-klib-commonizer:test" />
</list>
</option>
<option name="vmOptions" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>false</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<method v="2" />
</configuration>
</component>

File diff suppressed because it is too large Load Diff

View File

@@ -35,26 +35,30 @@ Support for multiplatform programming is one of Kotlins key benefits. It redu
## Editing Kotlin
* [Kotlin IntelliJ IDEA Plugin](https://kotlinlang.org/docs/tutorials/getting-started.html)
* [Kotlin IntelliJ IDEA Plugin](https://kotlinlang.org/docs/tutorials/getting-started.html) ([source code](https://github.com/JetBrains/intellij-community/tree/master/plugins/kotlin))
* [Kotlin Eclipse Plugin](https://kotlinlang.org/docs/tutorials/getting-started-eclipse.html)
* [Kotlin Sublime Text Package](https://github.com/vkostyukov/kotlin-sublime-package)
## Build environment requirements
In order to build Kotlin distribution you need to have:
This repository is using [Gradle toolchains](https://docs.gradle.org/current/userguide/toolchains.html) feature
to select and auto-provision required JDKs from [AdoptOpenJdk](https://adoptopenjdk.net) project.
- JDK 1.6, 1.7, 1.8 and 9
- Setup environment variables as following:
Unfortunately [AdoptOpenJdk](https://adoptopenjdk.net) project does not provide required JDK 1.6 and 1.7 images,
so you could either download them manually and provide path to installation via `JDK_16` and `JDK_17` environment variables or
use following SDK managers:
- [Asdf-vm](https://asdf-vm.com/)
- [Jabba](https://github.com/shyiko/jabba)
- [SDKMAN!](https://sdkman.io/)
JAVA_HOME="path to JDK 1.8"
JDK_16="path to JDK 1.6"
JDK_17="path to JDK 1.7"
JDK_18="path to JDK 1.8"
JDK_9="path to JDK 9"
Alternatively, it is still possible to only provide required JDKs via environment variables
(see [gradle.properties](./gradle.properties#L5) for supported variable names). To ensure Gradle uses only JDKs
from environmental variables - disable Gradle toolchain auto-detection by passing `-Porg.gradle.java.installations.auto-detect=false` option
(or put it into `$GRADLE_USER_HOME/gradle.properties`).
For local development, if you're not working on bytecode generation or the standard library, it's OK to have only JDK 1.8 and JDK 9 installed, and to point `JDK_16` and `JDK_17` environment variables to your JDK 1.8 installation.
You also can use [Gradle properties](https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties) to setup `JDK_*` variables.
For local development, if you're not working on the standard library, it's OK to avoid installing JDK 1.6 and JDK 1.7.
Add `kotlin.build.isObsoleteJdkOverrideEnabled=true` to the `local.properties` file, so build will only use JDK 1.8+. Note, that in this
case, build will have Gradle remote build cache misses for some tasks.
Note: The JDK 6 for MacOS is not available on Oracle's site. You can install it by
@@ -93,13 +97,10 @@ command line parameters on the first run:
- `clean` - clean build results
- `dist` - assembles the compiler distribution into `dist/kotlinc/` folder
- `ideaPlugin` - assembles the Kotlin IDEA plugin distribution into `dist/artifacts/ideaPlugin/Kotlin/` folder
- `install` - build and install all public artifacts into local maven repository
- `runIde` - build IDEA plugin and run IDEA with it
- `coreLibsTest` - build and run stdlib, reflect and kotlin-test tests
- `gradlePluginTest` - build and run gradle plugin tests
- `compilerTest` - build and run all compiler tests
- `ideaPluginTest` - build and run all IDEA plugin tests
To reproduce TeamCity build use `-Pteamcity=true` flag. Local builds don't run proguard and have jar compression disabled by default.
@@ -139,14 +140,6 @@ To be able to run tests from IntelliJ easily, check `Delegate IDE build/run acti
At this time, you can use the latest released `1.3.x` version of the Kotlin plugin for working with the code. To make sure you have the latest version installed, use `Tools` -> `Kotlin` -> `Configure Kotlin Plugin Updates`.
### Compiling and running
From this root project there are Run/Debug Configurations for running `IDEA` or the `Generate Compiler Tests` for example; so if you want to try out the latest and greatest IDEA plugin
* `VCS` -> `Git` -> `Pull`
* Run the `IDEA` run configuration in the project
* A child IntelliJ IDEA with the Kotlin plugin will then startup
### Dependency verification
We have a [dependencies verification](https://docs.gradle.org/current/userguide/dependency_verification.html) feature enabled in the

View File

@@ -25,6 +25,7 @@ import org.jetbrains.kotlin.context.withModule
import org.jetbrains.kotlin.context.withProject
import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.fir.builder.PsiHandlingMode
import org.jetbrains.kotlin.fir.builder.RawFirBuilder
import org.jetbrains.kotlin.fir.createSessionForTests
import org.jetbrains.kotlin.fir.java.FirJavaElementFinder
@@ -154,7 +155,7 @@ abstract class AbstractSimpleFileBenchmark {
.uniteWith(TopDownAnalyzerFacadeForJVM.AllJavaSourcesInProjectScope(env.project))
val session = createSessionForTests(env, scope)
val firProvider = session.firProvider as FirProviderImpl
val builder = RawFirBuilder(session, firProvider.kotlinScopeProvider)
val builder = RawFirBuilder(session, firProvider.kotlinScopeProvider, PsiHandlingMode.COMPILER)
val totalTransformer = FirTotalResolveProcessor(session)
val firFile = builder.buildFirFile(file).also(firProvider::recordFile)

View File

@@ -40,7 +40,7 @@ abstract class BuildMetaInfoFactory<T : BuildMetaInfo>(private val metaInfoClass
): T
fun create(args: CommonCompilerArguments): T {
val languageVersion = args.languageVersion?.let((LanguageVersion)::fromVersionString) ?: LanguageVersion.LATEST_STABLE
val languageVersion = args.languageVersion?.let { LanguageVersion.fromVersionString(it) } ?: LanguageVersion.LATEST_STABLE
return create(
isEAP = languageVersion.isPreRelease(),
@@ -51,7 +51,7 @@ abstract class BuildMetaInfoFactory<T : BuildMetaInfo>(private val metaInfoClass
ownVersion = OWN_VERSION,
coroutinesVersion = COROUTINES_VERSION,
multiplatformVersion = MULTIPLATFORM_VERSION,
metadataVersionArray = args.metadataVersion?.let((BinaryVersion)::parseVersionArray)
metadataVersionArray = args.metadataVersion?.let { BinaryVersion.parseVersionArray(it) }
)
}

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 if (oldData != null) {
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

@@ -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.incremental
import org.jetbrains.kotlin.name.FqName
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.io.Serializable
/**
* Changes to the classpath of the `KotlinCompile` task, used to compute the source files that need to be recompiled during an incremental
* run.
*/
sealed class ClasspathChanges : Serializable {
class Available() : ClasspathChanges() {
lateinit var lookupSymbols: List<LookupSymbol>
private set
lateinit var fqNames: List<FqName>
private set
constructor(lookupSymbols: List<LookupSymbol>, fqNames: List<FqName>) : this() {
this.lookupSymbols = lookupSymbols
this.fqNames = fqNames
}
private fun writeObject(out: ObjectOutputStream) {
out.writeInt(lookupSymbols.size)
lookupSymbols.forEach {
out.writeUTF(it.name)
out.writeUTF(it.scope)
}
out.writeInt(fqNames.size)
fqNames.forEach {
out.writeUTF(it.asString())
}
}
private fun readObject(ois: ObjectInputStream) {
val lookupSymbolsSize = ois.readInt()
val lookupSymbols = ArrayList<LookupSymbol>(lookupSymbolsSize)
repeat(lookupSymbolsSize) {
val name = ois.readUTF()
val scope = ois.readUTF()
lookupSymbols.add(LookupSymbol(name, scope))
}
this.lookupSymbols = lookupSymbols
val fqNamesSize = ois.readInt()
val fqNames = ArrayList<FqName>(fqNamesSize)
repeat(fqNamesSize) {
val fqNameString = ois.readUTF()
fqNames.add(FqName(fqNameString))
}
this.fqNames = fqNames
}
companion object {
private const val serialVersionUID = 0L
}
}
sealed class NotAvailable : ClasspathChanges() {
object UnableToCompute : NotAvailable()
object ForNonIncrementalRun : NotAvailable()
object ClasspathSnapshotIsDisabled : NotAvailable()
object ReservedForTestsOnly : NotAvailable()
object ForJSCompiler : NotAvailable()
}
}

View File

@@ -137,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)
}
}
@@ -269,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) {
@@ -283,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()
@@ -291,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)
}
}
@@ -317,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? =

View File

@@ -25,6 +25,7 @@ import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.build.GeneratedJvmClass
import org.jetbrains.kotlin.incremental.storage.*
import org.jetbrains.kotlin.inline.inlineFunctionsJvmNames
import org.jetbrains.kotlin.load.kotlin.FileBasedKotlinClass
import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader
import org.jetbrains.kotlin.load.kotlin.incremental.components.IncrementalCache
import org.jetbrains.kotlin.load.kotlin.incremental.components.JvmPackagePartProto
@@ -39,12 +40,11 @@ import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.org.objectweb.asm.*
import java.io.File
import java.security.MessageDigest
import java.util.*
val KOTLIN_CACHE_DIRECTORY_NAME = "kotlin"
open class IncrementalJvmCache(
private val targetDataRoot: File,
targetDataRoot: File,
targetOutputDir: File?,
pathConverter: FileToPathConverter
) : AbstractIncrementalCache<JvmClassName>(
@@ -114,32 +114,45 @@ open class IncrementalJvmCache(
}
open fun saveFileToCache(generatedClass: GeneratedJvmClass, changesCollector: ChangesCollector) {
val sourceFiles: Collection<File> = generatedClass.sourceFiles
val kotlinClass: LocalFileKotlinClass = generatedClass.outputClass
val className = kotlinClass.className
saveClassToCache(KotlinClassInfo.createFrom(generatedClass.outputClass), generatedClass.sourceFiles, changesCollector)
}
/**
* Saves information about the given (Kotlin) class to this cache, and stores changes between this class and its previous version into
* the given [ChangesCollector].
*
* @param kotlinClassInfo Information about a Kotlin class
* @param sourceFiles The source files that the given class was generated from, or `null` if this information is not available
* @param changesCollector A [ChangesCollector]
*/
fun saveClassToCache(kotlinClassInfo: KotlinClassInfo, sourceFiles: List<File>?, changesCollector: ChangesCollector) {
val className = kotlinClassInfo.className
dirtyOutputClassesMap.notDirty(className)
sourceFiles.forEach {
sourceToClassesMap.add(it, className)
if (sourceFiles != null) {
sourceFiles.forEach {
sourceToClassesMap.add(it, className)
}
internalNameToSource[className.internalName] = sourceFiles
}
internalNameToSource[className.internalName] = sourceFiles
if (kotlinClassInfo.classId.isLocal) return
if (kotlinClass.classId.isLocal) return
val header = kotlinClass.classHeader
when (header.kind) {
when (kotlinClassInfo.classKind) {
KotlinClassHeader.Kind.FILE_FACADE -> {
assert(sourceFiles.size == 1) { "Package part from several source files: $sourceFiles" }
if (sourceFiles != null) {
assert(sourceFiles.size == 1) { "Package part from several source files: $sourceFiles" }
}
packagePartMap.addPackagePart(className)
protoMap.process(kotlinClass, changesCollector)
constantsMap.process(kotlinClass, changesCollector)
inlineFunctionsMap.process(kotlinClass, changesCollector)
protoMap.process(kotlinClassInfo, changesCollector)
constantsMap.process(kotlinClassInfo, changesCollector)
inlineFunctionsMap.process(kotlinClassInfo, changesCollector)
}
KotlinClassHeader.Kind.MULTIFILE_CLASS -> {
val partNames = kotlinClass.classHeader.data?.toList()
?: throw AssertionError("Multifile class has no parts: ${kotlinClass.className}")
val partNames = kotlinClassInfo.classHeaderData.toList()
check(partNames.isNotEmpty()) { "Multifile class has no parts: $className" }
multifileFacadeToParts[className] = partNames
// When a class is replaced with a facade with the same name,
// the class' proto wouldn't ever be deleted,
@@ -154,25 +167,29 @@ open class IncrementalJvmCache(
internalNameToSource.remove(className.internalName)
// TODO NO_CHANGES? (delegates only)
constantsMap.process(kotlinClass, changesCollector)
inlineFunctionsMap.process(kotlinClass, changesCollector)
constantsMap.process(kotlinClassInfo, changesCollector)
inlineFunctionsMap.process(kotlinClassInfo, changesCollector)
}
KotlinClassHeader.Kind.MULTIFILE_CLASS_PART -> {
assert(sourceFiles.size == 1) { "Multifile class part from several source files: $sourceFiles" }
if (sourceFiles != null) {
assert(sourceFiles.size == 1) { "Multifile class part from several source files: $sourceFiles" }
}
packagePartMap.addPackagePart(className)
partToMultifileFacade.set(className.internalName, header.multifileClassName!!)
partToMultifileFacade.set(className.internalName, kotlinClassInfo.multifileClassName!!)
protoMap.process(kotlinClass, changesCollector)
constantsMap.process(kotlinClass, changesCollector)
inlineFunctionsMap.process(kotlinClass, changesCollector)
protoMap.process(kotlinClassInfo, changesCollector)
constantsMap.process(kotlinClassInfo, changesCollector)
inlineFunctionsMap.process(kotlinClassInfo, changesCollector)
}
KotlinClassHeader.Kind.CLASS -> {
assert(sourceFiles.size == 1) { "Class is expected to have only one source file: $sourceFiles" }
addToClassStorage(kotlinClass, sourceFiles.first())
if (sourceFiles != null) {
assert(sourceFiles.size == 1) { "Class is expected to have only one source file: $sourceFiles" }
addToClassStorage(kotlinClassInfo, sourceFiles.first())
}
protoMap.process(kotlinClass, changesCollector)
constantsMap.process(kotlinClass, changesCollector)
inlineFunctionsMap.process(kotlinClass, changesCollector)
protoMap.process(kotlinClassInfo, changesCollector)
constantsMap.process(kotlinClassInfo, changesCollector)
inlineFunctionsMap.process(kotlinClassInfo, changesCollector)
}
KotlinClassHeader.Kind.UNKNOWN, KotlinClassHeader.Kind.SYNTHETIC_CLASS -> {
}
@@ -185,7 +202,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)
}
@@ -278,8 +295,8 @@ open class IncrementalJvmCache(
private inner class ProtoMap(storageFile: File) : BasicStringMap<ProtoMapValue>(storageFile, ProtoMapValueExternalizer) {
@Synchronized
fun process(kotlinClass: LocalFileKotlinClass, changesCollector: ChangesCollector) {
return put(kotlinClass, changesCollector)
fun process(kotlinClassInfo: KotlinClassInfo, changesCollector: ChangesCollector) {
return put(kotlinClassInfo, changesCollector)
}
// A module mapping (.kotlin_module file) is stored in a cache,
@@ -295,20 +312,18 @@ open class IncrementalJvmCache(
}
@Synchronized
private fun put(kotlinClass: LocalFileKotlinClass, changesCollector: ChangesCollector) {
val header = kotlinClass.classHeader
val key = kotlinClass.className.internalName
private fun put(kotlinClassInfo: KotlinClassInfo, changesCollector: ChangesCollector) {
val key = kotlinClassInfo.className.internalName
val oldData = storage[key]
val newData = ProtoMapValue(
header.kind != KotlinClassHeader.Kind.CLASS,
BitEncoding.decodeBytes(header.data!!),
header.strings!!
kotlinClassInfo.classKind != KotlinClassHeader.Kind.CLASS,
BitEncoding.decodeBytes(kotlinClassInfo.classHeaderData),
kotlinClassInfo.classHeaderStrings
)
storage[key] = newData
val packageFqName = kotlinClass.className.packageFqName
changesCollector.collectProtoChanges(oldData?.toProtoData(packageFqName), newData.toProtoData(packageFqName))
val packageFqName = kotlinClassInfo.className.packageFqName
changesCollector.collectProtoChanges(oldData?.toProtoData(packageFqName), newData.toProtoData(packageFqName), packageProtoKey = key)
}
operator fun contains(className: JvmClassName): Boolean =
@@ -367,32 +382,18 @@ open class IncrementalJvmCache(
}
// todo: reuse code with InlineFunctionsMap?
private inner class ConstantsMap(storageFile: File) : BasicStringMap<Map<String, Any>>(storageFile, ConstantsMapExternalizer) {
private fun getConstantsMap(bytes: ByteArray): Map<String, Any> {
val result = HashMap<String, Any>()
ClassReader(bytes).accept(object : ClassVisitor(Opcodes.API_VERSION) {
override fun visitField(access: Int, name: String, desc: String, signature: String?, value: Any?): FieldVisitor? {
val staticFinal = Opcodes.ACC_STATIC or Opcodes.ACC_FINAL or Opcodes.ACC_PRIVATE
if (value != null && access and staticFinal == Opcodes.ACC_STATIC or Opcodes.ACC_FINAL) {
result[name] = value
}
return null
}
}, ClassReader.SKIP_CODE or ClassReader.SKIP_DEBUG or ClassReader.SKIP_FRAMES)
return result
}
private inner class ConstantsMap(storageFile: File) :
BasicStringMap<LinkedHashMap<String, Any>>(storageFile, LinkedHashMapExternalizer(StringExternalizer, ConstantExternalizer)) {
operator fun contains(className: JvmClassName): Boolean =
className.internalName in storage
@Synchronized
fun process(kotlinClass: LocalFileKotlinClass, changesCollector: ChangesCollector) {
val key = kotlinClass.className.internalName
fun process(kotlinClassInfo: KotlinClassInfo, changesCollector: ChangesCollector) {
val key = kotlinClassInfo.className.internalName
val oldMap = storage[key] ?: emptyMap()
val newMap = getConstantsMap(kotlinClass.fileContents)
val newMap = kotlinClassInfo.constantsMap
if (newMap.isNotEmpty()) {
storage[key] = newMap
} else {
@@ -401,8 +402,18 @@ open class IncrementalJvmCache(
for (const in oldMap.keys + newMap.keys) {
//Constant can be declared via companion object or via const field declaration
changesCollector.collectMemberIfValueWasChanged(kotlinClass.scopeFqName(companion = true), const, oldMap[const], newMap[const])
changesCollector.collectMemberIfValueWasChanged(kotlinClass.scopeFqName(companion = false), const, oldMap[const], newMap[const])
changesCollector.collectMemberIfValueWasChanged(
kotlinClassInfo.scopeFqName(companion = true),
const,
oldMap[const],
newMap[const]
)
changesCollector.collectMemberIfValueWasChanged(
kotlinClassInfo.scopeFqName(companion = false),
const,
oldMap[const],
newMap[const]
)
}
}
@@ -411,7 +422,7 @@ open class IncrementalJvmCache(
storage.remove(className.internalName)
}
override fun dumpValue(value: Map<String, Any>): String =
override fun dumpValue(value: LinkedHashMap<String, Any>): String =
value.dumpMap(Any::toString)
}
@@ -490,67 +501,20 @@ open class IncrementalJvmCache(
value.dumpCollection()
}
private fun addToClassStorage(kotlinClass: LocalFileKotlinClass, srcFile: File) {
val (nameResolver, proto) = JvmProtoBufUtil.readClassDataFrom(kotlinClass.classHeader.data!!, kotlinClass.classHeader.strings!!)
private fun addToClassStorage(classInfo: KotlinClassInfo, srcFile: File) {
val (nameResolver, proto) = JvmProtoBufUtil.readClassDataFrom(classInfo.classHeaderData, classInfo.classHeaderStrings)
addToClassStorage(proto, nameResolver, srcFile)
}
private inner class InlineFunctionsMap(storageFile: File) :
BasicStringMap<Map<String, Long>>(storageFile, StringToLongMapExternalizer) {
private fun getInlineFunctionsMap(header: KotlinClassHeader, bytes: ByteArray): Map<String, Long> {
val inlineFunctions = inlineFunctionsJvmNames(header)
if (inlineFunctions.isEmpty()) return emptyMap()
val result = HashMap<String, Long>()
var dummyVersion: Int = -1
ClassReader(bytes).accept(object : ClassVisitor(Opcodes.API_VERSION) {
override fun visit(
version: Int,
access: Int,
name: String?,
signature: String?,
superName: String?,
interfaces: Array<out String>?
) {
super.visit(version, access, name, signature, superName, interfaces)
dummyVersion = version
}
override fun visitMethod(
access: Int,
name: String,
desc: String,
signature: String?,
exceptions: Array<out String>?
): MethodVisitor? {
val dummyClassWriter = ClassWriter(0)
dummyClassWriter.visit(dummyVersion, 0, "dummy", null, AsmTypes.OBJECT_TYPE.internalName, null)
return object : MethodVisitor(Opcodes.API_VERSION, dummyClassWriter.visitMethod(0, name, desc, null, exceptions)) {
override fun visitEnd() {
val jvmName = name + desc
if (jvmName !in inlineFunctions) return
val dummyBytes = dummyClassWriter.toByteArray()!!
val hash = dummyBytes.md5()
result[jvmName] = hash
}
}
}
}, 0)
return result
}
BasicStringMap<LinkedHashMap<String, Long>>(storageFile, LinkedHashMapExternalizer(StringExternalizer, LongExternalizer)) {
@Synchronized
fun process(kotlinClass: LocalFileKotlinClass, changesCollector: ChangesCollector) {
val key = kotlinClass.className.internalName
fun process(kotlinClassInfo: KotlinClassInfo, changesCollector: ChangesCollector) {
val key = kotlinClassInfo.className.internalName
val oldMap = storage[key] ?: emptyMap()
val newMap = getInlineFunctionsMap(kotlinClass.classHeader, kotlinClass.fileContents)
val newMap = kotlinClassInfo.inlineFunctionsMap
if (newMap.isNotEmpty()) {
storage[key] = newMap
} else {
@@ -559,7 +523,7 @@ open class IncrementalJvmCache(
for (fn in oldMap.keys + newMap.keys) {
changesCollector.collectMemberIfValueWasChanged(
kotlinClass.scopeFqName(),
kotlinClassInfo.scopeFqName(),
functionNameBySignature(fn),
oldMap[fn],
newMap[fn]
@@ -576,7 +540,7 @@ open class IncrementalJvmCache(
storage.remove(className.internalName)
}
override fun dumpValue(value: Map<String, Long>): String =
override fun dumpValue(value: LinkedHashMap<String, Long>): String =
value.dumpMap { java.lang.Long.toHexString(it) }
}
}
@@ -602,13 +566,6 @@ sealed class ChangeInfo(val fqName: FqName) {
}
}
private fun LocalFileKotlinClass.scopeFqName(companion: Boolean = false) = when (classHeader.kind) {
KotlinClassHeader.Kind.CLASS -> {
className.fqNameForClassNameWithoutDollars.let { if (companion) it.child(DEFAULT_NAME_FOR_COMPANION_OBJECT) else it }
}
else -> className.packageFqName
}
fun ByteArray.md5(): Long {
val d = MessageDigest.getInstance("MD5").digest(this)!!
return ((d[0].toLong() and 0xFFL)
@@ -640,3 +597,125 @@ fun <K : Comparable<K>, V> Map<K, V>.dumpMap(dumpValue: (V) -> String): String =
@TestOnly
fun <T : Comparable<T>> Collection<T>.dumpCollection(): String =
"[${sorted().joinToString(", ", transform = Any::toString)}]"
/**
* Minimal information about a Kotlin class to compute recompilation-triggering changes during an incremental run of the `KotlinCompile`
* task (see [IncrementalJvmCache.saveClassToCache]).
*
* It's important that this class contain only the minimal required information, as it will be part of the classpath snapshot of the
* `KotlinCompile` task and the task needs to support compile avoidance. For example, this class should contain public method signatures,
* and should not contain private method signatures, or method implementations.
*/
class KotlinClassInfo constructor(
val classId: ClassId,
val classKind: KotlinClassHeader.Kind,
val classHeaderData: Array<String>, // Can be empty
val classHeaderStrings: Array<String>, // Can be empty
@Suppress("SpellCheckingInspection") val multifileClassName: String?,
val constantsMap: LinkedHashMap<String, Any>,
val inlineFunctionsMap: LinkedHashMap<String, Long>
) {
val className: JvmClassName by lazy { JvmClassName.byClassId(classId) }
fun scopeFqName(companion: Boolean = false) = when (classKind) {
KotlinClassHeader.Kind.CLASS -> {
className.fqNameForClassNameWithoutDollars.let { if (companion) it.child(DEFAULT_NAME_FOR_COMPANION_OBJECT) else it }
}
else -> className.packageFqName
}
companion object {
fun createFrom(kotlinClass: LocalFileKotlinClass): KotlinClassInfo {
return KotlinClassInfo(
kotlinClass.classId,
kotlinClass.classHeader.kind,
kotlinClass.classHeader.data ?: emptyArray(),
kotlinClass.classHeader.strings ?: emptyArray(),
kotlinClass.classHeader.multifileClassName,
getConstantsMap(kotlinClass.fileContents),
getInlineFunctionsMap(kotlinClass.classHeader, kotlinClass.fileContents)
)
}
/** Creates [KotlinClassInfo] from the given classContents, or returns `null` if the class is not a Kotlin class. */
fun tryCreateFrom(classContents: ByteArray): KotlinClassInfo? {
return FileBasedKotlinClass.create(classContents) { classId, _, classHeader, _ ->
KotlinClassInfo(
classId,
classHeader.kind,
classHeader.data ?: emptyArray(),
classHeader.strings ?: emptyArray(),
classHeader.multifileClassName,
getConstantsMap(classContents),
getInlineFunctionsMap(classHeader, classContents)
)
}
}
}
}
private fun getConstantsMap(bytes: ByteArray): LinkedHashMap<String, Any> {
val result = LinkedHashMap<String, Any>()
ClassReader(bytes).accept(object : ClassVisitor(Opcodes.API_VERSION) {
override fun visitField(access: Int, name: String, desc: String, signature: String?, value: Any?): FieldVisitor? {
val staticFinal = Opcodes.ACC_STATIC or Opcodes.ACC_FINAL or Opcodes.ACC_PRIVATE
if (value != null && access and staticFinal == Opcodes.ACC_STATIC or Opcodes.ACC_FINAL) {
result[name] = value
}
return null
}
}, ClassReader.SKIP_CODE or ClassReader.SKIP_DEBUG or ClassReader.SKIP_FRAMES)
return result
}
private fun getInlineFunctionsMap(header: KotlinClassHeader, bytes: ByteArray): LinkedHashMap<String, Long> {
val inlineFunctions = inlineFunctionsJvmNames(header)
if (inlineFunctions.isEmpty()) return LinkedHashMap()
val result = LinkedHashMap<String, Long>()
var dummyVersion: Int = -1
ClassReader(bytes).accept(object : ClassVisitor(Opcodes.API_VERSION) {
override fun visit(
version: Int,
access: Int,
name: String?,
signature: String?,
superName: String?,
interfaces: Array<out String>?
) {
super.visit(version, access, name, signature, superName, interfaces)
dummyVersion = version
}
override fun visitMethod(
access: Int,
name: String,
desc: String,
signature: String?,
exceptions: Array<out String>?
): MethodVisitor {
val dummyClassWriter = ClassWriter(0)
dummyClassWriter.visit(dummyVersion, 0, "dummy", null, AsmTypes.OBJECT_TYPE.internalName, null)
return object : MethodVisitor(Opcodes.API_VERSION, dummyClassWriter.visitMethod(0, name, desc, null, exceptions)) {
override fun visitEnd() {
val jvmName = name + desc
if (jvmName !in inlineFunctions) return
val dummyBytes = dummyClassWriter.toByteArray()!!
val hash = dummyBytes.md5()
result[jvmName] = hash
}
}
}
}, 0)
return result
}

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

@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.incremental
import com.intellij.openapi.diagnostic.Logger
import com.intellij.util.containers.MultiMap
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.incremental.components.LookupTracker
@@ -33,6 +34,8 @@ open class LookupStorage(
targetDataDir: File,
pathConverter: FileToPathConverter
) : BasicMapsOwner(targetDataDir) {
val LOG = Logger.getInstance("#org.jetbrains.kotlin.jps.build.KotlinBuilder")
companion object {
private val DELETED_TO_SIZE_TRESHOLD = 0.5
private val MINIMUM_GARBAGE_COLLECTIBLE_SIZE = 10000
@@ -41,36 +44,49 @@ 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
@Volatile
private var deletedCount: Int = 0
private var oldSize: Int = 0
init {
try {
if (countersFile.exists()) {
val lines = countersFile.readLines()
size = lines[0].toInt()
deletedCount = lines[1].toInt()
size = lines.firstOrNull()?.toIntOrNull() ?: throw IOException("$countersFile exists, but it is empty. " +
"Counters file is corrupted")
oldSize = size
}
} catch (e: IOException) {
throw e
} catch (e: Exception) {
throw IOException("Could not read $countersFile", e)
}
}
@Synchronized
fun get(lookupSymbol: LookupSymbol): Collection<String> {
val key = LookupSymbolKey(lookupSymbol.name, lookupSymbol.scope)
val fileIds = lookupMap[key] ?: return emptySet()
val paths = mutableSetOf<String>()
val filtered = mutableSetOf<Int>()
for (fileId in fileIds) {
val path = idToFile[fileId]?.path
if (path != null) {
paths.add(path)
filtered.add(fileId)
}
return fileIds.mapNotNull {
// null means it's outdated
idToFile[it]?.path
}
if (size > MINIMUM_GARBAGE_COLLECTIBLE_SIZE && filtered.size.toDouble() / fileIds.size.toDouble() < DELETED_TO_SIZE_TRESHOLD) {
lookupMap[key] = filtered
}
return paths
}
@Synchronized
@@ -81,8 +97,8 @@ open class LookupStorage(
val key = LookupSymbolKey(lookupSymbol.name, lookupSymbol.scope)
val paths = lookups[lookupSymbol]
val fileIds = paths.mapTo(TreeSet()) { pathToId[it]!! }
fileIds.addAll(lookupMap[key] ?: emptySet())
lookupMap[key] = fileIds
lookupMap.append(key, fileIds)
}
}
@@ -92,7 +108,6 @@ open class LookupStorage(
val id = fileToId[file] ?: continue
idToFile.remove(id)
fileToId.remove(file)
deletedCount++
}
}
@@ -103,7 +118,6 @@ open class LookupStorage(
}
size = 0
deletedCount = 0
super.clean()
}
@@ -111,18 +125,17 @@ open class LookupStorage(
@Synchronized
override fun flush(memoryCachesOnly: Boolean) {
try {
removeGarbageIfNeeded()
if (size != oldSize) {
if (size > 0) {
if (!countersFile.exists()) {
countersFile.parentFile.mkdirs()
countersFile.createNewFile()
}
if (size > 0) {
if (!countersFile.exists()) {
countersFile.parentFile.mkdirs()
countersFile.createNewFile()
countersFile.writeText("$size\n0")
}
countersFile.writeText("$size\n$deletedCount")
}
}
finally {
} finally {
super.flush(memoryCachesOnly)
}
}
@@ -137,13 +150,7 @@ open class LookupStorage(
return id
}
private fun removeGarbageIfNeeded(force: Boolean = false) {
if (force || (size > MINIMUM_GARBAGE_COLLECTIBLE_SIZE && deletedCount.toDouble() / size > DELETED_TO_SIZE_TRESHOLD)) {
doRemoveGarbage()
}
}
private fun doRemoveGarbage() {
private fun removeGarbageForTests() {
for (hash in lookupMap.keys) {
lookupMap[hash] = lookupMap[hash]!!.filter { it in idToFile }.toSet()
}
@@ -153,7 +160,6 @@ open class LookupStorage(
idToFile.clean()
fileToId.clean()
size = 0
deletedCount = 0
for ((file, oldId) in oldFileToId.entries.sortedBy { it.key.path }) {
val newId = addFileIfNeeded(file)
@@ -165,15 +171,16 @@ open class LookupStorage(
if (fileIds.isEmpty()) {
lookupMap.remove(lookup)
}
else {
} else {
lookupMap[lookup] = fileIds
}
}
}
@TestOnly fun forceGC() {
removeGarbageIfNeeded(force = true)
@TestOnly
fun forceGC() {
removeGarbageForTests()
flush(false)
}

View File

@@ -1104,6 +1104,11 @@ open class ProtoCompareGenerated(
if (!checkEquals(old.setter, new.setter)) return false
}
if (old.hasDelegateMethod() != new.hasDelegateMethod()) return false
if (old.hasDelegateMethod()) {
if (!checkEquals(old.delegateMethod, new.delegateMethod)) return false
}
return true
}
@@ -2353,6 +2358,10 @@ fun JvmProtoBuf.JvmPropertySignature.hashCode(stringIndexes: (Int) -> Int, fqNam
hashCode = 31 * hashCode + setter.hashCode(stringIndexes, fqNameIndexes, typeById)
}
if (hasDelegateMethod()) {
hashCode = 31 * hashCode + delegateMethod.hashCode(stringIndexes, fqNameIndexes, typeById)
}
return hashCode
}

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

@@ -33,15 +33,19 @@ class CachingLazyStorage<K, V>(
private val valueExternalizer: DataExternalizer<V>
) : LazyStorage<K, V> {
private var storage: PersistentHashMap<K, V>? = null
private var isStorageFileExist = true
private fun getStorageIfExists(): PersistentHashMap<K, V>? {
if (storage != null) return storage
if (!isStorageFileExist) return null
if (storageFile.exists()) {
storage = createMap()
return storage
}
isStorageFileExist = false
return null
}

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()
@@ -27,6 +27,10 @@ internal class LookupMap(storage: File) : BasicMap<LookupSymbolKey, Collection<I
storage.append(LookupSymbolKey(name, scope), listOf(fileId))
}
fun append(lookup: LookupSymbolKey, fileIds: Collection<Int>) {
storage.append(lookup, fileIds)
}
operator fun get(key: LookupSymbolKey): Collection<Int>? = storage[key]
operator fun set(key: LookupSymbolKey, fileIds: Set<Int>) {

View File

@@ -17,27 +17,53 @@
package org.jetbrains.kotlin.incremental.storage
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
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()
@@ -68,13 +94,12 @@ object ProtoMapValueExternalizer : DataExternalizer<ProtoMapValue> {
}
}
abstract class StringMapExternalizer<T> : DataExternalizer<Map<String, T>> {
override fun save(output: DataOutput, map: Map<String, T>?) {
output.writeInt(map!!.size)
for ((key, value) in map.entries) {
IOUtil.writeString(key, output)
output.writeString(key)
writeValue(output, value)
}
}
@@ -84,7 +109,7 @@ abstract class StringMapExternalizer<T> : DataExternalizer<Map<String, T>> {
val map = HashMap<String, T>(size)
repeat(size) {
val name = IOUtil.readString(input)!!
val name = input.readString()
map[name] = readValue(input)
}
@@ -95,7 +120,6 @@ abstract class StringMapExternalizer<T> : DataExternalizer<Map<String, T>> {
protected abstract fun readValue(input: DataInput): T
}
object StringToLongMapExternalizer : StringMapExternalizer<Long>() {
override fun readValue(input: DataInput): Long = input.readLong()
@@ -104,58 +128,43 @@ object StringToLongMapExternalizer : StringMapExternalizer<Long>() {
}
}
object ConstantsMapExternalizer : DataExternalizer<Map<String, Any>> {
override fun save(output: DataOutput, map: Map<String, Any>?) {
output.writeInt(map!!.size)
for (name in map.keys.sorted()) {
IOUtil.writeString(name, output)
val value = map[name]!!
when (value) {
is Int -> {
output.writeByte(Kind.INT.ordinal)
output.writeInt(value)
}
is Float -> {
output.writeByte(Kind.FLOAT.ordinal)
output.writeFloat(value)
}
is Long -> {
output.writeByte(Kind.LONG.ordinal)
output.writeLong(value)
}
is Double -> {
output.writeByte(Kind.DOUBLE.ordinal)
output.writeDouble(value)
}
is String -> {
output.writeByte(Kind.STRING.ordinal)
IOUtil.writeString(value, output)
}
else -> throw IllegalStateException("Unexpected constant class: ${value::class.java}")
/** [DataExternalizer] for a Kotlin constant. */
object ConstantExternalizer : DataExternalizer<Any> {
override fun save(output: DataOutput, value: Any) {
when (value) {
is Int -> {
output.writeByte(Kind.INT.ordinal)
output.writeInt(value)
}
is Float -> {
output.writeByte(Kind.FLOAT.ordinal)
output.writeFloat(value)
}
is Long -> {
output.writeByte(Kind.LONG.ordinal)
output.writeLong(value)
}
is Double -> {
output.writeByte(Kind.DOUBLE.ordinal)
output.writeDouble(value)
}
is String -> {
output.writeByte(Kind.STRING.ordinal)
output.writeString(value)
}
else -> throw IllegalStateException("Unexpected constant class: ${value::class.java}")
}
}
override fun read(input: DataInput): Map<String, Any>? {
val size = input.readInt()
val map = HashMap<String, Any>(size)
repeat(size) {
val name = IOUtil.readString(input)!!
val kind = Kind.values()[input.readByte().toInt()]
val value: Any = when (kind) {
Kind.INT -> input.readInt()
Kind.FLOAT -> input.readFloat()
Kind.LONG -> input.readLong()
Kind.DOUBLE -> input.readDouble()
Kind.STRING -> IOUtil.readString(input)!!
}
map[name] = value
override fun read(input: DataInput): Any {
return when (Kind.values()[input.readByte().toInt()]) {
Kind.INT -> input.readInt()
Kind.FLOAT -> input.readFloat()
Kind.LONG -> input.readLong()
Kind.DOUBLE -> input.readDouble()
Kind.STRING -> input.readString()
}
return map
}
private enum class Kind {
@@ -164,22 +173,47 @@ object ConstantsMapExternalizer : DataExternalizer<Map<String, Any>> {
}
object IntExternalizer : DataExternalizer<Int> {
override fun save(output: DataOutput, value: Int) = output.writeInt(value)
override fun read(input: DataInput): Int = input.readInt()
}
override fun save(output: DataOutput, value: Int) {
output.writeInt(value)
object LongExternalizer : DataExternalizer<Long> {
override fun save(output: DataOutput, value: Long) = output.writeLong(value)
override fun read(input: DataInput): Long = input.readLong()
}
object StringExternalizer : DataExternalizer<String> {
override fun save(output: DataOutput, value: String) = IOUtil.writeString(value, output)
override fun read(input: DataInput): String = IOUtil.readString(input)
}
// Should be consistent with org.jetbrains.jps.incremental.storage.PathStringDescriptor for correct work of portable caches
object PathStringDescriptor : EnumeratorStringDescriptor() {
private const val PORTABLE_CACHES_PROPERTY = "org.jetbrains.jps.portable.caches"
private val PORTABLE_CACHES = java.lang.Boolean.getBoolean(PORTABLE_CACHES_PROPERTY)
override fun getHashCode(path: String): Int {
if (!PORTABLE_CACHES) return FileUtil.pathHashCode(path)
// On case insensitive OS hash calculated from value converted to lower case
return if (StringUtil.isEmpty(path)) 0 else FileUtil.toCanonicalPath(path).hashCode()
}
override fun isEqual(val1: String, val2: String?): Boolean {
if (!PORTABLE_CACHES) return FileUtil.pathsEqual(val1, val2)
// On case insensitive OS hash calculated from path converted to lower case
if (val1 == val2) return true
if (val2 == null) return false
val path1 = FileUtil.toCanonicalPath(val1)
val path2 = FileUtil.toCanonicalPath(val2)
return path1 == path2
}
}
object PathStringDescriptor : EnumeratorStringDescriptor() {
override fun getHashCode(value: String) = FileUtil.pathHashCode(value)
override fun isEqual(val1: String, val2: String?) = FileUtil.pathsEqual(val1, val2)
}
open class CollectionExternalizer<T>(
private val elementExternalizer: DataExternalizer<T>,
private val newCollection: () -> MutableCollection<T>
private val elementExternalizer: DataExternalizer<T>,
private val newCollection: () -> MutableCollection<T>
) : DataExternalizer<Collection<T>> {
override fun read(input: DataInput): Collection<T> {
val result = newCollection()
@@ -200,3 +234,69 @@ open class CollectionExternalizer<T>(
object StringCollectionExternalizer : CollectionExternalizer<String>(EnumeratorStringDescriptor(), { HashSet() })
object IntCollectionExternalizer : CollectionExternalizer<Int>(IntExternalizer, { HashSet() })
fun DataOutput.writeString(value: String) = StringExternalizer.save(this, value)
fun DataInput.readString(): String = StringExternalizer.read(this)
class ListExternalizer<T>(
private val elementExternalizer: DataExternalizer<T>
) : DataExternalizer<List<T>> {
override fun save(output: DataOutput, value: List<T>) {
output.writeInt(value.size)
value.forEach {
elementExternalizer.save(output, it)
}
}
override fun read(input: DataInput): List<T> {
val size = input.readInt()
val list = ArrayList<T>(size)
repeat(size) {
list.add(elementExternalizer.read(input))
}
return list
}
}
class LinkedHashMapExternalizer<K, V>(
private val keyExternalizer: DataExternalizer<K>,
private val valueExternalizer: DataExternalizer<V>
) : DataExternalizer<LinkedHashMap<K, V>> {
override fun save(output: DataOutput, map: LinkedHashMap<K, V>) {
output.writeInt(map.size)
for ((key, value) in map) {
keyExternalizer.save(output, key)
valueExternalizer.save(output, value)
}
}
override fun read(input: DataInput): LinkedHashMap<K, V> {
val size = input.readInt()
val map = LinkedHashMap<K, V>(size)
repeat(size) {
val key = keyExternalizer.read(input)
val value = valueExternalizer.read(input)
map[key] = value
}
return map
}
}
class NullableValueExternalizer<T>(private val valueExternalizer: DataExternalizer<T>) : DataExternalizer<T> {
override fun save(output: DataOutput, value: T?) {
output.writeBoolean(value != null)
value?.let {
valueExternalizer.save(output, it)
}
}
override fun read(input: DataInput): T? {
return if (input.readBoolean()) {
valueExternalizer.read(input)
} else null
}
}

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

@@ -3443,6 +3443,34 @@ public final class DebugJvmProtoBuf {
* <code>optional .org.jetbrains.kotlin.metadata.jvm.JvmMethodSignature setter = 4;</code>
*/
org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignatureOrBuilder getSetterOrBuilder();
/**
* <code>optional .org.jetbrains.kotlin.metadata.jvm.JvmMethodSignature delegate_method = 5;</code>
*
* <pre>
* The delegate field of delegated properties may be optimized out; `getDelegate` should
* then call this method instead
* </pre>
*/
boolean hasDelegateMethod();
/**
* <code>optional .org.jetbrains.kotlin.metadata.jvm.JvmMethodSignature delegate_method = 5;</code>
*
* <pre>
* The delegate field of delegated properties may be optimized out; `getDelegate` should
* then call this method instead
* </pre>
*/
org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature getDelegateMethod();
/**
* <code>optional .org.jetbrains.kotlin.metadata.jvm.JvmMethodSignature delegate_method = 5;</code>
*
* <pre>
* The delegate field of delegated properties may be optimized out; `getDelegate` should
* then call this method instead
* </pre>
*/
org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignatureOrBuilder getDelegateMethodOrBuilder();
}
/**
* Protobuf type {@code org.jetbrains.kotlin.metadata.jvm.JvmPropertySignature}
@@ -3548,6 +3576,19 @@ public final class DebugJvmProtoBuf {
bitField0_ |= 0x00000008;
break;
}
case 42: {
org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature.Builder subBuilder = null;
if (((bitField0_ & 0x00000010) == 0x00000010)) {
subBuilder = delegateMethod_.toBuilder();
}
delegateMethod_ = input.readMessage(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature.PARSER, extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(delegateMethod_);
delegateMethod_ = subBuilder.buildPartial();
}
bitField0_ |= 0x00000010;
break;
}
}
}
} catch (org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException e) {
@@ -3684,11 +3725,48 @@ public final class DebugJvmProtoBuf {
return setter_;
}
public static final int DELEGATE_METHOD_FIELD_NUMBER = 5;
private org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature delegateMethod_;
/**
* <code>optional .org.jetbrains.kotlin.metadata.jvm.JvmMethodSignature delegate_method = 5;</code>
*
* <pre>
* The delegate field of delegated properties may be optimized out; `getDelegate` should
* then call this method instead
* </pre>
*/
public boolean hasDelegateMethod() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.jvm.JvmMethodSignature delegate_method = 5;</code>
*
* <pre>
* The delegate field of delegated properties may be optimized out; `getDelegate` should
* then call this method instead
* </pre>
*/
public org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature getDelegateMethod() {
return delegateMethod_;
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.jvm.JvmMethodSignature delegate_method = 5;</code>
*
* <pre>
* The delegate field of delegated properties may be optimized out; `getDelegate` should
* then call this method instead
* </pre>
*/
public org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignatureOrBuilder getDelegateMethodOrBuilder() {
return delegateMethod_;
}
private void initFields() {
field_ = org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmFieldSignature.getDefaultInstance();
syntheticMethod_ = org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature.getDefaultInstance();
getter_ = org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature.getDefaultInstance();
setter_ = org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature.getDefaultInstance();
delegateMethod_ = org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature.getDefaultInstance();
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
@@ -3715,6 +3793,9 @@ public final class DebugJvmProtoBuf {
if (((bitField0_ & 0x00000008) == 0x00000008)) {
output.writeMessage(4, setter_);
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
output.writeMessage(5, delegateMethod_);
}
getUnknownFields().writeTo(output);
}
@@ -3740,6 +3821,10 @@ public final class DebugJvmProtoBuf {
size += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeMessageSize(4, setter_);
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
size += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeMessageSize(5, delegateMethod_);
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
@@ -3853,6 +3938,7 @@ public final class DebugJvmProtoBuf {
getSyntheticMethodFieldBuilder();
getGetterFieldBuilder();
getSetterFieldBuilder();
getDelegateMethodFieldBuilder();
}
}
private static Builder create() {
@@ -3885,6 +3971,12 @@ public final class DebugJvmProtoBuf {
setterBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000008);
if (delegateMethodBuilder_ == null) {
delegateMethod_ = org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature.getDefaultInstance();
} else {
delegateMethodBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000010);
return this;
}
@@ -3945,6 +4037,14 @@ public final class DebugJvmProtoBuf {
} else {
result.setter_ = setterBuilder_.build();
}
if (((from_bitField0_ & 0x00000010) == 0x00000010)) {
to_bitField0_ |= 0x00000010;
}
if (delegateMethodBuilder_ == null) {
result.delegateMethod_ = delegateMethod_;
} else {
result.delegateMethod_ = delegateMethodBuilder_.build();
}
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
@@ -3973,6 +4073,9 @@ public final class DebugJvmProtoBuf {
if (other.hasSetter()) {
mergeSetter(other.getSetter());
}
if (other.hasDelegateMethod()) {
mergeDelegateMethod(other.getDelegateMethod());
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
@@ -4500,6 +4603,167 @@ public final class DebugJvmProtoBuf {
return setterBuilder_;
}
private org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature delegateMethod_ = org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature.getDefaultInstance();
private org.jetbrains.kotlin.protobuf.SingleFieldBuilder<
org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature, org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature.Builder, org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignatureOrBuilder> delegateMethodBuilder_;
/**
* <code>optional .org.jetbrains.kotlin.metadata.jvm.JvmMethodSignature delegate_method = 5;</code>
*
* <pre>
* The delegate field of delegated properties may be optimized out; `getDelegate` should
* then call this method instead
* </pre>
*/
public boolean hasDelegateMethod() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.jvm.JvmMethodSignature delegate_method = 5;</code>
*
* <pre>
* The delegate field of delegated properties may be optimized out; `getDelegate` should
* then call this method instead
* </pre>
*/
public org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature getDelegateMethod() {
if (delegateMethodBuilder_ == null) {
return delegateMethod_;
} else {
return delegateMethodBuilder_.getMessage();
}
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.jvm.JvmMethodSignature delegate_method = 5;</code>
*
* <pre>
* The delegate field of delegated properties may be optimized out; `getDelegate` should
* then call this method instead
* </pre>
*/
public Builder setDelegateMethod(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature value) {
if (delegateMethodBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
delegateMethod_ = value;
onChanged();
} else {
delegateMethodBuilder_.setMessage(value);
}
bitField0_ |= 0x00000010;
return this;
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.jvm.JvmMethodSignature delegate_method = 5;</code>
*
* <pre>
* The delegate field of delegated properties may be optimized out; `getDelegate` should
* then call this method instead
* </pre>
*/
public Builder setDelegateMethod(
org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature.Builder builderForValue) {
if (delegateMethodBuilder_ == null) {
delegateMethod_ = builderForValue.build();
onChanged();
} else {
delegateMethodBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000010;
return this;
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.jvm.JvmMethodSignature delegate_method = 5;</code>
*
* <pre>
* The delegate field of delegated properties may be optimized out; `getDelegate` should
* then call this method instead
* </pre>
*/
public Builder mergeDelegateMethod(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature value) {
if (delegateMethodBuilder_ == null) {
if (((bitField0_ & 0x00000010) == 0x00000010) &&
delegateMethod_ != org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature.getDefaultInstance()) {
delegateMethod_ =
org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature.newBuilder(delegateMethod_).mergeFrom(value).buildPartial();
} else {
delegateMethod_ = value;
}
onChanged();
} else {
delegateMethodBuilder_.mergeFrom(value);
}
bitField0_ |= 0x00000010;
return this;
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.jvm.JvmMethodSignature delegate_method = 5;</code>
*
* <pre>
* The delegate field of delegated properties may be optimized out; `getDelegate` should
* then call this method instead
* </pre>
*/
public Builder clearDelegateMethod() {
if (delegateMethodBuilder_ == null) {
delegateMethod_ = org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature.getDefaultInstance();
onChanged();
} else {
delegateMethodBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000010);
return this;
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.jvm.JvmMethodSignature delegate_method = 5;</code>
*
* <pre>
* The delegate field of delegated properties may be optimized out; `getDelegate` should
* then call this method instead
* </pre>
*/
public org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature.Builder getDelegateMethodBuilder() {
bitField0_ |= 0x00000010;
onChanged();
return getDelegateMethodFieldBuilder().getBuilder();
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.jvm.JvmMethodSignature delegate_method = 5;</code>
*
* <pre>
* The delegate field of delegated properties may be optimized out; `getDelegate` should
* then call this method instead
* </pre>
*/
public org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignatureOrBuilder getDelegateMethodOrBuilder() {
if (delegateMethodBuilder_ != null) {
return delegateMethodBuilder_.getMessageOrBuilder();
} else {
return delegateMethod_;
}
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.jvm.JvmMethodSignature delegate_method = 5;</code>
*
* <pre>
* The delegate field of delegated properties may be optimized out; `getDelegate` should
* then call this method instead
* </pre>
*/
private org.jetbrains.kotlin.protobuf.SingleFieldBuilder<
org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature, org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature.Builder, org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignatureOrBuilder>
getDelegateMethodFieldBuilder() {
if (delegateMethodBuilder_ == null) {
delegateMethodBuilder_ = new org.jetbrains.kotlin.protobuf.SingleFieldBuilder<
org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature, org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignature.Builder, org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.JvmMethodSignatureOrBuilder>(
getDelegateMethod(),
getParentForChildren(),
isClean());
delegateMethod_ = null;
}
return delegateMethodBuilder_;
}
// @@protoc_insertion_point(builder_scope:org.jetbrains.kotlin.metadata.jvm.JvmPropertySignature)
}
@@ -4740,7 +5004,7 @@ public final class DebugJvmProtoBuf {
"\020DESC_TO_CLASS_ID\020\002\"<\n\022JvmMethodSignatur" +
"e\022\022\n\004name\030\001 \001(\005B\004\230\265\030\001\022\022\n\004desc\030\002 \001(\005B\004\230\265\030" +
"\001\";\n\021JvmFieldSignature\022\022\n\004name\030\001 \001(\005B\004\230\265" +
"\030\001\022\022\n\004desc\030\002 \001(\005B\004\230\265\030\001\"\272\002\n\024JvmPropertySi" +
"\030\001\022\022\n\004desc\030\002 \001(\005B\004\230\265\030\001\"\212\003\n\024JvmPropertySi" +
"gnature\022C\n\005field\030\001 \001(\01324.org.jetbrains.k" +
"otlin.metadata.jvm.JvmFieldSignature\022O\n\020",
"synthetic_method\030\002 \001(\01325.org.jetbrains.k" +
@@ -4748,11 +5012,13 @@ public final class DebugJvmProtoBuf {
"\006getter\030\003 \001(\01325.org.jetbrains.kotlin.met" +
"adata.jvm.JvmMethodSignature\022E\n\006setter\030\004" +
" \001(\01325.org.jetbrains.kotlin.metadata.jvm" +
".JvmMethodSignature\022N\n\017delegate_method\030\005" +
" \001(\01325.org.jetbrains.kotlin.metadata.jvm" +
".JvmMethodSignature:\200\001\n\025constructor_sign" +
"ature\022*.org.jetbrains.kotlin.metadata.Co" +
"nstructor\030d \001(\01325.org.jetbrains.kotlin.m" +
"nstructor\030d \001(\01325.org.jetbrains.kotlin.m",
"etadata.jvm.JvmMethodSignature:x\n\020method" +
"_signature\022\'.org.jetbrains.kotlin.metada",
"_signature\022\'.org.jetbrains.kotlin.metada" +
"ta.Function\030d \001(\01325.org.jetbrains.kotlin" +
".metadata.jvm.JvmMethodSignature:O\n\030lamb" +
"da_class_origin_name\022\'.org.jetbrains.kot" +
@@ -4760,9 +5026,9 @@ public final class DebugJvmProtoBuf {
"perty_signature\022\'.org.jetbrains.kotlin.m" +
"etadata.Property\030d \001(\01327.org.jetbrains.k" +
"otlin.metadata.jvm.JvmPropertySignature:" +
"9\n\005flags\022\'.org.jetbrains.kotlin.metadata" +
"9\n\005flags\022\'.org.jetbrains.kotlin.metadata",
".Property\030e \001(\005:\0010:g\n\017type_annotation\022#." +
"org.jetbrains.kotlin.metadata.Type\030d \003(\013",
"org.jetbrains.kotlin.metadata.Type\030d \003(\013" +
"2).org.jetbrains.kotlin.metadata.Annotat" +
"ion:3\n\006is_raw\022#.org.jetbrains.kotlin.met" +
"adata.Type\030e \001(\010:z\n\031type_parameter_annot" +
@@ -4770,9 +5036,9 @@ public final class DebugJvmProtoBuf {
"peParameter\030d \003(\0132).org.jetbrains.kotlin" +
".metadata.Annotation:E\n\021class_module_nam" +
"e\022$.org.jetbrains.kotlin.metadata.Class\030" +
"e \001(\005B\004\230\265\030\001:k\n\024class_local_variable\022$.or" +
"e \001(\005B\004\230\265\030\001:k\n\024class_local_variable\022$.or",
"g.jetbrains.kotlin.metadata.Class\030f \003(\0132" +
"\'.org.jetbrains.kotlin.metadata.Property",
"\'.org.jetbrains.kotlin.metadata.Property" +
":P\n\034anonymous_object_origin_name\022$.org.j" +
"etbrains.kotlin.metadata.Class\030g \001(\005B\004\230\265" +
"\030\001:@\n\017jvm_class_flags\022$.org.jetbrains.ko" +
@@ -4780,7 +5046,7 @@ public final class DebugJvmProtoBuf {
"module_name\022&.org.jetbrains.kotlin.metad" +
"ata.Package\030e \001(\005B\004\230\265\030\001:o\n\026package_local" +
"_variable\022&.org.jetbrains.kotlin.metadat" +
"a.Package\030f \003(\0132\'.org.jetbrains.kotlin.m" +
"a.Package\030f \003(\0132\'.org.jetbrains.kotlin.m",
"etadata.PropertyB\022B\020DebugJvmProtoBuf"
};
org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
@@ -4826,7 +5092,7 @@ public final class DebugJvmProtoBuf {
internal_static_org_jetbrains_kotlin_metadata_jvm_JvmPropertySignature_fieldAccessorTable = new
org.jetbrains.kotlin.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_org_jetbrains_kotlin_metadata_jvm_JvmPropertySignature_descriptor,
new java.lang.String[] { "Field", "SyntheticMethod", "Getter", "Setter", });
new java.lang.String[] { "Field", "SyntheticMethod", "Getter", "Setter", "DelegateMethod", });
constructorSignature.internalInit(descriptor.getExtensions().get(0));
methodSignature.internalInit(descriptor.getExtensions().get(1));
lambdaClassOriginName.internalInit(descriptor.getExtensions().get(2));

View File

@@ -1,7 +1,6 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.crypto.checksum.Checksum
import org.gradle.plugins.ide.idea.model.IdeaModel
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import proguard.gradle.ProGuardTask
buildscript {
@@ -30,7 +29,7 @@ buildscript {
dependencies {
bootstrapCompilerClasspath(kotlin("compiler-embeddable", bootstrapKotlinVersion))
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.30")
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.32")
classpath(kotlin("gradle-plugin", bootstrapKotlinVersion))
classpath(kotlin("serialization", bootstrapKotlinVersion))
classpath("org.jetbrains.dokka:dokka-gradle-plugin:0.9.17")
@@ -56,13 +55,6 @@ pill {
val isTeamcityBuild = project.kotlinBuildProperties.isTeamcityBuild
val configuredJdks: List<JdkId> =
getConfiguredJdks().also {
it.forEach { jdkId ->
logger.info("Using ${jdkId.majorVersion} home: ${jdkId.homeDir}")
}
}
val defaultSnapshotVersion: String by extra
val buildNumber by extra(findProperty("build.number")?.toString() ?: defaultSnapshotVersion)
val kotlinVersion by extra(
@@ -114,37 +106,6 @@ subprojects {
extra["kotlinNativeVersion"] = kotlinNativeVersionObject
}
// Work-around necessary to avoid setting null javaHome. Will be removed after support of lazy task configuration
val jdkNotFoundConst = "JDK NOT FOUND"
if (isTeamcityBuild) {
extra["JDK_16"] = jdkPath("1.6")
extra["JDK_17"] = jdkPath("1.7")
} else {
extra["JDK_16"] = jdkPath("1.6", "1.8")
extra["JDK_17"] = jdkPath("1.7", "1.8")
}
extra["JDK_18"] = jdkPath("1.8")
extra["JDK_9"] = jdkPath("9")
extra["JDK_10"] = jdkPath("10")
extra["JDK_11"] = jdkPath("11")
extra["JDK_15"] = jdkPath("15")
// allow opening the project without setting up all env variables (see KT-26413)
if (!kotlinBuildProperties.isInIdeaSync) {
checkJDK()
}
fun checkJDK() {
val missingEnvVars = JdkMajorVersion.values()
.filter { it.isMandatory() && extra[it.name] == jdkNotFoundConst }
.mapTo(ArrayList()) { it.name }
if (missingEnvVars.isNotEmpty()) {
throw GradleException("Required environment variables are missing: ${missingEnvVars.joinToString()}")
}
}
rootProject.apply {
from(rootProject.file("gradle/versions.gradle.kts"))
from(rootProject.file("gradle/report.gradle.kts"))
@@ -167,8 +128,9 @@ extra["versions.junit"] = "4.12"
extra["versions.javaslang"] = "2.0.6"
extra["versions.ant"] = "1.10.7"
extra["versions.android"] = "2.3.1"
extra["versions.kotlinx-coroutines-core"] = "1.3.8"
extra["versions.kotlinx-coroutines-jdk8"] = "1.3.8"
extra["versions.kotlinx-coroutines-core"] = "1.5.0"
extra["versions.kotlinx-coroutines-core-jvm"] = "1.5.0"
extra["versions.kotlinx-coroutines-jdk8"] = "1.5.0"
extra["versions.json"] = "20160807"
extra["versions.native-platform"] = "0.14"
extra["versions.robolectric"] = "4.0"
@@ -186,12 +148,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.30-dev-1916"
extra["versions.kotlin-native"] = "1.6.0-dev-2972"
}
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)
val useJvmFir by extra(project.kotlinBuildProperties.useFir)
val intellijSeparateSdks = project.getBooleanProperty("intellijSeparateSdks") ?: false
@@ -200,7 +159,7 @@ extra["intellijSeparateSdks"] = intellijSeparateSdks
extra["IntellijCoreDependencies"] =
listOf(
"asm-all-8.0.1",
"asm-all-9.0",
"guava",
"jdom",
"jna",
@@ -252,6 +211,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",
@@ -333,6 +293,11 @@ extra["compilerArtifactsForIde"] = listOf(
":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",
@@ -350,15 +315,7 @@ extra["compilerArtifactsForIde"] = listOf(
// 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-fir:compileKotlin",
":plugins:uast-kotlin-fir:compileTestKotlin"
":kotlin-gradle-plugin:compileKotlin"
)
val tasksWithWarnings: List<String> by extra
@@ -383,7 +340,12 @@ val coreLibProjects = listOfNotNull(
val projectsWithDisabledFirBootstrap = coreLibProjects + listOf(
":kotlin-gradle-plugin",
":kotlinx-metadata",
":kotlinx-metadata-jvm"
":kotlinx-metadata-jvm",
// For some reason stdlib isn't imported correctly for this module
// Probably it's related to kotlin-test module usage
":kotlin-gradle-statistics",
// Requires serialization plugin
":wasm:wasm.ir"
)
val gradlePluginProjects = listOf(
@@ -417,8 +379,6 @@ fun Task.listConfigurationContents(configName: String) {
}
}
val defaultJvmTarget = "1.8"
val defaultJavaHome = jdkPath(if (Platform[203].orHigher()) "11" else defaultJvmTarget)
val ignoreTestFailures by extra(project.kotlinBuildProperties.ignoreTestFailures)
allprojects {
@@ -464,21 +424,25 @@ allprojects {
}
}
jvmTarget = defaultJvmTarget
javaHome = defaultJavaHome
// There are problems with common build dir:
// - some tests (in particular js and binary-compatibility-validator depend on the fixed (default) location
// - idea seems unable to exclude common buildDir from indexing
// therefore it is disabled by default
// buildDir = File(commonBuildDir, project.name)
project.configureJvmDefaultToolchain()
plugins.withId("java-base") {
project.configureShadowJarSubstitutionInCompileClasspath()
}
configureJvmProject(javaHome!!, jvmTarget!!)
tasks.withType<JavaCompile> {
options.compilerArgs.add("-Xlint:deprecation")
options.compilerArgs.add("-Xlint:unchecked")
options.compilerArgs.add("-Werror")
}
val commonCompilerArgs = listOfNotNull(
"-Xopt-in=kotlin.RequiresOptIn",
"-Xread-deserialized-contracts",
"-progressive".takeIf { hasProperty("test.progressive.mode") }
)
@@ -494,34 +458,26 @@ allprojects {
"-Xjvm-default=compatibility",
"-Xno-optimized-callable-references",
"-Xno-kotlin-nothing-value-exception",
"-Xnormalize-constructor-calls=enable"
"-Xskip-runtime-version-check",
"-Xsuppress-deprecated-jvm-target-warning" // Remove as soon as there are no modules for JDK 1.6 & 1.7
)
tasks.withType<org.jetbrains.kotlin.gradle.dsl.KotlinJvmCompile> {
kotlinOptions {
freeCompilerArgs = commonCompilerArgs + jvmCompilerArgs
if (useJvmIrBackend) {
useIR = true
}
if (useJvmFir && this@allprojects.name !in projectsWithDisabledFirBootstrap) {
if (useJvmFir && this@allprojects.path !in projectsWithDisabledFirBootstrap) {
freeCompilerArgs += "-Xuse-fir"
freeCompilerArgs += "-Xabi-stability=stable"
}
}
}
if (!kotlinBuildProperties.isInJpsBuildIdeaSync && !kotlinBuildProperties.useFir && !kotlinBuildProperties.disableWerror) {
// For compiler and stdlib, allWarningsAsErrors is configured in the corresponding "root" projects
// (compiler/build.gradle.kts and libraries/commonConfiguration.gradle).
val projectsWithWarningsAsErrors = listOf("core", "plugins").map { File(it).absoluteFile }
if (projectsWithWarningsAsErrors.any(projectDir::startsWith)) {
tasks.withType<org.jetbrains.kotlin.gradle.dsl.KotlinJvmCompile> {
if (path !in tasksWithWarnings) {
kotlinOptions {
allWarningsAsErrors = true
}
if (!kotlinBuildProperties.disableWerror) {
tasks.withType<org.jetbrains.kotlin.gradle.dsl.KotlinJvmCompile> {
if (path !in tasksWithWarnings) {
kotlinOptions {
allWarningsAsErrors = true
}
}
}
@@ -575,11 +531,6 @@ allprojects {
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")
configureJvmProject(javaHome!!, jvmTarget!!)
} // else we will actually fail during the first task execution. We could not fail before configuration is done due to impact on import in IDE
fun File.toProjectRootRelativePathOrSelf() = (relativeToOrNull(rootDir)?.takeUnless { it.startsWith("..") } ?: this).path
fun FileCollection.printClassPath(role: String) =
@@ -815,6 +766,7 @@ tasks {
register("distTest") {
dependsOn("compilerTest")
dependsOn("frontendApiTests")
dependsOn("toolsTest")
dependsOn("gradlePluginTest")
dependsOn("examplesTest")
@@ -876,14 +828,23 @@ 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")
dependsOn(
@@ -1083,66 +1044,6 @@ configure<IdeaModel> {
}
}
fun jdkPathOrNull(version: String): String? {
val jdkName = "JDK_${version.replace(".", "")}"
val jdkMajorVersion = JdkMajorVersion.valueOf(jdkName)
return configuredJdks.find { it.majorVersion == jdkMajorVersion }?.homeDir?.canonicalPath
}
fun jdkPath(version: String, vararg replacementVersions: String): String {
return jdkPathOrNull(version) ?: run {
replacementVersions.asSequence().map { jdkPathOrNull(it) }.find { it != null }
} ?: jdkNotFoundConst
}
fun Project.configureJvmProject(javaHome: String, javaVersion: String) {
val currentJavaHome = File(System.getProperty("java.home")!!).canonicalPath
val shouldFork = !currentJavaHome.startsWith(File(javaHome).canonicalPath)
tasks.withType<JavaCompile> {
if (name != "compileJava9Java") {
sourceCompatibility = javaVersion
targetCompatibility = javaVersion
options.isFork = shouldFork
options.forkOptions.javaHome = file(javaHome)
options.compilerArgs.add("-proc:none")
options.encoding = "UTF-8"
}
}
tasks.withType<KotlinCompile> {
kotlinOptions.jdkHome = javaHome.takeUnless { kotlinBuildProperties.suppressJdkHomeWarning }
kotlinOptions.jvmTarget = javaVersion
kotlinOptions.freeCompilerArgs += "-Xjvm-default=compatibility"
}
tasks.withType<Test> {
executable = File(javaHome, "bin/java").canonicalPath
}
plugins.withId("java-base") {
configureShadowJarSubstitutionInCompileClasspath()
}
}
fun Project.configureShadowJarSubstitutionInCompileClasspath() {
val substitutionMap = mapOf(":kotlin-reflect" to ":kotlin-reflect-api")
fun configureSubstitution(substitution: DependencySubstitution) {
val requestedProject = (substitution.requested as? ProjectComponentSelector)?.projectPath ?: return
val replacementProject = substitutionMap[requestedProject] ?: return
substitution.useTarget(project(replacementProject), "Non-default shadow jars should not be used in compile classpath")
}
sourceSets.all {
for (configName in listOf(compileOnlyConfigurationName, compileClasspathConfigurationName)) {
configurations.getByName(configName).resolutionStrategy.dependencySubstitution {
all(::configureSubstitution)
}
}
}
}
tasks.register("findShadowJarsInClasspath") {
doLast {
fun Collection<File>.printSorted(indent: String = " ") {
@@ -1210,3 +1111,19 @@ 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"
}
}
afterEvaluate {
val cacheRedirectorEnabled = findProperty("cacheRedirectorEnabled")?.toString()?.toBoolean() == true
if (cacheRedirectorEnabled) {
rootProject.plugins.withType(org.jetbrains.kotlin.gradle.targets.js.yarn.YarnPlugin::class.java) {
rootProject.the<org.jetbrains.kotlin.gradle.targets.js.yarn.YarnRootExtension>().downloadBaseUrl =
"https://cache-redirector.jetbrains.com/github.com/yarnpkg/yarn/releases/download"
}
}
}

View File

@@ -22,7 +22,7 @@ buildscript {
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.30")
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.32")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${project.bootstrapKotlinVersion}")
classpath("org.jetbrains.kotlin:kotlin-sam-with-receiver:${project.bootstrapKotlinVersion}")
}
@@ -143,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.30")
implementation("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.32")
implementation("com.gradle.publish:plugin-publish-plugin:0.14.0")
implementation("net.rubygrapefruit:native-platform:${property("versions.native-platform")}")
@@ -155,10 +155,10 @@ dependencies {
implementation("net.sf.proguard:proguard-gradle:6.2.2")
implementation("org.jetbrains.intellij.deps:asm-all:8.0.1")
implementation("gradle.plugin.org.jetbrains.gradle.plugin.idea-ext:gradle-idea-ext:0.5")
implementation("gradle.plugin.org.jetbrains.gradle.plugin.idea-ext:gradle-idea-ext:1.0.1")
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

@@ -79,7 +79,6 @@ 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
/**
* Special repository for annotations.jar required for idea runtime only.

View File

@@ -19,6 +19,17 @@ 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.disableWerror: Boolean
get() = getBoolean("kotlin.build.disable.werror") || useFir || isInJpsBuildIdeaSync || getBoolean("test.progressive.mode")
val KotlinBuildProperties.suppressJdkHomeWarning: Boolean get() = getBoolean("kotlin.suppress.jdkHome.warning", false)
val KotlinBuildProperties.pathToKotlinModularizedTestData: String?
get() = getOrNull("kotlin.fir.modularized.testdata.kotlin") as? String
val KotlinBuildProperties.pathToIntellijModularizedTestData: String?
get() = getOrNull("kotlin.fir.modularized.testdata.intellij") as? String
val KotlinBuildProperties.pathToYoutrackModularizedTestData: String?
get() = getOrNull("kotlin.fir.modularized.testdata.youtrack") as? String
val KotlinBuildProperties.isObsoleteJdkOverrideEnabled: Boolean
get() = getBoolean("kotlin.build.isObsoleteJdkOverrideEnabled", false)

View File

@@ -4,32 +4,36 @@
*/
import groovy.lang.Closure
import org.gradle.api.JavaVersion
import org.gradle.api.file.FileCollection
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.*
import org.gradle.internal.jvm.Jvm
import org.gradle.internal.jvm.inspection.JvmVersionDetector
import org.gradle.jvm.toolchain.JavaLauncher
import org.gradle.kotlin.dsl.property
import proguard.ClassSpecification
import java.io.File
import javax.inject.Inject
@CacheableTask
open class CacheableProguardTask @Inject constructor(
private val jvmVersionDetector: JvmVersionDetector
) : proguard.gradle.ProGuardTask() {
open class CacheableProguardTask : proguard.gradle.ProGuardTask() {
@Internal
var jdkHome: File? = null
@get:Internal
val javaLauncher: Property<JavaLauncher> = project.objects.property()
@get:Internal
val jdkHomePath: Provider<File> = javaLauncher.map { it.metadata.installationPath.asFile }
@get:Optional
@get:Input
internal val jdkMajorVersion: String?
get() = jdkHome?.let { jvmVersionDetector.getJavaVersion(Jvm.forHome(jdkHome)) }?.majorVersion
internal val jdkMajorVersion: Provider<JavaVersion> = javaLauncher.map {
JavaVersion.toVersion(it.metadata.languageVersion.toString())
}
@CompileClasspath
override fun getLibraryJarFileCollection(): FileCollection = super.getLibraryJarFileCollection().filter { libraryFile ->
jdkHome?.let { !libraryFile.absoluteFile.startsWith(it.absoluteFile) } ?: true
}
override fun getLibraryJarFileCollection(): FileCollection = super.getLibraryJarFileCollection()
.filter { libraryFile ->
jdkHomePath.orNull?.let { !libraryFile.absoluteFile.startsWith(it.absoluteFile) } ?: true
}
@InputFiles
@PathSensitive(PathSensitivity.RELATIVE)

View File

@@ -89,4 +89,4 @@ 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")
get() = rootDir.resolve("intellij/community").takeIf { it.isDirectory } ?: rootDir.resolve("intellij")

View File

@@ -0,0 +1,144 @@
/*
* 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 com.github.jengelman.gradle.plugins.shadow.relocation.RelocateClassContext
import com.github.jengelman.gradle.plugins.shadow.transformers.Transformer
import com.github.jengelman.gradle.plugins.shadow.transformers.TransformerContext
import org.gradle.api.file.FileTreeElement
import shadow.org.apache.tools.zip.ZipEntry
import shadow.org.apache.tools.zip.ZipOutputStream
import shadow.org.codehaus.plexus.util.IOUtil
import shadow.org.codehaus.plexus.util.ReaderFactory
import shadow.org.codehaus.plexus.util.WriterFactory
import shadow.org.codehaus.plexus.util.xml.Xpp3Dom
import shadow.org.codehaus.plexus.util.xml.Xpp3DomBuilder
import shadow.org.codehaus.plexus.util.xml.Xpp3DomWriter
import java.io.*
import java.lang.Exception
import java.util.LinkedHashMap
/**
* A resource processor that aggregates plexus `components.xml` files.
*
* Fixed version of [com.github.jengelman.gradle.plugins.shadow.transformers.ComponentsXmlResourceTransformer],
* may be dropped after [the fix in ShadowJAR](https://github.com/johnrengelman/shadow/pull/678/files) will be accepted
*/
class ComponentsXmlResourceTransformerPatched : Transformer {
private val components: MutableMap<String, Xpp3Dom> =
LinkedHashMap<String, Xpp3Dom>()
override fun canTransformResource(element: FileTreeElement): Boolean {
val path = element.relativePath.pathString
return COMPONENTS_XML_PATH == path
}
override fun transform(context: TransformerContext) {
val newDom: Xpp3Dom = try {
val bis: BufferedInputStream = object : BufferedInputStream(context.getIs()) {
override fun close() {
// leave ZIP open
}
}
val reader: Reader = ReaderFactory.newXmlReader(bis)
Xpp3DomBuilder.build(reader)
} catch (e: Exception) {
throw (IOException("Error parsing components.xml in " + context.getIs()).initCause(e) as IOException)
}
// Only try to merge in components if there are some elements in the component-set
if (newDom.getChild("components") == null) {
return
}
val children: Array<Xpp3Dom>? = newDom.getChild("components")?.getChildren("component")
children?.forEach { component ->
var role: String? = getValue(component, "role")
role = getRelocatedClass(role, context)
setValue(component, "role", role)
val roleHint = getValue(component, "role-hint")
var impl: String? = getValue(component, "implementation")
impl = getRelocatedClass(impl, context)
setValue(component, "implementation", impl)
val key = "$role:$roleHint"
if (components.containsKey(key)) {
// configuration carry over
val dom: Xpp3Dom? = components[key]
if (dom?.getChild("configuration") != null) {
component.addChild(dom.getChild("configuration"))
}
}
val requirements: Xpp3Dom? = component.getChild("requirements")
if (requirements != null && requirements.childCount > 0) {
for (r in requirements.childCount - 1 downTo 0) {
val requirement: Xpp3Dom = requirements.getChild(r)
var requiredRole: String? = getValue(requirement, "role")
requiredRole = getRelocatedClass(requiredRole, context)
setValue(requirement, "role", requiredRole)
}
}
components[key] = component
}
}
override fun modifyOutputStream(os: ZipOutputStream, preserveFileTimestamps: Boolean) {
val data = transformedResource
val entry = ZipEntry(COMPONENTS_XML_PATH)
entry.time = TransformerContext.getEntryTimestamp(preserveFileTimestamps, entry.time)
os.putNextEntry(entry)
IOUtil.copy(data, os)
components.clear()
}
override fun hasTransformedResource(): Boolean {
return components.isNotEmpty()
}
private val transformedResource: ByteArray
get() {
val baos = ByteArrayOutputStream(1024 * 4)
val writer: Writer = WriterFactory.newXmlWriter(baos)
try {
val dom = Xpp3Dom("component-set")
val componentDom = Xpp3Dom("components")
dom.addChild(componentDom)
for (component in components.values) {
componentDom.addChild(component)
}
Xpp3DomWriter.write(writer, dom)
} finally {
IOUtil.close(writer)
}
return baos.toByteArray()
}
companion object {
private const val COMPONENTS_XML_PATH = "META-INF/plexus/components.xml"
private fun getRelocatedClass(className: String?, context: TransformerContext): String? {
val relocators = context.relocators
val stats = context.stats
if (className != null && className.isNotEmpty() && relocators != null) {
for (relocator in relocators) {
if (relocator.canRelocateClass(className)) {
val relocateClassContext = RelocateClassContext(className, stats)
return relocator.relocateClass(relocateClassContext)
}
}
}
return className
}
private fun getValue(dom: Xpp3Dom, element: String): String {
val child: Xpp3Dom? = dom.getChild(element)
return if (child?.value != null) child.value else ""
}
private fun setValue(dom: Xpp3Dom, element: String, value: String?) {
val child: Xpp3Dom? = dom.getChild(element)
if (value == null || value.isEmpty()) {
return
}
child?.value = value
}
}
}

View File

@@ -26,7 +26,7 @@ fun CompatibilityPredicate.or(other: CompatibilityPredicate): CompatibilityPredi
}
enum class Platform : CompatibilityPredicate {
P202, P203;
P203;
val version: Int = name.drop(1).toInt()
@@ -43,10 +43,7 @@ enum class Platform : CompatibilityPredicate {
}
enum class Ide(val platform: Platform) : CompatibilityPredicate {
IJ202(Platform.P202),
IJ203(Platform.P203),
AS42(Platform.P202);
IJ203(Platform.P203);
val kind = Kind.values().first { it.shortName == name.take(2) }
val version = name.dropWhile { !it.isDigit() }.toInt()

View File

@@ -0,0 +1,184 @@
@file:JvmName("JvmToolchain")
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.jvm.toolchain.*
import org.gradle.kotlin.dsl.getByType
import org.gradle.kotlin.dsl.withType
import org.jetbrains.kotlin.gradle.dsl.KotlinTopLevelExtension
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
enum class JdkMajorVersion(
val majorVersion: Int,
val targetName: String = majorVersion.toString(),
val overrideMajorVersion: Int? = null,
private val mandatory: Boolean = true
) {
JDK_1_6(6, targetName = "1.6", overrideMajorVersion = 8),
JDK_1_7(7, targetName = "1.7", overrideMajorVersion = 8),
JDK_1_8(8, targetName = "1.8"),
JDK_9(9, overrideMajorVersion = 11),
JDK_10(10, mandatory = false, overrideMajorVersion = 11),
JDK_11(11, mandatory = false),
JDK_15(15, mandatory = false),
JDK_16(16, mandatory = false),
JDK_17(17, mandatory = false);
fun isMandatory(): Boolean = mandatory
companion object {
fun fromMajorVersion(majorVersion: Int) = values().first { it.majorVersion == majorVersion }
}
}
fun Project.configureJvmDefaultToolchain() {
configureJvmToolchain(JdkMajorVersion.JDK_1_8)
}
fun Project.shouldOverrideObsoleteJdk(
jdkVersion: JdkMajorVersion
): Boolean = kotlinBuildProperties.isObsoleteJdkOverrideEnabled &&
jdkVersion.overrideMajorVersion != null
fun Project.configureJvmToolchain(
jdkVersion: JdkMajorVersion
) {
// Ensure java only modules also set default toolchain
configureJavaOnlyToolchain(jdkVersion)
plugins.withId("org.jetbrains.kotlin.jvm") {
val kotlinExtension = extensions.getByType<KotlinTopLevelExtension>()
if (shouldOverrideObsoleteJdk(jdkVersion)) {
kotlinExtension.jvmToolchain {
(this as JavaToolchainSpec).languageVersion
.set(JavaLanguageVersion.of(jdkVersion.overrideMajorVersion!!))
}
updateJvmTarget(jdkVersion.targetName)
} else {
kotlinExtension.jvmToolchain {
(this as JavaToolchainSpec).languageVersion
.set(JavaLanguageVersion.of(jdkVersion.majorVersion))
}
}
tasks
.matching { it.name != "compileJava9Java" && it is JavaCompile }
.configureEach {
with(this as JavaCompile) {
options.compilerArgs.add("-proc:none")
options.encoding = "UTF-8"
}
}
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions.freeCompilerArgs += "-Xjvm-default=compatibility"
}
}
}
fun Project.configureJavaOnlyToolchain(
jdkVersion: JdkMajorVersion
) {
plugins.withId("java-base") {
val javaExtension = extensions.getByType<JavaPluginExtension>()
if (shouldOverrideObsoleteJdk(jdkVersion)) {
javaExtension.toolchain {
languageVersion.set(
JavaLanguageVersion.of(jdkVersion.overrideMajorVersion!!)
)
}
tasks.withType<JavaCompile>().configureEach {
targetCompatibility = jdkVersion.targetName
sourceCompatibility = jdkVersion.targetName
}
} else {
javaExtension.toolchain {
languageVersion.set(
JavaLanguageVersion.of(jdkVersion.majorVersion)
)
}
}
}
}
fun KotlinCompile.configureTaskToolchain(
jdkVersion: JdkMajorVersion
) {
if (project.shouldOverrideObsoleteJdk(jdkVersion)) {
kotlinJavaToolchain.toolchain.use(
project.getToolchainLauncherFor(
JdkMajorVersion.fromMajorVersion(
jdkVersion.overrideMajorVersion!!
)
)
)
kotlinOptions {
jvmTarget = jdkVersion.targetName
}
} else {
kotlinJavaToolchain.toolchain.use(
project.getToolchainLauncherFor(jdkVersion)
)
}
}
fun JavaCompile.configureTaskToolchain(
jdkVersion: JdkMajorVersion
) {
if (project.shouldOverrideObsoleteJdk(jdkVersion)) {
javaCompiler.set(
project.getToolchainCompilerFor(
JdkMajorVersion.fromMajorVersion(
jdkVersion.overrideMajorVersion!!
)
)
)
targetCompatibility = jdkVersion.targetName
sourceCompatibility = jdkVersion.targetName
} else {
javaCompiler.set(project.getToolchainCompilerFor(jdkVersion))
}
}
fun Project.updateJvmTarget(
jvmTarget: String
) {
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions.jvmTarget = jvmTarget
}
tasks.withType<JavaCompile>().configureEach {
sourceCompatibility = jvmTarget
targetCompatibility = jvmTarget
}
}
private fun Project.getToolchainCompilerFor(
jdkVersion: JdkMajorVersion
): Provider<JavaCompiler> {
val service = project.extensions.getByType<JavaToolchainService>()
return service.compilerFor {
this.languageVersion.set(JavaLanguageVersion.of(jdkVersion.majorVersion))
}
}
fun Project.getToolchainLauncherFor(
jdkVersion: JdkMajorVersion
): Provider<JavaLauncher> {
val service = project.extensions.getByType<JavaToolchainService>()
val jdkVersionWithOverride = project.getJdkVersionWithOverride(jdkVersion)
return service.launcherFor {
this.languageVersion.set(JavaLanguageVersion.of(jdkVersionWithOverride.majorVersion))
}
}
fun Project.getJdkVersionWithOverride(jdkVersion: JdkMajorVersion): JdkMajorVersion {
return if (project.shouldOverrideObsoleteJdk(jdkVersion)) {
JdkMajorVersion.fromMajorVersion(jdkVersion.overrideMajorVersion!!)
} else {
jdkVersion
}
}

View File

@@ -0,0 +1,57 @@
/*
* 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.
*/
@file:JvmName("LibrariesCommon")
import org.gradle.api.JavaVersion
import org.gradle.api.Project
import org.gradle.api.file.FileCollection
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.kotlin.dsl.get
import org.gradle.process.CommandLineArgumentProvider
@JvmOverloads
fun Project.configureJava9Compilation(
moduleName: String,
moduleOutputs: Collection<FileCollection> = setOf(sourceSets["main"].output)
) {
configurations["java9CompileClasspath"].extendsFrom(configurations["compileClasspath"])
tasks.named("compileJava9Java", JavaCompile::class.java) {
dependsOn(moduleOutputs)
targetCompatibility = JavaVersion.VERSION_1_9.toString()
sourceCompatibility = JavaVersion.VERSION_1_9.toString()
configureTaskToolchain(JdkMajorVersion.JDK_9)
// module-info.java should be in java9 source set by convention
val java9SourceSet = sourceSets["java9"].java
destinationDir = file("${java9SourceSet.outputDir}/META-INF/versions/9")
options.sourcepath = files(java9SourceSet.srcDirs)
val compileClasspath = configurations["java9CompileClasspath"]
val moduleFiles = objects.fileCollection().from(moduleOutputs)
val modulePath = compileClasspath.filter { it !in moduleFiles.files }
classpath = objects.fileCollection().from()
options.compilerArgumentProviders.add(
Java9AdditionalArgumentsProvider(
moduleName,
moduleFiles,
modulePath
)
)
}
}
private class Java9AdditionalArgumentsProvider(
private val moduleName: String,
private val moduleFiles: FileCollection,
private val modulePath: FileCollection
) : CommandLineArgumentProvider {
override fun asArguments(): Iterable<String> = listOf(
"--module-path", modulePath.asPath,
"--patch-module", "$moduleName=${moduleFiles.asPath}",
"-Xlint:-requires-transitive-automatic" // suppress automatic module transitive dependencies in kotlin.test
)
}

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,10 +225,23 @@ 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.publishGradlePlugin() {
mainPublicationName = "pluginMaven"
publish()
afterEvaluate {
tasks.withType<PublishTask> {
// Makes plugin publication task reuse poms and metadata from publication named "pluginMaven"
useAutomatedPublishing()
useGradleModuleMetadataIfAvailable()
}
}
}
fun Project.idePluginDependency(block: () -> Unit) {
val shouldActivate = rootProject.findProperty("publish.ide.plugin.dependencies")?.toString()?.toBoolean() == true
if (shouldActivate) {

View File

@@ -9,15 +9,15 @@
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.ModuleDependency
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.internal.jvm.Jvm
import org.gradle.jvm.toolchain.JavaLanguageVersion
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
@@ -124,6 +124,14 @@ fun DependencyHandler.add(configurationName: String, dependencyNotation: Any, co
}
}
fun Project.disableDependencyVerification() {
configurations.all {
resolutionStrategy {
disableDependencyVerification()
}
}
}
fun DependencyHandler.jpsLikeJarDependency(
dependencyNotation: Any,
scope: JpsDepScope,
@@ -281,14 +289,16 @@ fun Project.firstFromJavaHomeThatExists(vararg paths: String, jdkHome: File = Fi
fun Project.toolsJarApi(): Any =
if (kotlinBuildProperties.isInJpsBuildIdeaSync)
files(toolsJarFile() ?: error("tools.jar is not found!"))
toolsJar()
else
dependencies.project(":dependencies:tools-jar-api")
fun Project.toolsJar(): FileCollection = files(toolsJarFile() ?: error("tools.jar is not found!"))
fun Project.toolsJarFile(jdkHome: File = File(this.property("JDK_18") as String)): File? =
firstFromJavaHomeThatExists("lib/tools.jar", jdkHome = jdkHome)
fun Project.toolsJar(): FileCollection = files(
getToolchainLauncherFor(JdkMajorVersion.JDK_1_8)
.map {
Jvm.forHome(it.metadata.installationPath.asFile).toolsJar ?: throw GradleException("tools.jar not found!")
}
)
val compilerManifestClassPath
get() = "annotations-13.0.jar kotlin-stdlib.jar kotlin-reflect.jar kotlin-script-runtime.jar trove4j.jar"

View File

@@ -2,6 +2,8 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.api.Project
import org.gradle.api.artifacts.DependencySubstitution
import org.gradle.api.artifacts.component.ProjectComponentSelector
import org.gradle.api.file.DuplicatesStrategy
import org.gradle.api.tasks.TaskProvider
import org.gradle.jvm.tasks.Jar
@@ -80,6 +82,24 @@ private fun Project.compilerShadowJar(taskName: String, body: ShadowJar.() -> Un
}
}
fun Project.configureShadowJarSubstitutionInCompileClasspath() {
val substitutionMap = mapOf(":kotlin-reflect" to ":kotlin-reflect-api")
fun configureSubstitution(substitution: DependencySubstitution) {
val requestedProject = (substitution.requested as? ProjectComponentSelector)?.projectPath ?: return
val replacementProject = substitutionMap[requestedProject] ?: return
substitution.useTarget(project(replacementProject), "Non-default shadow jars should not be used in compile classpath")
}
sourceSets.all {
for (configName in listOf(compileOnlyConfigurationName, compileClasspathConfigurationName)) {
configurations.getByName(configName).resolutionStrategy.dependencySubstitution {
all(::configureSubstitution)
}
}
}
}
fun Project.embeddableCompiler(taskName: String = "embeddable", body: ShadowJar.() -> Unit = {}): TaskProvider<out ShadowJar> =
compilerShadowJar(taskName) {
configureEmbeddableCompilerRelocation()

View File

@@ -8,7 +8,7 @@ plugins {
kotlin("jvm")
}
publish()
publishGradlePlugin()
standardPublicJars()
extensions.extraProperties["kotlin.stdlib.default.dependency"] = "false"
@@ -37,12 +37,12 @@ configurations {
}
tasks.withType<KotlinCompile> {
kotlinOptions.languageVersion = "1.3"
kotlinOptions.apiVersion = "1.3"
kotlinOptions.languageVersion = "1.4"
kotlinOptions.apiVersion = "1.4"
kotlinOptions.freeCompilerArgs += listOf(
"-Xskip-prerelease-check",
"-Xskip-runtime-version-check",
"-Xsuppress-version-warnings"
"-Xsuppress-version-warnings",
"-Xuse-ir" // Needed as long as languageVersion is less than 1.5.
)
}

View File

@@ -24,16 +24,16 @@ fun ProjectSettings.compiler(block: IdeaCompilerConfiguration.() -> Unit) =
fun ProjectSettings.delegateActions(block: ActionDelegationConfig.() -> Unit) =
(this@delegateActions as ExtensionAware).extensions.configure(block)
fun ProjectSettings.runConfigurations(block: DefaultRunConfigurationContainer.() -> Unit) =
fun ProjectSettings.runConfigurations(block: RunConfigurationContainer.() -> Unit) =
(this@runConfigurations as ExtensionAware).extensions.configure("runConfigurations", block)
inline fun <reified T: RunConfiguration> DefaultRunConfigurationContainer.defaults(noinline block: T.() -> Unit) =
inline fun <reified T: RunConfiguration> RunConfigurationContainer.defaults(noinline block: T.() -> Unit) =
defaults(T::class.java, block)
fun DefaultRunConfigurationContainer.junit(name: String, block: JUnit.() -> Unit) =
fun RunConfigurationContainer.junit(name: String, block: JUnit.() -> Unit) =
create(name, JUnit::class.java, block)
fun DefaultRunConfigurationContainer.application(name: String, block: Application.() -> Unit) =
fun RunConfigurationContainer.application(name: String, block: Application.() -> Unit) =
create(name, Application::class.java, block)
fun ProjectSettings.ideArtifacts(block: NamedDomainObjectContainer<org.jetbrains.gradle.ext.TopLevelArtifact>.() -> Unit) =

View File

@@ -1,198 +0,0 @@
@file:Suppress("unused") // usages in build scripts are not tracked properly
import net.rubygrapefruit.platform.Native
import net.rubygrapefruit.platform.WindowsRegistry
import org.gradle.api.GradleException
import org.gradle.api.Project
import java.nio.file.Paths
import java.io.File
import net.rubygrapefruit.platform.WindowsRegistry.Key.HKEY_LOCAL_MACHINE
import org.gradle.internal.os.OperatingSystem
enum class JdkMajorVersion(private val mandatory: Boolean = true) {
JDK_16, JDK_17, JDK_18, JDK_9, JDK_10(false), JDK_11(false), /*15.0*/JDK_15(false);
fun isMandatory(): Boolean = mandatory
}
val jdkAlternativeVarNames = mapOf(JdkMajorVersion.JDK_9 to listOf("JDK_19"), JdkMajorVersion.JDK_15 to listOf("JDK_15_0"))
data class JdkId(val explicit: Boolean, val majorVersion: JdkMajorVersion, var version: String, var homeDir: File)
fun Project.getConfiguredJdks(): List<JdkId> {
val res = arrayListOf<JdkId>()
for (jdkMajorVersion in JdkMajorVersion.values()) {
val explicitJdkEnvVal = findProperty(jdkMajorVersion.name)?.toString()
?: System.getenv(jdkMajorVersion.name)
?: jdkAlternativeVarNames[jdkMajorVersion]?.mapNotNull { System.getenv(it) }?.firstOrNull()
?: continue
val explicitJdk = Paths.get(explicitJdkEnvVal).toRealPath().toFile()
if (!explicitJdk.isDirectory) {
throw GradleException("Invalid environment value $jdkMajorVersion: $explicitJdkEnvVal, expecting JDK home path")
}
res.add(JdkId(true, jdkMajorVersion, "X", explicitJdk))
}
if (res.size < JdkMajorVersion.values().size) {
res.discoverJdks(this)
}
return res
}
// see JEP 223
private val javaMajorVersionRegex = Regex("""(?:1\.)?(\d+).*""")
private val javaVersionRegex = Regex("""(?:1\.)?(\d+)(\.\d+)?([+-_]\w+){0,3}""")
fun MutableCollection<JdkId>.addIfBetter(project: Project, version: String, id: String, homeDir: File): Boolean {
val matchString = javaMajorVersionRegex.matchEntire(version)?.groupValues?.get(1)
val majorJdkVersion = when (matchString) {
"6" -> JdkMajorVersion.JDK_16
"7" -> JdkMajorVersion.JDK_17
"8" -> JdkMajorVersion.JDK_18
"9" -> JdkMajorVersion.JDK_9
else -> {
project.logger.info("Cannot recognize version string '$version' (found version '$matchString')")
return false
}
}
val prev = find { it.majorVersion == majorJdkVersion }
if (prev == null) {
add(JdkId(false, majorJdkVersion, version, homeDir))
return true
}
if (prev.explicit) return false
val versionsComparisonRes = compareVersions(prev.version, version)
if (versionsComparisonRes < 0 || (versionsComparisonRes == 0 && id.contains("64"))) { // prefer 64-bit
prev.version = version
prev.homeDir = homeDir
return true
}
return false
}
private fun compareVersions(left: String, right: String): Int {
if (left == right) return 0
fun MatchResult.extractNumVer(): List<Int> =
groups.drop(2).map {
it?.value?.filter { it in '0'..'9' }?.toIntOrNull() ?: 0
}
val lmi = (javaVersionRegex.matchEntire(left)?.extractNumVer() ?: emptyList()).iterator()
val rmi = (javaVersionRegex.matchEntire(right)?.extractNumVer() ?: emptyList()).iterator()
while (lmi.hasNext() && rmi.hasNext()) {
val l = lmi.next()
val r = rmi.next()
when {
l < r -> return -1
l > r -> return 1
}
}
return when {
rmi.hasNext() -> -1
lmi.hasNext() -> 1
else -> 0
}
}
fun MutableCollection<JdkId>.discoverJdks(project: Project) {
val os = OperatingSystem.current()
when {
os.isWindows -> discoverJdksOnWindows(project)
os.isMacOsX -> discoverJdksOnMacOS(project)
else -> discoverJdksOnUnix(project)
}
}
private val macOsJavaHomeOutRegexes =
listOf(
Regex("""\s+(\S+),\s+(\S+):\s+".*?"\s+(.+)"""),
Regex("""\s+(\S+)\s+\((.*?)\):\s+(.+)"""),
Regex("""\s+(\S+)\s+\((.*?)\)\s+"[^"]*"\s+-\s+"[^"]*"\s(.+)"""),
Regex("""\s+(\S+)\s+\((.+)\)\s+".+"\s+-\s+".+"\s+(.+)"""))
fun MutableCollection<JdkId>.discoverJdksOnMacOS(project: Project) {
val procBuilder = ProcessBuilder("/usr/libexec/java_home", "-V").redirectErrorStream(true)
val process = procBuilder.start()
val retCode = process.waitFor()
if (retCode != 0) throw GradleException("Unable to run 'java_home', return code $retCode")
process.inputStream.bufferedReader().forEachLine { line ->
for (rex in macOsJavaHomeOutRegexes) {
val matchResult = rex.matchEntire(line)
if (matchResult != null) {
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
}
}
}
}
}
private val unixConventionalJdkLocations = listOf(
"/usr/lib/jvm", // *deb, Arch
"/opt", // *rpm, Gentoo, HP/UX
"/usr/lib", // Slackware 32
"/usr/lib64", // Slackware 64
"/usr/local", // OpenBSD, FreeBSD
"/usr/pkg/java", // NetBSD
"/usr/jdk/instances") // Solaris
private val unixConventionalJdkDirRex = Regex("jdk|jre|java|zulu")
fun MutableCollection<JdkId>.discoverJdksOnUnix(project: Project) {
for (loc in unixConventionalJdkLocations) {
val installedJdks = File(loc).listFiles { dir ->
dir.isDirectory &&
unixConventionalJdkDirRex.containsMatchIn(dir.name) &&
fileFrom(dir, "bin", "java").isFile
} ?: continue
for (dir in installedJdks) {
val versionMatch = javaVersionRegex.find(dir.name)
if (versionMatch == null) {
project.logger.info("Unable to extract version from possible JDK dir: $dir")
}
else {
addIfBetter(project, versionMatch.value, dir.name, dir)
}
}
}
}
private val windowsConventionalJdkRegistryPaths = listOf(
"SOFTWARE\\JavaSoft\\Java Development Kit",
"SOFTWARE\\Wow6432Node\\JavaSoft\\Java Development Kit",
"SOFTWARE\\JavaSoft\\JDK",
"SOFTWARE\\Wow6432Node\\JavaSoft\\JDK")
fun MutableCollection<JdkId>.discoverJdksOnWindows(project: Project) {
val registry = Native.get(WindowsRegistry::class.java)
for (regPath in windowsConventionalJdkRegistryPaths) {
val jdkKeys = try {
registry.getSubkeys(HKEY_LOCAL_MACHINE, regPath)
} catch (e: RuntimeException) {
// ignore missing nodes
continue
}
for (jdkKey in jdkKeys) {
try {
val javaHome = registry.getStringValue(HKEY_LOCAL_MACHINE, regPath + "\\" + jdkKey, "JavaHome")
val versionMatch = javaVersionRegex.find(jdkKey)
if (versionMatch == null) {
project.logger.info("Unable to extract version from possible JDK location: $javaHome ($jdkKey)")
}
else {
javaHome.takeIf { it.isNotEmpty() }
?.let { File(it) }
?.takeIf { it.isDirectory && fileFrom(it, "bin", "java.exe").isFile }
?.let {
addIfBetter(project, versionMatch.value, jdkKey, it)
}
}
}
catch (e: RuntimeException) {
// Ignore
}
}
}
}

View File

@@ -17,16 +17,11 @@
// usages in build scripts are not tracked properly
@file:Suppress("unused")
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.artifacts.ModuleDependency
import org.gradle.api.artifacts.dsl.RepositoryHandler
import org.gradle.api.artifacts.repositories.IvyArtifactRepository
import org.gradle.api.tasks.JavaExec
import org.gradle.api.tasks.TaskProvider
import org.gradle.kotlin.dsl.DependencyHandlerScope
import org.gradle.kotlin.dsl.extra
import org.gradle.kotlin.dsl.register
import java.io.File
private fun Project.kotlinBuildLocalDependenciesDir(): File =
@@ -87,8 +82,6 @@ fun Project.intellijCoreDep() = "kotlin.build:intellij-core:${rootProject.extra[
fun Project.jpsStandalone() = "kotlin.build:jps-standalone:${rootProject.extra["versions.intellijSdk"]}"
fun Project.nodeJSPlugin() = "kotlin.build:NodeJS:${rootProject.extra["versions.idea.NodeJS"]}"
fun Project.jpsBuildTest() = "com.jetbrains.intellij.idea:jps-build-test:${rootProject.extra["versions.intellijSdk"]}"
fun Project.kotlinxCollectionsImmutable() = "org.jetbrains.kotlinx:kotlinx-collections-immutable-jvm:${rootProject.extra["versions.kotlinx-collections-immutable"]}"
@@ -146,70 +139,4 @@ fun ModuleDependency.includeIntellijCoreJarDependencies(project: Project, jarsFi
rootProject = project.rootProject
)
fun Project.intellijRootDir() = IntellijRootUtils.getIntellijRootDir(project)
fun DependencyHandlerScope.excludeInAndroidStudio(rootProject: Project, block: DependencyHandlerScope.() -> Unit) {
if (!rootProject.extra.has("versions.androidStudioRelease")) {
block()
}
}
fun Project.runIdeTask(name: String, ideaPluginDir: File, ideaSandboxDir: File, body: JavaExec.() -> Unit): TaskProvider<JavaExec> {
return tasks.register<JavaExec>(name) {
val ideaSandboxConfigDir = File(ideaSandboxDir, "config")
classpath = mainSourceSet.runtimeClasspath
mainClass.set("com.intellij.idea.Main")
workingDir = File(intellijRootDir(), "bin")
jvmArgs(
"-Xmx1250m",
"-XX:ReservedCodeCacheSize=240m",
"-XX:+HeapDumpOnOutOfMemoryError",
"-ea",
"-Didea.debug.mode=true",
"-Didea.system.path=$ideaSandboxDir",
"-Didea.config.path=$ideaSandboxConfigDir",
"-Didea.tooling.debug=true",
"-Dfus.internal.test.mode=true",
"-Dapple.laf.useScreenMenuBar=true",
"-Dapple.awt.graphics.UseQuartz=true",
"-Dsun.io.useCanonCaches=false",
"-Dplugin.path=${ideaPluginDir.absolutePath}"
)
jvmArgs("-Didea.platform.prefix=Idea")
if (rootProject.findProperty("versions.androidStudioRelease") != null) {
jvmArgs("-Didea.platform.prefix=AndroidStudio")
}
if (project.hasProperty("noPCE")) {
jvmArgs("-Didea.ProcessCanceledException=disabled")
}
jvmArgs("-Didea.is.internal=${project.findProperty("idea.is.internal") ?: true}")
project.findProperty("idea.args")?.let { arguments ->
jvmArgs(arguments.toString().split(" "))
}
args()
doFirst {
val disabledPluginsFile = File(ideaSandboxConfigDir, "disabled_plugins.txt")
val disabledPluginsContents = disabledPluginsFile.takeIf { it.isFile }?.readLines()
val filteredContents = disabledPluginsContents?.filterNot { it.contains("org.jetbrains.kotlin") }
if (filteredContents != null && filteredContents.size != disabledPluginsContents.size) {
with(disabledPluginsFile.printWriter()) {
filteredContents.forEach(this::println)
}
}
}
body()
}
}
fun Project.intellijRootDir() = IntellijRootUtils.getIntellijRootDir(project)

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) }
@@ -161,16 +171,18 @@ fun Project.configureDefaultPublishing() {
.all { configureRepository() }
}
private fun Project.getSensitiveProperty(name: String): String? {
return project.findProperty(name) as? String ?: System.getenv(name)
}
private fun Project.configureSigning() {
configure<SigningExtension> {
sign(extensions.getByType<PublishingExtension>().publications) // all publications
val signKeyId = project.findProperty("signKeyId") as? String
val signKeyId = project.getSensitiveProperty("signKeyId")
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")
val signKeyPrivate = project.getSensitiveProperty("signKeyPrivate") ?: error("Parameter `signKeyPrivate` not found")
val signKeyPassphrase = project.getSensitiveProperty("signKeyPassphrase") ?: error("Parameter `signKeyPassphrase` not found")
useInMemoryPgpKeys(signKeyId, signKeyPrivate, signKeyPassphrase)
} else {
useGpgCmd()

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,7 +24,6 @@ dependencies {
testApi(projectTests(":compiler:tests-compiler-utils"))
testApi(projectTests(":compiler:tests-common-new"))
testCompile(projectTests(":jps-plugin"))
testCompile(commonDep("junit:junit"))
testCompile(intellijDep()) { includeJars("util", "idea", "idea_rt", rootProject = rootProject) }
@@ -34,6 +33,9 @@ dependencies {
testCompile(jpsStandalone()) { includeJars("jps-model") }
testCompile(jpsBuildTest())
testRuntimeOnly(compile(intellijCoreDep()) { includeJars("intellij-core") })
testRuntimeOnly(compile(intellijDep()) { includeJars("jna", rootProject = rootProject) })
testCompile("org.junit.platform:junit-platform-launcher:${commonVer("org.junit.platform", "")}")
}

View File

@@ -15,7 +15,10 @@ import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.codegen.CodegenTestFiles
import org.jetbrains.kotlin.codegen.GenerationUtils
import org.jetbrains.kotlin.codegen.forTestCompile.ForTestCompileRuntime
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.config.CommonConfigurationKeys
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.config.languageVersionSettings
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.psi.KtFile
@@ -23,11 +26,11 @@ import org.jetbrains.kotlin.test.*
import org.jetbrains.kotlin.test.builders.TestConfigurationBuilder
import org.jetbrains.kotlin.test.model.DependencyKind
import org.jetbrains.kotlin.test.model.FrontendKinds
import org.jetbrains.kotlin.test.model.ResultingArtifact
import org.jetbrains.kotlin.test.runners.AbstractKotlinCompilerTest
import org.jetbrains.kotlin.test.services.*
import org.jetbrains.kotlin.test.services.configuration.CommonEnvironmentConfigurator
import org.jetbrains.kotlin.test.services.configuration.JvmEnvironmentConfigurator
import org.jetbrains.kotlin.test.services.impl.BackendKindExtractorImpl
import org.jetbrains.kotlin.test.services.impl.TemporaryDirectoryManagerImpl
import org.jetbrains.kotlin.test.services.sourceProviders.AdditionalDiagnosticsSourceFilesProvider
import org.jetbrains.kotlin.test.services.sourceProviders.CodegenHelpersSourceFilesProvider
@@ -382,6 +385,7 @@ class CodegenTestsOnAndroidGenerator private constructor(private val pathManager
"test${testDataFile.nameWithoutExtension.replaceFirstChar(Char::uppercaseChar)}",
emptySet()
)
startingArtifactFactory = { ResultingArtifact.Source() }
}.build(testDataFile.path)
}
@@ -406,7 +410,6 @@ class CodegenTestsOnAndroidGenerator private constructor(private val pathManager
assertions = JUnit5Assertions
useAdditionalService<TemporaryDirectoryManager>(::TemporaryDirectoryManagerImpl)
useAdditionalService<BackendKindExtractor>(::BackendKindExtractorImpl)
useSourcePreprocessor(*AbstractKotlinCompilerTest.defaultPreprocessors.toTypedArray())
useDirectives(*AbstractKotlinCompilerTest.defaultDirectiveContainers.toTypedArray())
}

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

@@ -5,21 +5,15 @@
package org.jetbrains.kotlin.backend.common
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.config.coroutinesIntrinsicsPackageFqName
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.isTopLevelInPackage
import org.jetbrains.kotlin.name.Name
val COROUTINE_SUSPENDED_NAME = Name.identifier("COROUTINE_SUSPENDED")
fun FunctionDescriptor.isBuiltInIntercepted(languageVersionSettings: LanguageVersionSettings): Boolean =
!languageVersionSettings.supportsFeature(LanguageFeature.ReleaseCoroutines) &&
isTopLevelInPackage("intercepted", languageVersionSettings.coroutinesIntrinsicsPackageFqName().asString())
fun FunctionDescriptor.isBuiltInSuspendCoroutineUninterceptedOrReturn(languageVersionSettings: LanguageVersionSettings): Boolean =
fun FunctionDescriptor.isBuiltInSuspendCoroutineUninterceptedOrReturn(): Boolean =
isTopLevelInPackage(
"suspendCoroutineUninterceptedOrReturn",
languageVersionSettings.coroutinesIntrinsicsPackageFqName().asString()
StandardNames.COROUTINES_INTRINSICS_PACKAGE_FQ_NAME.asString()
)

View File

@@ -19,7 +19,9 @@ interface TypeMappingContext<Writer : JvmDescriptorTypeWriter<Type>> {
fun getClassInternalName(typeConstructor: TypeConstructorMarker): String
fun getScriptInternalName(typeConstructor: TypeConstructorMarker): String
fun Writer.writeGenericType(type: SimpleTypeMarker, asmType: Type, mode: TypeMappingMode)
// NB: The counterpart, [KotlinTypeMapper#writeGenericType], doesn't have restriction on [type]
fun Writer.writeGenericType(type: KotlinTypeMarker, asmType: Type, mode: TypeMappingMode)
}
object AbstractTypeMapper {
@@ -44,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>,
@@ -51,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()
@@ -79,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()
@@ -99,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?)

View File

@@ -17,7 +17,7 @@
package org.jetbrains.kotlin.codegen
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeSubstitutor
@@ -26,7 +26,7 @@ class AccessorForConstructorDescriptor(
containingDeclaration: DeclarationDescriptor,
override val superCallTarget: ClassDescriptor?,
override val accessorKind: AccessorKind
) : AbstractAccessorForFunctionDescriptor(containingDeclaration, Name.special("<init>")),
) : AbstractAccessorForFunctionDescriptor(containingDeclaration, SpecialNames.INIT),
ClassConstructorDescriptor,
AccessorForCallableDescriptor<ConstructorDescriptor> {

View File

@@ -11,6 +11,7 @@ import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.resolve.calls.model.DefaultValueArgument
import org.jetbrains.kotlin.resolve.calls.model.ExpressionValueArgument
import org.jetbrains.kotlin.resolve.calls.model.VarargValueArgument
import org.jetbrains.kotlin.resolve.inline.InlineUtil
import org.jetbrains.kotlin.resolve.jvm.AsmTypes.OBJECT_TYPE
import org.jetbrains.kotlin.types.upperIfFlexible
import org.jetbrains.org.objectweb.asm.Type
@@ -51,7 +52,7 @@ class CallBasedArgumentGenerator(
callGenerator.putValueIfNeeded(
getJvmKotlinType(i),
StackValue.createDefaultValue(valueParameterTypes[i]),
ValueKind.DEFAULT_PARAMETER,
if (InlineUtil.isInlineParameter(valueParameters[i])) ValueKind.DEFAULT_INLINE_PARAMETER else ValueKind.DEFAULT_PARAMETER,
i
)
}

View File

@@ -15,9 +15,9 @@ enum class ValueKind {
GENERAL,
GENERAL_VARARG,
DEFAULT_PARAMETER,
DEFAULT_INLINE_PARAMETER,
DEFAULT_MASK,
METHOD_HANDLE_IN_DEFAULT,
CAPTURED,
NON_INLINEABLE_ARGUMENT_FOR_INLINE_PARAMETER_CALLED_IN_SUSPEND,
NON_INLINEABLE_ARGUMENT_FOR_INLINE_SUSPEND_PARAMETER
}

View File

@@ -27,24 +27,16 @@ import org.jetbrains.annotations.TestOnly;
import org.jetbrains.kotlin.backend.common.output.OutputFile;
import org.jetbrains.kotlin.backend.common.output.OutputFileCollection;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.config.AnalysisFlags;
import org.jetbrains.kotlin.config.JvmAnalysisFlags;
import org.jetbrains.kotlin.descriptors.ClassDescriptor;
import org.jetbrains.kotlin.descriptors.DescriptorUtilKt;
import org.jetbrains.kotlin.descriptors.ModuleDescriptor;
import org.jetbrains.kotlin.incremental.components.NoLookupLocation;
import org.jetbrains.kotlin.load.kotlin.ModuleMappingUtilKt;
import org.jetbrains.kotlin.metadata.ProtoBuf;
import org.jetbrains.kotlin.metadata.jvm.JvmModuleProtoBuf;
import org.jetbrains.kotlin.metadata.jvm.deserialization.ModuleMapping;
import org.jetbrains.kotlin.metadata.jvm.deserialization.ModuleMappingKt;
import org.jetbrains.kotlin.metadata.jvm.deserialization.PackageParts;
import org.jetbrains.kotlin.metadata.serialization.StringTable;
import org.jetbrains.kotlin.name.ClassId;
import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.psi.KtFile;
import org.jetbrains.kotlin.resolve.CompilerDeserializationConfiguration;
import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt;
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin;
import org.jetbrains.kotlin.serialization.StringTableImpl;
import org.jetbrains.org.objectweb.asm.Type;
@@ -52,7 +44,6 @@ import org.jetbrains.org.objectweb.asm.Type;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.getMappingFileName;
@@ -134,11 +125,6 @@ public class ClassFileFactory implements OutputFileCollection {
StringTableImpl stringTable = new StringTableImpl();
ClassFileUtilsKt.addDataFromCompiledModule(builder, packagePartRegistry, stringTable, state);
List<String> experimental = state.getLanguageVersionSettings().getFlag(AnalysisFlags.getExperimental());
if (!experimental.isEmpty()) {
writeExperimentalMarkers(state.getModule(), builder, experimental, stringTable);
}
Pair<ProtoBuf.StringTable, ProtoBuf.QualifiedNameTable> tables = stringTable.buildProto();
builder.setStringTable(tables.getFirst());
builder.setQualifiedNameTable(tables.getSecond());
@@ -162,26 +148,6 @@ public class ClassFileFactory implements OutputFileCollection {
});
}
private static void writeExperimentalMarkers(
@NotNull ModuleDescriptor module,
@NotNull JvmModuleProtoBuf.Module.Builder builder,
@NotNull List<String> experimental,
@NotNull StringTable stringTable
) {
for (String fqName : experimental) {
ClassDescriptor descriptor =
DescriptorUtilKt.resolveClassByFqName(module, new FqName(fqName), NoLookupLocation.FOR_ALREADY_TRACKED);
if (descriptor != null) {
ProtoBuf.Annotation.Builder annotation = ProtoBuf.Annotation.newBuilder();
ClassId classId = DescriptorUtilsKt.getClassId(descriptor);
if (classId != null) {
annotation.setId(stringTable.getQualifiedClassNameIndex(classId.asString(), false));
builder.addAnnotation(annotation);
}
}
}
}
@NotNull
@Override
public List<OutputFile> asList() {

View File

@@ -475,7 +475,7 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
List<Type> superCtorArgTypes = new ArrayList<>();
if (superClassAsmType.equals(LAMBDA) || functionReferenceTarget != null ||
CoroutineCodegenUtilKt.isCoroutineSuperClass(state.getLanguageVersionSettings(), superClassAsmType.getInternalName())
CoroutineCodegenUtilKt.isCoroutineSuperClass(superClassAsmType.getInternalName())
) {
iv.iconst(CodegenUtilKt.getArity(funDescriptor));
superCtorArgTypes.add(Type.INT_TYPE);

View File

@@ -7,7 +7,7 @@ package org.jetbrains.kotlin.codegen
import org.jetbrains.kotlin.codegen.binding.CodegenBinding
import org.jetbrains.kotlin.codegen.inline.loadCompiledInlineFunction
import org.jetbrains.kotlin.codegen.optimization.nullCheck.isCheckParameterIsNotNull
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
@@ -17,10 +17,6 @@ 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) {
@@ -75,20 +71,7 @@ class DelegatedPropertiesCodegenHelper(private val state: GenerationState) {
val asmMethod = state.typeMapper.mapAsmMethod(calleeDescriptor)
val isMangled = requiresFunctionNameManglingForReturnType(calleeDescriptor)
val methodNode = loadCompiledInlineFunction(containerId, asmMethod, calleeDescriptor.isSuspend, isMangled, state).node
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()
return methodNode.usesLocalExceptParameterNullCheck(metadataParameterIndex)
}
private fun getMetadataParameterIndex(calleeDescriptor: FunctionDescriptor): Int {

View File

@@ -89,7 +89,6 @@ import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor;
import org.jetbrains.kotlin.types.*;
import org.jetbrains.kotlin.types.checker.ClassicTypeSystemContextImpl;
import org.jetbrains.kotlin.types.expressions.DoubleColonLHS;
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;
@@ -1264,7 +1263,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
// Thus, do not generate it. Otherwise, it leads to VerifyError on run-time.
boolean isCrossinlineLambda = (callGenerator instanceof PsiInlineCodegen) &&
Objects.requireNonNull(((PsiInlineCodegen) callGenerator).getActiveLambda(),
"no active lambda found").isCrossInline;
"no active lambda found").isCrossInline();
if (!isCrossinlineLambda) {
v.aconst(null);
}
@@ -1288,11 +1287,11 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@NotNull
private static CallableDescriptor unwrapOriginalReceiverOwnerForSuspendLambda(@NotNull MethodContext context) {
FunctionDescriptor originalForDoResume =
context.getFunctionDescriptor().getUserData(CoroutineCodegenUtilKt.INITIAL_SUSPEND_DESCRIPTOR_FOR_DO_RESUME);
FunctionDescriptor originalForInvokeSuspend =
context.getFunctionDescriptor().getUserData(CoroutineCodegenUtilKt.INITIAL_SUSPEND_DESCRIPTOR_FOR_INVOKE_SUSPEND);
if (originalForDoResume != null) {
return originalForDoResume;
if (originalForInvokeSuspend != null) {
return originalForInvokeSuspend;
}
if (context.getFunctionDescriptor().isSuspend()) {
@@ -2617,26 +2616,6 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
? coroutineInstanceValueForSuspensionPoint
: getContinuationParameterFromEnclosingSuspendFunction(resolvedCall);
if (coroutineInstanceValue != null && needsExperimentalCoroutinesWrapper(resolvedCall.getCandidateDescriptor())) {
StackValue releaseContinuation = coroutineInstanceValue;
coroutineInstanceValue = new StackValue(CoroutineCodegenUtilKt.EXPERIMENTAL_CONTINUATION_ASM_TYPE) {
@Override
public void putSelector(
@NotNull Type type, @Nullable KotlinType kotlinType, @NotNull InstructionAdapter v
) {
releaseContinuation.put(CoroutineCodegenUtilKt.RELEASE_CONTINUATION_ASM_TYPE, v);
invokeCoroutineMigrationMethod(
v,
"toExperimentalContinuation",
Type.getMethodDescriptor(
CoroutineCodegenUtilKt.EXPERIMENTAL_CONTINUATION_ASM_TYPE,
CoroutineCodegenUtilKt.RELEASE_CONTINUATION_ASM_TYPE
)
);
}
};
}
tempVariables.put(continuationExpression, coroutineInstanceValue);
}
@@ -2774,7 +2753,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
SuspensionPointKind suspensionPointKind =
CoroutineCodegenUtilKt.isSuspensionPoint(resolvedCall, this, state.getLanguageVersionSettings());
CoroutineCodegenUtilKt.isSuspensionPoint(resolvedCall, this);
boolean maybeSuspensionPoint = suspensionPointKind != SuspensionPointKind.NEVER && !insideCallableReference();
boolean isConstructor = resolvedCall.getResultingDescriptor() instanceof ConstructorDescriptor;
if (!(callableMethod instanceof IntrinsicWithSpecialReceiver)) {
@@ -2833,7 +2812,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
KotlinType unboxedInlineClass = CoroutineCodegenUtilKt.originalReturnTypeOfSuspendFunctionReturningUnboxedInlineClass(
(FunctionDescriptor) resolvedCall.getResultingDescriptor(), typeMapper);
if (unboxedInlineClass != null) {
CoroutineCodegenUtilKt.generateCoroutineSuspendedCheck(v, state.getLanguageVersionSettings());
CoroutineCodegenUtilKt.generateCoroutineSuspendedCheck(v);
}
}
@@ -2948,7 +2927,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
FunctionDescriptor original =
CoroutineCodegenUtilKt.getOriginalSuspendFunctionView(
unwrapInitialSignatureDescriptor(DescriptorUtils.unwrapFakeOverride((FunctionDescriptor) descriptor.getOriginal())),
bindingContext, state
bindingContext
);
FunctionDescriptor functionDescriptor =
@@ -2971,8 +2950,10 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
if (isDefaultCompilation) {
return new InlineCodegenForDefaultBody(functionDescriptor, this, state, signature, sourceCompiler);
} else {
return new PsiInlineCodegen(this, state, functionDescriptor, signature, typeParameterMappings, sourceCompiler,
typeMapper.mapImplementationOwner(functionDescriptor), typeMapper.mapOwner(descriptor));
return new PsiInlineCodegen(
this, state, functionDescriptor, signature, typeParameterMappings, sourceCompiler,
typeMapper.mapImplementationOwner(functionDescriptor), typeMapper.mapOwner(descriptor), callElement
);
}
}
@@ -5241,7 +5222,7 @@ The "returned" value of try expression with no finally is either the last expres
}
CodegenUtilKt.generateAsCast(
v, rightKotlinType, boxedRightType, safeAs, state.getLanguageVersionSettings(), state.getUnifiedNullChecks()
v, rightKotlinType, boxedRightType, safeAs, state.getUnifiedNullChecks()
);
return Unit.INSTANCE;
@@ -5295,7 +5276,7 @@ The "returned" value of try expression with no finally is either the last expres
return null;
}
CodegenUtilKt.generateIsCheck(v, rhsKotlinType, type, state.getLanguageVersionSettings().supportsFeature(LanguageFeature.ReleaseCoroutines));
CodegenUtilKt.generateIsCheck(v, rhsKotlinType, type);
return null;
});
}

View File

@@ -481,8 +481,7 @@ public class FunctionCodegen {
}
if (!functionDescriptor.isExternal()) {
generateMethodBody(mv, functionDescriptor, methodContext, jvmSignature, strategy, memberCodegen, state.getJvmDefaultMode(),
state.getLanguageVersionSettings().supportsFeature(LanguageFeature.ReleaseCoroutines));
generateMethodBody(mv, functionDescriptor, methodContext, jvmSignature, strategy, memberCodegen, state.getJvmDefaultMode());
}
else if (staticInCompanionObject) {
// native @JvmStatic foo() in companion object should delegate to the static native function moved to the outer class
@@ -583,8 +582,7 @@ public class FunctionCodegen {
@NotNull JvmMethodSignature signature,
@NotNull FunctionGenerationStrategy strategy,
@NotNull MemberCodegen<?> parentCodegen,
@NotNull JvmDefaultMode jvmDefaultMode,
boolean isReleaseCoroutines
@NotNull JvmDefaultMode jvmDefaultMode
) {
mv.visitCode();
@@ -594,8 +592,7 @@ public class FunctionCodegen {
KotlinTypeMapper typeMapper = parentCodegen.typeMapper;
if (BuiltinSpecialBridgesUtil.shouldHaveTypeSafeBarrier(functionDescriptor, typeMapper::mapAsmMethod)) {
generateTypeCheckBarrierIfNeeded(
new InstructionAdapter(mv), functionDescriptor, signature.getReturnType(), null, typeMapper,
isReleaseCoroutines);
new InstructionAdapter(mv), functionDescriptor, signature.getReturnType(), null, typeMapper);
}
Label methodEntry = null;
@@ -1430,8 +1427,7 @@ public class FunctionCodegen {
MemberCodegen.markLineNumberForDescriptor(owner.getThisDescriptor(), iv);
if (delegateTo.getArgumentTypes().length > 0 && isSpecialBridge) {
generateTypeCheckBarrierIfNeeded(iv, descriptor, bridge.getReturnType(), delegateTo.getArgumentTypes(), typeMapper,
state.getLanguageVersionSettings().supportsFeature(LanguageFeature.ReleaseCoroutines));
generateTypeCheckBarrierIfNeeded(iv, descriptor, bridge.getReturnType(), delegateTo.getArgumentTypes(), typeMapper);
}
iv.load(0, OBJECT_TYPE);
@@ -1477,8 +1473,7 @@ public class FunctionCodegen {
@NotNull FunctionDescriptor descriptor,
@NotNull Type returnType,
@Nullable Type[] delegateParameterTypes,
@NotNull KotlinTypeMapper typeMapper,
boolean isReleaseCoroutines
@NotNull KotlinTypeMapper typeMapper
) {
BuiltinMethodsWithSpecialGenericSignature.TypeSafeBarrierDescription typeSafeBarrierDescription =
BuiltinMethodsWithSpecialGenericSignature.getDefaultValueForOverriddenBuiltinFunction(descriptor);
@@ -1512,7 +1507,7 @@ public class FunctionCodegen {
} else {
targetBoxedType = boxType(delegateParameterTypes[i]);
}
CodegenUtilKt.generateIsCheck(iv, kotlinType, targetBoxedType, isReleaseCoroutines);
CodegenUtilKt.generateIsCheck(iv, kotlinType, targetBoxedType);
iv.ifeq(defaultBranch);
}
}

View File

@@ -5,13 +5,12 @@
package org.jetbrains.kotlin.codegen
import org.jetbrains.kotlin.builtins.StandardNames.COROUTINES_JVM_INTERNAL_PACKAGE_FQ_NAME
import org.jetbrains.kotlin.builtins.createFunctionType
import org.jetbrains.kotlin.codegen.coroutines.coroutinesJvmInternalPackageFqName
import org.jetbrains.kotlin.codegen.coroutines.getOrCreateJvmSuspendFunctionView
import org.jetbrains.kotlin.codegen.coroutines.isSuspendLambdaOrLocalFunction
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.config.isReleaseCoroutines
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor
@@ -33,8 +32,7 @@ class JvmRuntimeTypes(
private val generateOptimizedCallableReferenceSuperClasses: Boolean
) {
private val kotlinJvmInternalPackage = MutablePackageFragmentDescriptor(module, FqName("kotlin.jvm.internal"))
private val kotlinCoroutinesJvmInternalPackage =
MutablePackageFragmentDescriptor(module, languageVersionSettings.coroutinesJvmInternalPackageFqName())
private val kotlinCoroutinesJvmInternalPackage = MutablePackageFragmentDescriptor(module, COROUTINES_JVM_INTERNAL_PACKAGE_FQ_NAME)
private fun internal(className: String, packageFragment: PackageFragmentDescriptor = kotlinJvmInternalPackage): Lazy<ClassDescriptor> =
lazy { createClass(packageFragment, className) }
@@ -53,24 +51,16 @@ class JvmRuntimeTypes(
private val localVariableReference: ClassDescriptor by internal("LocalVariableReference")
private val mutableLocalVariableReference: ClassDescriptor by internal("MutableLocalVariableReference")
private val coroutineImpl: ClassDescriptor by internal("CoroutineImpl", kotlinCoroutinesJvmInternalPackage)
private val continuationImpl: ClassDescriptor by coroutinesInternal("ContinuationImpl")
private val restrictedContinuationImpl: ClassDescriptor by coroutinesInternal("RestrictedContinuationImpl")
private val suspendLambda: ClassDescriptor by coroutinesInternal("SuspendLambda")
private val restrictedSuspendLambda: ClassDescriptor by coroutinesInternal("RestrictedSuspendLambda")
private val suspendFunctionInterface: ClassDescriptor? by lazy {
if (languageVersionSettings.isReleaseCoroutines())
createClass(kotlinCoroutinesJvmInternalPackage, "SuspendFunction", ClassKind.INTERFACE)
else null
createClass(kotlinCoroutinesJvmInternalPackage, "SuspendFunction", ClassKind.INTERFACE)
}
private fun createCoroutineSuperClass(className: String): ClassDescriptor {
return if (languageVersionSettings.isReleaseCoroutines())
createClass(kotlinCoroutinesJvmInternalPackage, className)
else
coroutineImpl
}
private fun createCoroutineSuperClass(className: String): ClassDescriptor = createClass(kotlinCoroutinesJvmInternalPackage, className)
private val propertyReferences: List<ClassDescriptor> by propertyClasses("PropertyReference", "")
private val mutablePropertyReferences: List<ClassDescriptor> by propertyClasses("MutablePropertyReference", "")
@@ -94,7 +84,7 @@ class JvmRuntimeTypes(
fun getSupertypesForClosure(descriptor: FunctionDescriptor): Collection<KotlinType> {
val actualFunctionDescriptor =
if (descriptor.isSuspend)
getOrCreateJvmSuspendFunctionView(descriptor, languageVersionSettings.supportsFeature(LanguageFeature.ReleaseCoroutines))
getOrCreateJvmSuspendFunctionView(descriptor)
else
descriptor
@@ -118,7 +108,7 @@ class JvmRuntimeTypes(
if (descriptor.isSuspend) {
return mutableListOf<KotlinType>().apply {
if (actualFunctionDescriptor.extensionReceiverParameter?.type
?.isRestrictsSuspensionReceiver(languageVersionSettings) == true
?.isRestrictsSuspensionReceiver() == true
) {
if (descriptor.isSuspendLambdaOrLocalFunction()) {
add(restrictedSuspendLambda.defaultType)

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

@@ -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 >= 199) {
// 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
}
}
@@ -149,4 +166,4 @@ class StringConcatGenerator(val mode: JvmStringConcat, val mv: InstructionAdapte
StringConcatGenerator(state.runtimeStringConcat, mv)
}
}
}

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,8 +35,10 @@ 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.name.SpecialNames;
import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.psi.stubs.KotlinFileStub;
import org.jetbrains.kotlin.resolve.BindingContext;
@@ -90,6 +93,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 +104,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
@@ -294,7 +299,7 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
private String getName(ClassDescriptor classDescriptor) {
String base = peekFromStack(nameStack);
Name descriptorName = safeIdentifier(classDescriptor.getName());
Name descriptorName = SpecialNames.safeIdentifier(classDescriptor.getName());
if (DescriptorUtils.isTopLevelDeclaration(classDescriptor)) {
return base.isEmpty() ? descriptorName.asString() : base + '/' + descriptorName;
}
@@ -472,7 +477,6 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
SimpleFunctionDescriptor jvmSuspendFunctionView =
CoroutineCodegenUtilKt.getOrCreateJvmSuspendFunctionView(
functionDescriptor,
languageVersionSettings.supportsFeature(LanguageFeature.ReleaseCoroutines),
this.bindingContext
);
@@ -709,54 +713,6 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
super.visitCallExpression(expression);
checkSamCall(expression);
checkCrossinlineCall(expression);
recordSuspendFunctionTypeWrapperForArguments(expression);
}
private void recordSuspendFunctionTypeWrapperForArguments(@NotNull KtCallExpression expression) {
ResolvedCall<?> call = CallUtilKt.getResolvedCall(expression, bindingContext);
if (call == null) return;
CallableDescriptor descriptor = call.getResultingDescriptor();
if (!CodegenUtilKt.needsExperimentalCoroutinesWrapper(descriptor)) return;
List<ResolvedValueArgument> argumentsByIndex = call.getValueArgumentsByIndex();
if (argumentsByIndex == null) return;
for (ValueParameterDescriptor parameter : descriptor.getValueParameters()) {
ResolvedValueArgument resolvedValueArgument = argumentsByIndex.get(parameter.getIndex());
if (!(resolvedValueArgument instanceof ExpressionValueArgument)) continue;
ValueArgument valueArgument = ((ExpressionValueArgument) resolvedValueArgument).getValueArgument();
if (valueArgument == null) continue;
KtExpression argumentExpression = valueArgument.getArgumentExpression();
if (argumentExpression == null) continue;
recordSuspendFunctionTypeWrapperForArgument(parameter, argumentExpression);
}
ReceiverValue receiver = call.getExtensionReceiver();
if (descriptor.getExtensionReceiverParameter() != null && receiver instanceof ExpressionReceiver) {
recordSuspendFunctionTypeWrapperForArgument(
descriptor.getExtensionReceiverParameter(),
((ExpressionReceiver) receiver).getExpression()
);
}
}
private void recordSuspendFunctionTypeWrapperForArgument(ParameterDescriptor parameter, KtExpression argumentExpression) {
if (FunctionTypesKt.isSuspendFunctionTypeOrSubtype(parameter.getType())) {
// SuspendFunctionN type is mapped to is mapped to FunctionTypeN+1, but we also need to remove an argument for return type
// So, it could be parameter.getType().getArguments().size() + 1 - 1
int functionTypeArity = parameter.getType().getArguments().size();
Type functionType = Type.getObjectType(NUMBERED_FUNCTION_PREFIX + functionTypeArity);
bindingTrace.record(
FUNCTION_TYPE_FOR_SUSPEND_WRAPPER,
argumentExpression,
functionType
);
}
}
private void checkCrossinlineCall(@NotNull KtCallExpression expression) {
@@ -855,6 +811,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 +832,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 +844,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 +925,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 +942,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 +971,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

@@ -13,15 +13,13 @@ import org.jetbrains.kotlin.codegen.binding.CodegenBinding
import org.jetbrains.kotlin.codegen.context.CodegenContext
import org.jetbrains.kotlin.codegen.context.FieldOwnerContext
import org.jetbrains.kotlin.codegen.context.MultifileClassFacadeContext
import org.jetbrains.kotlin.codegen.coroutines.continuationAsmType
import org.jetbrains.kotlin.codegen.coroutines.CONTINUATION_ASM_TYPE
import org.jetbrains.kotlin.codegen.coroutines.unwrapInitialDescriptorForSuspendFunction
import org.jetbrains.kotlin.codegen.inline.NUMBERED_FUNCTION_PREFIX
import org.jetbrains.kotlin.codegen.inline.ReificationArgument
import org.jetbrains.kotlin.codegen.intrinsics.TypeIntrinsics
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.config.isReleaseCoroutines
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.deserialization.PLATFORM_DEPENDENT_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
@@ -45,8 +43,6 @@ import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import org.jetbrains.kotlin.resolve.jvm.diagnostics.Synthetic
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodGenericSignature
import org.jetbrains.kotlin.resolve.scopes.receivers.TransientReceiver
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberDescriptor
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberDescriptor.CoroutinesCompatibilityMode
import org.jetbrains.kotlin.types.ErrorUtils
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeSystemCommonBackendContext
@@ -70,8 +66,7 @@ internal val JAVA_LANG_DEPRECATED = Type.getType(Deprecated::class.java).descrip
fun generateIsCheck(
v: InstructionAdapter,
kotlinType: KotlinType,
asmType: Type,
isReleaseCoroutines: Boolean
asmType: Type
) {
if (TypeUtils.isNullableType(kotlinType)) {
val nope = Label()
@@ -82,7 +77,7 @@ fun generateIsCheck(
ifnull(nope)
TypeIntrinsics.instanceOf(this, kotlinType, asmType, isReleaseCoroutines)
TypeIntrinsics.instanceOf(this, kotlinType, asmType)
goTo(end)
@@ -93,7 +88,7 @@ fun generateIsCheck(
mark(end)
}
} else {
TypeIntrinsics.instanceOf(v, kotlinType, asmType, isReleaseCoroutines)
TypeIntrinsics.instanceOf(v, kotlinType, asmType)
}
}
@@ -102,7 +97,6 @@ fun generateAsCast(
kotlinType: KotlinType,
asmType: Type,
isSafe: Boolean,
languageVersionSettings: LanguageVersionSettings,
unifiedNullChecks: Boolean,
) {
if (!isSafe) {
@@ -112,7 +106,7 @@ fun generateAsCast(
} else {
with(v) {
dup()
TypeIntrinsics.instanceOf(v, kotlinType, asmType, languageVersionSettings.isReleaseCoroutines())
TypeIntrinsics.instanceOf(v, kotlinType, asmType)
val ok = Label()
ifne(ok)
pop()
@@ -444,14 +438,10 @@ fun KotlinType.isInlineClassTypeWithPrimitiveEquality(): Boolean {
return false
}
fun CallableDescriptor.needsExperimentalCoroutinesWrapper() =
(this as? DeserializedMemberDescriptor)?.coroutinesExperimentalCompatibilityMode == CoroutinesCompatibilityMode.NEEDS_WRAPPER
fun recordCallLabelForLambdaArgument(declaration: KtFunctionLiteral, bindingTrace: BindingTrace) {
val labelName = getCallLabelForLambdaArgument(declaration, bindingTrace.bindingContext) ?: return
val functionDescriptor = bindingTrace[BindingContext.FUNCTION, declaration] ?: return
bindingTrace.record(CodegenBinding.CALL_LABEL_FOR_LAMBDA_ARGUMENT, functionDescriptor, labelName)
}
fun getCallLabelForLambdaArgument(declaration: KtFunctionLiteral, bindingContext: BindingContext): String? {
@@ -647,7 +637,7 @@ private fun generateLambdaForRunSuspend(
}
visitVarInsn(ALOAD, 1)
val continuationInternalName = state.languageVersionSettings.continuationAsmType().internalName
val continuationInternalName = CONTINUATION_ASM_TYPE.internalName
visitTypeInsn(
CHECKCAST,

View File

@@ -6,9 +6,9 @@
package org.jetbrains.kotlin.codegen.context
import org.jetbrains.kotlin.backend.common.isBuiltInSuspendCoroutineUninterceptedOrReturn
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.codegen.OwnerKind
import org.jetbrains.kotlin.codegen.binding.MutableClosure
import org.jetbrains.kotlin.config.coroutinesPackageFqName
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor
import org.jetbrains.kotlin.descriptors.isTopLevelInPackage
@@ -17,25 +17,26 @@ import org.jetbrains.kotlin.resolve.calls.callUtil.getParentResolvedCall
import org.jetbrains.kotlin.resolve.source.getPsi
class InlineLambdaContext(
functionDescriptor: FunctionDescriptor,
contextKind: OwnerKind,
parentContext: CodegenContext<*>,
closure: MutableClosure?,
val isCrossInline: Boolean,
private val isPropertyReference: Boolean
functionDescriptor: FunctionDescriptor,
contextKind: OwnerKind,
parentContext: CodegenContext<*>,
closure: MutableClosure?,
val isCrossInline: Boolean,
private val isPropertyReference: Boolean
) : MethodContext(functionDescriptor, contextKind, parentContext, closure, false) {
override fun getFirstCrossInlineOrNonInlineContext(): CodegenContext<*> {
if (isCrossInline && !isSuspendIntrinsicParameter()) return this
val parent = if (isPropertyReference) parentContext as? AnonymousClassContext else { parentContext as? ClosureContext } ?:
throw AssertionError(
"Parent of inlining lambda body should be " +
"${if (isPropertyReference) "ClosureContext" else "AnonymousClassContext"}, but: $parentContext"
)
val parent = if (isPropertyReference) parentContext as? AnonymousClassContext else {
parentContext as? ClosureContext
} ?: throw AssertionError(
"Parent of inlining lambda body should be " +
"${if (isPropertyReference) "ClosureContext" else "AnonymousClassContext"}, but: $parentContext"
)
val grandParent = parent.parentContext ?:
throw AssertionError("Parent context of lambda class context should exist: $contextDescriptor")
val grandParent =
parent.parentContext ?: throw AssertionError("Parent context of lambda class context should exist: $contextDescriptor")
return grandParent.firstCrossInlineOrNonInlineContext
}
@@ -44,7 +45,7 @@ class InlineLambdaContext(
if (contextDescriptor !is AnonymousFunctionDescriptor) return false
val resolvedCall = (contextDescriptor.source.getPsi() as? KtElement).getParentResolvedCall(state.bindingContext) ?: return false
val descriptor = resolvedCall.resultingDescriptor as? FunctionDescriptor ?: return false
return descriptor.isBuiltInSuspendCoroutineUninterceptedOrReturn(state.languageVersionSettings)
|| descriptor.isTopLevelInPackage("suspendCoroutine", state.languageVersionSettings.coroutinesPackageFqName().asString())
return descriptor.isBuiltInSuspendCoroutineUninterceptedOrReturn()
|| descriptor.isTopLevelInPackage("suspendCoroutine", StandardNames.COROUTINES_PACKAGE_FQ_NAME.asString())
}
}

View File

@@ -5,6 +5,7 @@
package org.jetbrains.kotlin.codegen.coroutines
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.codegen.optimization.boxing.isPrimitiveBoxing
import org.jetbrains.kotlin.codegen.optimization.common.asSequence
import org.jetbrains.kotlin.codegen.optimization.transformer.MethodTransformer
@@ -15,10 +16,9 @@ import org.jetbrains.kotlin.utils.sure
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.tree.MethodInsnNode
import org.jetbrains.org.objectweb.asm.tree.MethodNode
import java.util.*
private val BOXING_CLASS_INTERNAL_NAME =
RELEASE_COROUTINES_VERSION_SETTINGS.coroutinesJvmInternalPackageFqName().child(Name.identifier("Boxing")).topLevelClassInternalName()
StandardNames.COROUTINES_JVM_INTERNAL_PACKAGE_FQ_NAME.child(Name.identifier("Boxing")).topLevelClassInternalName()
@OptIn(ExperimentalStdlibApi::class)
object ChangeBoxingMethodTransformer : MethodTransformer() {

View File

@@ -7,6 +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.StandardNames
import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.binding.CodegenBinding
import org.jetbrains.kotlin.codegen.binding.CodegenBinding.CAPTURES_CROSSINLINE_LAMBDA
@@ -17,8 +18,6 @@ import org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings.METHO
import org.jetbrains.kotlin.codegen.serialization.JvmSerializerExtension
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.config.JVMConfigurationKeys
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.isReleaseCoroutines
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor
@@ -41,7 +40,6 @@ import org.jetbrains.kotlin.resolve.jvm.diagnostics.OtherOrigin
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature
import org.jetbrains.kotlin.serialization.DescriptorSerializer
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.makeNullable
import org.jetbrains.kotlin.utils.sure
import org.jetbrains.org.objectweb.asm.Label
import org.jetbrains.org.objectweb.asm.MethodVisitor
@@ -56,7 +54,7 @@ abstract class AbstractCoroutineCodegen(
element: KtElement,
closureContext: ClosureContext,
classBuilder: ClassBuilder,
private val userDataForDoResume: Map<out CallableDescriptor.UserDataKey<*>, *>? = null
private val userDataForInvokeSuspend: Map<out CallableDescriptor.UserDataKey<*>, *>? = null
) : ClosureCodegen(
outerExpressionCodegen.state,
element, null, closureContext, null,
@@ -67,17 +65,10 @@ abstract class AbstractCoroutineCodegen(
protected val languageVersionSettings = outerExpressionCodegen.state.languageVersionSettings
protected val methodToImplement =
if (languageVersionSettings.isReleaseCoroutines())
createImplMethod(
INVOKE_SUSPEND_METHOD_NAME,
SUSPEND_CALL_RESULT_NAME to classDescriptor.module.getResult(classDescriptor.builtIns.anyType)
)
else
createImplMethod(
DO_RESUME_METHOD_NAME,
"data" to classDescriptor.builtIns.nullableAnyType,
"throwable" to classDescriptor.builtIns.throwable.defaultType.makeNullable()
)
createImplMethod(
INVOKE_SUSPEND_METHOD_NAME,
SUSPEND_CALL_RESULT_NAME to classDescriptor.module.getResult(classDescriptor.builtIns.anyType)
)
private fun createImplMethod(name: String, vararg parameters: Pair<String, KotlinType>) =
SimpleFunctionDescriptorImpl.create(
@@ -94,7 +85,7 @@ abstract class AbstractCoroutineCodegen(
builtIns.nullableAnyType,
Modality.FINAL,
DescriptorVisibilities.PUBLIC,
userDataForDoResume
userDataForInvokeSuspend
)
}
@@ -109,7 +100,7 @@ abstract class AbstractCoroutineCodegen(
override fun generateConstructor(): Method {
val args = calculateConstructorParameters(typeMapper, languageVersionSettings, closure, asmType)
val argTypes = args.map { it.fieldType }.plus(languageVersionSettings.continuationAsmType()).toTypedArray()
val argTypes = args.map { it.fieldType }.plus(CONTINUATION_ASM_TYPE).toTypedArray()
val constructor = Method("<init>", Type.VOID_TYPE, argTypes)
val mv = v.newMethod(
@@ -124,18 +115,17 @@ abstract class AbstractCoroutineCodegen(
iv.generateClosureFieldsInitializationFromParameters(closure, args)
iv.load(0, AsmTypes.OBJECT_TYPE)
val hasArityParameter = !languageVersionSettings.isReleaseCoroutines() || passArityToSuperClass
if (hasArityParameter) {
iv.iconst(if (passArityToSuperClass) funDescriptor.arity else 0)
if (passArityToSuperClass) {
iv.iconst(funDescriptor.arity)
}
iv.load(argTypes.map { it.size }.sum(), AsmTypes.OBJECT_TYPE)
val parameters =
if (hasArityParameter)
listOf(Type.INT_TYPE, languageVersionSettings.continuationAsmType())
if (passArityToSuperClass)
listOf(Type.INT_TYPE, CONTINUATION_ASM_TYPE)
else
listOf(languageVersionSettings.continuationAsmType())
listOf(CONTINUATION_ASM_TYPE)
val superClassConstructorDescriptor = Type.getMethodDescriptor(
Type.VOID_TYPE,
@@ -148,9 +138,7 @@ abstract class AbstractCoroutineCodegen(
FunctionCodegen.endVisit(iv, "constructor", element)
}
if (languageVersionSettings.isReleaseCoroutines()) {
v.newField(JvmDeclarationOrigin.NO_ORIGIN, AsmUtil.NO_FLAG_PACKAGE_PRIVATE, "label", "I", null, null)
}
v.newField(JvmDeclarationOrigin.NO_ORIGIN, AsmUtil.NO_FLAG_PACKAGE_PRIVATE, "label", "I", null, null)
return constructor
}
@@ -167,7 +155,7 @@ class CoroutineCodegenForLambda private constructor(
private val forInline: Boolean
) : AbstractCoroutineCodegen(
outerExpressionCodegen, element, closureContext, classBuilder,
userDataForDoResume = mapOf(INITIAL_SUSPEND_DESCRIPTOR_FOR_DO_RESUME to originalSuspendFunctionDescriptor)
userDataForInvokeSuspend = mapOf(INITIAL_SUSPEND_DESCRIPTOR_FOR_INVOKE_SUSPEND to originalSuspendFunctionDescriptor)
) {
private val builtIns = funDescriptor.builtIns
@@ -215,8 +203,7 @@ class CoroutineCodegenForLambda private constructor(
funDescriptor.typeParameters,
funDescriptor.valueParameters,
funDescriptor.module.getContinuationOfTypeOrAny(
builtIns.unitType,
state.languageVersionSettings.supportsFeature(LanguageFeature.ReleaseCoroutines)
builtIns.unitType
),
funDescriptor.modality,
DescriptorVisibilities.PUBLIC
@@ -231,14 +218,11 @@ class CoroutineCodegenForLambda private constructor(
"too many arguments of create to have an erased signature: $argumentsNum: $typedCreate"
}
return typedCreate.module.resolveClassByFqName(
languageVersionSettings.coroutinesJvmInternalPackageFqName().child(
if (languageVersionSettings.isReleaseCoroutines())
Name.identifier("BaseContinuationImpl")
else
Name.identifier("CoroutineImpl")
StandardNames.COROUTINES_JVM_INTERNAL_PACKAGE_FQ_NAME.child(
Name.identifier("BaseContinuationImpl")
),
NoLookupLocation.FROM_BACKEND
).sure { "BaseContinuationImpl or CoroutineImpl is not found" }.defaultType.memberScope
).sure { "BaseContinuationImpl is not found" }.defaultType.memberScope
.getContributedFunctions(typedCreate.name, NoLookupLocation.FROM_BACKEND)
.find { it.valueParameters.size == argumentsNum }
.sure { "erased parent of $typedCreate is not found" }
@@ -365,7 +349,7 @@ class CoroutineCodegenForLambda private constructor(
v.thisName,
typeMapper.mapFunctionName(createCoroutineDescriptor, null),
Type.getMethodDescriptor(
languageVersionSettings.continuationAsmType(),
CONTINUATION_ASM_TYPE,
*createArgumentTypes.toTypedArray()
),
false
@@ -373,11 +357,7 @@ class CoroutineCodegenForLambda private constructor(
checkcast(Type.getObjectType(v.thisName))
// .doResume(Unit)
if (languageVersionSettings.isReleaseCoroutines()) {
invokeInvokeSuspendWithUnit(v.thisName)
} else {
invokeDoResumeWithUnit(v.thisName)
}
invokeInvokeSuspendWithUnit(v.thisName)
areturn(AsmTypes.OBJECT_TYPE)
}
@@ -540,15 +520,14 @@ class CoroutineCodegenForLambda private constructor(
override fun wrapMethodVisitor(mv: MethodVisitor, access: Int, name: String, desc: String): MethodVisitor {
val stateMachineBuilder = CoroutineTransformerMethodVisitor(
mv, access, name, desc, null, null,
containingClassInternalName = v.thisName,
obtainClassBuilderForCoroutineState = { v },
isForNamedFunction = false,
shouldPreserveClassInitialization = constructorCallNormalizationMode.shouldPreserveClassInitialization,
disableTailCallOptimizationForFunctionReturningUnit = false,
reportSuspensionPointInsideMonitor = { reportSuspensionPointInsideMonitor(element, state, it) },
lineNumber = CodegenUtil.getLineNumberForElement(element, false) ?: 0,
sourceFile = element.containingKtFile.name,
shouldPreserveClassInitialization = constructorCallNormalizationMode.shouldPreserveClassInitialization,
containingClassInternalName = v.thisName,
isForNamedFunction = false,
languageVersionSettings = languageVersionSettings,
disableTailCallOptimizationForFunctionReturningUnit = false,
useOldSpilledVarTypeAnalysis = state.configuration.getBoolean(JVMConfigurationKeys.USE_OLD_SPILLED_VAR_TYPE_ANALYSIS),
initialVarsCountByType = varsCountByType
)
@@ -625,7 +604,7 @@ class CoroutineCodegenForNamedFunction private constructor(
private val labelFieldStackValue by lazy {
StackValue.field(
FieldInfo.createForHiddenField(
computeLabelOwner(languageVersionSettings, v.thisName),
Type.getObjectType(v.thisName),
Type.INT_TYPE,
COROUTINE_LABEL_FIELD_NAME
),
@@ -647,44 +626,25 @@ class CoroutineCodegenForNamedFunction private constructor(
}
override fun generateClosureBody() {
generateResumeImpl()
if (!languageVersionSettings.isReleaseCoroutines()) {
generateGetLabelMethod()
generateSetLabelMethod()
}
generateInvokeSuspend()
v.newField(
JvmDeclarationOrigin.NO_ORIGIN, Opcodes.ACC_SYNTHETIC or AsmUtil.NO_FLAG_PACKAGE_PRIVATE,
languageVersionSettings.dataFieldName(), AsmTypes.OBJECT_TYPE.descriptor, null, null
CONTINUATION_RESULT_FIELD_NAME, AsmTypes.OBJECT_TYPE.descriptor, null, null
)
if (!languageVersionSettings.isReleaseCoroutines()) {
v.newField(
JvmDeclarationOrigin.NO_ORIGIN, Opcodes.ACC_SYNTHETIC or AsmUtil.NO_FLAG_PACKAGE_PRIVATE,
EXCEPTION_FIELD_NAME, AsmTypes.JAVA_THROWABLE_TYPE.descriptor, null, null
)
}
}
private fun generateResumeImpl() {
private fun generateInvokeSuspend() {
functionCodegen.generateMethod(
OtherOrigin(element),
methodToImplement,
object : FunctionGenerationStrategy.CodegenBased(state) {
override fun doGenerateBody(codegen: ExpressionCodegen, signature: JvmMethodSignature) {
StackValue.field(
AsmTypes.OBJECT_TYPE, Type.getObjectType(v.thisName), languageVersionSettings.dataFieldName(), false,
AsmTypes.OBJECT_TYPE, Type.getObjectType(v.thisName), CONTINUATION_RESULT_FIELD_NAME, false,
StackValue.LOCAL_0
).store(StackValue.local(1, AsmTypes.OBJECT_TYPE), codegen.v)
if (!languageVersionSettings.isReleaseCoroutines()) {
StackValue.field(
AsmTypes.JAVA_THROWABLE_TYPE, Type.getObjectType(v.thisName), EXCEPTION_FIELD_NAME, false,
StackValue.LOCAL_0
).store(StackValue.local(2, AsmTypes.JAVA_THROWABLE_TYPE), codegen.v)
}
labelFieldStackValue.store(
StackValue.operation(Type.INT_TYPE) {
labelFieldStackValue.put(Type.INT_TYPE, it)
@@ -736,7 +696,7 @@ class CoroutineCodegenForNamedFunction private constructor(
with(codegen.v) {
// We need to box the returned inline class in resume path.
// But first, check for COROUTINE_SUSPENDED, since the function can return it
generateCoroutineSuspendedCheck(languageVersionSettings)
generateCoroutineSuspendedCheck()
// Now we box the inline class
StackValue.coerce(AsmTypes.OBJECT_TYPE, typeMapper.mapType(inlineClassToBoxInInvokeSuspend), this)
StackValue.boxInlineClass(inlineClassToBoxInInvokeSuspend, this, typeMapper)

View File

@@ -9,15 +9,10 @@ import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.inline.*
import org.jetbrains.kotlin.codegen.optimization.common.*
import org.jetbrains.kotlin.codegen.optimization.fixStack.FixStackMethodTransformer
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.config.isReleaseCoroutines
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import org.jetbrains.kotlin.utils.sure
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.*
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
import org.jetbrains.org.objectweb.asm.tree.*
import org.jetbrains.org.objectweb.asm.tree.analysis.BasicValue
@@ -49,7 +44,6 @@ class CoroutineTransformerMethodVisitor(
obtainClassBuilderForCoroutineState: () -> ClassBuilder,
private val isForNamedFunction: Boolean,
private val shouldPreserveClassInitialization: Boolean,
private val languageVersionSettings: LanguageVersionSettings,
// Since tail-call optimization of functions with Unit return type relies on ability of call-site to recognize them,
// in order to ignore return value and push Unit, when we cannot ensure this ability, for example, when the function overrides function,
// returning Any, we need to disable tail-call optimization for these functions.
@@ -73,7 +67,6 @@ class CoroutineTransformerMethodVisitor(
private var continuationIndex = if (isForNamedFunction) -1 else 0
private var dataIndex = if (isForNamedFunction) -1 else 1
private var exceptionIndex = if (isForNamedFunction || languageVersionSettings.isReleaseCoroutines()) -1 else 2
override fun performTransformations(methodNode: MethodNode) {
removeFakeContinuationConstructorCall(methodNode)
@@ -89,9 +82,7 @@ class CoroutineTransformerMethodVisitor(
val suspensionPoints = collectSuspensionPoints(methodNode)
RedundantLocalsEliminationMethodTransformer(suspensionPoints)
.transform(containingClassInternalName, methodNode)
if (languageVersionSettings.isReleaseCoroutines()) {
ChangeBoxingMethodTransformer.transform(containingClassInternalName, methodNode)
}
ChangeBoxingMethodTransformer.transform(containingClassInternalName, methodNode)
updateMaxStack(methodNode)
checkForSuspensionPointInsideMonitor(methodNode, suspensionPoints)
@@ -105,7 +96,6 @@ class CoroutineTransformerMethodVisitor(
}
val examiner = MethodNodeExaminer(
languageVersionSettings,
containingClassInternalName,
methodNode,
suspensionPoints,
@@ -119,9 +109,6 @@ class CoroutineTransformerMethodVisitor(
}
dataIndex = methodNode.maxLocals++
if (!languageVersionSettings.isReleaseCoroutines()) {
exceptionIndex = methodNode.maxLocals++
}
continuationIndex = methodNode.maxLocals++
prepareMethodNodePreludeForNamedFunction(methodNode)
@@ -136,8 +123,6 @@ class CoroutineTransformerMethodVisitor(
UninitializedStoresProcessor(methodNode, shouldPreserveClassInitialization).run()
updateLvtAccordingToLiveness(methodNode, isForNamedFunction)
val spilledToVariableMapping = spillVariables(suspensionPoints, methodNode)
val suspendMarkerVarIndex = methodNode.maxLocals++
@@ -160,7 +145,7 @@ class CoroutineTransformerMethodVisitor(
insertBefore(
actualCoroutineStart,
insnListOf(
*withInstructionAdapter { loadCoroutineSuspendedMarker(languageVersionSettings) }.toArray(),
*withInstructionAdapter { loadCoroutineSuspendedMarker() }.toArray(),
tableSwitchLabel,
// Allow debugger to stop on enter into suspend function
LineNumberNode(lineNumber, tableSwitchLabel),
@@ -178,7 +163,7 @@ class CoroutineTransformerMethodVisitor(
)
insert(firstStateLabel, withInstructionAdapter {
generateResumeWithExceptionCheck(languageVersionSettings.isReleaseCoroutines(), dataIndex, exceptionIndex)
generateResumeWithExceptionCheck(dataIndex)
})
insert(last, defaultLabel)
@@ -194,9 +179,9 @@ class CoroutineTransformerMethodVisitor(
dropUnboxInlineClassMarkers(methodNode, suspensionPoints)
methodNode.removeEmptyCatchBlocks()
if (languageVersionSettings.isReleaseCoroutines()) {
writeDebugMetadata(methodNode, suspensionPointLineNumbers, spilledToVariableMapping)
}
updateLvtAccordingToLiveness(methodNode, isForNamedFunction, stateLabels)
writeDebugMetadata(methodNode, suspensionPointLineNumbers, spilledToVariableMapping)
}
// When suspension point is inlined, it is in range of fake inliner variables.
@@ -263,7 +248,7 @@ class CoroutineTransformerMethodVisitor(
methodNode.localVariables.add(
LocalVariableNode(
SUSPEND_FUNCTION_COMPLETION_PARAMETER_NAME,
languageVersionSettings.continuationAsmType().descriptor,
CONTINUATION_ASM_TYPE.descriptor,
null,
startLabel,
endLabel,
@@ -402,7 +387,7 @@ class CoroutineTransformerMethodVisitor(
methodNode.instructions.add(withInstructionAdapter { mark(endLabel) })
methodNode.visitLocalVariable(
CONTINUATION_VARIABLE_NAME,
languageVersionSettings.continuationAsmType().descriptor,
CONTINUATION_ASM_TYPE.descriptor,
null,
startLabel,
endLabel,
@@ -430,33 +415,17 @@ class CoroutineTransformerMethodVisitor(
}
private fun InstructionAdapter.getLabel() {
if (isForNamedFunction && !languageVersionSettings.isReleaseCoroutines())
invokevirtual(
classBuilderForCoroutineState.thisName,
"getLabel",
Type.getMethodDescriptor(Type.INT_TYPE),
false
)
else
getfield(
computeLabelOwner(languageVersionSettings, classBuilderForCoroutineState.thisName).internalName,
COROUTINE_LABEL_FIELD_NAME, Type.INT_TYPE.descriptor
)
getfield(
Type.getObjectType(classBuilderForCoroutineState.thisName).internalName,
COROUTINE_LABEL_FIELD_NAME, Type.INT_TYPE.descriptor
)
}
private fun InstructionAdapter.setLabel() {
if (isForNamedFunction && !languageVersionSettings.isReleaseCoroutines())
invokevirtual(
classBuilderForCoroutineState.thisName,
"setLabel",
Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE),
false
)
else
putfield(
computeLabelOwner(languageVersionSettings, classBuilderForCoroutineState.thisName).internalName,
COROUTINE_LABEL_FIELD_NAME, Type.INT_TYPE.descriptor
)
putfield(
Type.getObjectType(classBuilderForCoroutineState.thisName).internalName,
COROUTINE_LABEL_FIELD_NAME, Type.INT_TYPE.descriptor
)
}
private fun updateMaxStack(methodNode: MethodNode) {
@@ -534,8 +503,7 @@ class CoroutineTransformerMethodVisitor(
needDispatchReceiver,
internalNameForDispatchReceiver,
containingClassInternalName,
classBuilderForCoroutineState,
languageVersionSettings
classBuilderForCoroutineState
)
visitVarInsn(Opcodes.ASTORE, continuationIndex)
@@ -543,19 +511,13 @@ class CoroutineTransformerMethodVisitor(
visitLabel(afterCoroutineStateCreated)
visitVarInsn(Opcodes.ALOAD, continuationIndex)
getfield(classBuilderForCoroutineState.thisName, languageVersionSettings.dataFieldName(), AsmTypes.OBJECT_TYPE.descriptor)
getfield(classBuilderForCoroutineState.thisName, CONTINUATION_RESULT_FIELD_NAME, AsmTypes.OBJECT_TYPE.descriptor)
visitVarInsn(Opcodes.ASTORE, dataIndex)
val resultStartLabel = Label()
visitLabel(resultStartLabel)
addContinuationAndResultToLvt(methodNode, afterCoroutineStateCreated, resultStartLabel)
if (!languageVersionSettings.isReleaseCoroutines()) {
visitVarInsn(Opcodes.ALOAD, continuationIndex)
getfield(classBuilderForCoroutineState.thisName, EXCEPTION_FIELD_NAME, AsmTypes.JAVA_THROWABLE_TYPE.descriptor)
visitVarInsn(Opcodes.ASTORE, exceptionIndex)
}
})
}
@@ -692,7 +654,7 @@ class CoroutineTransformerMethodVisitor(
// k + 1 - data
// k + 2 - exception
for (slot in 0 until localsCount) {
if (slot == continuationIndex || slot == dataIndex || slot == exceptionIndex) continue
if (slot == continuationIndex || slot == dataIndex) continue
val value = frame.getLocal(slot)
if (value.type == null || !livenessFrame.isAlive(slot)) continue
@@ -791,19 +753,30 @@ class CoroutineTransformerMethodVisitor(
// Mutate method node
fun generateSpillAndUnspill(suspension: SuspensionPoint, slot: Int, spillableVariable: SpillableVariable?) {
if (spillableVariable == null) {
with(instructions) {
insert(suspension.tryCatchBlockEndLabelAfterSuspensionCall, withInstructionAdapter {
aconst(null)
store(slot, AsmTypes.OBJECT_TYPE)
})
fun splitLvtRecord(local: LocalVariableNode?, localRestart: LabelNode) {
// 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
)
)
}
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()
@@ -817,6 +790,19 @@ class CoroutineTransformerMethodVisitor(
}
}
if (spillableVariable == null) {
with(instructions) {
insert(suspension.tryCatchBlockEndLabelAfterSuspensionCall, withInstructionAdapter {
aconst(null)
store(slot, AsmTypes.OBJECT_TYPE)
})
}
val newStart = suspension.tryCatchBlocksContinuationLabel.findNextOrNull { it is LabelNode } as? LabelNode ?: return
splitLvtRecord(local, newStart)
return
}
val localRestart = LabelNode().linkWithLabel()
with(instructions) {
// store variable before suspension call
insertBefore(suspension.suspensionCallBegin, withInstructionAdapter {
@@ -846,25 +832,7 @@ class CoroutineTransformerMethodVisitor(
})
}
// 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
)
)
}
splitLvtRecord(local, localRestart)
}
fun cleanUpField(suspension: SuspensionPoint, fieldIndex: Int) {
@@ -986,7 +954,7 @@ class CoroutineTransformerMethodVisitor(
insert(possibleTryCatchBlockStart, withInstructionAdapter {
nop()
generateResumeWithExceptionCheck(languageVersionSettings.isReleaseCoroutines(), dataIndex, exceptionIndex)
generateResumeWithExceptionCheck(dataIndex)
// Load continuation argument just like suspending function returns it
load(dataIndex, AsmTypes.OBJECT_TYPE)
@@ -1112,8 +1080,7 @@ internal fun InstructionAdapter.generateContinuationConstructorCall(
needDispatchReceiver: Boolean,
internalNameForDispatchReceiver: String?,
containingClassInternalName: String,
classBuilderForCoroutineState: ClassBuilder,
languageVersionSettings: LanguageVersionSettings
classBuilderForCoroutineState: ClassBuilder
) {
anew(objectTypeForState)
dup()
@@ -1122,8 +1089,7 @@ internal fun InstructionAdapter.generateContinuationConstructorCall(
getParameterTypesIndicesForCoroutineConstructor(
methodNode.desc,
methodNode.access,
needDispatchReceiver, internalNameForDispatchReceiver ?: containingClassInternalName,
languageVersionSettings
needDispatchReceiver, internalNameForDispatchReceiver ?: containingClassInternalName
)
for ((type, index) in parameterTypesAndIndices) {
load(index, type)
@@ -1143,22 +1109,11 @@ internal fun InstructionAdapter.generateContinuationConstructorCall(
)
}
private fun InstructionAdapter.generateResumeWithExceptionCheck(isReleaseCoroutines: Boolean, dataIndex: Int, exceptionIndex: Int) {
private fun InstructionAdapter.generateResumeWithExceptionCheck(dataIndex: Int) {
// Check if resumeWithException has been called
if (isReleaseCoroutines) {
load(dataIndex, AsmTypes.OBJECT_TYPE)
invokestatic("kotlin/ResultKt", "throwOnFailure", "(Ljava/lang/Object;)V", false)
} else {
load(exceptionIndex, AsmTypes.OBJECT_TYPE)
dup()
val noExceptionLabel = Label()
ifnull(noExceptionLabel)
athrow()
mark(noExceptionLabel)
pop()
}
load(dataIndex, AsmTypes.OBJECT_TYPE)
invokestatic("kotlin/ResultKt", "throwOnFailure", "(Ljava/lang/Object;)V", false)
}
private fun Type.fieldNameForVar(index: Int) = descriptor.first() + "$" + index
@@ -1229,16 +1184,15 @@ private fun getParameterTypesIndicesForCoroutineConstructor(
desc: String,
containingFunctionAccess: Int,
needDispatchReceiver: Boolean,
thisName: String,
languageVersionSettings: LanguageVersionSettings
thisName: String
): Collection<Pair<Type, Int>> {
return mutableListOf<Pair<Type, Int>>().apply {
if (needDispatchReceiver) {
add(Type.getObjectType(thisName) to 0)
}
val continuationIndex =
getAllParameterTypes(desc, !isStatic(containingFunctionAccess), thisName).dropLast(1).map(Type::getSize).sum()
add(languageVersionSettings.continuationAsmType() to continuationIndex)
getAllParameterTypes(desc, !isStatic(containingFunctionAccess), thisName).dropLast(1).sumOf(Type::getSize)
add(CONTINUATION_ASM_TYPE to continuationIndex)
}
}
@@ -1254,13 +1208,16 @@ internal fun replaceFakeContinuationsWithRealOnes(methodNode: MethodNode, contin
}
}
private fun MethodNode.nodeTextWithLiveness(liveness: List<VariableLivenessFrame>): String =
liveness.zip(this.instructions.asSequence().toList()).joinToString("\n") { (a, b) -> "$a|${b.insnText}" }
/* We do not want to spill dead variables, thus, we shrink its LVT record to region, where the variable is alive,
* so, the variable will not be visible in debugger. User can still prolong life span of the variable by using it.
*
* This means, that function parameters do not longer span the whole function, including `this`.
* This might and will break some bytecode processors, including old versions of R8. See KT-24510.
*/
private fun updateLvtAccordingToLiveness(method: MethodNode, isForNamedFunction: Boolean) {
private fun updateLvtAccordingToLiveness(method: MethodNode, isForNamedFunction: Boolean, suspensionPoints: List<LabelNode>) {
val liveness = analyzeLiveness(method)
fun List<LocalVariableNode>.findRecord(insnIndex: Int, variableIndex: Int): LocalVariableNode? {
@@ -1288,17 +1245,15 @@ private fun updateLvtAccordingToLiveness(method: MethodNode, isForNamedFunction:
fun min(a: LabelNode, b: LabelNode): LabelNode =
if (method.instructions.indexOf(a) < method.instructions.indexOf(b)) a else b
fun max(a: LabelNode, b: LabelNode): LabelNode =
if (method.instructions.indexOf(a) < method.instructions.indexOf(b)) b else a
val oldLvt = arrayListOf<LocalVariableNode>()
for (record in method.localVariables) {
oldLvt += record
}
method.localVariables.clear()
val oldLvtNodeToLatestNewLvtNode = mutableMapOf<LocalVariableNode, LocalVariableNode>()
// Skip `this` for suspend lambda
val start = if (isForNamedFunction) 0 else 1
val oldLvtNodeToLatestNewLvtNode = mutableMapOf<LocalVariableNode, LocalVariableNode>()
for (variableIndex in start until method.maxLocals) {
if (oldLvt.none { it.index == variableIndex }) continue
var startLabel: LabelNode? = null
@@ -1310,7 +1265,7 @@ private fun updateLvtAccordingToLiveness(method: MethodNode, isForNamedFunction:
if (isAlive(insnIndex, variableIndex) && !isAlive(insnIndex + 1, variableIndex)) {
// No variable in LVT -> do not add one
val lvtRecord = oldLvt.findRecord(insnIndex, variableIndex) ?: continue
if (lvtRecord.name == CONTINUATION_VARIABLE_NAME) continue
if (lvtRecord.name == CONTINUATION_VARIABLE_NAME || lvtRecord.name == SUSPEND_CALL_RESULT_NAME) continue
// 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
@@ -1336,11 +1291,21 @@ private fun updateLvtAccordingToLiveness(method: MethodNode, isForNamedFunction:
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
val node = LocalVariableNode(lvtRecord.name, lvtRecord.desc, lvtRecord.signature, startLabel, endLabel, lvtRecord.index)
if (lvtRecord !in oldLvtNodeToLatestNewLvtNode) {
method.localVariables.add(node)
// Attempt to extend existing local variable node corresponding to the record in
// the original local variable table, if there is no back-edge
val latest = oldLvtNodeToLatestNewLvtNode[lvtRecord]
// if we can extend the previous range to where the local variable dies, we do not need a
// new entry, we know we cannot extend it to the lvt.endOffset, if we could we would have
// done so when we added it below.
val extended = latest?.extendRecordIfPossible(method, suspensionPoints, lvtRecord.end) ?: false
if (!extended) {
val new = LocalVariableNode(lvtRecord.name, lvtRecord.desc, lvtRecord.signature, startLabel, endLabel, lvtRecord.index)
oldLvtNodeToLatestNewLvtNode[lvtRecord] = new
method.localVariables.add(new)
// see if we can extend it all the way to the old end
new.extendRecordIfPossible(method, suspensionPoints, lvtRecord.end)
}
oldLvtNodeToLatestNewLvtNode[lvtRecord] = node
}
}
}
@@ -1362,3 +1327,35 @@ private fun updateLvtAccordingToLiveness(method: MethodNode, isForNamedFunction:
}
}
}
/* We cannot extend a record if there is STORE instruction or a back-edge.
* STORE instructions can signify a unspilling operation, in which case, the variable will become visible before it unspilled,
* back-edges occur in loops.
*
* @return true if the range has been extended
*/
private fun LocalVariableNode.extendRecordIfPossible(
method: MethodNode,
suspensionPoints: List<LabelNode>,
endLabel: LabelNode
): Boolean {
val nextSuspensionPointLabel = suspensionPoints.find { it in InsnSequence(end, endLabel) } ?: endLabel
var current: AbstractInsnNode? = end
while (current != null && current != nextSuspensionPointLabel) {
if (current is JumpInsnNode) {
if (method.instructions.indexOf(current.label) < method.instructions.indexOf(current)) {
return false
}
}
// TODO: HACK
// TODO: Find correct label, which is OK to be used as end label.
if (current.opcode == Opcodes.ARETURN && nextSuspensionPointLabel != endLabel) return false
if (current.isStoreOperation() && (current as VarInsnNode).`var` == index) {
return false
}
current = current.next
}
end = nextSuspensionPointLabel
return true
}

View File

@@ -6,7 +6,7 @@
package org.jetbrains.kotlin.codegen.coroutines
import org.jetbrains.kotlin.codegen.optimization.boxing.isUnitInstance
import org.jetbrains.kotlin.codegen.optimization.common.MethodAnalyzer
import org.jetbrains.kotlin.codegen.optimization.common.FastMethodAnalyzer
import org.jetbrains.kotlin.codegen.optimization.common.asSequence
import org.jetbrains.kotlin.codegen.optimization.common.removeAll
import org.jetbrains.kotlin.codegen.optimization.fixStack.top
@@ -85,7 +85,7 @@ private class UnitSourceInterpreter(private val localVariables: Set<Int>) : Basi
}
fun run(internalClassName: String, methodNode: MethodNode): Array<Frame<BasicValue>?> {
val frames = MethodAnalyzer<BasicValue>(internalClassName, methodNode, this).analyze()
val frames = FastMethodAnalyzer<BasicValue>(internalClassName, methodNode, this).analyze()
// The ASM analyzer does not visit POP instructions, so we do so here.
for ((insn, frame) in methodNode.instructions.asSequence().zip(frames.asSequence())) {
if (frame != null && insn.opcode == Opcodes.POP) {

View File

@@ -6,7 +6,7 @@
package org.jetbrains.kotlin.codegen.coroutines
import org.jetbrains.kotlin.codegen.StackValue
import org.jetbrains.kotlin.codegen.optimization.common.MethodAnalyzer
import org.jetbrains.kotlin.codegen.optimization.common.FastMethodAnalyzer
import org.jetbrains.kotlin.codegen.optimization.common.OptimizationBasicInterpreter
import org.jetbrains.org.objectweb.asm.Label
import org.jetbrains.org.objectweb.asm.Opcodes
@@ -130,11 +130,11 @@ internal fun performSpilledVariableFieldTypesAnalysis(
thisName: String
): Array<out Frame<BasicValue>?> {
val interpreter = IntLikeCoerceInterpreter()
MethodAnalyzer(thisName, methodNode, interpreter).analyze()
FastMethodAnalyzer(thisName, methodNode, interpreter).analyze()
for ((insn, type) in interpreter.needsToBeCoerced) {
methodNode.instructions.insert(insn, withInstructionAdapter { coerceInt(type, this) })
}
return MethodAnalyzer(thisName, methodNode, OptimizationBasicInterpreter()).analyze()
return FastMethodAnalyzer(thisName, methodNode, OptimizationBasicInterpreter()).analyze()
}
private fun coerceInt(to: Type, v: InstructionAdapter) {

View File

@@ -88,18 +88,17 @@ class SuspendFunctionGenerationStrategy(
return CoroutineTransformerMethodVisitor(
mv, access, name, desc, null, null, containingClassInternalName, this::classBuilderForCoroutineState,
isForNamedFunction = true,
shouldPreserveClassInitialization = constructorCallNormalizationMode.shouldPreserveClassInitialization,
disableTailCallOptimizationForFunctionReturningUnit = originalSuspendDescriptor.returnType?.isUnit() == true &&
originalSuspendDescriptor.overriddenDescriptors.isNotEmpty() &&
!originalSuspendDescriptor.allOverriddenFunctionsReturnUnit(),
reportSuspensionPointInsideMonitor = { reportSuspensionPointInsideMonitor(declaration, state, it) },
lineNumber = CodegenUtil.getLineNumberForElement(declaration, false) ?: 0,
sourceFile = declaration.containingKtFile.name,
shouldPreserveClassInitialization = constructorCallNormalizationMode.shouldPreserveClassInitialization,
needDispatchReceiver = originalSuspendDescriptor.dispatchReceiverParameter != null,
internalNameForDispatchReceiver = (originalSuspendDescriptor.containingDeclaration as? ClassDescriptor)?.let {
if (it.isInlineClass()) state.typeMapper.mapType(it).internalName else null
} ?: containingClassInternalNameOrNull(),
languageVersionSettings = languageVersionSettings,
disableTailCallOptimizationForFunctionReturningUnit = originalSuspendDescriptor.returnType?.isUnit() == true &&
originalSuspendDescriptor.overriddenDescriptors.isNotEmpty() &&
!originalSuspendDescriptor.allOverriddenFunctionsReturnUnit(),
useOldSpilledVarTypeAnalysis = state.configuration.getBoolean(JVMConfigurationKeys.USE_OLD_SPILLED_VAR_TYPE_ANALYSIS)
)
}
@@ -155,8 +154,7 @@ class SuspendFunctionGenerationStrategy(
needDispatchReceiver,
internalNameForDispatchReceiver,
containingClassInternalName,
classBuilderForCoroutineState,
languageVersionSettings
classBuilderForCoroutineState
)
addFakeContinuationConstructorCallMarker(this, false)
pop() // Otherwise stack-transformation breaks

View File

@@ -12,7 +12,6 @@ import org.jetbrains.kotlin.codegen.optimization.common.asSequence
import org.jetbrains.kotlin.codegen.optimization.common.isMeaningful
import org.jetbrains.kotlin.codegen.optimization.fixStack.top
import org.jetbrains.kotlin.codegen.optimization.transformer.MethodTransformer
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.utils.sure
import org.jetbrains.org.objectweb.asm.Label
@@ -27,7 +26,6 @@ import org.jetbrains.org.objectweb.asm.tree.analysis.BasicValue
import org.jetbrains.org.objectweb.asm.tree.analysis.Frame
internal class MethodNodeExaminer(
val languageVersionSettings: LanguageVersionSettings,
containingClassInternalName: String,
val methodNode: MethodNode,
suspensionPoints: List<SuspensionPoint>,
@@ -41,7 +39,6 @@ internal class MethodNodeExaminer(
private val popsBeforeSafeUnitInstances = mutableSetOf<AbstractInsnNode>()
private val areturnsAfterSafeUnitInstances = mutableSetOf<AbstractInsnNode>()
private val meaningfulSuccessorsCache = hashMapOf<AbstractInsnNode, List<AbstractInsnNode>>()
private val meaningfulPredecessorsCache = hashMapOf<AbstractInsnNode, List<AbstractInsnNode>>()
init {
if (!disableTailCallOptimizationForFunctionReturningUnit) {
@@ -54,10 +51,8 @@ internal class MethodNodeExaminer(
for (pop in popsBeforeUnitInstances) {
val units = pop.meaningfulSuccessors()
val allUnitsAreSafe = units.all { unit ->
// check no other predecessor exists
unit.meaningfulPredecessors().all { it in popsBeforeUnitInstances } &&
// check they have only returns among successors
unit.meaningfulSuccessors().all { it.opcode == Opcodes.ARETURN }
// check they have only returns among successors
unit.meaningfulSuccessors().all { it.opcode == Opcodes.ARETURN }
}
if (!allUnitsAreSafe) continue
// save them all to the properties
@@ -76,35 +71,22 @@ internal class MethodNodeExaminer(
private fun AbstractInsnNode.isAreturnAfterSafeUnitInstance(): Boolean = this in areturnsAfterSafeUnitInstances
private fun AbstractInsnNode.meaningfulSuccessors(): List<AbstractInsnNode> = meaningfulSuccessorsCache.getOrPut(this) {
meaningfulSuccessorsOrPredecessors(true)
}
private fun AbstractInsnNode.meaningfulPredecessors(): List<AbstractInsnNode> = meaningfulPredecessorsCache.getOrPut(this) {
meaningfulSuccessorsOrPredecessors(false)
}
private fun AbstractInsnNode.meaningfulSuccessorsOrPredecessors(isSuccessors: Boolean): List<AbstractInsnNode> {
fun AbstractInsnNode.isMeaningful() = isMeaningful && opcode != Opcodes.NOP && opcode != Opcodes.GOTO && this !is LineNumberNode
fun AbstractInsnNode.getIndices() =
if (isSuccessors) controlFlowGraph.getSuccessorsIndices(this)
else controlFlowGraph.getPredecessorsIndices(this)
val visited = mutableSetOf<AbstractInsnNode>()
fun dfs(insn: AbstractInsnNode) {
if (insn in visited) return
visited += insn
if (!insn.isMeaningful()) {
for (succIndex in insn.getIndices()) {
for (succIndex in controlFlowGraph.getSuccessorsIndices(insn)) {
dfs(methodNode.instructions[succIndex])
}
}
}
for (succIndex in getIndices()) {
for (succIndex in controlFlowGraph.getSuccessorsIndices(this)) {
dfs(methodNode.instructions[succIndex])
}
return visited.filter { it.isMeaningful() }
visited.filter { it.isMeaningful() }
}
fun replacePopsBeforeSafeUnitInstancesWithCoroutineSuspendedChecks() {
@@ -116,7 +98,7 @@ internal class MethodNodeExaminer(
val label = Label()
methodNode.instructions.insertBefore(pop, withInstructionAdapter {
dup()
loadCoroutineSuspendedMarker(languageVersionSettings)
loadCoroutineSuspendedMarker()
ifacmpne(label)
areturn(AsmTypes.OBJECT_TYPE)
mark(label)
@@ -159,8 +141,8 @@ internal class MethodNodeExaminer(
* @return indices of safely reachable returns for each instruction in the method node
*/
private fun findSafelyReachableReturns(): Array<Set<Int>?> {
val insns = methodNode.instructions
val reachableReturnsIndices = Array(insns.size()) init@{ index ->
val insns = methodNode.instructions.toArray()
val reachableReturnsIndices = Array(insns.size) init@{ index ->
val insn = insns[index]
if (insn.opcode == Opcodes.ARETURN && !insn.isAreturnAfterSafeUnitInstance()) {
@@ -182,7 +164,7 @@ internal class MethodNodeExaminer(
var changed: Boolean
do {
changed = false
for (index in 0 until insns.size()) {
for (index in insns.indices.reversed()) {
if (insns[index].opcode == Opcodes.ARETURN) continue
@Suppress("RemoveExplicitTypeArguments")

View File

@@ -9,6 +9,8 @@ import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.backend.common.COROUTINE_SUSPENDED_NAME
import org.jetbrains.kotlin.backend.common.isBuiltInSuspendCoroutineUninterceptedOrReturn
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.builtins.StandardNames.COROUTINES_INTRINSICS_PACKAGE_FQ_NAME
import org.jetbrains.kotlin.builtins.StandardNames.COROUTINES_JVM_INTERNAL_PACKAGE_FQ_NAME
import org.jetbrains.kotlin.builtins.isBuiltinFunctionalClassDescriptor
import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.binding.CodegenBinding
@@ -54,67 +56,27 @@ import org.jetbrains.org.objectweb.asm.tree.MethodNode
const val COROUTINE_LABEL_FIELD_NAME = "label"
const val SUSPEND_FUNCTION_CREATE_METHOD_NAME = "create"
const val DO_RESUME_METHOD_NAME = "doResume"
const val INVOKE_SUSPEND_METHOD_NAME = "invokeSuspend"
const val EXCEPTION_FIELD_NAME = "exception"
const val CONTINUATION_RESULT_FIELD_NAME = "result"
val RELEASE_COROUTINES_VERSION_SETTINGS = LanguageVersionSettingsImpl(LanguageVersion.KOTLIN_1_3, ApiVersion.KOTLIN_1_3)
private const val GET_CONTEXT_METHOD_NAME = "getContext"
fun LanguageVersionSettings.isResumeImplMethodName(name: String) =
if (isReleaseCoroutines())
name == INVOKE_SUSPEND_METHOD_NAME
else
name == DO_RESUME_METHOD_NAME
val DEBUG_METADATA_ANNOTATION_ASM_TYPE: Type =
COROUTINES_JVM_INTERNAL_PACKAGE_FQ_NAME.child(Name.identifier("DebugMetadata")).topLevelClassAsmType()
fun LanguageVersionSettings.dataFieldName(): String = if (isReleaseCoroutines()) "result" else "data"
fun coroutineContextAsmType(): Type =
StandardNames.COROUTINES_PACKAGE_FQ_NAME.child(Name.identifier("CoroutineContext")).topLevelClassAsmType()
fun isResumeImplMethodNameFromAnyLanguageSettings(name: String) = name == INVOKE_SUSPEND_METHOD_NAME || name == DO_RESUME_METHOD_NAME
fun LanguageVersionSettings.coroutinesJvmInternalPackageFqName() =
coroutinesPackageFqName().child(Name.identifier("jvm")).child(Name.identifier("internal"))
val DEBUG_METADATA_ANNOTATION_ASM_TYPE = RELEASE_COROUTINES_VERSION_SETTINGS.coroutinesJvmInternalPackageFqName()
.child(Name.identifier("DebugMetadata")).topLevelClassAsmType()
fun LanguageVersionSettings.continuationAsmType() =
continuationInterfaceFqName().topLevelClassAsmType()
fun continuationAsmTypes() = listOf(
LanguageVersionSettingsImpl(LanguageVersion.KOTLIN_1_3, ApiVersion.KOTLIN_1_3).continuationAsmType(),
LanguageVersionSettingsImpl(LanguageVersion.KOTLIN_1_2, ApiVersion.KOTLIN_1_2).continuationAsmType()
)
fun LanguageVersionSettings.coroutineContextAsmType() =
coroutinesPackageFqName().child(Name.identifier("CoroutineContext")).topLevelClassAsmType()
fun LanguageVersionSettings.isCoroutineSuperClass(internalName: String): Boolean {
val coroutinesJvmInternalPackage = coroutinesJvmInternalPackageFqName()
return if (isReleaseCoroutines())
coroutinesJvmInternalPackage.identifiedChild("ContinuationImpl") == internalName ||
coroutinesJvmInternalPackage.identifiedChild("RestrictedContinuationImpl") == internalName ||
coroutinesJvmInternalPackage.identifiedChild("SuspendLambda") == internalName ||
coroutinesJvmInternalPackage.identifiedChild("RestrictedSuspendLambda") == internalName
else
coroutinesJvmInternalPackage.identifiedChild("CoroutineImpl") == internalName
}
fun String.isCoroutineSuperClass(): Boolean =
COROUTINES_JVM_INTERNAL_PACKAGE_FQ_NAME.identifiedChild("ContinuationImpl") == this ||
COROUTINES_JVM_INTERNAL_PACKAGE_FQ_NAME.identifiedChild("RestrictedContinuationImpl") == this ||
COROUTINES_JVM_INTERNAL_PACKAGE_FQ_NAME.identifiedChild("SuspendLambda") == this ||
COROUTINES_JVM_INTERNAL_PACKAGE_FQ_NAME.identifiedChild("RestrictedSuspendLambda") == this
private fun FqName.identifiedChild(name: String) = child(Name.identifier(name)).topLevelClassInternalName()
private fun LanguageVersionSettings.coroutinesIntrinsicsFileFacadeInternalName() =
coroutinesIntrinsicsPackageFqName().child(Name.identifier("IntrinsicsKt")).topLevelClassAsmType()
private fun LanguageVersionSettings.internalCoroutineIntrinsicsOwnerInternalName() =
coroutinesJvmInternalPackageFqName().child(Name.identifier("CoroutineIntrinsics")).topLevelClassInternalName()
fun computeLabelOwner(languageVersionSettings: LanguageVersionSettings, thisName: String): Type =
if (languageVersionSettings.isReleaseCoroutines())
Type.getObjectType(thisName)
else
languageVersionSettings.coroutinesJvmInternalPackageFqName().child(Name.identifier("CoroutineImpl")).topLevelClassAsmType()
private const val NORMALIZE_CONTINUATION_METHOD_NAME = "normalizeContinuation"
private const val GET_CONTEXT_METHOD_NAME = "getContext"
private val coroutinesIntrinsicsFileFacadeInternalName: Type =
COROUTINES_INTRINSICS_PACKAGE_FQ_NAME.child(Name.identifier("IntrinsicsKt")).topLevelClassAsmType()
data class ResolvedCallWithRealDescriptor(val resolvedCall: ResolvedCall<*>, val fakeContinuationExpression: KtExpression)
@@ -122,7 +84,7 @@ data class ResolvedCallWithRealDescriptor(val resolvedCall: ResolvedCall<*>, val
val INITIAL_DESCRIPTOR_FOR_SUSPEND_FUNCTION = object : CallableDescriptor.UserDataKey<FunctionDescriptor> {}
@JvmField
val INITIAL_SUSPEND_DESCRIPTOR_FOR_DO_RESUME = object : CallableDescriptor.UserDataKey<FunctionDescriptor> {}
val INITIAL_SUSPEND_DESCRIPTOR_FOR_INVOKE_SUSPEND = object : CallableDescriptor.UserDataKey<FunctionDescriptor> {}
val CONTINUATION_PARAMETER_NAME = Name.identifier("continuation")
@@ -158,9 +120,9 @@ fun ResolvedCall<*>.replaceSuspensionFunctionWithRealDescriptor(
val newCandidateDescriptor =
when (function) {
is FunctionImportedFromObject ->
getOrCreateJvmSuspendFunctionView(function.callableFromObject, isReleaseCoroutines, bindingContext).asImportedFromObject()
getOrCreateJvmSuspendFunctionView(function.callableFromObject, bindingContext).asImportedFromObject()
is SimpleFunctionDescriptor ->
getOrCreateJvmSuspendFunctionView(function, isReleaseCoroutines, bindingContext)
getOrCreateJvmSuspendFunctionView(function, bindingContext)
else ->
throw AssertionError("Unexpected suspend function descriptor: $function")
}
@@ -223,10 +185,10 @@ private fun NewResolvedCallImpl<VariableDescriptor>.asDummyOldResolvedCall(bindi
enum class SuspensionPointKind { NEVER, NOT_INLINE, ALWAYS }
fun ResolvedCall<*>.isSuspensionPoint(codegen: ExpressionCodegen, languageVersionSettings: LanguageVersionSettings): SuspensionPointKind {
fun ResolvedCall<*>.isSuspensionPoint(codegen: ExpressionCodegen): SuspensionPointKind {
val functionDescriptor = resultingDescriptor as? FunctionDescriptor ?: return SuspensionPointKind.NEVER
if (!functionDescriptor.unwrapInitialDescriptorForSuspendFunction().isSuspend) return SuspensionPointKind.NEVER
if (functionDescriptor.isBuiltInSuspendCoroutineUninterceptedOrReturnInJvm(languageVersionSettings)) return SuspensionPointKind.ALWAYS
if (functionDescriptor.isBuiltInSuspendCoroutineUninterceptedOrReturnInJvm()) return SuspensionPointKind.ALWAYS
if (functionDescriptor.isInline) return SuspensionPointKind.NEVER
val isInlineLambda = this.safeAs<VariableAsFunctionResolvedCall>()
@@ -242,7 +204,6 @@ fun CallableDescriptor.isSuspendFunctionNotSuspensionView(): Boolean {
fun <D : FunctionDescriptor> getOrCreateJvmSuspendFunctionView(function: D, state: GenerationState): D = getOrCreateJvmSuspendFunctionView(
function,
state.languageVersionSettings.supportsFeature(LanguageFeature.ReleaseCoroutines),
state.bindingContext
)
@@ -252,7 +213,6 @@ fun <D : FunctionDescriptor> getOrCreateJvmSuspendFunctionView(function: D, stat
@JvmOverloads
fun <D : FunctionDescriptor> getOrCreateJvmSuspendFunctionView(
function: D,
isReleaseCoroutines: Boolean,
bindingContext: BindingContext? = null
): D {
assert(function.isSuspend) {
@@ -272,7 +232,7 @@ fun <D : FunctionDescriptor> getOrCreateJvmSuspendFunctionView(
outType = if (function.containingDeclaration.safeAs<ClassDescriptor>()?.isBuiltinFunctionalClassDescriptor == true)
function.builtIns.nullableAnyType
else
function.getContinuationParameterTypeOfSuspendFunction(isReleaseCoroutines),
function.getContinuationParameterTypeOfSuspendFunction(),
declaresDefaultValue = false, isCrossinline = false,
isNoinline = false, varargElementType = null,
source = SourceElement.NO_SOURCE
@@ -309,8 +269,7 @@ fun <D : FunctionDescriptor> D.createCustomCopy(
return result as D
}
private fun FunctionDescriptor.getContinuationParameterTypeOfSuspendFunction(isReleaseCoroutines: Boolean) =
module.getContinuationOfTypeOrAny(returnType!!, if (this.needsExperimentalCoroutinesWrapper()) false else isReleaseCoroutines)
private fun FunctionDescriptor.getContinuationParameterTypeOfSuspendFunction() = module.getContinuationOfTypeOrAny(returnType!!)
fun ModuleDescriptor.getResult(kotlinType: KotlinType) =
module.resolveTopLevelClass(
@@ -323,44 +282,11 @@ fun ModuleDescriptor.getResult(kotlinType: KotlinType) =
)
} ?: ErrorUtils.createErrorType("For Result")
private fun MethodNode.invokeNormalizeContinuation(languageVersionSettings: LanguageVersionSettings) {
visitMethodInsn(
Opcodes.INVOKESTATIC,
languageVersionSettings.internalCoroutineIntrinsicsOwnerInternalName(),
NORMALIZE_CONTINUATION_METHOD_NAME,
Type.getMethodDescriptor(languageVersionSettings.continuationAsmType(), languageVersionSettings.continuationAsmType()),
false
)
}
fun FunctionDescriptor.isBuiltInSuspendCoroutineUninterceptedOrReturnInJvm() =
getUserData(INITIAL_DESCRIPTOR_FOR_SUSPEND_FUNCTION)?.isBuiltInSuspendCoroutineUninterceptedOrReturn() == true
fun FunctionDescriptor.isBuiltInSuspendCoroutineUninterceptedOrReturnInJvm(languageVersionSettings: LanguageVersionSettings) =
getUserData(INITIAL_DESCRIPTOR_FOR_SUSPEND_FUNCTION)?.isBuiltInSuspendCoroutineUninterceptedOrReturn(languageVersionSettings) == true
fun createMethodNodeForIntercepted(languageVersionSettings: LanguageVersionSettings): MethodNode {
val node =
MethodNode(
Opcodes.API_VERSION,
Opcodes.ACC_STATIC,
"fake",
Type.getMethodDescriptor(languageVersionSettings.continuationAsmType(), languageVersionSettings.continuationAsmType()),
null, null
)
node.visitVarInsn(Opcodes.ALOAD, 0)
node.invokeNormalizeContinuation(languageVersionSettings)
node.visitInsn(Opcodes.ARETURN)
node.visitMaxs(1, 1)
return node
}
fun createMethodNodeForCoroutineContext(
functionDescriptor: FunctionDescriptor,
languageVersionSettings: LanguageVersionSettings
): MethodNode {
assert(functionDescriptor.isBuiltInCoroutineContext(languageVersionSettings)) {
fun createMethodNodeForCoroutineContext(functionDescriptor: FunctionDescriptor): MethodNode {
assert(functionDescriptor.isBuiltInCoroutineContext()) {
"functionDescriptor must be kotlin.coroutines.intrinsics.coroutineContext property getter"
}
@@ -369,7 +295,7 @@ fun createMethodNodeForCoroutineContext(
Opcodes.API_VERSION,
Opcodes.ACC_STATIC,
"fake",
Type.getMethodDescriptor(languageVersionSettings.coroutineContextAsmType()),
Type.getMethodDescriptor(coroutineContextAsmType()),
null, null
)
@@ -377,20 +303,20 @@ fun createMethodNodeForCoroutineContext(
addFakeContinuationMarker(v)
v.invokeGetContext(languageVersionSettings)
v.invokeGetContext()
node.visitMaxs(1, 1)
return node
}
fun createMethodNodeForSuspendCoroutineUninterceptedOrReturn(languageVersionSettings: LanguageVersionSettings): MethodNode {
fun createMethodNodeForSuspendCoroutineUninterceptedOrReturn(): MethodNode {
val node =
MethodNode(
Opcodes.API_VERSION,
Opcodes.ACC_STATIC,
"fake",
Type.getMethodDescriptor(OBJECT_TYPE, AsmTypes.FUNCTION1, languageVersionSettings.continuationAsmType()),
Type.getMethodDescriptor(OBJECT_TYPE, AsmTypes.FUNCTION1, CONTINUATION_ASM_TYPE),
null, null
)
@@ -405,25 +331,22 @@ fun createMethodNodeForSuspendCoroutineUninterceptedOrReturn(languageVersionSett
"($OBJECT_TYPE)$OBJECT_TYPE"
)
if (languageVersionSettings.supportsFeature(LanguageFeature.ReleaseCoroutines)) {
val elseLabel = Label()
// if (result === COROUTINE_SUSPENDED) {
dup()
loadCoroutineSuspendedMarker(languageVersionSettings)
ifacmpne(elseLabel)
// DebugProbesKt.probeCoroutineSuspended(continuation)
load(1, OBJECT_TYPE) // continuation
checkcast(languageVersionSettings.continuationAsmType())
invokestatic(
languageVersionSettings.coroutinesJvmInternalPackageFqName().child(Name.identifier("DebugProbesKt"))
.topLevelClassAsmType().internalName,
"probeCoroutineSuspended",
"(${languageVersionSettings.continuationAsmType()})V",
false
)
// }
mark(elseLabel)
}
val elseLabel = Label()
// if (result === COROUTINE_SUSPENDED) {
dup()
loadCoroutineSuspendedMarker()
ifacmpne(elseLabel)
// DebugProbesKt.probeCoroutineSuspended(continuation)
load(1, OBJECT_TYPE) // continuation
checkcast(CONTINUATION_ASM_TYPE)
invokestatic(
COROUTINES_JVM_INTERNAL_PACKAGE_FQ_NAME.child(Name.identifier("DebugProbesKt")).topLevelClassAsmType().internalName,
"probeCoroutineSuspended",
"($CONTINUATION_ASM_TYPE)V",
false
)
// }
mark(elseLabel)
}
node.visitInsn(Opcodes.ARETURN)
@@ -433,13 +356,13 @@ fun createMethodNodeForSuspendCoroutineUninterceptedOrReturn(languageVersionSett
}
private fun InstructionAdapter.invokeGetContext(languageVersionSettings: LanguageVersionSettings) {
private fun InstructionAdapter.invokeGetContext() {
invokeinterface(
languageVersionSettings.continuationAsmType().internalName,
CONTINUATION_ASM_TYPE.internalName,
GET_CONTEXT_METHOD_NAME,
Type.getMethodDescriptor(languageVersionSettings.coroutineContextAsmType())
Type.getMethodDescriptor(coroutineContextAsmType())
)
areturn(languageVersionSettings.coroutineContextAsmType())
areturn(coroutineContextAsmType())
}
@Suppress("UNCHECKED_CAST")
@@ -447,15 +370,12 @@ fun <D : CallableDescriptor?> D.unwrapInitialDescriptorForSuspendFunction(): D =
this.safeAs<SimpleFunctionDescriptor>()?.getUserData(INITIAL_DESCRIPTOR_FOR_SUSPEND_FUNCTION) as D ?: this
fun FunctionDescriptor.getOriginalSuspendFunctionView(bindingContext: BindingContext, isReleaseCoroutines: Boolean): FunctionDescriptor =
fun FunctionDescriptor.getOriginalSuspendFunctionView(bindingContext: BindingContext): FunctionDescriptor =
if (isSuspend)
getOrCreateJvmSuspendFunctionView(unwrapInitialDescriptorForSuspendFunction().original, isReleaseCoroutines, bindingContext)
getOrCreateJvmSuspendFunctionView(unwrapInitialDescriptorForSuspendFunction().original, bindingContext)
else
this
fun FunctionDescriptor.getOriginalSuspendFunctionView(bindingContext: BindingContext, state: GenerationState) =
getOriginalSuspendFunctionView(bindingContext, state.languageVersionSettings.supportsFeature(LanguageFeature.ReleaseCoroutines))
// For each suspend function, we have a corresponding JVM view function that has an extra continuation parameter,
// and, more importantly, returns 'kotlin.Any' (so that it can return as a reference value or a special COROUTINE_SUSPENDED object).
// This also causes boxing of primitives and inline class values.
@@ -482,38 +402,24 @@ fun FunctionDescriptor.originalReturnTypeOfSuspendFunctionReturningUnboxedInline
return originalReturnType
}
fun InstructionAdapter.loadCoroutineSuspendedMarker(languageVersionSettings: LanguageVersionSettings) {
fun InstructionAdapter.loadCoroutineSuspendedMarker() {
invokestatic(
languageVersionSettings.coroutinesIntrinsicsFileFacadeInternalName().internalName,
coroutinesIntrinsicsFileFacadeInternalName.internalName,
"get$COROUTINE_SUSPENDED_NAME",
Type.getMethodDescriptor(OBJECT_TYPE),
false
)
}
fun InstructionAdapter.generateCoroutineSuspendedCheck(languageVersionSettings: LanguageVersionSettings) {
fun InstructionAdapter.generateCoroutineSuspendedCheck() {
dup()
loadCoroutineSuspendedMarker(languageVersionSettings)
loadCoroutineSuspendedMarker()
val elseLabel = Label()
ifacmpne(elseLabel)
areturn(OBJECT_TYPE)
mark(elseLabel)
}
fun InstructionAdapter.invokeDoResumeWithUnit(thisName: String) {
// .doResume(Unit, null)
StackValue.putUnitInstance(this)
aconst(null)
invokevirtual(
thisName,
DO_RESUME_METHOD_NAME,
Type.getMethodDescriptor(OBJECT_TYPE, OBJECT_TYPE, AsmTypes.JAVA_THROWABLE_TYPE),
false
)
}
fun InstructionAdapter.invokeInvokeSuspendWithUnit(thisName: String) {
StackValue.putUnitInstance(this)
@@ -537,18 +443,14 @@ fun FunctionDescriptor.isSuspendLambdaOrLocalFunction() = this.isSuspend && when
}
fun FunctionDescriptor.isLocalSuspendFunctionNotSuspendLambda() = isSuspendLambdaOrLocalFunction() && this !is AnonymousFunctionDescriptor
@JvmField
val EXPERIMENTAL_CONTINUATION_ASM_TYPE = StandardNames.CONTINUATION_INTERFACE_FQ_NAME_EXPERIMENTAL.topLevelClassAsmType()
@JvmField
val RELEASE_CONTINUATION_ASM_TYPE = StandardNames.CONTINUATION_INTERFACE_FQ_NAME_RELEASE.topLevelClassAsmType()
val CONTINUATION_ASM_TYPE = StandardNames.CONTINUATION_INTERFACE_FQ_NAME.topLevelClassAsmType()
fun FunctionDescriptor.isInvokeSuspendOfLambda(): Boolean {
if (this !is SimpleFunctionDescriptor) return false
if (valueParameters.size != 1 ||
valueParameters[0].name.asString() != SUSPEND_CALL_RESULT_NAME ||
name.asString() != "invokeSuspend"
name.asString() != INVOKE_SUSPEND_METHOD_NAME
) return false
return containingDeclaration is SyntheticClassDescriptorForLambda
}

View File

@@ -73,8 +73,8 @@ import kotlin.math.max
* - restore constructor arguments
*/
class UninitializedStoresProcessor(
private val methodNode: MethodNode,
private val shouldPreserveClassInitialization: Boolean
private val methodNode: MethodNode,
private val shouldPreserveClassInitialization: Boolean
) {
// <init> method is "special", because it will invoke <init> from this class or from a base class for #0
//
@@ -87,10 +87,10 @@ class UninitializedStoresProcessor(
fun run() {
val interpreter = UninitializedNewValueMarkerInterpreter(methodNode.instructions)
val frames = CustomFramesMethodAnalyzer(
"fake", methodNode, interpreter,
this::UninitializedNewValueFrame
).analyze()
if (methodNode.instructions.toArray().none { it.opcode == Opcodes.NEW })
return
val frames = CustomFramesMethodAnalyzer("fake", methodNode, interpreter, this::UninitializedNewValueFrame).analyze()
interpreter.analyzePopInstructions(frames)
@@ -115,12 +115,12 @@ class UninitializedStoresProcessor(
// POP
val typeNameForClass = newInsn.desc.replace('/', '.')
insertBefore(newInsn, LdcInsnNode(typeNameForClass))
insertBefore(newInsn, MethodInsnNode(
Opcodes.INVOKESTATIC, "java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;", false
))
insertBefore(
newInsn,
MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;", false)
)
set(newInsn, InsnNode(Opcodes.POP))
}
else {
} else {
remove(newInsn)
}
}
@@ -138,10 +138,7 @@ class UninitializedStoresProcessor(
}
methodNode.maxLocals = max(methodNode.maxLocals, nextVarIndex)
methodNode.instructions.insertBefore(insn, insnListOf(
TypeInsnNode(Opcodes.NEW, newInsn.desc),
InsnNode(Opcodes.DUP)
))
methodNode.instructions.insertBefore(insn, insnListOf(TypeInsnNode(Opcodes.NEW, newInsn.desc), InsnNode(Opcodes.DUP)))
for (type in storedTypes.reversed()) {
nextVarIndex -= type.size
@@ -174,11 +171,11 @@ class UninitializedStoresProcessor(
assert(insn.opcode == Opcodes.INVOKESPECIAL) { "Expected opcode Opcodes.INVOKESPECIAL for <init>, but ${insn.opcode} found" }
val paramsCountIncludingReceiver = Type.getArgumentTypes((insn as MethodInsnNode).desc).size + 1
val newValue = peek(paramsCountIncludingReceiver) as? UninitializedNewValue ?:
if (isInSpecialMethod)
return null
else
error("Expected value generated with NEW")
val newValue = peek(paramsCountIncludingReceiver) as? UninitializedNewValue
?: if (isInSpecialMethod)
return null
else
error("Expected value generated with NEW")
assert(peek(paramsCountIncludingReceiver - 1) is UninitializedNewValue) {
"Next value after NEW should be one generated by DUP"
@@ -188,8 +185,8 @@ class UninitializedStoresProcessor(
}
private class UninitializedNewValue(
val newInsn: TypeInsnNode,
val internalName: String
val newInsn: TypeInsnNode,
val internalName: String
) : StrictBasicValue(Type.getObjectType(internalName)) {
override fun toString() = "UninitializedNewValue(internalName='$internalName')"
}
@@ -236,7 +233,8 @@ class UninitializedStoresProcessor(
private fun checkUninitializedObjectCopy(newInsn: TypeInsnNode, usageInsn: AbstractInsnNode) {
when (usageInsn.opcode) {
Opcodes.DUP, Opcodes.ASTORE, Opcodes.ALOAD -> {}
Opcodes.DUP, Opcodes.ASTORE, Opcodes.ALOAD -> {
}
else -> error("Unexpected copy instruction for ${newInsn.debugText}: ${usageInsn.debugText}")
}
}

View File

@@ -62,7 +62,7 @@ class AnonymousObjectTransformer(
createClassReader().accept(object : ClassVisitor(Opcodes.API_VERSION, classBuilder.visitor) {
override fun visit(version: Int, access: Int, name: String, signature: String?, superName: String, interfaces: Array<String>) {
classBuilder.defineClass(null, maxOf(version, state.classFileVersion), access, name, signature, superName, interfaces)
if (languageVersionSettings.isCoroutineSuperClass(superName)) {
if (superName.isCoroutineSuperClass()) {
inliningContext.isContinuation = true
}
superClassName = superName
@@ -295,7 +295,6 @@ class AnonymousObjectTransformer(
capturedBuilder: ParametersBuilder,
isConstructor: Boolean
): InlineResult {
val typeParametersToReify = inliningContext.root.inlineMethodReifier.reifyInstructions(sourceNode)
val parameters =
if (isConstructor) capturedBuilder.buildParameters() else getMethodParametersWithCaptured(capturedBuilder, sourceNode)
@@ -304,7 +303,10 @@ class AnonymousObjectTransformer(
transformationInfo.capturedLambdasToInline, parentRemapper, isConstructor
)
val inliner = MethodInliner(
val reifiedTypeParametersUsages = if (inliningContext.shouldReifyTypeParametersInObjects)
inliningContext.root.inlineMethodReifier.reifyInstructions(sourceNode)
else null
val result = MethodInliner(
sourceNode,
parameters,
inliningContext.subInline(transformationInfo.nameGenerator),
@@ -318,11 +320,10 @@ class AnonymousObjectTransformer(
inliningContext.callSiteInfo.isInlineOrInsideInline,
inliningContext.callSiteInfo.file,
inliningContext.callSiteInfo.lineNumber
), null
)
val result = inliner.doInline(deferringVisitor, LocalVarRemapper(parameters, 0), false, mapOf())
result.reifiedTypeParametersUsages.mergeAll(typeParametersToReify)
),
null
).doInline(deferringVisitor, LocalVarRemapper(parameters, 0), false, mapOf())
reifiedTypeParametersUsages?.let(result.reifiedTypeParametersUsages::mergeAll)
deferringVisitor.visitMaxs(-1, -1)
return result
}
@@ -421,11 +422,13 @@ class AnonymousObjectTransformer(
}
private fun getMethodParametersWithCaptured(capturedBuilder: ParametersBuilder, sourceNode: MethodNode): Parameters {
val builder = ParametersBuilder.initializeBuilderFrom(
oldObjectType,
sourceNode.desc,
isStatic = sourceNode.access and Opcodes.ACC_STATIC != 0
)
val builder = ParametersBuilder.newBuilder()
if (sourceNode.access and Opcodes.ACC_STATIC == 0) {
builder.addThis(oldObjectType, skipped = false)
}
for (type in Type.getArgumentTypes(sourceNode.desc)) {
builder.addNextParameter(type, false)
}
for (param in capturedBuilder.listCaptured()) {
builder.addCapturedParamCopy(param)
}
@@ -517,13 +520,10 @@ class AnonymousObjectTransformer(
val paramTypes = transformationInfo.constructorDesc?.let { Type.getArgumentTypes(it) } ?: emptyArray()
for (type in paramTypes) {
val info = indexToFunctionalArgument[constructorParamBuilder.nextParameterOffset]
val isCaptured = capturedParams.contains(constructorParamBuilder.nextParameterOffset)
val parameterInfo = constructorParamBuilder.addNextParameter(type, info is LambdaInfo)
parameterInfo.functionalArgument = info
if (capturedParams.contains(parameterInfo.index)) {
parameterInfo.isCaptured = true
} else {
//otherwise it's super constructor parameter
}
parameterInfo.isCaptured = isCaptured
}
//For all inlined lambdas add their captured parameters

View File

@@ -32,10 +32,9 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
private val initialFrameSize = codegen.frameMap.currentSize
protected val invocationParamBuilder = ParametersBuilder.newBuilder()
protected val expressionMap = linkedMapOf<Int, FunctionalArgument>()
protected val maskValues = ArrayList<Int>()
protected var maskStartIndex = -1
protected var methodHandleInDefaultMethodIndex = -1
private val maskValues = ArrayList<Int>()
private var maskStartIndex = -1
private var methodHandleInDefaultMethodIndex = -1
protected fun generateStub(text: String, codegen: BaseExpressionCodegen) {
leaveTemps()
@@ -71,14 +70,23 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
private fun inlineCall(nodeAndSmap: SMAPAndMethodNode, isInlineOnly: Boolean): InlineResult {
val node = nodeAndSmap.node
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) {
val parameters = invocationParamBuilder.buildParameters()
val infos = expandMaskConditionsAndUpdateVariableNodes(
node, maskStartIndex, maskValues, methodHandleInDefaultMethodIndex,
parameters.parameters.filter { it.functionalArgument === DefaultValueOfInlineParameter }
.mapTo(mutableSetOf()) { parameters.getDeclarationSlot(it) }
)
for (info in infos) {
val lambda = DefaultLambda(info, sourceCompiler)
parameters.getParameterByDeclarationSlot(info.offset).functionalArgument = lambda
if (info.needReification) {
lambda.reifiedTypeParametersUsages.mergeAll(reifiedTypeInliner.reifyInstructions(lambda.node.node))
}
rememberCapturedForDefaultLambda(lambda)
for (captured in lambda.capturedVars) {
val param = invocationParamBuilder.addCapturedParam(captured, captured.fieldName, false)
param.remapValue = StackValue.local(codegen.frameMap.enterTemp(param.type), param.type)
param.isSynthetic = true
}
}
}
@@ -87,7 +95,7 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
val parameters = invocationParamBuilder.buildParameters()
val info = RootInliningContext(
expressionMap, state, codegen.inlineNameGenerator.subGenerator(jvmSignature.asmMethod.name),
state, codegen.inlineNameGenerator.subGenerator(jvmSignature.asmMethod.name),
sourceCompiler, sourceCompiler.inlineCallSiteInfo, reifiedTypeInliner, typeParameterMappings
)
@@ -121,7 +129,9 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
// In case `codegen.visitor` is `<clinit>`, initializer for the `$assertionsDisabled` field
// needs to be inserted before the code that actually uses it.
generateAssertFieldIfNeeded(info)
if (info.generateAssertField) {
generateAssertField()
}
val shouldSpillStack = node.requiresEmptyStackOnEntry()
if (shouldSpillStack) {
@@ -134,16 +144,6 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
return result
}
abstract fun extractDefaultLambdas(node: MethodNode): List<DefaultLambda>
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]!!)
}
private fun generateAndInsertFinallyBlocks(
intoNode: MethodNode,
insertPoints: List<MethodInliner.PointForExternalFinallyBlocks>,
@@ -184,6 +184,9 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
val splitBy = SimpleInterval(start.info as LabelNode, extension.finallyIntervalEnd)
processor.tryBlocksMetaInfo.splitAndRemoveCurrentIntervals(splitBy, true)
processor.localVarsMetaInfo.splitAndRemoveCurrentIntervals(splitBy, true)
finallyNode.localVariables.forEach {
processor.localVarsMetaInfo.addNewInterval(LocalVarNodeWrapper(it))
}
}
curInstr = curInstr.next
@@ -193,7 +196,7 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
processor.substituteLocalVarTable(intoNode)
}
protected abstract fun generateAssertFieldIfNeeded(info: RootInliningContext)
protected abstract fun generateAssertField()
private fun isInlinedToInlineFunInKotlinRuntime(): Boolean {
val codegen = this.codegen as? ExpressionCodegen ?: return false
@@ -207,9 +210,7 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
}
protected fun rememberClosure(parameterType: Type, index: Int, lambdaInfo: LambdaInfo) {
val closureInfo = invocationParamBuilder.addNextValueParameter(parameterType, true, null, index)
closureInfo.functionalArgument = lambdaInfo
expressionMap[closureInfo.index] = lambdaInfo
invocationParamBuilder.addNextValueParameter(parameterType, true, null, index).functionalArgument = lambdaInfo
}
protected fun putCapturedToLocalVal(stackValue: StackValue, capturedParam: CapturedParamDesc, kotlinType: KotlinType?) {
@@ -236,10 +237,12 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
NonInlineableArgumentForInlineableParameterCalledInSuspend
ValueKind.NON_INLINEABLE_ARGUMENT_FOR_INLINE_SUSPEND_PARAMETER ->
NonInlineableArgumentForInlineableSuspendParameter
ValueKind.DEFAULT_INLINE_PARAMETER ->
DefaultValueOfInlineParameter
else -> null
}
when {
kind === ValueKind.DEFAULT_PARAMETER ->
kind === ValueKind.DEFAULT_PARAMETER || kind === ValueKind.DEFAULT_INLINE_PARAMETER ->
codegen.frameMap.enterTemp(info.type) // the inline function will put the value into this slot
stackValue.isLocalWithNoBoxing(jvmKotlinType) ->
info.remapValue = stackValue
@@ -258,14 +261,6 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
}
}
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
}
}
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

View File

@@ -9,7 +9,6 @@ import org.jetbrains.kotlin.codegen.ClassBuilder
import org.jetbrains.kotlin.codegen.state.GenerationState
class RootInliningContext(
expressionMap: Map<Int, FunctionalArgument>,
state: GenerationState,
nameGenerator: NameGenerator,
val sourceCompilerForInline: SourceCompilerForInline,
@@ -17,12 +16,11 @@ class RootInliningContext(
val inlineMethodReifier: ReifiedTypeInliner<*>,
typeParameterMappings: TypeParameterMappings<*>
) : InliningContext(
null, expressionMap, state, nameGenerator, TypeRemapper.createRoot(typeParameterMappings), null, false
null, state, nameGenerator, TypeRemapper.createRoot(typeParameterMappings), null, false
)
class RegeneratedClassContext(
parent: InliningContext,
expressionMap: Map<Int, FunctionalArgument>,
state: GenerationState,
nameGenerator: NameGenerator,
typeRemapper: TypeRemapper,
@@ -30,22 +28,29 @@ class RegeneratedClassContext(
override val callSiteInfo: InlineCallSiteInfo,
override val transformationInfo: TransformationInfo
) : InliningContext(
parent, expressionMap, state, nameGenerator, typeRemapper, lambdaInfo, true
parent, state, nameGenerator, typeRemapper, lambdaInfo, true
) {
val continuationBuilders: MutableMap<String, ClassBuilder> = hashMapOf()
}
open class InliningContext(
val parent: InliningContext?,
val expressionMap: Map<Int, FunctionalArgument>,
val state: GenerationState,
val nameGenerator: NameGenerator,
val typeRemapper: TypeRemapper,
val lambdaInfo: LambdaInfo?,
val classRegeneration: Boolean
) {
val isInliningLambda
get() = lambdaInfo != null
val isInliningLambda = lambdaInfo != null
// Consider this arrangement:
// inline fun <reified T> f(x: () -> Unit = { /* uses `T` in a local class */ }) = x()
// inline fun <reified V> g() = f<...> { /* uses `V` in a local class */ }
// When inlining `f` into `g`, we need to reify the contents of the default for `x` (if it was used), but not the
// contents of the lambda passed as the argument in `g` as all reified type parameters used by the latter are not from `f`.
val shouldReifyTypeParametersInObjects: Boolean
get() = lambdaInfo == null || lambdaInfo is DefaultLambda
var generateAssertField = false
@@ -54,7 +59,8 @@ open class InliningContext(
var isContinuation: Boolean = false
val isRoot: Boolean = parent == null
val isRoot: Boolean
get() = parent == null
val root: RootInliningContext
get() = if (isRoot) this as RootInliningContext else parent!!.root
@@ -88,7 +94,7 @@ open class InliningContext(
callSiteInfo: InlineCallSiteInfo,
transformationInfo: TransformationInfo
): InliningContext = RegeneratedClassContext(
this, expressionMap, state, generator, TypeRemapper.createFrom(typeRemapper, newTypeMappings),
this, state, generator, TypeRemapper.createFrom(typeRemapper, newTypeMappings),
lambdaInfo, callSiteInfo, transformationInfo
)
@@ -101,7 +107,7 @@ open class InliningContext(
): InliningContext {
val isInliningLambda = lambdaInfo != null
return InliningContext(
this, expressionMap, state, generator,
this, state, generator,
TypeRemapper.createFrom(
typeRemapper,
additionalTypeMappings,

View File

@@ -0,0 +1,386 @@
/*
* 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 org.jetbrains.kotlin.codegen.optimization.boxing.isMethodInsnWith
import org.jetbrains.kotlin.codegen.optimization.common.InsnSequence
import org.jetbrains.kotlin.codegen.optimization.common.removeUnusedLocalVariables
import org.jetbrains.kotlin.codegen.optimization.common.updateMaxStack
import org.jetbrains.kotlin.codegen.optimization.transformer.MethodTransformer
import org.jetbrains.org.objectweb.asm.Label
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.tree.*
class InplaceArgumentsMethodTransformer : MethodTransformer() {
override fun transform(internalClassName: String, methodNode: MethodNode) {
val methodContext = parseMethodOrNull(methodNode)
if (methodContext != null) {
if (methodContext.calls.isEmpty()) return
collectStartToEnd(methodContext)
collectLvtEntryInstructions(methodContext)
collectSuspensionPoints(methodContext)
transformMethod(methodContext)
updateLvtEntriesForMovedInstructions(methodContext)
methodNode.removeUnusedLocalVariables()
methodNode.updateMaxStack()
}
stripMarkers(methodNode)
}
private class MethodContext(
val methodNode: MethodNode,
val calls: List<CallContext>
) {
val startArgToEndArg = HashMap<AbstractInsnNode, AbstractInsnNode>()
val lvtEntryForInstruction = HashMap<AbstractInsnNode, LocalVariableNode>()
val varInstructionMoved = HashMap<AbstractInsnNode, CallContext>()
val suspensionJumpLabels = HashSet<LabelNode>()
}
private class CallContext(
val callStartMarker: AbstractInsnNode,
val callEndMarker: AbstractInsnNode,
val args: List<ArgContext>,
val calls: List<CallContext>,
val endLabel: LabelNode
)
private class ArgContext(
val argStartMarker: AbstractInsnNode,
val argEndMarker: AbstractInsnNode,
val calls: List<CallContext>,
val storeInsn: VarInsnNode
) {
val loadOpcode = storeInsn.opcode - Opcodes.ISTORE + Opcodes.ILOAD
val varIndex = storeInsn.`var`
}
private fun parseMethodOrNull(methodNode: MethodNode): MethodContext? {
// We assume that the method body structure follows this grammar:
// METHOD ::= insn* (CALL insn*)*
// CALL ::= callStartMarker insn* (ARG insn*)* (CALL insn*)* callEndMarker
// ARG ::= argStartMarker insn* (CALL insn*)* argEndMarker storeInsn
val iter = methodNode.instructions.iterator()
val calls = ArrayList<CallContext>()
try {
while (iter.hasNext()) {
val insn = iter.next()
when {
insn.isInplaceCallStartMarker() ->
calls.add(parseCall(methodNode, insn, iter))
insn.isInplaceCallEndMarker() || insn.isInplaceArgumentStartMarker() || insn.isInplaceArgumentEndMarker() ->
throw ParseErrorException()
}
}
} catch (e: ParseErrorException) {
return null
}
return MethodContext(methodNode, calls)
}
private fun parseCall(methodNode: MethodNode, start: AbstractInsnNode, iter: ListIterator<AbstractInsnNode>): CallContext {
// CALL ::= callStartMarker insn* (ARG insn*)* (CALL insn*)* callEndMarker
val args = ArrayList<ArgContext>()
val calls = ArrayList<CallContext>()
while (iter.hasNext()) {
val insn = iter.next()
when {
insn.isInplaceCallStartMarker() ->
calls.add(parseCall(methodNode, insn, iter))
insn.isInplaceCallEndMarker() -> {
val previous = insn.previous
val endLabel =
if (previous.type == AbstractInsnNode.LABEL)
previous as LabelNode
else
LabelNode(Label()).also {
// Make sure each call with inplace arguments has an endLabel
// (we need it to update LVT after transformation).
methodNode.instructions.insertBefore(insn, it)
}
return CallContext(start, insn, args, calls, endLabel)
}
insn.isInplaceArgumentStartMarker() ->
args.add(parseArg(methodNode, insn, iter))
insn.isInplaceArgumentEndMarker() ->
throw ParseErrorException()
}
}
// Reached instruction list end, didn't find inplace-call-end marker
throw ParseErrorException()
}
private fun parseArg(methodNode: MethodNode, start: AbstractInsnNode, iter: ListIterator<AbstractInsnNode>): ArgContext {
// ARG ::= argStartMarker insn* (CALL insn*)* argEndMarker storeInsn
val calls = ArrayList<CallContext>()
while (iter.hasNext()) {
val insn = iter.next()
when {
insn.isInplaceCallStartMarker() ->
calls.add(parseCall(methodNode, insn, iter))
insn.isInplaceArgumentEndMarker() -> {
val next = insn.next
if (next is VarInsnNode && next.opcode in Opcodes.ISTORE..Opcodes.ASTORE) {
iter.next()
return ArgContext(start, insn, calls, next)
} else {
throw ParseErrorException()
}
}
insn.isInplaceCallEndMarker() || insn.isInplaceArgumentStartMarker() ->
throw ParseErrorException()
}
}
// Reached instruction list end, didn't find inplace-argument-end marker
throw ParseErrorException()
}
private class ParseErrorException : RuntimeException() {
override fun fillInStackTrace(): Throwable = this
}
private fun collectStartToEnd(methodContext: MethodContext) {
for (call in methodContext.calls) {
collectStartToEnd(methodContext, call)
}
}
private fun collectStartToEnd(methodContext: MethodContext, callContext: CallContext) {
for (arg in callContext.args) {
collectStartToEnd(methodContext, arg)
}
for (call in callContext.calls) {
collectStartToEnd(methodContext, call)
}
}
private fun collectStartToEnd(methodContext: MethodContext, argContext: ArgContext) {
methodContext.startArgToEndArg[argContext.argStartMarker] = argContext.argEndMarker
for (call in argContext.calls) {
collectStartToEnd(methodContext, call)
}
}
private fun collectLvtEntryInstructions(methodContext: MethodContext) {
val insnList = methodContext.methodNode.instructions
val insnArray = insnList.toArray()
for (lv in methodContext.methodNode.localVariables) {
val lvStartIndex = insnList.indexOf(lv.start)
val lvEndIndex = insnList.indexOf(lv.end)
for (i in lvStartIndex until lvEndIndex) {
val insn = insnArray[i]
if (insn.opcode in Opcodes.ILOAD..Opcodes.ALOAD || insn.opcode in Opcodes.ISTORE..Opcodes.ASTORE) {
if ((insn as VarInsnNode).`var` == lv.index) {
methodContext.lvtEntryForInstruction[insn] = lv
}
} else if (insn.opcode == Opcodes.IINC) {
if ((insn as IincInsnNode).`var` == lv.index) {
methodContext.lvtEntryForInstruction[insn] = lv
}
}
}
}
}
private fun collectSuspensionPoints(methodContext: MethodContext) {
val insnList = methodContext.methodNode.instructions
var insn = insnList.first
while (
!insn.isMethodInsnWith(Opcodes.INVOKESTATIC) {
owner == "kotlin/coroutines/intrinsics/IntrinsicsKt" &&
name == "getCOROUTINE_SUSPENDED" &&
desc == "()Ljava/lang/Object;"
}
) {
insn = insn.next ?: return
}
// Find a first TABLESWITCH and record its jump destinations
while (insn != null) {
if (insn.opcode != Opcodes.TABLESWITCH || insn.previous.opcode != Opcodes.GETFIELD) {
insn = insn.next
continue
}
val getFiendInsn = insn.previous as FieldInsnNode
if (getFiendInsn.name != "label" || getFiendInsn.desc != "I") {
insn = insn.next
continue
}
val tableSwitchInsn = insn as TableSwitchInsnNode
methodContext.suspensionJumpLabels.addAll(tableSwitchInsn.labels)
methodContext.suspensionJumpLabels.add(tableSwitchInsn.dflt)
return
}
}
private fun transformMethod(methodContext: MethodContext) {
for (call in methodContext.calls) {
transformCall(methodContext, call)
}
}
private fun transformCall(methodContext: MethodContext, callContext: CallContext) {
// Transform nested calls
for (arg in callContext.args) {
for (nestedCall in arg.calls) {
transformCall(methodContext, nestedCall)
}
}
for (call in callContext.calls) {
transformCall(methodContext, call)
}
// If an inplace argument contains a non-local jump,
// moving such argument inside inline function body can interfere with stack normalization.
// TODO investigate complex cases
if (callContext.args.any { it.isUnsafeToMove(methodContext) }) {
// Do not transform such call, just strip call and argument markers.
val insnList = methodContext.methodNode.instructions
for (arg in callContext.args) {
insnList.remove(arg.argStartMarker)
insnList.remove(arg.argEndMarker)
}
insnList.remove(callContext.callStartMarker)
insnList.remove(callContext.callEndMarker)
return
}
moveInplaceArgumentsFromStoresToLoads(methodContext, callContext)
}
private fun ArgContext.isUnsafeToMove(methodContext: MethodContext): Boolean {
val argInsns = InsnSequence(this.argStartMarker, this.argEndMarker)
val localLabels = argInsns.filterTo(HashSet()) { it is LabelNode }
return argInsns.any { insn ->
insn in methodContext.suspensionJumpLabels ||
insn.opcode == Opcodes.GOTO && (insn as JumpInsnNode).label !in localLabels
}
}
private fun moveInplaceArgumentsFromStoresToLoads(methodContext: MethodContext, callContext: CallContext) {
// Transform call
val insnList = methodContext.methodNode.instructions
val args = callContext.args.associateBy { it.varIndex }
var argsProcessed = 0
var insn: AbstractInsnNode = callContext.callStartMarker
while (insn != callContext.callEndMarker) {
when {
insn.isInplaceArgumentStartMarker() -> {
// Skip argument body
insn = methodContext.startArgToEndArg[insn]!!
}
insn.opcode in Opcodes.ILOAD..Opcodes.ALOAD -> {
// Load instruction
val loadInsn = insn as VarInsnNode
val varIndex = loadInsn.`var`
val arg = args[varIndex]
if (arg == null || arg.loadOpcode != insn.opcode) {
// Not an argument load
insn = insn.next
} else {
// For each argument within this call we have
// <inplaceArgStartMarker>
// <argumentBody>
// <inplaceArgEndMarker>
// store [arg]
// ...
// load [arg]
// Replace 'load [arg]' with '<argumentBody>', drop 'store [arg]' and argument markers.
var argInsn = arg.argStartMarker.next
while (argInsn != arg.argEndMarker) {
// If a LOAD/STORE/IINC instruction was moved,
// record it so that we can update corresponding LVT entry if needed.
// NB it's better to do so after all transformations, so that we don't recalculate node indices.
if (argInsn.opcode in Opcodes.ILOAD..Opcodes.ALOAD ||
argInsn.opcode in Opcodes.ISTORE..Opcodes.ASTORE ||
argInsn.opcode == Opcodes.IINC
) {
methodContext.varInstructionMoved[argInsn] = callContext
}
val argInsnNext = argInsn.next
insnList.remove(argInsn)
insnList.insertBefore(loadInsn, argInsn)
argInsn = argInsnNext
}
// Remove argument load and corresponding argument store instructions
insnList.remove(arg.storeInsn)
insn = loadInsn.next
insnList.remove(loadInsn)
// Replace subsequent argument loads with DUP instructions of appropriate size
while (insn.opcode == loadInsn.opcode && (insn as VarInsnNode).`var` == varIndex) {
if (insn.opcode == Opcodes.LLOAD || insn.opcode == Opcodes.DLOAD) {
insnList.insertBefore(insn, InsnNode(Opcodes.DUP2))
} else {
insnList.insertBefore(insn, InsnNode(Opcodes.DUP))
}
val next = insn.next
insnList.remove(insn)
insn = next
}
// Remove argument markers
insnList.remove(arg.argStartMarker)
insnList.remove(arg.argEndMarker)
// If there are no more inplace arguments left to process, we are done
++argsProcessed
if (argsProcessed >= callContext.args.size)
break
}
}
else ->
insn = insn.next
}
}
// Remove call start and call end markers
insnList.remove(callContext.callStartMarker)
insnList.remove(callContext.callEndMarker)
}
private fun updateLvtEntriesForMovedInstructions(methodContext: MethodContext) {
val insnList = methodContext.methodNode.instructions
for ((insn, callContext) in methodContext.varInstructionMoved.entries) {
// Extend local variable interval to call end label if needed
val lv = methodContext.lvtEntryForInstruction[insn] ?: continue
val lvEndIndex = insnList.indexOf(lv.end)
val endLabelIndex = insnList.indexOf(callContext.endLabel)
if (endLabelIndex > lvEndIndex) {
lv.end = callContext.endLabel
}
}
}
private fun stripMarkers(methodNode: MethodNode) {
var insn = methodNode.instructions.first
while (insn != null) {
if (insn.isInplaceCallStartMarker() ||
insn.isInplaceCallEndMarker() ||
insn.isInplaceArgumentStartMarker() ||
insn.isInplaceArgumentEndMarker()
) {
val next = insn.next
methodNode.instructions.remove(insn)
insn = next
continue
}
insn = insn.next
}
}
}

View File

@@ -6,6 +6,7 @@
package org.jetbrains.kotlin.codegen.inline
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.codegen.coroutines.isCoroutineSuperClass
import org.jetbrains.kotlin.resolve.jvm.AsmTypes.*
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.org.objectweb.asm.ClassReader
@@ -16,12 +17,7 @@ import org.jetbrains.org.objectweb.asm.tree.FieldInsnNode
interface FunctionalArgument
abstract class LambdaInfo(@JvmField val isCrossInline: Boolean) : FunctionalArgument {
abstract val isBoundCallableReference: Boolean
abstract val isSuspend: Boolean
abstract class LambdaInfo : FunctionalArgument {
abstract val lambdaClassType: Type
abstract val invokeMethod: Method
@@ -39,11 +35,17 @@ abstract class LambdaInfo(@JvmField val isCrossInline: Boolean) : FunctionalArgu
val reifiedTypeParametersUsages = ReifiedTypeParametersUsages()
open val hasDispatchReceiver = true
open val hasDispatchReceiver
get() = true
fun addAllParameters(remapper: FieldRemapper): Parameters {
val builder = ParametersBuilder.initializeBuilderFrom(OBJECT_TYPE, invokeMethod.descriptor, this)
val builder = ParametersBuilder.newBuilder()
if (hasDispatchReceiver) {
builder.addThis(lambdaClassType, skipped = true).functionalArgument = this
}
for (type in Type.getArgumentTypes(invokeMethod.descriptor)) {
builder.addNextParameter(type, skipped = false)
}
for (info in capturedVars) {
val field = remapper.findField(FieldInsnNode(0, info.containingLambdaName, info.fieldName, ""))
?: error("Captured field not found: " + info.containingLambdaName + "." + info.fieldName)
@@ -65,76 +67,73 @@ abstract class LambdaInfo(@JvmField val isCrossInline: Boolean) : FunctionalArgu
object NonInlineableArgumentForInlineableParameterCalledInSuspend : FunctionalArgument
object NonInlineableArgumentForInlineableSuspendParameter : FunctionalArgument
object DefaultValueOfInlineParameter : FunctionalArgument
abstract class ExpressionLambda(isCrossInline: Boolean) : LambdaInfo(isCrossInline) {
abstract class ExpressionLambda : LambdaInfo() {
fun generateLambdaBody(sourceCompiler: SourceCompilerForInline) {
node = sourceCompiler.generateLambdaBody(this, reifiedTypeParametersUsages)
node.node.preprocessSuspendMarkers(forInline = true, keepFakeContinuation = false)
}
}
abstract class DefaultLambda(
final override val lambdaClassType: Type,
capturedArgs: Array<Type>,
isCrossinline: Boolean,
val offset: Int,
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>
class DefaultLambda(info: ExtractedDefaultLambda, sourceCompiler: SourceCompilerForInline) : LambdaInfo() {
val isBoundCallableReference: Boolean
final override val invokeMethod: Method
override val lambdaClassType: Type = info.type
override val capturedVars: List<CapturedParamDesc>
override val invokeMethod: Method
get() = Method(node.node.name, node.node.desc)
private val nullableAnyType = sourceCompiler.state.module.builtIns.nullableAnyType
override val invokeMethodParameters: List<KotlinType>
get() = List(invokeMethod.argumentTypes.size) { nullableAnyType }
override val invokeMethodReturnType: KotlinType
get() = nullableAnyType
val originalBoundReceiverType: Type?
protected val isPropertyReference: Boolean
protected val isFunctionReference: Boolean
init {
val classBytes = loadClass(sourceCompiler)
val classBytes =
sourceCompiler.state.inlineCache.classBytes.getOrPut(lambdaClassType.internalName) {
loadClassBytesByInternalName(sourceCompiler.state, lambdaClassType.internalName)
}
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>$constructorDescriptor for default lambda $lambdaClassType"
// TODO: suspend lambdas are their own continuations, so the body is pre-inlined into `invokeSuspend`
// and thus can't be detangled from the state machine. To make them inlinable, this needs to be redesigned.
// See `SuspendLambdaLowering`.
require(!superName.isCoroutineSuperClass()) {
"suspend default lambda ${lambdaClassType.internalName} cannot be inlined; use a function reference instead"
}
val constructorMethod = Method("<init>", Type.VOID_TYPE, info.capturedArgs)
val constructor = getMethodNode(classBytes, lambdaClassType, constructorMethod)?.node
assert(constructor != null || info.capturedArgs.isEmpty()) {
"can't find constructor '$constructorMethod' for default lambda '${lambdaClassType.internalName}'"
}
val isPropertyReference = superName in PROPERTY_REFERENCE_SUPER_CLASSES
val isReference = isPropertyReference ||
superName == FUNCTION_REFERENCE.internalName || superName == FUNCTION_REFERENCE_IMPL.internalName
// 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) }
info.capturedArgs.singleOrNull()?.takeIf { isReference && AsmUtil.isPrimitive(it) }
capturedVars =
if (isFunctionReference || isPropertyReference)
capturedArgs.singleOrNull()?.let {
listOf(capturedParamDesc(AsmUtil.RECEIVER_PARAMETER_NAME, AsmUtil.boxType(it), isSuspend = false))
if (isReference)
info.capturedArgs.singleOrNull()?.let {
// See `InlinedLambdaRemapper`
listOf(capturedParamDesc(AsmUtil.RECEIVER_PARAMETER_NAME, OBJECT_TYPE, isSuspend = false))
} ?: emptyList()
else
constructor?.findCapturedFieldAssignmentInstructions()?.map { fieldNode ->
capturedParamDesc(fieldNode.name, Type.getType(fieldNode.desc), isSuspend = false)
}?.toList() ?: emptyList()
isBoundCallableReference = (isFunctionReference || isPropertyReference) && capturedVars.isNotEmpty()
}
private fun loadClass(sourceCompiler: SourceCompilerForInline): ByteArray =
sourceCompiler.state.inlineCache.classBytes.getOrPut(lambdaClassType.internalName) {
loadClassBytesByInternalName(sourceCompiler.state, lambdaClassType.internalName)
}
// 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 } }
isBoundCallableReference = isReference && capturedVars.isNotEmpty()
node = loadDefaultLambdaBody(classBytes, lambdaClassType, isPropertyReference)
}
private companion object {

View File

@@ -6,19 +6,15 @@
package org.jetbrains.kotlin.codegen.inline
import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.coroutines.continuationAsmType
import org.jetbrains.kotlin.codegen.coroutines.CONTINUATION_ASM_TYPE
import org.jetbrains.kotlin.codegen.inline.FieldRemapper.Companion.foldName
import org.jetbrains.kotlin.codegen.inline.coroutines.CoroutineTransformer
import org.jetbrains.kotlin.codegen.inline.coroutines.markNoinlineLambdaIfSuspend
import org.jetbrains.kotlin.codegen.inline.coroutines.surroundInvokesWithSuspendMarkersIfNeeded
import org.jetbrains.kotlin.codegen.optimization.ApiVersionCallsPreprocessingMethodTransformer
import org.jetbrains.kotlin.codegen.optimization.FixStackWithLabelNormalizationMethodTransformer
import org.jetbrains.kotlin.codegen.optimization.common.ControlFlowGraph
import org.jetbrains.kotlin.codegen.optimization.common.InsnSequence
import org.jetbrains.kotlin.codegen.optimization.common.asSequence
import org.jetbrains.kotlin.codegen.optimization.common.isMeaningful
import org.jetbrains.kotlin.codegen.optimization.fixStack.peek
import org.jetbrains.kotlin.codegen.optimization.fixStack.top
import org.jetbrains.kotlin.codegen.optimization.common.*
import org.jetbrains.kotlin.codegen.optimization.fixStack.*
import org.jetbrains.kotlin.codegen.optimization.nullCheck.isCheckParameterIsNotNull
import org.jetbrains.kotlin.codegen.pseudoInsns.PseudoInsn
import org.jetbrains.kotlin.config.LanguageFeature
@@ -36,8 +32,6 @@ import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
import org.jetbrains.org.objectweb.asm.commons.LocalVariablesSorter
import org.jetbrains.org.objectweb.asm.commons.MethodRemapper
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
import org.jetbrains.org.objectweb.asm.tree.analysis.Frame
import org.jetbrains.org.objectweb.asm.util.Printer
import java.util.*
@@ -57,8 +51,10 @@ class MethodInliner(
) {
private val languageVersionSettings = inliningContext.state.languageVersionSettings
private val invokeCalls = ArrayList<InvokeCall>()
//keeps order
private val transformations = ArrayList<TransformationInfo>()
//current state
private val currentTypeMapping = HashMap<String, String?>()
private val result = InlineResult.create()
@@ -92,10 +88,6 @@ class MethodInliner(
): InlineResult {
//analyze body
var transformedNode = markPlacesForInlineAndRemoveInlinable(node, returnLabels, finallyDeepShift)
if (inliningContext.isInliningLambda && isDefaultLambdaWithReification(inliningContext.lambdaInfo!!)) {
//TODO maybe move reification in one place
inliningContext.root.inlineMethodReifier.reifyInstructions(transformedNode)
}
//substitute returns with "goto end" instruction to keep non local returns in lambdas
val end = linkedLabel()
@@ -232,7 +224,7 @@ class MethodInliner(
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) {
if (info is PsiExpressionLambda && info.invokeMethodDescriptor.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)
@@ -277,7 +269,8 @@ class MethodInliner(
val varRemapper = LocalVarRemapper(lambdaParameters, valueParamShift)
//TODO add skipped this and receiver
val lambdaResult = inliner.doInline(localVariablesSorter, varRemapper, true, info.returnLabels, invokeCall.finallyDepthShift)
val lambdaResult =
inliner.doInline(localVariablesSorter, varRemapper, true, info.returnLabels, invokeCall.finallyDepthShift)
result.mergeWithNotChangeInfo(lambdaResult)
result.reifiedTypeParametersUsages.mergeAll(lambdaResult.reifiedTypeParametersUsages)
result.reifiedTypeParametersUsages.mergeAll(info.reifiedTypeParametersUsages)
@@ -307,7 +300,7 @@ class MethodInliner(
} else capturedParamDesc
visitFieldInsn(
Opcodes.GETSTATIC, realDesc.containingLambdaName,
FieldRemapper.foldName(realDesc.fieldName), realDesc.type.descriptor
foldName(realDesc.fieldName), realDesc.type.descriptor
)
}
super.visitMethodInsn(opcode, info.newClassName, name, info.newConstructorDescriptor, itf)
@@ -321,10 +314,11 @@ class MethodInliner(
} else {
super.visitMethodInsn(opcode, owner, name, desc, itf)
}
} else if ((!inliningContext.isInliningLambda || isDefaultLambdaWithReification(inliningContext.lambdaInfo!!)) &&
ReifiedTypeInliner.isNeedClassReificationMarker(MethodInsnNode(opcode, owner, name, desc, false))
) {
//we shouldn't process here content of inlining lambda it should be reified at external level except default lambdas
} else if (ReifiedTypeInliner.isNeedClassReificationMarker(MethodInsnNode(opcode, owner, name, desc, false))) {
// If objects are reified, the marker will be recreated by `handleAnonymousObjectRegeneration` above.
if (!inliningContext.shouldReifyTypeParametersInObjects) {
super.visitMethodInsn(opcode, owner, name, desc, itf)
}
} else {
super.visitMethodInsn(opcode, owner, name, desc, itf)
}
@@ -349,9 +343,6 @@ class MethodInliner(
return resultNode
}
private fun isDefaultLambdaWithReification(lambdaInfo: LambdaInfo) =
lambdaInfo is DefaultLambda && lambdaInfo.needReification
private fun prepareNode(node: MethodNode, finallyDeepShift: Int): MethodNode {
node.instructions.resetLabels()
@@ -381,10 +372,7 @@ class MethodInliner(
private fun getNewIndex(`var`: Int): Int {
val lambdaInfo = inliningContext.lambdaInfo
if (reorderIrLambdaParameters && lambdaInfo is IrExpressionLambda) {
val extensionSize =
if (lambdaInfo.isExtensionLambda && !lambdaInfo.isBoundCallableReference)
lambdaInfo.invokeMethod.argumentTypes[0].size
else 0
val extensionSize = if (lambdaInfo.isExtensionLambda) lambdaInfo.invokeMethod.argumentTypes[0].size else 0
return when {
// v-- extensionSize v-- argsSizeOnStack
// |- extension -|- captured -|- real -|- locals -| old descriptor
@@ -450,7 +438,7 @@ class MethodInliner(
else -> ""
}
val varName = if (!varSuffix.isEmpty() && name == AsmUtil.THIS) AsmUtil.INLINE_DECLARATION_SITE_THIS else name
val varName = if (varSuffix.isNotEmpty() && name == AsmUtil.THIS) AsmUtil.INLINE_DECLARATION_SITE_THIS else name
super.visitLocalVariable(varName + varSuffix, desc, signature, start, end, getNewIndex(index))
}
}
@@ -542,36 +530,36 @@ class MethodInliner(
cur.opcode == Opcodes.GETSTATIC -> {
val fieldInsnNode = cur as FieldInsnNode?
val className = fieldInsnNode!!.owner
if (isAnonymousSingletonLoad(className, fieldInsnNode.name)) {
recordTransformation(
AnonymousObjectTransformationInfo(
className, awaitClassReification, isAlreadyRegenerated(className), true,
inliningContext.nameGenerator
when {
isAnonymousSingletonLoad(className, fieldInsnNode.name) -> {
recordTransformation(
AnonymousObjectTransformationInfo(
className, awaitClassReification, isAlreadyRegenerated(className), true,
inliningContext.nameGenerator
)
)
)
awaitClassReification = false
} else if (isWhenMappingAccess(className, fieldInsnNode.name)) {
recordTransformation(
WhenMappingTransformationInfo(
className, inliningContext.nameGenerator, isAlreadyRegenerated(className), fieldInsnNode
awaitClassReification = false
}
isWhenMappingAccess(className, fieldInsnNode.name) -> {
recordTransformation(
WhenMappingTransformationInfo(
className, inliningContext.nameGenerator, isAlreadyRegenerated(className), fieldInsnNode
)
)
)
} else if (fieldInsnNode.isCheckAssertionsStatus()) {
fieldInsnNode.owner = inlineCallSiteInfo.ownerClassName
if (inliningContext.isInliningLambda) {
if (inliningContext.lambdaInfo!!.isCrossInline) {
assert(inliningContext.parent?.parent is RegeneratedClassContext) {
"$inliningContext grandparent shall be RegeneratedClassContext but got ${inliningContext.parent?.parent}"
}
inliningContext.parent!!.parent!!.generateAssertField = true
} else {
assert(inliningContext.parent != null) {
"$inliningContext parent shall not be null"
}
inliningContext.parent!!.generateAssertField = true
}
} else {
inliningContext.generateAssertField = true
}
fieldInsnNode.isCheckAssertionsStatus() -> {
fieldInsnNode.owner = inlineCallSiteInfo.ownerClassName
when {
// In inline function itself:
inliningContext.parent == null -> inliningContext
// In method of regenerated object - field should already exist:
inliningContext.parent is RegeneratedClassContext -> inliningContext.parent
// In lambda inlined into the root function:
inliningContext.parent.parent == null -> inliningContext.parent
// In lambda inlined into a method of a regenerated object:
else -> inliningContext.parent.parent as? RegeneratedClassContext
?: throw AssertionError("couldn't find class for \$assertionsDisabled (context = $inliningContext)")
}.generateAssertField = true
}
}
}
@@ -601,7 +589,7 @@ class MethodInliner(
assert(lambdaInfo.lambdaClassType.internalName == nodeRemapper.originalLambdaInternalName) {
"Wrong bytecode template for contract template: ${lambdaInfo.lambdaClassType.internalName} != ${nodeRemapper.originalLambdaInternalName}"
}
fieldInsn.name = FieldRemapper.foldName(fieldInsn.name)
fieldInsn.name = foldName(fieldInsn.name)
fieldInsn.opcode = Opcodes.PUTSTATIC
toDelete.addAll(stackTransformations)
}
@@ -641,9 +629,8 @@ class MethodInliner(
private fun replaceContinuationAccessesWithFakeContinuationsIfNeeded(processingNode: MethodNode) {
// in ir backend inline suspend lambdas do not use ALOAD 0 to get continuation, since they are generated as static functions
// instead they get continuation from parameter.
if (inliningContext.state.isIrBackend) return
val lambdaInfo = inliningContext.lambdaInfo ?: return
if (!lambdaInfo.isSuspend) return
if (lambdaInfo !is PsiExpressionLambda || !lambdaInfo.invokeMethodDescriptor.isSuspend) return
val sources = analyzeMethodNodeWithInterpreter(processingNode, Aload0Interpreter(processingNode))
val cfg = ControlFlowGraph.build(processingNode)
val aload0s = processingNode.instructions.asSequence().filter { it.opcode == Opcodes.ALOAD && it.safeAs<VarInsnNode>()?.`var` == 0 }
@@ -701,7 +688,7 @@ class MethodInliner(
}
for ((index, param) in paramTypes.reversed().withIndex()) {
if (param != languageVersionSettings.continuationAsmType() && param != OBJECT_TYPE) continue
if (param != CONTINUATION_ASM_TYPE && param != OBJECT_TYPE) continue
val sourceIndices = (frame.getStack(frame.stackSize - index - 1) as? Aload0BasicValue)?.indices ?: continue
for (sourceIndex in sourceIndices) {
val src = processingNode.instructions[sourceIndex]
@@ -746,6 +733,7 @@ class MethodInliner(
private fun preprocessNodeBeforeInline(node: MethodNode, returnLabels: Map<String, Label?>) {
try {
InplaceArgumentsMethodTransformer().transform("fake", node)
FixStackWithLabelNormalizationMethodTransformer().transform("fake", node)
} catch (e: Throwable) {
throw wrapException(e, node, "couldn't inline method call")
@@ -756,7 +744,9 @@ class MethodInliner(
ApiVersionCallsPreprocessingMethodTransformer(targetApiVersion).transform("fake", node)
}
val frames = analyzeMethodNodeWithInterpreter(node, BasicInterpreter())
removeFakeVariablesInitializationIfPresent(node)
val frames = FastStackAnalyzer("<fake>", node, FixStackInterpreter()).analyze()
val localReturnsNormalizer = LocalReturnsNormalizer()
@@ -778,6 +768,73 @@ class MethodInliner(
localReturnsNormalizer.transform(node)
}
private fun removeFakeVariablesInitializationIfPresent(node: MethodNode) {
// Before 1.6, we generated fake variable initialization instructions
// ICONST_0
// ISTORE x
// for all inline functions. Original intent was to mark inline function body for the debugger with corresponding LVT entry.
// However, for @InlineOnly functions corresponding LVT entries were not copied (assuming that nobody is actually debugging
// @InlineOnly functions).
// Since 1.6, we no longer generate fake variables for @InlineOnly functions
// Here we erase fake variable initialization for @InlineOnly functions inlined into existing bytecode (e.g., inline function
// inside third-party library).
// We consider a sequence of instructions 'ICONST_0; ISTORE x' a fake variable initialization if the corresponding variable 'x'
// is not used in the bytecode (see below).
val insnArray = node.instructions.toArray()
// Very conservative variable usage check.
// Here we look at integer variables only (this includes integral primitive types: byte, char, short, boolean).
// Variable is considered "used" if:
// - it's loaded with ILOAD instruction
// - it's incremented with IINC instruction
// - there's a local variable table entry for this variable
val usedIntegerVar = BooleanArray(node.maxLocals)
for (insn in insnArray) {
if (insn.type == AbstractInsnNode.VAR_INSN && insn.opcode == Opcodes.ILOAD) {
usedIntegerVar[(insn as VarInsnNode).`var`] = true
} else if (insn.type == AbstractInsnNode.IINC_INSN) {
usedIntegerVar[(insn as IincInsnNode).`var`] = true
}
}
for (localVariable in node.localVariables) {
val d0 = localVariable.desc[0]
// byte || char || short || int || boolean
if (d0 == 'B' || d0 == 'C' || d0 == 'S' || d0 == 'I' || d0 == 'Z') {
usedIntegerVar[localVariable.index] = true
}
}
// Looking for sequences of instructions:
// p0: ICONST_0
// p1: ISTORE x
// p2: <label>
// If variable 'x' is not "used" (see above), remove p0 and p1 instructions.
var changes = false
for (p0 in insnArray) {
if (p0.opcode != Opcodes.ICONST_0) continue
val p1 = p0.next ?: break
if (p1.opcode != Opcodes.ISTORE) continue
val p2 = p1.next ?: break
if (p2.type != AbstractInsnNode.LABEL) continue
val varIndex = (p1 as VarInsnNode).`var`
if (!usedIntegerVar[varIndex]) {
changes = true
node.instructions.remove(p0)
node.instructions.remove(p1)
}
}
if (changes) {
// If we removed some instructions, some TCBs could (in theory) become empty.
// Remove empty TCBs if there are any.
node.removeEmptyCatchBlocks()
}
}
private fun isAnonymousClassThatMustBeRegenerated(type: Type?): Boolean {
if (type == null || type.sort != Type.OBJECT) return false
return inliningContext.isRegeneratedAnonymousObject(type.internalName)
@@ -845,9 +902,9 @@ class MethodInliner(
if (inliningContext.isInliningLambda && inliningContext.lambdaInfo is IrExpressionLambda && !inliningContext.parent!!.isInliningLambda) {
val capturedVars = inliningContext.lambdaInfo.capturedVars
var offset = parameters.realParametersSizeOnStack
val map = capturedVars.map {
val map = capturedVars.associate {
offset to it.also { offset += it.type.size }
}.toMap()
}
var cur: AbstractInsnNode? = node.instructions.first
while (cur != null) {
@@ -892,6 +949,7 @@ class MethodInliner(
}
}
@Suppress("SameParameterValue")
private fun wrapException(originalException: Throwable, node: MethodNode, errorSuffix: String): RuntimeException {
return if (originalException is InlineException) {
InlineException("$errorPrefix: $errorSuffix", originalException)
@@ -904,7 +962,7 @@ class MethodInliner(
private class LocalReturn(
private val returnInsn: AbstractInsnNode,
private val insertBeforeInsn: AbstractInsnNode,
private val frame: Frame<BasicValue>
private val frame: Frame<FixStackValue>
) {
fun transform(insnList: InsnList, returnVariableIndex: Int) {
@@ -915,22 +973,19 @@ class MethodInliner(
if (expectedStackSize == actualStackSize) return
var stackSize = actualStackSize
val topValue = frame.getStack(stackSize - 1)
if (isReturnWithValue) {
val storeOpcode = Opcodes.ISTORE + returnInsn.opcode - Opcodes.IRETURN
insnList.insertBefore(insertBeforeInsn, VarInsnNode(storeOpcode, returnVariableIndex))
insnList.insertBefore(insertBeforeInsn, VarInsnNode(topValue.storeOpcode, returnVariableIndex))
stackSize--
}
while (stackSize > 0) {
val stackElementSize = frame.getStack(stackSize - 1).size
val popOpcode = if (stackElementSize == 1) Opcodes.POP else Opcodes.POP2
insnList.insertBefore(insertBeforeInsn, InsnNode(popOpcode))
insnList.insertBefore(insertBeforeInsn, InsnNode(frame.getStack(stackSize - 1).popOpcode))
stackSize--
}
if (isReturnWithValue) {
val loadOpcode = Opcodes.ILOAD + returnInsn.opcode - Opcodes.IRETURN
insnList.insertBefore(insertBeforeInsn, VarInsnNode(loadOpcode, returnVariableIndex))
insnList.insertBefore(insertBeforeInsn, VarInsnNode(topValue.loadOpcode, returnVariableIndex))
}
}
}
@@ -940,10 +995,10 @@ class MethodInliner(
private var returnVariableSize = 0
private var returnOpcode = -1
internal fun addLocalReturnToTransform(
fun addLocalReturnToTransform(
returnInsn: AbstractInsnNode,
insertBeforeInsn: AbstractInsnNode,
sourceValueFrame: Frame<BasicValue>
sourceValueFrame: Frame<FixStackValue>
) {
assert(isReturnOpcode(returnInsn.opcode)) { "return instruction expected" }
assert(returnOpcode < 0 || returnOpcode == returnInsn.opcode) { "Return op should be " + Printer.OPCODES[returnOpcode] + ", got " + Printer.OPCODES[returnInsn.opcode] }
@@ -952,11 +1007,7 @@ class MethodInliner(
localReturns.add(LocalReturn(returnInsn, insertBeforeInsn, sourceValueFrame))
if (returnInsn.opcode != Opcodes.RETURN) {
returnVariableSize = if (returnInsn.opcode == Opcodes.LRETURN || returnInsn.opcode == Opcodes.DRETURN) {
2
} else {
1
}
returnVariableSize = if (returnInsn.opcode == Opcodes.LRETURN || returnInsn.opcode == Opcodes.DRETURN) 2 else 1
}
}

View File

@@ -5,11 +5,11 @@
package org.jetbrains.kotlin.codegen.inline
import org.jetbrains.kotlin.codegen.optimization.common.FastMethodAnalyzer
import org.jetbrains.kotlin.codegen.optimization.common.InsnSequence
import org.jetbrains.kotlin.codegen.optimization.common.isMeaningful
import org.jetbrains.kotlin.codegen.optimization.nullCheck.isCheckParameterIsNotNull
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodParameterSignature
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.tree.AbstractInsnNode
import org.jetbrains.org.objectweb.asm.tree.FieldInsnNode
@@ -17,15 +17,6 @@ import org.jetbrains.org.objectweb.asm.tree.MethodNode
import org.jetbrains.org.objectweb.asm.tree.VarInsnNode
import org.jetbrains.org.objectweb.asm.tree.analysis.*
fun parameterOffsets(isStatic: Boolean, valueParameters: List<JvmMethodParameterSignature>): Array<Int> {
var nextOffset = if (isStatic) 0 else 1
return Array(valueParameters.size) { index ->
nextOffset.also {
nextOffset += valueParameters[index].asmType.size
}
}
}
fun MethodNode.remove(instructions: Sequence<AbstractInsnNode>) =
instructions.forEach {
this@remove.instructions.remove(it)
@@ -136,7 +127,7 @@ internal class Aload0Interpreter(private val node: MethodNode) : BasicInterprete
internal fun AbstractInsnNode.isAload0() = opcode == Opcodes.ALOAD && (this as VarInsnNode).`var` == 0
internal fun analyzeMethodNodeWithInterpreter(node: MethodNode, interpreter: BasicInterpreter): Array<out Frame<BasicValue>?> {
val analyzer = object : Analyzer<BasicValue>(interpreter) {
val analyzer = object : FastMethodAnalyzer<BasicValue>("fake", node, interpreter) {
override fun newFrame(nLocals: Int, nStack: Int): Frame<BasicValue> {
return object : Frame<BasicValue>(nLocals, nStack) {
@@ -151,7 +142,7 @@ internal fun analyzeMethodNodeWithInterpreter(node: MethodNode, interpreter: Bas
}
try {
return analyzer.analyze("fake", node)
return analyzer.analyze()
} catch (e: AnalyzerException) {
throw RuntimeException(e)
}

View File

@@ -107,22 +107,5 @@ class ParametersBuilder private constructor() {
fun newBuilder(): ParametersBuilder {
return ParametersBuilder()
}
@JvmOverloads
@JvmStatic
fun initializeBuilderFrom(
objectType: Type, descriptor: String, inlineLambda: LambdaInfo? = null, isStatic: Boolean = false
): ParametersBuilder {
val builder = newBuilder()
if (inlineLambda?.hasDispatchReceiver != false && !isStatic) {
//skipped this for inlined lambda cause it will be removed
builder.addThis(objectType, inlineLambda != null).functionalArgument = inlineLambda
}
for (type in Type.getArgumentTypes(descriptor)) {
builder.addNextParameter(type, false)
}
return builder
}
}
}

View File

@@ -5,16 +5,13 @@
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.*
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
@@ -28,12 +25,9 @@ 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.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,
@@ -43,19 +37,17 @@ class PsiInlineCodegen(
typeParameterMappings: TypeParameterMappings<KotlinType>,
sourceCompiler: SourceCompilerForInline,
private val methodOwner: Type,
private val actualDispatchReceiver: Type
private val actualDispatchReceiver: Type,
reportErrorsOn: KtElement,
) : InlineCodegen<ExpressionCodegen>(
codegen, state, signature, typeParameterMappings, sourceCompiler,
ReifiedTypeInliner(
typeParameterMappings, PsiInlineIntrinsicsSupport(state), codegen.typeSystem,
typeParameterMappings, PsiInlineIntrinsicsSupport(state, reportErrorsOn), codegen.typeSystem,
state.languageVersionSettings, state.unifiedNullChecks
),
), CallGenerator {
override fun generateAssertFieldIfNeeded(info: RootInliningContext) {
if (info.generateAssertField) {
codegen.parentCodegen.generateAssertField()
}
}
override fun generateAssertField() =
codegen.parentCodegen.generateAssertField()
override fun genCallInner(
callableMethod: Callable,
@@ -70,19 +62,16 @@ class PsiInlineCodegen(
return
}
try {
val registerLineNumber = registerLineNumberAfterwards(resolvedCall)
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)
}
for (info in closuresToGenerate) {
// 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())
performInline(registerLineNumberAfterwards(resolvedCall), functionDescriptor.isInlineOnly())
} finally {
state.globalInlineContext.exitFromInlining()
}
@@ -97,8 +86,7 @@ class PsiInlineCodegen(
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) {
if (!DescriptorAsmUtil.isStaticMethod((sourceCompiler as PsiSourceCompilerForInline).context.contextKind, functionDescriptor)) {
hiddenParameters += invocationParamBuilder.addNextParameter(methodOwner, false, actualDispatchReceiver) to
codegen.frameMap.enterTemp(methodOwner)
}
@@ -120,14 +108,6 @@ class PsiInlineCodegen(
hiddenParameters.clear()
}
/*lambda or callable reference*/
private fun isInliningParameter(expression: KtExpression, valueParameterDescriptor: ValueParameterDescriptor): Boolean {
//TODO deparenthesize typed
val deparenthesized = KtPsiUtil.deparenthesize(expression)
return InlineUtil.isInlineParameter(valueParameterDescriptor) && isInlinableParameterExpression(deparenthesized)
}
override fun genValueAndPut(
valueParameterDescriptor: ValueParameterDescriptor?,
argumentExpression: KtExpression,
@@ -139,7 +119,9 @@ class PsiInlineCodegen(
"which cannot be declared in Kotlin and thus be inline: $codegen"
}
if (isInliningParameter(argumentExpression, valueParameterDescriptor)) {
val isInlineParameter = InlineUtil.isInlineParameter(valueParameterDescriptor)
//TODO deparenthesize typed
if (isInlineParameter && isInlinableParameterExpression(KtPsiUtil.deparenthesize(argumentExpression))) {
rememberClosure(argumentExpression, parameterType.type, valueParameterDescriptor)
} else {
val value = codegen.gen(argumentExpression)
@@ -159,6 +141,8 @@ class PsiInlineCodegen(
private fun isCallSiteIsSuspend(descriptor: ValueParameterDescriptor): Boolean =
state.bindingContext[CodegenBinding.CALL_SITE_IS_SUSPEND_FOR_CROSSINLINE_LAMBDA, descriptor] == true
private val closuresToGenerate = mutableListOf<PsiExpressionLambda>()
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}" }
@@ -170,6 +154,7 @@ class PsiInlineCodegen(
val lambda = PsiExpressionLambda(ktLambda!!, state, parameter.isCrossinline, boundReceiver != null)
rememberClosure(type, parameter.index, lambda)
closuresToGenerate += lambda
if (boundReceiver != null) {
// Has to be done immediately to preserve evaluation order.
val receiver = codegen.generateReceiverValue(boundReceiver, false)
@@ -184,7 +169,7 @@ class PsiInlineCodegen(
}
}
var activeLambda: LambdaInfo? = null
var activeLambda: PsiExpressionLambda? = null
private set
private fun putClosureParametersOnStack(next: PsiExpressionLambda, receiverValue: StackValue?) {
@@ -200,11 +185,6 @@ class PsiInlineCodegen(
putCapturedToLocalVal(stackValue, activeLambda!!.capturedVars[paramIndex], stackValue.kotlinType)
override fun reorderArgumentsIfNeeded(actualArgsWithDeclIndex: List<ArgumentAndDeclIndex>, valueParameterTypes: List<Type>) = Unit
override fun extractDefaultLambdas(node: MethodNode): List<DefaultLambda> =
extractDefaultLambdas(node, extractDefaultLambdaOffsetAndDescriptor(jvmSignature, functionDescriptor)) { parameter ->
PsiDefaultLambda(type, capturedArgs, parameter, offset, needReification, sourceCompiler)
}
}
private val FunctionDescriptor.explicitParameters
@@ -213,9 +193,9 @@ private val FunctionDescriptor.explicitParameters
class PsiExpressionLambda(
expression: KtExpression,
private val state: GenerationState,
isCrossInline: Boolean,
override val isBoundCallableReference: Boolean
) : ExpressionLambda(isCrossInline) {
val isCrossInline: Boolean,
val isBoundCallableReference: Boolean
) : ExpressionLambda() {
override val lambdaClassType: Type
override val invokeMethod: Method
@@ -224,7 +204,7 @@ class PsiExpressionLambda(
override val invokeMethodParameters: List<KotlinType?>
get() {
val actualInvokeDescriptor = if (isSuspend)
val actualInvokeDescriptor = if (invokeMethodDescriptor.isSuspend)
getOrCreateJvmSuspendFunctionView(invokeMethodDescriptor, state)
else
invokeMethodDescriptor
@@ -242,8 +222,6 @@ class PsiExpressionLambda(
override val returnLabels: Map<String, Label?>
override val isSuspend: Boolean
val closure: CalculatedClosure
init {
@@ -272,7 +250,6 @@ class PsiExpressionLambda(
?: 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`.
@@ -303,32 +280,3 @@ class PsiExpressionLambda(
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,13 +5,20 @@
package org.jetbrains.kotlin.codegen.inline
import org.jetbrains.kotlin.builtins.StandardNames
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.load.java.JvmAnnotationNames
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.jvm.AsmTypes.*
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm.*
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.model.TypeParameterMarker
import org.jetbrains.org.objectweb.asm.Type
@@ -19,7 +26,10 @@ 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,
private val reportErrorsOn: KtElement,
) : ReifiedTypeInliner.IntrinsicsSupport<KotlinType> {
override fun putClassInstance(v: InstructionAdapter, type: KotlinType) {
DescriptorAsmUtil.putJavaLangClassInstance(v, state.typeMapper.mapType(type), type, state.typeMapper)
}
@@ -56,5 +66,26 @@ 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
override fun checkAnnotatedType(type: KotlinType) {
if (type.annotations.hasAnnotation(StandardNames.FqNames.extensionFunctionType)) {
state.diagnostics.report(TYPEOF_EXTENSION_FUNCTION_TYPE.on(reportErrorsOn))
} else if (type.annotations.any { it.fqName != JvmAnnotationNames.ENHANCED_NULLABILITY_ANNOTATION }) {
state.diagnostics.report(TYPEOF_ANNOTATED_TYPE.on(reportErrorsOn))
}
}
override fun reportSuspendTypeUnsupported() {
state.diagnostics.report(TYPEOF_SUSPEND_TYPE.on(reportErrorsOn))
}
override fun reportNonReifiedTypeParameterWithRecursiveBoundUnsupported(typeParameterName: Name) {
state.diagnostics.report(TYPEOF_NON_REIFIED_TYPE_PARAMETER_WITH_RECURSIVE_BOUND.on(reportErrorsOn, typeParameterName.asString()))
}
}

View File

@@ -15,7 +15,6 @@ 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.*
@@ -23,13 +22,11 @@ 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
@@ -160,8 +157,7 @@ class PsiSourceCompilerForInline(
}
FunctionCodegen.generateMethodBody(
adapter, descriptor, context, jvmMethodSignature, strategy, parentCodegen, state.jvmDefaultMode,
state.languageVersionSettings.isReleaseCoroutines()
adapter, descriptor, context, jvmMethodSignature, strategy, parentCodegen, state.jvmDefaultMode
)
if (isLambda) {
@@ -237,7 +233,7 @@ class PsiSourceCompilerForInline(
}
override fun compileInlineFunction(jvmSignature: JvmMethodSignature): SMAPAndMethodNode {
generateInlineIntrinsic(state.languageVersionSettings, functionDescriptor, jvmSignature.asmMethod, codegen.typeSystem)?.let {
generateInlineIntrinsic(functionDescriptor, jvmSignature.asmMethod, codegen.typeSystem)?.let {
return it
}

View File

@@ -20,9 +20,9 @@ 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
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeSystemCommonBackendContext
@@ -63,11 +63,19 @@ 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
fun checkAnnotatedType(type: KT)
fun reportSuspendTypeUnsupported()
fun reportNonReifiedTypeParameterWithRecursiveBoundUnsupported(typeParameterName: Name)
}
companion object {
@@ -223,7 +231,7 @@ class ReifiedTypeInliner<KT : KotlinTypeMarker>(
if (stubCheckcast !is TypeInsnNode) return false
val newMethodNode = MethodNode(Opcodes.API_VERSION)
generateAsCast(InstructionAdapter(newMethodNode), kotlinType, asmType, safe, languageVersionSettings, unifiedNullChecks)
generateAsCast(InstructionAdapter(newMethodNode), kotlinType, asmType, safe, unifiedNullChecks)
instructions.insert(insn, newMethodNode.instructions)
// Keep stubCheckcast to avoid VerifyErrors on 1.8+ bytecode,
@@ -247,7 +255,7 @@ class ReifiedTypeInliner<KT : KotlinTypeMarker>(
if (stubInstanceOf !is TypeInsnNode) return false
val newMethodNode = MethodNode(Opcodes.API_VERSION)
generateIsCheck(InstructionAdapter(newMethodNode), kotlinType, asmType, languageVersionSettings.isReleaseCoroutines())
generateIsCheck(InstructionAdapter(newMethodNode), kotlinType, asmType)
instructions.insert(insn, newMethodNode.instructions)
instructions.remove(stubInstanceOf)

View File

@@ -78,12 +78,12 @@ fun loadCompiledInlineFunction(
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)
val bytes = state.inlineCache.classBytes.getOrPut(containerType.internalName) {
findVirtualFile(state, containerId)?.contentsToByteArray()
?: throw IllegalStateException("Couldn't find declaration file for $containerId")
}
getMethodNode(containerType, bytes, asmMethod, isSuspend, isMangled)
}
return SMAPAndMethodNode(cloneMethodNode(resultInCache.node), resultInCache.classSMAP)
}
@@ -91,25 +91,24 @@ fun loadCompiledInlineFunction(
private fun getMethodNode(
owner: Type,
bytes: ByteArray,
name: String,
descriptor: String,
method: Method,
isSuspend: Boolean,
isMangled: Boolean
): SMAPAndMethodNode {
getMethodNode(owner, bytes, name, descriptor, isSuspend)?.let { return it }
getMethodNode(owner, bytes, method, 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 }
val dashIndex = method.name.indexOf('-')
val nameWithoutManglingSuffix = if (dashIndex > 0) method.name.substring(0, dashIndex) else method.name
if (nameWithoutManglingSuffix != method.name) {
getMethodNode(owner, bytes, Method(nameWithoutManglingSuffix, method.descriptor), isSuspend)?.let { return it }
}
getMethodNode(owner, bytes, "$nameWithoutManglingSuffix-impl", descriptor, isSuspend)?.let { return it }
getMethodNode(owner, bytes, Method("$nameWithoutManglingSuffix-impl", method.descriptor), isSuspend)?.let { return it }
}
throw IllegalStateException("couldn't find inline method $owner.$name$descriptor")
throw IllegalStateException("couldn't find inline method $owner.$method")
}
// 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)
private fun getMethodNode(owner: Type, bytes: ByteArray, method: Method, isSuspend: Boolean) =
(if (isSuspend) getMethodNode(bytes, owner, Method(method.name + FOR_INLINE_SUFFIX, method.descriptor)) else null)
?: getMethodNode(bytes, owner, method)

View File

@@ -12,7 +12,6 @@ import org.jetbrains.kotlin.codegen.inline.*
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.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import org.jetbrains.org.objectweb.asm.MethodVisitor
@@ -49,18 +48,16 @@ class CoroutineTransformer(
fun suspendLambdaWithGeneratedStateMachine(node: MethodNode): Boolean =
!isContinuationNotLambda() && isSuspendLambda(node) && isStateMachine(node)
private fun isContinuationNotLambda(): Boolean = inliningContext.isContinuation &&
if (state.languageVersionSettings.isReleaseCoroutines()) superClassName.endsWith("ContinuationImpl")
else methods.any { it.name == "getLabel" }
private fun isContinuationNotLambda(): Boolean = inliningContext.isContinuation && superClassName.endsWith("ContinuationImpl")
private fun isStateMachine(node: MethodNode): Boolean =
node.instructions.asSequence().any { insn -> insn is LdcInsnNode && insn.cst == ILLEGAL_STATE_ERROR_MESSAGE }
private fun isSuspendLambda(node: MethodNode) = isResumeImpl(node)
private fun isSuspendLambda(node: MethodNode) = isInvokeSuspend(node)
fun newMethod(node: MethodNode): DeferredMethodVisitor {
return when {
isResumeImpl(node) -> {
isInvokeSuspend(node) -> {
assert(!isStateMachine(node)) {
"Inlining/transforming state-machine"
}
@@ -71,9 +68,8 @@ class CoroutineTransformer(
}
}
private fun isResumeImpl(node: MethodNode): Boolean =
state.languageVersionSettings.isResumeImplMethodName(node.name.removeSuffix(FOR_INLINE_SUFFIX)) &&
inliningContext.isContinuation
private fun isInvokeSuspend(node: MethodNode): Boolean =
node.name.removeSuffix(FOR_INLINE_SUFFIX) == INVOKE_SUSPEND_METHOD_NAME && inliningContext.isContinuation
private fun isSuspendFunctionWithFakeConstructorCall(node: MethodNode): Boolean = findFakeContinuationConstructorClassName(node) != null
@@ -88,16 +84,15 @@ class CoroutineTransformer(
val sourceCompilerForInline = inliningContext.root.sourceCompilerForInline
val stateMachineBuilder = CoroutineTransformerMethodVisitor(
createNewMethodFrom(node, name), node.access, name, node.desc, null, null,
containingClassInternalName = classBuilder.thisName,
obtainClassBuilderForCoroutineState = { classBuilder },
isForNamedFunction = false,
shouldPreserveClassInitialization = state.constructorCallNormalizationMode.shouldPreserveClassInitialization,
disableTailCallOptimizationForFunctionReturningUnit = false,
reportSuspensionPointInsideMonitor = { sourceCompilerForInline.reportSuspensionPointInsideMonitor(it) },
// TODO: this linenumbers might not be correct and since they are used only for step-over, check them.
lineNumber = inliningContext.callSiteInfo.lineNumber,
sourceFile = inliningContext.callSiteInfo.file?.name ?: "",
languageVersionSettings = state.languageVersionSettings,
shouldPreserveClassInitialization = state.constructorCallNormalizationMode.shouldPreserveClassInitialization,
containingClassInternalName = classBuilder.thisName,
isForNamedFunction = false,
disableTailCallOptimizationForFunctionReturningUnit = false,
useOldSpilledVarTypeAnalysis = state.configuration.getBoolean(JVMConfigurationKeys.USE_OLD_SPILLED_VAR_TYPE_ANALYSIS)
)
@@ -123,17 +118,16 @@ class CoroutineTransformer(
val sourceCompilerForInline = inliningContext.root.sourceCompilerForInline
val stateMachineBuilder = CoroutineTransformerMethodVisitor(
createNewMethodFrom(node, name), node.access, name, node.desc, null, null,
containingClassInternalName = classBuilder.thisName,
obtainClassBuilderForCoroutineState = { (inliningContext as RegeneratedClassContext).continuationBuilders[continuationClassName]!! },
isForNamedFunction = true,
shouldPreserveClassInitialization = state.constructorCallNormalizationMode.shouldPreserveClassInitialization,
disableTailCallOptimizationForFunctionReturningUnit = disableTailCallOptimization,
reportSuspensionPointInsideMonitor = { sourceCompilerForInline.reportSuspensionPointInsideMonitor(it) },
lineNumber = inliningContext.callSiteInfo.lineNumber,
sourceFile = inliningContext.callSiteInfo.file?.name ?: "",
languageVersionSettings = state.languageVersionSettings,
shouldPreserveClassInitialization = state.constructorCallNormalizationMode.shouldPreserveClassInitialization,
containingClassInternalName = classBuilder.thisName,
isForNamedFunction = true,
needDispatchReceiver = true,
internalNameForDispatchReceiver = classBuilder.thisName,
disableTailCallOptimizationForFunctionReturningUnit = disableTailCallOptimization,
putContinuationParameterToLvt = !state.isIrBackend,
useOldSpilledVarTypeAnalysis = state.configuration.getBoolean(JVMConfigurationKeys.USE_OLD_SPILLED_VAR_TYPE_ANALYSIS)
)

View File

@@ -16,20 +16,16 @@
package org.jetbrains.kotlin.codegen.inline
import org.jetbrains.kotlin.codegen.DescriptorAsmUtil
import org.jetbrains.kotlin.codegen.OwnerKind
import org.jetbrains.kotlin.codegen.inline.ReifiedTypeInliner.Companion.isNeedClassReificationMarker
import org.jetbrains.kotlin.codegen.optimization.common.InsnSequence
import org.jetbrains.kotlin.codegen.optimization.common.asSequence
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.inline.InlineUtil
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodParameterKind
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.util.OperatorNameConventions
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.*
import kotlin.math.max
private data class Condition(
val mask: Int, val constant: Int,
@@ -41,25 +37,6 @@ private data class Condition(
val varIndex = varInsNode?.`var` ?: 0
}
fun extractDefaultLambdaOffsetAndDescriptor(
jvmSignature: JvmMethodSignature,
functionDescriptor: FunctionDescriptor
): Map<Int, ValueParameterDescriptor> {
val valueParameters = jvmSignature.valueParameters
val containingDeclaration = functionDescriptor.containingDeclaration
val kind =
if (DescriptorUtils.isInterface(containingDeclaration)) OwnerKind.DEFAULT_IMPLS
else OwnerKind.getMemberOwnerKind(containingDeclaration)
val parameterOffsets = parameterOffsets(DescriptorAsmUtil.isStaticMethod(kind, functionDescriptor), valueParameters)
val valueParameterOffset = valueParameters.takeWhile { it.kind != JvmMethodParameterKind.VALUE }.size
return functionDescriptor.valueParameters.filter {
InlineUtil.isInlineParameter(it) && it.declaresDefaultValue()
}.associateBy {
parameterOffsets[valueParameterOffset + it.index]
}
}
class ExtractedDefaultLambda(val type: Type, val capturedArgs: Array<Type>, val offset: Int, val needReification: Boolean)
fun expandMaskConditionsAndUpdateVariableNodes(
@@ -202,3 +179,68 @@ private fun defaultLambdaFakeCallStub(args: Array<Type>, lambdaOffset: Int): Met
false
)
}
fun loadDefaultLambdaBody(classBytes: ByteArray, classType: Type, isPropertyReference: Boolean): SMAPAndMethodNode {
// In general we can't know what the correct unboxed `invoke` is, and what Kotlin types its arguments have,
// as the type of this object may be any subtype of the parameter's type. All we know is that Function<N>
// has to have a `invoke` that takes `Object`s and returns an `Object`; everything else needs to be figured
// out from its contents. TODO: for > 22 arguments, the only argument is an array. `MethodInliner` can't do that.
val invokeName = if (isPropertyReference) OperatorNameConventions.GET.asString() else OperatorNameConventions.INVOKE.asString()
val invokeNode = getMethodNode(classBytes, classType) {
it.name == invokeName && it.returnType == AsmTypes.OBJECT_TYPE && it.argumentTypes.all { arg -> arg == AsmTypes.OBJECT_TYPE }
} ?: error("can't find erased invoke '$invokeName(Object...): Object' in default lambda '${classType.internalName}'")
return if (invokeNode.node.access.and(Opcodes.ACC_BRIDGE) == 0)
invokeNode
else
invokeNode.node.inlineBridge(classBytes, classType)
}
private fun MethodNode.inlineBridge(classBytes: ByteArray, classType: Type): SMAPAndMethodNode {
// If the erased invoke is a bridge, we need to locate the unboxed invoke and inline it. As mentioned above,
// we don't know what the Kotlin types of its arguments/returned value are, so we can't generate our own
// boxing/unboxing code; luckily, the bridge already has that.
val invokeInsn = instructions.singleOrNull { it is MethodInsnNode && it.owner == classType.internalName } as MethodInsnNode?
?: error("no single invoke of method on this in '${name}${desc}' of default lambda '${classType.internalName}'")
val targetMethod = Method(invokeInsn.name, invokeInsn.desc)
val target = getMethodNode(classBytes, classType, targetMethod)
?: error("can't find non-bridge invoke '$targetMethod' in default lambda '${classType.internalName}")
// Store unboxed/casted arguments in the correct variable slots
val targetArgs = targetMethod.argumentTypes
val targetArgsSize = targetArgs.sumOf { it.size } + if (target.node.access.and(Opcodes.ACC_STATIC) == 0) 1 else 0
var offset = targetArgsSize
for (type in targetArgs.reversed()) {
offset -= type.size
instructions.insertBefore(invokeInsn, VarInsnNode(type.getOpcode(Opcodes.ISTORE), offset))
}
if (target.node.access.and(Opcodes.ACC_STATIC) == 0) {
instructions.insertBefore(invokeInsn, InsnNode(Opcodes.POP)) // this
}
// Remap returns and ranges for arguments' LVT entries
val invokeLabel = LabelNode()
val returnLabel = LabelNode()
instructions.insertBefore(invokeInsn, invokeLabel)
instructions.insert(invokeInsn, returnLabel)
for (insn in target.node.instructions) {
if (insn.opcode in Opcodes.IRETURN..Opcodes.RETURN) {
target.node.instructions.set(insn, JumpInsnNode(Opcodes.GOTO, returnLabel))
}
}
for (local in target.node.localVariables) {
if (local.index < targetArgsSize) {
local.start = invokeLabel
local.end = returnLabel
}
}
// Insert contents of the method into the bridge
instructions.filterIsInstance<LineNumberNode>().forEach { instructions.remove(it) } // those are not meaningful
instructions.insertBefore(invokeInsn, target.node.instructions)
instructions.remove(invokeInsn)
localVariables = target.node.localVariables
tryCatchBlocks = target.node.tryCatchBlocks
maxLocals = max(maxLocals, target.node.maxLocals)
maxStack = max(maxStack, target.node.maxStack)
return SMAPAndMethodNode(this, target.classSMAP)
}

View File

@@ -0,0 +1,223 @@
/*
* 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 org.jetbrains.kotlin.codegen.optimization.nullCheck.isParameterCheckedForNull
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
import org.jetbrains.org.objectweb.asm.tree.*
fun canInlineArgumentsInPlace(methodNode: MethodNode): Boolean {
// Usual inline functions are inlined in the following way:
// <evaluate argument #1>
// <store argument to an argument variable V1>
// ...
// <evaluate argument #N>
// <store argument to an argument variable VN>
// <inline function method body with parameter variables Pi remapped to argument variables Vi>
// If an argument #k is already stored in a local variable W, this variable W is reused.
// When inlining arguments in-place, we instead replace corresponding variable load instructions in the inline function method body
// with bytecode for evaluating a given argument.
// We can do so if such transformation keeps the evaluation order intact, possibly disregarding class initialization.
//
// This is true for many simple @InlineOnly functions from Kotlin standard library.
// For example, bytecode for 'inline fun println(message: Any?)' is:
// GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
// ALOAD 0
// INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/Object;)V
// Basic inlining for 'println("Hello, world!")' would produce (skipping labels and line numbers):
// // evaluate arguments, storing them to local variables
// LDC "Hello, world!"
// ASTORE 0
// GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
// ALOAD 0
// INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/Object;)V
// With argument "Hello, world!" inlined in-place it would be:
// GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
// LDC "Hello, world!"
// INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/Object;)V
// Such inlining is possible because we consider it OK to reorder 'GETSTATIC java/lang/System.out : Ljava/io/PrintStream;' instruction
// with any argument evaluation instructions ('LDC "Hello, world!"' in this case).
val tcbStartLabels = methodNode.tryCatchBlocks.mapTo(HashSet()) { it.start }
val methodParameterTypes = Type.getArgumentTypes(methodNode.desc)
val jvmArgumentTypes = ArrayList<Type>(methodParameterTypes.size + 1)
if (methodNode.access and Opcodes.ACC_STATIC == 0) {
// Here we don't care much about the exact 'this' type,
// it's only important to remember that variable slot #0 holds an object reference.
jvmArgumentTypes.add(AsmTypes.OBJECT_TYPE)
}
jvmArgumentTypes.addAll(methodParameterTypes)
val argumentVarEnd = jvmArgumentTypes.sumOf { it.size }
var expectedArgumentVar = 0
var lastArgIndex = 0
var insn = methodNode.instructions.first
// During arguments evaluation, make sure that all arguments are loaded in expected order
// and there are no unexpected side effects in-between.
while (insn != null && expectedArgumentVar < argumentVarEnd) {
// Entering a try-catch block before all arguments are loaded breaks evaluation order.
if (insn in tcbStartLabels)
return false
// Some instructions break evaluation order.
if (insn.isProhibitedDuringArgumentsEvaluation())
return false
// Allow a limited list of 'GETSTATIC <owner> <name> <desc>' instructions.
if (insn.opcode == Opcodes.GETSTATIC) {
val fieldInsn = insn as FieldInsnNode
val fieldSignature = FieldSignature(fieldInsn.owner, fieldInsn.name, fieldInsn.desc)
if (fieldSignature !in whitelistedStaticFields)
return false
}
// Writing to or incrementing an argument variable forbids in-place argument inlining.
if (insn.opcode in Opcodes.ISTORE..Opcodes.ASTORE && (insn as VarInsnNode).`var` < argumentVarEnd)
return false
if (insn.opcode == Opcodes.IINC && (insn as IincInsnNode).`var` < argumentVarEnd)
return false
// Analyze variable loads.
if (insn.opcode in Opcodes.ILOAD..Opcodes.ALOAD) {
// Skip parameter null check: 'aload x; ldc "..."; invokestatic <check>'
if (insn.opcode == Opcodes.ALOAD && insn.isParameterCheckedForNull()) {
// Go directly to the instruction after 'invokestatic <check>'
insn = insn.next.next.next
continue
}
val varInsn = insn as VarInsnNode
val varIndex = (varInsn).`var`
if (varIndex == expectedArgumentVar) {
// Expected argument variable loaded.
expectedArgumentVar += jvmArgumentTypes[lastArgIndex].size
++lastArgIndex
// Skip a sequence of load instructions referring to the same argument variable
// (such sequence is present in functions like 'Array.copyOf' and can be replaced with DUP instructions).
do {
insn = insn.next
} while (insn != null && insn.opcode == varInsn.opcode && (insn as VarInsnNode).`var` == varIndex)
continue
} else if (varIndex < argumentVarEnd) {
// Loaded an argument variable, but not an expected one => broken evaluation order
return false
} else {
// It's OK to load any non-argument variable during argument evaluation.
insn = insn.next
continue
}
}
// Anything else is fine.
insn = insn.next
}
// Method body is over, but not all arguments were loaded on stack.
if (expectedArgumentVar < argumentVarEnd)
return false
// After arguments evaluation make sure that argument variables are no longer accessed
// (we are not going to store anything to those variables anyway).
while (insn != null) {
if (insn.opcode in Opcodes.ILOAD..Opcodes.ALOAD || insn.opcode in Opcodes.ISTORE..Opcodes.ASTORE) {
if ((insn as VarInsnNode).`var` < argumentVarEnd)
return false
} else if (insn.opcode == Opcodes.IINC) {
if ((insn as IincInsnNode).`var` < argumentVarEnd)
return false
}
insn = insn.next
}
// Didn't encounter anything suspicious.
return true
}
internal data class FieldSignature(
val owner: String,
val name: String,
val desc: String
)
private val whitelistedStaticFields: Set<FieldSignature> =
hashSetOf(
FieldSignature("java/lang/System", "out", "Ljava/io/PrintStream;"),
FieldSignature("kotlin/Result", "Companion", "Lkotlin/Result\$Companion;"),
FieldSignature("kotlin/_Assertions", "ENABLED", "Z")
)
private fun AbstractInsnNode.isProhibitedDuringArgumentsEvaluation() =
opcode in opcodeProhibitedDuringArgumentsEvaluation.indices &&
opcodeProhibitedDuringArgumentsEvaluation[opcode]
private val opcodeProhibitedDuringArgumentsEvaluation = BooleanArray(256).also { a ->
// Any kind of jump during arguments evaluation is a hazard.
// This includes all conditional jump instructions, switch instructions, return and throw instructions.
// Very conservative, but enough for practical cases.
for (i in Opcodes.IFEQ..Opcodes.RETURN) a[i] = true
a[Opcodes.IFNULL] = true
a[Opcodes.IFNONNULL] = true
a[Opcodes.ATHROW] = true
// Instruction with non-trivial side effects is a hazard.
// NB GETSTATIC is taken care of separately.
a[Opcodes.PUTSTATIC] = true
a[Opcodes.PUTFIELD] = true
a[Opcodes.INVOKEVIRTUAL] = true
a[Opcodes.INVOKESPECIAL] = true
a[Opcodes.INVOKESTATIC] = true
a[Opcodes.INVOKEINTERFACE] = true
a[Opcodes.INVOKEDYNAMIC] = true
a[Opcodes.MONITORENTER] = true
a[Opcodes.MONITOREXIT] = true
// Integer division instructions can throw exception
a[Opcodes.IDIV] = true
a[Opcodes.LDIV] = true
a[Opcodes.IREM] = true
a[Opcodes.LREM] = true
// CHECKCAST can throw exception
a[Opcodes.CHECKCAST] = true
// Array creation can throw exception (in case of negative array size)
a[Opcodes.NEWARRAY] = true
a[Opcodes.ANEWARRAY] = true
a[Opcodes.MULTIANEWARRAY] = true
// Array access instructions can throw exception
for (i in Opcodes.IALOAD..Opcodes.SALOAD) a[i] = true
for (i in Opcodes.IASTORE..Opcodes.SASTORE) a[i] = true
}
private const val MARKER_INPLACE_CALL_START = "<INPLACE-CALL-START>"
private const val MARKER_INPLACE_ARGUMENT_START = "<INPLACE-ARGUMENT-START>"
private const val MARKER_INPLACE_ARGUMENT_END = "<INPLACE-ARGUMENT-END>"
private const val MARKER_INPLACE_CALL_END = "<INPLACE-CALL-END>"
private fun InstructionAdapter.addMarker(name: String) {
visitMethodInsn(Opcodes.INVOKESTATIC, INLINE_MARKER_CLASS_NAME, name, "()V", false)
}
fun InstructionAdapter.addInplaceCallStartMarker() = addMarker(MARKER_INPLACE_CALL_START)
fun InstructionAdapter.addInplaceCallEndMarker() = addMarker(MARKER_INPLACE_CALL_END)
fun InstructionAdapter.addInplaceArgumentStartMarker() = addMarker(MARKER_INPLACE_ARGUMENT_START)
fun InstructionAdapter.addInplaceArgumentEndMarker() = addMarker(MARKER_INPLACE_ARGUMENT_END)
internal fun AbstractInsnNode.isInplaceCallStartMarker() = isInlineMarker(this, MARKER_INPLACE_CALL_START)
internal fun AbstractInsnNode.isInplaceCallEndMarker() = isInlineMarker(this, MARKER_INPLACE_CALL_END)
internal fun AbstractInsnNode.isInplaceArgumentStartMarker() = isInlineMarker(this, MARKER_INPLACE_ARGUMENT_START)
internal fun AbstractInsnNode.isInplaceArgumentEndMarker() = isInlineMarker(this, MARKER_INPLACE_ARGUMENT_END)

View File

@@ -43,6 +43,7 @@ import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
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 org.jetbrains.org.objectweb.asm.util.Printer
import org.jetbrains.org.objectweb.asm.util.Textifier
@@ -59,7 +60,7 @@ const val INLINE_FUN_VAR_SUFFIX = "\$iv"
internal const val FIRST_FUN_LABEL = "$$$$\$ROOT$$$$$"
internal const val SPECIAL_TRANSFORMATION_NAME = "\$special"
const val INLINE_TRANSFORMATION_SUFFIX = "\$inlined"
internal const val INLINE_CALL_TRANSFORMATION_SUFFIX = "$" + INLINE_TRANSFORMATION_SUFFIX
internal const val INLINE_CALL_TRANSFORMATION_SUFFIX = "$$INLINE_TRANSFORMATION_SUFFIX"
internal const val INLINE_FUN_THIS_0_SUFFIX = "\$inline_fun"
internal const val DEFAULT_LAMBDA_FAKE_CALL = "$$\$DEFAULT_LAMBDA_FAKE_CALL$$$"
internal const val CAPTURED_FIELD_FOLD_PREFIX = "$$$"
@@ -67,11 +68,10 @@ internal const val CAPTURED_FIELD_FOLD_PREFIX = "$$$"
private const val NON_LOCAL_RETURN = "$$$$\$NON_LOCAL_RETURN$$$$$"
const val CAPTURED_FIELD_PREFIX = "$"
private const val NON_CAPTURED_FIELD_PREFIX = "$$"
private const val INLINE_MARKER_CLASS_NAME = "kotlin/jvm/internal/InlineMarker"
internal const val INLINE_MARKER_CLASS_NAME = "kotlin/jvm/internal/InlineMarker"
private const val INLINE_MARKER_BEFORE_METHOD_NAME = "beforeInlineCall"
private const val INLINE_MARKER_AFTER_METHOD_NAME = "afterInlineCall"
private const val INLINE_MARKER_FINALLY_START = "finallyStart"
private const val INLINE_MARKER_FINALLY_END = "finallyEnd"
private const val INLINE_MARKER_BEFORE_SUSPEND_ID = 0
private const val INLINE_MARKER_AFTER_SUSPEND_ID = 1
@@ -84,40 +84,18 @@ private const val INLINE_MARKER_AFTER_INLINE_SUSPEND_ID = 7
private const val INLINE_MARKER_BEFORE_UNBOX_INLINE_CLASS = 8
private const val INLINE_MARKER_AFTER_UNBOX_INLINE_CLASS = 9
internal fun getMethodNode(
classData: ByteArray,
methodName: String,
methodDescriptor: String,
classType: Type,
signatureAmbiguity: Boolean = false
): SMAPAndMethodNode? {
val cr = ClassReader(classData)
internal inline fun getMethodNode(classData: ByteArray, classType: Type, crossinline match: (Method) -> Boolean): SMAPAndMethodNode? {
var node: MethodNode? = null
val debugInfo = arrayOfNulls<String>(2)
cr.accept(object : ClassVisitor(Opcodes.API_VERSION) {
var sourceFile: String? = null
var sourceMap: String? = null
ClassReader(classData).accept(object : ClassVisitor(Opcodes.API_VERSION) {
override fun visitSource(source: String?, debug: String?) {
super.visitSource(source, debug)
debugInfo[0] = source
debugInfo[1] = debug
sourceFile = source
sourceMap = debug
}
override fun visitMethod(
access: Int,
name: String,
desc: String,
signature: String?,
exceptions: Array<String>?
): MethodVisitor? {
if (methodName != name || (signatureAmbiguity && access.and(Opcodes.ACC_SYNTHETIC) != 0)) return null
if (methodDescriptor != desc) {
val sameNumberOfParameters = Type.getArgumentTypes(methodDescriptor).size == Type.getArgumentTypes(desc).size
if (!signatureAmbiguity || !sameNumberOfParameters) {
return null
}
}
override fun visitMethod(access: Int, name: String, desc: String, signature: String?, exceptions: Array<String>?): MethodVisitor? {
if (!match(Method(name, desc))) return null
node?.let { existing ->
throw AssertionError("Can't find proper '$name' method for inline: ambiguity between '${existing.name + existing.desc}' and '${name + desc}'")
}
@@ -126,15 +104,15 @@ internal fun getMethodNode(
}
}, ClassReader.SKIP_FRAMES or if (GENERATE_SMAP) 0 else ClassReader.SKIP_DEBUG)
if (node == null) {
return null
return node?.let{
val (first, last) = listOfNotNull(it).lineNumberRange()
SMAPAndMethodNode(it, SMAPParser.parseOrCreateDefault(sourceMap, sourceFile, classType.internalName, first, last))
}
val (first, last) = listOfNotNull(node).lineNumberRange()
val smap = SMAPParser.parseOrCreateDefault(debugInfo[1], debugInfo[0], classType.internalName, first, last)
return SMAPAndMethodNode(node!!, smap)
}
internal fun getMethodNode(classData: ByteArray, classType: Type, method: Method): SMAPAndMethodNode? =
getMethodNode(classData, classType) { it == method }
internal fun Collection<MethodNode>.lineNumberRange(): Pair<Int, Int> {
var minLine = Int.MAX_VALUE
var maxLine = Int.MIN_VALUE
@@ -323,7 +301,7 @@ internal fun firstLabelInChain(node: LabelNode): LabelNode {
internal fun areLabelsBeforeSameInsn(first: LabelNode, second: LabelNode): Boolean =
firstLabelInChain(first) == firstLabelInChain(second)
internal val MethodNode?.nodeText: String
val MethodNode?.nodeText: String
get() {
if (this == null) {
return "Not generated"
@@ -347,8 +325,42 @@ internal val AbstractInsnNode?.insnText: String
return sw.toString().trim()
}
fun AbstractInsnNode?.insnText(insnList: InsnList): String {
if (this == null) return "<null>"
fun AbstractInsnNode.indexOf() =
insnList.indexOf(this)
fun LabelNode.labelText() =
"L#${this.indexOf()}"
return when (this) {
is LabelNode ->
labelText()
is JumpInsnNode ->
"$insnOpcodeText ${label.labelText()}"
is LookupSwitchInsnNode ->
"$insnOpcodeText " +
this.keys.zip(this.labels).joinToString(prefix = "[", postfix = "]") { (key, label) -> "$key:${label.labelText()}" }
is TableSwitchInsnNode ->
"$insnOpcodeText " +
(min..max).zip(this.labels).joinToString(prefix = "[", postfix = "]") { (key, label) -> "$key:${label.labelText()}" }
else ->
insnText
}
}
internal val AbstractInsnNode?.insnOpcodeText: String
get() = if (this == null) "null" else Printer.OPCODES[opcode]
get() = when (this) {
null -> "null"
is LabelNode -> "LABEL"
is LineNumberNode -> "LINENUMBER"
is FrameNode -> "FRAME"
else -> Printer.OPCODES[opcode]
}
internal fun TryCatchBlockNode.text(insns: InsnList): String =
"[${insns.indexOf(start)} .. ${insns.indexOf(end)} -> ${insns.indexOf(handler)}]"
internal fun loadClassBytesByInternalName(state: GenerationState, internalName: String): ByteArray {
//try to find just compiled classes then in dependencies
@@ -522,17 +534,15 @@ internal fun isInlineMarker(insn: AbstractInsnNode): Boolean {
return isInlineMarker(insn, null)
}
private fun isInlineMarker(insn: AbstractInsnNode, name: String?): Boolean {
if (insn !is MethodInsnNode) {
return false
}
internal fun isInlineMarker(insn: AbstractInsnNode, name: String?): Boolean {
if (insn.opcode != Opcodes.INVOKESTATIC) return false
return insn.getOpcode() == Opcodes.INVOKESTATIC &&
insn.owner == INLINE_MARKER_CLASS_NAME &&
val methodInsn = insn as MethodInsnNode
return methodInsn.owner == INLINE_MARKER_CLASS_NAME &&
if (name != null)
insn.name == name
methodInsn.name == name
else
insn.name == INLINE_MARKER_BEFORE_METHOD_NAME || insn.name == INLINE_MARKER_AFTER_METHOD_NAME
methodInsn.name == INLINE_MARKER_BEFORE_METHOD_NAME || methodInsn.name == INLINE_MARKER_AFTER_METHOD_NAME
}
internal fun isBeforeInlineMarker(insn: AbstractInsnNode): Boolean {

View File

@@ -5,13 +5,11 @@
package org.jetbrains.kotlin.codegen.inline
import org.jetbrains.kotlin.backend.common.isBuiltInIntercepted
import org.jetbrains.kotlin.backend.common.isBuiltInSuspendCoroutineUninterceptedOrReturn
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.codegen.coroutines.createMethodNodeForCoroutineContext
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
@@ -30,25 +28,22 @@ import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
import org.jetbrains.org.objectweb.asm.commons.Method
import org.jetbrains.org.objectweb.asm.tree.MethodNode
fun generateInlineIntrinsicForIr(languageVersionSettings: LanguageVersionSettings, descriptor: FunctionDescriptor): SMAPAndMethodNode? =
fun generateInlineIntrinsicForIr(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)
descriptor.isBuiltInCoroutineContext() ->
createMethodNodeForCoroutineContext(descriptor)
descriptor.isBuiltInSuspendCoroutineUninterceptedOrReturn() ->
createMethodNodeForSuspendCoroutineUninterceptedOrReturn()
else -> null
}?.let { SMAPAndMethodNode(it, SMAP(listOf())) }
internal fun generateInlineIntrinsic(
languageVersionSettings: LanguageVersionSettings,
descriptor: FunctionDescriptor,
asmMethod: Method,
typeSystem: TypeSystemCommonBackendContext
): SMAPAndMethodNode? {
return generateInlineIntrinsicForIr(languageVersionSettings, descriptor) ?: when {
return generateInlineIntrinsicForIr(descriptor) ?: when {
isSpecialEnumMethod(descriptor) ->
createSpecialEnumMethodBody(descriptor.name.asString(), descriptor.original.typeParameters.single(), typeSystem)
TypeOfChecker.isTypeOf(descriptor) ->

View File

@@ -5,6 +5,7 @@
package org.jetbrains.kotlin.codegen.inline
import org.jetbrains.kotlin.builtins.isSuspendFunctionType
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.resolve.jvm.AsmTypes.*
import org.jetbrains.kotlin.types.TypeSystemCommonBackendContext
@@ -43,9 +44,9 @@ fun <KT : KotlinTypeMarker> TypeSystemCommonBackendContext.generateTypeOf(
val typeParameter = type.typeConstructor().getTypeParameterClassifier()
if (typeParameter != null) {
if (!doesTypeContainTypeParametersWithRecursiveBounds(type)) {
throw UnsupportedOperationException(
"Non-reified type parameters with recursive bounds are not supported yet: ${typeParameter.getName()}"
)
intrinsicsSupport.reportNonReifiedTypeParameterWithRecursiveBoundUnsupported(typeParameter.getName())
v.aconst(null)
return
}
generateNonReifiedTypeParameter(v, typeParameter, intrinsicsSupport)
@@ -89,6 +90,29 @@ fun <KT : KotlinTypeMarker> TypeSystemCommonBackendContext.generateTypeOf(
}
v.invokestatic(REFLECTION, methodName, signature, false)
if (intrinsicsSupport.toKotlinType(type).isSuspendFunctionType) {
intrinsicsSupport.reportSuspendTypeUnsupported()
}
intrinsicsSupport.checkAnnotatedType(type)
if (intrinsicsSupport.state.stableTypeOf) {
if (intrinsicsSupport.isMutableCollectionType(type)) {
v.invokestatic(REFLECTION, "mutableCollectionType", Type.getMethodDescriptor(K_TYPE, K_TYPE), false)
} else if (type.typeConstructor().isNothingConstructor()) {
v.invokestatic(REFLECTION, "nothingType", 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(

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