Compare commits

...

145 Commits

Author SHA1 Message Date
Nikolay Krasko
9bfc3402fe Reorder the list of previous releases 2017-11-27 15:09:33 +03:00
Nikolay Krasko
fb39961b95 Update changelog for 1.2.0 2017-11-27 15:03:24 +03:00
Vyacheslav Gerasimov
9a771d38c4 Move KDsl gradleFrameworkSupport and moduleBuilder to gradle.xml
#KT-21236 Fixed Target versions 1.2.20
2017-11-27 12:20:50 +01:00
Sergey Igushkin
aa3fd0db18 Fix missing sourcesJar & javadocJar in kotlin-annotations-android 2017-11-27 13:40:05 +03:00
Dmitry Jemerov
a284fdf329 Send API version instead of build number for plugin update checks
#KT-21263 Fixed

(cherry picked from commit 200d7f0)
2017-11-24 19:44:56 +01:00
Alexey Tsvetkov
38cd527050 Rebuild when language/api version is changed (JPS)
#KT-20757 fixed
2017-11-23 19:58:33 +03:00
Alexey Tsvetkov
977da95aee Fix default value for api version string in IC meta info file 2017-11-23 19:58:33 +03:00
Nikolay Krasko
9f2dbb05c0 Update changelog for 1.2-RC2 2017-11-23 15:37:51 +03:00
Dmitry Jemerov
4286cceda8 Reorder imports to avoid merge conflict 2017-11-22 18:27:29 +01:00
Mikhail Glukhikh
c4b33b0822 Add fallback flag for legacy var smart casts after try #KT-21377 Fixed
(cherry picked from commit 078c27e)
2017-11-22 19:18:45 +03:00
Dmitry Jemerov
54fe95f5d5 Don't crash with old versions of Android Gradle plugin
#KT-21383 Fixed

(cherry picked from commit e00cc5a)
2017-11-22 15:20:03 +01:00
Dmitry Jemerov
40a098f239 Don't pack any kotlin stdlib classes into kotlin-plugin.jar
#KT-21395 Fixed

(cherry picked from commit 3fbc5ab)
2017-11-22 15:19:52 +01:00
Ilya Chernikov
dcf3039f01 Restore a file missing due to the cherrypicking glitch 2017-11-22 14:04:18 +01:00
Yan Zhulanow
c88f3a9c08 Kapt: Do not add duplicating library entries in project importing 2017-11-22 02:00:22 +09:00
Nikolay Krasko
66550e1bf5 Don't force configure with kotlin-jdk artifacts for early versions (KT-21028)
#KT-21028 Fixed
2017-11-21 16:22:14 +03:00
Ilya Chernikov
98f83be9b2 Bring back filtering of jna and shading of jline in embeddable compiler
they were lost during the migration to gradle

(cherry picked from commit 126a6a8)
2017-11-20 19:56:26 +01:00
Mikhail Glukhikh
f005b45233 Catch InvalidModuleException from getModality() in icon provider
Related to KT-20986

(cherry picked from commit 4c583c5)
2017-11-20 16:55:12 +03:00
Mikhail Glukhikh
e7f648653d Throw InvalidModuleException in assertValid() instead of standard ISE
(cherry picked from commit e53cedb)
2017-11-20 16:51:16 +03:00
Ilya Chernikov
9464b10ace Add kotlin-annotation-processing-embeddable, publish base kapt3 as kotlion-annotation-processing
(cherry picked from commit 148d4e4)
2017-11-19 15:19:35 +01:00
Mikhael Bogdanov
a4d81ba206 Switch DEFAULT_METHOD_CALL_FROM_JAVA6_TARGET according to LL
(cherry picked from commit a547019)
2017-11-17 16:43:32 +01:00
Mikhail Glukhikh
b6bc8eb28d Downgrade "use expression body" inspection to INFORMATION default level 2017-11-17 17:06:28 +03:00
Ilya Gorbunov
4ae5a14e52 Write deployVersion into build.txt (for 1.2.0 and 1.2.10)
(cherry picked from commit 25483ca)
2017-11-16 19:11:58 +03:00
Alexey Tsvetkov
91891fc213 Avoid deserializing .kotlin_module as class proto
#KT-20184 fixed
2017-11-16 14:49:39 +03:00
Alexander Udalov
2f7110d91b Restore and deprecate JvmFileClassesProvider.getFileClassInternalName
#KT-21270 Fixed

(cherry picked from commit c55ac55526)
2017-11-16 12:24:29 +01:00
Denis Zharkov
41ca822170 Fix KNPE caused by optimizations in control-flow analysis
The problem is that when performing full analysis we do it in
a backward order while result for trivial vals is filled
in a forward one.

It turns out that reversedInstuctions might return a superset of
forward traversed instructions, e.g. in case of dead code in lambda.

At the same time result for trivial vals is constant
for any instruction, thus we can just return its constant value
and use it in the full analysis

 #KT-20895 Fixed
2017-11-14 16:39:53 +03:00
Dmitry Jemerov
0cfa11f98f Generate 'expectedBy' dependency instead of 'implement' (KT-21006)
(cherry picked from commit f67e01d)
2017-11-14 14:26:57 +01:00
Mikhael Bogdanov
bfcb4a5ee4 Always do stack spilling during inline cause of dex problem
Dex issue: https://issuetracker.google.com/issues/68796377

  #KT-20844 Fixed

(cherry picked from commit dff6e94)
2017-11-13 17:02:36 +01:00
Sergey Igushkin
11f17519b4 Fix configuration of Gradle plugins publishing to the plugins portal.
(cherry picked from commit 8b60510)
2017-11-13 19:01:21 +03:00
Yan Zhulanow
576f85032f Attempt to fix Gradle project importing error on older Gradle versions (KT-20967) 2017-11-14 00:05:36 +09:00
Ilya Gorbunov
e382182b87 Introduce deployRepo parameter to override deploy-repo set by teamcity
Currently it isn't possible to do that from command line.

(cherry picked from commit 598dc1a)
2017-11-10 00:21:03 +03:00
Ilya Gorbunov
9be7c63a56 Fix intellij-community revision JFlex is downloaded from
Because it was removed in master

(cherry picked from commit e801390)
2017-11-09 18:19:17 +03:00
Anton Bannykh
de9448ff00 JS: use ANT replace task to set $version
Needed make kotlin-test depend on the same version of kotlin

(cherry picked from commit 4d12426145)
2017-11-09 15:16:09 +03:00
Ilya Gorbunov
a4eccab182 Strengthen deprecation for CharSequence.size in JS
(cherry picked from commit a005f48)
2017-11-09 14:49:03 +03:00
Ilya Gorbunov
20fca3e731 Remove deprecated pairwise function
It was replaced with zipWithNext.

(cherry picked from commit 9305903)
2017-11-09 14:49:03 +03:00
Simon Ogorodnik
b283544cbe Improve diagnosticMissingPackageFragment reporting post-review 2017-11-08 19:43:52 +03:00
Alexey Sedunov
8dddfc5390 Misc: Wrap function/property search in read action
This fixes some assertion errors
2017-11-07 20:32:37 +03:00
Nicolay Mitropolsky
c05f2581dc UAST: Complex test data moved to separate file (KT-20990)
(cherry picked from commit fab8187)
2017-11-07 17:42:37 +01:00
Nicolay Mitropolsky
db28e34996 UAST: yet another fight with string literals in string literals (KT-20990)
(cherry picked from commit 9730d50)
2017-11-07 17:42:21 +01:00
Nicolay Mitropolsky
416470d901 UAST: correct processing of string literals in string literals (KT-20990)
(cherry picked from commit a11cf25)
2017-11-07 17:41:56 +01:00
Nikolay Krasko
ef76ab47af Increase stub version because of change in overload sorting
See commit f197f36e23
2017-11-07 15:47:36 +03:00
Nikolay Krasko
52ea816d9c Restrict 172 plugin to 172 ide only 2017-11-07 12:33:11 +03:00
Pavel V. Talanov
1c690ee27c Fix light class exception on empty multifile facade
Fix generating multifile facade with all members private (in bytecode)
leading to delegate not being generated for corresponding light class

 #KT-20966 Fixed
2017-11-04 16:46:20 +03:00
Nikolay Krasko
f197f36e23 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-04 16:39:03 +03:00
Alexey Sedunov
a0d4f81931 Move: Fix applicability check in IDEA 173
(cherry picked from commit d798ae8)
2017-11-04 16:39:02 +03:00
Mikhail Glukhikh
59a644e04a Choose implementing module correctly in "create actual fix"
Take implements / expectedBy dependency into account
So #KT-20803 Fixed

(cherry picked from commit 561d774)
2017-11-04 16:39:01 +03:00
Mikhail Glukhikh
f0afa9d9be Enhance AbstractQuickFixMultiModuleTest
Handle same files at different source roots correctly

(cherry picked from commit f0da585)
2017-11-04 16:39:00 +03:00
Nikolay Krasko
ef5bf215bf Fix accessing nullable location() method 2017-11-04 16:38:59 +03:00
Ilya Gorbunov
06fb3f6ade Minor clarification in changelog 2017-11-02 19:21:44 +03:00
Vyacheslav Gerasimov
2518a61702 Configure Kotlin: add mavenCentral() to repositories
Since kotlin stdlib depends on artifacts from mavenCentral() we should add it
 #KT-18719 Fixed
2017-11-02 15:28:35 +03:00
Nikolay Krasko
b7cc8b2627 Update changelog 2017-11-01 17:28:09 +03:00
Nikolay Krasko
0f07e7dc04 Update changelog for 1.2-rc 2017-10-31 18:58:36 +03:00
Nikolay Krasko
7145007c77 Revert "Move: Fix applicability check in IDEA 173"
This reverts commit d95d56838b.
2017-10-31 16:45:31 +03:00
Alexey Sedunov
d95d56838b Move: Fix applicability check in IDEA 173
(cherry picked from commit d798ae8)
2017-10-31 16:12:15 +03:00
Alexey Sedunov
3fcbb4307f Misc: Fix quickfix test data
(cherry picked from commit e65adeb)
2017-10-30 16:14:15 +03:00
Alexey Sedunov
22de8cac5e Misc: Update default language version in Maven import test
(cherry picked from commit d89a946)
2017-10-30 16:14:15 +03:00
Alexey Sedunov
ed7b563cb7 Misc: Update member hierarchy test data to include new stdlib classes
(cherry picked from commit d6ee9c9)
2017-10-30 16:14:14 +03:00
Alexey Sedunov
32c555fbe3 Misc: Drop test for implementing abstract members in expect-class
The "not implemented" error is not reported for such classes, so
quick fix is not available anymore (see KT-16099)

(cherry picked from commit 83b1040)
2017-10-30 16:14:14 +03:00
Alexey Sedunov
e1f3b4c2de Misc: Update configuration test data
(cherry picked from commit 997aa12)
2017-10-30 16:14:14 +03:00
Alexey Sedunov
cf445ab977 Create from Usage: Work around type renaming
This fixes test failure after changes in KotlinTypeFactory

(cherry picked from commit 2883a92)
2017-10-30 16:14:14 +03:00
Simon Ogorodnik
22604abfc7 Improve diagnosticMissingPackageFragment reporting
Single execution path to report missing package fragment problems

Split failures on PluginDeclarationProviderFactory site by
known reasons to improve exception analysis
2017-10-30 16:11:41 +03:00
Alexey Sedunov
c394037339 Misc: Update keyword completion test data
It reflects top-level lateinit variables available since 1.2
Fixes four keyword completion tests

(cherry picked from commit b8fb002)
2017-10-30 13:51:58 +03:00
Denis Zharkov
55209fd60f Fix incorrect UNINITIALIZED_ENUM_COMPANION diagnostic
#KT-20959 Fixed
2017-10-27 09:37:03 +03:00
Ilya Gorbunov
32de211e88 Remove IS_PRE_RELEASE flag 2017-10-26 17:29:09 +03:00
Dmitry Petrov
7c3d079eeb 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 41b1594)
2017-10-26 16:10:51 +03:00
Ilya Gorbunov
afd83dc86e Finalize math function parameter names
#KT-4900

(cherry picked from commit ace9d0d)
2017-10-25 22:01:19 +03:00
Alexey Andreev
79925cfe2f JS: raise metadata version due to incompatible changes in 1.2 runtime 2017-10-25 20:27:18 +03:00
Alexey Andreev
99ab812cee JS: add getFunctionById intrinsic 2017-10-25 20:27:09 +03:00
Alexey Andreev
1506a72fc3 JS: add intrinsic for !!. Use it instead of ternary conditionals
See KT-2976
2017-10-25 20:27:01 +03:00
Vyacheslav Gerasimov
66bc20ccf9 Remove GradleProjectImportProvider and GradleProjectOpenProcessor
(cherry picked from commit b27334d)
2017-10-25 17:56:40 +03:00
Dmitry Jemerov
292800c295 Add formatting rule for array literals
#KT-19599 Fixed

(cherry picked from commit 9940327)
2017-10-25 16:55:44 +02:00
Pavel V. Talanov
fa18ac4690 IDELightClassContexts: fix light member mismatch on InlineOnly members
#KT-20922 Fixed
 #KT-20906 Fixed
2017-10-25 17:44:07 +03:00
Alexander Udalov
4e01178e7b Use ServiceLoader instead of IntelliJ extensions for DefaultErrorMessages
#KT-10473 Fixed

(cherry picked from commit 1a8be635b9)
2017-10-25 16:35:31 +02:00
Alexander Udalov
7b0f1eadd3 Do not use DefaultErrorMessages.Extension as IntelliJ extension in plugins
(cherry picked from commit 1c6dce3674)
2017-10-25 16:35:31 +02:00
Nikolay Krasko
65d4ea40f4 Configure new projects with kotlin-stdlib-jdk7/8 (KT-20286)
No migration for old projects has been added yet.

 #KT-20286 Fixed
2017-10-25 17:30:30 +03:00
Ilya Chernikov
7af997424f Fix "base" jar and "public" jar tasks archive name conflict
fixes KT-20877

(cherry picked from commit caca7c6)
2017-10-25 14:16:12 +02:00
Nicolay Mitropolsky
881316d2af UAST: Fix for unsafe cast for class initializer (EA-109918)
(cherry picked from commit 1fa5152)
2017-10-25 14:26:36 +03:00
Alexander Udalov
2181290c64 Fix test data for empty LHS vs isInitialized
Ignore the "property imported from object" part on JS

(cherry picked from commit e73760d4ff)
2017-10-25 12:13:23 +02:00
Alexey Tsvetkov
6f82d464c1 Turn off IC for multiplatform projects by default
Multiplatform IC is enabled when a corresponding platform property is enabled
and 'kotlin.incremental.multiplatform' is set to `true`.

See KT-20840
2017-10-25 01:13:26 +03:00
Alexey Tsvetkov
c6d232a16e Perform non-IC build when JS lib is changed 2017-10-24 16:30:21 +03:00
Dmitry Jemerov
edca38584e Show "No SDK configured" notification only in JVM modules
(cherry picked from commit 499cfb5)
2017-10-24 15:13:41 +02:00
Dmitry Jemerov
73cf115bd7 Add dependency to kotlin-test-annotations-common to new MP projects
#KT-20833 Fixed

(cherry picked from commit 537600b)
2017-10-24 15:13:31 +02:00
Dmitry Petrov
e308dd02d8 Add box tests for new nullability assertions
(cherry picked from commit 0a84c3f)
2017-10-24 16:03:23 +03:00
Dmitry Petrov
2058b5d750 STRICT_JAVA_NULLABILITY_ASSERTIONS directive in box tests
(cherry picked from commit 44e4c3f)
2017-10-24 16:03:23 +03:00
Dmitry Petrov
a284f9d28b Minor: move nullability assertion tests javaInterop/notNullAssertions
(cherry picked from commit 5c62a14)
2017-10-24 16:03:23 +03:00
Dmitry Petrov
85e3cded24 Sanitize declaration return types
On JVM, strip @EnhancedNullability annotation from inferred types for
functions, properties, and local variables, so that these annotations
do not "escape" from Kotlin declarations.

(cherry picked from commit 3be2143)
2017-10-24 16:03:23 +03:00
Dmitry Petrov
d6d785c2bf Generate assertions for expressions with enhanced nullability
If an expression with type annotated with @EnhancedNullability is used
as a function expression body, or property initializer, or variable
initializer, and corresponding type can not contain null,
generate nullability assertions for this expression.

(cherry picked from commit 640914d)
2017-10-24 16:03:23 +03:00
Dmitry Petrov
8c751b402f Language feature for nullability assertions on enhanced nullability
(cherry picked from commit 06bdc1f)
2017-10-24 16:03:23 +03:00
Mikhail Glukhikh
7124c690c6 Make editor in SelfTargetingIntention.invoke nullable
This prevents EA-105844 from happening.
Should fix KT-20899.

(cherry picked from commit 5a6f22c)
2017-10-24 15:54:34 +03:00
Dmitry Petrov
7dcb68bccd Mark operands of POP2 as don't touch in unused expression elimination
Fixes KT-20879.

(cherry picked from commit f23dfdc)
2017-10-24 15:39:24 +03:00
Anton Bannykh
059133ea06 JPS JS: fix friend path detection in projects imported from Gradle (KT-18963 fixed)
(cherry picked from commit b2e53644a5)
2017-10-24 15:27:17 +03:00
Alexander Udalov
766ba407fd Fix isInitialized receiver generation for empty LHS
#KT-20774 Fixed

(cherry picked from commit bafc75ade4)
2017-10-24 13:15:03 +02:00
Alexey Andreev
200fd2852e JS: prohibit declaration names that clash with JS builtin functions
See KT-18095, KT-17475, KT-18105, KT-5259
2017-10-24 12:34:31 +03:00
Alexey Andreev
3000ee65b4 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 12:34:20 +03:00
Alexey Andreev
f9a8113d1b Support generation of relative path in JS source maps in JPS builder
See KT-20820
2017-10-24 12:34:03 +03:00
Alexey Andreev
c40572548f 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 12:33:40 +03:00
Dmitry Petrov
1142cb1486 Remove CLI help on 'preserve-class-initialization' mode
See https://youtrack.jetbrains.com/issue/KT-19532#comment=27-2492178

(cherry picked from commit 68870a1)
2017-10-24 09:38:43 +03:00
Simon Ogorodnik
9a1681087f 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:13:24 +03:00
Mikhail Glukhikh
09ead0edad Fix search scope during inlining #KT-20251 Fixed
Do not use KotlinSourceFilterScope because build scripts are lost otherwise

(cherry picked from commit 1b0421d)
2017-10-23 19:27:54 +03:00
Dmitry Jemerov
97616416dc Correctly propagate dependencies in multiplatform projects with Android
(cherry picked from commit 81615fa)
2017-10-23 16:27:27 +02:00
Dmitry Jemerov
55e8e84063 Rename KotlinPlatformGradleDetector to KotlinGradleModelFacade
(cherry picked from commit cc85ac4)
2017-10-23 16:27:27 +02:00
Dmitry Jemerov
216bdcbd41 Ignore "module per source set" option in Android projects
(cherry picked from commit f589c9b)
2017-10-23 16:27:27 +02:00
Dmitry Jemerov
f2628d4f70 Use binary path instead of name to locate libraries from Android deps
(cherry picked from commit 14a30e0)
2017-10-23 16:27:27 +02:00
Nicolay Mitropolsky
97399b99ee AbstractUastTest: findUElementByTextFromPsi refactored for readability
(cherry picked from commit 8a34c48)
2017-10-23 17:00:32 +03:00
Nicolay Mitropolsky
71867c4b73 UastKotlinPsiVariable: factory methods reformatting
(cherry picked from commit 8e17bab)
2017-10-23 17:00:01 +03:00
Nicolay Mitropolsky
f9449308d7 UAST: Fix for unsafe cast for annotation (EA-109738)
(cherry picked from commit 299a4b7)
2017-10-23 16:59:41 +03:00
Nicolay Mitropolsky
478611eb52 UAST: tests utils for bottom-top finding UElements moved to AbstractUastTest.kt
(cherry picked from commit c5fa7fb217)
2017-10-23 16:59:00 +03:00
nickl
64e1c88ac1 UastKotlinPsiVariable psiParent made lazy to eliminate recursion when building UAST parents
(cherry picked from commit 6a659f3)
2017-10-23 16:50:40 +03:00
Nikolay Krasko
06cb9127f4 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-21 00:41:40 +03:00
Nikolay Krasko
0d80bcc8cf TypeDeclarationProvider should return null for irrelevant symbols
Otherwise other providers won't be checked.
2017-10-21 00:41:39 +03:00
Denis Zharkov
db0d95eea8 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:10:17 +03:00
Anton Bannykh
fd839dcb05 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:47:33 +03:00
Mikhail Glukhikh
81f53bb1e5 Related to DSGN-4505: change expect / actual icons to the new ones
(cherry picked from commit 26c1aec5df)
2017-10-20 18:14:30 +03:00
Ilya Chernikov
88f061c152 Add compiler proguard rule for keeping ProgressManager used in webdemo
(cherry picked from commit 5284db8)
2017-10-19 14:19:33 +02:00
Alexey Tsvetkov
8a3a4df93a Compile kotlin-android-extensions-runtime for JDK 1.6 2017-10-18 17:45:56 +03:00
Ilya Gorbunov
2f1d4c15c9 Fixes in changelog around libraries and multiplatform projects
(cherry picked from commit 83f1fe7)
2017-10-18 08:45:20 +03:00
Dmitry Petrov
4c3b9d58fb Minor updates to 1.2-Beta2 changelog
- move KT-20217 to "Tools. Gradle" section;
- add KT-16926 to "IDE" section
  (reopened and fixed in 1.2-Beta2)
2017-10-17 19:35:31 +04:00
Alexey Tsvetkov
46b005bafc 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:34:17 +03:00
Ilya Gorbunov
5d4d444f97 Enable publishing for kotlin-annotations-android
(cherry picked from commit eaa3b3ccf0)
2017-10-17 18:19:44 +03:00
Stanislav Erokhin
7a5051128a Disable annotation processor for javac by default in whole project
(cherry picked from commit 0a2421d)
2017-10-17 17:28:38 +03:00
Sergey Igushkin
fa2d276718 Use runtimeJar configuration instead of default for plugin markers.
(cherry picked from commit d453a2f)
2017-10-17 15:23:49 +03:00
Dmitry Petrov
7b873eb8ce Update changelog for 1.2-Beta2 2017-10-17 15:17:29 +03:00
Alexey Sedunov
979c7c06ef MPP: Fix implementing module search in Gradle runner
(cherry picked from commit 9fe0681)
2017-10-16 23:59:21 +03:00
Alexey Sedunov
6e0e4a634e Gradle: Support 'expectedBy' configuration
(cherry picked from commit db34bae)
2017-10-16 23:59:09 +03:00
Alexey Sedunov
c7bc8b280c Gradle: Add dependencies for indirectly implemented modules
#KT-16926 Fixed

(cherry picked from commit a2a8335)
2017-10-16 23:58:45 +03:00
Sergey Igushkin
d363f5be7e Fix missing ReflectUtil, call the ctor through reflection manually.
(cherry picked from commit 0a80852)
2017-10-16 22:03:28 +02:00
Sergey Igushkin
e8b944ebbf Add android-extensions-compiler content to kotlin-android-extensions
(cherry picked from commit e94e62b)
2017-10-16 22:02:30 +02:00
Ilya Chernikov
ead2cb374a Fix dependencies rewriting and gradle integration tests after applying rewriting
(cherry picked from commit 431d47a)
2017-10-16 22:02:14 +02:00
Ilya Chernikov
ba040ebd61 Use rewriteDeps task on the projects with runtime dependency on embeddable compiler...
which are using shaded dependencies

(cherry picked from commit 050403d)
2017-10-16 22:01:44 +02:00
Ilya Chernikov
f3921a3d24 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-16 22:01:09 +02:00
Ilya Chernikov
2d50bef4f7 Remove original jar artifact from archives when adding a new one by runtimeJar tasks
(cherry picked from commit 5babf89)
2017-10-16 22:00:26 +02:00
Ilya Gorbunov
323ec39ac6 Do not pack build.txt into jars, leave it only in artifact zip bundles
(cherry picked from commit 13d6e96c2f)
2017-10-16 21:19:20 +03:00
Ilya Gorbunov
acb2850260 Remove maven poms that are no longer submodules of the main project
(cherry picked from commit 3bea095618)
2017-10-16 21:19:18 +03:00
Ilya Gorbunov
0da4bf4c08 Fork java compiler to ensure forkOptions are used
(cherry picked from commit 341edc3f86)
2017-10-16 21:19:16 +03:00
Ilya Gorbunov
765fe92165 Fix the obsolete form of -Xdump-declarations-to argument
(cherry picked from commit 93efc51843)
2017-10-16 21:19:14 +03:00
Pavel V. Talanov
ed4f3d3bf6 PluginDeclarationProviderFactory: improve diagnostic
Attempting to catch EA-103048
2017-10-16 19:25:39 +03:00
Alexey Andreev
7e49e17ce5 JS: fix behaviour of char-returning functions with multiple inheritance
See KT-19772
2017-10-16 19:07:58 +03:00
Mikhail Glukhikh
5052ae5cf8 Delay elvis-bound smart casts to version 1.3
(cherry picked from commit e73e4dc)
2017-10-16 19:05:14 +03:00
Mikhail Glukhikh
24e218afc8 Don't register safe cast type info for unstable values
Important: to be removed in 1.3
So #KT-20752 Fixed

(cherry picked from commit a55c6f0)
2017-10-16 19:05:03 +03:00
Alexander Udalov
ab6360a7d5 Write isPreRelease into JvmBuildMetaInfo for non-stable language version
(cherry picked from commit 03baa51f82)
2017-10-16 17:57:32 +02:00
Alexander Udalov
058b832b71 Extract shouldWritePreReleaseFlag(), use in JS as well as JVM
Fix the difference in behavior between JS and JVM

(cherry picked from commit 8b0b334601)
2017-10-16 17:57:28 +02:00
Alexander Udalov
b460b89df5 Mark class files as pre-release if language version > LATEST_STABLE
#KT-20547 Fixed

(cherry picked from commit 0510c553c3)
2017-10-16 17:57:25 +02:00
Alexander Udalov
c7253584c5 Extract skipPreReleaseCheck out of DeserializationConfiguration.skipMetadataVersionCheck
(cherry picked from commit 3665255a2b)
2017-10-16 17:57:20 +02:00
Stanislav Erokhin
c4e4298eac Support parenthesized left expression for ExpectedTypeFromCast
(cherry picked from commit b9fa8d4)
2017-10-16 18:46:17 +03:00
Denis Zharkov
e4b4475235 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:13:25 +03:00
Ilya Gorbunov
7cddd345f8 Set IS_PRE_RELEASE flag 2017-10-16 03:47:52 +03:00
489 changed files with 6411 additions and 7561 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -20,6 +20,7 @@ import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.config.ApiVersion
import org.jetbrains.kotlin.config.KotlinCompilerVersion
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.config.shouldWritePreReleaseFlag
import org.jetbrains.kotlin.load.java.JvmBytecodeBinaryVersion
import org.jetbrains.kotlin.load.kotlin.JvmMetadataVersion
@@ -58,18 +59,23 @@ data class JvmBuildMetaInfo(
}
}
fun JvmBuildMetaInfo(args: CommonCompilerArguments): JvmBuildMetaInfo =
JvmBuildMetaInfo(isEAP = KotlinCompilerVersion.isPreRelease(),
compilerBuildVersion = KotlinCompilerVersion.VERSION,
languageVersionString = args.languageVersion ?: LanguageVersion.LATEST_STABLE.versionString,
apiVersionString = args.apiVersion ?: ApiVersion.LATEST_STABLE.versionString,
coroutinesEnable = args.coroutinesState == CommonCompilerArguments.ENABLE,
coroutinesWarn = args.coroutinesState == CommonCompilerArguments.WARN,
coroutinesError = args.coroutinesState == CommonCompilerArguments.ERROR,
multiplatformEnable = args.multiPlatform,
metadataVersionMajor = JvmMetadataVersion.INSTANCE.major,
metadataVersionMinor = JvmMetadataVersion.INSTANCE.minor,
metadataVersionPatch = JvmMetadataVersion.INSTANCE.patch,
bytecodeVersionMajor = JvmBytecodeBinaryVersion.INSTANCE.major,
bytecodeVersionMinor = JvmBytecodeBinaryVersion.INSTANCE.minor,
bytecodeVersionPatch = JvmBytecodeBinaryVersion.INSTANCE.patch)
fun JvmBuildMetaInfo(args: CommonCompilerArguments): JvmBuildMetaInfo {
val languageVersion = args.languageVersion?.let((LanguageVersion)::fromVersionString) ?: LanguageVersion.LATEST_STABLE
return JvmBuildMetaInfo(
isEAP = languageVersion.shouldWritePreReleaseFlag(),
compilerBuildVersion = KotlinCompilerVersion.VERSION,
languageVersionString = languageVersion.versionString,
apiVersionString = args.apiVersion ?: languageVersion.versionString,
coroutinesEnable = args.coroutinesState == CommonCompilerArguments.ENABLE,
coroutinesWarn = args.coroutinesState == CommonCompilerArguments.WARN,
coroutinesError = args.coroutinesState == CommonCompilerArguments.ERROR,
multiplatformEnable = args.multiPlatform,
metadataVersionMajor = JvmMetadataVersion.INSTANCE.major,
metadataVersionMinor = JvmMetadataVersion.INSTANCE.minor,
metadataVersionPatch = JvmMetadataVersion.INSTANCE.patch,
bytecodeVersionMajor = JvmBytecodeBinaryVersion.INSTANCE.major,
bytecodeVersionMinor = JvmBytecodeBinaryVersion.INSTANCE.minor,
bytecodeVersionPatch = JvmBytecodeBinaryVersion.INSTANCE.patch
)
}

View File

@@ -287,7 +287,9 @@ open class IncrementalJvmCache(
fun remove(className: JvmClassName, changesCollector: ChangesCollector) {
val key = className.internalName
val oldValue = storage[key] ?: return
changesCollector.collectProtoChanges(oldData = oldValue.toProtoData(className.packageFqName), newData = null)
if (key != MODULE_MAPPING_FILE_NAME) {
changesCollector.collectProtoChanges(oldData = oldValue.toProtoData(className.packageFqName), newData = null)
}
storage.remove(key)
}

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

@@ -478,7 +478,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 {
@@ -34,6 +35,7 @@ repositories {
}
maven(url = "https://dl.bintray.com/kotlin/kotlin-dev") // for dex-method-list
// maven { setUrl("https://repo.gradle.org/gradle/libs-releases-local") }
jcenter()
}
dependencies {
@@ -42,6 +44,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",
"org.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

@@ -1,47 +0,0 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.codegen;
import kotlin.jvm.functions.Function0;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.storage.LockBasedStorageManager;
import org.jetbrains.kotlin.storage.NotNullLazyValue;
public class ClassBuilderOnDemand extends DelegatingClassBuilder {
private final NotNullLazyValue<ClassBuilder> classBuilder;
public ClassBuilderOnDemand(@NotNull Function0<ClassBuilder> createClassBuilder) {
this.classBuilder = LockBasedStorageManager.NO_LOCKS.createLazyValue(createClassBuilder);
}
@Override
@NotNull
protected ClassBuilder getDelegate() {
return classBuilder.invoke();
}
@Override
public void done() {
if (isComputed()) {
classBuilder.invoke().done();
}
}
public boolean isComputed() {
return classBuilder.isComputed();
}
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.codegen
import org.jetbrains.kotlin.storage.LockBasedStorageManager
class ClassBuilderOnDemand(createClassBuilder: () -> ClassBuilder) : DelegatingClassBuilder() {
private val classBuilder = LockBasedStorageManager.NO_LOCKS.createLazyValue(createClassBuilder)
val isComputed: Boolean
get() = classBuilder.isComputed()
override fun getDelegate() = classBuilder()
fun ensureGenerated() {
classBuilder()
}
override fun done() {
if (isComputed) {
classBuilder().done()
}
}
}

View File

@@ -51,6 +51,7 @@ import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
import org.jetbrains.kotlin.codegen.when.SwitchCodegen;
import org.jetbrains.kotlin.codegen.when.SwitchCodegenProvider;
import org.jetbrains.kotlin.config.ApiVersion;
import org.jetbrains.kotlin.config.LanguageFeature;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor;
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor;
@@ -307,7 +308,12 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
RuntimeAssertionInfo runtimeAssertionInfo = null;
if (selector instanceof KtExpression) {
runtimeAssertionInfo = bindingContext.get(JvmBindingContextSlices.RUNTIME_ASSERTION_INFO, (KtExpression) selector);
KtExpression expression = (KtExpression) selector;
runtimeAssertionInfo = bindingContext.get(JvmBindingContextSlices.RUNTIME_ASSERTION_INFO, expression);
if (runtimeAssertionInfo == null &&
state.getLanguageVersionSettings().supportsFeature(LanguageFeature.StrictJavaNullabilityAssertions)) {
runtimeAssertionInfo = bindingContext.get(JvmBindingContextSlices.BODY_RUNTIME_ASSERTION_INFO, expression);
}
}
if (BuiltinSpecialBridgesKt.isValueArgumentForCallToMethodWithTypeCheckBarrier(selector, bindingContext)) return stackValue;
@@ -1717,12 +1723,22 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
private boolean shouldGenerateSingletonAsThisOrOuterFromContext(ClassDescriptor classDescriptor) {
return isPossiblyUninitializedSingleton(classDescriptor) &&
isInsideSingleton(classDescriptor) &&
isThisInitialized(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.
private boolean isThisInitialized(ClassDescriptor classDescriptor) {
CodegenContext context = this.context;
while (context != null) {
if (context instanceof ConstructorContext) {
@@ -1732,9 +1748,24 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
return constructorContext.isThisInitialized();
}
}
else if (context instanceof ClassContext) {
ClassDescriptor contextClass = ((ClassContext) context).getContextDescriptor();
if (isInInnerClassesChainFor(contextClass, classDescriptor)) {
return true;
}
}
context = context.getParentContext();
}
return true;
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
@@ -2784,7 +2815,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
@Nullable
private StackValue generateCallableReferenceReceiver(@NotNull ResolvedCall<?> resolvedCall) {
public StackValue generateCallableReferenceReceiver(@NotNull ResolvedCall<?> resolvedCall) {
CallableDescriptor descriptor = resolvedCall.getResultingDescriptor();
if (descriptor.getExtensionReceiverParameter() == null && descriptor.getDispatchReceiverParameter() == null) return null;

View File

@@ -317,7 +317,10 @@ class MultifileClassCodegenImpl(
}
private fun writeKotlinMultifileFacadeAnnotationIfNeeded() {
if (!state.classBuilderMode.generateMetadata) return
if (!state.classBuilderMode.generateMetadata) {
classBuilder.ensureGenerated()
return
}
if (files.any { it.isScript() }) return
val extraFlags = if (shouldGeneratePartHierarchy) JvmAnnotationNames.METADATA_MULTIFILE_PARTS_INHERIT_FLAG else 0

View File

@@ -32,6 +32,7 @@ import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.codegen.state.TypeMapperUtilsKt;
import org.jetbrains.kotlin.codegen.when.SwitchCodegenProvider;
import org.jetbrains.kotlin.codegen.when.WhenByEnumsMapping;
import org.jetbrains.kotlin.config.LanguageVersionSettings;
import org.jetbrains.kotlin.coroutines.CoroutineUtilKt;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.annotations.Annotations;
@@ -56,6 +57,7 @@ import org.jetbrains.kotlin.resolve.constants.ConstantValue;
import org.jetbrains.kotlin.resolve.constants.EnumValue;
import org.jetbrains.kotlin.resolve.constants.NullValue;
import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt;
import org.jetbrains.kotlin.resolve.jvm.RuntimeAssertionsOnDeclarationBodyChecker;
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue;
import org.jetbrains.kotlin.resolve.scopes.receivers.TransientReceiver;
import org.jetbrains.kotlin.types.KotlinType;
@@ -86,6 +88,8 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
private final JvmRuntimeTypes runtimeTypes;
private final TypeMappingConfiguration<Type> typeMappingConfiguration;
private final SwitchCodegenProvider switchCodegenProvider;
private final LanguageVersionSettings languageVersionSettings;
private final ClassBuilderMode classBuilderMode;
public CodegenAnnotatingVisitor(@NotNull GenerationState state) {
this.bindingTrace = state.getBindingTrace();
@@ -94,6 +98,8 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
this.runtimeTypes = state.getJvmRuntimeTypes();
this.typeMappingConfiguration = state.getTypeMapper().getTypeMappingConfiguration();
this.switchCodegenProvider = new SwitchCodegenProvider(state);
this.languageVersionSettings = state.getLanguageVersionSettings();
this.classBuilderMode = state.getClassBuilderMode();
}
@NotNull
@@ -411,6 +417,8 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
// working around a problem with shallow analysis
if (descriptor == null) return;
checkRuntimeAsserionsOnDeclarationBody(property, descriptor);
if (descriptor instanceof LocalVariableDescriptor) {
recordLocalVariablePropertyMetadata((LocalVariableDescriptor) descriptor);
}
@@ -447,6 +455,14 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
nameStack.pop();
}
private void checkRuntimeAsserionsOnDeclarationBody(@NotNull KtDeclaration declaration, DeclarationDescriptor descriptor) {
if (classBuilderMode.generateBodies) {
// NB This is required only for bodies generation.
// In light class generation can cause recursion in types resolution.
RuntimeAssertionsOnDeclarationBodyChecker.check(declaration, descriptor, bindingTrace, languageVersionSettings);
}
}
@NotNull
private Type getMetadataOwner(@NotNull KtProperty property) {
for (int i = classStack.size() - 1; i >= 0; i--) {
@@ -469,12 +485,24 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
return Type.getObjectType(JvmFileClassUtil.getFileClassInternalName(property.getContainingKtFile()));
}
@Override
public void visitPropertyAccessor(@NotNull KtPropertyAccessor accessor) {
PropertyAccessorDescriptor accessorDescriptor = bindingContext.get(PROPERTY_ACCESSOR, accessor);
if (accessorDescriptor != null) {
checkRuntimeAsserionsOnDeclarationBody(accessor, accessorDescriptor);
}
super.visitPropertyAccessor(accessor);
}
@Override
public void visitNamedFunction(@NotNull KtNamedFunction function) {
FunctionDescriptor functionDescriptor = (FunctionDescriptor) bindingContext.get(DECLARATION_TO_DESCRIPTOR, function);
// working around a problem with shallow analysis
if (functionDescriptor == null) return;
checkRuntimeAsserionsOnDeclarationBody(function, functionDescriptor);
String nameForClassOrPackageMember = getNameForClassOrPackageMember(functionDescriptor);
if (functionDescriptor instanceof SimpleFunctionDescriptor && functionDescriptor.isSuspend()) {

View File

@@ -185,6 +185,11 @@ abstract class InlineCodegen<out T: BaseExpressionCodegen>(
}
private fun canSkipStackSpillingOnInline(methodNode: MethodNode): Boolean {
// Temporary disable this optimization until
// https://issuetracker.google.com/issues/68796377 is fixed
// or until d8 substitute dex
return false
// Stack spilling before inline function 'f' call is required if:
// - 'f' is a suspend function
// - 'f' has try-catch blocks

View File

@@ -36,9 +36,9 @@ object LateinitIsInitialized : IntrinsicPropertyGetter() {
private fun getStackValue(resolvedCall: ResolvedCall<*>, codegen: ExpressionCodegen): StackValue? {
val expression =
(resolvedCall.extensionReceiver as? ExpressionReceiver)?.expression as? KtCallableReferenceExpression ?: return null
val referenceResolvedCall = expression.callableReference.getResolvedCallWithAssert(codegen.bindingContext)
// TODO: support properties imported from objects as soon as KT-18982 is fixed
val receiver = expression.receiverExpression?.let(codegen::gen) ?: StackValue.none()
val receiver = codegen.generateCallableReferenceReceiver(referenceResolvedCall) ?: StackValue.none()
val target = expression.callableReference.getResolvedCallWithAssert(codegen.bindingContext).resultingDescriptor
return codegen.intermediateValueForProperty(target as PropertyDescriptor, true, false, null, false, receiver, null, true)

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

@@ -17,8 +17,7 @@
package org.jetbrains.kotlin.codegen
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.config.KotlinCompilerVersion
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.config.shouldWritePreReleaseFlag
import org.jetbrains.kotlin.load.java.JvmAnnotationNames
import org.jetbrains.kotlin.load.java.JvmBytecodeBinaryVersion
import org.jetbrains.kotlin.load.kotlin.JvmMetadataVersion
@@ -37,7 +36,7 @@ fun writeKotlinMetadata(
av.visit(JvmAnnotationNames.BYTECODE_VERSION_FIELD_NAME, JvmBytecodeBinaryVersion.INSTANCE.toArray())
av.visit(JvmAnnotationNames.KIND_FIELD_NAME, kind.id)
var flags = extraFlags
if (KotlinCompilerVersion.isPreRelease() && state.languageVersionSettings.languageVersion == LanguageVersion.LATEST_STABLE) {
if (state.languageVersionSettings.shouldWritePreReleaseFlag()) {
flags = flags or JvmAnnotationNames.METADATA_PRE_RELEASE_FLAG
}
if (flags != 0) {
@@ -51,4 +50,4 @@ fun writeSyntheticClassMetadata(cb: ClassBuilder, state: GenerationState) {
writeKotlinMetadata(cb, state, KotlinClassHeader.Kind.SYNTHETIC_CLASS, 0) { _ ->
// Do nothing
}
}
}

View File

@@ -106,6 +106,12 @@ abstract class CommonCompilerArguments : CommonToolArguments() {
)
var coroutinesState: String? by FreezableVar(WARN)
@Argument(
value = "-Xlegacy-smart-cast-after-try",
description = "Allow var smart casts despite assignment in try block"
)
var legacySmartCastAfterTry by FreezableVar(false)
open fun configureAnalysisFlags(collector: MessageCollector): MutableMap<AnalysisFlag<*>, Any> {
return HashMap<AnalysisFlag<*>, Any>().apply {
put(AnalysisFlag.skipMetadataVersionCheck, skipMetadataVersionCheck)

View File

@@ -106,16 +106,16 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
@Argument(value = "-Xno-param-assertions", description = "Don't generate not-null assertions on parameters of methods accessible from Java")
var noParamAssertions: Boolean by FreezableVar(false)
@Argument(value = "-Xstrict-java-nullability-assertions", description = "Generate nullability assertions for non-null Java expressions")
var strictJavaNullabilityAssertions: Boolean by FreezableVar(false)
@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"
valueDescription = "{disable|enable}",
description = "Normalize constructor calls (disable: don't normalize; enable: normalize), default is disable"
)
var constructorCallNormalizationMode: String? by FreezableVar(JVMConstructorCallNormalizationMode.DEFAULT.description)

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

@@ -204,6 +204,12 @@ public abstract class CLICompiler<A extends CommonCompilerArguments> extends CLI
extraLanguageFeatures.put(LanguageFeature.Coroutines, coroutinesState);
}
if (arguments.getLegacySmartCastAfterTry()) {
extraLanguageFeatures.put(LanguageFeature.SoundSmartCastsAfterTry, LanguageFeature.State.DISABLED);
}
setupPlatformSpecificLanguageFeatureSettings(extraLanguageFeatures, arguments);
CommonConfigurationKeysKt.setLanguageVersionSettings(configuration, new LanguageVersionSettingsImpl(
languageVersion,
ApiVersion.createByLanguageVersion(apiVersion),
@@ -212,6 +218,13 @@ public abstract class CLICompiler<A extends CommonCompilerArguments> extends CLI
));
}
protected void setupPlatformSpecificLanguageFeatureSettings(
@NotNull Map<LanguageFeature, LanguageFeature.State> extraLanguageFeatures,
@NotNull A commandLineArguments
) {
// do nothing
}
@Nullable
private static KotlinPaths computeKotlinPaths(@NotNull MessageCollector messageCollector, @NotNull CommonCompilerArguments arguments) {
KotlinPaths paths;

View File

@@ -228,6 +228,17 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
}
}
override fun setupPlatformSpecificLanguageFeatureSettings(
extraLanguageFeatures: MutableMap<LanguageFeature, LanguageFeature.State>,
commandLineArguments: K2JVMCompilerArguments
) {
if (commandLineArguments.strictJavaNullabilityAssertions) {
extraLanguageFeatures[LanguageFeature.StrictJavaNullabilityAssertions] = LanguageFeature.State.ENABLED
}
super.setupPlatformSpecificLanguageFeatureSettings(extraLanguageFeatures, commandLineArguments)
}
private fun registerJavacIfNeeded(environment: KotlinCoreEnvironment,
arguments: K2JVMCompilerArguments): Boolean {
if (arguments.useJavac) {
@@ -374,8 +385,6 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
configuration.put(JVMConfigurationKeys.ADD_BUILT_INS_FROM_COMPILER_TO_DEPENDENCIES, arguments.addCompilerBuiltIns)
configuration.put(JVMConfigurationKeys.CREATE_BUILT_INS_FROM_MODULE_DEPENDENCIES, arguments.loadBuiltInsFromDependencies)
arguments.declarationsOutputPath?.let { configuration.put(JVMConfigurationKeys.DECLARATIONS_JSON_PATH, it) }
}

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

@@ -0,0 +1,33 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("FileClasses")
package org.jetbrains.kotlin.fileClasses
import org.jetbrains.kotlin.psi.KtFile
@Deprecated("Use JvmFileClassUtil instead.", level = DeprecationLevel.ERROR)
open class JvmFileClassesProvider
@Suppress("DEPRECATION_ERROR")
@Deprecated("Use JvmFileClassUtil instead.", level = DeprecationLevel.ERROR)
object NoResolveFileClassesProvider : JvmFileClassesProvider()
@Suppress("DEPRECATION_ERROR", "unused")
@Deprecated("Use JvmFileClassUtil.getFileClassInternalName instead.", ReplaceWith("JvmFileClassUtil.getFileClassInternalName(file)"), DeprecationLevel.ERROR)
fun JvmFileClassesProvider.getFileClassInternalName(file: KtFile): String =
JvmFileClassUtil.getFileClassInternalName(file)

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

@@ -32,6 +32,9 @@ object JvmBindingContextSlices {
@JvmField
val RECEIVER_RUNTIME_ASSERTION_INFO: WritableSlice<ExpressionReceiver, RuntimeAssertionInfo> = BasicWritableSlice(RewritePolicy.DO_NOTHING)
@JvmField
val BODY_RUNTIME_ASSERTION_INFO: WritableSlice<KtExpression, RuntimeAssertionInfo> = BasicWritableSlice(RewritePolicy.DO_NOTHING)
@JvmField
val LOAD_FROM_JAVA_SIGNATURE_ERRORS: WritableSlice<DeclarationDescriptor, List<String>> = Slices.createCollectiveSlice()

View File

@@ -0,0 +1,43 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.resolve.jvm
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.annotations.FilteredAnnotations
import org.jetbrains.kotlin.load.java.JvmAnnotationNames
import org.jetbrains.kotlin.resolve.BindingTrace
import org.jetbrains.kotlin.resolve.DeclarationReturnTypeSanitizer
import org.jetbrains.kotlin.types.UnwrappedType
import org.jetbrains.kotlin.types.WrappedTypeFactory
object JvmDeclarationReturnTypeSanitizer : DeclarationReturnTypeSanitizer {
override fun sanitizeReturnType(
inferred: UnwrappedType,
wrappedTypeFactory: WrappedTypeFactory,
trace: BindingTrace,
languageVersionSettings: LanguageVersionSettings
): UnwrappedType =
if (languageVersionSettings.supportsFeature(LanguageFeature.StrictJavaNullabilityAssertions)) {
// NB can't check for presence of EnhancedNullability here,
// because it will also cause recursion in declaration type resolution.
inferred.replaceAnnotations(FilteredAnnotations(inferred.annotations) {
it != JvmAnnotationNames.ENHANCED_NULLABILITY_ANNOTATION
})
}
else inferred
}

View File

@@ -18,9 +18,12 @@ package org.jetbrains.kotlin.resolve.jvm
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.load.java.typeEnhancement.hasEnhancedNullability
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingTrace
import org.jetbrains.kotlin.resolve.calls.callUtil.isSafeCall
import org.jetbrains.kotlin.resolve.calls.checkers.AdditionalTypeChecker
import org.jetbrains.kotlin.resolve.calls.checkers.CallChecker
@@ -31,9 +34,9 @@ import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValue
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.checker.isClassType
import org.jetbrains.kotlin.types.typeUtil.immediateSupertypes
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class RuntimeAssertionInfo(val needNotNullAssertion: Boolean, val message: String) {
@@ -83,6 +86,9 @@ class RuntimeAssertionInfo(val needNotNullAssertion: Boolean, val message: Strin
}
}
private val KtExpression.textForRuntimeAssertionInfo
get() = StringUtil.trimMiddle(text, 50)
class RuntimeAssertionsDataFlowExtras(
private val c: ResolutionContext<*>,
private val dataFlowValue: DataFlowValue,
@@ -93,7 +99,7 @@ class RuntimeAssertionsDataFlowExtras(
override val possibleTypes: Set<KotlinType>
get() = c.dataFlowInfo.getCollectedTypes(dataFlowValue)
override val presentableText: String
get() = StringUtil.trimMiddle(expression.text, 50)
get() = expression.textForRuntimeAssertionInfo
}
object RuntimeAssertionsTypeChecker : AdditionalTypeChecker {
@@ -138,4 +144,101 @@ object RuntimeAssertionsOnExtensionReceiverCallChecker : CallChecker {
c.trace.record(JvmBindingContextSlices.RECEIVER_RUNTIME_ASSERTION_INFO, expressionReceiverValue, assertionInfo)
}
}
}
object RuntimeAssertionsOnDeclarationBodyChecker {
@JvmStatic
fun check(
declaration: KtDeclaration,
descriptor: DeclarationDescriptor,
bindingTrace: BindingTrace,
languageVersionSettings: LanguageVersionSettings
) {
if (!languageVersionSettings.supportsFeature(LanguageFeature.StrictJavaNullabilityAssertions)) return
when {
declaration is KtProperty && descriptor is VariableDescriptor ->
checkLocalVariable(declaration, descriptor, bindingTrace)
declaration is KtFunction && descriptor is FunctionDescriptor ->
checkFunction(declaration, descriptor, bindingTrace)
declaration is KtProperty && descriptor is PropertyDescriptor ->
checkProperty(declaration, descriptor, bindingTrace)
declaration is KtPropertyAccessor && descriptor is PropertyAccessorDescriptor ->
checkPropertyAccessor(declaration, descriptor, bindingTrace)
}
}
private fun checkLocalVariable(
declaration: KtProperty,
descriptor: VariableDescriptor,
bindingTrace: BindingTrace
) {
if (declaration.typeReference != null) return
checkNullabilityAssertion(declaration.initializer ?: return, descriptor.type, bindingTrace)
}
private fun checkFunction(
declaration: KtFunction,
descriptor: FunctionDescriptor,
bindingTrace: BindingTrace
) {
if (declaration.typeReference != null || declaration.hasBlockBody()) return
checkNullabilityAssertion(declaration.bodyExpression ?: return, descriptor.returnType ?: return,
bindingTrace)
}
private fun checkProperty(
declaration: KtProperty,
descriptor: PropertyDescriptor,
bindingTrace: BindingTrace
) {
if (declaration.typeReference != null) return
// TODO nullability assertion on delegate initialization expression, see KT-20823
if (declaration.hasDelegateExpression()) return
checkNullabilityAssertion(declaration.initializer ?: return, descriptor.type, bindingTrace)
}
private fun checkPropertyAccessor(
declaration: KtPropertyAccessor,
descriptor: PropertyAccessorDescriptor,
bindingTrace: BindingTrace
) {
if (declaration.property.typeReference != null || declaration.hasBlockBody()) return
checkNullabilityAssertion(declaration.bodyExpression ?: return, descriptor.correspondingProperty.type,
bindingTrace)
}
private fun checkNullabilityAssertion(
expression: KtExpression,
declarationType: KotlinType,
bindingTrace: BindingTrace
) {
if (declarationType.unwrap().canContainNull()) return
val expressionType = bindingTrace.getType(expression) ?: return
if (expressionType.isError) return
if (!expressionType.hasEnhancedNullability()) return
bindingTrace.record(
JvmBindingContextSlices.BODY_RUNTIME_ASSERTION_INFO,
expression,
RuntimeAssertionInfo(true, expression.textForRuntimeAssertionInfo)
)
}
private fun UnwrappedType.canContainNull(): Boolean {
val upper = upperIfFlexible()
return when {
upper.isMarkedNullable -> true
upper.isClassType -> false
else -> upper.immediateSupertypes().all { it.unwrap().canContainNull() }
}
}
}

View File

@@ -18,6 +18,7 @@ package org.jetbrains.kotlin.resolve.jvm.checkers
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
@@ -28,7 +29,7 @@ import org.jetbrains.kotlin.resolve.calls.callResolverUtil.getSuperCallExpressio
import org.jetbrains.kotlin.resolve.calls.checkers.CallChecker
import org.jetbrains.kotlin.resolve.calls.checkers.CallCheckerContext
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm.*
class InterfaceDefaultMethodCallChecker(val jvmTarget: JvmTarget) : CallChecker {
@@ -41,7 +42,8 @@ class InterfaceDefaultMethodCallChecker(val jvmTarget: JvmTarget) : CallChecker
isStaticDeclaration(descriptor) &&
isInterface(descriptor.containingDeclaration) &&
descriptor is JavaCallableMemberDescriptor) {
context.trace.report(ErrorsJvm.INTERFACE_STATIC_METHOD_CALL_FROM_JAVA6_TARGET.on(reportOn))
val diagnostic = if (isDefaultCallsProhibited(context)) INTERFACE_STATIC_METHOD_CALL_FROM_JAVA6_TARGET_ERROR else INTERFACE_STATIC_METHOD_CALL_FROM_JAVA6_TARGET
context.trace.report(diagnostic.on(reportOn))
}
if (getSuperCallExpression(resolvedCall.call) == null) return
@@ -55,11 +57,15 @@ class InterfaceDefaultMethodCallChecker(val jvmTarget: JvmTarget) : CallChecker
val classifier = DescriptorUtils.getParentOfType(context.scope.ownerDescriptor, ClassifierDescriptor::class.java)
//is java interface default method called from trait
if (classifier != null && DescriptorUtils.isInterface(classifier)) {
context.trace.report(ErrorsJvm.INTERFACE_CANT_CALL_DEFAULT_METHOD_VIA_SUPER.on(reportOn))
context.trace.report(INTERFACE_CANT_CALL_DEFAULT_METHOD_VIA_SUPER.on(reportOn))
}
else if (!supportDefaults) {
context.trace.report(ErrorsJvm.DEFAULT_METHOD_CALL_FROM_JAVA6_TARGET.on(reportOn))
val diagnostic = if (isDefaultCallsProhibited(context)) DEFAULT_METHOD_CALL_FROM_JAVA6_TARGET_ERROR else DEFAULT_METHOD_CALL_FROM_JAVA6_TARGET
context.trace.report(diagnostic.on(reportOn))
}
}
}
private fun isDefaultCallsProhibited(context: CallCheckerContext) =
context.languageVersionSettings.supportsFeature(LanguageFeature.DefaultMethodsCallFromJava6TargetError)
}

View File

@@ -115,8 +115,10 @@ public class DefaultErrorMessagesJvm implements DefaultErrorMessages.Extension {
"Please make explicit overrides (abstract or concrete) for the following non-abstract members of ''{1}'': {2}",
NAME, NAME, STRING);
MAP.put(DEFAULT_METHOD_CALL_FROM_JAVA6_TARGET, "Super calls to Java default methods are prohibited in JVM target 1.6. Recompile with '-jvm-target 1.8'");
MAP.put(DEFAULT_METHOD_CALL_FROM_JAVA6_TARGET, "Super calls to Java default methods are deprecated in JVM target 1.6. Recompile with '-jvm-target 1.8'");
MAP.put(DEFAULT_METHOD_CALL_FROM_JAVA6_TARGET_ERROR, "Super calls to Java default methods are prohibited in JVM target 1.6. Recompile with '-jvm-target 1.8'");
MAP.put(INTERFACE_STATIC_METHOD_CALL_FROM_JAVA6_TARGET, "Calls to static methods in Java interfaces are deprecated in JVM target 1.6. Recompile with '-jvm-target 1.8'");
MAP.put(INTERFACE_STATIC_METHOD_CALL_FROM_JAVA6_TARGET_ERROR, "Calls to static methods in Java interfaces are prohibited in JVM target 1.6. Recompile with '-jvm-target 1.8'");
MAP.put(INLINE_FROM_HIGHER_PLATFORM, "Cannot inline bytecode built with {0} into bytecode that is being built with {1}. Please specify proper ''-jvm-target'' option", STRING, STRING);

View File

@@ -96,8 +96,10 @@ public interface ErrorsJvm {
DiagnosticFactory3<PsiElement, DeclarationDescriptor, DeclarationDescriptor, String> TARGET6_INTERFACE_INHERITANCE = DiagnosticFactory3.create(ERROR);
DiagnosticFactory0<PsiElement> DEFAULT_METHOD_CALL_FROM_JAVA6_TARGET = DiagnosticFactory0.create(ERROR);
DiagnosticFactory0<PsiElement> DEFAULT_METHOD_CALL_FROM_JAVA6_TARGET = DiagnosticFactory0.create(WARNING);
DiagnosticFactory0<PsiElement> DEFAULT_METHOD_CALL_FROM_JAVA6_TARGET_ERROR = DiagnosticFactory0.create(ERROR);
DiagnosticFactory0<PsiElement> INTERFACE_STATIC_METHOD_CALL_FROM_JAVA6_TARGET = DiagnosticFactory0.create(WARNING);
DiagnosticFactory0<PsiElement> INTERFACE_STATIC_METHOD_CALL_FROM_JAVA6_TARGET_ERROR = DiagnosticFactory0.create(ERROR);
DiagnosticFactory2<PsiElement, String, String> INLINE_FROM_HIGHER_PLATFORM = DiagnosticFactory2.create(ERROR);

View File

@@ -81,7 +81,9 @@ object JvmPlatformConfigurator : PlatformConfigurator(
delegationFilter = JvmDelegationFilter,
overridesBackwardCompatibilityHelper = JvmOverridesBackwardCompatibilityHelper
overridesBackwardCompatibilityHelper = JvmOverridesBackwardCompatibilityHelper,
declarationReturnTypeSanitizer = JvmDeclarationReturnTypeSanitizer
) {
override fun configureModuleComponents(container: StorageComponentContainer) {
container.useImpl<JvmReflectionAPICallChecker>()

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>,
@@ -291,8 +294,14 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon
val variableUseStatusData: Map<Instruction, Edges<ReadOnlyUseControlFlowInfo>>
get() {
val resultForTrivialVals = computeUseInfoForTrivialVals()
if (rootVariables.nonTrivialVariables.isEmpty()) return resultForTrivialVals
val edgesForTrivialVals = computeUseInfoForTrivialVals()
if (rootVariables.nonTrivialVariables.isEmpty()) {
return hashMapOf<Instruction, Edges<ReadOnlyUseControlFlowInfo>>().apply {
pseudocode.traverse(TraversalOrder.FORWARD) { instruction ->
put(instruction, edgesForTrivialVals)
}
}
}
return pseudocodeVariableDataCollector.collectData(TraversalOrder.BACKWARD, UseControlFlowInfo()) { instruction: Instruction, incomingEdgesData: Collection<UseControlFlowInfo> ->
@@ -333,17 +342,16 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon
Edges(enterResult, exitResult)
}
}.mapValues {
(instruction, edges) ->
val edgeForTrivialVals = resultForTrivialVals[instruction]!!
(_, edges) ->
Edges(
edgeForTrivialVals.incoming.replaceDelegate(edges.incoming),
edgeForTrivialVals.outgoing.replaceDelegate(edges.outgoing)
edgesForTrivialVals.incoming.replaceDelegate(edges.incoming),
edgesForTrivialVals.outgoing.replaceDelegate(edges.outgoing)
)
}
}
private fun computeUseInfoForTrivialVals(): Map<Instruction, Edges<ReadOnlyUseControlFlowInfoImpl>> {
private fun computeUseInfoForTrivialVals(): Edges<ReadOnlyUseControlFlowInfoImpl> {
val used = hashSetOf<VariableDescriptor>()
pseudocode.traverse(TraversalOrder.FORWARD) { instruction ->
@@ -355,13 +363,7 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon
}
val constantUseInfo = ReadOnlyUseControlFlowInfoImpl(used, null)
val constantEdges = Edges(constantUseInfo, constantUseInfo)
val result = hashMapOf<Instruction, Edges<ReadOnlyUseControlFlowInfoImpl>>()
pseudocode.traverse(TraversalOrder.FORWARD) { instruction ->
result[instruction] = constantEdges
}
return result
return Edges(constantUseInfo, constantUseInfo)
}
private fun extractValWithTrivialInitializer(instruction: Instruction): 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;
@@ -982,9 +983,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);
// Function contracts
DiagnosticFactory1<KtElement, String> ERROR_IN_CONTRACT_DESCRIPTION = DiagnosticFactory1.create(ERROR);

View File

@@ -14,6 +14,17 @@
* limitations under the License.
*/
package foo
package org.jetbrains.kotlin.diagnostics
class A(val x: String)
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.VersionRequirement;
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 {
@@ -888,9 +872,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.put(ERROR_IN_CONTRACT_DESCRIPTION, "Error in contract description: {0}", TO_STRING);
MAP.put(CONTRACT_NOT_ALLOWED, "Contract is not allowed here");

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

@@ -22,10 +22,12 @@ import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.serialization.deserialization.DeserializationConfiguration
class CompilerDeserializationConfiguration(languageVersionSettings: LanguageVersionSettings) : DeserializationConfiguration {
override val typeAliasesAllowed = languageVersionSettings.supportsFeature(LanguageFeature.TypeAliases)
override val skipMetadataVersionCheck = languageVersionSettings.getFlag(AnalysisFlag.skipMetadataVersionCheck)
override val skipPreReleaseCheck = skipMetadataVersionCheck || !languageVersionSettings.languageVersion.isStable
override val typeAliasesAllowed = languageVersionSettings.supportsFeature(LanguageFeature.TypeAliases)
override val isJvmPackageNameSupported = languageVersionSettings.supportsFeature(LanguageFeature.JvmPackageName)
override val returnsEffectAllowed: Boolean = languageVersionSettings.supportsFeature(LanguageFeature.ReturnsEffect)

View File

@@ -0,0 +1,40 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.resolve
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.UnwrappedType
import org.jetbrains.kotlin.types.WrappedTypeFactory
interface DeclarationReturnTypeSanitizer {
fun sanitizeReturnType(
inferred: UnwrappedType,
wrappedTypeFactory: WrappedTypeFactory,
trace: BindingTrace,
languageVersionSettings: LanguageVersionSettings
): UnwrappedType
object Default : DeclarationReturnTypeSanitizer {
override fun sanitizeReturnType(
inferred: UnwrappedType,
wrappedTypeFactory: WrappedTypeFactory,
trace: BindingTrace,
languageVersionSettings: LanguageVersionSettings
) = inferred
}
}

View File

@@ -87,6 +87,7 @@ public class DescriptorResolver {
private final WrappedTypeFactory wrappedTypeFactory;
private final SyntheticResolveExtension syntheticResolveExtension;
private final TypeApproximator typeApproximator;
private final DeclarationReturnTypeSanitizer declarationReturnTypeSanitizer;
public DescriptorResolver(
@NotNull AnnotationResolver annotationResolver,
@@ -103,7 +104,8 @@ public class DescriptorResolver {
@NotNull ModifiersChecker modifiersChecker,
@NotNull WrappedTypeFactory wrappedTypeFactory,
@NotNull Project project,
TypeApproximator approximator
@NotNull TypeApproximator approximator,
@NotNull DeclarationReturnTypeSanitizer declarationReturnTypeSanitizer
) {
this.annotationResolver = annotationResolver;
this.builtIns = builtIns;
@@ -120,6 +122,7 @@ public class DescriptorResolver {
this.wrappedTypeFactory = wrappedTypeFactory;
this.syntheticResolveExtension = SyntheticResolveExtension.Companion.getInstance(project);
typeApproximator = approximator;
this.declarationReturnTypeSanitizer = declarationReturnTypeSanitizer;
}
public List<KotlinType> resolveSupertypes(
@@ -1152,12 +1155,12 @@ public class DescriptorResolver {
) {
return wrappedTypeFactory.createRecursionIntolerantDeferredType(trace, () -> {
PreliminaryDeclarationVisitor.Companion.createForDeclaration(function, trace, languageVersionSettings);
KotlinType type = expressionTypingServices.getBodyExpressionType(
trace, scope, dataFlowInfo, function, functionDescriptor);
KotlinType result = transformAnonymousTypeIfNeeded(functionDescriptor, function, type, trace);
UnwrappedType approximatedType = typeApproximator.approximateDeclarationType(result, false);
functionsTypingVisitor.checkTypesForReturnStatements(function, trace, approximatedType);
return approximatedType;
KotlinType type = expressionTypingServices.getBodyExpressionType(trace, scope, dataFlowInfo, function, functionDescriptor);
KotlinType publicType = transformAnonymousTypeIfNeeded(functionDescriptor, function, type, trace);
UnwrappedType approximatedType = typeApproximator.approximateDeclarationType(publicType, false);
KotlinType sanitizedType = declarationReturnTypeSanitizer.sanitizeReturnType(approximatedType, wrappedTypeFactory, trace, languageVersionSettings);
functionsTypingVisitor.checkTypesForReturnStatements(function, trace, sanitizedType);
return sanitizedType;
});
}

View File

@@ -134,7 +134,7 @@ class FunctionDescriptorResolver(
assert(function.typeReference == null) {
"Return type must be initialized early for function: " + function.text + ", at: " + DiagnosticUtils.atLocation(function) }
val returnType = when {
val inferredReturnType = when {
function.hasBlockBody() ->
builtIns.unitType
function.hasBody() ->
@@ -142,7 +142,7 @@ class FunctionDescriptorResolver(
else ->
ErrorUtils.createErrorType("No type, no body")
}
functionDescriptor.setReturnType(returnType)
functionDescriptor.setReturnType(inferredReturnType)
}
fun initializeFunctionDescriptorAndExplicitReturnType(

View File

@@ -24,7 +24,7 @@ interface IdentifierChecker {
fun checkIdentifier(identifier: PsiElement?, diagnosticHolder: DiagnosticSink)
fun checkDeclaration(declaration: KtDeclaration, diagnosticHolder: DiagnosticSink)
object DEFAULT : IdentifierChecker {
object Default : IdentifierChecker {
override fun checkIdentifier(identifier: PsiElement?, diagnosticHolder: DiagnosticSink) {}
override fun checkDeclaration(declaration: KtDeclaration, diagnosticHolder: DiagnosticSink) {}
}

View File

@@ -20,11 +20,16 @@ import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.*
import org.jetbrains.kotlin.descriptors.impl.FunctionDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor
import org.jetbrains.kotlin.descriptors.impl.PropertyDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.VariableDescriptorWithInitializerImpl
import org.jetbrains.kotlin.diagnostics.Errors.*
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPsiUtil
import org.jetbrains.kotlin.psi.KtVariableDeclaration
import org.jetbrains.kotlin.resolve.calls.context.ContextDependency
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory

View File

@@ -22,7 +22,7 @@ import org.jetbrains.kotlin.descriptors.DeclarationDescriptorNonRoot
interface OverloadFilter {
fun filterPackageMemberOverloads(overloads: Collection<DeclarationDescriptorNonRoot>): Collection<DeclarationDescriptorNonRoot>
object DEFAULT : OverloadFilter {
object Default : OverloadFilter {
override fun filterPackageMemberOverloads(overloads: Collection<DeclarationDescriptorNonRoot>): Collection<DeclarationDescriptorNonRoot> =
overloads
}

View File

@@ -21,7 +21,7 @@ import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
interface OverridesBackwardCompatibilityHelper {
fun overrideCanBeOmitted(overridingDescriptor: CallableMemberDescriptor): Boolean
object DEFAULT : OverridesBackwardCompatibilityHelper {
object Default : OverridesBackwardCompatibilityHelper {
override fun overrideCanBeOmitted(overridingDescriptor: CallableMemberDescriptor): Boolean =
false
}

View File

@@ -64,8 +64,9 @@ abstract class TargetPlatform(val platformName: String) {
override val platformConfigurator =
object : PlatformConfigurator(
DynamicTypesSettings(), listOf(), listOf(), listOf(), listOf(), listOf(),
IdentifierChecker.DEFAULT, OverloadFilter.DEFAULT, PlatformToKotlinClassMap.EMPTY, DelegationFilter.DEFAULT,
OverridesBackwardCompatibilityHelper.DEFAULT
IdentifierChecker.Default, OverloadFilter.Default, PlatformToKotlinClassMap.EMPTY, DelegationFilter.Default,
OverridesBackwardCompatibilityHelper.Default,
DeclarationReturnTypeSanitizer.Default
) {
override fun configureModuleComponents(container: StorageComponentContainer) {
container.useInstance(SyntheticScopes.Empty)
@@ -118,7 +119,8 @@ abstract class PlatformConfigurator(
private val overloadFilter: OverloadFilter,
private val platformToKotlinClassMap: PlatformToKotlinClassMap,
private val delegationFilter: DelegationFilter,
private val overridesBackwardCompatibilityHelper: OverridesBackwardCompatibilityHelper
private val overridesBackwardCompatibilityHelper: OverridesBackwardCompatibilityHelper,
private val declarationReturnTypeSanitizer: DeclarationReturnTypeSanitizer
) {
private val declarationCheckers: List<DeclarationChecker> = DEFAULT_DECLARATION_CHECKERS + additionalDeclarationCheckers
private val callCheckers: List<CallChecker> = DEFAULT_CALL_CHECKERS + additionalCallCheckers
@@ -139,6 +141,7 @@ abstract class PlatformConfigurator(
useInstance(platformToKotlinClassMap)
useInstance(delegationFilter)
useInstance(overridesBackwardCompatibilityHelper)
useInstance(declarationReturnTypeSanitizer)
}
}

View File

@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.resolve
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.VariableDescriptorWithAccessors
import org.jetbrains.kotlin.descriptors.impl.VariableDescriptorWithInitializerImpl
import org.jetbrains.kotlin.diagnostics.Errors
@@ -39,7 +40,9 @@ class VariableTypeAndInitializerResolver(
private val constantExpressionEvaluator: ConstantExpressionEvaluator,
private val delegatedPropertyResolver: DelegatedPropertyResolver,
private val wrappedTypeFactory: WrappedTypeFactory,
private val typeApproximator: TypeApproximator
private val typeApproximator: TypeApproximator,
private val declarationReturnTypeSanitizer: DeclarationReturnTypeSanitizer,
private val languageVersionSettings: LanguageVersionSettings
) {
companion object {
@JvmField
@@ -92,6 +95,7 @@ class VariableTypeAndInitializerResolver(
else -> resolveInitializerType(scopeForInitializer, variable.initializer!!, dataFlowInfo, trace, local)
}
else -> null
}
}
@@ -152,7 +156,9 @@ class VariableTypeAndInitializerResolver(
trace: BindingTrace,
local: Boolean
): KotlinType {
return approximateType(expressionTypingServices.safeGetType(scope, initializer, TypeUtils.NO_EXPECTED_TYPE, dataFlowInfo, trace), local)
val inferredType = expressionTypingServices.safeGetType(scope, initializer, TypeUtils.NO_EXPECTED_TYPE, dataFlowInfo, trace)
val approximatedType = approximateType(inferredType, local)
return declarationReturnTypeSanitizer.sanitizeReturnType(approximatedType, wrappedTypeFactory, trace, languageVersionSettings)
}
private fun approximateType(type: KotlinType, local: Boolean): UnwrappedType = typeApproximator.approximateDeclarationType(type, local)

View File

@@ -180,12 +180,25 @@ class GenericCandidateResolver(
private fun getBinaryWithTypeParent(calleeExpression: KtExpression?): KtBinaryExpressionWithTypeRHS? {
val callExpression = calleeExpression?.parent.safeAs<KtCallExpression>() ?: return null
val parent = callExpression.parent
return when (parent) {
is KtBinaryExpressionWithTypeRHS -> parent
is KtQualifiedExpression -> parent.parent.safeAs<KtBinaryExpressionWithTypeRHS>().takeIf { parent.selectorExpression == callExpression }
else -> null
val possibleQualifiedExpression = callExpression.parent
val targetExpression = if (possibleQualifiedExpression is KtQualifiedExpression) {
if (possibleQualifiedExpression.selectorExpression != callExpression) return null
possibleQualifiedExpression
}
else {
callExpression
}
return targetExpression.topParenthesizedParentOrMe().parent.safeAs<KtBinaryExpressionWithTypeRHS>()
}
private fun KtExpression.topParenthesizedParentOrMe(): KtExpression {
var result: KtExpression = this
while (KtPsiUtil.deparenthesizeOnce(result.parent.safeAs()) == result) {
result = result.parent.safeAs() ?: break
}
return result
}
private fun addValidityConstraintsForConstituentTypes(builder: ConstraintSystem.Builder, type: KotlinType) {

View File

@@ -96,9 +96,12 @@ internal class DelegatingDataFlowInfo private constructor(
nullability: Nullability,
languageVersionSettings: LanguageVersionSettings,
typeInfo: SetMultimap<DataFlowValue, KotlinType>? = null,
affectReceiver: Boolean = true
affectReceiver: Boolean = true,
recordUnstable: Boolean = true
): Boolean {
map.put(value, nullability)
if (value.isStable || recordUnstable) {
map.put(value, nullability)
}
val identifierInfo = value.identifierInfo
if (affectReceiver && !nullability.canBeNull() &&
@@ -108,7 +111,8 @@ internal class DelegatingDataFlowInfo private constructor(
val receiverType = identifierInfo.receiverType
if (identifierInfo.safe && receiverType != null) {
val receiverValue = DataFlowValue(identifierInfo.receiverInfo, receiverType)
putNullabilityAndTypeInfo(map, receiverValue, nullability, languageVersionSettings, typeInfo)
putNullabilityAndTypeInfo(map, receiverValue, nullability,
languageVersionSettings, typeInfo, recordUnstable = recordUnstable)
}
}
is IdentifierInfo.SafeCast -> {
@@ -118,12 +122,16 @@ internal class DelegatingDataFlowInfo private constructor(
languageVersionSettings.supportsFeature(LanguageFeature.SafeCastCheckBoundSmartCasts)) {
val subjectValue = DataFlowValue(identifierInfo.subjectInfo, subjectType)
putNullabilityAndTypeInfo(map, subjectValue, nullability, languageVersionSettings, typeInfo)
typeInfo?.put(subjectValue, targetType)
putNullabilityAndTypeInfo(map, subjectValue, nullability,
languageVersionSettings, typeInfo, recordUnstable = false)
if (subjectValue.isStable) {
typeInfo?.put(subjectValue, targetType)
}
}
}
is IdentifierInfo.Variable -> identifierInfo.bound?.let {
putNullabilityAndTypeInfo(map, it, nullability, languageVersionSettings, typeInfo)
putNullabilityAndTypeInfo(map, it, nullability,
languageVersionSettings, typeInfo, recordUnstable = recordUnstable)
}
}
}

View File

@@ -23,7 +23,7 @@ interface DelegationFilter {
fun filter(interfaceMember: CallableMemberDescriptor, languageVersionSettings: LanguageVersionSettings): Boolean
object DEFAULT : DelegationFilter {
object Default : DelegationFilter {
override fun filter(interfaceMember: CallableMemberDescriptor, languageVersionSettings: LanguageVersionSettings) = true
}
}

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

@@ -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

@@ -1315,6 +1315,12 @@ public class IncrementalJvmCompilerRunnerTestGenerated extends AbstractIncrement
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("jps-plugin/testData/incremental/withJava/other"), Pattern.compile("^([^\\.]+)$"), TargetBackend.ANY, true);
}
@TestMetadata("allKotlinFilesRemovedThenNewAdded")
public void testAllKotlinFilesRemovedThenNewAdded() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("jps-plugin/testData/incremental/withJava/other/allKotlinFilesRemovedThenNewAdded/");
doTest(fileName);
}
@TestMetadata("classToPackageFacade")
public void testClassToPackageFacade() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("jps-plugin/testData/incremental/withJava/other/classToPackageFacade/");

View File

@@ -0,0 +1,2 @@
public final class AllInlineOnly {
}

View File

@@ -0,0 +1,11 @@
// p.AllInlineOnly
@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("AllInlineOnly")
package p
@kotlin.internal.InlineOnly
public inline fun f(): Int = 3
@kotlin.internal.InlineOnly
public inline fun g(p: String): String = "p"

View File

@@ -0,0 +1,2 @@
public final class AllPrivate {
}

View File

@@ -0,0 +1,9 @@
// p.AllPrivate
@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("AllPrivate")
package p
private fun f(): Int = 3
private fun g(p: String): String = "p"

View File

@@ -7,6 +7,7 @@ where advanced options include:
-Xcoroutines={enable|warn|error}
Enable coroutines or report warnings or errors on declarations and use sites of 'suspend' modifier
-Xintellij-plugin-root=<path> Path to the kotlin-compiler.jar or directory where IntelliJ configuration files can be found
-Xlegacy-smart-cast-after-try Allow var smart casts despite assignment in try block
-Xmulti-platform Enable experimental language support for multi-platform projects
-Xno-check-actual Do not check presence of 'actual' modifier in multi-platform projects
-Xno-inline Disable method inlining

View File

@@ -5,8 +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
-Xnormalize-constructor-calls={disable|enable}
Normalize constructor calls (disable: don't normalize; enable: normalize), 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
@@ -26,12 +26,15 @@ where advanced options include:
Script resolver environment in key-value pairs (the value could be quoted and escaped)
-Xsingle-module Combine modules for source files and binary dependencies into a single module
-Xskip-runtime-version-check Allow Kotlin runtime libraries of incompatible versions in the classpath
-Xstrict-java-nullability-assertions
Generate nullability assertions for non-null Java expressions
-Xuse-javac Use javac for Java source and class files analysis
-Xuse-old-class-files-reading Use old class files reading implementation (may slow down the build and should be used in case of problems with the new implementation)
-Xallow-kotlin-package Allow compiling code in package 'kotlin' and allow not requiring kotlin.stdlib in module-info
-Xcoroutines={enable|warn|error}
Enable coroutines or report warnings or errors on declarations and use sites of 'suspend' modifier
-Xintellij-plugin-root=<path> Path to the kotlin-compiler.jar or directory where IntelliJ configuration files can be found
-Xlegacy-smart-cast-after-try Allow var smart casts despite assignment in try block
-Xmulti-platform Enable experimental language support for multi-platform projects
-Xno-check-actual Do not check presence of 'actual' modifier in multi-platform projects
-Xno-inline Disable method inlining

View File

@@ -0,0 +1,4 @@
$TESTDATA_DIR$/legacySmartCastsAfterTry.kt
-d
$TEMP_DIR$
-Xlegacy-smart-cast-after-try

View File

@@ -0,0 +1,9 @@
fun foo() {
var some: String? = null
some = "alpha"
try {
some = "omega"
}
catch (e: Exception) {}
some.length
}

View File

@@ -0,0 +1,4 @@
compiler/testData/cli/jvm/legacySmartCastsAfterTry.kt:2:25: warning: variable 'some' initializer is redundant
var some: String? = null
^
OK

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,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,29 @@
// TARGET_BACKEND: JVM
// STRICT_JAVA_NULLABILITY_ASSERTIONS
// FILE: box.kt
fun box(): String {
try {
J().test()
return "Fail: should throw"
}
catch (e: Throwable) {
return "OK"
}
}
// FILE: test.kt
fun withAssertion(j: J) = j.nullString()
// FILE: J.java
import org.jetbrains.annotations.NotNull;
public class J {
public @NotNull String nullString() {
return null;
}
public void test() {
TestKt.withAssertion(this);
}
}

View File

@@ -0,0 +1,34 @@
// TARGET_BACKEND: JVM
// STRICT_JAVA_NULLABILITY_ASSERTIONS
// See KT-8135
// We could generate runtime assertion on call site for 'generic<NOT_NULL_TYPE>()' below.
// FILE: box.kt
fun box(): String {
try {
J().test()
return "OK"
}
catch (e: Throwable) {
return "Fail: SHOULD NOT throw"
}
}
// FILE: test.kt
fun withAssertion(j: J) = generic<String?>(j)
fun <T> generic(j: J) = j.nullT<T>()
// FILE: J.java
import org.jetbrains.annotations.NotNull;
public class J {
public <T> @NotNull T nullT() {
return null;
}
public void test() {
TestKt.withAssertion(this);
}
}

View File

@@ -0,0 +1,28 @@
// TARGET_BACKEND: JVM
// STRICT_JAVA_NULLABILITY_ASSERTIONS
// FILE: box.kt
fun box(): String {
try {
outer()
return "Fail: should throw"
}
catch (e: Throwable) {
return "OK"
}
}
// FILE: test.kt
fun outer() {
fun withAssertion() = J().nullString()
withAssertion() // NB not used itself
}
// FILE: J.java
import org.jetbrains.annotations.NotNull;
public class J {
public @NotNull String nullString() {
return null;
}
}

View File

@@ -0,0 +1,31 @@
// TARGET_BACKEND: JVM
// STRICT_JAVA_NULLABILITY_ASSERTIONS
// FILE: box.kt
fun box(): String {
try {
J().test()
return "Fail: should throw"
}
catch (e: Throwable) {
return "OK"
}
}
// FILE: test.kt
fun withAssertion(j: J) {
val x = j.nullString()
}
// FILE: J.java
import org.jetbrains.annotations.NotNull;
public class J {
public @NotNull String nullString() {
return null;
}
public void test() {
TestKt.withAssertion(this);
}
}

View File

@@ -0,0 +1,31 @@
// TARGET_BACKEND: JVM
// STRICT_JAVA_NULLABILITY_ASSERTIONS
// FILE: box.kt
fun box(): String {
try {
J().test()
return "Fail: should throw"
}
catch (e: Throwable) {
return "OK"
}
}
// FILE: test.kt
class C {
val withAssertion = J().nullString()
}
// FILE: J.java
import org.jetbrains.annotations.NotNull;
public class J {
public @NotNull String nullString() {
return null;
}
public Object test() {
return new C();
}
}

View File

@@ -0,0 +1,29 @@
// TARGET_BACKEND: JVM
// STRICT_JAVA_NULLABILITY_ASSERTIONS
// FILE: box.kt
fun box(): String {
try {
J().test()
return "Fail: should throw"
}
catch (e: Throwable) {
return "OK"
}
}
// FILE: test.kt
val withAssertion get() = J().nullString()
// FILE: J.java
import org.jetbrains.annotations.NotNull;
public class J {
public @NotNull String nullString() {
return null;
}
public void test() {
TestKt.getWithAssertion();
}
}

View File

@@ -0,0 +1,31 @@
// TARGET_BACKEND: JVM
// STRICT_JAVA_NULLABILITY_ASSERTIONS
// FILE: box.kt
fun box(): String {
try {
J().test()
return "Fail: should throw"
}
catch (e: Throwable) {
return "OK"
}
}
// FILE: test.kt
val withAssertion = J().nullString()
fun clinitTrigger() {}
// FILE: J.java
import org.jetbrains.annotations.NotNull;
public class J {
public @NotNull String nullString() {
return null;
}
public void test() {
TestKt.clinitTrigger();
}
}

View File

@@ -0,0 +1,9 @@
//WITH_RUNTIME
fun foo(x: String, ys: List<String>) =
x + ys.fold("", { a, b -> a + b })
var flag = true
fun box(): String =
foo("O", if (flag) listOf("k").map { it.toUpperCase() } else listOf())

View File

@@ -0,0 +1,39 @@
// WITH_RUNTIME
package test
class Foo {
lateinit var p: String
fun test(): Boolean {
if (!::p.isInitialized) {
p = "OK"
return false
}
return true
}
}
object Bar {
lateinit var p: String
fun test(): Boolean {
if (!::p.isInitialized) {
p = "OK"
return false
}
return true
}
}
fun box(): String {
val foo = Foo()
if (foo.test()) return "Fail 1"
if (!foo.test()) return "Fail 2"
val bar = Bar
if (bar.test()) return "Fail 3"
if (!bar.test()) return "Fail 4"
return bar.p
}

View File

@@ -0,0 +1,16 @@
// WITH_RUNTIME
// IGNORE_BACKEND: JS
package test
import test.Derived.p
open class Base(val b: Boolean)
object Derived : Base(::p.isInitialized) {
lateinit var p: String
}
fun box(): String {
return if (Derived.b) "Fail" else "OK"
}

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"
}

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