Compare commits

...

90 Commits

Author SHA1 Message Date
Ilya Gorbunov
0110bff083 Introduce deployRepo parameter to override deploy-repo set by teamcity
Currently it isn't possible to do that from command line.
2017-11-09 20:52:53 +03:00
Sergey Igushkin
84d71446f2 Fix missing sourcesJar & javadocJar in kotlin-annotations-android 2017-11-09 20:20:58 +03:00
Ilya Gorbunov
235f60e56f Fix intellij-community revision JFlex is downloaded from
Because it was removed in master

(cherry picked from commit e801390)
2017-11-09 18:09:53 +03:00
Sergey Igushkin
962cc51c2e Update ChangeLog.md 2017-11-09 14:52:27 +03:00
Ilya Gorbunov
25483ca286 Write deployVersion into build.txt (for 1.1.60) 2017-11-08 17:17:35 +03:00
Simon Ogorodnik
d63b7ade7e Improve diagnosticMissingPackageFragment reporting
Single execution path to report missing package fragment problems

Split failures on PluginDeclarationProviderFactory site by
known reasons to improve exception analysis

(cherry picked from commit 339d06d)
2017-11-07 16:29:05 +03:00
Nikolay Krasko
1a898e1f46 Increase stub version because of change in overload sorting
See commit f197f36e23
2017-11-07 15:57:08 +03:00
Nikolay Krasko
9674dc6279 Don't resort deserialized descriptors based on renderer, preserve proto order
Use only names and types for sorting. Otherwise if deserialized descriptor
is rendered different from origin we might get Psi-Stub mismatch error.

Use the original proto order for declarations with same name and kind.

 #KT-20782 Fixed
 #EA-109887 Fixed
2017-11-07 15:57:07 +03:00
Mikhail Glukhikh
f7906ed7ee Fix problem with mutable map in "simplifiable call chain"
So #KT-20315 Fixed

(cherry picked from commit 45c9be2)
2017-11-01 19:48:13 +03:00
Nikolay Krasko
461ebbc4cd Fix accessing nullable location() method 2017-10-30 20:49:15 +03:00
Dmitry Petrov
c4ceb5653a Fix issues with enum entry self-reference
Given a singleton class 'S' with possibly uninitialized static instance
(enum entry, interface companion object).
Such singleton can be referenced by name, or as an explicit or implicit
'this'.
For a given singleton class 'S' we
either use 'this@S' from context (local or captured),
or 'S' as a static instance.

Local or captured 'this@S' should be used if:
  - we are in the constructor for 'S',
    and corresponding instance is initialized
        by super or delegating constructor call;
  - we are in any other member of 'S' or any of its inner classes.

Otherwise, a static instance should be used.

(cherry picked from commit 28535a5)
2017-10-27 09:40:17 +03:00
Denis Zharkov
a9f3940e47 Fix incorrect UNINITIALIZED_ENUM_COMPANION diagnostic
#KT-20959 Fixed
2017-10-27 09:38:47 +03:00
Alexander Udalov
c12be9b54b Use ServiceLoader instead of IntelliJ extensions for DefaultErrorMessages
#KT-10473 Fixed

(cherry picked from commit 1a8be635b9)
2017-10-26 18:38:51 +02:00
Alexander Udalov
2472d1c1fd Do not use DefaultErrorMessages.Extension as IntelliJ extension in plugins
(cherry picked from commit 1c6dce3674)
2017-10-26 18:38:48 +02:00
Vyacheslav Gerasimov
47fe7aefcb Remove GradleProjectImportProvider and GradleProjectOpenProcessor 2017-10-26 19:11:42 +03:00
Sergey Igushkin
ad975b517e Update 1.1.60 changelog 2017-10-26 17:24:33 +03:00
Ilya Chernikov
31189f8270 Fix "base" jar and "public" jar tasks archive name conflict
fixes KT-20877

(cherry picked from commit caca7c6)
2017-10-25 14:20:46 +02:00
Alexey Tsvetkov
c8c4835d17 Perform non-IC build when JS lib is changed 2017-10-24 16:36:35 +03:00
Mikhail Zarechenskiy
c43fe9b9ff Provide no-arg constructors for common expected annotations in stdlib
This is needed because we treat `expect` classes as not having implicit default constructors (see more in KT-15522, f3344ec)

(cherry picked from commit 1845a87)
2017-10-24 16:35:00 +03:00
Dmitry Petrov
88c952902d Mark operands of POP2 as don't touch in unused expression elimination
Fixes KT-20879.

(cherry picked from commit f23dfdc)
2017-10-24 15:41:00 +03:00
Anton Bannykh
1b6f495014 JPS JS: fix friend path detection in projects imported from Gradle (KT-18963 fixed)
(cherry-picked from commit b2e53644a5)
2017-10-24 15:26:19 +03:00
Sergey Igushkin
3f9a068e5c Advance bootstrap to 1.1.60-eap-30 2017-10-24 15:17:09 +03:00
Alexey Andreev
bdd5310dce JS: several bugfixes in incremental compilation
1. Fix exported packages sometimes being mixed up
2. Fix metadata losing package fragments sometimes
3. Don't serialize empty packages to .meta.js
4. Preserve order of package fragments in .meta.js
5. In IC tests, compare textual representation of metadata rather
   than binary representation
2017-10-24 11:58:50 +03:00
Alexey Andreev
61e570279a Support generation of relative path in JS source maps in JPS builder
See KT-20820
2017-10-24 11:53:23 +03:00
Alexey Andreev
c61034191e JS: fix copying functions with default arguments across interfaces
Copy function to super interface first, then copy from interface
to class. Add interface set to JsClassModel for this purpose.

See KT-20625
2017-10-24 11:53:03 +03:00
Simon Ogorodnik
0bf6a37384 EA-105522, KT-20256: Fix TextRange.<init> "Invalid range specified"
Check when caret inside template, and don't try to create invalid
range then

 EA-105522 fixed
 #KT-20256 fixed

(cherry picked from commit cace662)
2017-10-23 21:39:19 +03:00
Nikolay Krasko
3e1482a869 Use CompilerPathsEx.getOutputPaths for getting the full list of output dirs (KT-20789)
CompilerPathsEx.getOutputPaths isn't using OrderEnumerationHandler extension
so far and works badly when delegating runnners to gradle is enabled.

 #KT-20789 Fixed
2017-10-20 21:24:17 +03:00
Nikolay Krasko
6757212e0f TypeDeclarationProvider should return null for irrelevant symbols
Otherwise other providers won't be checked.
2017-10-20 21:23:57 +03:00
Nikolay Krasko
70f3e1a53e Request path from URI before construction file 2017-10-20 21:23:36 +03:00
Denis Zharkov
cba7c848c2 Fix wrong nullability enhancement for annotated java.lang.Object type
Effectively, this commit drops cached value for j.l.Object type
This cache was introduced when types were immutable, but they
became mutable after starting reading top-level TYPE_USE annotations,
that lead to changing shared JAVA_LANG_OBJECT_CLASSIFIER_TYPE instance

 #KT-20826 Fixed
2017-10-20 19:11:39 +03:00
Anton Bannykh
63fbab77dd JS: add kotlin-test testCompile dependency to JS module generated by multiplatform wizard (KT-20346, KT-20831, KT-20832 fixed)
(cherry-picked from commit e90c914)
2017-10-20 18:46:24 +03:00
Sergey Igushkin
74567aaa43 Add 1.1.60 changelog 2017-10-19 21:12:51 +03:00
Alexey Tsvetkov
caa010f0ff Compile kotlin-android-extensions-runtime for JDK 1.6
(cherry picked from commit 8a3a4df)
2017-10-19 16:24:51 +03:00
Stanislav Erokhin
5f0b6a5fb6 Disable annotation processor for javac by default in whole project
(cherry picked from commit 0a2421d)

(cherry picked from commit 7a50511)
2017-10-19 16:24:04 +03:00
Sergey Igushkin
0341227552 Use runtimeJar configuration instead of default for plugin markers.
(cherry picked from commit d453a2f)

(cherry picked from commit fa2d276)
2017-10-19 16:23:28 +03:00
Ilya Chernikov
14099e8a66 Add compiler proguard rule for keeping ProgressManager used in webdemo
(cherry picked from commit 5284db8)
2017-10-19 14:16:28 +02:00
Sergey Igushkin
480768c841 Fix missing ReflectUtil, call the ctor through reflection manually.
(cherry picked from commit 0a80852)
2017-10-19 14:08:28 +02:00
Sergey Igushkin
82b033b85d Add android-extensions-compiler content to kotlin-android-extensions
(cherry picked from commit e94e62b)
2017-10-19 14:07:22 +02:00
Ilya Chernikov
6c73373f64 Fix dependencies rewriting and gradle integration tests after applying rewriting
(cherry picked from commit 431d47a)
2017-10-19 14:07:05 +02:00
Ilya Chernikov
1596622f60 Use rewriteDeps task on the projects with runtime dependency on embeddable compiler...
which are using shaded dependencies

(cherry picked from commit 050403d)
2017-10-19 14:05:22 +02:00
Ilya Chernikov
49d040886f Move embeddable compiler shading logic to buildSrc, implement rewriteDeps task
the task takes a jar an a shading task (like the one that creates embeddable
compiler) and rewrites jar's dependencies to the shaded ones according the
the shade task.

(cherry picked from commit fb70227)
2017-10-19 14:03:02 +02:00
Ilya Chernikov
8a41561b36 Remove original jar artifact from archives when adding a new one by runtimeJar tasks
(cherry picked from commit 5babf89)
2017-10-19 14:01:48 +02:00
Anton Bannykh
ea33a0aa6c JS: publish to NPM sourcemaps and *.kjsm files
(cherry-picked from commit 6d6ce7c)
2017-10-18 21:18:11 +03:00
Anton Bannykh
1729f175c1 JS: add ant tasks for publishing kotlin-test-js to NPM (KT-19682)
(cherry-picked from commit 2d3929e)
2017-10-18 21:16:42 +03:00
Ilya Gorbunov
83eb6dd000 Enable publishing for kotlin-annotations-android
(cherry picked from commit eaa3b3ccf0)
2017-10-17 21:03:38 +03:00
Ilya Gorbunov
fe60fb4a44 Do not pack build.txt into jars, leave it only in artifact zip bundles
(cherry picked from commit 13d6e96c2f)
2017-10-17 21:02:39 +03:00
Ilya Gorbunov
0c95783829 Remove maven poms that are no longer submodules of the main project
(cherry picked from commit 3bea095618)
2017-10-17 21:02:39 +03:00
Ilya Gorbunov
5b04b84e71 Fork java compiler to ensure forkOptions are used
(cherry picked from commit 341edc3f86)
2017-10-17 21:02:39 +03:00
Ilya Gorbunov
15f9fa7b03 Fix the obsolete form of -Xdump-declarations-to argument
(cherry picked from commit 93efc51)
2017-10-17 21:02:39 +03:00
Alexey Tsvetkov
52093f3fad Fix android extensions maven dependencies
`kotlin-android-extensions-runtime` and `kotlin-android-extensions-compiler`
had `com.google.android:android` as a provided dependency, but
during transition to Kotlin Gradle build the dependency was declared
as `runtime` instead of `compileOnly`.
2017-10-17 18:36:19 +03:00
Denis Zharkov
c3a6cb3ab4 Refine ClassDescriptor::isCommonFinalClass definition
Do not treat annotations as final classes as they are not final in Java

 #KT-20776 Fixed
2017-10-16 16:14:12 +03:00
Yan Zhulanow
ee36a19db5 Disable uninitialized object copying checks for Parcelable writeToParcel() to createFromParcel() 2017-10-13 16:37:57 +03:00
Yan Zhulanow
8e5026e6b1 Minor: Add dependency to android-extensions-runtime to get rid of compile errors in IDE 2017-10-13 16:37:51 +03:00
Yan Zhulanow
31f08c6ba5 Tests: Do not search for android-extensions-runtime in KOTLIN_PATH 2017-10-13 16:37:44 +03:00
Pavel V. Talanov
0a3f4b5be3 Scripts: Accept objects as DependenciesResolver implementations
Fixes DependenciesResolver.NoDependencies causing "missing constructor without parameters" warning
2017-10-12 19:25:07 +03:00
Ilya Chernikov
4e51e04e3c Add stdlib to gradle scripts classpath, since it is not included into compiler anymore
(cherry picked from commit 279126a)
2017-10-12 15:36:39 +02:00
Paul Merlin
5740163c92 Script template provider for settings.gradle.kts files
This commit introduces GradleSettingsKotlinDSLTemplateProvider and
registers it as Kotlin IntelliJ plugin extension.

(cherry picked from commit e911a1e)
2017-10-12 15:36:30 +02:00
Dmitry Petrov
0331627757 Build compiler, plugin & stdlib with constructor call normalization
Required as a workaround for Proguard bug
https://sourceforge.net/p/proguard/bugs/664/

When processing bytecode generated by Kotlin compiler for constructor
call with stack spilling during arguments evaluation, ProGuard performs
an equivalent transformation for the bytecode, but emits invalid stack
frame information.
In JVM 1.6, such invalid stack frames are ignored and re-evaluated by
JVM during bytecode verification.
In JVM 1.8, such invalid stack frames cause VerifyError.
2017-10-12 16:10:55 +03:00
Alexey Andreev
ac85c9d728 Fix Kotlin/JS compiler under JRE9
See KT-20653, KT-20650
2017-10-12 15:02:54 +03:00
Nikolay Krasko
95e8aa6c41 Revert old id for run configurations (KT-20621)
Currently there's no way for smooth IDs migration.

 #KT-20621 Fixed
2017-10-12 14:00:24 +03:00
Leonid Stashevsky
0132a54d22 Rename android-annotations -> kotlin-annotations-android
also rewrite it's buildscript in kts and add to compiler tests dependencies
2017-10-12 11:10:10 +03:00
Alexey Andreev
512c2da560 Enable test that now passes in JS 2017-10-12 11:02:37 +03:00
Alexey Andreev
0eb713920b Fix JS DCE removing reachable functions 2017-10-11 17:42:33 +03:00
Denis Zharkov
67c25aa6ab Add cache for declaration names in StubBasedPackageMemberDeclarationProvider
#KT-20683 Fixed
2017-10-10 18:37:40 +03:00
Denis Zharkov
ca0c2690a9 Optimize ConstraintSystemBuilderImpl::generateNewBound
Do not process the bound if it's just the same
This situation can actually happen in case of adding bound
containing type variable itself
2017-10-10 18:33:39 +03:00
Denis Zharkov
ac8ce070e8 Introduce cache for KotlinBuiltins::builtInClassesByName
There are a lot of places requesting nothing/any/.. instances
and just asking the scopes isn't very effecient:
see org.jetbrains.kotlin.builtins.KotlinBuiltIns#createPackage
having ChainedMemberScope and a `map` call
2017-10-10 18:33:39 +03:00
Denis Zharkov
0eeb47d8ff Do not create redundant temporary trace
It will be commited after use in any case
2017-10-10 18:33:39 +03:00
Denis Zharkov
2ddea32b37 Optimize subtyping for simple cases 2017-10-10 18:33:39 +03:00
Denis Zharkov
e5ae916fe5 Drop effectively unused parameter with default value 2017-10-10 18:33:39 +03:00
Denis Zharkov
f6be73cb3d Get rid of a couple of usages of simpleTypeWithNonTrivialMemberScope
The simple versions of KotlinTypeFactory::simpleType may lead
to smaller number of KotlinType instances
(defaultType from descriptor are used if there are no arguments)
2017-10-10 18:33:39 +03:00
Denis Zharkov
ea142d884f Rename KotlinTypeFactory::simpleType to simpleTypeWithNonTrivialMemberScope
To state it must be used only for limited number of cases
2017-10-10 18:33:39 +03:00
Denis Zharkov
080b4dccc9 Cache virtualFilePath for KtFile
Because of com.intellij.openapi.vfs.local.CoreLocalVirtualFile#getPath
that has a rather slow implementation calling String::replace on each call

At the same time this method gets called very frequently when
recording lookups
2017-10-10 18:33:39 +03:00
Denis Zharkov
dc40c34152 Optimize subtyping for case of objects identity
It may be rather frequent (e.g. in case of types without arguments or
for dispatch receiver parameters)
2017-10-10 18:33:39 +03:00
Denis Zharkov
97d648731a Add explicit fast path in TypeCheckerContext::anySupertype 2017-10-10 18:33:39 +03:00
Denis Zharkov
97b9e1c444 Optimize CandidateResolver::checkReceiver
- Do not calculate smart cast variants unless they're not necessary
- Avoid calling subtyping twice just to know if smart cast is necessary
  (now the needed info is contained in ReceiverSmartCastResult)
2017-10-10 18:33:39 +03:00
Denis Zharkov
71020fb690 Minor. Drop unused method 2017-10-10 18:33:39 +03:00
Denis Zharkov
83bdf55dda Inline TypeCheckerContext::anySupertype
This method is a hot spot, since it's may be called
several times during one isSubtypeOf call and it contains
two lambdas, so it's worth inlining it
2017-10-10 18:33:39 +03:00
Denis Zharkov
6528ced4b5 Use smaller default deque size for BFS over supertypes
The default value (16) seems to be rather big
2017-10-10 18:33:39 +03:00
Denis Zharkov
264107081f Minor. Get rid of redundant var
The lazyness here is redundant since SmartList doesn't make a lot of
harm, but at the same time `var` here leads to another
kotlin/jvm/internal/Ref$ObjectRef instance
2017-10-10 18:33:39 +03:00
Denis Zharkov
0f2ed5e570 Optimize type checking for common cases
- Type equality for simple constructors (no arguments)
- Subtyping on final classes
2017-10-10 18:33:39 +03:00
Denis Zharkov
8a664a0ac2 Minor. Move local functions as a private to class 2017-10-10 18:33:39 +03:00
Denis Zharkov
7cfc3ea46f Fix obviously wrong !is check in type checker 2017-10-10 18:33:39 +03:00
Mikhael Bogdanov
a30d946351 Write script descriptor type to ASM_TYPE slice
#KT-20707 Fixed

(cherry picked from commit a79c2bf)
2017-10-10 17:05:35 +02:00
Vyacheslav Gerasimov
0425afb061 Add name for GradleProjectImportProvider
#KT-20648 Fixed

(cherry picked from commit 62d0e4a)
2017-10-10 14:44:19 +03:00
Alexey Andreev
9ceb9e729a Fix compilation of JS stdlib
1. Don't import intrinsics when compiling stdlib, use declarations
   from current module instead
2. Add constructor with one argument to SourceFilePathResolver,
   to fix bootstrapping issues.
3. Pass correct source roots to compiler when building
   stdlib, since now we pass module root by default,
   while stdlib source roots are outside of module root.
2017-10-10 14:21:32 +03:00
Dmitry Petrov
5cf9937423 Provide configurable constructor call normalization
Three modes:

- 'disable' (default): normalize constructor calls in coroutines only
  (required because uninitialized objects can't be stored in fields),
  don't insert additional code for forced class initialization;

- 'enable': normalize constructor calls,
  don't insert additional code for forced class initialization;

- 'preserve-class-initialization': normalize constructor calls,
  insert additional code for forced class initialization.
2017-10-10 08:52:48 +03:00
Dmitry Petrov
40dfee6d81 Fix self-reference to singleton in initializer
Singleton instance is "initialized" by delegating constructor call,
which is superclass constructor call in case of singletons (because
singletons can't have more than one constructor).

Singleton constructor is effectively split into two stages:
- before a super constructor call;
- after a super constructor call.

Before super constructor call, singleton instance can't be used directly
(see KT-20662), because neither 'this' nor static instance is
initialized yet. However, it can be used in closures, in which case a
static instance should be used (escaping uninitialized this is
prohibited by JVM). Actually using this static instance before it is
initialized (e.g., invoking a method that uses this singleton) will
cause a correct ExceptionInInitializerError.

After a super constructor call, static instance of a singleton may be
not initialized yet (in case of enum entries and interface companion
objects). However, we already have an initialized 'this', which we
should use for singleton references.

 #KT-20651 Fixed
2017-10-10 08:52:43 +03:00
Anton Bannykh
c4d2e0f519 JS: temporarily remove @Before @After annotations from 1.1.50
(cherry-picked from commit 0976a78f6a)
2017-10-09 18:31:59 +03:00
Mikhael Bogdanov
8bef2ec503 Update stdlib jre8 test jvm-target
(cherry picked from commit bd9ac65)
2017-10-09 16:51:12 +02:00
Mikhael Bogdanov
fc0d0f2c48 Update cli module jvm-target
#KT-20671 Fixed

(cherry picked from commit 3c81430)
2017-10-09 16:51:09 +02:00
279 changed files with 3349 additions and 2581 deletions

View File

@@ -3,6 +3,213 @@
<!-- Find: ([^\`/\[])(KT-\d+) -->
<!-- Replace: $1[`$2`](https://youtrack.jetbrains.com/issue/$2) -->
## 1.1.60
### Android
#### New Features
- [`KT-20051`](https://youtrack.jetbrains.com/issue/KT-20051) Quickfixes to support @Parcelize
#### Fixes
- [`KT-19747`](https://youtrack.jetbrains.com/issue/KT-19747) Android extensions + Parcelable: VerifyError in case of RawValue annotation on a type when it's unknown how to parcel it
- [`KT-19899`](https://youtrack.jetbrains.com/issue/KT-19899) Parcelize: Building with ProGuard enabled
- [`KT-19988`](https://youtrack.jetbrains.com/issue/KT-19988) [Android Extensions] inner class LayoutContainer causes NoSuchMethodError
- [`KT-20002`](https://youtrack.jetbrains.com/issue/KT-20002) Parcelize explodes on LongArray
- [`KT-20019`](https://youtrack.jetbrains.com/issue/KT-20019) Parcelize does not propogate flags argument when writing nested Parcelable
- [`KT-20020`](https://youtrack.jetbrains.com/issue/KT-20020) Parcelize does not use primitive array read/write methods on Parcel
- [`KT-20021`](https://youtrack.jetbrains.com/issue/KT-20021) Parcelize does not serialize Parcelable enum as Parcelable
- [`KT-20022`](https://youtrack.jetbrains.com/issue/KT-20022) Parcelize should dispatch directly to java.lang.Enum when writing an enum.
- [`KT-20034`](https://youtrack.jetbrains.com/issue/KT-20034) Application installation failed (INSTALL_FAILED_DEXOPT) in Android 4.3 devices if I use Parcelize
- [`KT-20057`](https://youtrack.jetbrains.com/issue/KT-20057) Parcelize should use specialized write/create methods where available.
- [`KT-20062`](https://youtrack.jetbrains.com/issue/KT-20062) Parceler should allow otherwise un-parcelable property types in enclosing class.
### Compiler
#### Performance Improvements
- [`KT-20462`](https://youtrack.jetbrains.com/issue/KT-20462) Don't create an array copy for '*<array-constructor-fun>(...)'
#### Fixes
- [`KT-14697`](https://youtrack.jetbrains.com/issue/KT-14697) Use-site targeted annotation is not correctly loaded from class file
- [`KT-17680`](https://youtrack.jetbrains.com/issue/KT-17680) Android Studio and multiple tests in single file
- [`KT-19251`](https://youtrack.jetbrains.com/issue/KT-19251) Stack spilling in constructor arguments breaks Quasar
- [`KT-19592`](https://youtrack.jetbrains.com/issue/KT-19592) Apply JSR 305 default nullability qualifiers with to generic type arguments if they're applicable for TYPE_USE
- [`KT-20016`](https://youtrack.jetbrains.com/issue/KT-20016) JSR 305: default nullability qualifiers are ignored in TYPE_USE and PARAMETER positions
- [`KT-20131`](https://youtrack.jetbrains.com/issue/KT-20131) Support @NonNull(when = NEVER) nullability annotation
- [`KT-20158`](https://youtrack.jetbrains.com/issue/KT-20158) Preserve flexibility for Java types annotated with @NonNull(when = UNKNOWN)
- [`KT-20337`](https://youtrack.jetbrains.com/issue/KT-20337) No multifile class facade is generated for files with type aliases only
- [`KT-20387`](https://youtrack.jetbrains.com/issue/KT-20387) Wrong argument generated for accessor call of a protected generic 'operator fun get/set' from base class with primitive type as type parameter
- [`KT-20418`](https://youtrack.jetbrains.com/issue/KT-20418) Wrong code generated for literal long range with mixed integer literal ends
- [`KT-20491`](https://youtrack.jetbrains.com/issue/KT-20491) Incorrect synthetic accessor generated for a generic base class function specialized with primitive type
- [`KT-20651`](https://youtrack.jetbrains.com/issue/KT-20651) "Don't know how to generate outer expression" for enum-values with non-trivial self-closures
- [`KT-20707`](https://youtrack.jetbrains.com/issue/KT-20707) Support when by enum in kotlin scripts
- [`KT-20879`](https://youtrack.jetbrains.com/issue/KT-20879) Compiler problem in when-expressions
### IDE
#### New Features
- [`KT-14175`](https://youtrack.jetbrains.com/issue/KT-14175) Surround with try ... catch (... finally) doesn't work for expressions
- [`KT-15769`](https://youtrack.jetbrains.com/issue/KT-15769) Join lines could "convert to expression body"
- [`KT-19134`](https://youtrack.jetbrains.com/issue/KT-19134) IntelliJ Color Scheme editor - allow changing color of colons and double colons
- [`KT-20308`](https://youtrack.jetbrains.com/issue/KT-20308) New Gradle with Kotlin DSL project wizard
#### Fixes
- [`KT-15932`](https://youtrack.jetbrains.com/issue/KT-15932) Attempt to rename private property finds unrelated usages
- [`KT-18996`](https://youtrack.jetbrains.com/issue/KT-18996) After Kotlin compiler settings change: 'Apply' button doesn't work
- [`KT-19458`](https://youtrack.jetbrains.com/issue/KT-19458) Resolver for 'completion/highlighting in ScriptModuleInfo for build.gradle.kts / JVM' does not know how to resolve LibraryInfo
- [`KT-19474`](https://youtrack.jetbrains.com/issue/KT-19474) Kotlin Gradle Script: highlighting fails on unresolved references
- [`KT-19823`](https://youtrack.jetbrains.com/issue/KT-19823) Kotlin Gradle project import into IntelliJ: import kapt generated classes into classpath
- [`KT-19958`](https://youtrack.jetbrains.com/issue/KT-19958) Android: kotlinOptions from build.gradle are not imported into facet
- [`KT-19972`](https://youtrack.jetbrains.com/issue/KT-19972) AssertionError “Resolver for 'completion/highlighting in ModuleProductionSourceInfo(module=Module: 'kotlin-pure_main') for files dummy.kt for platform JVM' does not know how to resolve SdkInfo“ on copying Kotlin file with kotlin.* imports from other project
- [`KT-20112`](https://youtrack.jetbrains.com/issue/KT-20112) maven dependency type test-jar with scope compile not
- [`KT-20185`](https://youtrack.jetbrains.com/issue/KT-20185) Stub and PSI element type mismatch for "var nullableSuspend: (suspend (P) -> Unit)? = null"
- [`KT-20199`](https://youtrack.jetbrains.com/issue/KT-20199) Cut action is not available during indexing
- [`KT-20331`](https://youtrack.jetbrains.com/issue/KT-20331) Wrong EAP repository
- [`KT-20346`](https://youtrack.jetbrains.com/issue/KT-20346) Can't build tests in common code due to missing org.jetbrains.kotlin:kotlin-test-js testCompile dependency in JS
- [`KT-20419`](https://youtrack.jetbrains.com/issue/KT-20419) Android Studio plugin 1.1.50 show multiple gutter icon for the same item
- [`KT-20519`](https://youtrack.jetbrains.com/issue/KT-20519) Error “Parameter specified as non-null is null: method ModuleGrouperKt.isQualifiedModuleNamesEnabled” on creating Gradle (Kotlin DSL) project from scratch
- [`KT-20550`](https://youtrack.jetbrains.com/issue/KT-20550) Spring: "Navigate to autowired candidates" gutter action is missed (IDEA 2017.3)
- [`KT-20566`](https://youtrack.jetbrains.com/issue/KT-20566) Spring: "Navigate to the spring beans declaration" gutter action for `@ComponentScan` is missed (IDEA 2017.3)
- [`KT-20621`](https://youtrack.jetbrains.com/issue/KT-20621) Provide automatic migration from JetRunConfigurationType to KotlinRunConfigurationType
- [`KT-20648`](https://youtrack.jetbrains.com/issue/KT-20648) Do we need a separate ProjectImportProvider for gradle kotlin dsl projects?
- [`KT-20782`](https://youtrack.jetbrains.com/issue/KT-20782) Non-atomic trees update
- [`KT-20789`](https://youtrack.jetbrains.com/issue/KT-20789) Can't navigate to inline call/inline use site when runner is delegated to Gradle
- [`KT-20843`](https://youtrack.jetbrains.com/issue/KT-20843) Kotlin TypeDeclarationProvider may stop other declarations providers execution
- [`KT-20929`](https://youtrack.jetbrains.com/issue/KT-20929) Import Project from Gradle wizard: the same page is shown twice
### IDE. Completion
- [`KT-16383`](https://youtrack.jetbrains.com/issue/KT-16383) IllegalStateException: Failed to create expression from text: '<init>' on choosing ByteArray from completion list
- [`KT-18458`](https://youtrack.jetbrains.com/issue/KT-18458) Spring: code completion does not suggest bean names inside `@Qualifier` before function parameter
- [`KT-20256`](https://youtrack.jetbrains.com/issue/KT-20256) java.lang.Throwable “Invalid range specified” on editing template inside string literal
### IDE. Inspections and Intentions
#### New Features
- [`KT-14695`](https://youtrack.jetbrains.com/issue/KT-14695) Simplify comparison intention produces meaningless statement for assert()
- [`KT-17204`](https://youtrack.jetbrains.com/issue/KT-17204) Add `Assign to property quickfix`
- [`KT-18220`](https://youtrack.jetbrains.com/issue/KT-18220) Add data modifier to a class quickfix
- [`KT-18742`](https://youtrack.jetbrains.com/issue/KT-18742) Add quick-fix for CANNOT_CHECK_FOR_ERASED
- [`KT-19735`](https://youtrack.jetbrains.com/issue/KT-19735) Add quickfix for type mismatch that converts Sequence/Array/List
- [`KT-20259`](https://youtrack.jetbrains.com/issue/KT-20259) Show warning if arrays are compared by '!='
#### Fixes
- [`KT-10546`](https://youtrack.jetbrains.com/issue/KT-10546) Wrong "Unused property" warning on using inline object syntax
- [`KT-16394`](https://youtrack.jetbrains.com/issue/KT-16394) "Convert reference to lambda" generates wrong code
- [`KT-16808`](https://youtrack.jetbrains.com/issue/KT-16808) Intention "Remove unnecessary parantheses" is erroneously proposed for elvis operator on LHS of `in` operator if RHS of elvis is return with value
- [`KT-17437`](https://youtrack.jetbrains.com/issue/KT-17437) Class highlighted as unused even if Companion methods/fields really used
- [`KT-19377`](https://youtrack.jetbrains.com/issue/KT-19377) Inspections are run for Kotlin Gradle DSL sources
- [`KT-19420`](https://youtrack.jetbrains.com/issue/KT-19420) Kotlin Gradle script editor: suggestion to import required class from stdlib fails with AE: ResolverForProjectImpl.descriptorForModule()
- [`KT-19626`](https://youtrack.jetbrains.com/issue/KT-19626) (Specify type explicitly) Descriptor was not found for VALUE_PARAMETER
- [`KT-19674`](https://youtrack.jetbrains.com/issue/KT-19674) 'Convert property initializer to getter' intention fails on incompilable initializer with AssertionError at SpecifyTypeExplicitlyIntention$Companion.addTypeAnnotationWithTemplate()
- [`KT-19782`](https://youtrack.jetbrains.com/issue/KT-19782) Surround with if else doesn't work for expressions
- [`KT-20010`](https://youtrack.jetbrains.com/issue/KT-20010) 'Replace safe access expression with 'if' expression' IDEA Kotlin plugin intention may failed
- [`KT-20104`](https://youtrack.jetbrains.com/issue/KT-20104) "Recursive property accessor" reports false positive when property reference is used in the assignment
- [`KT-20218`](https://youtrack.jetbrains.com/issue/KT-20218) AE on calling intention “Convert to secondary constructor” for already referred argument
- [`KT-20231`](https://youtrack.jetbrains.com/issue/KT-20231) False positive 'Redundant override' when delegated member hides super type override
- [`KT-20261`](https://youtrack.jetbrains.com/issue/KT-20261) Incorrect "Redundant Unit return type" inspection for Nothing-typed expression
- [`KT-20315`](https://youtrack.jetbrains.com/issue/KT-20315) "call chain on collection type may be simplified" generates code that does not compile
- [`KT-20333`](https://youtrack.jetbrains.com/issue/KT-20333) Assignment can be lifted out of try is applied too broadly
- [`KT-20366`](https://youtrack.jetbrains.com/issue/KT-20366) Code cleanup: some inspections are broken
- [`KT-20369`](https://youtrack.jetbrains.com/issue/KT-20369) Inspection messages with INFORMATION highlight type are shown in Code Inspect
- [`KT-20409`](https://youtrack.jetbrains.com/issue/KT-20409) useless warning "Remove curly braces" for Chinese character
- [`KT-20417`](https://youtrack.jetbrains.com/issue/KT-20417) Converting property getter to block body doesn't insert explicit return type
### IDE. Refactorings
#### Performance Improvements
- [`KT-18823`](https://youtrack.jetbrains.com/issue/KT-18823) Move class to a separate file is very slow in 'kotlin' project
- [`KT-20205`](https://youtrack.jetbrains.com/issue/KT-20205) Invoke MoveKotlinDeclarationsProcessor.findUsages() under progress
#### Fixes
- [`KT-15840`](https://youtrack.jetbrains.com/issue/KT-15840) Introduce type alias: don't change not-nullable type with nullable typealias
- [`KT-17949`](https://youtrack.jetbrains.com/issue/KT-17949) Rename private fun should not search it out of scope
- [`KT-18196`](https://youtrack.jetbrains.com/issue/KT-18196) Refactor / Copy: the copy is formatted
- [`KT-18594`](https://youtrack.jetbrains.com/issue/KT-18594) Refactor / Extract (Functional) Parameter are available for annotation arguments, but fail with AE: "Body element is not found"
- [`KT-19439`](https://youtrack.jetbrains.com/issue/KT-19439) Kotlin introduce parameter causes exception
- [`KT-19909`](https://youtrack.jetbrains.com/issue/KT-19909) copy a kotlin class removes imports and other modifications
- [`KT-19949`](https://youtrack.jetbrains.com/issue/KT-19949) AssertionError „Resolver for 'project source roots and libraries for platform JVM' does not know how to resolve ModuleProductionSourceInfo“ through MoveConflictChecker.getModuleDescriptor() on copying Kotlin file from other project
- [`KT-20092`](https://youtrack.jetbrains.com/issue/KT-20092) Refactor / Copy: copy of .kt file removes all the blank lines and 'hanging' comments
- [`KT-20335`](https://youtrack.jetbrains.com/issue/KT-20335) Refactor → Extract Type Parameter: “AWT events are not allowed inside write action” after processing duplicates
- [`KT-20402`](https://youtrack.jetbrains.com/issue/KT-20402) Throwable “PsiElement(IDENTIFIER) by KotlinInplaceParameterIntroducer” on calling Refactor → Extract Parameter for default values
- [`KT-20403`](https://youtrack.jetbrains.com/issue/KT-20403) AE “Body element is not found” on calling Refactor → Extract Parameter for default values in constructor of class without body
### JavaScript
#### Fixes
- [`KT-8285`](https://youtrack.jetbrains.com/issue/KT-8285) JS: don't generate tmp when only need one component
- [`KT-14549`](https://youtrack.jetbrains.com/issue/KT-14549) JS: Non-local returns from secondary constructors don't work
- [`KT-15294`](https://youtrack.jetbrains.com/issue/KT-15294) JS: parse error in `js()` function
- [`KT-17450`](https://youtrack.jetbrains.com/issue/KT-17450) PlatformDependent members of collections are compiled in JS
- [`KT-18010`](https://youtrack.jetbrains.com/issue/KT-18010) JS: JsName annotation in interfaces can cause runtime exception
- [`KT-18063`](https://youtrack.jetbrains.com/issue/KT-18063) Inlining does not work properly in JS for suspend functions from another module
- [`KT-18548`](https://youtrack.jetbrains.com/issue/KT-18548) JS: wrong string interpolation with generic or Any parameters
- [`KT-19794`](https://youtrack.jetbrains.com/issue/KT-19794) runtime crash with empty object (Javascript)
- [`KT-19818`](https://youtrack.jetbrains.com/issue/KT-19818) JS: generate paths relative to .map file by default (unless "-source-map-prefix" is used)
- [`KT-19906`](https://youtrack.jetbrains.com/issue/KT-19906) JS: rename compiler option "-source-map-source-roots" to avoid misleading since sourcemaps have field called "sourceRoot"
- [`KT-20287`](https://youtrack.jetbrains.com/issue/KT-20287) Functions don't actually return Unit in Kotlin-JS -> unexpected null problems vs JDK version
- [`KT-20451`](https://youtrack.jetbrains.com/issue/KT-20451) KotlinJs - interface function with default parameter, overridden by implementor, can't be found at runtime
- [`KT-20650`](https://youtrack.jetbrains.com/issue/KT-20650) JS: compiler crashes in Java 9 with NoClassDefFoundError
- [`KT-20653`](https://youtrack.jetbrains.com/issue/KT-20653) JS: compiler crashes in Java 9 with TranslationRuntimeException
- [`KT-20820`](https://youtrack.jetbrains.com/issue/KT-20820) JS: IDEA project doesn't generate paths relative to .map
### Libraries
- [`KT-20596`](https://youtrack.jetbrains.com/issue/KT-20596) 'synchronized' does not allow non-local return in Kotlin JS
- [`KT-20600`](https://youtrack.jetbrains.com/issue/KT-20600) Typo in POMs for kotlin-runtime
### Tools
- [`KT-19692`](https://youtrack.jetbrains.com/issue/KT-19692) kotlin-jpa plugin doesn't support @MappedSuperclass annotation
- [`KT-20030`](https://youtrack.jetbrains.com/issue/KT-20030) Parcelize can directly reference writeToParcel and CREATOR for final, non-Parcelize Parcelable types in same compilation unit.
- [`KT-19742`](https://youtrack.jetbrains.com/issue/KT-19742) [Android extensions] Calling clearFindViewByIdCache causes NPE
- [`KT-19749`](https://youtrack.jetbrains.com/issue/KT-19749) Android extensions + Parcelable: NoSuchMethodError on attempt to pack into parcel a serializable object
- [`KT-20026`](https://youtrack.jetbrains.com/issue/KT-20026) Parcelize overrides describeContents despite being already implemented.
- [`KT-20027`](https://youtrack.jetbrains.com/issue/KT-20027) Parcelize uses wrong classloader when reading parcelable type.
- [`KT-20029`](https://youtrack.jetbrains.com/issue/KT-20029) Parcelize should not directly reference parcel methods on types outside compilation unit
- [`KT-20032`](https://youtrack.jetbrains.com/issue/KT-20032) Parcelize does not respect type nullability in case of Parcelize parcelables
### Tools. Gradle
- [`KT-3463`](https://youtrack.jetbrains.com/issue/KT-3463) Gradle plugin ignores kotlin compile options changes
- [`KT-16299`](https://youtrack.jetbrains.com/issue/KT-16299) Gradle build does not recompile annotated classes on changing compiler's plugins configuration
- [`KT-16764`](https://youtrack.jetbrains.com/issue/KT-16764) Kotlin Gradle plugin should replicate task dependencies of Java source directories
- [`KT-17564`](https://youtrack.jetbrains.com/issue/KT-17564) Applying Kotlin's Gradle plugin results in src/main/java being listed twice in sourceSets.main.allSource
- [`KT-17674`](https://youtrack.jetbrains.com/issue/KT-17674) Test code is not compiled incrementally when main is changed
- [`KT-18765`](https://youtrack.jetbrains.com/issue/KT-18765) Move incremental compilation message from Gradle's warning to info logging level
- [`KT-20036`](https://youtrack.jetbrains.com/issue/KT-20036) Gradle tasks up-to-date-ness
### Tools. J2K
- [`KT-19565`](https://youtrack.jetbrains.com/issue/KT-19565) Java code using Iterator#remove converted to red code
- [`KT-19651`](https://youtrack.jetbrains.com/issue/KT-19651) Java class with static-only methods can contain 'protected' members
### Tools. JPS
- [`KT-20082`](https://youtrack.jetbrains.com/issue/KT-20082) Java 9: incremental build reports bogus error for reference to Kotlin source
- [`KT-20671`](https://youtrack.jetbrains.com/issue/KT-20671) Kotlin plugin compiler exception when compiling under JDK9
### Tools. Maven
- [`KT-20064`](https://youtrack.jetbrains.com/issue/KT-20064) Maven + Java 9: compile task warns about module-info in the output path
- [`KT-20400`](https://youtrack.jetbrains.com/issue/KT-20400) Do not output module name, version and related information by default in Maven builds
### Tools. REPL
- [`KT-20167`](https://youtrack.jetbrains.com/issue/KT-20167) JDK 9 `unresolved supertypes: Object` when working with Kotlin Scripting API
### Tools. kapt
- [`KT-17923`](https://youtrack.jetbrains.com/issue/KT-17923) Reference to Dagger generated class is highlighted red
- [`KT-18923`](https://youtrack.jetbrains.com/issue/KT-18923) Kapt: Do not use the Kotlin error message collector to issue errors from kapt
- [`KT-19097`](https://youtrack.jetbrains.com/issue/KT-19097) Request: Decent support of `kapt.kotlin.generated` on Intellij/Android Studio
- [`KT-20877`](https://youtrack.jetbrains.com/issue/KT-20877) Butterknife: UninitializedPropertyAccessException: "lateinit property has not been initialized" for field annotated with `@BindView`.
## 1.1.50
### Android

View File

@@ -44837,6 +44837,19 @@ public final class DebugJsAstProtoBuf {
*/
int getSuperNameId();
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
java.util.List<java.lang.Integer> getInterfaceNameIdList();
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
int getInterfaceNameIdCount();
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
int getInterfaceNameId(int index);
/**
* <code>optional .org.jetbrains.kotlin.serialization.js.ast.GlobalBlock post_declaration_block = 3;</code>
*/
@@ -44925,6 +44938,27 @@ public final class DebugJsAstProtoBuf {
bitField0_ |= 0x00000004;
break;
}
case 32: {
if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) {
interfaceNameId_ = new java.util.ArrayList<java.lang.Integer>();
mutable_bitField0_ |= 0x00000004;
}
interfaceNameId_.add(input.readInt32());
break;
}
case 34: {
int length = input.readRawVarint32();
int limit = input.pushLimit(length);
if (!((mutable_bitField0_ & 0x00000004) == 0x00000004) && input.getBytesUntilLimit() > 0) {
interfaceNameId_ = new java.util.ArrayList<java.lang.Integer>();
mutable_bitField0_ |= 0x00000004;
}
while (input.getBytesUntilLimit() > 0) {
interfaceNameId_.add(input.readInt32());
}
input.popLimit(limit);
break;
}
}
}
} catch (org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException e) {
@@ -44933,6 +44967,9 @@ public final class DebugJsAstProtoBuf {
throw new org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) {
interfaceNameId_ = java.util.Collections.unmodifiableList(interfaceNameId_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
@@ -44995,6 +45032,28 @@ public final class DebugJsAstProtoBuf {
return superNameId_;
}
public static final int INTERFACE_NAME_ID_FIELD_NUMBER = 4;
private java.util.List<java.lang.Integer> interfaceNameId_;
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
public java.util.List<java.lang.Integer>
getInterfaceNameIdList() {
return interfaceNameId_;
}
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
public int getInterfaceNameIdCount() {
return interfaceNameId_.size();
}
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
public int getInterfaceNameId(int index) {
return interfaceNameId_.get(index);
}
public static final int POST_DECLARATION_BLOCK_FIELD_NUMBER = 3;
private org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock postDeclarationBlock_;
/**
@@ -45019,6 +45078,7 @@ public final class DebugJsAstProtoBuf {
private void initFields() {
nameId_ = 0;
superNameId_ = 0;
interfaceNameId_ = java.util.Collections.emptyList();
postDeclarationBlock_ = org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock.getDefaultInstance();
}
private byte memoizedIsInitialized = -1;
@@ -45053,6 +45113,9 @@ public final class DebugJsAstProtoBuf {
if (((bitField0_ & 0x00000004) == 0x00000004)) {
output.writeMessage(3, postDeclarationBlock_);
}
for (int i = 0; i < interfaceNameId_.size(); i++) {
output.writeInt32(4, interfaceNameId_.get(i));
}
getUnknownFields().writeTo(output);
}
@@ -45074,6 +45137,15 @@ public final class DebugJsAstProtoBuf {
size += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeMessageSize(3, postDeclarationBlock_);
}
{
int dataSize = 0;
for (int i = 0; i < interfaceNameId_.size(); i++) {
dataSize += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeInt32SizeNoTag(interfaceNameId_.get(i));
}
size += dataSize;
size += 1 * getInterfaceNameIdList().size();
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
@@ -45196,12 +45268,14 @@ public final class DebugJsAstProtoBuf {
bitField0_ = (bitField0_ & ~0x00000001);
superNameId_ = 0;
bitField0_ = (bitField0_ & ~0x00000002);
interfaceNameId_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000004);
if (postDeclarationBlockBuilder_ == null) {
postDeclarationBlock_ = org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock.getDefaultInstance();
} else {
postDeclarationBlockBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000004);
bitField0_ = (bitField0_ & ~0x00000008);
return this;
}
@@ -45238,7 +45312,12 @@ public final class DebugJsAstProtoBuf {
to_bitField0_ |= 0x00000002;
}
result.superNameId_ = superNameId_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
if (((bitField0_ & 0x00000004) == 0x00000004)) {
interfaceNameId_ = java.util.Collections.unmodifiableList(interfaceNameId_);
bitField0_ = (bitField0_ & ~0x00000004);
}
result.interfaceNameId_ = interfaceNameId_;
if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
to_bitField0_ |= 0x00000004;
}
if (postDeclarationBlockBuilder_ == null) {
@@ -45268,6 +45347,16 @@ public final class DebugJsAstProtoBuf {
if (other.hasSuperNameId()) {
setSuperNameId(other.getSuperNameId());
}
if (!other.interfaceNameId_.isEmpty()) {
if (interfaceNameId_.isEmpty()) {
interfaceNameId_ = other.interfaceNameId_;
bitField0_ = (bitField0_ & ~0x00000004);
} else {
ensureInterfaceNameIdIsMutable();
interfaceNameId_.addAll(other.interfaceNameId_);
}
onChanged();
}
if (other.hasPostDeclarationBlock()) {
mergePostDeclarationBlock(other.getPostDeclarationBlock());
}
@@ -45372,6 +45461,72 @@ public final class DebugJsAstProtoBuf {
return this;
}
private java.util.List<java.lang.Integer> interfaceNameId_ = java.util.Collections.emptyList();
private void ensureInterfaceNameIdIsMutable() {
if (!((bitField0_ & 0x00000004) == 0x00000004)) {
interfaceNameId_ = new java.util.ArrayList<java.lang.Integer>(interfaceNameId_);
bitField0_ |= 0x00000004;
}
}
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
public java.util.List<java.lang.Integer>
getInterfaceNameIdList() {
return java.util.Collections.unmodifiableList(interfaceNameId_);
}
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
public int getInterfaceNameIdCount() {
return interfaceNameId_.size();
}
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
public int getInterfaceNameId(int index) {
return interfaceNameId_.get(index);
}
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
public Builder setInterfaceNameId(
int index, int value) {
ensureInterfaceNameIdIsMutable();
interfaceNameId_.set(index, value);
onChanged();
return this;
}
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
public Builder addInterfaceNameId(int value) {
ensureInterfaceNameIdIsMutable();
interfaceNameId_.add(value);
onChanged();
return this;
}
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
public Builder addAllInterfaceNameId(
java.lang.Iterable<? extends java.lang.Integer> values) {
ensureInterfaceNameIdIsMutable();
org.jetbrains.kotlin.protobuf.AbstractMessageLite.Builder.addAll(
values, interfaceNameId_);
onChanged();
return this;
}
/**
* <code>repeated int32 interface_name_id = 4;</code>
*/
public Builder clearInterfaceNameId() {
interfaceNameId_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
private org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock postDeclarationBlock_ = org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock.getDefaultInstance();
private org.jetbrains.kotlin.protobuf.SingleFieldBuilder<
org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock, org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock.Builder, org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlockOrBuilder> postDeclarationBlockBuilder_;
@@ -45379,7 +45534,7 @@ public final class DebugJsAstProtoBuf {
* <code>optional .org.jetbrains.kotlin.serialization.js.ast.GlobalBlock post_declaration_block = 3;</code>
*/
public boolean hasPostDeclarationBlock() {
return ((bitField0_ & 0x00000004) == 0x00000004);
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>optional .org.jetbrains.kotlin.serialization.js.ast.GlobalBlock post_declaration_block = 3;</code>
@@ -45404,7 +45559,7 @@ public final class DebugJsAstProtoBuf {
} else {
postDeclarationBlockBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
bitField0_ |= 0x00000008;
return this;
}
/**
@@ -45418,7 +45573,7 @@ public final class DebugJsAstProtoBuf {
} else {
postDeclarationBlockBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
bitField0_ |= 0x00000008;
return this;
}
/**
@@ -45426,7 +45581,7 @@ public final class DebugJsAstProtoBuf {
*/
public Builder mergePostDeclarationBlock(org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock value) {
if (postDeclarationBlockBuilder_ == null) {
if (((bitField0_ & 0x00000004) == 0x00000004) &&
if (((bitField0_ & 0x00000008) == 0x00000008) &&
postDeclarationBlock_ != org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock.getDefaultInstance()) {
postDeclarationBlock_ =
org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock.newBuilder(postDeclarationBlock_).mergeFrom(value).buildPartial();
@@ -45437,7 +45592,7 @@ public final class DebugJsAstProtoBuf {
} else {
postDeclarationBlockBuilder_.mergeFrom(value);
}
bitField0_ |= 0x00000004;
bitField0_ |= 0x00000008;
return this;
}
/**
@@ -45450,14 +45605,14 @@ public final class DebugJsAstProtoBuf {
} else {
postDeclarationBlockBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000004);
bitField0_ = (bitField0_ & ~0x00000008);
return this;
}
/**
* <code>optional .org.jetbrains.kotlin.serialization.js.ast.GlobalBlock post_declaration_block = 3;</code>
*/
public org.jetbrains.kotlin.serialization.js.ast.DebugJsAstProtoBuf.GlobalBlock.Builder getPostDeclarationBlockBuilder() {
bitField0_ |= 0x00000004;
bitField0_ |= 0x00000008;
onChanged();
return getPostDeclarationBlockFieldBuilder().getBuilder();
}
@@ -49376,33 +49531,34 @@ public final class DebugJsAstProtoBuf {
"expression\030\002 \002(\01325.org.jetbrains.kotlin." +
"serialization.js.ast.Expression\"3\n\013NameB" +
"inding\022\024\n\014signature_id\030\001 \002(\005\022\016\n\006nameId\030\002" +
" \002(\005\"\214\001\n\nClassModel\022\017\n\007name_id\030\001 \002(\005\022\025\n\r" +
"super_name_id\030\002 \001(\005\022V\n\026post_declaration_" +
"block\030\003 \001(\01326.org.jetbrains.kotlin.seria" +
"lization.js.ast.GlobalBlock\";\n\014InlineMod" +
"ule\022\024\n\014signature_id\030\001 \002(\005\022\025\n\rexpression_" +
"id\030\002 \002(\005\"\034\n\013StringTable\022\r\n\005entry\030\001 \003(\t\"K" +
"\n\tNameTable\022>\n\005entry\030\001 \003(\0132/.org.jetbrai",
"ns.kotlin.serialization.js.ast.Name\"\263\001\n\004" +
"Name\022\021\n\ttemporary\030\001 \002(\010\022\022\n\nidentifier\030\002 " +
"\001(\005\022\025\n\rlocal_name_id\030\003 \001(\005\022\027\n\010imported\030\004" +
" \001(\010:\005false\022T\n\020special_function\030\005 \001(\0162:." +
"org.jetbrains.kotlin.serialization.js.as" +
"t.SpecialFunction\"\346\001\n\005Chunk\022L\n\014string_ta" +
"ble\030\001 \002(\01326.org.jetbrains.kotlin.seriali" +
"zation.js.ast.StringTable\022H\n\nname_table\030" +
"\002 \002(\01324.org.jetbrains.kotlin.serializati" +
"on.js.ast.NameTable\022E\n\010fragment\030\003 \002(\01323.",
"org.jetbrains.kotlin.serialization.js.as" +
"t.Fragment*@\n\013SideEffects\022\021\n\rAFFECTS_STA" +
"TE\020\001\022\024\n\020DEPENDS_ON_STATE\020\002\022\010\n\004PURE\020\003*?\n\016" +
"InlineStrategy\022\017\n\013AS_FUNCTION\020\000\022\014\n\010IN_PL" +
"ACE\020\001\022\016\n\nNOT_INLINE\020\002*\275\001\n\017SpecialFunctio" +
"n\022\032\n\026DEFINE_INLINE_FUNCTION\020\001\022\021\n\rWRAP_FU" +
"NCTION\020\002\022\021\n\rTO_BOXED_CHAR\020\003\022\016\n\nUNBOX_CHA" +
"R\020\004\022\020\n\014SUSPEND_CALL\020\005\022\024\n\020COROUTINE_RESUL" +
"T\020\006\022\030\n\024COROUTINE_CONTROLLER\020\007\022\026\n\022COROUTI" +
"NE_RECEIVER\020\010B\024B\022DebugJsAstProtoBuf"
" \002(\005\"\247\001\n\nClassModel\022\017\n\007name_id\030\001 \002(\005\022\025\n\r" +
"super_name_id\030\002 \001(\005\022\031\n\021interface_name_id" +
"\030\004 \003(\005\022V\n\026post_declaration_block\030\003 \001(\01326" +
".org.jetbrains.kotlin.serialization.js.a" +
"st.GlobalBlock\";\n\014InlineModule\022\024\n\014signat" +
"ure_id\030\001 \002(\005\022\025\n\rexpression_id\030\002 \002(\005\"\034\n\013S" +
"tringTable\022\r\n\005entry\030\001 \003(\t\"K\n\tNameTable\022>",
"\n\005entry\030\001 \003(\0132/.org.jetbrains.kotlin.ser" +
"ialization.js.ast.Name\"\263\001\n\004Name\022\021\n\ttempo" +
"rary\030\001 \002(\010\022\022\n\nidentifier\030\002 \001(\005\022\025\n\rlocal_" +
"name_id\030\003 \001(\005\022\027\n\010imported\030\004 \001(\010:\005false\022T" +
"\n\020special_function\030\005 \001(\0162:.org.jetbrains" +
".kotlin.serialization.js.ast.SpecialFunc" +
"tion\"\346\001\n\005Chunk\022L\n\014string_table\030\001 \002(\01326.o" +
"rg.jetbrains.kotlin.serialization.js.ast" +
".StringTable\022H\n\nname_table\030\002 \002(\01324.org.j" +
"etbrains.kotlin.serialization.js.ast.Nam",
"eTable\022E\n\010fragment\030\003 \002(\01323.org.jetbrains" +
".kotlin.serialization.js.ast.Fragment*@\n" +
"\013SideEffects\022\021\n\rAFFECTS_STATE\020\001\022\024\n\020DEPEN" +
"DS_ON_STATE\020\002\022\010\n\004PURE\020\003*?\n\016InlineStrateg" +
"y\022\017\n\013AS_FUNCTION\020\000\022\014\n\010IN_PLACE\020\001\022\016\n\nNOT_" +
"INLINE\020\002*\275\001\n\017SpecialFunction\022\032\n\026DEFINE_I" +
"NLINE_FUNCTION\020\001\022\021\n\rWRAP_FUNCTION\020\002\022\021\n\rT" +
"O_BOXED_CHAR\020\003\022\016\n\nUNBOX_CHAR\020\004\022\020\n\014SUSPEN" +
"D_CALL\020\005\022\024\n\020COROUTINE_RESULT\020\006\022\030\n\024COROUT" +
"INE_CONTROLLER\020\007\022\026\n\022COROUTINE_RECEIVER\020\010",
"B\024B\022DebugJsAstProtoBuf"
};
org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
@@ -49715,7 +49871,7 @@ public final class DebugJsAstProtoBuf {
internal_static_org_jetbrains_kotlin_serialization_js_ast_ClassModel_fieldAccessorTable = new
org.jetbrains.kotlin.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_org_jetbrains_kotlin_serialization_js_ast_ClassModel_descriptor,
new java.lang.String[] { "NameId", "SuperNameId", "PostDeclarationBlock", });
new java.lang.String[] { "NameId", "SuperNameId", "InterfaceNameId", "PostDeclarationBlock", });
internal_static_org_jetbrains_kotlin_serialization_js_ast_InlineModule_descriptor =
getDescriptor().getMessageTypes().get(50);
internal_static_org_jetbrains_kotlin_serialization_js_ast_InlineModule_fieldAccessorTable = new

View File

@@ -8,7 +8,7 @@ import org.jetbrains.kotlin.gradle.tasks.Kotlin2JsCompile
buildscript {
extra["defaultSnapshotVersion"] = "1.1-SNAPSHOT"
kotlinBootstrapFrom(BootstrapOption.BintrayDev("1.1.60-dev-277"))
kotlinBootstrapFrom(BootstrapOption.BintrayDev("1.1.60-eap-30"))
val repos = listOfNotNull(
bootstrapKotlinRepo,
@@ -238,7 +238,7 @@ allprojects {
kotlinOptions {
languageVersion = kotlinLanguageVersion
apiVersion = kotlinLanguageVersion
freeCompilerArgs = listOf("-Xallow-kotlin-package")
freeCompilerArgs = listOf("-Xallow-kotlin-package", "-Xnormalize-constructor-calls=enable")
}
}
@@ -460,7 +460,9 @@ fun jdkPath(version: String): String = jdkPathIfFound(version)
fun Project.configureJvmProject(javaHome: String, javaVersion: String) {
tasks.withType<JavaCompile> {
options.isFork = true
options.forkOptions.javaHome = file(javaHome)
options.compilerArgs.add("-proc:none")
}
tasks.withType<KotlinCompile> {

View File

@@ -2,6 +2,7 @@
buildscript {
val buildSrcKotlinVersion: String by extra(findProperty("buildSrc.kotlin.version")?.toString() ?: embeddedKotlinVersion)
extra["buildSrcKotlinRepo"] = findProperty("buildSrc.kotlin.repo")
extra["versions.shadow"] = "2.0.1"
repositories {
extra["buildSrcKotlinRepo"]?.let {
@@ -33,6 +34,7 @@ repositories {
maven { setUrl(it) }
}
// maven { setUrl("https://repo.gradle.org/gradle/libs-releases-local") }
jcenter()
}
dependencies {
@@ -40,6 +42,7 @@ dependencies {
// compile("net.rubygrapefruit:native-platform:0.14")
// TODO: adding the dep to the plugin breaks the build unexpectedly, resolve and uncomment
// compile("org.jetbrains.kotlin:kotlin-gradle-plugin:${rootProject.extra["bootstrap_kotlin_version"]}")
compile("com.github.jengelman.gradle.plugins:shadow:${property("versions.shadow")}")
}
samWithReceiver {

View File

@@ -1,14 +1,12 @@
@file:Suppress("unused") // usages in build scripts are not tracked properly
import org.gradle.api.*
import org.gradle.api.artifacts.ConfigurablePublishArtifact
import org.gradle.api.artifacts.*
import org.gradle.api.tasks.*
import org.gradle.kotlin.dsl.*
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.ConfigurationContainer
import org.gradle.api.artifacts.Dependency
import org.gradle.api.file.DuplicatesStrategy
import org.gradle.api.file.FileCollection
import org.gradle.api.internal.artifacts.publish.ArchivePublishArtifact
import org.gradle.api.plugins.BasePluginConvention
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.javadoc.Javadoc
@@ -61,18 +59,13 @@ fun<T> Project.runtimeJarArtifactBy(task: Task, artifactRef: T, body: Configurab
addArtifact("runtimeJar", task, artifactRef, body)
}
fun Project.buildVersion(): Dependency {
val cfg = configurations.create("build-version")
return dependencies.add(cfg.name, dependencies.project(":prepare:build.version", configuration = "buildVersion"))
}
fun<T: Jar> Project.runtimeJar(task: T, body: T.() -> Unit = {}): T {
val buildVersionCfg = configurations.create("buildVersion")
dependencies.add(buildVersionCfg.name, dependencies.project(":prepare:build.version", configuration = "buildVersion"))
extra["runtimeJarTask"] = task
tasks.findByName("jar")?.let { defaultJarTask ->
configurations.getOrCreate("archives").artifacts.removeAll { (it as? ArchivePublishArtifact)?.archiveTask?.let { it == defaultJarTask } ?: false }
}
return task.apply {
setupPublicJar()
from(buildVersionCfg) { into("META-INF") }
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
body()
project.runtimeJarArtifactBy(this, this)
@@ -139,7 +132,7 @@ fun Project.ideaPlugin(subdir: String = "lib", body: AbstractCopyTask.() -> Unit
task("idea-plugin") {
dependsOn(pluginTask)
}
}
return pluginTask
}

View File

@@ -0,0 +1,130 @@
@file:Suppress("unused") // usages in build scripts are not tracked properly
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.file.DuplicatesStrategy
import org.gradle.api.tasks.bundling.Zip
import org.gradle.jvm.tasks.Jar
import org.gradle.kotlin.dsl.task
import org.gradle.kotlin.dsl.*
val kotlinEmbeddableRootPackage = "org.jetbrains.kotlin"
val packagesToRelocate =
listOf( "com.intellij",
"com.google",
"com.sampullara",
"org.apache",
"org.jdom",
"org.picocontainer",
"jline",
"gnu",
"org.fusesource")
// The shaded compiler "dummy" is used to rewrite dependencies in projects that are used with the embeddable compiler
// on the runtime and use some shaded dependencies from the compiler
// To speed-up rewriting process we want to have this dummy as small as possible.
// But due to the shadow plugin bug (https://github.com/johnrengelman/shadow/issues/262) it is not possible to use
// packagesToRelocate list to for the include list. Therefore the exclude list has to be created.
val packagesToExcludeFromDummy =
listOf("org/jetbrains/kotlin/**",
"org/intellij/lang/annotations/**",
"org/jetbrains/jps/**",
"META-INF/**",
"com/sun/jna/**",
"com/thoughtworks/xstream/**",
"javaslang/**",
"*.proto",
"messages/**",
"net/sf/cglib/**",
"one/util/streamex/**",
"org/iq80/snappy/**",
"org/jline/**",
"org/json/**",
"org/xmlpull/**",
"*.txt")
private fun ShadowJar.configureEmbeddableCompilerRelocation(withJavaxInject: Boolean = true) {
relocate("com.google.protobuf", "org.jetbrains.kotlin.protobuf")
packagesToRelocate.forEach {
relocate(it, "$kotlinEmbeddableRootPackage.$it")
}
if (withJavaxInject) {
relocate("javax.inject", "$kotlinEmbeddableRootPackage.javax.inject")
}
relocate("org.fusesource", "$kotlinEmbeddableRootPackage.org.fusesource") {
// TODO: remove "it." after #KT-12848 get addressed
exclude("org.fusesource.jansi.internal.CLibrary")
}
}
private fun Project.compilerShadowJar(taskName: String, body: ShadowJar.() -> Unit): Jar {
val compilerJar = configurations.getOrCreate("compilerJar")
dependencies.add(compilerJar.name, dependencies.project(":kotlin-compiler", configuration = "runtimeJar"))
return task<ShadowJar>(taskName) {
destinationDir = File(buildDir, "libs")
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(compilerJar)
body()
}
}
fun Project.embeddableCompiler(taskName: String = "embeddable", body: ShadowJar.() -> Unit = {}): Jar =
compilerShadowJar(taskName) {
configureEmbeddableCompilerRelocation()
body()
}
fun Project.compilerDummyForDependenciesRewriting(taskName: String = "compilerDummy", body: ShadowJar.() -> Unit = {}): Jar =
compilerShadowJar(taskName) {
exclude(packagesToExcludeFromDummy)
body()
}
const val COMPILER_DUMMY_JAR_CONFIGURATION_NAME = "compilerDummyJar"
fun Project.compilerDummyJar(task: Jar, body: Jar.() -> Unit = {}) {
task.body()
addArtifact(COMPILER_DUMMY_JAR_CONFIGURATION_NAME, task, task)
}
fun Project.embeddableCompilerDummyForDependenciesRewriting(taskName: String = "embeddable", body: Jar.() -> Unit = {}): Jar {
val compilerDummyJar = configurations.getOrCreate("compilerDummyJar")
dependencies.add(compilerDummyJar.name,
dependencies.project(":kotlin-compiler-embeddable", configuration = COMPILER_DUMMY_JAR_CONFIGURATION_NAME))
return task<ShadowJar>(taskName) {
destinationDir = File(buildDir, "libs")
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(compilerDummyJar)
configureEmbeddableCompilerRelocation(withJavaxInject = false)
body()
}
}
fun Project.rewriteDepsToShadedJar(originalJarTask: Jar, shadowJarTask: Zip, body: Jar.() -> Unit = {}): Jar {
val originalFiles by lazy {
val jarContents = zipTree(originalJarTask.outputs.files.singleFile).files
val basePath = jarContents.find { it.name == "MANIFEST.MF" }?.parentFile?.parentFile ?: throw GradleException("cannot determine the jar root dir")
jarContents.map { it.relativeTo(basePath).path }.toSet()
}
return task<Jar>("rewrittenDepsJar") {
originalJarTask.apply {
classifier = "original"
}
shadowJarTask.apply {
dependsOn(originalJarTask)
from(originalJarTask)// { include("**") }
classifier = "shadow"
}
dependsOn(shadowJarTask)
from(project.zipTree(shadowJarTask.outputs.files.singleFile)) { include { originalFiles.any { originalFile -> it.file.canonicalPath.endsWith(originalFile) } } }
body()
}
}
fun Project.rewriteDepsToShadedCompiler(originalJarTask: Jar, body: Jar.() -> Unit = {}): Jar =
rewriteDepsToShadedJar(originalJarTask, embeddableCompilerDummyForDependenciesRewriting(), body)

View File

@@ -24,7 +24,6 @@ dependencies {
compileOnly(project(":plugins:android-extensions-compiler"))
compile(project(":kotlin-test:kotlin-test-jvm"))
compile(project(":compiler:tests-common-jvm6"))
compile(project(":android-annotations"))
compile(commonDep("junit:junit"))
compile(ideaSdkCoreDeps("intellij-core"))
compile(ideaSdkDeps("openapi", "idea", "idea_rt"))

View File

@@ -1736,7 +1736,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
if (descriptor instanceof ClassDescriptor) {
ClassDescriptor classDescriptor = (ClassDescriptor) descriptor;
if (isPossiblyUninitializedSingleton(classDescriptor) && isInsideSingleton(classDescriptor)) {
if (shouldGenerateSingletonAsThisOrOuterFromContext(classDescriptor)) {
return generateThisOrOuterFromContext(classDescriptor, false, false);
}
if (isObject(classDescriptor)) {
@@ -1759,6 +1759,52 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
throw new UnsupportedOperationException("don't know how to generate reference " + descriptor);
}
private boolean shouldGenerateSingletonAsThisOrOuterFromContext(ClassDescriptor classDescriptor) {
if (!isPossiblyUninitializedSingleton(classDescriptor)) return false;
if (!isInsideSingleton(classDescriptor)) return false;
// We are inside a singleton class 'S' with possibly uninitialized static instance
// (enum entry, interface companion object).
// Such singleton can be referenced by name, or as an explicit or implicit 'this'.
// For a given singleton class 'S' we either use 'this@S' from context (local or captured),
// or 'S' as a static instance.
//
// Local or captured 'this@S' should be used if:
// - we are in the constructor for 'S',
// and corresponding instance is initialized by super or delegating constructor call;
// - we are in any other member of 'S' or any of its inner classes.
//
// Otherwise, a static instance should be used.
CodegenContext context = this.context;
while (context != null) {
if (context instanceof ConstructorContext) {
ConstructorContext constructorContext = (ConstructorContext) context;
ClassDescriptor constructedClass = constructorContext.getConstructorDescriptor().getConstructedClass();
if (constructedClass == classDescriptor) {
return constructorContext.isThisInitialized();
}
}
else if (context instanceof ClassContext) {
ClassDescriptor contextClass = ((ClassContext) context).getContextDescriptor();
if (isInInnerClassesChainFor(contextClass, classDescriptor)) {
return true;
}
}
context = context.getParentContext();
}
return false;
}
private static boolean isInInnerClassesChainFor(ClassDescriptor innerClass, ClassDescriptor outerClass) {
if (innerClass == outerClass) return true;
if (!innerClass.isInner()) return false;
DeclarationDescriptor containingDeclaration = innerClass.getContainingDeclaration();
if (!(containingDeclaration instanceof ClassDescriptor)) return false;
return isInInnerClassesChainFor((ClassDescriptor) containingDeclaration, outerClass);
}
@Nullable
private StackValue applyIntrinsic(
DeclarationDescriptor descriptor,
@@ -2601,7 +2647,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
!CodegenUtilKt.isJvmStaticInObjectOrClass(context.getFunctionDescriptor())) {
return StackValue.local(0, typeMapper.mapType(calleeContainingClass));
}
else if (CodegenUtilKt.isPossiblyUninitializedSingleton(calleeContainingClass) && isInsideSingleton(calleeContainingClass)) {
else if (shouldGenerateSingletonAsThisOrOuterFromContext(calleeContainingClass)) {
return generateThisOrOuterFromContext(calleeContainingClass, isSuper, forceOuter);
}
else if (isEnumEntry(calleeContainingClass)) {

View File

@@ -137,7 +137,8 @@ public class FunctionCodegen {
state,
CoroutineCodegenUtilKt.<FunctionDescriptor>unwrapInitialDescriptorForSuspendFunction(functionDescriptor),
function,
v.getThisName()
v.getThisName(),
state.getConstructorCallNormalizationMode()
);
}
else {

View File

@@ -1382,10 +1382,28 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
@NotNull ClassConstructorDescriptor constructorDescriptor,
@Nullable ResolvedCall<ConstructorDescriptor> delegationConstructorCall
) {
MethodContext codegenContext = codegen.context;
assert codegenContext instanceof ConstructorContext :
"Constructor context expected: " + codegenContext;
assert !((ConstructorContext) codegenContext).isThisInitialized() :
"Delegating constructor call is already generated for " + ((ConstructorContext) codegenContext).getConstructorDescriptor();
if (delegationConstructorCall == null) {
genSimpleSuperCall(iv);
return;
}
else {
generateDelegationConstructorCall(iv, codegen, constructorDescriptor, delegationConstructorCall);
}
((ConstructorContext) codegenContext).setThisInitialized(true);
}
private void generateDelegationConstructorCall(
@NotNull InstructionAdapter iv,
@NotNull ExpressionCodegen codegen,
@NotNull ClassConstructorDescriptor constructorDescriptor,
@NotNull ResolvedCall<ConstructorDescriptor> delegationConstructorCall
) {
iv.load(0, OBJECT_TYPE);
ConstructorDescriptor delegateConstructor = SamCodegenUtil.resolveSamAdapter(codegen.getConstructorDescriptor(delegationConstructorCall));

View File

@@ -193,8 +193,15 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
@Override
public void visitScript(@NotNull KtScript script) {
classStack.push(bindingContext.get(SCRIPT, script));
nameStack.push(AsmUtil.internalNameByFqNameWithoutInnerClasses(script.getFqName()));
ClassDescriptor scriptDescriptor = bindingContext.get(SCRIPT, script);
// working around a problem with shallow analysis
if (scriptDescriptor == null) return;
String scriptInternalName = AsmUtil.internalNameByFqNameWithoutInnerClasses(script.getFqName());
recordClosure(scriptDescriptor, scriptInternalName);
classStack.push(scriptDescriptor);
nameStack.push(scriptInternalName);
script.acceptChildren(this);
nameStack.pop();
classStack.pop();

View File

@@ -27,6 +27,7 @@ import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.OBJECT_TYPE;
public class ConstructorContext extends MethodContext {
private static final StackValue LOCAL_1 = StackValue.local(1, OBJECT_TYPE);
private boolean thisInitialized = false;
public ConstructorContext(
@NotNull ConstructorDescriptor contextDescriptor,
@@ -46,6 +47,18 @@ public class ConstructorContext extends MethodContext {
return stackValue;
}
public ConstructorDescriptor getConstructorDescriptor() {
return (ConstructorDescriptor) getContextDescriptor();
}
public boolean isThisInitialized() {
return thisInitialized;
}
public void setThisInitialized(boolean thisInitialized) {
this.thisInitialized = thisInitialized;
}
@Override
public String toString() {
return "Constructor: " + getContextDescriptor();

View File

@@ -145,6 +145,8 @@ class CoroutineCodegenForLambda private constructor(
) {
private val builtIns = funDescriptor.builtIns
private val constructorCallNormalizationMode = outerExpressionCodegen.state.constructorCallNormalizationMode
private lateinit var constructorToUseFromInvoke: Method
private val createCoroutineDescriptor =
@@ -313,6 +315,7 @@ class CoroutineCodegenForLambda private constructor(
mv, access, name, desc, null, null,
obtainClassBuilderForCoroutineState = { v },
element = element,
shouldPreserveClassInitialization = constructorCallNormalizationMode.shouldPreserveClassInitialization,
containingClassInternalName = v.thisName,
isForNamedFunction = false
)

View File

@@ -54,6 +54,7 @@ class CoroutineTransformerMethodVisitor(
private val containingClassInternalName: String,
obtainClassBuilderForCoroutineState: () -> ClassBuilder,
private val isForNamedFunction: Boolean,
private val shouldPreserveClassInitialization: Boolean,
private val element: KtElement,
// It's only matters for named functions, may differ from '!isStatic(access)' in case of DefaultImpls
private val needDispatchReceiver: Boolean = false,
@@ -99,7 +100,7 @@ class CoroutineTransformerMethodVisitor(
// If we don't do this, then relevant frames will not be analyzed, that is unexpected from point of view of next steps (e.g. variable spilling)
removeUnreachableSuspensionPointsAndExitPoints(methodNode, suspensionPoints)
processUninitializedStores(methodNode)
UninitializedStoresProcessor(methodNode, shouldPreserveClassInitialization).run()
spillVariables(suspensionPoints, methodNode)

View File

@@ -20,6 +20,7 @@ import org.jetbrains.kotlin.codegen.ExpressionCodegen
import org.jetbrains.kotlin.codegen.FunctionGenerationStrategy
import org.jetbrains.kotlin.codegen.binding.CodegenBinding
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.config.JVMConstructorCallNormalizationMode
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.psi.KtFunction
@@ -34,7 +35,8 @@ class SuspendFunctionGenerationStrategy(
state: GenerationState,
private val originalSuspendDescriptor: FunctionDescriptor,
private val declaration: KtFunction,
private val containingClassInternalName: String
private val containingClassInternalName: String,
private val constructorCallNormalizationMode: JVMConstructorCallNormalizationMode
) : FunctionGenerationStrategy.CodegenBased(state) {
private lateinit var transformer: CoroutineTransformerMethodVisitor
@@ -59,6 +61,7 @@ class SuspendFunctionGenerationStrategy(
mv, access, name, desc, null, null, containingClassInternalName, this::classBuilderForCoroutineState,
isForNamedFunction = true,
element = declaration,
shouldPreserveClassInitialization = constructorCallNormalizationMode.shouldPreserveClassInitialization,
needDispatchReceiver = originalSuspendDescriptor.dispatchReceiverParameter != null,
internalNameForDispatchReceiver = containingClassInternalNameOrNull()
).also {

View File

@@ -71,11 +71,15 @@ import org.jetbrains.org.objectweb.asm.tree.analysis.Interpreter
* - generate NEW/DUP
* - restore constructor arguments
*/
internal fun processUninitializedStores(methodNode: MethodNode) {
UninitializedStoresProcessor(methodNode).run()
}
class UninitializedStoresProcessor(
private val methodNode: MethodNode,
private val shouldPreserveClassInitialization: Boolean
) {
companion object {
val AVOID_UNINITIALIZED_OBJECT_COPYING_CHECK_ANNOTATION_DESCRIPTOR =
"Lkotlin/internal/annotations/AvoidUninitializedObjectCopyingCheck;"
}
class UninitializedStoresProcessor(private val methodNode: MethodNode) {
// <init> method is "special", because it will invoke <init> from this class or from a base class for #0
//
// <clinit> method is "special", because <clinit> for singleton objects is generated as:
@@ -84,7 +88,11 @@ class UninitializedStoresProcessor(private val methodNode: MethodNode) {
// and the newly created value is dropped.
private val isInSpecialMethod = methodNode.name == "<init>" || methodNode.name == "<clinit>"
private val shouldCheckUninitializedObjectCopy = !methodNode.invisibleAnnotations.orEmpty()
.any { it.desc == AVOID_UNINITIALIZED_OBJECT_COPYING_CHECK_ANNOTATION_DESCRIPTOR }
fun run() {
if (!shouldCheckUninitializedObjectCopy) return
val interpreter = UninitializedNewValueMarkerInterpreter(methodNode.instructions)
val frames = CustomFramesMethodAnalyzer(
@@ -108,21 +116,21 @@ class UninitializedStoresProcessor(private val methodNode: MethodNode) {
methodNode.instructions.run {
removeAll(removableUsages)
// Replace 'NEW C' instruction with "manual" initialization of class 'C':
// LDC [typeName for C]
// INVOKESTATIC java/lang/Class.forName (Ljava/lang/String;)Ljava/lang/Class;
// 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
)
)
set(newInsn, InsnNode(Opcodes.POP))
if (shouldPreserveClassInitialization) {
// Replace 'NEW C' instruction with "manual" initialization of class 'C':
// LDC [typeName for C]
// INVOKESTATIC java/lang/Class.forName (Ljava/lang/String;)Ljava/lang/Class;
// 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
))
set(newInsn, InsnNode(Opcodes.POP))
}
else {
remove(newInsn)
}
}
val indexOfConstructorArgumentFromTopOfStack = Type.getArgumentTypes((insn as MethodInsnNode).desc).size
@@ -175,7 +183,7 @@ class UninitializedStoresProcessor(private val methodNode: MethodNode) {
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)
if (isInSpecialMethod || !shouldCheckUninitializedObjectCopy)
return null
else
error("Expected value generated with NEW")

View File

@@ -20,16 +20,23 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.codegen.ClassBuilder;
import org.jetbrains.kotlin.codegen.DelegatingClassBuilder;
import org.jetbrains.kotlin.config.JVMConstructorCallNormalizationMode;
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin;
import org.jetbrains.org.objectweb.asm.MethodVisitor;
public class OptimizationClassBuilder extends DelegatingClassBuilder {
private final ClassBuilder delegate;
private final boolean disableOptimization;
private final JVMConstructorCallNormalizationMode constructorCallNormalizationMode;
public OptimizationClassBuilder(@NotNull ClassBuilder delegate, boolean disableOptimization) {
public OptimizationClassBuilder(
@NotNull ClassBuilder delegate,
boolean disableOptimization,
JVMConstructorCallNormalizationMode constructorCallNormalizationMode
) {
this.delegate = delegate;
this.disableOptimization = disableOptimization;
this.constructorCallNormalizationMode = constructorCallNormalizationMode;
}
@NotNull
@@ -50,7 +57,7 @@ public class OptimizationClassBuilder extends DelegatingClassBuilder {
) {
return new OptimizationMethodVisitor(
super.newMethod(origin, access, name, desc, signature, exceptions),
disableOptimization,
disableOptimization, constructorCallNormalizationMode,
access, name, desc, signature, exceptions
);
}

View File

@@ -19,19 +19,28 @@ package org.jetbrains.kotlin.codegen.optimization;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.codegen.ClassBuilderFactory;
import org.jetbrains.kotlin.codegen.DelegatingClassBuilderFactory;
import org.jetbrains.kotlin.config.JVMConstructorCallNormalizationMode;
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin;
public class OptimizationClassBuilderFactory extends DelegatingClassBuilderFactory {
private final boolean disableOptimization;
private final JVMConstructorCallNormalizationMode constructorCallNormalizationMode;
public OptimizationClassBuilderFactory(ClassBuilderFactory delegate, boolean disableOptimization) {
public OptimizationClassBuilderFactory(
ClassBuilderFactory delegate,
boolean disableOptimization,
JVMConstructorCallNormalizationMode constructorCallNormalizationMode
) {
super(delegate);
this.disableOptimization = disableOptimization;
this.constructorCallNormalizationMode = constructorCallNormalizationMode;
}
@NotNull
@Override
public OptimizationClassBuilder newClassBuilder(@NotNull JvmDeclarationOrigin origin) {
return new OptimizationClassBuilder(getDelegate().newClassBuilder(origin), disableOptimization);
return new OptimizationClassBuilder(
getDelegate().newClassBuilder(origin), disableOptimization, constructorCallNormalizationMode
);
}
}

View File

@@ -23,23 +23,31 @@ import org.jetbrains.kotlin.codegen.optimization.boxing.StackPeepholeOptimizatio
import org.jetbrains.kotlin.codegen.optimization.common.prepareForEmitting
import org.jetbrains.kotlin.codegen.optimization.nullCheck.RedundantNullCheckMethodTransformer
import org.jetbrains.kotlin.codegen.optimization.transformer.CompositeMethodTransformer
import org.jetbrains.kotlin.config.JVMConstructorCallNormalizationMode
import org.jetbrains.org.objectweb.asm.MethodVisitor
import org.jetbrains.org.objectweb.asm.tree.MethodNode
class OptimizationMethodVisitor(
delegate: MethodVisitor,
private val disableOptimization: Boolean,
private val constructorCallNormalizationMode: JVMConstructorCallNormalizationMode,
access: Int,
name: String,
desc: String,
signature: String?,
exceptions: Array<String>?
) : TransformationMethodVisitor(delegate, access, name, desc, signature, exceptions) {
private val constructorCallNormalizationTransformer =
UninitializedStoresMethodTransformer(constructorCallNormalizationMode)
override fun performTransformations(methodNode: MethodNode) {
normalizationMethodTransformer.transform("fake", methodNode)
constructorCallNormalizationTransformer.transform("fake", methodNode)
if (canBeOptimized(methodNode) && !disableOptimization) {
optimizationTransformer.transform("fake", methodNode)
}
methodNode.prepareForEmitting()
}
@@ -48,7 +56,6 @@ class OptimizationMethodVisitor(
val normalizationMethodTransformer = CompositeMethodTransformer(
FixStackWithLabelNormalizationMethodTransformer(),
UninitializedStoresMethodTransformer(),
MethodVerifier("AFTER mandatory stack transformations")
)

View File

@@ -18,10 +18,17 @@ package org.jetbrains.kotlin.codegen.optimization
import org.jetbrains.kotlin.codegen.coroutines.UninitializedStoresProcessor
import org.jetbrains.kotlin.codegen.optimization.transformer.MethodTransformer
import org.jetbrains.kotlin.config.JVMConstructorCallNormalizationMode
import org.jetbrains.org.objectweb.asm.tree.MethodNode
class UninitializedStoresMethodTransformer : MethodTransformer() {
class UninitializedStoresMethodTransformer(
private val mode: JVMConstructorCallNormalizationMode
) : MethodTransformer() {
override fun transform(internalClassName: String, methodNode: MethodNode) {
UninitializedStoresProcessor(methodNode).run()
if (mode.isEnabled) {
UninitializedStoresProcessor(methodNode, mode.shouldPreserveClassInitialization).run()
}
}
}

View File

@@ -79,18 +79,22 @@ class PopBackwardPropagationTransformer : MethodTransformer() {
private fun analyzeMethodBody(): Array<out Frame<SourceValue>?> {
val frames = Analyzer<SourceValue>(HazardsTrackingInterpreter()).analyze("fake", methodNode)
postprocessDupNxM(frames)
postprocessStackHazards(frames)
return frames
}
private fun postprocessDupNxM(frames: Array<out Frame<SourceValue>?>) {
private fun postprocessStackHazards(frames: Array<out Frame<SourceValue>?>) {
val insns = methodNode.instructions.toArray()
for (i in frames.indices) {
val frame = frames[i] ?: continue
val insn = insns[i]
when (insn.opcode) {
Opcodes.POP2 -> {
val top2 = frame.peekWords(2) ?: throwIncorrectBytecode(insn, frame)
top2.forEach { it.insns.markAsDontTouch() }
}
Opcodes.DUP_X1 -> {
val top2 = frame.peekWords(1, 1) ?: throwIncorrectBytecode(insn, frame)
top2.forEach { it.insns.markAsDontTouch() }

View File

@@ -181,10 +181,15 @@ class GenerationState @JvmOverloads constructor(
val shouldInlineConstVals = languageVersionSettings.supportsFeature(LanguageFeature.InlineConstVals)
val constructorCallNormalizationMode = configuration.get(JVMConfigurationKeys.CONSTRUCTOR_CALL_NORMALIZATION_MODE,
JVMConstructorCallNormalizationMode.DEFAULT)
init {
val disableOptimization = configuration.get(JVMConfigurationKeys.DISABLE_OPTIMIZATION, false)
this.interceptedBuilderFactory = builderFactory
.wrapWith(
{ OptimizationClassBuilderFactory(it, configuration.get(JVMConfigurationKeys.DISABLE_OPTIMIZATION, false)) },
{ OptimizationClassBuilderFactory(it, disableOptimization, constructorCallNormalizationMode) },
{ BuilderFactoryForDuplicateSignatureDiagnostics(
it, this.bindingContext, diagnostics, this.moduleName,
shouldGenerate = { !shouldOnlyCollectSignatures(it) }

View File

@@ -33,7 +33,8 @@ val testDistProjects = listOf(
":kotlin-preloader",
":plugins:android-extensions-compiler",
":kotlin-ant",
":kotlin-annotations-jvm")
":kotlin-annotations-jvm",
":kotlin-annotations-android")
dependencies {
depDistProjects.forEach {

View File

@@ -1,7 +1,7 @@
apply { plugin("kotlin") }
jvmTarget = "1.6"
jvmTarget = "1.8"
dependencies {
compile(project(":compiler:util"))

View File

@@ -19,6 +19,7 @@ package org.jetbrains.kotlin.cli.common.arguments
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.config.AnalysisFlag
import org.jetbrains.kotlin.config.JVMConstructorCallNormalizationMode
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.utils.Jsr305State
import org.jetbrains.kotlin.utils.ReportLevel
@@ -108,6 +109,16 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
@Argument(value = "-Xno-optimize", description = "Disable optimizations")
var noOptimize: Boolean by FreezableVar(false)
@Argument(
value = "-Xnormalize-constructor-calls",
valueDescription = "{disable|enable|preserve-class-initialization}",
description = "Normalize constructor calls " +
"(disable: don't normalize; enable: normalize; " +
"preserve-class-initialization: normalize preserving class initialization order), " +
"default is disable"
)
var constructorCallNormalizationMode: String? by FreezableVar(JVMConstructorCallNormalizationMode.DEFAULT.description)
@Argument(value = "-Xreport-perf", description = "Report detailed performance statistics")
var reportPerf: Boolean by FreezableVar(false)

View File

@@ -0,0 +1,3 @@
# Note that this file is also present in idea/src/META-INF/services
org.jetbrains.kotlin.resolve.jvm.diagnostics.DefaultErrorMessagesJvm
org.jetbrains.kotlin.js.resolve.diagnostics.DefaultErrorMessagesJs

View File

@@ -60,7 +60,7 @@ class K2JSDce : CLITool<K2JSDceArguments>() {
}
val dceResult = DeadCodeElimination.run(files, includedDeclarations, logConsumer)
if (dceResult.status == DeadCodeEliminationStatus.FAILED) return ExitCode.COMPILATION_ERROR
val nodes = dceResult.reachableNodes
val nodes = dceResult.reachableNodes.filterTo(mutableSetOf()) { it.reachable }
val reachabilitySeverity = if (arguments.printReachabilityInfo) CompilerMessageSeverity.INFO else CompilerMessageSeverity.LOGGING
messageCollector.report(reachabilitySeverity, "")

View File

@@ -349,6 +349,16 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
configuration.put(JVMConfigurationKeys.DISABLE_PARAM_ASSERTIONS, arguments.noParamAssertions)
configuration.put(JVMConfigurationKeys.NO_EXCEPTION_ON_EXPLICIT_EQUALS_FOR_BOXED_NULL, arguments.noExceptionOnExplicitEqualsForBoxedNull);
configuration.put(JVMConfigurationKeys.DISABLE_OPTIMIZATION, arguments.noOptimize)
val constructorCallNormalizationMode = JVMConstructorCallNormalizationMode.fromStringOrNull(arguments.constructorCallNormalizationMode)
if (constructorCallNormalizationMode == null) {
configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY)
.report(ERROR, "Unknown constructor call normalization mode: ${arguments.constructorCallNormalizationMode}, " +
"supported modes: ${JVMConstructorCallNormalizationMode.values().map { it.description }}")
}
configuration.put(JVMConfigurationKeys.CONSTRUCTOR_CALL_NORMALIZATION_MODE,
constructorCallNormalizationMode ?: JVMConstructorCallNormalizationMode.DEFAULT)
configuration.put(JVMConfigurationKeys.INHERIT_MULTIFILE_PARTS, arguments.inheritMultifileParts)
configuration.put(JVMConfigurationKeys.SKIP_RUNTIME_VERSION_CHECK, arguments.skipRuntimeVersionCheck)
configuration.put(JVMConfigurationKeys.USE_FAST_CLASS_FILES_READING, !arguments.useOldClassFilesReading)

View File

@@ -80,7 +80,7 @@ class KotlinCliJavaFileManagerImpl(private val myPsiManager: PsiManager) : CoreJ
private val binaryCache: MutableMap<ClassId, JavaClass?> = THashMap()
private val signatureParsingComponent =
BinaryClassSignatureParser(ClassifierResolutionContext { findClass(it, allScope) })
BinaryClassSignatureParser()
override fun findClass(classId: ClassId, searchScope: GlobalSearchScope): JavaClass? {
val virtualFile = findVirtualFileForTopLevelClass(classId, searchScope) ?: return null

View File

@@ -153,8 +153,8 @@ class ReplCodeAnalyzer(environment: KotlinCoreEnvironment) {
return delegateFactory.getPackageMemberDeclarationProvider(packageFqName)
}
override fun diagnoseMissingPackageFragment(file: KtFile) {
delegateFactory.diagnoseMissingPackageFragment(file)
override fun diagnoseMissingPackageFragment(fqName: FqName, file: KtFile?) {
delegateFactory.diagnoseMissingPackageFragment(fqName, file)
}
class AdaptablePackageMemberDeclarationProvider(

View File

@@ -1,4 +1,6 @@
import org.gradle.jvm.tasks.Jar
description = "Compiler runner + daemon client"
apply { plugin("kotlin") }
@@ -13,6 +15,7 @@ dependencies {
compileOnly(project(":compiler:daemon-common"))
compile(project(":kotlin-daemon-client"))
compileOnly(project(":compiler:util"))
runtime(projectRuntimeJar(":kotlin-compiler-embeddable"))
}
sourceSets {
@@ -20,10 +23,13 @@ sourceSets {
"test" {}
}
runtimeJar {
val jar: Jar by tasks
jar.apply {
from(getSourceSetsFrom(":kotlin-daemon-client")["main"].output.classesDirs)
from(getSourceSetsFrom(":compiler:daemon-common")["main"].output.classesDirs)
}
runtimeJar(rewriteDepsToShadedCompiler(jar))
sourcesJar()
javadocJar()

View File

@@ -216,4 +216,9 @@ messages/**)
-keep class com.sun.source.** { *; }
# for coroutines
-keep class kotlinx.coroutines.** { *; }
-keep class kotlinx.coroutines.** { *; }
# for webdemo
-keep class com.intellij.openapi.progress.ProgressManager { *; }

View File

@@ -57,6 +57,8 @@ public class JVMConfigurationKeys {
CompilerConfigurationKey.create("disable not-null call receiver assertions");
public static final CompilerConfigurationKey<Boolean> DISABLE_PARAM_ASSERTIONS =
CompilerConfigurationKey.create("disable not-null parameter assertions");
public static final CompilerConfigurationKey<JVMConstructorCallNormalizationMode> CONSTRUCTOR_CALL_NORMALIZATION_MODE =
CompilerConfigurationKey.create("constructor call normalization mode");
public static final CompilerConfigurationKey<Boolean> NO_EXCEPTION_ON_EXPLICIT_EQUALS_FOR_BOXED_NULL =
CompilerConfigurationKey.create("do not throw NPE on explicit 'equals' call for null receiver of platform boxed primitive type");
public static final CompilerConfigurationKey<Boolean> DISABLE_OPTIMIZATION =

View File

@@ -14,6 +14,23 @@
* limitations under the License.
*/
package foo
package org.jetbrains.kotlin.config
fun dummy() {}
enum class JVMConstructorCallNormalizationMode(
val description: String,
val isEnabled: Boolean,
val shouldPreserveClassInitialization: Boolean
) {
DISABLE("disable", false, false),
ENABLE("enable", true, false),
PRESERVE_CLASS_INITIALIZATION("preserve-class-initialization", true, true)
;
companion object {
@JvmField
val DEFAULT = DISABLE
@JvmStatic
fun fromStringOrNull(string: String?) = values().find { it.description == string }
}
}

View File

@@ -16,14 +16,11 @@
package org.jetbrains.kotlin.load.java.structure.impl.classFiles
import com.intellij.psi.CommonClassNames
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.kotlin.builtins.PrimitiveType
import org.jetbrains.kotlin.load.java.structure.JavaClassifierType
import org.jetbrains.kotlin.load.java.structure.JavaType
import org.jetbrains.kotlin.load.java.structure.JavaTypeParameter
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.utils.addToStdlib.flattenTo
import org.jetbrains.kotlin.utils.compact
@@ -33,14 +30,11 @@ import java.text.StringCharacterIterator
/**
* Take a look at com.intellij.psi.impl.compiled.SignatureParsing
* NOTE: currently this class can simply be converted to an object, but there are postponed plans
* to introduce cached instance for java.lang.Object type that would require injected class finder.
* So please, do not convert it to object
*/
class BinaryClassSignatureParser(globalContext: ClassifierResolutionContext) {
companion object {
private val JAVA_LANG_OBJECT = ClassId.topLevel(FqName(CommonClassNames.JAVA_LANG_OBJECT))
}
private val JAVA_LANG_OBJECT_CLASSIFIER_TYPE: JavaClassifierType =
PlainJavaClassifierType({ globalContext.resolveClass(JAVA_LANG_OBJECT) }, emptyList())
class BinaryClassSignatureParser {
fun parseTypeParametersDeclaration(signature: CharacterIterator, context: ClassifierResolutionContext): List<JavaTypeParameter> {
if (signature.current() != '<') {
@@ -68,25 +62,14 @@ class BinaryClassSignatureParser(globalContext: ClassifierResolutionContext) {
val parameterName = name.toString()
// postpone list allocation till a second bound is seen; ignore sole Object bound
var bounds: MutableList<JavaClassifierType>? = null
var jlo = false
val bounds: MutableList<JavaClassifierType> = ContainerUtil.newSmartList()
while (signature.current() == ':') {
signature.next()
val bound = parseClassifierRefSignature(signature, context) ?: continue
if (bounds == null) {
if (JAVA_LANG_OBJECT_CLASSIFIER_TYPE === bound) {
jlo = true
continue
}
bounds = ContainerUtil.newSmartList()
if (jlo) {
bounds.add(JAVA_LANG_OBJECT_CLASSIFIER_TYPE)
}
}
bounds.add(bound)
}
return BinaryJavaTypeParameter(Name.identifier(parameterName), bounds ?: emptyList())
return BinaryJavaTypeParameter(Name.identifier(parameterName), bounds)
}
fun parseClassifierRefSignature(signature: CharacterIterator, context: ClassifierResolutionContext): JavaClassifierType? {
@@ -148,8 +131,6 @@ class BinaryClassSignatureParser(globalContext: ClassifierResolutionContext) {
}
signature.next()
if (canonicalName.toString() == "java/lang/Object") return JAVA_LANG_OBJECT_CLASSIFIER_TYPE
return PlainJavaClassifierType(
{ context.resolveByInternalName(canonicalName.toString()) },
argumentGroups.reversed().flattenTo(arrayListOf()).compact()

View File

@@ -80,6 +80,9 @@ open class KotlinScriptDefinitionFromAnnotatedTemplate(
private fun <T : Any> instantiateResolver(resolverClass: KClass<T>): T? {
try {
resolverClass.objectInstance?.let {
return it
}
val constructorWithoutParameters = resolverClass.constructors.find { it.parameters.all { it.isOptional } }
if (constructorWithoutParameters == null) {
log.warn("[kts] ${resolverClass.qualifiedName} must have a constructor without required parameters")

View File

@@ -190,7 +190,10 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon
}
private fun WriteValueInstruction.isTrivialInitializer() =
element is KtVariableDeclaration || element is KtParameter
// WriteValueInstruction having KtDeclaration as an element means
// it must be a write happened at the same time when
// the variable (common variable/parameter/object) has been declared
element is KtDeclaration
private inner class ReadOnlyInitControlFlowInfoImpl(
val declaredSet: ImmutableSet<VariableDescriptor>,

View File

@@ -27,6 +27,7 @@ import org.jetbrains.kotlin.config.LanguageFeature;
import org.jetbrains.kotlin.config.LanguageVersion;
import org.jetbrains.kotlin.config.LanguageVersionSettings;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.diagnostics.rendering.DiagnosticRenderer;
import org.jetbrains.kotlin.lexer.KtKeywordToken;
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken;
import org.jetbrains.kotlin.lexer.KtTokens;
@@ -977,9 +978,9 @@ public interface Errors {
DiagnosticFactory1<PsiElement, CallableDescriptor> ILLEGAL_SUSPEND_FUNCTION_CALL = DiagnosticFactory1.create(ERROR);
DiagnosticFactory0<PsiElement> ILLEGAL_RESTRICTED_SUSPENDING_FUNCTION_CALL = DiagnosticFactory0.create(ERROR);
DiagnosticFactory2<PsiElement, String, String> PLUGIN_ERROR = DiagnosticFactory2.create(ERROR);
DiagnosticFactory2<PsiElement, String, String> PLUGIN_WARNING = DiagnosticFactory2.create(WARNING);
DiagnosticFactory2<PsiElement, String, String> PLUGIN_INFO = DiagnosticFactory2.create(INFO);
DiagnosticFactory1<PsiElement, RenderedDiagnostic<?>> PLUGIN_ERROR = DiagnosticFactory1.create(ERROR);
DiagnosticFactory1<PsiElement, RenderedDiagnostic<?>> PLUGIN_WARNING = DiagnosticFactory1.create(WARNING);
DiagnosticFactory1<PsiElement, RenderedDiagnostic<?>> PLUGIN_INFO = DiagnosticFactory1.create(INFO);
// Error sets
ImmutableSet<? extends DiagnosticFactory<?>> UNRESOLVED_REFERENCE_DIAGNOSTICS = ImmutableSet.of(

View File

@@ -14,6 +14,17 @@
* limitations under the License.
*/
package foo
package org.jetbrains.kotlin.diagnostics
fun useA(a: A) = a.x
import org.jetbrains.kotlin.diagnostics.rendering.DiagnosticRenderer
class RenderedDiagnostic<D : Diagnostic>(
val diagnostic: D,
val renderer: DiagnosticRenderer<D>
) {
val text = renderer.render(diagnostic)
val factory: DiagnosticFactory<*> get() = diagnostic.factory
override fun toString() = text
}

View File

@@ -16,9 +16,6 @@
package org.jetbrains.kotlin.diagnostics
import com.intellij.mock.MockApplication
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.builtins.isFunctionType
import org.jetbrains.kotlin.descriptors.CallableDescriptor
@@ -167,19 +164,15 @@ inline fun <reified T : KtDeclaration> reportOnDeclarationAs(trace: BindingTrace
}
fun <D : Diagnostic> DiagnosticSink.reportFromPlugin(diagnostic: D, ext: DefaultErrorMessages.Extension) {
if (ApplicationManager.getApplication() !is MockApplication) {
return this.report(diagnostic)
}
@Suppress("UNCHECKED_CAST")
val renderer = ext.map[diagnostic.factory] as? DiagnosticRenderer<D>
?: error("Renderer not found for diagnostic ${diagnostic.factory.name}")
val text = renderer.render(diagnostic)
val renderedDiagnostic = RenderedDiagnostic(diagnostic, renderer)
when (diagnostic.severity) {
Severity.ERROR -> report(Errors.PLUGIN_ERROR.on(diagnostic.psiElement, diagnostic.factory.name, text))
Severity.WARNING -> report(Errors.PLUGIN_WARNING.on(diagnostic.psiElement, diagnostic.factory.name, text))
Severity.INFO -> report(Errors.PLUGIN_INFO.on(diagnostic.psiElement, diagnostic.factory.name, text))
Severity.ERROR -> report(Errors.PLUGIN_ERROR.on(diagnostic.psiElement, renderedDiagnostic))
Severity.WARNING -> report(Errors.PLUGIN_WARNING.on(diagnostic.psiElement, renderedDiagnostic))
Severity.INFO -> report(Errors.PLUGIN_INFO.on(diagnostic.psiElement, renderedDiagnostic))
}
}
}

View File

@@ -16,26 +16,27 @@
package org.jetbrains.kotlin.diagnostics.rendering;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.util.io.FileUtil;
import kotlin.Pair;
import kotlin.collections.CollectionsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.kotlin.config.LanguageVersion;
import org.jetbrains.kotlin.diagnostics.Diagnostic;
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory;
import org.jetbrains.kotlin.diagnostics.Errors;
import org.jetbrains.kotlin.diagnostics.RenderedDiagnostic;
import org.jetbrains.kotlin.resolve.VarianceConflictDiagnosticData;
import org.jetbrains.kotlin.serialization.deserialization.descriptors.SinceKotlinInfo;
import org.jetbrains.kotlin.types.KotlinTypeKt;
import org.jetbrains.kotlin.util.MappedExtensionProvider;
import org.jetbrains.kotlin.util.OperatorNameConventions;
import org.jetbrains.kotlin.utils.addToStdlib.AddToStdlibKt;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ServiceLoader;
import static org.jetbrains.kotlin.diagnostics.Errors.*;
import static org.jetbrains.kotlin.diagnostics.rendering.Renderers.*;
@@ -44,47 +45,30 @@ import static org.jetbrains.kotlin.diagnostics.rendering.RenderingContext.of;
public class DefaultErrorMessages {
public interface Extension {
ExtensionPointName<Extension> EP_NAME = ExtensionPointName.create("org.jetbrains.kotlin.defaultErrorMessages");
@NotNull
DiagnosticFactoryToRendererMap getMap();
}
private static final DiagnosticFactoryToRendererMap MAP = new DiagnosticFactoryToRendererMap("Default");
private static final MappedExtensionProvider<Extension, List<DiagnosticFactoryToRendererMap>> RENDERER_MAPS = MappedExtensionProvider.create(
Extension.EP_NAME,
extensions -> {
List<DiagnosticFactoryToRendererMap> result = new ArrayList<>(extensions.size() + 1);
for (Extension extension : extensions) {
result.add(extension.getMap());
}
result.add(MAP);
return result;
});
private static final List<DiagnosticFactoryToRendererMap> RENDERER_MAPS =
CollectionsKt.plus(
Collections.singletonList(MAP),
CollectionsKt.map(ServiceLoader.load(Extension.class, DefaultErrorMessages.class.getClassLoader()), Extension::getMap)
);
@NotNull
@SuppressWarnings("unchecked")
public static String render(@NotNull Diagnostic diagnostic) {
for (DiagnosticFactoryToRendererMap map : RENDERER_MAPS.get()) {
DiagnosticRenderer renderer = map.get(diagnostic.getFactory());
if (renderer != null) {
//noinspection unchecked
return renderer.render(diagnostic);
}
DiagnosticRenderer renderer = getRendererForDiagnostic(diagnostic);
if (renderer != null) {
return renderer.render(diagnostic);
}
throw new IllegalArgumentException("Don't know how to render diagnostic of type " + diagnostic.getFactory().getName() +
" with the following renderer maps: " + RENDERER_MAPS.get());
return diagnostic.toString() + " (error: could not render message)";
}
@TestOnly
@Nullable
public static DiagnosticRenderer getRendererForDiagnostic(@NotNull Diagnostic diagnostic) {
for (DiagnosticFactoryToRendererMap map : RENDERER_MAPS.get()) {
DiagnosticRenderer renderer = map.get(diagnostic.getFactory());
if (renderer != null) return renderer;
}
return null;
return AddToStdlibKt.firstNotNullResult(RENDERER_MAPS, map -> map.get(diagnostic.getFactory()));
}
static {
@@ -885,9 +869,9 @@ public class DefaultErrorMessages {
MAP.put(ILLEGAL_SUSPEND_FUNCTION_CALL, "Suspend function ''{0}'' should be called only from a coroutine or another suspend function", NAME);
MAP.put(ILLEGAL_RESTRICTED_SUSPENDING_FUNCTION_CALL, "Restricted suspending functions can only invoke member or extension suspending functions on their restricted coroutine scope");
MAP.put(PLUGIN_ERROR, "{0}: {1}", TO_STRING, TO_STRING);
MAP.put(PLUGIN_WARNING, "{0}: {1}", TO_STRING, TO_STRING);
MAP.put(PLUGIN_INFO, "{0}: {1}", TO_STRING, TO_STRING);
MAP.put(PLUGIN_ERROR, "{0}", (d, c) -> d.getText());
MAP.put(PLUGIN_WARNING, "{0}", (d, c) -> d.getText());
MAP.put(PLUGIN_INFO, "{0}", (d, c) -> d.getText());
MAP.setImmutable();

View File

@@ -32,7 +32,7 @@ class KotlinLookupLocation(val element: KtElement) : LookupLocation {
if (containingJetFile.doNotAnalyze != null) return null
return object : LocationInfo {
override val filePath = containingJetFile.virtualFile.path
override val filePath = containingJetFile.virtualFilePath
override val position: Position
get() = getLineAndColumnInPsiFile(containingJetFile, element.textRange).let { Position(it.line, it.column) }

View File

@@ -50,6 +50,9 @@ open class KtFile(viewProvider: FileViewProvider, val isCompiled: Boolean) :
@Volatile
private var hasTopLeveCallables: Boolean? = null
@Volatile
private var pathCached: String? = null
val importList: KtImportList?
get() = findChildByTypeOrClass(KtStubElementTypes.IMPORT_LIST, KtImportList::class.java)
@@ -104,6 +107,15 @@ open class KtFile(viewProvider: FileViewProvider, val isCompiled: Boolean) :
return result
}
val virtualFilePath
get(): String {
pathCached?.let { return it }
return virtualFile.path.also {
pathCached = it
}
}
val isScriptByTree: Boolean
get() = script != null
@@ -170,6 +182,7 @@ open class KtFile(viewProvider: FileViewProvider, val isCompiled: Boolean) :
super<PsiFileBase>.clearCaches()
isScript = null
hasTopLeveCallables = null
pathCached = null
}
fun isScript(): Boolean = stub?.isScript() ?: isScriptByTree

View File

@@ -28,7 +28,7 @@ object KotlinStubVersions {
// Binary stub version should be increased if stub format (org.jetbrains.kotlin.psi.stubs.impl) is changed
// or changes are made to the core stub building code (org.jetbrains.kotlin.idea.decompiler.stubBuilder).
// Increasing this version will lead to reindexing of all binary files that are potentially kotlin binaries (including all class files).
private const val BINARY_STUB_VERSION = 62
private const val BINARY_STUB_VERSION = 63
// Classfile stub version should be increased if changes are made to classfile stub building subsystem (org.jetbrains.kotlin.idea.decompiler.classFile)
// Increasing this version will lead to reindexing of all classfiles.

View File

@@ -65,7 +65,7 @@ class TypeAliasExpander(
}
private fun TypeAliasExpansion.createAbbreviation(annotations: Annotations, isNullable: Boolean) =
KotlinTypeFactory.simpleType(
KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope(
annotations,
descriptor.typeConstructor,
arguments,

View File

@@ -369,11 +369,11 @@ class TypeResolver(
return if (scopeForTypeParameter is ErrorUtils.ErrorScope)
ErrorUtils.createErrorType("?")
else
KotlinTypeFactory.simpleType(annotations,
typeParameter.typeConstructor,
listOf(),
false,
scopeForTypeParameter)
KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope(annotations,
typeParameter.typeConstructor,
listOf(),
false,
scopeForTypeParameter)
}
private fun getScopeForTypeParameter(c: TypeResolutionContext, typeParameterDescriptor: TypeParameterDescriptor): MemberScope {

View File

@@ -59,7 +59,6 @@ import java.util.List;
import static org.jetbrains.kotlin.psi.KtPsiUtil.getLastElementDeparenthesized;
import static org.jetbrains.kotlin.resolve.BindingContextUtils.getRecordedTypeInfo;
import static org.jetbrains.kotlin.resolve.calls.callResolverUtil.ResolveArgumentsMode.RESOLVE_FUNCTION_ARGUMENTS;
import static org.jetbrains.kotlin.resolve.calls.callResolverUtil.ResolveArgumentsMode.SHAPE_FUNCTION_ARGUMENTS;
import static org.jetbrains.kotlin.resolve.calls.context.ContextDependency.DEPENDENT;
import static org.jetbrains.kotlin.resolve.calls.context.ContextDependency.INDEPENDENT;
@@ -109,13 +108,8 @@ public class ArgumentTypeResolver {
return KotlinTypeChecker.DEFAULT.isSubtypeOf(actualType, expectedType);
}
public void checkTypesWithNoCallee(@NotNull CallResolutionContext<?> context) {
checkTypesWithNoCallee(context, SHAPE_FUNCTION_ARGUMENTS);
}
public void checkTypesWithNoCallee(
@NotNull CallResolutionContext<?> context,
@NotNull ResolveArgumentsMode resolveFunctionArgumentBodies
@NotNull CallResolutionContext<?> context
) {
if (context.checkArguments != CheckArgumentTypesMode.CHECK_VALUE_ARGUMENTS) return;
@@ -126,9 +120,7 @@ public class ArgumentTypeResolver {
}
}
if (resolveFunctionArgumentBodies == RESOLVE_FUNCTION_ARGUMENTS) {
checkTypesForFunctionArgumentsWithNoCallee(context);
}
checkTypesForFunctionArgumentsWithNoCallee(context);
for (KtTypeProjection typeProjection : context.call.getTypeArguments()) {
KtTypeReference typeReference = typeProjection.getTypeReference();
@@ -141,7 +133,7 @@ public class ArgumentTypeResolver {
}
}
public void checkTypesForFunctionArgumentsWithNoCallee(@NotNull CallResolutionContext<?> context) {
private void checkTypesForFunctionArgumentsWithNoCallee(@NotNull CallResolutionContext<?> context) {
if (context.checkArguments != CheckArgumentTypesMode.CHECK_VALUE_ARGUMENTS) return;
for (ValueArgument valueArgument : context.call.getValueArguments()) {
@@ -175,15 +167,6 @@ public class ArgumentTypeResolver {
return isFunctionLiteralArgument(expression, context) || isCallableReferenceArgument(expression, context);
}
@NotNull
public static KtFunction getFunctionLiteralArgument(
@NotNull KtExpression expression, @NotNull ResolutionContext context
) {
assert isFunctionLiteralArgument(expression, context);
//noinspection ConstantConditions
return getFunctionLiteralArgumentIfAny(expression, context);
}
@Nullable
public static KtFunction getFunctionLiteralArgumentIfAny(
@NotNull KtExpression expression, @NotNull ResolutionContext context

View File

@@ -74,13 +74,8 @@ class CallCompleter(
// for the case 'foo(a)' where 'foo' is a variable, the call 'foo.invoke(a)' shouldn't be completed separately,
// it's completed when the outer (variable as function call) is completed
if (!isInvokeCallOnVariable(context.call)) {
val temporaryTrace = TemporaryBindingTrace.create(context.trace, "Trace to complete a resulting call")
val contextWithTemporaryTrace = context.replaceBindingTrace(temporaryTrace)
completeResolvedCallAndArguments(resolvedCall, results, contextWithTemporaryTrace, tracing)
completeAllCandidates(contextWithTemporaryTrace, results)
temporaryTrace.commit()
completeResolvedCallAndArguments(resolvedCall, results, context, tracing)
completeAllCandidates(context, results)
}
if (resolvedCall != null && context.trace.wantsDiagnostics()) {

View File

@@ -62,7 +62,6 @@ import javax.inject.Inject;
import java.util.*;
import static org.jetbrains.kotlin.diagnostics.Errors.*;
import static org.jetbrains.kotlin.resolve.calls.callResolverUtil.ResolveArgumentsMode.RESOLVE_FUNCTION_ARGUMENTS;
import static org.jetbrains.kotlin.resolve.calls.results.OverloadResolutionResults.Code.INCOMPLETE_TYPE_INFERENCE;
import static org.jetbrains.kotlin.types.TypeUtils.NO_EXPECTED_TYPE;
@@ -621,7 +620,7 @@ public class CallResolver {
if (CallResolverUtilKt.isInvokeCallOnVariable(context.call)) return;
if (!results.isSingleResult()) {
if (results.getResultCode() == INCOMPLETE_TYPE_INFERENCE) {
argumentTypeResolver.checkTypesWithNoCallee(context, RESOLVE_FUNCTION_ARGUMENTS);
argumentTypeResolver.checkTypesWithNoCallee(context);
}
return;
}
@@ -648,7 +647,7 @@ public class CallResolver {
}
private <D extends CallableDescriptor> OverloadResolutionResultsImpl<D> checkArgumentTypesAndFail(BasicCallResolutionContext context) {
argumentTypeResolver.checkTypesWithNoCallee(context, ResolveArgumentsMode.RESOLVE_FUNCTION_ARGUMENTS);
argumentTypeResolver.checkTypesWithNoCallee(context);
return OverloadResolutionResultsImpl.nameNotFound();
}

View File

@@ -81,7 +81,7 @@ fun replaceReturnTypeForCallable(type: KotlinType, given: KotlinType): KotlinTyp
fun replaceReturnTypeByUnknown(type: KotlinType) = replaceReturnTypeForCallable(type, DONT_CARE)
private fun replaceTypeArguments(type: KotlinType, newArguments: List<TypeProjection>) =
KotlinTypeFactory.simpleType(type.annotations, type.constructor, newArguments, type.isMarkedNullable, type.memberScope)
KotlinTypeFactory.simpleType(type.annotations, type.constructor, newArguments, type.isMarkedNullable)
private fun getParameterArgumentsOfCallableType(type: KotlinType) =
type.arguments.dropLast(1)
@@ -126,8 +126,8 @@ fun getErasedReceiverType(receiverParameterDescriptor: ReceiverParameterDescript
receiverType.constructor
}
return KotlinTypeFactory.simpleType(receiverType.annotations, receiverTypeConstructor, fakeTypeArguments,
receiverType.isMarkedNullable, ErrorUtils.createErrorScope("Error scope for erased receiver type", /*throwExceptions=*/true))
return KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope(receiverType.annotations, receiverTypeConstructor, fakeTypeArguments,
receiverType.isMarkedNullable, ErrorUtils.createErrorScope("Error scope for erased receiver type", /*throwExceptions=*/true))
}
fun isOrOverridesSynthesized(descriptor: CallableMemberDescriptor): Boolean {

View File

@@ -448,7 +448,7 @@ class CandidateResolver(
val erasedReceiverType = getErasedReceiverType(receiverParameterDescriptor, candidateDescriptor)
if (!smartCastManager.isSubTypeBySmartCastIgnoringNullability(receiverArgument, erasedReceiverType, this)) {
if (smartCastManager.getSmartCastReceiverResult(receiverArgument, erasedReceiverType, this) == null) {
RECEIVER_TYPE_ERROR
} else {
SUCCESS
@@ -505,22 +505,21 @@ class CandidateResolver(
val candidateDescriptor = candidateCall.candidateDescriptor
if (TypeUtils.dependsOnTypeParameters(receiverParameter.type, candidateDescriptor.typeParameters)) return SUCCESS
val isSubtypeBySmartCastIgnoringNullability = smartCastManager.isSubTypeBySmartCastIgnoringNullability(
receiverArgument, receiverParameter.type, this)
// Here we know that receiver is OK ignoring nullability and check that nullability is OK too
// Doing it simply as full subtyping check (receiverValueType <: receiverParameterType)
val call = candidateCall.call
val safeAccess = isExplicitReceiver && !implicitInvokeCheck && call.isExplicitSafeCall()
val expectedReceiverParameterType = if (safeAccess) TypeUtils.makeNullable(receiverParameter.type) else receiverParameter.type
if (!isSubtypeBySmartCastIgnoringNullability) {
val smartCastSubtypingResult = smartCastManager.getSmartCastReceiverResult(receiverArgument, expectedReceiverParameterType, this)
if (smartCastSubtypingResult == null) {
tracing.wrongReceiverType(
trace, receiverParameter, receiverArgument,
this.replaceCallPosition(CallPosition.ExtensionReceiverPosition(candidateCall)))
return OTHER_ERROR
}
// Here we know that receiver is OK ignoring nullability and check that nullability is OK too
// Doing it simply as full subtyping check (receiverValueType <: receiverParameterType)
val call = candidateCall.call
val safeAccess = isExplicitReceiver && !implicitInvokeCheck && call.isExplicitSafeCall()
val expectedReceiverParameterType = if (safeAccess) TypeUtils.makeNullable(receiverParameter.type) else receiverParameter.type
val notNullReceiverExpected = !ArgumentTypeResolver.isSubtypeOfForArgumentType(receiverArgument.type, expectedReceiverParameterType)
val notNullReceiverExpected = smartCastSubtypingResult != SmartCastManager.ReceiverSmartCastResult.OK
val smartCastNeeded =
notNullReceiverExpected || !isCandidateVisibleOrExtensionReceiver(receiverArgument, null, isDispatchReceiver)
var reportUnsafeCall = false

View File

@@ -82,6 +82,7 @@ private fun ConstraintSystemBuilderImpl.addConstraintFromBounds(old: Bound, new:
}
private fun ConstraintSystemBuilderImpl.generateNewBound(bound: Bound, substitution: Bound) {
if (bound === substitution) return
// Let's have a bound 'T <=> My<R>', and a substitution 'R <=> Type'.
// Here <=> means lower_bound, upper_bound or exact_bound constraint.
// Then a new bound 'T <=> My<_/in/out Type>' can be generated.
@@ -127,4 +128,4 @@ private fun ConstraintSystemBuilderImpl.generateNewBound(bound: Bound, substitut
if (approximationBounds.lower.containsConstrainingTypeWithoutProjection() && bound.kind != UPPER_BOUND) {
addNewBound(approximationBounds.lower, LOWER_BOUND)
}
}
}

View File

@@ -30,18 +30,11 @@ import org.jetbrains.kotlin.resolve.calls.context.ResolutionContext
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeIntersector
import org.jetbrains.kotlin.types.TypeUtils
import java.util.*
class SmartCastManager {
private fun getSmartCastVariants(
receiverToCast: ReceiverValue,
context: ResolutionContext<*>
): List<KotlinType> =
getSmartCastVariants(receiverToCast, context.trace.bindingContext, context.scope.ownerDescriptor, context.dataFlowInfo)
fun getSmartCastVariants(
receiverToCast: ReceiverValue,
bindingContext: BindingContext,
@@ -81,29 +74,40 @@ class SmartCastManager {
return dataFlowInfo.getCollectedTypes(dataFlowValue)
}
fun isSubTypeBySmartCastIgnoringNullability(
fun getSmartCastReceiverResult(
receiverArgument: ReceiverValue,
receiverParameterType: KotlinType,
context: ResolutionContext<*>
): Boolean {
val smartCastTypes = getSmartCastVariants(receiverArgument, context)
return getSmartCastSubType(TypeUtils.makeNullable(receiverParameterType), smartCastTypes) != null
): ReceiverSmartCastResult? {
getSmartCastReceiverResultWithGivenNullability(receiverArgument, receiverParameterType, context)?.let {
return it
}
val nullableParameterType = TypeUtils.makeNullable(receiverParameterType)
return when {
getSmartCastReceiverResultWithGivenNullability(receiverArgument, nullableParameterType, context) == null -> null
else -> ReceiverSmartCastResult.SMARTCAST_NEEDED_OR_NOT_NULL_EXPECTED
}
}
private fun getSmartCastSubType(
private fun getSmartCastReceiverResultWithGivenNullability(
receiverArgument: ReceiverValue,
receiverParameterType: KotlinType,
smartCastTypes: Collection<KotlinType>
): KotlinType? {
val subTypes = smartCastTypes
.filter { ArgumentTypeResolver.isSubtypeOfForArgumentType(it, receiverParameterType) }
.distinct()
if (subTypes.isEmpty()) return null
context: ResolutionContext<*>
): ReceiverSmartCastResult? =
when {
ArgumentTypeResolver.isSubtypeOfForArgumentType(receiverArgument.type, receiverParameterType) ->
ReceiverSmartCastResult.OK
getSmartCastVariantsExcludingReceiver(context, receiverArgument).any {
ArgumentTypeResolver.isSubtypeOfForArgumentType(it, receiverParameterType)
} ->
ReceiverSmartCastResult.SMARTCAST_NEEDED_OR_NOT_NULL_EXPECTED
else -> null
}
val intersection = TypeIntersector.intersectTypes(subTypes)
if (intersection == null || !intersection.constructor.isDenotable) {
return receiverParameterType
}
return intersection
enum class ReceiverSmartCastResult {
OK,
SMARTCAST_NEEDED_OR_NOT_NULL_EXPECTED
}
companion object {

View File

@@ -55,12 +55,7 @@ class FileScopeFactory(
fun createScopesForFile(file: KtFile, existingImports: ImportingScope? = null): FileScopes {
val packageView = moduleDescriptor.getPackage(file.packageFqName)
val packageFragment = topLevelDescriptorProvider.getPackageFragment(file.packageFqName)
if (packageFragment == null) {
// TODO J2K and change return type of diagnoseMissingPackageFragment() to Nothing
(topLevelDescriptorProvider as? LazyClassContext)?.declarationProviderFactory?.diagnoseMissingPackageFragment(file)
error("Could not find fragment ${file.packageFqName} for file ${file.name}")
}
val packageFragment = topLevelDescriptorProvider.getPackageFragmentOrDiagnoseFailure(file.packageFqName, file)
return FilesScopesBuilder(file, existingImports, packageFragment, packageView).result
}
@@ -119,7 +114,7 @@ class FileScopeFactory(
}
}
val lexicalScope = LexicalScope.Base(lazyImportingScope, topLevelDescriptorProvider.getPackageFragment(file.packageFqName)!!)
val lexicalScope = LexicalScope.Base(lazyImportingScope, topLevelDescriptorProvider.getPackageFragmentOrDiagnoseFailure(file.packageFqName, file))
val importResolver = object : ImportResolver {
override fun forceResolveAllImports() {

View File

@@ -216,16 +216,8 @@ open class LazyDeclarationResolver @Deprecated("") constructor(
val ktFile = declaration.containingFile as KtFile
val fqName = ktFile.packageFqName
topLevelDescriptorProvider.assertValid()
val packageDescriptor = topLevelDescriptorProvider.getPackageFragment(fqName)
if (packageDescriptor == null) {
if (topLevelDescriptorProvider is LazyClassContext) {
topLevelDescriptorProvider.declarationProviderFactory.diagnoseMissingPackageFragment(ktFile)
}
else {
throw IllegalStateException("Cannot find package fragment for file " + ktFile.name + " with package " + fqName)
}
}
return packageDescriptor!!.getMemberScope()
val packageDescriptor = topLevelDescriptorProvider.getPackageFragmentOrDiagnoseFailure(fqName, ktFile)
return packageDescriptor.getMemberScope()
}
else {
return when (parentDeclaration) {

View File

@@ -137,7 +137,7 @@ public class ResolveSession implements KotlinCodeAnalyzer, LazyClassContext {
@Inject
public void setDelegationFilter(@NotNull DelegationFilter delegationFilter) {
public void setDelegationFilter(@NotNull DelegationFilter delegationFilter) {
this.delegationFilter = delegationFilter;
}
@@ -213,6 +213,18 @@ public class ResolveSession implements KotlinCodeAnalyzer, LazyClassContext {
return packages.invoke(fqName);
}
@NotNull
@Override
public LazyPackageDescriptor getPackageFragmentOrDiagnoseFailure(@NotNull FqName fqName, @Nullable KtFile from) {
LazyPackageDescriptor packageDescriptor = getPackageFragment(fqName);
if (packageDescriptor == null) {
declarationProviderFactory.diagnoseMissingPackageFragment(fqName, from);
assert false : "diagnoseMissingPackageFragment should throw!";
}
return packageDescriptor;
}
@Nullable
private LazyPackageDescriptor createPackage(FqName fqName) {
PackageMemberDeclarationProvider provider = declarationProviderFactory.getPackageMemberDeclarationProvider(fqName);
@@ -350,8 +362,7 @@ public class ResolveSession implements KotlinCodeAnalyzer, LazyClassContext {
) {
result.add(current);
for (FqName subPackage : packageFragmentProvider.getSubPackagesOf(current.getFqName(), MemberScope.Companion.getALL_NAME_FILTER())) {
LazyPackageDescriptor fragment = getPackageFragment(subPackage);
assert fragment != null : "Couldn't find fragment for " + subPackage;
LazyPackageDescriptor fragment = getPackageFragmentOrDiagnoseFailure(subPackage, null);
collectAllPackages(result, fragment);
}
return result;

View File

@@ -19,11 +19,14 @@ package org.jetbrains.kotlin.resolve.lazy
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyPackageDescriptor
interface TopLevelDescriptorProvider {
fun getPackageFragment(fqName: FqName): LazyPackageDescriptor?
fun getPackageFragmentOrDiagnoseFailure(fqName: FqName, from: KtFile?): LazyPackageDescriptor
fun getTopLevelClassifierDescriptors(fqName: FqName, location: LookupLocation): Collection<ClassifierDescriptor>
fun assertValid()
@@ -36,6 +39,10 @@ object NoTopLevelDescriptorProvider : TopLevelDescriptorProvider {
shouldNotBeCalled()
}
override fun getPackageFragmentOrDiagnoseFailure(fqName: FqName, from: KtFile?): LazyPackageDescriptor {
shouldNotBeCalled()
}
override fun getTopLevelClassifierDescriptors(fqName: FqName, location: LookupLocation): Collection<ClassifierDescriptor> {
shouldNotBeCalled()
}

View File

@@ -40,7 +40,11 @@ public abstract class AbstractDeclarationProviderFactory implements DeclarationP
}
@Override
public void diagnoseMissingPackageFragment(KtFile file) {
throw new IllegalStateException("Cannot find package fragment for file " + file.getName() + " with package " + file.getPackageFqName());
public void diagnoseMissingPackageFragment(@NotNull FqName fqName, @Nullable KtFile file) {
String message = "Cannot find package fragment " + fqName;
if (file != null) {
message += "\nvFile = " + file.getVirtualFilePath() + ", file package = '" + file.getPackageFqName() + "'";
}
throw new IllegalStateException(message);
}
}

View File

@@ -34,5 +34,5 @@ public interface DeclarationProviderFactory {
@Nullable
PackageMemberDeclarationProvider getPackageMemberDeclarationProvider(@NotNull FqName packageFqName);
void diagnoseMissingPackageFragment(KtFile file);
void diagnoseMissingPackageFragment(@NotNull FqName fqName, @Nullable KtFile file);
}

View File

@@ -234,7 +234,7 @@ public class CommonSupertypes {
else {
newScope = ErrorUtils.createErrorScope("A scope for common supertype which is not a normal classifier", true);
}
return KotlinTypeFactory.simpleType(Annotations.Companion.getEMPTY(), constructor, newProjections, nullable, newScope);
return KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope(Annotations.Companion.getEMPTY(), constructor, newProjections, nullable, newScope);
}
@NotNull

View File

@@ -134,7 +134,7 @@ public class TypeIntersector {
IntersectionTypeConstructor constructor = new IntersectionTypeConstructor(resultingTypes);
return KotlinTypeFactory.simpleType(
return KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope(
Annotations.Companion.getEMPTY(),
constructor,
Collections.emptyList(),

View File

@@ -155,7 +155,7 @@ class LocalClassDescriptorHolder(
throw UnsupportedOperationException("Should not be called for top-level declarations")
}
override fun diagnoseMissingPackageFragment(file: KtFile?) {
override fun diagnoseMissingPackageFragment(fqName: FqName, file: KtFile?) {
throw UnsupportedOperationException()
}
}

View File

@@ -46,15 +46,10 @@ protected constructor(
cached = WeakReference(newVal)
return newVal.second
}
companion object {
@JvmStatic fun <T, R> create(epName: ExtensionPointName<T>, map: (List<T>) -> R): MappedExtensionProvider<T, R>
= MappedExtensionProvider(epName, map)
}
}
class ExtensionProvider<T>(epName: ExtensionPointName<T>) : MappedExtensionProvider<T, List<T>>(epName, { it }) {
companion object {
@JvmStatic fun <T> create(epName: ExtensionPointName<T>): ExtensionProvider<T> = ExtensionProvider(epName)
}
}
}

View File

@@ -16,12 +16,12 @@
package org.jetbrains.kotlin.incremental
import com.intellij.openapi.util.io.FileUtil
import org.jetbrains.kotlin.build.GeneratedFile
import org.jetbrains.kotlin.cli.common.ExitCode
import org.jetbrains.kotlin.cli.common.arguments.K2JSCompilerArguments
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.js.K2JSCompiler
import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler
import org.jetbrains.kotlin.config.IncrementalCompilation
import org.jetbrains.kotlin.config.Services
import org.jetbrains.kotlin.incremental.components.LookupTracker
@@ -83,6 +83,16 @@ class IncrementalJsCompilerRunner(
override fun calculateSourcesToCompile(caches: IncrementalJsCachesManager, changedFiles: ChangedFiles.Known, args: K2JSCompilerArguments): CompilationMode {
if (BuildInfo.read(lastBuildInfoFile) == null) return CompilationMode.Rebuild { "No information on previous build" }
val libs = (args.libraries ?: "").split(File.pathSeparator).mapTo(HashSet()) { File(it) }
val libsDirs = libs.filter { it.isDirectory }
val changedLib = changedFiles.allAsSequence.find { it in libs }
?: changedFiles.allAsSequence.find { changedFile ->
libsDirs.any { libDir -> FileUtil.isAncestor(libDir, changedFile, true) }
}
if (changedLib != null) return CompilationMode.Rebuild { "Library has been changed: $changedLib" }
return CompilationMode.Incremental(getDirtyFiles(changedFiles))
}
@@ -133,4 +143,7 @@ class IncrementalJsCompilerRunner(
args.freeArgs = freeArgsBackup
}
}
private val ChangedFiles.Known.allAsSequence: Sequence<File>
get() = modified.asSequence() + removed.asSequence()
}

View File

@@ -78,7 +78,7 @@ class JvmSharedVariablesManager(val builtIns: KotlinBuiltIns) : SharedVariablesM
ClassConstructorDescriptorImpl.create(genericRefClass, Annotations.EMPTY, true, SourceElement.NO_SOURCE).apply {
initialize(emptyList(), Visibilities.PUBLIC)
val typeParameter = typeParameters[0]
val typeParameterType = KotlinTypeFactory.simpleType(Annotations.EMPTY, typeParameter.typeConstructor, listOf(), false, MemberScope.Empty)
val typeParameterType = KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope(Annotations.EMPTY, typeParameter.typeConstructor, listOf(), false, MemberScope.Empty)
returnType = KotlinTypeFactory.simpleNotNullType(Annotations.EMPTY, genericRefClass, listOf(TypeProjectionImpl(Variance.INVARIANT, typeParameterType)))
}
@@ -182,7 +182,7 @@ class JvmSharedVariablesManager(val builtIns: KotlinBuiltIns) : SharedVariablesM
private fun getSharedVariableType(valueType: KotlinType): KotlinType =
primitiveRefDescriptorProviders[getPrimitiveType(valueType)]?.refType ?:
objectRefDescriptorsProvider.getRefType(valueType)
private fun getPrimitiveType(type: KotlinType): PrimitiveType? =
when {
KotlinBuiltIns.isBoolean(type) -> PrimitiveType.BOOLEAN

View File

@@ -46,7 +46,7 @@ sealed class NewTypeVariable(builtIns: KotlinBuiltIns, name: String) {
// member scope is used if we have receiver with type TypeVariable(T)
// todo add to member scope methods from supertypes for type variable
val defaultType: SimpleType = KotlinTypeFactory.simpleType(
val defaultType: SimpleType = KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope(
Annotations.EMPTY, freshTypeConstructor, arguments = emptyList(),
nullable = false, memberScope = builtIns.any.unsubstitutedMemberScope)
@@ -61,4 +61,4 @@ class TypeVariableForLambdaReturnType(
val lambdaArgument: LambdaKotlinCallArgument,
builtIns: KotlinBuiltIns,
name: String
) : NewTypeVariable(builtIns, name)
) : NewTypeVariable(builtIns, name)

View File

@@ -5,6 +5,8 @@ where advanced options include:
or all modules on the module path if <module> is ALL-MODULE-PATH
-Xbuild-file=<path> Path to the .xml build file to compile
-Xcompile-java Reuse javac analysis and compile Java source files
-Xnormalize-constructor-calls={disable|enable|preserve-class-initialization}
Normalize constructor calls (disable: don't normalize; enable: normalize; preserve-class-initialization: normalize preserving class initialization order), default is disable
-Xdump-declarations-to=<path> Path to JSON file to dump Java to Kotlin declaration mappings
-Xmultifile-parts-inherit Compile multifile classes as a hierarchy of parts and facade
-Xmodule-path=<path> Paths where to find Java 9+ modules

View File

@@ -0,0 +1,41 @@
// TARGET_BACKEND: JVM
// WITH_RUNTIME
// KOTLIN_CONFIGURATION_FLAGS: CONSTRUCTOR_CALL_NORMALIZATION_MODE=disable
// FILE: test.kt
fun box(): String {
Foo(
logged("i", 1.let { it }),
logged("j",
Foo(
logged("k", 2.let { it }),
null
)
)
)
val result = log.toString()
if (result != "<clinit>ik<init>j<init>") return "Fail: '$result'"
return "OK"
}
// FILE: util.kt
val log = StringBuilder()
fun <T> logged(msg: String, value: T): T {
log.append(msg)
return value
}
// FILE: Foo.kt
class Foo(i: Int, j: Foo?) {
init {
log.append("<init>")
}
companion object {
init {
log.append("<clinit>")
}
}
}

View File

@@ -0,0 +1,41 @@
// TARGET_BACKEND: JVM
// WITH_RUNTIME
// KOTLIN_CONFIGURATION_FLAGS: CONSTRUCTOR_CALL_NORMALIZATION_MODE=enable
// FILE: test.kt
fun box(): String {
Foo(
logged("i", 1.let { it }),
logged("j",
Foo(
logged("k", 2.let { it }),
null
)
)
)
val result = log.toString()
if (result != "ik<clinit><init>j<init>") return "Fail: '$result'"
return "OK"
}
// FILE: util.kt
val log = StringBuilder()
fun <T> logged(msg: String, value: T): T {
log.append(msg)
return value
}
// FILE: Foo.kt
class Foo(i: Int, j: Foo?) {
init {
log.append("<init>")
}
companion object {
init {
log.append("<clinit>")
}
}
}

View File

@@ -0,0 +1,41 @@
// TARGET_BACKEND: JVM
// WITH_RUNTIME
// KOTLIN_CONFIGURATION_FLAGS: CONSTRUCTOR_CALL_NORMALIZATION_MODE=preserve-class-initialization
// FILE: test.kt
fun box(): String {
Foo(
logged("i", 1.let { it }),
logged("j",
Foo(
logged("k", 2.let { it }),
null
)
)
)
val result = log.toString()
if (result != "<clinit>ik<init>j<init>") return "Fail: '$result'"
return "OK"
}
// FILE: util.kt
val log = StringBuilder()
fun <T> logged(msg: String, value: T): T {
log.append(msg)
return value
}
// FILE: Foo.kt
class Foo(i: Int, j: Foo?) {
init {
log.append("<init>")
}
companion object {
init {
log.append("<clinit>")
}
}
}

View File

@@ -1,6 +1,5 @@
// WITH_RUNTIME
// WITH_COROUTINES
// IGNORE_BACKEND: JS
import helpers.*
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
@@ -49,7 +48,7 @@ fun box(): String {
}
}
if (logger.toString() != "A.<clinit>;args;A.<init>;") {
if (logger.toString() != "args;A.<clinit>;A.<init>;") {
return "Fail: '$logger'"
}

View File

@@ -0,0 +1,24 @@
interface IFoo {
fun foo(): String
}
interface IBar {
fun bar(): String
}
abstract class Base(val x: IFoo)
enum class Test : IFoo, IBar {
FOO {
// FOO referenced from inner class constructor with uninitialized 'this'
inner class Inner : Base(FOO)
val z = Inner()
override fun foo() = "OK"
override fun bar() = z.x.foo()
}
}
fun box() = Test.FOO.bar()

View File

@@ -0,0 +1,24 @@
interface IFoo {
fun foo(): String
}
interface IBar {
fun bar(): String
}
enum class Test : IFoo, IBar {
FOO {
// FOO referenced from inner class constructor with initialized 'this'
inner class Inner {
val fooFoo = FOO.foo()
}
val z = Inner()
override fun foo() = "OK"
override fun bar() = z.fooFoo
}
}
fun box() = Test.FOO.bar()

View File

@@ -0,0 +1,23 @@
interface IFoo {
fun foo(): String
}
interface IBar {
fun bar(): String
}
enum class Test : IFoo, IBar {
FOO {
// FOO referenced from inner class constructor with initialized 'this',
// in delegate initializer
inner class Inner : IFoo by FOO
val z = Inner()
override fun foo() = "OK"
override fun bar() = z.foo()
}
}
fun box() = Test.FOO.bar()

View File

@@ -0,0 +1,14 @@
enum class Test(val x: String, val closure1: () -> String) {
FOO("O", { FOO.x }) {
override val y: String = "K"
val closure2 = { y } // Implicit 'FOO'
override val z: String = closure2()
};
abstract val y: String
abstract val z: String
fun test() = closure1() + z
}
fun box() = Test.FOO.test()

View File

@@ -0,0 +1,14 @@
enum class Test(val x: String, val closure1: () -> String) {
FOO("O", run { { FOO.x } }) {
override val y: String = "K"
val closure2 = { y } // Implicit 'FOO'
override val z: String = closure2()
};
abstract val y: String
abstract val z: String
fun test() = closure1() + z
}
fun box() = Test.FOO.test()

View File

@@ -0,0 +1,8 @@
enum class Foo(
val x: String,
val callback: () -> String
) {
FOO("OK", { FOO.x })
}
fun box() = Foo.FOO.callback()

View File

@@ -0,0 +1,17 @@
interface Callback {
fun invoke(): String
}
enum class Foo(
val x: String,
val callback: Callback
) {
FOO(
"OK",
object : Callback {
override fun invoke() = FOO.x
}
)
}
fun box() = Foo.FOO.callback.invoke()

View File

@@ -0,0 +1,17 @@
interface IFn {
operator fun invoke(): String
}
abstract class Base(val fn: IFn)
class Host {
companion object : Base(
object : IFn {
override fun invoke(): String = Host.ok()
}
) {
fun ok() = "OK"
}
}
fun box() = Host.Companion.fn()

View File

@@ -0,0 +1,9 @@
class Test {
companion object {
fun ok() = "OK"
val x = run { Test.ok() }
fun test() = x
}
}
fun box() = Test.test()

View File

@@ -0,0 +1,9 @@
abstract class Base(val fn: () -> String)
class Host {
companion object : Base(run { { Host.ok() } }) {
fun ok() = "OK"
}
}
fun box() = Host.Companion.fn()

View File

@@ -0,0 +1,9 @@
abstract class Base(val fn: () -> String)
class Host {
companion object : Base({ Host.ok() }) {
fun ok() = "OK"
}
}
fun box() = Host.Companion.fn()

View File

@@ -0,0 +1,17 @@
interface IFn {
operator fun invoke(): String
}
abstract class Base(val fn: IFn)
interface Host {
companion object : Base(
object : IFn {
override fun invoke(): String = Host.ok()
}
) {
fun ok() = "OK"
}
}
fun box() = Host.Companion.fn()

View File

@@ -0,0 +1,9 @@
interface Test {
companion object {
fun ok() = "OK"
val x = run { Test.ok() }
fun test() = x
}
}
fun box() = Test.test()

View File

@@ -0,0 +1,9 @@
abstract class Base(val fn: () -> String)
interface Host {
companion object : Base(run { { Host.ok() } }) {
fun ok() = "OK"
}
}
fun box() = Host.Companion.fn()

View File

@@ -0,0 +1,9 @@
abstract class Base(val fn: () -> String)
interface Host {
companion object : Base({ Host.ok() }) {
fun ok() = "OK"
}
}
fun box() = Host.Companion.fn()

View File

@@ -0,0 +1,15 @@
interface IFn {
operator fun invoke(): String
}
abstract class Base(val fn: IFn)
object Test : Base(
object : IFn {
override fun invoke(): String = Test.ok()
}
) {
fun ok() = "OK"
}
fun box() = Test.fn()

View File

@@ -0,0 +1,7 @@
object Test {
fun ok() = "OK"
val x = run { Test.ok() }
fun test() = x
}
fun box() = Test.test()

View File

@@ -0,0 +1,7 @@
abstract class Base(val fn: () -> String)
object Test : Base(run { { Test.ok() } }) {
fun ok() = "OK"
}
fun box() = Test.fn()

View File

@@ -0,0 +1,7 @@
abstract class Base(val fn: () -> String)
object Test : Base({ Test.ok() }) {
fun ok() = "OK"
}
fun box() = Test.fn()

View File

@@ -0,0 +1,23 @@
fun abs(x: Int) = if (x < 0) -x else x
fun abs(x: Long) = if (x < 0) -x else x
fun test1() =
5 in abs(-1) .. 10
fun test2() =
5 in 1 .. abs(-10)
fun test3() =
5L in abs(-1L) .. 10L
fun test4() =
5L in 1L .. abs(-10L)
fun box(): String {
if (!test1()) return "Fail 1"
if (!test2()) return "Fail 2"
if (!test3()) return "Fail 3"
if (!test4()) return "Fail 4"
return "OK"
}

View File

@@ -0,0 +1,10 @@
enum class Build { Debug, Release }
fun applySomething(build: Build) = when (build) {
Build.Debug -> "OK"
Build.Release -> "fail"
}
val rv = applySomething(Build.Debug)
// expected: rv: OK

View File

@@ -0,0 +1,9 @@
// See KT-20959
enum class Foo {;
companion object {
val x = <!DEBUG_INFO_LEAKING_THIS!>foo<!>() // there should be no UNINITIALIZED_ENUM_COMPANION
private fun foo() = "OK"
}
}

View File

@@ -0,0 +1,27 @@
package
public final enum class Foo : kotlin.Enum<Foo> {
private constructor Foo()
public final override /*1*/ /*fake_override*/ val name: kotlin.String
public final override /*1*/ /*fake_override*/ val ordinal: kotlin.Int
protected final override /*1*/ /*fake_override*/ fun clone(): kotlin.Any
public final override /*1*/ /*fake_override*/ fun compareTo(/*0*/ other: Foo): kotlin.Int
public final override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
protected/*protected and package*/ final override /*1*/ /*fake_override*/ /*isHiddenForResolutionEverywhereBesideSupercalls*/ fun finalize(): kotlin.Unit
public final override /*1*/ /*fake_override*/ /*isHiddenForResolutionEverywhereBesideSupercalls*/ fun getDeclaringClass(): java.lang.Class<Foo!>!
public final override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
public companion object Companion {
private constructor Companion()
public final val x: kotlin.String
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
private final fun foo(): kotlin.String
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
}
// Static members
public final /*synthesized*/ fun valueOf(/*0*/ value: kotlin.String): Foo
public final /*synthesized*/ fun values(): kotlin.Array<Foo>
}

View File

@@ -0,0 +1,19 @@
// FILE: MyAnnotation.java
public @interface MyAnnotation {
}
// FILE: MyAnnoClass.java
public class MyAnnoClass implements MyAnnotation {
//...
}
// FILE: main.kt
val ann: MyAnnotation = MyAnnoClass()
fun foo(x: MyAnnoClass) {
bar(x)
}
fun bar(y: MyAnnotation) {
y.hashCode()
}

View File

@@ -0,0 +1,19 @@
package
public val ann: MyAnnotation
public fun bar(/*0*/ y: MyAnnotation): kotlin.Unit
public fun foo(/*0*/ x: MyAnnoClass): kotlin.Unit
public open class MyAnnoClass : MyAnnotation {
public constructor MyAnnoClass()
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
}
public final annotation class MyAnnotation : kotlin.Annotation {
public constructor MyAnnotation()
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
}

View File

@@ -0,0 +1,17 @@
// FILE: A.java
import org.checkerframework.checker.nullness.qual.*;
public class A {
@NonNull
public Object foo() { return null; }
}
// FILE: B.java
public class B {
public static void assertNonNull(Object x) {}
}
// FILE: main.kt
fun main() {
A()
B.assertNonNull(null)
}

View File

@@ -0,0 +1,21 @@
package
public fun main(): kotlin.Unit
public open class A {
public constructor A()
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
@org.checkerframework.checker.nullness.qual.NonNull public open fun foo(): @org.checkerframework.checker.nullness.qual.NonNull kotlin.Any
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
}
public open class B {
public constructor B()
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
// Static members
public open fun assertNonNull(/*0*/ x: kotlin.Any!): kotlin.Unit
}

View File

@@ -0,0 +1,8 @@
>>> enum class Build { Debug, Release }
>>> fun applySomething(build: Build) = when (build) {
... Build.Debug -> "OK"
... Build.Release -> "fail"
...}
>>> applySomething(Build.Debug)
OK

View File

@@ -3,7 +3,7 @@ package localObjects {
~x~val x : Int
}
class Foo {
open class Foo {
~foo()~fun foo() : Int
}

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