Compare commits

...

356 Commits

Author SHA1 Message Date
Nicolay Mitropolsky
5312bac2a9 Uast: KotlinAccessorCallExpression made implement JvmDeclarationUElement 2018-01-15 19:06:11 +03:00
Nicolay Mitropolsky
6c5715469a Idea version set to 173.3942.27 2018-01-15 19:06:11 +03:00
Nicolay Mitropolsky
ff30ce558d Uast: handling @receiver annotations 2018-01-15 19:06:11 +03:00
Nicolay Mitropolsky
f33d7328b9 Uast: Constructors.kt testdata fixes 2018-01-15 19:06:10 +03:00
Nicolay Mitropolsky
49e3d39327 Uast: uastParent made final in KotlinAbstractUElement 2018-01-15 19:06:10 +03:00
Nicolay Mitropolsky
b82daeb5fa Uast: no more need to exclude UIdentifier from JvmDeclarationUElement check 2018-01-15 19:06:10 +03:00
Nicolay Mitropolsky
701de5aa78 Uast: making AbstractKotlinUClass not inherit from AbstractJavaUClass 2018-01-15 19:06:09 +03:00
Nicolay Mitropolsky
f08cb75b1f Uast: removing java-uast usage from KotlinUastLanguagePlugin and KotlinEnumConstantClassReference 2018-01-15 19:05:47 +03:00
Nicolay Mitropolsky
658a23ca63 Uast: AbstractKotlinUVariable annotations now are retrieved from Kotlin Psi, not from compiled (KT-21025)
and `KotlinNullabilityUAnnotation` now is created for every `AbstractKotlinUVariable`
2018-01-15 19:05:47 +03:00
Nicolay Mitropolsky
ec8a3993f7 Uast: WrappedUAnnotation as replacement for usage of JavaUAnnotation (KT-21025) 2018-01-15 19:05:47 +03:00
Vyacheslav Gerasimov
1c92139391 Set correct until-build for Idea 173 plugin 2018-01-15 19:05:46 +03:00
Nicolay Mitropolsky
8ad25ff9f9 Fixing non-running tests, that used MockApplication environment 2018-01-15 19:05:46 +03:00
Alexey Sedunov
80ba1484c4 Data Inflow: Support grouping by expression nullability 2018-01-15 19:05:46 +03:00
Nicolay Mitropolsky
0e358021b3 Uast: Constructors.kt testData fixes 2018-01-15 19:05:46 +03:00
Alexey Sedunov
4de9eb5690 Data Inflow: Support grouping by leaf expressions 2018-01-15 19:05:45 +03:00
Alexey Sedunov
c860953447 Safe Delete: Suppress walking through light field initializer
This fixes some tests failing in 173 branch

 #KT-21508 Fixed
2018-01-15 19:05:44 +03:00
Nikolay Krasko
19bef952ab Fix inAnnotation test in 173 branch 2018-01-15 19:05:44 +03:00
Nikolay Krasko
8b4b7c0f54 Update file name replace in QuickFix tests 2018-01-15 19:05:44 +03:00
Nicolay Mitropolsky
76ce624be4 Uast: SuperCalls.render.txt testdata fix 2018-01-15 19:05:44 +03:00
Nicolay Mitropolsky
1547c4e425 Uast: AbstractKotlinUClass compilation fix 2018-01-15 19:05:44 +03:00
Nicolay Mitropolsky
825095e7c8 Spring: fix for package-completion tests
because otherwise `java` package name interfere with `java` directory name completion from somewhere
2018-01-15 19:05:44 +03:00
Nicolay Mitropolsky
dafbabd33d Spring: removing needless EP-s because they ported to UAST in platform 2018-01-15 19:05:44 +03:00
Nicolay Mitropolsky
b6bee67d5f KotlinSpringComponentScanInspection made to support platform JamReferenceContributor 2018-01-15 19:05:43 +03:00
Vyacheslav Gerasimov
951abf5818 Drop missing gradle extensions from gradle.xml 2018-01-15 19:05:43 +03:00
Nikolay Krasko
a6d00c68b5 Update test data because of changed action name in 173 2018-01-15 19:05:43 +03:00
Nicolay Mitropolsky
6ed01fc635 Idea version set to 173.3727.22(RC1) 2018-01-15 19:05:43 +03:00
Nicolay Mitropolsky
3bdf0a6b1a UAST: StringTemplateComplex testdata fix 2018-01-15 19:05:43 +03:00
Alexey Sedunov
859c39d60c Line Markers: Respect subclass module when filtering out duplicates
#KT-21010 Fixed
2018-01-15 19:05:43 +03:00
Alexey Sedunov
f0cb8a6cac Move: Fix applicability check in IDEA 173 2018-01-15 19:05:43 +03:00
Vyacheslav Gerasimov
d88a83d734 Fix formatting for new kotlin dsl gradle project build script 2018-01-15 19:05:42 +03:00
Vyacheslav Gerasimov
ed2a85de27 Drop new Kotlin Dsl gradle project wizard which has been merged to idea 2018-01-15 19:05:42 +03:00
Nicolay Mitropolsky
e26a0c6896 SpringTestFixtureExtension: option to forbid facet autoconfigure added 2018-01-15 19:05:42 +03:00
Nicolay Mitropolsky
23d9694707 SpringKotlinAutowiringInspection: getting rid of SpringJavaInjectionPointsAutowiringInspection 2018-01-15 19:05:42 +03:00
Nicolay Mitropolsky
8a55e48784 AbstractIntentionTest: isApplicableOnPooled made run under ProgressIndicator 2018-01-15 19:05:42 +03:00
Vyacheslav Gerasimov
7b6834fb25 Update ideaVersion to 173.3415.22 2018-01-15 19:05:42 +03:00
Nicolay Mitropolsky
59131f294b Ultimate-plugin: UAST added as dependency 2018-01-15 19:05:42 +03:00
Nicolay Mitropolsky
3fb327a957 Ultimate-plugin: multiplePropertiesAnnotationConfig.kt test data fixes
`@Qualifier` should not be there. It was a bug in platform
2018-01-15 19:05:41 +03:00
Nicolay Mitropolsky
280a3e74c4 AbstractQuickFixTest: FORCE_PACKAGE_FOLDER directive added
It was added as workaround for IDEA-176033 (IDEA-176032 in particular)
2018-01-15 19:05:41 +03:00
Nicolay Mitropolsky
c19486b802 AbstractExtractionTest: fix for invalid files
`configureByFile` should be run after other configurations (like `configureKotlinRuntimeAndSdk`) because they could make configured file invalid
2018-01-15 19:05:41 +03:00
Nicolay Mitropolsky
9a3d890437 RecursiveMethodCallMarkerInfo and SuspendCallMarkerInfo forced to target Leaf-elements
because of restriction added in IDEA 173
2018-01-15 19:05:41 +03:00
Nicolay Mitropolsky
dbb93af9bf AbstractNavigateToLibraryTest: fix for invalid files
otherwise current file is invalidated by `configureAs` and `additionalConfig`
2018-01-15 19:05:41 +03:00
Nicolay Mitropolsky
890077c690 EdtTestUtil.runInEdtAndWait fix for proper user action emulation
changed because `com.intellij.ide.IdeEventQueue` doesn't consider events from `SwingUtilities.invokeAndWait` as user interaction
2018-01-15 19:05:41 +03:00
Nicolay Mitropolsky
fee91f762b KotlinCoreEnvironment: set ideaCompatibleBuildNumber = "173.1" 2018-01-15 19:05:41 +03:00
Nicolay Mitropolsky
ec15a56e88 UAST: SimpleKotlinRenderLogTest.testWhenAndDestructing testdata fix 2018-01-15 19:05:40 +03:00
Nicolay Mitropolsky
53401f25a5 AbstractJavaToKotlinConverterForWebDemoTest: setup fix: JvmElementProvider and JavaModuleSystem added 2018-01-15 19:05:40 +03:00
Mikhail Glukhikh
017635c1fc ExpressionOfTypeProcessor: get member name in read action 2018-01-15 19:05:40 +03:00
Mikhail Glukhikh
18218bf58d Fix find usages tests in 173 (run via ProgressIndicator) 2018-01-15 19:05:40 +03:00
Nicolay Mitropolsky
ceebcfe64c Workaround for CoreEnvironment initialization: explicitly setting versions for extensions 2018-01-15 19:05:40 +03:00
Nicolay Mitropolsky
56b2993ba5 Spring gutter icons SpringApiIcons -> SpringApiIcons.Gutter fix.
Following the patch in idea https://upsource.jetbrains.com/IDEA/revision/ultimate-527b9189219f191b62eed59d699f57acccda05c3
2018-01-15 19:05:40 +03:00
Nicolay Mitropolsky
fd25152db0 Idea version set to 173.3302.8 2018-01-15 19:05:40 +03:00
Nikolay Krasko
e8cd61c75c Update file structure tests as FileStructurePopup api was changed in 173 2018-01-15 19:05:40 +03:00
Nicolay Mitropolsky
4b96acfbd7 Spring-Kotlin: Gutter repaired (KT-20550, KT-20566)
Platform now allows Gutter to be placed only on leafs elements, this patch fixes it for `KotlinSpringClassAnnotator`.
2018-01-15 19:05:39 +03:00
Ilya Gorbunov
b88417f98d streamex version was changed in 173-snapshot to 0.6.5 2018-01-15 19:05:39 +03:00
Nicolay Mitropolsky
3ed6b1e1e4 UAST: support for JvmDeclarationUElement 2018-01-15 19:05:39 +03:00
Nicolay Mitropolsky
32d90fbc86 UAST test data fixes: LocalVariableWithAnnotationKt fix for variable type
it is not clear for me why it was not `String`
2018-01-15 19:05:39 +03:00
Nicolay Mitropolsky
1a13f1f9ca UAST test data fixes: @null in render
as a "nullability" annotation for primitive types
2018-01-15 19:05:39 +03:00
Nicolay Mitropolsky
e04dffd32c idea-version set to since-build="173.1" until-build="181.*" 2018-01-15 19:05:39 +03:00
Vyacheslav Gerasimov
c09f4b3857 Fix GradleNoduleBuilder use qualified names check 2018-01-15 19:05:39 +03:00
Nicolay Mitropolsky
bab397f930 JvmFacade-related tests repair 2018-01-15 19:05:38 +03:00
Simon Ogorodnik
12d301d172 Fix proguard settings for 173 2018-01-15 19:05:38 +03:00
Simon Ogorodnik
b5f32ecd42 Fix compilation in 173 2018-01-15 19:05:38 +03:00
Anton Bannykh
9b244bbdf0 Fix compilation (MockParameterInfoUIContext.java)
(cherry picked from commit 21b0956)
2018-01-15 19:05:38 +03:00
Nicolay Mitropolsky
cf04a0dbfe KotlinLanguageInjector using Registry to enable annotation injections
(cherry picked from commit 8bdfeb7)
2018-01-15 19:05:38 +03:00
Simon Ogorodnik
15de7b25c3 Fix compilation 2018-01-15 19:05:38 +03:00
Dmitry Jemerov
adeee2ea36 Fix compatibility with BuildScriptDataBuilder API changes 2018-01-15 19:05:38 +03:00
Nicolay Mitropolsky
415bf894fc KotlinLanguageInjector#injectInAnnotationCall optimization: using PsiClassNamePatternCondition to avoid calling getResolvedCall 2018-01-15 19:05:37 +03:00
Nicolay Mitropolsky
1b19a033ce KotlinLanguageInjector can inject into files modified for autocompletion 2018-01-15 19:05:37 +03:00
Nicolay Mitropolsky
bca109473f KotlinLanguageInjector understands patterns-injections into Java annotations 2018-01-15 19:05:37 +03:00
xiexed
8637125bf0 KtLightAbstractAnnotation build fix for 173 (#1283) 2018-01-15 19:05:37 +03:00
Dmitry Jemerov
f8a207532c Register new service and EPs added in 173 2018-01-15 19:05:37 +03:00
xiexed
c1859a28af Fixes for 173 after 28.08.17 changes in IDEA (#1271)
* `JarFileSystem.getJarRootForLocalFile` now is nullable in IDEA

* Spring-related renamings following ones in IDEA
2018-01-15 19:05:36 +03:00
Nicolay Mitropolsky
1f1323d08e Build fix for KotlinSpringClassAnnotator after collectNavigationMarkers nullability changes in IDEA 173 2018-01-15 19:05:36 +03:00
Vyacheslav Gerasimov
881617e08a UAST: Fix testPropertyWithAnnotation 2018-01-15 19:05:36 +03:00
Vyacheslav Gerasimov
6b5059bc0e UAST: Add testConvertTypeInAnnotation 2018-01-15 19:05:36 +03:00
Vyacheslav Gerasimov
e50a774bcc UAST: override getFunctionalInterfaceType + test 2018-01-15 19:05:36 +03:00
Vyacheslav Gerasimov
034632cb5c UAST: Properly handle annotations on local variables 2018-01-15 19:05:35 +03:00
Vyacheslav Gerasimov
6f9f20be66 Fix compilation 2018-01-15 19:05:35 +03:00
Vyacheslav Gerasimov
da747f8559 Download IDEA 173.3188.16 2018-01-15 19:05:35 +03:00
Nikolay Krasko
bf0ea2a6f3 == 172 -> 173 ^^^ == 2018-01-15 19:05:35 +03:00
Natalia Selezneva
d13ae20275 Debugger: do not fail if j2k couldn't convert expression creating codeFragment from text 2018-01-15 18:40:04 +03:00
Nicolay Mitropolsky
90b79bd9c7 Uast: Fix for missing local variables in ctor-s bodies
similar to how it is done in `KotlinUBlockExpression`

(cherry picked from commit f4a7ecc)
2018-01-15 17:52:18 +03:00
Yan Zhulanow
2607972422 Kapt: Temporarily disable location mapping for stub declarations
Placing location table inside .java file triggers annotation processor to run on each line table modification (even when the stub declarations themselves are the same). The right way is to move the metadata out of the .java file, but we need an another EAP for that.
2018-01-15 23:30:49 +09:00
Anton Bannykh
00b2388c10 JS DCE: drop unknown file report severity to WARNING
*.kjsm and other files might be received when FileCollection is
used in Gradle as a dependency.

Example: `testCompile project(":$coroutines_core").sourceSets.test.output`
(a popular-ish solution to introduce dependencies between tests)

(cherry picked from commit c6d7ffb3eb)
2018-01-12 20:58:01 +03:00
Anton Bannykh
93b05ccec0 Reformat K2JSDce.kt
(cherry picked from commit 5d6d321fb2)
2018-01-12 20:57:53 +03:00
Nicolay Mitropolsky
a8ee34865b KtLightAnnotation: handling vararg with single arg (EA-114679)
It is deprecated but yet possible form of usage

(cherry picked from commit 9cb62d6)
2018-01-11 17:23:01 +03:00
Yan Zhulanow
38aa7c2e20 Kapt: Add missing 'flush()', otherwise the serialized data can be empty (KT-22226)
This fixes a Maven integration tests for kapt.
2018-01-11 22:23:17 +09:00
Alexey Sedunov
317f403acc Gradle: Use copyable user data for compiler plugin options
#KT-22227 Fixed
2018-01-11 16:16:19 +03:00
Ilya Gorbunov
5d80387406 Add sample for coerceIn with floating point range
#KT-20357

(cherry picked from commit 6197c5bf7f)
2018-01-11 09:37:30 +03:00
Ilya Gorbunov
aba4301e17 Add samples for coerceIn, coerceAtLeast, coerceAtMost for comparable types
#KT-20357

(cherry picked from commit 8fc83e3ff5)
2018-01-11 09:37:28 +03:00
shiraji
f8aa5503e6 Add samples for coerceIn
#KT-20357

(cherry picked from commit 17573a3c21)
2018-01-11 09:37:26 +03:00
shiraji
41e486ee3a Add samples for coerceAtMost
#KT-20357

(cherry picked from commit 4559da9848)
2018-01-11 09:37:24 +03:00
shiraji
fc90512d06 Add samples for coerceAtLeast
#KT-20357

(cherry picked from commit db607e231c)
2018-01-11 09:37:22 +03:00
kenji tomita
e8509c0c06 Add samples for reversed list views
#KT-20357

(cherry picked from commit 1db0e5c23e)
2018-01-11 09:37:20 +03:00
AdamMc331
56a6f89f90 Added samples for property delegates as part of KT-20357.
(cherry picked from commit 2fc26ba08f)
2018-01-11 09:37:18 +03:00
Vyacheslav Gerasimov
66ed8c0f94 Update changelog for 1.2.20 2018-01-10 20:27:13 +03:00
Nicolay Mitropolsky
90230168d4 Revert imports changes in KotlinUastLanguagePlugin.kt and KotlinUastApiTest.kt 2018-01-10 17:21:12 +03:00
Denis Zharkov
9ae269160a Add -Xsupport-compatqual-checker-framework-annotations flag
It's implemented through Jsr305State while it's not related
to jsr-305 becasue currently it's the most convenient way
to introduce the flag.

Probably, it's worth renaming Jsr305State to something more abstract
like NullabilityAnnotationsConfiguration

 #KT-21982 Fixed
2018-01-10 17:03:38 +03:00
Alexey Sedunov
c754cd79df Gradle: Compile Gradle models/model builders for plugins under JVM 1.6
This prevents imports failure in projects using older versions of Gradle
2018-01-10 16:21:25 +03:00
Alexey Sedunov
86ef1751e4 Maven: Fix <args> parsing on import to the Kotlin facet
#KT-22153 Fixed
2018-01-10 16:19:49 +03:00
Ilya Gorbunov
0aea2d94a7 Samples: add some operations to do with the constructed ranges
(cherry picked from commit c8bd623d69)
2018-01-10 15:38:00 +03:00
kenji tomita
ae6782642a Add samples for range construction operators
(cherry picked from commit 4cb2b12f01)
2018-01-10 15:38:00 +03:00
Andre Perkins
94d6f5ac5c Add sample for emptySet
(cherry picked from commit 31d650a041)
2018-01-10 15:37:59 +03:00
Jake Wharton
e23c40ac8f Implement String.toBoolean() for JS.
#KT-16348

(cherry picked from commit 11696ac4c0)
2018-01-10 15:37:58 +03:00
Ilya Chernikov
cf08a9e424 Make daemon starting more tolerant to the failures - retry
(cherry picked from commit 386cfec)
2018-01-10 13:35:16 +01:00
Nicolay Mitropolsky
930574068b Uast: KtLightAnnotation converting support (KT-21702)
(cherry picked from commit 4a4bf56)
2018-01-10 15:14:44 +03:00
Dmitry Jemerov
269f49deca Don't generate references to eap-1.1 and eap-1.2 repositories
Now all Kotlin EAP releases are published only to kotlin-eap on Bintray

(cherry picked from commit 99a9634609)
2018-01-10 12:19:23 +01:00
Dmitry Jemerov
f9b7447b8c Don't generate references to eap-1.1 and eap-1.2 repositories
Now all Kotlin EAP releases are published only to kotlin-eap on Bintray

(cherry picked from commit 99a9634)
2018-01-10 12:15:36 +01:00
Yan Zhulanow
ace2570e34 EA-101715: Handle also case with IntegerValueTypeConstructor 2018-01-10 17:50:17 +09:00
Yan Zhulanow
e65b41153f Kapt: Be less strict when it's impossible to add a generated Kotlin source directory for Android project (KT-22056, EA-114271) 2018-01-10 17:50:16 +09:00
Yan Zhulanow
835a9c55aa Kapt: Remove laziness from diagnosticFactory and javacMessages, use factory from supertype (KT-22189)
writeDiagnostic() may be invoked after the 'context' is cleared, and lazy implementations will fail.
2018-01-10 17:50:15 +09:00
Yan Zhulanow
6e91144fe6 Minor: Remove bulk class added by mistake 2018-01-10 17:50:14 +09:00
Yan Zhulanow
34dc2f737b Minor: Fix problem in IDE with @TestOnly annotation resolution 2018-01-10 17:50:13 +09:00
Yan Zhulanow
dee5adfc1f Use Gradle API to import annotations from compiler plugins instead of nasty data storage tasks
Tasks itself will be left for some time until all users migrate to the newer IDE plugin versions.
2018-01-10 17:50:13 +09:00
Yan Zhulanow
b94b02cfa4 Minor: Fix red code in IDE 2018-01-10 17:50:12 +09:00
Yan Zhulanow
ca2b0990d3 SamWithReceiver: Add Maven/Gradle importers for SamWithReceiver 2018-01-10 17:50:11 +09:00
Yan Zhulanow
c5e6dac10f AllOpen: Fix incorrect 'accessing non-final property in constructor' warning (KT-16619) 2018-01-10 17:50:10 +09:00
Yan Zhulanow
9a03a89efb Kapt: Store line information in a file doc comment, instead of annotations (KT-21936) 2018-01-10 17:50:10 +09:00
Yan Zhulanow
bc1f7d71fb NoArg: Parse 'invokeInitializers' option in Maven importer (KT-19900) 2018-01-10 17:46:57 +09:00
Yan Zhulanow
53fa6ff803 Compiler plugins: Refactor Maven import handlers in order to support other plugin options 2018-01-10 17:46:51 +09:00
Yan Zhulanow
986cda3e22 Kapt: Clear stubs directory on non-incremental stub generation (KT-21735) 2018-01-10 17:46:45 +09:00
Dmitry Jemerov
b41446e586 Fix HighlightingTestGenerated and LambdaImplicitHintsTest
(cherry picked from commit 361824e)
2018-01-09 18:05:41 +01:00
Dmitry Jemerov
4bc5d46fa8 Honor "Use continuation indent in argument lists" for indent by Enter
#KT-22121 Fixed

(cherry picked from commit 8c7f57c)
2018-01-09 15:44:52 +01:00
Dmitry Jemerov
0c9e23c5c5 Refactoring: replace WrappingStrategy interface with lambda
(cherry picked from commit d79ac58)
2018-01-09 15:44:44 +01:00
Dmitry Jemerov
49cb5aff4b Don't wrap argument list containing anonymous functions
Just like for objects and lambdas, don't consider line breaks inside
anonymous functions as line breaks inside argument list

(cherry picked from commit 67897d9)
2018-01-09 15:44:36 +01:00
Dmitry Jemerov
10093b36e3 Improved logic for chained lambda indentation
#KT-22071 Fixed

(cherry picked from commit a5cc980)
2018-01-09 15:44:29 +01:00
Dmitry Jemerov
c7023c0a7e Use receiver type of extension members as qualifier in Goto Symbol
#KT-17217 Fixed

(cherry picked from commit 54c262c)
2018-01-09 15:44:20 +01:00
Dmitry Jemerov
6b2f35e4d1 Show line marker navigation actions in Alt-Enter menu
#KT-14951 Fixed

(cherry picked from commit 0104ed7)
2018-01-09 15:44:12 +01:00
Dmitry Jemerov
25b4ecae69 Delegate Ctrl-Shift-Enter to plain handler if needed
#KT-11503 Fixed

(cherry picked from commit 63af3c8)
2018-01-09 15:44:02 +01:00
Dmitry Jemerov
a538e88f2f Don't require documentation in test sources
#KT-21837 Fixed

(cherry picked from commit f36f85f)
2018-01-09 15:43:52 +01:00
Dmitry Jemerov
67f1ed0803 SortModifiersInspection detects modifiers before annotations
#KT-22013 Fixed

(cherry picked from commit 165ac97)
2018-01-09 15:43:42 +01:00
Dmitry Jemerov
7536dc1544 Check that a file with .kt extension is actually a KtFile
#KT-22111 Fixed

(cherry picked from commit 408c753)
2018-01-09 15:43:22 +01:00
Dmitry Jemerov
bb3afcb6b0 Cleanup: apply all inspection quickfixes
(cherry picked from commit 69c8da7)
2018-01-09 15:43:11 +01:00
Dmitry Jemerov
e4f1d4116f Reformat
(cherry picked from commit 6f722d6)
2018-01-09 15:43:02 +01:00
Dmitry Jemerov
997b04be24 Check correct element to determine if 'if' rbrace needs wrapping
#KT-22093 Fixed

(cherry picked from commit 6299e0e)
2018-01-09 15:42:53 +01:00
Dmitry Jemerov
26e613e198 Call arguments should not affect parameter names returned in MethodInfo
The parameter names are only used for blacklist filtering, and should
correspond only to the function being called; the order and number of
actually provided arguments does not matter.

(cherry picked from commit e9ca6a6)
2018-01-09 13:51:51 +01:00
Dmitry Jemerov
54813f401b Rename test to correspond to the name of code under test
(cherry picked from commit 599bb87)
2018-01-09 13:51:43 +01:00
Dmitry Jemerov
9598ca900e Respect imports when rendering class names in type hints
#KT-19524 Fixed

(cherry picked from commit 78682ac)
2018-01-09 13:51:37 +01:00
Dmitry Jemerov
78e39a666d Prototype of inlay hints for suspending calls (KT-20187)
(cherry picked from commit 45282af)
2018-01-09 13:51:31 +01:00
Dmitry Jemerov
12b0cdb7ed Don't show type hints for SAM constructors
#KT-22050 Fixed

(cherry picked from commit d060203)
2018-01-09 13:51:24 +01:00
Dmitry Jemerov
a09ca78828 Better position of argument name hint for multiline varargs
#KT-20614 Fixed

(cherry picked from commit 0991dba)
2018-01-09 13:51:12 +01:00
Dmitry Jemerov
15239b117d Show inlay hints for implicit parameters and receivers of lambdas
#KT-20533 Fixed

(cherry picked from commit 6c23d3a)
2018-01-09 13:51:04 +01:00
Dmitry Jemerov
f0304af6bc Add inlay hints for values returned from lambdas
#KT-20067 Fixed

(cherry picked from commit da157fa)
2018-01-09 13:50:57 +01:00
Dmitry Jemerov
9f93caea76 Cleanup: better function name
(cherry picked from commit e558837)
2018-01-09 13:50:46 +01:00
Toshiaki Kameyama
713f0f577f KT-21949 Please add a separate Color Scheme settings for properties synthesized from Java accessors (#1458)
(cherry picked from commit 3b21255)
2018-01-08 13:07:25 +01:00
Toshiaki Kameyama
8a8120497f KT-21213 multiline kdoc - intellij joins lines together without space (#1459)
* KT-21213 multiline kdoc - intellij joins lines together without space

* Use \n directly as a line separator #KT-21213

* Remove unused import #KT-21213

(cherry picked from commit 19c35ef)
2018-01-05 15:31:15 +01:00
Dmitry Jemerov
bdf349844e Avoid exception from DocumentImpl.setInBulkUpdate in reformat inspection
#KT-21036 Fixed

(cherry picked from commit d51dd97)
2018-01-04 19:05:02 +01:00
Toshiaki Kameyama
59637b1dd4 KT-21974 Editor color scheme option for Kotlin typealias names (#1457)
(cherry picked from commit 266b40b)
2018-01-04 17:42:12 +01:00
Toshiaki Kameyama
c9e413e853 Add intention to specify all types explicitly in destructuring assignment
#KT-16260 Fixed

(cherry picked from commit 6b2c22a)
2018-01-03 17:26:49 +01:00
Toshiaki Kameyama
88e715ed2f KT-18674 Join Lines should join strings (#1305)
* Join Lines should join strings #KT-18674 Fixed

* #KT-18674 Fixed

(cherry picked from commit eb12cfd)
2018-01-03 11:28:42 +01:00
Toshiaki Kameyama
edd860ea18 KT-21929 Inappropriate quick fix for a sealed class instantiation (#1444)
(cherry picked from commit 16695c1)
2018-01-03 11:22:21 +01:00
Toshiaki Kameyama
457c2eaae7 KT-21780 Wrong redundant setter inspection (#1453)
(cherry picked from commit de185b7)
2018-01-03 11:16:20 +01:00
Toshiaki Kameyama
40d92ca413 KT-14670 Support kotlinPackageName() macro in live templates (#1455)
* KT-14670 Support kotlinPackageName() macro in live templates

* Use context.psiElementAtStartOffset.containingFile #KT-14670

(cherry picked from commit 640c28c)
2018-01-03 11:13:16 +01:00
Dmitry Jemerov
90cf47542b Add a rule for invalid characters in names
(cherry picked from commit 84d6305)
2018-01-02 14:37:16 +01:00
Dmitry Jemerov
2e7fddbf72 Apply same style for top-level and object properties
#KT-20437 Fixed

(cherry picked from commit f83c534)
2018-01-02 14:37:16 +01:00
Dmitry Jemerov
e04510bea2 Naming convention inspection for test functions
#KT-21547 Fixed

(cherry picked from commit 1c7d972)
2018-01-02 14:37:16 +01:00
Dmitry Jemerov
881be4dac0 Report more friendly messages from naming conventions inspection
#KT-19736 Fixed

(cherry picked from commit 37d2ff2)
2018-01-02 14:37:16 +01:00
Dmitry Jemerov
acb9e19d4e Reformat
(cherry picked from commit 429bf5b)
2018-01-02 14:37:16 +01:00
Sergey Igushkin
f8ee0e12b9 Fix incomplete cherry-pick of Gradle build cache 2018-01-02 15:07:51 +03:00
Toshiaki Kameyama
5adc0bcffe KT-15320 Live templates: please add function which returns the "outer" class name
(cherry picked from commit 79ff365)
2018-01-02 12:43:52 +01:00
Sergey Igushkin
0fe3ed1e31 (minor) Separate the Gradle annotations from CompilerArgumentAware
(cherry picked from commit e49a52b)
2018-01-02 14:27:50 +03:00
Sergey Igushkin
ba60d83d9c Improve disambiguation of subplugin option inputs
The original approach required evaluating the existing input properties
of the task. This led to evaluation of the property values, and could
execute incorrectly if the task was not properly initialized at that
moment.
The new approach fixes that by first grouping options from each
subplugin by key and then adding disambiguating index suffixes.

(cherry picked from commit 6eb028a)
2018-01-02 14:27:34 +03:00
Sergey Igushkin
29485df0db Move conditional task caching setup into the task constructors;
Add 'kotlin.caching.enabled' flag to switch the caching for all tasks;
Rename and change semantics of cache support checks: make two instead
    of one, `isBuildCacheSupported` and `isBuildCacheEnabledForKotlin`;
Remove FileOptionKind entries that are redundant at the moment;
Improvements in BuildCacheIT.kt and other refactoring  suggestions from
    the review
    https://upsource.jetbrains.com/kotlin/review/KOTLIN-CR-1647

(cherry picked from commit a668a12)
2018-01-02 14:27:03 +03:00
Sergey Igushkin
f788bc2f33 Fix top-level property of an API-level-dependent class: move to the body
(cherry picked from commit cc86a36)
2018-01-02 14:26:09 +03:00
Sergey Igushkin
6ace267699 Add BuildCacheRelocationIT, remove same files testing as redundant.
(cherry picked from commit d444b7d)
2018-01-02 14:25:53 +03:00
Sergey Igushkin
dce565e32d Fix JS DCE classpath duplicated in two input properties
* Do not add the classpath elements to source to avoid them being
  treated as task inputs without proper classpath normalization
* Move resolution of the classpath configuration to execution time

(cherry picked from commit 14a6248)
2018-01-02 14:25:36 +03:00
Sergey Igushkin
e141472704 Fix Kotlin destination dir added to Java task without normalization.
Issue #KT-20604 Fixed

(cherry picked from commit dcd5192)
2018-01-02 14:25:17 +03:00
Sergey Igushkin
4316e24243 Turn on relocatable build cache -- change PathSensitivity to RELATIVE
(cherry picked from commit a6d0775)
2018-01-02 14:25:00 +03:00
Sergey Igushkin
60bffb9c21 Subplugin options refactoring & Gradle input improvements
Introduce FilesSubpluginOption Special kind of SubpluginOption that
holds a list of files together with the kind of these files with respect
to the task.

Add a logic for handling such options and converting them into
task inputs.

Refactor CompilerPluginOptions: make it store subplugin options to be
able to add options from KotlinCompile to the kapt tasks.

Introduce WrapperSubpluginOption for encoded and complex options.

Remove pluginOptions from the Gradle inputs built from the
compiler args.

Do not cache Kotlin compilation with kapt1 enabled: since we are going
to drop kapt1 it anyway, there's no point in implementing
proper cache for it, so just disable the caching of the task in case
kapt1 is used.

(cherry picked from commit 81c596d)
2018-01-02 14:24:42 +03:00
Sergey Igushkin
3a7df0be10 Add integration tests for Gralde build cache support.
Add an up-to-date'ness test for subplugin options.

(cherry picked from commit ee148f5)
2018-01-02 14:24:23 +03:00
Sergey Igushkin
de9f61406e Explicit opt-in switch for Kapt caching.
(cherry picked from commit 23a57f3)
2018-01-02 14:24:05 +03:00
Sergey Igushkin
15c37555bb Add Kotlin sources output as a separate output directory for kapt.
(cherry picked from commit 6f2fdcf)
2018-01-02 14:23:48 +03:00
Sergey Igushkin
a62543fc55 Disable IC when IC cache is missing
Check task build directory for any files

(cherry picked from commit 5f2a652)
2018-01-02 14:23:31 +03:00
Sergey Igushkin
3955d6f2b0 Make the tasks cacheable, add logic that decides whether to cache them
(cherry picked from commit e71446b)
2018-01-02 14:23:11 +03:00
Sergey Igushkin
e2bf5d298d Annotate the properties with @PathSensitive (+ override source)
(cherry picked from commit 46ed706)
2018-01-02 14:22:53 +03:00
Sergey Igushkin
3c05d3c3ca Add @LocalState of buildServicesWorkingDir to KotlinCompile
(cherry picked from commit 835097d)
2018-01-02 14:22:38 +03:00
Sergey Igushkin
fbb14ada36 Map compiler arguments to Gradle inputs.
(cherry picked from commit b637252)
2018-01-02 14:22:22 +03:00
Sergey Igushkin
3af0d5745e Make pluginOptions.classpath a separate input in the Gradle tasks
(cherry picked from commit b03e758)

(cherry picked from commit dab4acd)
2018-01-02 14:22:05 +03:00
Sergey Igushkin
4a530b8bf4 Move CompilerArgumentAware to the <...>.internal package.
(cherry picked from commit b7b0d8e)
2018-01-02 14:21:46 +03:00
Sergey Igushkin
5eee3a31df Refactor compiler arguments in Gradle tasks:
Pull create/setup args functions up to CompilerArgumentsAware interface
Remove diamond-shaped CompilerArgumentsAware inheritance
Provide the default implementation for serialization in the interface
Make KotlinJsDce implement CompilerArgumentsAware
Implement the compiler args logic for Kapt & GenerateStubs tasks

(cherry picked from commit b3bee53)
2018-01-02 14:21:29 +03:00
Ilya Gorbunov
1123fb8ee7 Keep exception primary constructors for binary compatibility in JS
Resort to a workaround for KT-22053 in direct Throwable inheritors.

(cherry picked from commit e2306ecf94)
2017-12-30 20:21:22 +03:00
Ilya Gorbunov
111623335d Update expected reachable node count
(cherry picked from commit 3825187e93)
2017-12-30 20:21:20 +03:00
Ilya Gorbunov
7938f56d25 Relax nullability of UninitializedPropertyAccessException constructor parameters
To make it consistent with other exception types

(cherry picked from commit a1f67e347f)
2017-12-30 20:21:18 +03:00
Ilya Gorbunov
b3f57dbe3a Add missing exception constructors to common and JS declarations
Add test to validate exception properties after calling various constructors.

Make NumberFormatException a descendant of IllegalArgumentException in all platforms.

#KT-21861 Fixed
#KT-21191 Fixed

(cherry picked from commit 4e26ca5659)
2017-12-30 20:21:16 +03:00
Pavel V. Talanov
598adee862 Scripts: fix any file deletion potentially leading to reindex 2017-12-29 20:22:50 +03:00
Toshiaki Kameyama
d435622249 Specify type: do not suggest nullable type if not null is overridden
So #KT-12814 Fixed

(cherry picked from commit 817dadc)
2017-12-29 20:11:52 +03:00
Mikhail Glukhikh
fe6ad4f8fd Add modifier fix: improve style a bit
(cherry picked from commit 50eaca1)
2017-12-29 20:11:40 +03:00
Toshiaki Kameyama
1f755ed331 Do not suggest "add inner" quick fix for interfaces etc. #KT-18396 Fixed
(cherry picked from commit 184651d)
2017-12-29 20:11:29 +03:00
Toshiaki Kameyama
cdd07ceb34 Add inspection to detect is checks for object types #KT-21741 Fixed
(cherry picked from commit 84a6ef6)
2017-12-29 20:11:15 +03:00
Dmitry Jemerov
db791e0b60 Send source code in exceptions as attachments, not text (common cases)
#KT-17678 In Progress

(cherry picked from commit 25ea534)
2017-12-29 15:41:23 +01:00
Mikhail Glukhikh
d1c4992a9a Do not report "redundant suspend" on override / open #KT-21938 Fixed
(cherry picked from commit fc93e7a)
2017-12-29 14:53:16 +03:00
Mikhail Glukhikh
1d82608d60 Build fix: convert reference to lambda
Related to KT-19283 (fixes mistake in 3f005924)

(cherry picked from commit 0df3ffb)
2017-12-29 14:52:03 +03:00
Toshiaki Kameyama
9df3359719 Do not suggest quickfix 'Specify type explicitly' with existing type
So #KT-15180 Fixed

(cherry picked from commit 5e765c5)
2017-12-29 14:51:46 +03:00
Mikhail Glukhikh
ad3f6bd5fa Elvis -> if-then: handle case with safe cast separately #KT-17816 Fixed
(cherry picked from commit 5475f99)
2017-12-29 14:51:26 +03:00
Mikhail Glukhikh
810d3bec56 Lambda -> reference: build bound reference for complex qualified
So #KT-19073 Fixed

(cherry picked from commit ec60c92)
2017-12-29 14:51:14 +03:00
Mikhail Glukhikh
9a967ec844 Allow using add modifier quick-fixes in batch mode #KT-21950 Fixed
(cherry picked from commit 73bca21)
2017-12-29 14:51:02 +03:00
Mikhail Glukhikh
2cd529833c Fix potential leak in "unused lambda expression body" fix
(cherry picked from commit 2e71691)
2017-12-29 14:50:39 +03:00
Mikhail Glukhikh
4567fd0c39 Add extra tests for KT-20429, simplify code a bit
(cherry picked from commit 8e23ca5)
2017-12-29 14:50:26 +03:00
Toshiaki Kameyama
15ea032a20 CFG: provide "used as expression" in enum constant constructor
This allows to avoid
"unused return value of a function with lambda expression body"
for such a situation
So #KT-20429 Fixed

(cherry picked from commit a653045)
2017-12-29 14:50:12 +03:00
Mikhail Glukhikh
0585059906 Extend range of "use expression body" to left brace..end of return
Range is extended iff we are in DO_NOT_SHOW case,
otherwise just return is highlighted to avoid ugly highlighting
So #KT-19771 Fixed

(cherry picked from commit e10fa21)
2017-12-29 14:49:18 +03:00
Mikhail Glukhikh
e07c1c68ea Minor: improve style in "operator to function"
(cherry picked from commit 95e7d29)
2017-12-29 14:40:05 +03:00
Toshiaki Kameyama
307d54391d Do not suggest replacing comparison to null with function call
So #KT-20620 Fixed

(cherry picked from commit 52df70a)
2017-12-29 14:39:40 +03:00
Mikhail Glukhikh
d38dba06de Do not report "redundant Unit return type" on expression bodies
So #KT-21983 Fixed

(cherry picked from commit d7807b5)
2017-12-29 14:39:30 +03:00
Mikhail Glukhikh
c3a0e0dc6b Inline dialog: handle case with unknown occurrence number correctly
So #KT-21963 Fixed

(cherry picked from commit 232ec63)
2017-12-29 14:39:18 +03:00
Mikhail Glukhikh
96d6fa70f6 Inline dialog: show "inline all and keep" for occurred once declarations
So #KT-21964 Fixed

(cherry picked from commit 947e853)
2017-12-29 14:39:08 +03:00
Mikhail Glukhikh
c11b43c03e Inline dialog: unify messages with each other #KT-21965 Fixed
(cherry picked from commit d5bb7e4)
2017-12-29 14:38:57 +03:00
Mikhail Glukhikh
e439c3053e Do not suggest "convert ref to lambda" for reflect types #KT-19283 Fixed
(cherry picked from commit 3f00592)
2017-12-29 14:38:44 +03:00
Dmitry Jemerov
21195e033c More cleanup after J2K
(cherry picked from commit 896246a)
2017-12-29 10:29:41 +01:00
Dmitry Jemerov
0928618979 Catch exceptions from decompiler service
EA-108937 - RE: InvocationExprent.toJava

(cherry picked from commit d0e8e17)
2017-12-29 10:29:32 +01:00
Dmitry Jemerov
020f54d95b Don't add null module info to list
EA-113650 - TCE: LazyModuleDependencies.getModulesWhoseInternalsAreVisible

(cherry picked from commit 9a61abf)
2017-12-29 10:29:24 +01:00
Dmitry Jemerov
769c38912f Check if containing file is KtFile
EA-109460 - CCE: KtElementImplStub.getContainingKtFile

(cherry picked from commit 2c41802)
2017-12-29 10:29:12 +01:00
Dmitry Jemerov
a9f31287aa Take read action in KtLightParameter.isEquivalentTo()
EA-109775 - (OperatorReferencesSearcher) assert: PsiFileImpl.getStubTree

(cherry picked from commit 4b6efe3)
2017-12-29 10:29:02 +01:00
Dmitry Jemerov
82572e94a4 KtLightParameter: convert to .kt and cleanup
(cherry picked from commit 7f1dd88)
2017-12-29 10:28:34 +01:00
Dmitry Jemerov
ce6ea5262f KtLightElementParameter: rename to .kt
(cherry picked from commit 98d26ae)
2017-12-29 10:28:02 +01:00
Dmitry Jemerov
59d7845238 Handle I/O exceptions when updating library jars
EA-101940 - FNFE: FileUtil.openOutputStream

(cherry picked from commit cde84a7923)
2017-12-29 10:27:51 +01:00
Dmitry Jemerov
0c36b5caf6 Take longer read action in forEachKotlinOverride()
EA-114124 - assert: CompositeElement.getChildrenAsPsiElements

(cherry picked from commit 254f766)
2017-12-29 10:26:43 +01:00
Dmitry Jemerov
92501a18e0 Check for project disposed when reporting outdated libraries
EA-106858 - assert: ComponentManagerImpl.getPicoContainer

(cherry picked from commit 768fce4722)
2017-12-29 10:26:32 +01:00
Dmitry Jemerov
ff773fe3de Don't pass null element to RefactoringFactory.createRename()
EA-114286 - IAE: RenameProcessor.$$$reportNull$$$

(cherry picked from commit cc2faa6)
2017-12-29 10:25:10 +01:00
Dmitry Jemerov
96756e54a6 Don't try to read attribute for files with no ID
(EA-114351 - CCE: PersistentFSImpl.getFileId)

(cherry picked from commit 9a15654)
2017-12-29 10:25:01 +01:00
Sergey Igushkin
a351d26204 Use .withDependencies { ... } to set up default versions with Gradle 4.4
+ Improve the test for omitted Kotlin module versions.

Issues: #KT-21806 Fixed, #KT-21203 Fixed

(cherry picked from commit 276a6ac)
2017-12-28 19:52:25 +03:00
Sergey Igushkin
c26e150bc6 (minor) Fix testAndroidExtensionsIncremental() ambiguous file operation
(cherry picked from commit 685b138)
2017-12-28 19:52:24 +03:00
Sergey Igushkin
d893b4796a Fix Kotlin internal files created in 'build/' ignoring custom buildDir
Issue #KT-10537 Fixed

(cherry picked from commit 01931c2)
2017-12-28 19:52:24 +03:00
Sergey Igushkin
8462ac8ef3 Fix @OutputFile annotation on a String property outputFile.
(cherry picked from commit d51b17c)
2017-12-28 19:52:24 +03:00
Sergey Igushkin
d1b81a90c2 Add java-gradle-plugin for kotlin-gradle-plugin tasks validation;
Make task properties validation fail on warnings; run it during IT

(cherry picked from commit 9d1091c)
2017-12-28 19:52:24 +03:00
Sergey Igushkin
599c149a8c Mark Gradle task properties with input/output annotations.
(cherry picked from commit 7031087)
2017-12-28 19:52:24 +03:00
Sergey Igushkin
2778ef614a Compile against gradleApi()
(cherry picked from commit d62ced3)
2017-12-28 19:52:24 +03:00
Vyacheslav Gerasimov
2af2497d58 Update changelog for 1.2.20 2017-12-28 16:13:43 +03:00
Ilya Chernikov
13f69878c2 Reading KOTLIN_HOME only once
may fix #KT-21145, or at least make it less flaky

(cherry picked from commit efc470d)
2017-12-28 09:46:52 +01:00
Ilya Chernikov
36e07f2d00 Add kotlin-compiler-client-embeddable to the plugin's lib since...
it's used in the `KotlinJsr223JvmScriptEngine4Idea`
Fixes #KT-18613

(cherry picked from commit 945da50)
2017-12-28 09:46:30 +01:00
Ilya Gorbunov
755de4564e Fix Volatile usages in common and JS code
(cherry picked from commit 042f81f23b)
2017-12-28 02:18:16 +03:00
Ilya Gorbunov
4c25ab2f12 JS: Move declaration to match their packages in JVM and Common stdlib
Mostly internal, but also two public annotations

(cherry picked from commit a33a3867b8)
2017-12-28 02:18:14 +03:00
Ilya Gorbunov
e499f24528 Do not compile SynchronizedLazyImpl for platforms other than JVM
(cherry picked from commit d2eb8b4a3f)
2017-12-28 02:18:12 +03:00
Ilya Gorbunov
d4b9933ce4 Improve expect declarations in kotlin.text
- Replace overloads with default parameters in expect declarations by suppressing errors
- Remove meaningless inline modifier

(cherry picked from commit b6595d661d)
2017-12-28 02:18:10 +03:00
Ilya Gorbunov
08d2e29459 Remove inheritance between LinkedHashSet/Map and HashSet/Map
(cherry picked from commit 824b506abe)
2017-12-28 02:18:08 +03:00
Ilya Gorbunov
763740a49b Make common ArrayList declaration not open and implementing RandomAccess
(cherry picked from commit c5c6eed170)
2017-12-28 02:18:06 +03:00
Ilya Gorbunov
0acd2b9698 Extract kotlin.collections expect classes into separate files
Add missing expect declarations for AbstractMutableMap/Set.

(cherry picked from commit fb13347864)
2017-12-28 02:18:04 +03:00
Ilya Gorbunov
4b6c3dfff1 Move expect declarations to the appropriate packages
So that they match actual declarations in Kotlin/JVM stdlib.

(cherry picked from commit 93ef16deaf)
2017-12-28 02:18:01 +03:00
Anton Bannykh
1d9254fd92 kotlin-test-js: pass test function result to test framework (e.g. Promise)
(cherry picked from commit 2df85ae4a9)
2017-12-27 20:00:41 +03:00
Anton Bannykh
efd90b7a36 JS: test kotlin-test as box tests, support nested, fix mpp
Support tests inside nested classes and companion objects (KT-21850
fixed).
Don't launch multiplatform tests twice (KT-21567 fixed).

(cherry picked from commit 79359b7bc2)
2017-12-27 20:00:31 +03:00
Anton Bannykh
9799c6150d Make :js:npm a separate project to avoid calling update_dependencies
(cherry picked from commit 3e0d83b7d1)
2017-12-27 17:36:18 +03:00
Ilya Gorbunov
792db1469c Add racing version of each Lazy test
Run several concurrent accesses to a lazy value
many times and validate invariants.

(cherry picked from commit f468990f97)
2017-12-27 17:08:41 +03:00
Ilya Gorbunov
5dcdce291c Improve stability of lazy test, make some tests take less time
(cherry picked from commit 4827aadcfd)
2017-12-27 17:08:41 +03:00
Ilya Gorbunov
3ca581876a Do not read volatile _value field second time it is already initialized
(cherry picked from commit 934b3cc54e)
2017-12-27 17:08:40 +03:00
Ilya Gorbunov
e63a0e3823 Make SafePublicationLazyImpl.initializer volatile
This establishes happens-before relation between nulling out the initializer and
checking whether it is null. This will prevent the subsequent _value reads
being reordered before the initializer reads.

#KT-21868 Fixed

(cherry picked from commit 5d62277fa5)
2017-12-27 17:08:40 +03:00
Ilya Gorbunov
5490746bdc Add pattern and options properties to common Regex
And add a test that accesses them and checks they work as expected.

(cherry picked from commit 10639eaf6a)
2017-12-27 17:08:40 +03:00
Ilya Gorbunov
5894c52d4c Replace Regex constructor-like functions with secondary constructors
Historically secondary constructors were not supported in Kotlin/JS, so they had to
be emulated with constructor-like top level functions, now they can be rewritten
as true secondary constructors.

#KT-22003 Fixed

(cherry picked from commit d9edc5f221)
2017-12-27 17:08:39 +03:00
Ilya Gorbunov
a000111a92 Tests: use helper function to assert compile-time and run-time type check
To cleanup warnings about useless cast or type check that is always true.

(cherry picked from commit 053f3b6ac0)
2017-12-27 17:08:39 +03:00
Ilya Gorbunov
6848ea630f Compile common stdlib tests against common stdlib
Declare platform-specific test utilities as expect.

(cherry picked from commit ecd42f14b3)
2017-12-27 17:08:39 +03:00
Chris Povirk
d202cf5314 Recognize Checker Framework declaration annotations.
We are migrating Guava to use these annotations rather than jsr305's
@Nullable. We can't use the Checker Framework's _@Nullable_ yet because
we promise compatibility with Java 7, which doesn't support type
annotations. This is related to but distinct from
https://youtrack.jetbrains.com/issue/KT-21408, which is about a
different jsr305 annotation we use, @ParametersAreNonnullByDefault.

I've also updated some docs to mention Kotlin's existing support for the
Checker Framework _@NonNull_.

(cherry picked from commit ac87ad422d)
2017-12-27 13:23:29 +01:00
Ilya Chernikov
6beee0c1ba Increment repl line generation on compilation error
fixes #KT-17921 and #KT-21141
Tests added to the JSR223 local eval example

(cherry picked from commit 953a485)
2017-12-26 19:32:29 +01:00
Ilya Chernikov
cf7b5fec05 Make JSR 223 examples compatible with embeddable compiler, strip ...
some dependencies.
Fixes #KT-17561 and related issues
Warning: API changed slightly

(cherry picked from commit 2d8e73f)
2017-12-26 19:31:57 +01:00
Nikolay Krasko
d1efa8e08c More nullability update in selectors for compatibility in 181 2017-12-26 17:40:19 +03:00
Nikolay Krasko
64a4e7b607 Use platform types to prepare for nullability check in 181 2017-12-26 17:40:18 +03:00
Joscha Alisch
7a47bc1c5d Select lambda after other args when it's outside argument list (KT-21214)
#KT-21214 Fixed
2017-12-26 13:23:14 +03:00
Toshiaki Kameyama
edc6d162f4 KT-21928 Structure view doesn't show default constructor 2017-12-26 13:22:59 +03:00
Nikolay Krasko
b007da5ac3 Consistency for replace string quick fix message
https://youtrack.jetbrains.com/issue/KT-21746#comment=27-2634335
2017-12-26 13:21:24 +03:00
Nikolay Krasko
579ea2e90a Fix smart step into to Kotlin SAM adapter (KT-21538)
#KT-21538 Fixed
2017-12-26 13:21:24 +03:00
Nikolay Krasko
93e0d9336b Don't show file root if it's same as the only declaration (KT-21200)
#KT-21200 Fixed
2017-12-26 13:21:24 +03:00
Sergey Igushkin
0923c40495 Fix unconditional warning in JS compilation with sourceMap disabled.
(cherry picked from commit 149b197)
2017-12-25 16:01:36 +03:00
Sergey Igushkin
def71307e3 Fix both moduleFile and destination passed to the compiler
when it is run not in daemon from Gradle; don't pass the destination in
such case.

Issue #KT-21637 Fixed

(cherry picked from commit 66d3c94)
2017-12-25 16:01:36 +03:00
Alexey Tsvetkov
9ba9ceeb64 Track changes in inline function when friend paths are disabled in JS 2017-12-22 18:38:39 +03:00
Alexey Tsvetkov
a23f96a2dd Replace testCancelLongKotlinCompilation with less flaky test 2017-12-22 18:38:36 +03:00
Alexey Tsvetkov
d595b7d398 Explicitly request rebuild when untracked java file is removed
Previously a rebuild was happenning because FileNotFoundException
was thrown when getting psiFile of removed file.
2017-12-22 18:38:33 +03:00
Alexey Tsvetkov
e7f93c6102 Include tests from incremental-compilation-impl in compiler tests 2017-12-22 18:38:30 +03:00
Alexey Tsvetkov
56881e7783 Turn off class redeclaration test for JS IC temporarily
So the tests could be run on TC.
Turn on after KT-19846 is fixed.
2017-12-22 18:38:27 +03:00
Alexey Tsvetkov
542e556577 Generate source maps in JS IC tests
#KT-21700 fixed
2017-12-22 18:38:24 +03:00
Alexey Tsvetkov
1bb538b044 Recompile only files from last iteration after compile error 2017-12-22 18:38:21 +03:00
Alexey Tsvetkov
15bd424aba Allow to edit non-JPS build logs in "Show difference" window for non-JPS IC tests 2017-12-22 18:38:18 +03:00
Alexey Tsvetkov
e44a4bb54c Add JS specific IC build log in test
JS IC compares proto using a source file path as a key,
so moving file causes recompilation of its usages
unlike JVM IC that uses a class file path as a key.
2017-12-22 18:38:15 +03:00
Alexey Tsvetkov
0e94bfd734 Fix IC test build log diverged from JPS
JPS marks dirty direct usages of removed classes since 172.* before a build.
Generic IC also marks dirty all subclasses and their usages.
That is necessary because a method from a removed class could be used
through a subclass.
JPS and generic IC logs diverged in 172 branch, but non-JPS tests
were not run on CI.
2017-12-22 18:38:12 +03:00
Alexey Tsvetkov
d317f789be Recompile inline function usages in JS when offset is changed
Otherwise source maps would differ after rebuild
2017-12-22 18:38:09 +03:00
Alexey Tsvetkov
058b40369c Recompile all subclasses of removed classes 2017-12-22 18:38:06 +03:00
Alexey Tsvetkov
7cbd83541a Unify processing of removed files for JS and JVM IC 2017-12-22 18:38:03 +03:00
Alexey Tsvetkov
e96abbebd1 Avoid processing incremental changes after first build for JVM 2017-12-22 18:38:00 +03:00
Alexey Tsvetkov
03046159b0 Make general IC logs similar to JPS IC logs 2017-12-22 18:37:56 +03:00
Alexey Tsvetkov
cd1c87bfef Compile actual and expected declarations together
#KT-20840 fixed
2017-12-22 18:37:50 +03:00
Alexey Tsvetkov
a951af8775 Fix stdlib usages in IC tests
* Use stdlib from dist
* Check that stdlib exists
* Don't add stdlib for JS, because compiler adds one by default
(stdlib would be read twice which is slow)
2017-12-22 18:37:47 +03:00
Alexey Tsvetkov
8c0a2da7aa Minor: remove unused variable 2017-12-22 18:37:44 +03:00
Alexey Tsvetkov
f3e4232649 Avoid computing source files changes in IC for Gradle 2017-12-22 18:37:40 +03:00
Alexey Tsvetkov
5f48a4484d Allow override removing temporary module files after build
For debug purposes
2017-12-22 18:37:36 +03:00
Alexey Tsvetkov
153e296a8e Allow customizing directory for temporary module files 2017-12-22 18:37:33 +03:00
Alexey Tsvetkov
3dd3403447 Avoid generating too long path for temp module file
#KT-21841 fixed
2017-12-22 18:37:30 +03:00
Alexey Tsvetkov
99cab8129e Do not set api version to language version when language version is null
#KT-21852 fixed
    #KT-21574 fixed
2017-12-22 18:37:26 +03:00
Dmitry Jemerov
414ea3dd2d Insert line break before elvis when converting if to elvis
This ensures correct indentation
2017-12-22 10:53:59 +01:00
Dmitry Jemerov
e6e4072b55 Add option for wrapping closing paren in multiline if conditions 2017-12-22 10:53:52 +01:00
Dmitry Jemerov
10d6f4eddb Add predefined code style for Kotlin style guide 2017-12-22 10:53:47 +01:00
Dmitry Jemerov
4a615262a9 Don't apply indent on Enter after modifier list
#KT-9562 Fixed
2017-12-22 10:53:40 +01:00
Dmitry Jemerov
9d38d341bc Correctly apply annotation wrap before modifier keyword
#KT-20314 Fixed
2017-12-22 10:53:29 +01:00
Dmitry Jemerov
01ecc145ed Apply indent of continuation call start to its children
#KT-15099 Fixed
2017-12-22 10:53:23 +01:00
Dmitry Jemerov
e017ef71d7 Force no line break after dot in chained calls
#KT-20362 Fixed
2017-12-22 10:53:18 +01:00
Dmitry Jemerov
25a88ab707 Line breaks in objects and lambdas don't trigger call paren wrapping
#KT-19727 Fixed
2017-12-22 10:53:11 +01:00
Dmitry Jemerov
51e964d579 Option to apply normal indent to children of 'if' expressions 2017-12-22 10:53:02 +01:00
Dmitry Jemerov
8988675ad4 Refactoring: extract 'continuationIf' method 2017-12-22 10:52:56 +01:00
Dmitry Jemerov
c3a7044405 Don't wrap parentheses in long argument list containing only object 2017-12-22 10:52:50 +01:00
Dmitry Jemerov
aea040bafa KotlinFormattingModelBuilder: J2K 2017-12-22 10:52:45 +01:00
Dmitry Jemerov
cf457ae2e3 KotlinFormattingModelBuilder: rename to .kt 2017-12-22 10:52:40 +01:00
Toshiaki Kameyama
f28c7bc937 Inspection to highlight usages of Collections.sort() and replace them with .sort() method from Kotlin stdlib
#KT-11023 Fixed
2017-12-22 10:52:25 +01:00
Toshiaki Kameyama
1023228335 KT-21698 Create interface shouldn't suggest to declare it inside a class which implements it 2017-12-22 10:52:04 +01:00
Dmitry Jemerov
e06adf2559 Regenerate test 2017-12-22 10:51:42 +01:00
Dmitry Jemerov
7fc586d4a5 Don't apply highlighting to zero-length elements
#KT-19820 Fixed
2017-12-22 10:51:32 +01:00
Dmitry Jemerov
dd2e9a0bdd Fix highlighting of TODO calls in lambdas
#KT-19915 Fixed
2017-12-22 10:51:25 +01:00
Dmitry Jemerov
a2976598f9 Apply rainbow highlighting in anonymous initializers
#KT-18839 Fixed
2017-12-22 10:51:19 +01:00
Dmitry Jemerov
82d23b7ee5 Don't show type hints for destructuring declarations with explicit type
#KT-21833 Fixed
2017-12-22 10:51:12 +01:00
Dmitry Jemerov
3f50ae8d8d Put argument name hint before spread element
#KT-21645 Fixed
2017-12-22 10:51:07 +01:00
Dmitry Jemerov
e1b1869441 Don't show argument name hints for dynamic calls.
Mark function descriptors created for dynamic calls as having
synthesized parameter names.

 #KT-21275 Fixed
2017-12-22 10:51:02 +01:00
Dmitry Jemerov
c5cfd05083 Add mapOf() to default parameter name hints blacklist
#KT-18829 Fixed
2017-12-22 10:50:56 +01:00
Dmitry Jemerov
ae3b331bb7 Add single-arg 'assert' method to parameter name hints blacklist
#KT-17965 Fixed
2017-12-22 10:50:50 +01:00
Dmitry Jemerov
2d7f46ef34 Don't show type hint for local variable initialized with object
#KT-17964 Fixed
2017-12-22 10:50:44 +01:00
Dmitry Jemerov
0222539d23 Don't show parameter name hints when calling Java methods with unknown
parameter names

 #KT-17843 Fixed
2017-12-22 10:50:38 +01:00
Dmitry Jemerov
af5211fcf2 Enable "Configure Kotlin plugin updates" with no open project
#KT-20380 Fixed
2017-12-22 10:50:31 +01:00
Dmitry Jemerov
4051934cbe Fix name of inspection description file 2017-12-22 10:50:24 +01:00
kenji tomita
399166d92d Use BodyResolveMode.PARTIAL and ProblemHighlightType.GENERIC_ERROR_OR_WARNING 2017-12-22 10:50:13 +01:00
kenji tomita
176d6fedfa code style inspection: to -> Pair function used not in infix form 2017-12-22 10:50:07 +01:00
Toshiaki Kameyama
b4c3e98955 KT-21770 Pasting into an interpolated string shouldn't escape $ 2017-12-22 10:49:18 +01:00
Toshiaki Kameyama
68712713c4 KT-17928 Support code folding for primary constructors 2017-12-22 10:49:13 +01:00
Dmitry Jemerov
149a40ba46 Add 'reformat' flag to DeprecatedSymbolUsageFixBase 2017-12-22 10:49:02 +01:00
Dmitry Jemerov
4e0f73520a Disallow formatting in KotlinQuickFix.isAvailable() 2017-12-22 10:48:50 +01:00
Dmitry Jemerov
d65a2f36f2 Check that add() method is in fact MutableCollection.add()
#KT-18881 Fixed
2017-12-22 10:48:36 +01:00
Dmitry Jemerov
bd2e69ddeb Don't suggest mapTo() transformation over range literals
#KT-18816 Fixed
2017-12-22 10:48:27 +01:00
Dmitry Jemerov
982bc8efa3 Don't generate .forEach { return } when converting loop to call chain
#KT-17161 Fixed
2017-12-22 10:48:17 +01:00
Dmitry Jemerov
59d15e1b00 Fix incorrect replacement with 'any' instead of 'all'
#KT-17730 Fixed
2017-12-22 10:48:07 +01:00
Dmitry Jemerov
e115d3d622 Delete unused class 2017-12-22 10:47:59 +01:00
Dmitry Jemerov
53e924ef6e Update EAP channel names in plugin update check dialog 2017-12-22 10:47:47 +01:00
Nicolay Mitropolsky
ab2b0538ed LightClassUtil.extractPropertyAccessors refactoring to fix KotlinShortNamesCacheTest.testGetMethodsByNameWithCustomPropertyAccessors test
After light classes caching the test started to fail.
 Also refer Simon Ogorodnik.

(cherry picked from commit 657123f)
2017-12-22 12:20:25 +03:00
Nicolay Mitropolsky
4a7eeb9ecb LightClassEqualsTest fix by creating lightclasses with createNoCache
(cherry picked from commit bb4d6d1)
2017-12-22 12:20:25 +03:00
Nicolay Mitropolsky
ad83c4ae22 *kapt3-idea* added to test-dependencies in *uast-kotlin*
(cherry picked from commit 4c5cf0f)
2017-12-22 12:20:25 +03:00
Mikhael Bogdanov
07c5845c38 Generate annotations in proper order in DefaultImpls
(cherry picked from commit ea5505f)
2017-12-22 10:06:55 +01:00
Mikhael Bogdanov
84d641af4a Generate proper java parameter names for DefaultImpls
#KT-21919 Fixed

(cherry picked from commit c9d0ab3)
2017-12-22 10:06:49 +01:00
Ilya Gorbunov
6c7837a848 Use empty array instead of presized for Collection.toArray
#KT-21918

(cherry picked from commit 94a0e50)
2017-12-22 05:15:23 +03:00
Sergey Igushkin
391d08bc9c Improve kapt arguments & javac options usability with Kotlin DSL
Issue #KT-21596 Fixed

(cherry picked from commit 710c726)
2017-12-21 18:50:41 +03:00
Alexey Sedunov
030c1fb21d Change Signature: Fix overrider search for suspend functions
#KT-21288 Fixed

(cherry picked from commit 0ab924a)
2017-12-21 18:46:22 +03:00
Alexey Sedunov
04a934e453 Kotlin Facet: Do not auto-advance version in imported projects
#KT-21879 Fixed

(cherry picked from commit b5bd594)
2017-12-21 18:46:22 +03:00
Alexey Sedunov
7253090595 Misc: Fix NPE on external project import
(cherry picked from commit 8854036)
2017-12-21 18:46:21 +03:00
Kirill
d4c5b12c66 Support callable references in "implicit this" inspection
Second part of #KT-21510

(cherry picked from commit 7842fa4)
2017-12-21 17:32:32 +03:00
Kirill
252a754758 Support callable references in "explicit this" inspection
So #KT-21510 Fixed

(cherry picked from commit 74e5a94)
2017-12-21 17:31:36 +03:00
Mikhail Glukhikh
b7d7241630 Inline handler: fix reference detection for properties
(cherry picked from commit 4173960)
2017-12-21 17:29:05 +03:00
Mikhail Glukhikh
b7d45f7ac7 Extract common class from two KotlinInline<...>Dialogs #KT-17212 Fixed
(cherry picked from commit ce441e2)
2017-12-21 17:28:43 +03:00
Mikhail Glukhikh
959e8ea851 Fix "fake JVM field" inspection test XML
(cherry picked from commit 484bf01)
2017-12-21 17:28:32 +03:00
Mikhael Bogdanov
108e1c2d1c Don't delete nested default lambda classes during inline transformation
(cherry picked from commit 50608d0)
2017-12-21 13:15:08 +01:00
Mikhael Bogdanov
1a6fb37c45 Provide test source mapping data for separate and non-separate compilation
Compilation in same module or in separate ones

(cherry picked from commit b65dcf2)
2017-12-21 13:15:04 +01:00
Mikhael Bogdanov
8f9b839a5c Copy nested objects of default lambda during inline
(cherry picked from commit f4f7c83)
2017-12-21 13:15:02 +01:00
Mikhael Bogdanov
d88617cdac Properly process default lambda source mapping
#KT-21827 Fixed

(cherry picked from commit 3513f1a)
2017-12-21 13:14:58 +01:00
Vyacheslav Gerasimov
1710bfd11d Add previous release to changelog 2017-12-20 18:29:41 +03:00
Pavel V. Talanov
d778febc6c Minor, JvmAnalyzerFacade: drop logging
Prevent log spam
2017-12-20 17:33:36 +03:00
Pavel V. Talanov
f77f8e552f ScriptDefinitionsManager: ignore reloadDefinitionsBy calls
If definitions are not loaded yet
2017-12-19 17:28:01 +03:00
Pavel V. Talanov
8a639609bb scriptTemplatesFromCompilerSettings: fix ScriptDefinitionsManager access
#KT-21545 Fixed
2017-12-19 17:27:59 +03:00
Vyacheslav Gerasimov
bee01ffe6e Add changelog for 1.2.20 2017-12-19 16:06:02 +03:00
Mikhail Glukhikh
834433251c Unused symbol: revert entry point check optimization to fix regression
E.g. JUnit 3 tests was highlighted as unused after it

(cherry picked from commit 4bff0fb)
2017-12-19 16:01:53 +03:00
Nicolay Mitropolsky
eea2612ce0 Fix for "safe delete" after caching added to light elements
(cherry picked from commit 4a6cc39)
2017-12-19 13:35:28 +03:00
Ilya Chernikov
86a0356a75 Do not log daemon connection errors as exceptions - may reduce number of ...
redundant report if the problem is corrected on retry

(cherry picked from commit 260fe36)
2017-12-18 17:05:30 +01:00
Ilya Chernikov
8b4cf7f02b Make daemon session retrieval more robust to the daemon failures
(cherry picked from commit f83dc0a)
2017-12-18 16:51:56 +01:00
Ilya Chernikov
e91a31cab2 Treat "daemon is dying" state as a case for fallback compilation strategy in jps
(cherry picked from commit 1101bb7)
2017-12-18 16:51:47 +01:00
Ilya Chernikov
c539b3602a Retry socket connection on connection errors, number of retries and...
retry interval are configurable via the system props

(cherry picked from commit 6e34f57)
2017-12-18 16:51:38 +01:00
Ilya Chernikov
2fd094bb89 Ignore connection error on the (optional) daemon.clearJarCache call
May fix issues with NoSuchObjectException and UnmarshalException - the
stacktraces often point to this place

(cherry picked from commit 1cd14f0)
2017-12-18 16:51:29 +01:00
Mikhail Glukhikh
f350761b76 Fix corner cases (override/script/null/etc.) in "might be const"
Related to KT-20644

(cherry picked from commit 0d64ab4)
2017-12-18 18:25:09 +03:00
Ilya Gorbunov
8cb29c688c Do not leak primitiveness of an array wrapped with asList
A primitive array wrapped in a List with asList had incorrect implementation of toArray method:
while it declares that an object array is returned, it returned a primitive array.
Therefore the methods such as `Collection.toTypedArray()` and its dependents
`ArrayList(collection)`, `Collection + Iterable` might behave incorrectly
having relied on `toTypedArray` returned an object array.

#KT-21828 Fixed

(cherry picked from commit d8cd926)
2017-12-18 16:03:23 +03:00
Sergey Igushkin
76cc5556ab Optimize embeddable JARs
Exclude the compiler dummy JAR from the resulting shadow JAR

(cherry picked from commit c55f08a)
2017-12-18 15:59:52 +03:00
1160 changed files with 17742 additions and 10696 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -28,18 +28,20 @@ import java.io.File
/**
* Incremental cache common for JVM and JS
*/
abstract class IncrementalCacheCommon(workingDir: File) : BasicMapsOwner(workingDir) {
abstract class IncrementalCacheCommon<ClassName>(workingDir: File) : BasicMapsOwner(workingDir) {
companion object {
private val SUBTYPES = "subtypes"
private val SUPERTYPES = "supertypes"
private val CLASS_FQ_NAME_TO_SOURCE = "class-fq-name-to-source"
@JvmStatic protected val SOURCE_TO_CLASSES = "source-to-classes"
@JvmStatic protected val DIRTY_OUTPUT_CLASSES = "dirty-output-classes"
}
private val dependents = arrayListOf<IncrementalCacheCommon>()
fun addDependentCache(cache: IncrementalCacheCommon) {
private val dependents = arrayListOf<IncrementalCacheCommon<ClassName>>()
fun addDependentCache(cache: IncrementalCacheCommon<ClassName>) {
dependents.add(cache)
}
val thisWithDependentCaches: Iterable<IncrementalCacheCommon> by lazy {
val thisWithDependentCaches: Iterable<IncrementalCacheCommon<ClassName>> by lazy {
val result = arrayListOf(this)
result.addAll(dependents)
result
@@ -48,6 +50,8 @@ abstract class IncrementalCacheCommon(workingDir: File) : BasicMapsOwner(working
private val subtypesMap = registerMap(SubtypesMap(SUBTYPES.storageFile))
private val supertypesMap = registerMap(SupertypesMap(SUPERTYPES.storageFile))
protected val classFqNameToSourceMap = registerMap(ClassFqNameToSourceMap(CLASS_FQ_NAME_TO_SOURCE.storageFile))
internal abstract val sourceToClassesMap: AbstractSourceToOutputMap<ClassName>
internal abstract val dirtyOutputClassesMap: AbstractDirtyClassesMap<ClassName>
fun getSubtypesOf(className: FqName): Sequence<FqName> =
subtypesMap[className].asSequence()
@@ -55,7 +59,16 @@ abstract class IncrementalCacheCommon(workingDir: File) : BasicMapsOwner(working
fun getSourceFileIfClass(fqName: FqName): File? =
classFqNameToSourceMap[fqName]
abstract fun markDirty(removedAndCompiledSources: List<File>)
open fun markDirty(removedAndCompiledSources: List<File>) {
for (sourceFile in removedAndCompiledSources) {
val classes = sourceToClassesMap[sourceFile]
classes.forEach {
dirtyOutputClassesMap.markDirty(it)
}
sourceToClassesMap.clearOutputsForSource(sourceFile)
}
}
protected fun addToClassStorage(proto: ProtoBuf.Class, nameResolver: NameResolver, srcFile: File) {
val supertypes = proto.supertypes(TypeTable(proto.typeTable))
@@ -73,11 +86,19 @@ abstract class IncrementalCacheCommon(workingDir: File) : BasicMapsOwner(working
classFqNameToSourceMap[child] = srcFile
}
protected fun removeAllFromClassStorage(removedClasses: Collection<FqName>) {
abstract fun clearCacheForRemovedClasses(changesCollector: ChangesCollector)
protected fun removeAllFromClassStorage(removedClasses: Collection<FqName>, changesCollector: ChangesCollector) {
if (removedClasses.isEmpty()) return
val removedFqNames = removedClasses.toSet()
for (removedClass in removedFqNames) {
for (affectedClass in withSubtypes(removedClass, thisWithDependentCaches)) {
changesCollector.collectSignature(affectedClass, areSubclassesAffected = false)
}
}
for (cache in thisWithDependentCaches) {
val parentsFqNames = hashSetOf<FqName>()
val childrenFqNames = hashSetOf<FqName>()

View File

@@ -31,19 +31,20 @@ import java.io.DataInput
import java.io.DataOutput
import java.io.File
open class IncrementalJsCache(cachesDir: File) : IncrementalCacheCommon(cachesDir) {
open class IncrementalJsCache(cachesDir: File) : IncrementalCacheCommon<FqName>(cachesDir) {
companion object {
private val TRANSLATION_RESULT_MAP = "translation-result"
private val SOURCES_TO_CLASSES_FQNS = "sources-to-classes"
private val INLINE_FUNCTIONS = "inline-functions"
private val HEADER_FILE_NAME = "header.meta"
}
private val dirtySources = arrayListOf<File>()
override val sourceToClassesMap = registerMap(SourceToFqNameMap(SOURCE_TO_CLASSES.storageFile))
override val dirtyOutputClassesMap = registerMap(DirtyClassesFqNameMap(DIRTY_OUTPUT_CLASSES.storageFile))
private val translationResults = registerMap(TranslationResultMap(TRANSLATION_RESULT_MAP.storageFile))
private val sourcesToClasses = registerMap(SourceToClassesMap(SOURCES_TO_CLASSES_FQNS.storageFile))
private val inlineFunctions = registerMap(InlineFunctionsMap(INLINE_FUNCTIONS.storageFile))
private val dirtySources = hashSetOf<File>()
private val headerFile: File
get() = File(cachesDir, HEADER_FILE_NAME)
@@ -55,30 +56,23 @@ open class IncrementalJsCache(cachesDir: File) : IncrementalCacheCommon(cachesDi
}
override fun markDirty(removedAndCompiledSources: List<File>) {
super.markDirty(removedAndCompiledSources)
dirtySources.addAll(removedAndCompiledSources)
}
fun compareAndUpdate(incrementalResults: IncrementalResultsConsumerImpl, changesCollector: ChangesCollector) {
val translatedFiles = incrementalResults.packageParts
dirtySources.forEach {
if (it !in translatedFiles) {
translationResults.remove(it, changesCollector)
inlineFunctions.remove(it)
}
removeAllFromClassStorage(sourcesToClasses[it])
sourcesToClasses.clearOutputsForSource(it)
}
dirtySources.clear()
for ((srcFile, data) in translatedFiles) {
dirtySources.remove(srcFile)
val (binaryMetadata, binaryAst) = data
val oldProtoMap = translationResults[srcFile]?.metadata?.let { getProtoData(srcFile, it) } ?: emptyMap()
val newProtoMap = getProtoData(srcFile, binaryMetadata)
for (protoData in newProtoMap.values) {
for ((classId, protoData) in newProtoMap) {
registerOutputForFile(srcFile, classId.asSingleFqName())
if (protoData is ClassProtoData) {
addToClassStorage(protoData.proto, protoData.nameResolver, srcFile)
}
@@ -96,6 +90,21 @@ open class IncrementalJsCache(cachesDir: File) : IncrementalCacheCommon(cachesDi
}
}
private fun registerOutputForFile(srcFile: File, name: FqName) {
sourceToClassesMap.add(srcFile, name)
dirtyOutputClassesMap.notDirty(name)
}
override fun clearCacheForRemovedClasses(changesCollector: ChangesCollector) {
dirtySources.forEach {
translationResults.remove(it, changesCollector)
inlineFunctions.remove(it)
}
removeAllFromClassStorage(dirtyOutputClassesMap.getDirtyOutputClasses(), changesCollector)
dirtySources.clear()
dirtyOutputClassesMap.clean()
}
fun nonDirtyPackageParts(): Map<File, TranslationResultValue> =
hashMapOf<File, TranslationResultValue>().apply {
for (path in translationResults.keys()) {
@@ -107,25 +116,6 @@ open class IncrementalJsCache(cachesDir: File) : IncrementalCacheCommon(cachesDi
}
}
private class SourceToClassesMap(storageFile: File) : BasicStringMap<Collection<String>>(storageFile, PathStringDescriptor, StringCollectionExternalizer) {
fun clearOutputsForSource(sourceFile: File) {
remove(sourceFile.canonicalPath)
}
fun add(sourceFile: File, className: FqName) {
storage.append(sourceFile.canonicalPath, className.asString())
}
operator fun get(sourceFile: File): Collection<FqName> =
storage[sourceFile.canonicalPath].orEmpty().map { FqName(it) }
override fun dumpValue(value: Collection<String>) = value.dumpCollection()
private fun remove(path: String) {
storage.remove(path)
}
}
private object TranslationResultValueExternalizer : DataExternalizer<TranslationResultValue> {
override fun save(output: DataOutput, value: TranslationResultValue) {
output.writeInt(value.metadata.size)

View File

@@ -44,15 +44,13 @@ val KOTLIN_CACHE_DIRECTORY_NAME = "kotlin"
open class IncrementalJvmCache(
private val targetDataRoot: File,
targetOutputDir: File?
) : IncrementalCacheCommon(File(targetDataRoot, KOTLIN_CACHE_DIRECTORY_NAME)), IncrementalCache {
) : IncrementalCacheCommon<JvmClassName>(File(targetDataRoot, KOTLIN_CACHE_DIRECTORY_NAME)), IncrementalCache {
companion object {
private val PROTO_MAP = "proto"
private val CONSTANTS_MAP = "constants"
private val PACKAGE_PARTS = "package-parts"
private val MULTIFILE_CLASS_FACADES = "multifile-class-facades"
private val MULTIFILE_CLASS_PARTS = "multifile-class-parts"
private val SOURCE_TO_CLASSES = "source-to-classes"
private val DIRTY_OUTPUT_CLASSES = "dirty-output-classes"
private val INLINE_FUNCTIONS = "inline-functions"
private val INTERNAL_NAME_TO_SOURCE = "internal-name-to-source"
private val JAVA_SOURCES_PROTO_MAP = "java-sources-proto-map"
@@ -60,13 +58,14 @@ open class IncrementalJvmCache(
private val MODULE_MAPPING_FILE_NAME = "." + ModuleMapping.MAPPING_FILE_EXT
}
override val sourceToClassesMap = registerMap(SourceToJvmNameMap(SOURCE_TO_CLASSES.storageFile))
override val dirtyOutputClassesMap = registerMap(DirtyClassesJvmNameMap(DIRTY_OUTPUT_CLASSES.storageFile))
private val protoMap = registerMap(ProtoMap(PROTO_MAP.storageFile))
private val constantsMap = registerMap(ConstantsMap(CONSTANTS_MAP.storageFile))
private val packagePartMap = registerMap(PackagePartMap(PACKAGE_PARTS.storageFile))
private val multifileFacadeToParts = registerMap(MultifileClassFacadeMap(MULTIFILE_CLASS_FACADES.storageFile))
private val partToMultifileFacade = registerMap(MultifileClassPartMap(MULTIFILE_CLASS_PARTS.storageFile))
private val sourceToClassesMap = registerMap(SourceToClassesMap(SOURCE_TO_CLASSES.storageFile))
private val dirtyOutputClassesMap = registerMap(DirtyOutputClassesMap(DIRTY_OUTPUT_CLASSES.storageFile))
private val inlineFunctionsMap = registerMap(InlineFunctionsMap(INLINE_FUNCTIONS.storageFile))
// todo: try to use internal names only?
private val internalNameToSource = registerMap(InternalNameToSourcesMap(INTERNAL_NAME_TO_SOURCE.storageFile))
@@ -76,17 +75,6 @@ open class IncrementalJvmCache(
protected open fun debugLog(message: String) {}
override fun markDirty(removedAndCompiledSources: List<File>) {
for (sourceFile in removedAndCompiledSources) {
val classes = sourceToClassesMap[sourceFile]
classes.forEach {
dirtyOutputClassesMap.markDirty(it.internalName)
}
sourceToClassesMap.clearOutputsForSource(sourceFile)
}
}
fun isTrackedFile(file: File) = sourceToClassesMap.contains(file)
// used in gradle
@@ -98,7 +86,7 @@ open class IncrementalJvmCache(
internalNameToSource[internalName]
fun isMultifileFacade(className: JvmClassName): Boolean =
className.internalName in multifileFacadeToParts
className in multifileFacadeToParts
override fun getClassFilePath(internalClassName: String): String {
return toSystemIndependentName(File(outputDir, "$internalClassName.class").canonicalPath)
@@ -107,7 +95,7 @@ open class IncrementalJvmCache(
fun saveModuleMappingToCache(sourceFiles: Collection<File>, file: File) {
val jvmClassName = JvmClassName.byInternalName(MODULE_MAPPING_FILE_NAME)
protoMap.storeModuleMapping(jvmClassName, file.readBytes())
dirtyOutputClassesMap.notDirty(MODULE_MAPPING_FILE_NAME)
dirtyOutputClassesMap.notDirty(jvmClassName)
sourceFiles.forEach { sourceToClassesMap.add(it, jvmClassName) }
}
@@ -116,7 +104,7 @@ open class IncrementalJvmCache(
val kotlinClass: LocalFileKotlinClass = generatedClass.outputClass
val className = kotlinClass.className
dirtyOutputClassesMap.notDirty(className.internalName)
dirtyOutputClassesMap.notDirty(className)
sourceFiles.forEach {
sourceToClassesMap.add(it, className)
}
@@ -181,7 +169,7 @@ open class IncrementalJvmCache(
val (proto, nameResolver) = serializedJavaClass.toProtoData()
addToClassStorage(proto, nameResolver, source)
dirtyOutputClassesMap.notDirty(jvmClassName.internalName)
dirtyOutputClassesMap.notDirty(jvmClassName)
}
fun getObsoleteJavaClasses(): Collection<ClassId> =
@@ -192,31 +180,28 @@ open class IncrementalJvmCache(
fun isJavaClassToTrack(classId: ClassId): Boolean {
val jvmClassName = JvmClassName.byClassId(classId)
return dirtyOutputClassesMap.isDirty(jvmClassName.internalName) ||
javaSourcesProtoMap[jvmClassName.internalName] == null
return dirtyOutputClassesMap.isDirty(jvmClassName) ||
jvmClassName !in javaSourcesProtoMap
}
fun isJavaClassAlreadyInCache(classId: ClassId): Boolean {
val jvmClassName = JvmClassName.byClassId(classId)
return javaSourcesProtoMap[jvmClassName.internalName] != null
return jvmClassName in javaSourcesProtoMap
}
fun clearCacheForRemovedClasses(changesCollector: ChangesCollector) {
val dirtyClasses = dirtyOutputClassesMap
.getDirtyOutputClasses()
.map(JvmClassName::byInternalName)
.toList()
override fun clearCacheForRemovedClasses(changesCollector: ChangesCollector) {
val dirtyClasses = dirtyOutputClassesMap.getDirtyOutputClasses()
val facadesWithRemovedParts = hashMapOf<JvmClassName, MutableSet<String>>()
for (dirtyClass in dirtyClasses) {
val facade = partToMultifileFacade.get(dirtyClass.internalName) ?: continue
val facade = partToMultifileFacade.get(dirtyClass) ?: continue
val facadeClassName = JvmClassName.byInternalName(facade)
val removedParts = facadesWithRemovedParts.getOrPut(facadeClassName) { hashSetOf() }
removedParts.add(dirtyClass.internalName)
}
for ((facade, removedParts) in facadesWithRemovedParts.entries) {
val allParts = multifileFacadeToParts[facade.internalName] ?: continue
val allParts = multifileFacadeToParts[facade] ?: continue
val notRemovedParts = allParts.filter { it !in removedParts }
if (notRemovedParts.isEmpty()) {
@@ -238,16 +223,14 @@ open class IncrementalJvmCache(
javaSourcesProtoMap.remove(it, changesCollector)
}
removeAllFromClassStorage(dirtyClasses.map { it.fqNameForClassNameWithoutDollars })
removeAllFromClassStorage(dirtyClasses.map { it.fqNameForClassNameWithoutDollars }, changesCollector)
dirtyOutputClassesMap.clean()
}
override fun getObsoletePackageParts(): Collection<String> {
val obsoletePackageParts =
dirtyOutputClassesMap.getDirtyOutputClasses().filter { packagePartMap.isPackagePart(JvmClassName.byInternalName(it)) }
val obsoletePackageParts = dirtyOutputClassesMap.getDirtyOutputClasses().filter(packagePartMap::isPackagePart)
debugLog("Obsolete package parts: $obsoletePackageParts")
return obsoletePackageParts
return obsoletePackageParts.map { it.internalName }
}
override fun getPackagePartData(partInternalName: String): JvmPackagePartProto? {
@@ -267,8 +250,9 @@ open class IncrementalJvmCache(
}
override fun getStableMultifileFacadeParts(facadeInternalName: String): Collection<String>? {
val partNames = multifileFacadeToParts.get(facadeInternalName) ?: return null
return partNames.filter { !dirtyOutputClassesMap.isDirty(it) }
val jvmClassName = JvmClassName.byInternalName(facadeInternalName)
val partNames = multifileFacadeToParts[jvmClassName] ?: return null
return partNames.filter { !dirtyOutputClassesMap.isDirty(JvmClassName.byInternalName(it)) }
}
override fun getModuleMappingData(): ByteArray? {
@@ -351,7 +335,11 @@ open class IncrementalJvmCache(
changesCollector.collectProtoChanges(oldValue.toProtoData(), newData = null)
}
operator fun get(internalName: String) = storage[internalName]
operator fun get(className: JvmClassName): SerializedJavaClass? =
storage[className.internalName]
operator fun contains(className: JvmClassName): Boolean =
className.internalName in storage
override fun dumpValue(value: SerializedJavaClass): String =
java.lang.Long.toHexString(value.proto.toByteArray().md5())
@@ -419,13 +407,15 @@ open class IncrementalJvmCache(
}
private inner class MultifileClassFacadeMap(storageFile: File) : BasicStringMap<Collection<String>>(storageFile, StringCollectionExternalizer) {
operator fun set(facadeName: JvmClassName, partNames: Collection<String>) {
storage[facadeName.internalName] = partNames
operator fun set(className: JvmClassName, partNames: Collection<String>) {
storage[className.internalName] = partNames
}
operator fun get(internalName: String): Collection<String>? = storage[internalName]
operator fun get(className: JvmClassName): Collection<String>? =
storage[className.internalName]
operator fun contains(internalName: String): Boolean = internalName in storage
operator fun contains(className: JvmClassName): Boolean =
className.internalName in storage
fun remove(className: JvmClassName) {
storage.remove(className.internalName)
@@ -439,9 +429,8 @@ open class IncrementalJvmCache(
storage[partName] = facadeName
}
fun get(partName: String): String? {
return storage.get(partName)
}
fun get(partName: JvmClassName): String? =
storage[partName.internalName]
fun remove(className: JvmClassName) {
storage.remove(className.internalName)
@@ -450,27 +439,6 @@ open class IncrementalJvmCache(
override fun dumpValue(value: String): String = value
}
inner class SourceToClassesMap(storageFile: File) : BasicStringMap<Collection<String>>(storageFile, PathStringDescriptor, StringCollectionExternalizer) {
fun clearOutputsForSource(sourceFile: File) {
remove(sourceFile.absolutePath)
}
fun add(sourceFile: File, className: JvmClassName) {
storage.append(sourceFile.absolutePath, className.internalName)
}
fun contains(sourceFile: File) = sourceFile.absolutePath in storage
operator fun get(sourceFile: File): Collection<JvmClassName> =
storage[sourceFile.absolutePath].orEmpty().map { JvmClassName.byInternalName(it) }
override fun dumpValue(value: Collection<String>) = value.dumpCollection()
private fun remove(path: String) {
storage.remove(path)
}
}
inner class InternalNameToSourcesMap(storageFile: File) : BasicStringMap<Collection<String>>(storageFile, EnumeratorStringDescriptor(), PathCollectionExternalizer) {
operator fun set(internalName: String, sourceFiles: Iterable<File>) {
storage[internalName] = sourceFiles.map { it.canonicalPath }
@@ -492,24 +460,6 @@ open class IncrementalJvmCache(
addToClassStorage(proto, nameResolver, srcFile)
}
private inner class DirtyOutputClassesMap(storageFile: File) : BasicStringMap<Boolean>(storageFile, BooleanDataDescriptor.INSTANCE) {
fun markDirty(className: String) {
storage[className] = true
}
fun notDirty(className: String) {
storage.remove(className)
}
fun getDirtyOutputClasses(): Collection<String> =
storage.keys
fun isDirty(className: String): Boolean =
storage.contains(className)
override fun dumpValue(value: Boolean) = ""
}
private inner class InlineFunctionsMap(storageFile: File) : BasicStringMap<Map<String, Long>>(storageFile, StringToLongMapExternalizer) {
private fun getInlineFunctionsMap(header: KotlinClassHeader, bytes: ByteArray): Map<String, Long> {
val inlineFunctions = inlineFunctionsJvmNames(header)

View File

@@ -116,7 +116,7 @@ data class DirtyData(
)
fun ChangesCollector.getDirtyData(
caches: Iterable<IncrementalCacheCommon>,
caches: Iterable<IncrementalCacheCommon<*>>,
reporter: ICReporter
): DirtyData {
val dirtyLookupSymbols = HashSet<LookupSymbol>()
@@ -170,7 +170,7 @@ fun mapLookupSymbolsToFiles(
}
fun mapClassesFqNamesToFiles(
caches: Iterable<IncrementalCacheCommon>,
caches: Iterable<IncrementalCacheCommon<*>>,
classesFqNames: Iterable<FqName>,
reporter: ICReporter,
excludes: Set<File> = emptySet()
@@ -192,7 +192,7 @@ fun mapClassesFqNamesToFiles(
fun withSubtypes(
typeFqName: FqName,
caches: Iterable<IncrementalCacheCommon>
caches: Iterable<IncrementalCacheCommon<*>>
): Set<FqName> {
val types = LinkedList(listOf(typeFqName))
val subtypes = hashSetOf<FqName>()

View File

@@ -0,0 +1,46 @@
/*
* 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.incremental.storage
import com.intellij.util.io.BooleanDataDescriptor
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import java.io.File
internal class DirtyClassesJvmNameMap(storageFile: File) : AbstractDirtyClassesMap<JvmClassName>(JvmClassNameTransformer, storageFile)
internal class DirtyClassesFqNameMap(storageFile: File) : AbstractDirtyClassesMap<FqName>(FqNameTransformer, storageFile)
internal abstract class AbstractDirtyClassesMap<Name>(
private val nameTransformer: NameTransformer<Name>,
storageFile: File
) : BasicStringMap<Boolean>(storageFile, BooleanDataDescriptor.INSTANCE) {
fun markDirty(className: Name) {
storage[nameTransformer.asString(className)] = true
}
fun notDirty(className: Name) {
storage.remove(nameTransformer.asString(className))
}
fun getDirtyOutputClasses(): Collection<Name> =
storage.keys.map { nameTransformer.asName(it) }
fun isDirty(className: Name): Boolean =
storage.contains(nameTransformer.asString(className))
override fun dumpValue(value: Boolean) = ""
}

View File

@@ -0,0 +1,41 @@
/*
* 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.incremental.storage
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
internal interface NameTransformer<Name> {
fun asString(name: Name): String
fun asName(string: String): Name
}
internal object FqNameTransformer : NameTransformer<FqName> {
override fun asString(name: FqName): String =
name.asString()
override fun asName(string: String): FqName =
FqName(string)
}
internal object JvmClassNameTransformer : NameTransformer<JvmClassName> {
override fun asString(name: JvmClassName): String =
name.internalName
override fun asName(string: String): JvmClassName =
JvmClassName.byInternalName(string)
}

View File

@@ -0,0 +1,51 @@
/*
* 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.incremental.storage
import org.jetbrains.kotlin.incremental.dumpCollection
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import java.io.File
internal class SourceToJvmNameMap(storageFile: File) : AbstractSourceToOutputMap<JvmClassName>(JvmClassNameTransformer, storageFile)
internal class SourceToFqNameMap(storageFile: File) : AbstractSourceToOutputMap<FqName>(FqNameTransformer, storageFile)
internal abstract class AbstractSourceToOutputMap<Name>(
private val nameTransformer: NameTransformer<Name>,
storageFile: File
) : BasicStringMap<Collection<String>>(storageFile, PathStringDescriptor, StringCollectionExternalizer) {
fun clearOutputsForSource(sourceFile: File) {
remove(sourceFile.absolutePath)
}
fun add(sourceFile: File, className: Name) {
storage.append(sourceFile.absolutePath, nameTransformer.asString(className))
}
fun contains(sourceFile: File): Boolean =
sourceFile.absolutePath in storage
operator fun get(sourceFile: File): Collection<Name> =
storage[sourceFile.absolutePath].orEmpty().map(nameTransformer::asName)
override fun dumpValue(value: Collection<String>) =
value.dumpCollection()
private fun remove(path: String) {
storage.remove(path)
}
}

View File

@@ -28,6 +28,9 @@ data class BuildLogFinder(
private const val GRADLE_LOG = "gradle-build.log"
private const val DATA_CONTAINER_LOG = "data-container-version-build.log"
private const val SIMPLE_LOG = "build.log"
fun isJpsLogFile(file: File): Boolean =
file.name.let { it == SIMPLE_LOG || it == DATA_CONTAINER_LOG }
}
fun findBuildLog(dir: File): File? {

View File

@@ -357,6 +357,7 @@ tasks {
dependsOn("scriptingTest")
dependsOn(":kotlin-build-common:test")
dependsOn(":compiler:incremental-compilation-impl:test")
}
"examplesTest" {

View File

@@ -1,10 +1,8 @@
@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.*
@@ -104,23 +102,22 @@ fun Project.embeddableCompilerDummyForDependenciesRewriting(taskName: String = "
}
}
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()
fun Project.rewriteDepsToShadedJar(originalJarTask: Jar, shadowJarTask: Jar, body: Jar.() -> Unit = {}): Jar {
originalJarTask.apply {
classifier = "original"
}
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) } } }
val compilerDummyJarFile by lazy { configurations.getAt("compilerDummyJar").singleFile }
return shadowJarTask.apply {
dependsOn(originalJarTask)
from(originalJarTask)// { include("**") }
// When Gradle traverses the inputs, reject the shaded compiler JAR,
// which leads to the content of that JAR being excluded as well:
exclude { it.file == compilerDummyJarFile }
classifier = null
body()
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
* 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.
@@ -19,14 +19,22 @@ package org.jetbrains.kotlin.codegen;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.diagnostics.DiagnosticUtils;
import org.jetbrains.kotlin.util.ExceptionUtilKt;
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments;
public class CompilationException extends RuntimeException {
public class CompilationException extends KotlinExceptionWithAttachments {
private final PsiElement element;
public CompilationException(@NotNull String message, @Nullable Throwable cause, @Nullable PsiElement element) {
super(ExceptionUtilKt.getExceptionMessage("Back-end (JVM)", message, cause, element), cause);
super(ExceptionUtilKt.getExceptionMessage("Back-end (JVM)", message, cause,
element == null ? null : DiagnosticUtils.atLocation(element)),
cause);
this.element = element;
if (element != null) {
withAttachment("element.kt", element.getText());
}
}
@Nullable

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
* 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.
@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.codegen
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.diagnostic.Logger
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
@@ -23,7 +24,7 @@ import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
object ExceptionLogger {
@JvmStatic
fun logDescriptorNotFound(problemDescription: String, psi: PsiElement): AssertionError {
LOG.error(problemDescription, psi.getElementTextWithContext())
LOG.error(problemDescription, Attachment("psi.kt", psi.getElementTextWithContext()))
throw AssertionError(problemDescription)
}

View File

@@ -223,9 +223,8 @@ public class FunctionCodegen {
generateMethodAnnotations(functionDescriptor, asmMethod, mv);
JvmMethodSignature signature = typeMapper.mapSignatureSkipGeneric(functionDescriptor);
generateParameterAnnotations(functionDescriptor, mv, signature);
GenerateJava8ParameterNamesKt.generateParameterNames(functionDescriptor, mv, signature, state, (flags & ACC_SYNTHETIC) != 0);
generateParameterAnnotations(functionDescriptor, mv, jvmSignature);
GenerateJava8ParameterNamesKt.generateParameterNames(functionDescriptor, mv, jvmSignature, state, (flags & ACC_SYNTHETIC) != 0);
generateBridges(functionDescriptor);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
* 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.
@@ -33,6 +33,7 @@ import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils;
import org.jetbrains.kotlin.util.slicedMap.BasicWritableSlice;
import org.jetbrains.kotlin.util.slicedMap.Slices;
import org.jetbrains.kotlin.util.slicedMap.WritableSlice;
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments;
import org.jetbrains.org.objectweb.asm.Type;
import java.util.*;
@@ -124,7 +125,8 @@ public class CodegenBinding {
return asmTypeForAnonymousClass(bindingContext, variableDescriptor);
}
throw new IllegalStateException("Couldn't compute ASM type for " + PsiUtilsKt.getElementTextWithContext(expression));
throw new KotlinExceptionWithAttachments("Couldn't compute ASM type for expression")
.withAttachment("expression.kt", PsiUtilsKt.getElementTextWithContext(expression));
}
@NotNull

View File

@@ -164,7 +164,7 @@ class DefaultLambda(
classReader.b,
invokeMethod.name,
invokeMethod.descriptor,
lambdaClassType)!!
lambdaClassType) ?: error("Can't find method '${invokeMethod.name}${invokeMethod.descriptor}' in '${classReader.className}'")
if (needReification) {
//nested classes could also require reification

View File

@@ -164,7 +164,9 @@ class MethodInliner(
result.merge(transformResult)
result.addChangedType(oldClassName, newClassName)
if (inliningContext.isInliningLambda && transformationInfo!!.canRemoveAfterTransformation()) {
if (inliningContext.isInliningLambda &&
inliningContext.lambdaInfo !is DefaultLambda && //never delete default lambda classes
transformationInfo!!.canRemoveAfterTransformation()) {
// this class is transformed and original not used so we should remove original one after inlining
result.addClassToRemove(oldClassName)
}
@@ -220,15 +222,20 @@ class MethodInliner(
setLambdaInlining(true)
val lambdaSMAP = info.node.classSMAP
val sourceMapper = if (inliningContext.classRegeneration && !inliningContext.isInliningLambda)
NestedSourceMapper(sourceMapper, lambdaSMAP.intervals, lambdaSMAP.sourceInfo)
else
InlineLambdaSourceMapper(sourceMapper.parent!!, info.node)
val childSourceMapper =
if (inliningContext.classRegeneration && !inliningContext.isInliningLambda)
NestedSourceMapper(sourceMapper, lambdaSMAP.intervals, lambdaSMAP.sourceInfo)
else if (info is DefaultLambda) {
NestedSourceMapper(sourceMapper.parent!!, lambdaSMAP.intervals, lambdaSMAP.sourceInfo)
}
else InlineLambdaSourceMapper(sourceMapper.parent!!, info.node)
val inliner = MethodInliner(
info.node.node, lambdaParameters, inliningContext.subInlineLambda(info),
newCapturedRemapper, true /*cause all calls in same module as lambda*/,
newCapturedRemapper,
if (info is DefaultLambda) isSameModule else true /*cause all nested objects in same module as lambda*/,
"Lambda inlining " + info.lambdaClassType.internalName,
sourceMapper, inlineCallSiteInfo, null
childSourceMapper, inlineCallSiteInfo, null
)
val varRemapper = LocalVarRemapper(lambdaParameters, valueParamShift)
@@ -242,7 +249,7 @@ class MethodInliner(
StackValue.onStack(info.invokeMethod.returnType).put(bridge.returnType, this)
setLambdaInlining(false)
addInlineMarker(this, false)
sourceMapper.endMapping()
childSourceMapper.endMapping()
inlineOnlySmapSkipper?.markCallSiteLineNumber(remappingMethodAdapter)
}
else if (isAnonymousConstructorCall(owner, name)) { //TODO add method

View File

@@ -51,7 +51,7 @@ open class DefaultValues(val defaultValue: String, val possibleValues: List<Stri
)
object JsSourceMapContentModes : DefaultValues(
"\"${K2JsArgumentConstants.SOURCE_MAP_SOURCE_CONTENT_INLINING}\"",
"null",
listOf(
K2JsArgumentConstants.SOURCE_MAP_SOURCE_CONTENT_NEVER,
K2JsArgumentConstants.SOURCE_MAP_SOURCE_CONTENT_ALWAYS,

View File

@@ -22,7 +22,7 @@ import org.jetbrains.kotlin.utils.Jsr305State
import org.jetbrains.kotlin.utils.ReportLevel
class Jsr305Parser(private val collector: MessageCollector) {
fun parse(value: Array<String>?): Jsr305State {
fun parse(value: Array<String>?, supportCompatqualCheckerFrameworkAnnotations: String?): Jsr305State {
var global: ReportLevel? = null
var migration: ReportLevel? = null
val userDefined = mutableMapOf<String, ReportLevel>()
@@ -70,7 +70,25 @@ class Jsr305Parser(private val collector: MessageCollector) {
}
}
val state = Jsr305State(global ?: ReportLevel.WARN, migration, userDefined)
val enableCompatqualCheckerFrameworkAnnotations = when (supportCompatqualCheckerFrameworkAnnotations) {
"enable" -> true
"disable" -> false
null -> null
else -> {
collector.report(
CompilerMessageSeverity.ERROR,
"Unrecognized -Xsupport-compatqual-checker-framework-annotations option: $supportCompatqualCheckerFrameworkAnnotations. Possible values are 'enable'/'disable'"
)
null
}
}
val state = Jsr305State(
global ?: ReportLevel.WARN, migration, userDefined,
enableCompatqualCheckerFrameworkAnnotations =
enableCompatqualCheckerFrameworkAnnotations
?: Jsr305State.COMPATQUAL_CHECKER_FRAMEWORK_ANNOTATIONS_SUPPORT_DEFAULT_VALUE
)
return if (state == Jsr305State.DISABLED) Jsr305State.DISABLED else state
}

View File

@@ -16,13 +16,10 @@
package org.jetbrains.kotlin.cli.common.arguments
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.config.AnalysisFlag
import org.jetbrains.kotlin.config.JVMConstructorCallNormalizationMode
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.utils.Jsr305State
import org.jetbrains.kotlin.utils.ReportLevel
class K2JVMCompilerArguments : CommonCompilerArguments() {
companion object {
@@ -191,6 +188,17 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
)
var jsr305: Array<String>? by FreezableVar(null)
@Argument(
value = "-Xsupport-compatqual-checker-framework-annotations",
valueDescription = "enable|disable",
description =
"""
Specify behavior for Checker Framework compatqual annotations (NullableDecl/NonNullDecl).
Default value is 'enable'
"""
)
var supportCompatqualCheckerFrameworkAnnotations: String? by FreezableVar(null)
@Argument(
value = "-Xno-exception-on-explicit-equals-for-boxed-null",
description = "Do not throw NPE on explicit 'equals' call for null receiver of platform boxed primitive type"
@@ -202,7 +210,10 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
override fun configureAnalysisFlags(collector: MessageCollector): MutableMap<AnalysisFlag<*>, Any> {
val result = super.configureAnalysisFlags(collector)
result[AnalysisFlag.jsr305] = Jsr305Parser(collector).parse(jsr305)
result[AnalysisFlag.jsr305] = Jsr305Parser(collector).parse(
jsr305,
supportCompatqualCheckerFrameworkAnnotations
)
return result
}
}

View File

@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.cli.common.arguments
import com.intellij.util.text.VersionComparatorUtil
import java.util.*
import kotlin.reflect.KClass
import kotlin.reflect.KMutableProperty1
@@ -98,4 +99,10 @@ fun <T : Any> collectProperties(kClass: KClass<T>, inheritedOnly: Boolean): List
return properties.filter {
it.visibility == KVisibility.PUBLIC && it.findAnnotation<Transient>() == null
}
}
fun CommonCompilerArguments.setApiVersionToLanguageVersionIfNeeded() {
if (languageVersion != null && VersionComparatorUtil.compare(languageVersion, apiVersion) < 0) {
apiVersion = languageVersion
}
}

View File

@@ -53,6 +53,7 @@ open class BasicReplStageHistory<T>(override val lock: ReentrantReadWriteLock =
lock.write {
val removed = map { it.id }
clear()
currentGeneration.incrementAndGet()
return removed
}
}
@@ -67,7 +68,10 @@ open class BasicReplStageHistory<T>(override val lock: ReentrantReadWriteLock =
currentGeneration.incrementAndGet()
removed
}
else emptyList()
else {
currentGeneration.incrementAndGet()
emptyList()
}
}
}
}

View File

@@ -35,7 +35,15 @@ class GenericReplCompilingEvaluator(val compiler: ReplCompiler,
val aggregatedState = state.asState(AggregatedReplStageState::class.java)
val compiled = compiler.compile(state, codeLine)
when (compiled) {
is ReplCompileResult.Error -> ReplEvalResult.Error.CompileTime(compiled.message, compiled.location)
is ReplCompileResult.Error -> {
aggregatedState.apply {
lock.write {
assert(state1.history.size == state2.history.size)
adjustHistories() // needed due to statefulness of AnalyzerEngine - in case of compilation errors the line name reuse leads to #KT-17921
}
}
ReplEvalResult.Error.CompileTime(compiled.message, compiled.location)
}
is ReplCompileResult.Incomplete -> ReplEvalResult.Incomplete()
is ReplCompileResult.CompiledClasses -> {
val result = eval(state, compiled, scriptArgs, invokeWrapper)
@@ -46,14 +54,7 @@ class GenericReplCompilingEvaluator(val compiler: ReplCompiler,
aggregatedState.apply {
lock.write {
if (state1.history.size > state2.history.size) {
if (state2.history.size == 0) {
state1.history.reset()
}
else {
state2.history.peek()?.let {
state1.history.resetTo(it.id)
}
}
adjustHistories()
assert(state1.history.size == state2.history.size)
}
}
@@ -91,3 +92,9 @@ class GenericReplCompilingEvaluator(val compiler: ReplCompiler,
evaluator.eval(state, compiledCode, scriptArgs ?: defaultScriptArgs, invokeWrapper)
}
}
private fun AggregatedReplStageState<*, *>.adjustHistories(): Iterable<ILineId>? =
state2.history.peek()?.let {
state1.history.resetTo(it.id)
}
?: state1.history.reset()

View File

@@ -44,6 +44,7 @@ import java.io.PrintStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.jetbrains.kotlin.cli.common.ExitCode.*;
import static org.jetbrains.kotlin.cli.common.environment.UtilKt.setIdeaIoUseFallback;
@@ -239,11 +240,12 @@ public abstract class CLICompiler<A extends CommonCompilerArguments> extends CLI
// do nothing
}
private static final String kotlinHomeEnvVar = System.getenv(KOTLIN_HOME_ENV_VAR);
@Nullable
private static KotlinPaths computeKotlinPaths(@NotNull MessageCollector messageCollector, @NotNull CommonCompilerArguments arguments) {
KotlinPaths paths;
String kotlinHomeProperty = System.getProperty(KOTLIN_HOME_PROPERTY);
String kotlinHomeEnvVar = System.getenv(KOTLIN_HOME_ENV_VAR);
File kotlinHome =
arguments.getKotlinHome() != null ? new File(arguments.getKotlinHome()) :
kotlinHomeProperty != null ? new File(kotlinHomeProperty) :

View File

@@ -45,6 +45,7 @@ import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles;
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment;
import org.jetbrains.kotlin.cli.jvm.plugins.PluginCliParser;
import org.jetbrains.kotlin.config.*;
import org.jetbrains.kotlin.incremental.components.ExpectActualTracker;
import org.jetbrains.kotlin.incremental.components.LookupTracker;
import org.jetbrains.kotlin.incremental.js.IncrementalDataProvider;
import org.jetbrains.kotlin.incremental.js.IncrementalResultsConsumer;
@@ -418,6 +419,11 @@ public class K2JSCompiler extends CLICompiler<K2JSCompilerArguments> {
configuration.put(CommonConfigurationKeys.LOOKUP_TRACKER, lookupTracker);
}
ExpectActualTracker expectActualTracker = services.get(ExpectActualTracker.class);
if (expectActualTracker != null) {
configuration.put(CommonConfigurationKeys.EXPECT_ACTUAL_TRACKER, expectActualTracker);
}
String sourceMapEmbedContentString = arguments.getSourceMapEmbedSources();
SourceMapSourceEmbedding sourceMapContentEmbedding = sourceMapEmbedContentString != null ?
sourceMapContentEmbeddingMap.get(sourceMapEmbedContentString) :

View File

@@ -33,19 +33,11 @@ class K2JSDce : CLITool<K2JSDceArguments>() {
override fun execImpl(messageCollector: MessageCollector, services: Services, arguments: K2JSDceArguments): ExitCode {
val baseDir = File(arguments.outputDirectory ?: "min")
var hasErrors = false
val files = arguments.freeArgs.flatMap { arg ->
val files = collectInputFiles(baseDir, arg, messageCollector)
if (files != null) {
files
}
else {
hasErrors = true
emptyList()
}
collectInputFiles(baseDir, arg, messageCollector)
}
if (hasErrors) return ExitCode.COMPILATION_ERROR
if (messageCollector.hasErrors()) return ExitCode.COMPILATION_ERROR
if (files.isEmpty() && !arguments.version) {
messageCollector.report(CompilerMessageSeverity.ERROR, "no source files")
@@ -56,8 +48,9 @@ class K2JSDce : CLITool<K2JSDceArguments>() {
for (file in files) {
existingFiles[file.outputPath]?.let {
messageCollector.report(
CompilerMessageSeverity.ERROR,
"duplicate target file will be created for '${file.resource.name}' and '${it.resource.name}'")
CompilerMessageSeverity.ERROR,
"duplicate target file will be created for '${file.resource.name}' and '${it.resource.name}'"
)
return ExitCode.COMPILATION_ERROR
}
existingFiles[file.outputPath] = file
@@ -69,8 +62,7 @@ class K2JSDce : CLITool<K2JSDceArguments>() {
return if (!arguments.devMode) {
performDce(files, arguments, messageCollector)
}
else {
} else {
copyFiles(files)
ExitCode.OK
}
@@ -95,8 +87,10 @@ class K2JSDce : CLITool<K2JSDceArguments>() {
val reachabilitySeverity = if (arguments.printReachabilityInfo) CompilerMessageSeverity.INFO else CompilerMessageSeverity.LOGGING
messageCollector.report(reachabilitySeverity, "")
for (node in nodes.extractRoots()) {
printTree(node, { messageCollector.report(reachabilitySeverity, it) },
printNestedMembers = false, showLocations = true)
printTree(
node, { messageCollector.report(reachabilitySeverity, it) },
printNestedMembers = false, showLocations = true
)
}
return ExitCode.OK
@@ -123,14 +117,13 @@ class K2JSDce : CLITool<K2JSDceArguments>() {
FileOutputStream(targetFile).use { output ->
input.copyTo(output)
}
}
}
}
private fun mapSourcePaths(inputFile: File, targetFile: File): Boolean {
val json = try {
InputStreamReader(FileInputStream(inputFile), "UTF-8").use { parseJson(it) }
}
catch (e: JsonSyntaxException) {
} catch (e: JsonSyntaxException) {
return false
}
@@ -145,12 +138,10 @@ class K2JSDce : CLITool<K2JSDceArguments>() {
if (result != null) {
if (File(targetFile.parentFile, result).exists()) {
result
}
else {
} else {
it
}
}
else {
} else {
it
}
}
@@ -165,7 +156,7 @@ class K2JSDce : CLITool<K2JSDceArguments>() {
return true
}
private fun collectInputFiles(baseDir: File, fileName: String, messageCollector: MessageCollector): List<InputFile>? {
private fun collectInputFiles(baseDir: File, fileName: String, messageCollector: MessageCollector): List<InputFile> {
val file = File(fileName)
return when {
file.isDirectory -> {
@@ -180,15 +171,17 @@ class K2JSDce : CLITool<K2JSDceArguments>() {
collectInputFilesFromZip(baseDir, fileName)
}
else -> {
messageCollector.report(CompilerMessageSeverity.ERROR,
"invalid file name '$fileName'; must end either with '.js', '.zip' or '.jar'")
null
messageCollector.report(
CompilerMessageSeverity.WARNING,
"invalid file name '${file.absolutePath}'; must end either with '.js', '.zip' or '.jar'"
)
emptyList()
}
}
}
else -> {
messageCollector.report(CompilerMessageSeverity.ERROR, "source file or directory not found: $fileName")
null
emptyList()
}
}
}
@@ -197,41 +190,47 @@ class K2JSDce : CLITool<K2JSDceArguments>() {
val moduleName = getModuleNameFromPath(path)
val pathToSourceMapCandidate = "$path.map"
val pathToSourceMap = if (File(pathToSourceMapCandidate).exists()) pathToSourceMapCandidate else null
return InputFile(InputResource.file(path), pathToSourceMap?.let { InputResource.file(it) },
File(baseDir, "$moduleName.js").absolutePath, moduleName)
return InputFile(
InputResource.file(path), pathToSourceMap?.let { InputResource.file(it) },
File(baseDir, "$moduleName.js").absolutePath, moduleName
)
}
private fun collectInputFilesFromZip(baseDir: File, path: String): List<InputFile> {
return ZipFile(path).use { zipFile ->
zipFile.entries().asSequence()
.filter { !it.isDirectory }
.filter { it.name.endsWith(".js") }
.filter { zipFile.getEntry(it.name.metaJs()) != null }
.distinctBy { it.name }
.map { entry ->
val moduleName = getModuleNameFromPath(entry.name)
val pathToSourceMapCandidate = "${entry.name}.map"
val pathToSourceMap = if (zipFile.getEntry(pathToSourceMapCandidate) != null) pathToSourceMapCandidate else null
InputFile(InputResource.zipFile(path, entry.name), pathToSourceMap?.let { InputResource.zipFile(path, it) },
File(baseDir, "$moduleName.js").absolutePath, moduleName)
}
.toList()
.filter { !it.isDirectory }
.filter { it.name.endsWith(".js") }
.filter { zipFile.getEntry(it.name.metaJs()) != null }
.distinctBy { it.name }
.map { entry ->
val moduleName = getModuleNameFromPath(entry.name)
val pathToSourceMapCandidate = "${entry.name}.map"
val pathToSourceMap = if (zipFile.getEntry(pathToSourceMapCandidate) != null) pathToSourceMapCandidate else null
InputFile(
InputResource.zipFile(path, entry.name), pathToSourceMap?.let { InputResource.zipFile(path, it) },
File(baseDir, "$moduleName.js").absolutePath, moduleName
)
}
.toList()
}
}
private fun collectInputFilesFromDirectory(baseDir: File, path: String): List<InputFile> {
return File(path).walkTopDown().asSequence()
.filter { !it.isDirectory }
.filter { it.name.endsWith(".js") }
.filter { File(it.path.metaJs()).exists() }
.map { entry ->
val moduleName = getModuleNameFromPath(entry.name)
val pathToSourceMapCandidate = "${entry.path}.map"
val pathToSourceMap = if (File(pathToSourceMapCandidate).exists()) pathToSourceMapCandidate else null
InputFile(InputResource.file(entry.path), pathToSourceMap?.let { InputResource.file(it) },
File(baseDir, "$moduleName.js").absolutePath, moduleName)
}
.toList()
.filter { !it.isDirectory }
.filter { it.name.endsWith(".js") }
.filter { File(it.path.metaJs()).exists() }
.map { entry ->
val moduleName = getModuleNameFromPath(entry.name)
val pathToSourceMapCandidate = "${entry.path}.map"
val pathToSourceMap = if (File(pathToSourceMapCandidate).exists()) pathToSourceMapCandidate else null
InputFile(
InputResource.file(entry.path), pathToSourceMap?.let { InputResource.file(it) },
File(baseDir, "$moduleName.js").absolutePath, moduleName
)
}
.toList()
}
private fun String.metaJs() = removeSuffix(".js") + ".meta.js"

View File

@@ -42,6 +42,7 @@ import org.jetbrains.kotlin.cli.jvm.plugins.PluginCliParser
import org.jetbrains.kotlin.cli.jvm.repl.ReplFromTerminal
import org.jetbrains.kotlin.codegen.CompilationException
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.incremental.components.ExpectActualTracker
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.javac.JavacWrapper
import org.jetbrains.kotlin.load.java.JavaClassesTracker
@@ -300,6 +301,10 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
configuration.put(CommonConfigurationKeys.LOOKUP_TRACKER, it)
}
services.get(ExpectActualTracker::class.java)?.let {
configuration.put(CommonConfigurationKeys.EXPECT_ACTUAL_TRACKER, it)
}
services.get(IncrementalCompilationComponents::class.java)?.let {
configuration.put(JVMConfigurationKeys.INCREMENTAL_COMPILATION_COMPONENTS, it)
}

View File

@@ -28,6 +28,9 @@ import com.intellij.ide.highlighter.JavaFileType
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.lang.MetaLanguage
import com.intellij.lang.java.JavaParserDefinition
import com.intellij.lang.jvm.facade.JvmElementProvider
import com.intellij.lang.jvm.facade.JvmFacade
import com.intellij.lang.jvm.facade.JvmFacadeImpl
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.TransactionGuard
import com.intellij.openapi.application.TransactionGuardImpl
@@ -43,6 +46,7 @@ import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.*
import com.intellij.openapi.vfs.impl.ZipHandler
import com.intellij.psi.FileContextProvider
import com.intellij.psi.JavaModuleSystem
import com.intellij.psi.PsiElementFinder
import com.intellij.psi.PsiManager
import com.intellij.psi.augment.PsiAugmentProvider
@@ -377,7 +381,7 @@ class KotlinCoreEnvironment private constructor(
}
companion object {
private val ideaCompatibleBuildNumber = "172.9999"
private val ideaCompatibleBuildNumber = "173.1"
init {
setCompatibleBuild()
@@ -500,6 +504,8 @@ class KotlinCoreEnvironment private constructor(
//
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), TypeAnnotationModifier.EP_NAME, TypeAnnotationModifier::class.java)
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), MetaLanguage.EP_NAME, MetaLanguage::class.java)
//
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), JavaModuleSystem.EP_NAME, JavaModuleSystem::class.java)
}
private fun registerApplicationExtensionPointsAndExtensionsFrom(configuration: CompilerConfiguration, configFilePath: String) {
@@ -549,6 +555,7 @@ class KotlinCoreEnvironment private constructor(
private fun registerProjectExtensionPoints(area: ExtensionsArea) {
CoreApplicationEnvironment.registerExtensionPoint(area, PsiTreeChangePreprocessor.EP_NAME, PsiTreeChangePreprocessor::class.java)
CoreApplicationEnvironment.registerExtensionPoint(area, PsiElementFinder.EP_NAME, PsiElementFinder::class.java)
CoreApplicationEnvironment.registerExtensionPoint(area, JvmElementProvider.EP_NAME, JvmElementProvider::class.java)
}
// made public for Upsource

View File

@@ -41,6 +41,7 @@ import org.jetbrains.kotlin.descriptors.impl.ModuleDependenciesImpl
import org.jetbrains.kotlin.frontend.java.di.createContainerForTopDownAnalyzerForJvm
import org.jetbrains.kotlin.frontend.java.di.initJvmBuiltInsForTopDownAnalysis
import org.jetbrains.kotlin.frontend.java.di.initialize
import org.jetbrains.kotlin.incremental.components.ExpectActualTracker
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.javac.components.JavacBasedClassFinder
import org.jetbrains.kotlin.javac.components.JavacBasedSourceElementFactory
@@ -133,6 +134,7 @@ object TopDownAnalyzerFacadeForJVM {
val incrementalComponents = configuration.get(JVMConfigurationKeys.INCREMENTAL_COMPILATION_COMPONENTS)
val lookupTracker = configuration.get(CommonConfigurationKeys.LOOKUP_TRACKER) ?: LookupTracker.DO_NOTHING
val expectActualTracker = configuration.get(CommonConfigurationKeys.EXPECT_ACTUAL_TRACKER) ?: ExpectActualTracker.DoNothing
val targetIds = configuration.get(JVMConfigurationKeys.MODULES)?.map(::TargetId)
val separateModules = !configuration.getBoolean(JVMConfigurationKeys.USE_SINGLE_MODULE)
@@ -171,7 +173,7 @@ object TopDownAnalyzerFacadeForJVM {
val dependencyScope = GlobalSearchScope.notScope(sourceScope)
val dependenciesContainer = createContainerForTopDownAnalyzerForJvm(
dependenciesContext, trace, DeclarationProviderFactory.EMPTY, dependencyScope, lookupTracker,
dependenciesContext, trace, DeclarationProviderFactory.EMPTY, dependencyScope, lookupTracker, expectActualTracker,
packagePartProvider(dependencyScope), moduleClassResolver, jvmTarget, languageVersionSettings, configureJavaClassFinder
)
@@ -196,7 +198,7 @@ object TopDownAnalyzerFacadeForJVM {
// to be stored in CliLightClassGenerationSupport, and it better be the source one (otherwise light classes would not be found)
// TODO: get rid of duplicate invocation of CodeAnalyzerInitializer#initialize, or refactor CliLightClassGenerationSupport
val container = createContainerForTopDownAnalyzerForJvm(
moduleContext, trace, declarationProviderFactory(storageManager, files), sourceScope, lookupTracker,
moduleContext, trace, declarationProviderFactory(storageManager, files), sourceScope, lookupTracker, expectActualTracker,
partProvider, moduleClassResolver, jvmTarget, languageVersionSettings, configureJavaClassFinder,
javaClassTracker = configuration[JVMConfigurationKeys.JAVA_CLASSES_TRACKER]
).apply {

View File

@@ -18,6 +18,7 @@ package org.jetbrains.kotlin.cli.jvm.repl
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.Disposer
import org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.repl.*
@@ -46,6 +47,9 @@ open class GenericReplCompiler(disposable: Disposable,
messageCollector: MessageCollector
) : ReplCompiler {
constructor(scriptDefinition: KotlinScriptDefinition, compilerConfiguration: CompilerConfiguration, messageCollector: MessageCollector) :
this(Disposer.newDisposable(), scriptDefinition, compilerConfiguration, messageCollector)
private val checker = GenericReplChecker(disposable, scriptDefinition, compilerConfiguration, messageCollector)
override fun createState(lock: ReentrantReadWriteLock): IReplStageState<*> = GenericReplCompilerState(checker.environment, lock)

View File

@@ -61,6 +61,7 @@ messages/**)
-dontwarn net.jpountz.lz4.LZ4Factory
-dontwarn org.jetbrains.annotations.ReadOnly
-dontwarn org.jetbrains.annotations.Mutable
-dontwarn com.intellij.util.io.TarUtil
#-libraryjars '<rtjar>'
#-libraryjars '<jssejar>'

View File

@@ -116,8 +116,9 @@ object KotlinCompilerClient {
}
else {
if (!isLastAttempt && autostart) {
startDaemon(compilerId, newJVMOptions, daemonOptions, reportingTargets)
reportingTargets.report(DaemonReportCategory.DEBUG, "new daemon started, trying to find it")
if (startDaemon(compilerId, newJVMOptions, daemonOptions, reportingTargets)) {
reportingTargets.report(DaemonReportCategory.DEBUG, "new daemon started, trying to find it")
}
}
null
}
@@ -361,7 +362,7 @@ object KotlinCompilerClient {
}
private fun startDaemon(compilerId: CompilerId, daemonJVMOptions: DaemonJVMOptions, daemonOptions: DaemonOptions, reportingTargets: DaemonReportingTargets) {
private fun startDaemon(compilerId: CompilerId, daemonJVMOptions: DaemonJVMOptions, daemonOptions: DaemonOptions, reportingTargets: DaemonReportingTargets): Boolean {
val javaExecutable = File(File(System.getProperty("java.home"), "bin"), "java")
val serverHostname = System.getProperty(JAVA_RMI_SERVER_HOSTNAME) ?: error("$JAVA_RMI_SERVER_HOSTNAME is not set!")
val platformSpecificOptions = listOf(
@@ -420,14 +421,22 @@ object KotlinCompilerClient {
} ?: DAEMON_DEFAULT_STARTUP_TIMEOUT_MS
if (daemonOptions.runFilesPath.isNotEmpty()) {
val succeeded = isEchoRead.tryAcquire(daemonStartupTimeout, TimeUnit.MILLISECONDS)
if (!isProcessAlive(daemon))
throw RuntimeException("Daemon terminated unexpectedly with error code: ${daemon.exitValue()}")
if (!succeeded)
throw RuntimeException("Unable to get response from daemon in $daemonStartupTimeout ms")
return when {
!isProcessAlive(daemon) -> {
reportingTargets.report(DaemonReportCategory.INFO, "Daemon terminated unexpectedly with error code: ${daemon.exitValue()}")
false
}
!succeeded -> {
reportingTargets.report(DaemonReportCategory.INFO, "Unable to get response from daemon in $daemonStartupTimeout ms")
false
}
else -> true
}
}
else
// without startEcho defined waiting for max timeout
Thread.sleep(daemonStartupTimeout)
return true
}
finally {
// assuming that all important output is already done, the rest should be routed to the log by the daemon itself

View File

@@ -92,13 +92,13 @@ private inline fun tryConnectToDaemon(port: Int, report: (DaemonReportCategory,
val daemon = LocateRegistry.getRegistry(LoopbackNetworkInterface.loopbackInetAddressName, port, LoopbackNetworkInterface.clientLoopbackSocketFactory)
?.lookup(COMPILER_SERVICE_RMI_NAME)
when (daemon) {
null -> report(DaemonReportCategory.EXCEPTION, "daemon not found")
null -> report(DaemonReportCategory.INFO, "daemon not found")
is CompileService -> return daemon
else -> report(DaemonReportCategory.EXCEPTION, "Unable to cast compiler service, actual class received: ${daemon::class.java.name}")
else -> report(DaemonReportCategory.INFO, "Unable to cast compiler service, actual class received: ${daemon::class.java.name}")
}
}
catch (e: Throwable) {
report(DaemonReportCategory.EXCEPTION, "cannot connect to registry: " + (e.cause?.message ?: e.message ?: "unknown error"))
report(DaemonReportCategory.INFO, "cannot connect to registry: " + (e.cause?.message ?: e.message ?: "unknown error"))
}
return null
}

View File

@@ -18,10 +18,7 @@ package org.jetbrains.kotlin.daemon.common
import java.io.IOException
import java.io.Serializable
import java.net.Inet6Address
import java.net.InetAddress
import java.net.ServerSocket
import java.net.Socket
import java.net.*
import java.rmi.RemoteException
import java.rmi.registry.LocateRegistry
import java.rmi.registry.Registry
@@ -33,6 +30,11 @@ import java.util.*
const val SOCKET_ANY_FREE_PORT = 0
const val JAVA_RMI_SERVER_HOSTNAME = "java.rmi.server.hostname"
const val DAEMON_RMI_SOCKET_BACKLOG_SIZE_PROPERTY = "kotlin.daemon.socket.backlog.size"
const val DAEMON_RMI_SOCKET_CONNECT_ATTEMPTS_PROPERTY = "kotlin.daemon.socket.connect.attempts"
const val DAEMON_RMI_SOCKET_CONNECT_INTERVAL_PROPERTY = "kotlin.daemon.socket.connect.interval"
const val DEFAULT_SERVER_SOCKET_BACKLOG_SIZE = 50
const val DEFAULT_SOCKET_CONNECT_ATTEMPTS = 3
const val DEFAULT_SOCKET_CONNECT_INTERVAL_MS = 10L
object LoopbackNetworkInterface {
@@ -41,7 +43,9 @@ object LoopbackNetworkInterface {
// size of the requests queue for daemon services, so far seems that we don't need any big numbers here
// but if we'll start getting "connection refused" errors, that could be the first place to try to fix it
val SERVER_SOCKET_BACKLOG_SIZE by lazy { System.getProperty(DAEMON_RMI_SOCKET_BACKLOG_SIZE_PROPERTY)?.toIntOrNull() ?: 50 }
val SERVER_SOCKET_BACKLOG_SIZE by lazy { System.getProperty(DAEMON_RMI_SOCKET_BACKLOG_SIZE_PROPERTY)?.toIntOrNull() ?: DEFAULT_SERVER_SOCKET_BACKLOG_SIZE }
val SOCKET_CONNECT_ATTEMPTS by lazy { System.getProperty(DAEMON_RMI_SOCKET_CONNECT_ATTEMPTS_PROPERTY)?.toIntOrNull() ?: DEFAULT_SOCKET_CONNECT_ATTEMPTS }
val SOCKET_CONNECT_INTERVAL_MS by lazy { System.getProperty(DAEMON_RMI_SOCKET_CONNECT_INTERVAL_PROPERTY)?.toLongOrNull() ?: DEFAULT_SOCKET_CONNECT_INTERVAL_MS }
val serverLoopbackSocketFactory by lazy { ServerLoopbackSocketFactory() }
val clientLoopbackSocketFactory by lazy { ClientLoopbackSocketFactory() }
@@ -75,7 +79,18 @@ object LoopbackNetworkInterface {
override fun hashCode(): Int = super.hashCode()
@Throws(IOException::class)
override fun createSocket(host: String, port: Int): Socket = Socket(InetAddress.getByName(null), port)
override fun createSocket(host: String, port: Int): Socket {
var attemptsLeft = SOCKET_CONNECT_ATTEMPTS
while (true) {
try {
return Socket(InetAddress.getByName(null), port)
}
catch (e: ConnectException) {
if (--attemptsLeft <= 0) throw e
}
Thread.sleep(SOCKET_CONNECT_INTERVAL_MS)
}
}
}
}

View File

@@ -453,8 +453,8 @@ class CompileServiceImpl(
workingDir,
enabled = true)
return IncrementalJsCompilerRunner(workingDir, versions, reporter)
.compile(allKotlinFiles, args, compilerMessageCollector, { changedFiles })
val compiler = IncrementalJsCompilerRunner(workingDir, versions, reporter)
return compiler.compile(allKotlinFiles, args, compilerMessageCollector, changedFiles)
}
private fun execIncrementalCompiler(
@@ -514,7 +514,7 @@ class CompileServiceImpl(
friendBuildHistoryFile = incrementalCompilationOptions.friendDifferenceFile,
usePreciseJavaTracking = incrementalCompilationOptions.usePreciseJavaTracking
)
return compiler.compile(allKotlinFiles, k2jvmArgs, compilerMessageCollector, { changedFiles })
return compiler.compile(allKotlinFiles, k2jvmArgs, compilerMessageCollector, changedFiles)
}
override fun leaseReplSession(

View File

@@ -29,6 +29,7 @@ import org.jetbrains.kotlin.contracts.ContractDeserializerImpl
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.PackagePartProvider
import org.jetbrains.kotlin.frontend.di.configureModule
import org.jetbrains.kotlin.incremental.components.ExpectActualTracker
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.load.java.AbstractJavaClassFinder
import org.jetbrains.kotlin.load.java.InternalFlexibleTypeTransformer
@@ -49,10 +50,12 @@ import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactory
private fun StorageComponentContainer.configureJavaTopDownAnalysis(
moduleContentScope: GlobalSearchScope,
project: Project,
lookupTracker: LookupTracker
lookupTracker: LookupTracker,
expectActualTracker: ExpectActualTracker
) {
useInstance(moduleContentScope)
useInstance(lookupTracker)
useInstance(expectActualTracker)
useImpl<ResolveSession>()
useImpl<LazyTopDownAnalyzer>()
@@ -79,6 +82,7 @@ fun createContainerForLazyResolveWithJava(
moduleClassResolver: ModuleClassResolver,
targetEnvironment: TargetEnvironment,
lookupTracker: LookupTracker,
expectActualTracker: ExpectActualTracker,
packagePartProvider: PackagePartProvider,
jvmTarget: JvmTarget,
languageVersionSettings: LanguageVersionSettings,
@@ -87,7 +91,7 @@ fun createContainerForLazyResolveWithJava(
javaClassTracker: JavaClassesTracker? = null
): StorageComponentContainer = createContainer("LazyResolveWithJava", JvmPlatform) {
configureModule(moduleContext, JvmPlatform, jvmTarget, bindingTrace)
configureJavaTopDownAnalysis(moduleContentScope, moduleContext.project, lookupTracker)
configureJavaTopDownAnalysis(moduleContentScope, moduleContext.project, lookupTracker, expectActualTracker)
if (configureJavaClassFinder != null) {
configureJavaClassFinder()
@@ -127,6 +131,7 @@ fun createContainerForTopDownAnalyzerForJvm(
declarationProviderFactory: DeclarationProviderFactory,
moduleContentScope: GlobalSearchScope,
lookupTracker: LookupTracker,
expectActualTracker: ExpectActualTracker,
packagePartProvider: PackagePartProvider,
moduleClassResolver: ModuleClassResolver,
jvmTarget: JvmTarget,
@@ -135,7 +140,7 @@ fun createContainerForTopDownAnalyzerForJvm(
javaClassTracker: JavaClassesTracker? = null
): ComponentProvider = createContainerForLazyResolveWithJava(
moduleContext, bindingTrace, declarationProviderFactory, moduleContentScope, moduleClassResolver,
CompilerEnvironment, lookupTracker, packagePartProvider, jvmTarget, languageVersionSettings,
CompilerEnvironment, lookupTracker, expectActualTracker, packagePartProvider, jvmTarget, languageVersionSettings,
useBuiltInsProvider = true,
configureJavaClassFinder = configureJavaClassFinder,
javaClassTracker = javaClassTracker

View File

@@ -16,7 +16,6 @@
package org.jetbrains.kotlin.resolve.jvm
import com.intellij.openapi.diagnostic.Logger
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.analyzer.*
import org.jetbrains.kotlin.config.JvmTarget
@@ -26,6 +25,7 @@ import org.jetbrains.kotlin.descriptors.PackagePartProvider
import org.jetbrains.kotlin.descriptors.impl.CompositePackageFragmentProvider
import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl
import org.jetbrains.kotlin.frontend.java.di.createContainerForLazyResolveWithJava
import org.jetbrains.kotlin.incremental.components.ExpectActualTracker
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.load.java.lazy.ModuleClassResolverImpl
import org.jetbrains.kotlin.load.java.structure.JavaClass
@@ -72,7 +72,6 @@ object JvmAnalyzerFacade : AnalyzerFacade() {
val resolverForReferencedModule = referencedClassModule?.let { resolverForProject.tryGetResolverForModule(it as M) }
val resolverForModule = resolverForReferencedModule ?: run {
LOG.warn("Java referenced $referencedClassModule from $moduleInfo\nReferenced class was: $javaClass\n")
// in case referenced class lies outside of our resolver, resolve the class as if it is inside our module
// this leads to java class being resolved several times
resolverForProject.resolverForModule(moduleInfo)
@@ -94,6 +93,7 @@ object JvmAnalyzerFacade : AnalyzerFacade() {
moduleClassResolver,
targetEnvironment,
lookupTracker,
ExpectActualTracker.DoNothing,
packagePartProvider,
jvmTarget,
languageVersionSettings,
@@ -120,6 +120,4 @@ object JvmAnalyzerFacade : AnalyzerFacade() {
override val targetPlatform: TargetPlatform
get() = JvmPlatform
private val LOG = Logger.getInstance(JvmAnalyzerFacade::class.java)
}

View File

@@ -34,6 +34,7 @@ import org.jetbrains.kotlin.descriptors.PackagePartProvider
import org.jetbrains.kotlin.descriptors.impl.CompositePackageFragmentProvider
import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl
import org.jetbrains.kotlin.frontend.di.configureModule
import org.jetbrains.kotlin.incremental.components.ExpectActualTracker
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.load.kotlin.MetadataFinderFactory
import org.jetbrains.kotlin.name.Name
@@ -142,6 +143,7 @@ object CommonAnalyzerFacade : AnalyzerFacade() {
useInstance(moduleContentScope)
useInstance(LookupTracker.DO_NOTHING)
useInstance(ExpectActualTracker.DoNothing)
useImpl<ResolveSession>()
useImpl<LazyTopDownAnalyzer>()
useInstance(languageVersionSettings)

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
* Copyright 2010-2018 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.

View File

@@ -1447,6 +1447,10 @@ class ControlFlowProcessor(private val trace: BindingTrace) {
generateCallOrMarkUnresolved(call)
}
override fun visitInitializerList(list: KtInitializerList) {
list.acceptChildren(this)
}
private fun generateCallOrMarkUnresolved(call: KtCallElement) {
if (!generateCall(call)) {
val arguments = call.valueArguments.mapNotNull(ValueArgument::getArgumentExpression)

View File

@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.config
import org.jetbrains.kotlin.incremental.components.ExpectActualTracker
import org.jetbrains.kotlin.incremental.components.LookupTracker
object CommonConfigurationKeys {
@@ -33,6 +34,9 @@ object CommonConfigurationKeys {
@JvmField
val LOOKUP_TRACKER = CompilerConfigurationKey.create<LookupTracker>("lookup tracker")
@JvmField
val EXPECT_ACTUAL_TRACKER = CompilerConfigurationKey.create<ExpectActualTracker>("expect actual tracker")
}
var CompilerConfiguration.languageVersionSettings: LanguageVersionSettings

View File

@@ -25,6 +25,7 @@ import org.jetbrains.kotlin.container.useImpl
import org.jetbrains.kotlin.container.useInstance
import org.jetbrains.kotlin.context.ModuleContext
import org.jetbrains.kotlin.extensions.StorageComponentContainerContributor
import org.jetbrains.kotlin.incremental.components.ExpectActualTracker
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.*
@@ -127,6 +128,7 @@ fun createContainerForLazyLocalClassifierAnalyzer(
useInstance(localClassDescriptorHolder)
useInstance(lookupTracker)
useInstance(ExpectActualTracker.DoNothing)
useImpl<LazyTopDownAnalyzer>()

View File

@@ -379,6 +379,11 @@ class KtPsiFactory @JvmOverloads constructor(private val project: Project, val m
return whenEntry
}
fun createWhenCondition(conditionText: String): KtWhenCondition {
val whenEntry = createWhenEntry("$conditionText -> {}")
return whenEntry.conditions[0]
}
fun createBlockStringTemplateEntry(expression: KtExpression): KtStringTemplateEntryWithExpression {
// We don't want reformatting here as it can potentially change something in raw strings
val stringTemplateExpression = createExpressionByPattern("\"$\${$0}\"", expression, reformat = false) as KtStringTemplateExpression

View File

@@ -20,6 +20,7 @@ import com.intellij.injected.editor.VirtualFileWindow
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import com.intellij.psi.impl.source.tree.TreeUtil
import com.intellij.psi.search.PsiSearchScopeUtil
import com.intellij.psi.search.SearchScope
import com.intellij.psi.util.PsiTreeUtil
@@ -400,3 +401,11 @@ fun ASTNode.siblings(forward: Boolean = true): Sequence<ASTNode> {
return generateSequence(treePrev) { it.treePrev }
}
}
fun ASTNode.leaves(forward: Boolean = true): Sequence<ASTNode> {
if (forward) {
return generateSequence(TreeUtil.nextLeaf(this)) { TreeUtil.nextLeaf(it) }
} else {
return generateSequence(TreeUtil.prevLeaf(this)) { TreeUtil.prevLeaf(it) }
}
}

View File

@@ -25,6 +25,7 @@ import org.jetbrains.kotlin.config.LanguageVersionSettings;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory1;
import org.jetbrains.kotlin.extensions.DeclarationAttributeAltererExtension;
import org.jetbrains.kotlin.incremental.components.ExpectActualTracker;
import org.jetbrains.kotlin.lexer.KtKeywordToken;
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken;
import org.jetbrains.kotlin.lexer.KtTokens;
@@ -280,7 +281,7 @@ public class ModifiersChecker {
@NotNull DeclarationDescriptor descriptor
) {
for (DeclarationChecker checker : declarationCheckers) {
checker.check(declaration, descriptor, trace, trace.getBindingContext(), languageVersionSettings);
checker.check(declaration, descriptor, trace, trace.getBindingContext(), languageVersionSettings, expectActualTracker);
}
OperatorModifierChecker.INSTANCE.check(declaration, descriptor, trace, languageVersionSettings);
PublishedApiUsageChecker.INSTANCE.check(declaration, descriptor, trace);
@@ -304,14 +305,19 @@ public class ModifiersChecker {
@NotNull
private final LanguageVersionSettings languageVersionSettings;
@NotNull
private final ExpectActualTracker expectActualTracker;
public ModifiersChecker(
@NotNull AnnotationChecker annotationChecker,
@NotNull Iterable<DeclarationChecker> declarationCheckers,
@NotNull LanguageVersionSettings languageVersionSettings
@NotNull LanguageVersionSettings languageVersionSettings,
@NotNull ExpectActualTracker expectActualTracker
) {
this.annotationChecker = annotationChecker;
this.declarationCheckers = declarationCheckers;
this.languageVersionSettings = languageVersionSettings;
this.expectActualTracker = expectActualTracker;
}
@NotNull

View File

@@ -136,6 +136,7 @@ class DynamicCallableDescriptors(storageManager: StorageManager, builtIns: Kotli
Modality.FINAL,
Visibilities.PUBLIC
)
functionDescriptor.setHasSynthesizedParameterNames(true)
return functionDescriptor
}

View File

@@ -19,6 +19,7 @@ package org.jetbrains.kotlin.resolve.checkers
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.incremental.components.ExpectActualTracker
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.resolve.BindingContext
@@ -29,7 +30,8 @@ interface DeclarationChecker {
descriptor: DeclarationDescriptor,
diagnosticHolder: DiagnosticSink,
bindingContext: BindingContext,
languageVersionSettings: LanguageVersionSettings
languageVersionSettings: LanguageVersionSettings,
expectActualTracker: ExpectActualTracker
)
}
@@ -38,7 +40,9 @@ interface SimpleDeclarationChecker : DeclarationChecker {
declaration: KtDeclaration,
descriptor: DeclarationDescriptor,
diagnosticHolder: DiagnosticSink,
bindingContext: BindingContext, languageVersionSettings: LanguageVersionSettings
bindingContext: BindingContext,
languageVersionSettings: LanguageVersionSettings,
expectActualTracker: ExpectActualTracker
) = check(declaration, descriptor, diagnosticHolder, bindingContext)
fun check(

View File

@@ -23,6 +23,7 @@ import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.diagnostics.Errors.DELEGATED_MEMBER_HIDES_SUPERTYPE_OVERRIDE
import org.jetbrains.kotlin.incremental.components.ExpectActualTracker
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtDelegatedSuperTypeEntry
@@ -37,7 +38,8 @@ class DelegationChecker : DeclarationChecker {
descriptor: DeclarationDescriptor,
diagnosticHolder: DiagnosticSink,
bindingContext: BindingContext,
languageVersionSettings: LanguageVersionSettings
languageVersionSettings: LanguageVersionSettings,
expectActualTracker: ExpectActualTracker
) {
if (descriptor !is ClassDescriptor) return
if (declaration !is KtClassOrObject) return

View File

@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.resolve.checkers
import com.intellij.openapi.vfs.VfsUtilCore
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.config.AnalysisFlag
import org.jetbrains.kotlin.config.LanguageFeature
@@ -23,6 +24,7 @@ import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.incremental.components.ExpectActualTracker
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtConstructor
@@ -40,6 +42,7 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered
import org.jetbrains.kotlin.resolve.source.PsiSourceFile
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeConstructor
import org.jetbrains.kotlin.types.TypeConstructorSubstitution
@@ -48,7 +51,9 @@ import org.jetbrains.kotlin.types.checker.NewKotlinTypeChecker
import org.jetbrains.kotlin.types.checker.TypeCheckerContext
import org.jetbrains.kotlin.types.typeUtil.asTypeProjection
import org.jetbrains.kotlin.utils.SmartList
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.kotlin.utils.keysToMap
import java.io.File
object ExpectedActualDeclarationChecker : DeclarationChecker {
override fun check(
@@ -56,7 +61,8 @@ object ExpectedActualDeclarationChecker : DeclarationChecker {
descriptor: DeclarationDescriptor,
diagnosticHolder: DiagnosticSink,
bindingContext: BindingContext,
languageVersionSettings: LanguageVersionSettings
languageVersionSettings: LanguageVersionSettings,
expectActualTracker: ExpectActualTracker
) {
if (!languageVersionSettings.supportsFeature(LanguageFeature.MultiPlatformProjects)) return
@@ -64,7 +70,7 @@ object ExpectedActualDeclarationChecker : DeclarationChecker {
if (descriptor !is MemberDescriptor || DescriptorUtils.isEnumEntry(descriptor)) return
if (descriptor.isExpect) {
checkExpectedDeclarationHasActual(declaration, descriptor, diagnosticHolder, descriptor.module)
checkExpectedDeclarationHasActual(declaration, descriptor, diagnosticHolder, descriptor.module, expectActualTracker)
}
else {
val checkActual = !languageVersionSettings.getFlag(AnalysisFlag.multiPlatformDoNotCheckActual)
@@ -76,7 +82,8 @@ object ExpectedActualDeclarationChecker : DeclarationChecker {
reportOn: KtNamedDeclaration,
descriptor: MemberDescriptor,
diagnosticHolder: DiagnosticSink,
platformModule: ModuleDescriptor
platformModule: ModuleDescriptor,
expectActualTracker: ExpectActualTracker
) {
// Only look for top level actual members; class members will be handled as a part of that expected class
if (descriptor.containingDeclaration !is PackageFragmentDescriptor) return
@@ -96,8 +103,32 @@ object ExpectedActualDeclarationChecker : DeclarationChecker {
val incompatibility = compatibility as Map<Incompatible, Collection<MemberDescriptor>>
diagnosticHolder.report(Errors.NO_ACTUAL_FOR_EXPECT.on(reportOn, descriptor, platformModule, incompatibility))
}
else {
val actualMembers = compatibility.asSequence()
.filter { (compatibility, _) ->
compatibility is Compatible || (compatibility is Incompatible && compatibility.kind != Compatibility.IncompatibilityKind.STRONG)
}.flatMap { it.value.asSequence() }
expectActualTracker?.reportExpectActual(expected = descriptor, actualMembers = actualMembers)
}
}
private fun ExpectActualTracker.reportExpectActual(expected: MemberDescriptor, actualMembers: Sequence<MemberDescriptor>) {
if (this is ExpectActualTracker.DoNothing) return
val expectedFile = sourceFile(expected) ?: return
for (actual in actualMembers) {
val actualFile = sourceFile(actual) ?: continue
report(expectedFile = expectedFile, actualFile = actualFile)
}
}
private fun sourceFile(descriptor: MemberDescriptor): File? =
descriptor.source
.containingFile
.safeAs<PsiSourceFile>()
?.run { VfsUtilCore.virtualToIoFile(psiFile.virtualFile) }
fun Map<out Compatibility, Collection<MemberDescriptor>>.allStrongIncompatibilities(): Boolean =
this.keys.all { it is Incompatible && it.kind == Compatibility.IncompatibilityKind.STRONG }

View File

@@ -22,6 +22,7 @@ import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.incremental.components.ExpectActualTracker
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.resolve.BindingContext
@@ -37,7 +38,8 @@ abstract class KotlinVersionStringAnnotationValueChecker(
descriptor: DeclarationDescriptor,
diagnosticHolder: DiagnosticSink,
bindingContext: BindingContext,
languageVersionSettings: LanguageVersionSettings
languageVersionSettings: LanguageVersionSettings,
expectActualTracker: ExpectActualTracker
) {
val annotation = descriptor.annotations.findAnnotation(annotationFqName) ?: return
val version = annotation.allValueArguments.values.singleOrNull()?.value as? String ?: return

View File

@@ -24,6 +24,7 @@ import org.jetbrains.kotlin.descriptors.VariableDescriptor
import org.jetbrains.kotlin.descriptors.impl.FunctionExpressionDescriptor
import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.incremental.components.ExpectActualTracker
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
@@ -61,7 +62,8 @@ object UnderscoreChecker : DeclarationChecker {
descriptor: DeclarationDescriptor,
diagnosticHolder: DiagnosticSink,
bindingContext: BindingContext,
languageVersionSettings: LanguageVersionSettings
languageVersionSettings: LanguageVersionSettings,
expectActualTracker: ExpectActualTracker
) {
if (declaration is KtProperty && descriptor !is VariableDescriptor) return
if (declaration is KtCallableDeclaration) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
* 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.
@@ -19,6 +19,7 @@ package org.jetbrains.kotlin.resolve.lazy
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
interface AbsentDescriptorHandler {
fun diagnoseDescriptorNotFound(declaration: KtDeclaration): DeclarationDescriptor
@@ -29,5 +30,9 @@ class BasicAbsentDescriptorHandler : AbsentDescriptorHandler {
}
class NoDescriptorForDeclarationException @JvmOverloads constructor(declaration: KtDeclaration, additionalDetails: String? = null) :
IllegalStateException("Descriptor wasn't found for declaration $declaration\n${declaration.getElementTextWithContext()}"
+ (additionalDetails?.let { "\n---------------------------------------------------\n$it" } ?: ""))
KotlinExceptionWithAttachments("Descriptor wasn't found for declaration $declaration"
+ (additionalDetails?.let { "\n---------------------------------------------------\n$it" } ?: "")) {
init {
withAttachment("declaration.kt", declaration.getElementTextWithContext())
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
* 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.
@@ -41,6 +41,7 @@ import org.jetbrains.kotlin.util.KotlinFrontEndException;
import org.jetbrains.kotlin.util.LookupTrackerUtilKt;
import org.jetbrains.kotlin.util.PerformanceCounter;
import org.jetbrains.kotlin.util.ReenteringLazyValueComputationException;
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments;
import static org.jetbrains.kotlin.diagnostics.Errors.TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM;
@@ -240,8 +241,8 @@ public abstract class ExpressionTypingVisitorDispatcher extends KtVisitor<Kotlin
try {
// This trows AssertionError in CLI and reports the error in the IDE
LOG.error(
"Exception while analyzing expression at " + DiagnosticUtils.atLocation(expression) + ":\n" + expression.getText() + "\n",
e
new KotlinExceptionWithAttachments("Exception while analyzing expression at " + DiagnosticUtils.atLocation(expression), e)
.withAttachment("expression.kt", expression.getText())
);
}
catch (AssertionError errorFromLogger) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
* 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.
@@ -17,11 +17,15 @@
package org.jetbrains.kotlin.util
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.diagnostics.DiagnosticUtils
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
class KotlinFrontEndException(message: String, cause: Throwable) : RuntimeException(message, cause) {
class KotlinFrontEndException(message: String, cause: Throwable) : KotlinExceptionWithAttachments(message, cause) {
constructor(
message: String,
cause: Throwable,
element: PsiElement
) : this(getExceptionMessage("Front-end", message, cause, element), cause)
) : this(getExceptionMessage("Front-end", message, cause, DiagnosticUtils.atLocation(element)), cause) {
withAttachment("element.kt", element.text)
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
* 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.
@@ -17,14 +17,12 @@
package org.jetbrains.kotlin.util
import com.intellij.openapi.application.ApplicationManager
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.diagnostics.DiagnosticUtils
fun getExceptionMessage(
subsystemName: String,
message: String,
cause: Throwable?,
element: PsiElement?
location: String?
): String = ApplicationManager.getApplication().runReadAction<String> {
val result = StringBuilder(subsystemName + " Internal error: ").append(message).append("\n")
if (cause != null) {
@@ -32,9 +30,8 @@ fun getExceptionMessage(
result.append("Cause: ").append(causeMessage ?: cause.toString()).append("\n")
}
if (element != null) {
result.append("File being compiled and position: ").append(DiagnosticUtils.atLocation(element)).append("\n")
result.append("PsiElement: ").append(element.text).append("\n")
if (location != null) {
result.append("File being compiled and position: ").append(location).append("\n")
}
else {
result.append("Element is unknown")

View File

@@ -0,0 +1,31 @@
/*
* 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.incremental
import org.jetbrains.kotlin.incremental.components.ExpectActualTracker
import java.io.File
internal class ExpectActualTrackerImpl : ExpectActualTracker {
private val expectToActual = hashMapOf<File, MutableSet<File>>()
val expectToActualMap: Map<File, Set<File>>
get() = expectToActual
override fun report(expectedFile: File, actualFile: File) {
expectToActual.getOrPut(expectedFile) { hashSetOf() }.add(actualFile)
}
}

View File

@@ -19,7 +19,7 @@ package org.jetbrains.kotlin.incremental
import org.jetbrains.kotlin.incremental.storage.BasicMapsOwner
import java.io.File
abstract class IncrementalCachesManager<PlatformCache : IncrementalCacheCommon>(
abstract class IncrementalCachesManager<PlatformCache : IncrementalCacheCommon<*>>(
protected val cachesRootDir: File,
protected val reporter: ICReporter
) {

View File

@@ -25,6 +25,7 @@ import org.jetbrains.kotlin.compilerRunner.OutputItemsCollectorImpl
import org.jetbrains.kotlin.compilerRunner.SimpleOutputItem
import org.jetbrains.kotlin.compilerRunner.toGeneratedFile
import org.jetbrains.kotlin.config.Services
import org.jetbrains.kotlin.incremental.components.ExpectActualTracker
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.incremental.multiproject.ArtifactChangesProvider
import org.jetbrains.kotlin.incremental.multiproject.ChangesRegistry
@@ -54,10 +55,12 @@ abstract class IncrementalCompilerRunner<
protected abstract fun destinationDir(args: Args): File
fun compile(
allKotlinSources: List<File>,
allSourceFiles: List<File>,
args: Args,
messageCollector: MessageCollector,
getChangedFiles: (CacheManager)-> ChangedFiles
// when [providedChangedFiles] is not null, changes are provided by external system (e.g. Gradle)
// otherwise we track source files changes ourselves.
providedChangedFiles: ChangedFiles?
): ExitCode {
assert(isICEnabled()) { "Incremental compilation is not enabled" }
var caches = createCacheManager(args)
@@ -70,18 +73,20 @@ abstract class IncrementalCompilerRunner<
destinationDir(args).deleteRecursively()
caches = createCacheManager(args)
// todo more optimal fix
caches.inputsCache.sourceSnapshotMap.compareAndUpdate(allKotlinSources)
return compileIncrementally(args, caches, allKotlinSources, CompilationMode.Rebuild(), messageCollector)
if (providedChangedFiles == null) {
caches.inputsCache.sourceSnapshotMap.compareAndUpdate(allSourceFiles)
}
val allKotlinFiles = allSourceFiles.filter { it.isKotlinFile() }
return compileIncrementally(args, caches, allKotlinFiles, CompilationMode.Rebuild(), messageCollector)
}
return try {
val changedFiles = getChangedFiles(caches)
val changedFiles = providedChangedFiles ?: caches.inputsCache.sourceSnapshotMap.compareAndUpdate(allSourceFiles)
val compilationMode = sourcesToCompile(caches, changedFiles, args)
val exitCode = when (compilationMode) {
is CompilationMode.Incremental -> {
compileIncrementally(args, caches, allKotlinSources, compilationMode, messageCollector)
compileIncrementally(args, caches, allSourceFiles, compilationMode, messageCollector)
}
is CompilationMode.Rebuild -> {
rebuild { "Non-incremental compilation will be performed: ${compilationMode.reason}" }
@@ -113,7 +118,7 @@ abstract class IncrementalCompilerRunner<
}.filterTo(dirtyFiles, File::isKotlinFile)
if (dirtySourcesSinceLastTimeFile.exists()) {
val files = dirtySourcesSinceLastTimeFile.readLines().map(::File).filter(File::exists)
val files = dirtySourcesSinceLastTimeFile.readLines().map(::File)
if (files.isNotEmpty()) {
reporter.report { "Source files added since last compilation: ${reporter.pathsAsString(files)}" }
}
@@ -149,11 +154,13 @@ abstract class IncrementalCompilerRunner<
protected open fun makeServices(
args: Args,
lookupTracker: LookupTracker,
expectActualTracker: ExpectActualTracker,
caches: CacheManager,
compilationMode: CompilationMode
): Services.Builder =
Services.Builder().apply {
register(LookupTracker::class.java, lookupTracker)
register(ExpectActualTracker::class.java, expectActualTracker)
register(CompilationCanceledStatus::class.java, EmptyCompilationCanceledStatus)
}
@@ -185,22 +192,24 @@ abstract class IncrementalCompilerRunner<
val allSourcesToCompile = HashSet<File>()
var exitCode = ExitCode.OK
val allGeneratedFiles = hashSetOf<GeneratedFile>()
while (dirtySources.any() || runWithNoDirtyKotlinSources(caches)) {
val complementaryFiles = caches.inputsCache.clearComplementaryFilesMapping(dirtySources)
dirtySources.addAll(complementaryFiles)
caches.platformCache.markDirty(dirtySources)
caches.inputsCache.removeOutputForSourceFiles(dirtySources)
val lookupTracker = LookupTrackerImpl(LookupTracker.DO_NOTHING)
val expectActualTracker = ExpectActualTrackerImpl()
val (sourcesToCompile, removedKotlinSources) = dirtySources.partition(File::exists)
// todo: more optimal to save only last iteration, but it will require adding standalone-ic specific logs
// (because jps rebuilds all files from last build if it failed and gradle rebuilds everything)
allSourcesToCompile.addAll(sourcesToCompile)
val text = allSourcesToCompile.joinToString(separator = System.getProperty("line.separator")) { it.canonicalPath }
val text = dirtySources.joinToString(separator = System.getProperty("line.separator")) { it.canonicalPath }
dirtySourcesSinceLastTimeFile.writeText(text)
val services = makeServices(args, lookupTracker, caches, compilationMode).build()
val services = makeServices(args, lookupTracker, expectActualTracker, caches, compilationMode).build()
args.reportOutputFiles = true
val outputItemsCollector = OutputItemsCollectorImpl()
@@ -224,7 +233,7 @@ abstract class IncrementalCompilerRunner<
}
}
allGeneratedFiles.addAll(generatedFiles)
caches.inputsCache.registerComplementaryFiles(expectActualTracker)
caches.inputsCache.registerOutputForSourceFiles(generatedFiles)
caches.lookupCache.update(lookupTracker, sourcesToCompile, removedKotlinSources)
val changesCollector = ChangesCollector()

View File

@@ -24,6 +24,7 @@ import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.js.K2JSCompiler
import org.jetbrains.kotlin.config.IncrementalCompilation
import org.jetbrains.kotlin.config.Services
import org.jetbrains.kotlin.incremental.components.ExpectActualTracker
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.incremental.js.*
import java.io.File
@@ -41,9 +42,7 @@ fun makeJsIncrementally(
withJsIC {
val compiler = IncrementalJsCompilerRunner(cachesDir, versions, reporter)
compiler.compile(allKotlinFiles, args, messageCollector) {
it.inputsCache.sourceSnapshotMap.compareAndUpdate(allKotlinFiles)
}
compiler.compile(allKotlinFiles, args, messageCollector, providedChangedFiles = null)
}
}
@@ -99,10 +98,11 @@ class IncrementalJsCompilerRunner(
override fun makeServices(
args: K2JSCompilerArguments,
lookupTracker: LookupTracker,
expectActualTracker: ExpectActualTracker,
caches: IncrementalJsCachesManager,
compilationMode: CompilationMode
): Services.Builder =
super.makeServices(args, lookupTracker, caches, compilationMode).apply {
super.makeServices(args, lookupTracker, expectActualTracker, caches, compilationMode).apply {
register(IncrementalResultsConsumer::class.java, IncrementalResultsConsumerImpl())
if (compilationMode is CompilationMode.Incremental) {
@@ -121,7 +121,8 @@ class IncrementalJsCompilerRunner(
val jsCache = caches.platformCache
jsCache.header = incrementalResults.headerMetadata
return jsCache.compareAndUpdate(incrementalResults, changesCollector)
jsCache.compareAndUpdate(incrementalResults, changesCollector)
jsCache.clearCacheForRemovedClasses(changesCollector)
}
override fun runCompiler(

View File

@@ -37,6 +37,7 @@ import org.jetbrains.kotlin.compilerRunner.ArgumentUtils
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.IncrementalCompilation
import org.jetbrains.kotlin.config.Services
import org.jetbrains.kotlin.incremental.components.ExpectActualTracker
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.incremental.multiproject.ArtifactChangesProvider
import org.jetbrains.kotlin.incremental.multiproject.ChangesRegistry
@@ -63,7 +64,6 @@ fun makeIncrementally(
val rootsWalk = sourceRoots.asSequence().flatMap { it.walk() }
val files = rootsWalk.filter(File::isFile)
val sourceFiles = files.filter { it.extension.toLowerCase() in allExtensions }.toList()
val kotlinFiles = sourceFiles.filter { it.extension.toLowerCase() in kotlinExtensions }
withIC {
val compiler = IncrementalJvmCompilerRunner(
@@ -73,9 +73,7 @@ fun makeIncrementally(
// Use precise setting in case of non-Gradle build
usePreciseJavaTracking = true
)
compiler.compile(kotlinFiles, args, messageCollector) {
it.inputsCache.sourceSnapshotMap.compareAndUpdate(sourceFiles)
}
compiler.compile(sourceFiles, args, messageCollector, providedChangedFiles = null)
}
}
@@ -158,11 +156,11 @@ class IncrementalJvmCompilerRunner(
dirtyFiles.addAll(dirtyFilesFromFqNames)
}
val lastBuildInfo = BuildInfo.read(lastBuildInfoFile)
val lastBuildInfo = BuildInfo.read(lastBuildInfoFile) ?: return CompilationMode.Rebuild { "No information on previous build" }
reporter.report { "Last Kotlin Build info -- $lastBuildInfo" }
val changesFromFriend by lazy {
val myLastTS = lastBuildInfo?.startTS ?: return@lazy ChangesEither.Unknown()
val myLastTS = lastBuildInfo.startTS
val storage = friendBuildHistoryFile?.let { BuildDiffsStorage.readFromFile(it, reporter) } ?: return@lazy ChangesEither.Unknown()
val (prevDiffs, newDiffs) = storage.buildDiffs.partition { it.ts < myLastTS }
@@ -226,6 +224,12 @@ class IncrementalJvmCompilerRunner(
for (javaFile in javaFiles) {
if (!caches.platformCache.isTrackedFile(javaFile)) {
if (!javaFile.exists()) {
// todo: can we do this more optimal?
reporter.report { "Could not get changed for untracked removed java file $javaFile" }
return false
}
val psiFile = javaFile.psiFile()
if (psiFile !is PsiJavaFile) {
reporter.report { "[Precise Java tracking] Expected PsiJavaFile, got ${psiFile?.javaClass}" }
@@ -404,10 +408,11 @@ class IncrementalJvmCompilerRunner(
override fun makeServices(
args: K2JVMCompilerArguments,
lookupTracker: LookupTracker,
expectActualTracker: ExpectActualTracker,
caches: IncrementalJvmCachesManager,
compilationMode: CompilationMode
): Services.Builder =
super.makeServices(args, lookupTracker, caches, compilationMode).apply {
super.makeServices(args, lookupTracker, expectActualTracker, caches, compilationMode).apply {
val targetId = TargetId(args.moduleName!!, "java-production")
val targetToCache = mapOf(targetId to caches.platformCache)
val incrementalComponents = IncrementalCompilationComponentsImpl(targetToCache)

View File

@@ -23,20 +23,63 @@ import org.jetbrains.kotlin.incremental.storage.BasicMapsOwner
import org.jetbrains.kotlin.incremental.storage.BasicStringMap
import org.jetbrains.kotlin.incremental.storage.PathStringDescriptor
import org.jetbrains.kotlin.incremental.storage.StringCollectionExternalizer
import org.jetbrains.kotlin.modules.TargetId
import java.io.File
import java.util.*
import kotlin.collections.HashSet
class InputsCache(
workingDir: File,
private val reporter: ICReporter
) : BasicMapsOwner(workingDir) {
companion object {
private val SOURCE_TO_OUTPUT_FILES = "source-to-output"
private val SOURCE_SNAPSHOTS = "source-snapshot"
private val SOURCE_TO_OUTPUT_FILES = "source-to-output"
private val COMPLEMENTARY_FILES = "complementary-files"
}
internal val sourceToOutputMap = registerMap(SourceToOutputFilesMap(SOURCE_TO_OUTPUT_FILES.storageFile))
internal val sourceSnapshotMap = registerMap(FileSnapshotMap(SOURCE_SNAPSHOTS.storageFile))
private val sourceToOutputMap = registerMap(FilesMap(SOURCE_TO_OUTPUT_FILES.storageFile))
/**
* A file X is a complementary to a file Y if they contain corresponding expect/actual declarations.
* Complementary files should be compiled together during IC so the compiler does not complain
* about missing parts.
* TODO: provide a better solution (maintain an index of expect/actual declarations akin to IncrementalPackagePartProvider)
*/
private val complementaryFilesMap = registerMap(FilesMap(COMPLEMENTARY_FILES.storageFile))
fun clearComplementaryFilesMapping(dirtyFiles: Collection<File>): Collection<File> {
val complementaryFiles = HashSet<File>()
val filesQueue = ArrayDeque(dirtyFiles)
while (filesQueue.isNotEmpty()) {
val file = filesQueue.pollFirst()
complementaryFilesMap.remove(file).filterTo(filesQueue) { complementaryFiles.add(it) }
}
complementaryFiles.removeAll(dirtyFiles)
return complementaryFiles
}
internal fun registerComplementaryFiles(expectActualTracker: ExpectActualTrackerImpl) {
val actualToExpect = hashMapOf<File, MutableSet<File>>()
for ((expect, actuals) in expectActualTracker.expectToActualMap) {
for (actual in actuals) {
actualToExpect.getOrPut(actual) { hashSetOf() }.add(expect)
}
complementaryFilesMap[expect] = actuals
}
for ((actual, expects) in actualToExpect) {
complementaryFilesMap[actual] = expects
}
}
fun removeOutputForSourceFiles(sources: Iterable<File>) {
for (sourceFile in sources) {
sourceToOutputMap.remove(sourceFile).forEach { it ->
reporter.report { "Deleting $it on clearing cache for $sourceFile" }
it.delete()
}
}
}
// generatedFiles can contain multiple entries with the same source file
// for example Kapt3 IC will generate a .java stub and .class stub for each source file
@@ -53,29 +96,21 @@ class InputsCache(
sourceToOutputMap[source] = outputs
}
}
}
fun removeOutputForSourceFiles(sources: Iterable<File>) {
sources.forEach { sourceToOutputMap.remove(it) }
private class FilesMap(storageFile: File)
: BasicStringMap<Collection<String>>(storageFile, PathStringDescriptor, StringCollectionExternalizer) {
operator fun set(sourceFile: File, outputFiles: Collection<File>) {
storage[sourceFile.absolutePath] = outputFiles.map { it.absolutePath }
}
inner class SourceToOutputFilesMap(storageFile: File) : BasicStringMap<Collection<String>>(storageFile, PathStringDescriptor, StringCollectionExternalizer) {
operator fun set(sourceFile: File, outputFiles: Collection<File>) {
storage[sourceFile.absolutePath] = outputFiles.map { it.absolutePath }
}
operator fun get(sourceFile: File): Collection<File> =
storage[sourceFile.absolutePath].orEmpty().map(::File)
operator fun get(sourceFile: File): Collection<File> =
storage[sourceFile.absolutePath].orEmpty().map(::File)
override fun dumpValue(value: Collection<String>) =
value.dumpCollection()
override fun dumpValue(value: Collection<String>) = value.dumpCollection()
fun remove(file: File) {
// TODO: do it in the code that uses cache, since cache should not generally delete anything outside of it!
// but for a moment it is an easiest solution to implement
get(file).forEach {
reporter.report { "Deleting $it on clearing cache for $file" }
it.delete()
}
storage.remove(file.absolutePath)
}
}
fun remove(file: File): Collection<File> =
get(file).also { storage.remove(file.absolutePath) }
}

View File

@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.incremental
import com.intellij.testFramework.UsefulTestCase
import com.intellij.util.containers.HashMap
import org.jetbrains.kotlin.TestWithWorkingDir
import org.jetbrains.kotlin.cli.common.ExitCode
@@ -23,9 +24,6 @@ import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.incremental.testingUtils.*
import org.jetbrains.kotlin.incremental.utils.TestCompilationResult
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import java.io.File
abstract class AbstractIncrementalCompilerRunnerTestBase<Args : CommonCompilerArguments> : TestWithWorkingDir() {
@@ -83,7 +81,13 @@ abstract class AbstractIncrementalCompilerRunnerTestBase<Args : CommonCompilerAr
}
if (expectedSBWithoutErrors.toString() != actualSBWithoutErrors.toString()) {
Assert.assertEquals(expectedSB.toString(), actualSB.toString())
if (BuildLogFinder.isJpsLogFile(buildLogFile)) {
// JPS logs should be updated carefully, because standalone logs are a bit different (no removed classes, iterations, etc)
Assert.assertEquals(expectedSB.toString(), actualSB.toString())
}
else {
UsefulTestCase.assertSameLinesWithFile(buildLogFile.canonicalPath, actualSB.toString(), false)
}
}
// todo: also compare caches
@@ -110,20 +114,17 @@ abstract class AbstractIncrementalCompilerRunnerTestBase<Args : CommonCompilerAr
private fun stepLogAsString(step: Int, ktSources: Iterable<String>, errors: Collection<String>, includeErrors: Boolean = true): String {
val sb = StringBuilder()
sb.appendLine("<======= STEP $step =======>")
sb.appendLine()
sb.appendLine("Compiled kotlin sources:")
ktSources.toSet().toTypedArray().sortedArray().forEach { sb.appendLine(it) }
sb.appendLine("================ Step #$step =================")
sb.appendLine()
sb.appendLine("Compiling files:")
ktSources.toSet().toTypedArray().sortedArray().forEach { sb.appendLine(" $it") }
sb.appendLine("End of files")
sb.appendLine("Exit code: ${if (errors.isEmpty()) "OK" else "ABORT"}")
if (errors.isEmpty()) {
sb.appendLine("SUCCESS")
}
else {
sb.appendLine("FAILURE")
if (includeErrors) {
errors.filter(String::isNotEmpty).forEach { sb.appendLine(it) }
}
if (errors.isNotEmpty() && includeErrors) {
sb.appendLine("------------------------------------------")
sb.appendLine("COMPILATION FAILED")
errors.filter(String::isNotEmpty).forEach { sb.appendLine(it) }
}
return sb.toString()
@@ -136,6 +137,11 @@ abstract class AbstractIncrementalCompilerRunnerTestBase<Args : CommonCompilerAr
companion object {
@JvmStatic
protected val bootstrapKotlincLib: File = File("dependencies/bootstrap-compiler/Kotlin/kotlinc/lib")
private val distKotlincLib: File = File("dist/kotlinc/lib")
@JvmStatic
protected val kotlinStdlibJvm: File = File(distKotlincLib, "kotlin-stdlib.jar").also {
UsefulTestCase.assertExists(it)
}
}
}

View File

@@ -37,6 +37,6 @@ abstract class AbstractIncrementalJsCompilerRunnerTest : AbstractIncrementalComp
override fun createCompilerArguments(destinationDir: File, testDir: File): K2JSCompilerArguments =
K2JSCompilerArguments().apply {
outputFile = File(destinationDir, "${testDir.name}.js").path
libraries = File(bootstrapKotlincLib, "kotlin-stdlib-js.jar").path
sourceMap = true
}
}

View File

@@ -0,0 +1,27 @@
/*
* 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.incremental
import org.jetbrains.kotlin.cli.common.arguments.K2JSCompilerArguments
import java.io.File
abstract class AbstractIncrementalJsCompilerRunnerWithFriendModulesDisabledTest : AbstractIncrementalJsCompilerRunnerTest() {
override fun createCompilerArguments(destinationDir: File, testDir: File): K2JSCompilerArguments =
super.createCompilerArguments(destinationDir, testDir).apply {
friendModulesDisabled = true
}
}

View File

@@ -77,7 +77,7 @@ abstract class AbstractIncrementalJvmCompilerRunnerTest : AbstractIncrementalCom
private val compileClasspath =
listOf(
File(bootstrapKotlincLib, "kotlin-stdlib.jar"),
kotlinStdlibJvm,
KotlinTestUtils.getAnnotationsJar()
).joinToString(File.pathSeparator) { it.canonicalPath }
}

View File

@@ -0,0 +1,29 @@
/*
* 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.incremental
import org.jetbrains.kotlin.cli.common.arguments.K2JSCompilerArguments
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import java.io.File
abstract class AbstractIncrementalMultiplatformJsCompilerRunnerTest : AbstractIncrementalJsCompilerRunnerTest() {
override fun createCompilerArguments(destinationDir: File, testDir: File): K2JSCompilerArguments {
return super.createCompilerArguments(destinationDir, testDir).apply {
multiPlatform = true
}
}
}

View File

@@ -0,0 +1,28 @@
/*
* 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.incremental
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import java.io.File
abstract class AbstractIncrementalMultiplatformJvmCompilerRunnerTest : AbstractIncrementalJvmCompilerRunnerTest() {
override fun createCompilerArguments(destinationDir: File, testDir: File): K2JVMCompilerArguments {
return super.createCompilerArguments(destinationDir, testDir).apply {
multiPlatform = true
}
}
}

View File

@@ -122,12 +122,6 @@ public class IncrementalJsCompilerRunnerTestGenerated extends AbstractIncrementa
doTest(fileName);
}
@TestMetadata("classRedeclaration")
public void testClassRedeclaration() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("jps-plugin/testData/incremental/pureKotlin/classRedeclaration/");
doTest(fileName);
}
@TestMetadata("classSignatureChanged")
public void testClassSignatureChanged() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("jps-plugin/testData/incremental/pureKotlin/classSignatureChanged/");
@@ -965,4 +959,28 @@ public class IncrementalJsCompilerRunnerTestGenerated extends AbstractIncrementa
doTest(fileName);
}
}
@TestMetadata("jps-plugin/testData/incremental/js")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public static class Js extends AbstractIncrementalJsCompilerRunnerTest {
public void testAllFilesPresentInJs() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("jps-plugin/testData/incremental/js"), Pattern.compile("^([^\\.]+)$"), TargetBackend.ANY, true);
}
@TestMetadata("jps-plugin/testData/incremental/js/friendsModuleDisabled")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public static class FriendsModuleDisabled extends AbstractIncrementalJsCompilerRunnerTest {
public void testAllFilesPresentInFriendsModuleDisabled() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("jps-plugin/testData/incremental/js/friendsModuleDisabled"), Pattern.compile("^([^\\.]+)$"), TargetBackend.ANY, true);
}
@TestMetadata("internalInlineFunctionIsChanged")
public void testInternalInlineFunctionIsChanged() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("jps-plugin/testData/incremental/js/friendsModuleDisabled/internalInlineFunctionIsChanged/");
doTest(fileName);
}
}
}
}

View File

@@ -0,0 +1,44 @@
/*
* 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.incremental;
import com.intellij.testFramework.TestDataPath;
import org.jetbrains.kotlin.test.JUnit3RunnerWithInners;
import org.jetbrains.kotlin.test.KotlinTestUtils;
import org.jetbrains.kotlin.test.TargetBackend;
import org.jetbrains.kotlin.test.TestMetadata;
import org.junit.runner.RunWith;
import java.io.File;
import java.util.regex.Pattern;
/** This class is generated by {@link org.jetbrains.kotlin.generators.tests.TestsPackage}. DO NOT MODIFY MANUALLY */
@SuppressWarnings("all")
@TestMetadata("jps-plugin/testData/incremental/js/friendsModuleDisabled")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public class IncrementalJsCompilerRunnerWithFriendModulesDisabledTestGenerated extends AbstractIncrementalJsCompilerRunnerWithFriendModulesDisabledTest {
public void testAllFilesPresentInFriendsModuleDisabled() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("jps-plugin/testData/incremental/js/friendsModuleDisabled"), Pattern.compile("^([^\\.]+)$"), TargetBackend.ANY, false);
}
@TestMetadata("internalInlineFunctionIsChanged")
public void testInternalInlineFunctionIsChanged() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("jps-plugin/testData/incremental/js/friendsModuleDisabled/internalInlineFunctionIsChanged/");
doTest(fileName);
}
}

View File

@@ -122,12 +122,6 @@ public class IncrementalJvmCompilerRunnerTestGenerated extends AbstractIncrement
doTest(fileName);
}
@TestMetadata("classRedeclaration")
public void testClassRedeclaration() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("jps-plugin/testData/incremental/pureKotlin/classRedeclaration/");
doTest(fileName);
}
@TestMetadata("classSignatureChanged")
public void testClassSignatureChanged() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("jps-plugin/testData/incremental/pureKotlin/classSignatureChanged/");
@@ -1363,6 +1357,12 @@ public class IncrementalJvmCompilerRunnerTestGenerated extends AbstractIncrement
doTest(fileName);
}
@TestMetadata("classRedeclaration")
public void testClassRedeclaration() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("jps-plugin/testData/incremental/withJava/other/classRedeclaration/");
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,50 @@
/*
* 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.incremental;
import com.intellij.testFramework.TestDataPath;
import org.jetbrains.kotlin.test.JUnit3RunnerWithInners;
import org.jetbrains.kotlin.test.KotlinTestUtils;
import org.jetbrains.kotlin.test.TargetBackend;
import org.jetbrains.kotlin.test.TestMetadata;
import org.junit.runner.RunWith;
import java.io.File;
import java.util.regex.Pattern;
/** This class is generated by {@link org.jetbrains.kotlin.generators.tests.TestsPackage}. DO NOT MODIFY MANUALLY */
@SuppressWarnings("all")
@TestMetadata("jps-plugin/testData/incremental/multiplatform")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public class IncrementalMultiplatformJsCompilerRunnerTestGenerated extends AbstractIncrementalMultiplatformJsCompilerRunnerTest {
public void testAllFilesPresentInMultiplatform() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("jps-plugin/testData/incremental/multiplatform"), Pattern.compile("^([^\\.]+)$"), TargetBackend.ANY, true);
}
@TestMetadata("touchActual")
public void testTouchActual() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("jps-plugin/testData/incremental/multiplatform/touchActual/");
doTest(fileName);
}
@TestMetadata("touchExpect")
public void testTouchExpect() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("jps-plugin/testData/incremental/multiplatform/touchExpect/");
doTest(fileName);
}
}

View File

@@ -0,0 +1,50 @@
/*
* 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.incremental;
import com.intellij.testFramework.TestDataPath;
import org.jetbrains.kotlin.test.JUnit3RunnerWithInners;
import org.jetbrains.kotlin.test.KotlinTestUtils;
import org.jetbrains.kotlin.test.TargetBackend;
import org.jetbrains.kotlin.test.TestMetadata;
import org.junit.runner.RunWith;
import java.io.File;
import java.util.regex.Pattern;
/** This class is generated by {@link org.jetbrains.kotlin.generators.tests.TestsPackage}. DO NOT MODIFY MANUALLY */
@SuppressWarnings("all")
@TestMetadata("jps-plugin/testData/incremental/multiplatform")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public class IncrementalMultiplatformJvmCompilerRunnerTestGenerated extends AbstractIncrementalMultiplatformJvmCompilerRunnerTest {
public void testAllFilesPresentInMultiplatform() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("jps-plugin/testData/incremental/multiplatform"), Pattern.compile("^([^\\.]+)$"), TargetBackend.ANY, true);
}
@TestMetadata("touchActual")
public void testTouchActual() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("jps-plugin/testData/incremental/multiplatform/touchActual/");
doTest(fileName);
}
@TestMetadata("touchExpect")
public void testTouchExpect() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("jps-plugin/testData/incremental/multiplatform/touchExpect/");
doTest(fileName);
}
}

View File

@@ -127,10 +127,10 @@ object LightClassUtil {
return getPsiMethodWrappers(declaration).firstOrNull()
}
private fun getPsiMethodWrappers(declaration: KtDeclaration): Sequence<PsiMethod> {
return getWrappingClasses(declaration).flatMap { it.methods.asSequence() }
.filter { method -> method is KtLightMethod && method.kotlinOrigin === declaration }
}
private fun getPsiMethodWrappers(declaration: KtDeclaration): Sequence<KtLightMethod> =
getWrappingClasses(declaration).flatMap { it.methods.asSequence() }
.filterIsInstance<KtLightMethod>()
.filter { it.kotlinOrigin === declaration }
private fun getWrappingClass(declaration: KtDeclaration): PsiClass? {
var declaration = declaration
@@ -191,33 +191,19 @@ object LightClassUtil {
private fun extractPropertyAccessors(
ktDeclaration: KtDeclaration,
specialGetter: PsiMethod?, specialSetter: PsiMethod?): PropertyAccessorsPsiMethods {
var getterWrapper = specialGetter
var setterWrapper = specialSetter
val additionalAccessors = arrayListOf<PsiMethod>()
for (wrapper in getPsiMethodWrappers(ktDeclaration)) {
if (wrapper !is KtLightMethod) continue
if (wrapper.isSetter) {
if (setterWrapper == null || setterWrapper === specialSetter) {
setterWrapper = wrapper
}
else {
additionalAccessors.add(wrapper)
}
}
else {
if (getterWrapper == null || getterWrapper === specialGetter) {
getterWrapper = wrapper
}
else {
additionalAccessors.add(wrapper)
}
}
}
val (setters, getters) = getPsiMethodWrappers(ktDeclaration).partition { it.isSetter }
val allGetters = listOfNotNull(specialGetter) + getters.filterNot { it == specialGetter }
val allSetters = listOfNotNull(specialSetter) + setters.filterNot { it == specialSetter }
val backingField = getLightClassBackingField(ktDeclaration)
return PropertyAccessorsPsiMethods(getterWrapper, setterWrapper, backingField, additionalAccessors)
val additionalAccessors = allGetters.drop(1) + allSetters.drop(1)
return PropertyAccessorsPsiMethods(
allGetters.firstOrNull(),
allSetters.firstOrNull(),
backingField,
additionalAccessors
)
}
fun buildLightTypeParameterList(

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
* 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.
@@ -34,6 +34,7 @@ import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.debugText.getDebugText
import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
interface LightClassDataHolder {
val javaFileStub: PsiJavaFileStub
@@ -107,7 +108,10 @@ fun PsiJavaFileStub.findDelegate(classOrObject: KtClassOrObject): PsiClass {
}
val stubFileText = DebugUtil.stubTreeToString(this)
throw IllegalStateException("Couldn't get delegate for ${classOrObject.getDebugText()}\nin $ktFileText\nstub: \n$stubFileText")
throw KotlinExceptionWithAttachments("Couldn't get delegate for class")
.withAttachment(classOrObject.name ?: "unnamed class or object", classOrObject.getDebugText())
.withAttachment("file.kt", ktFileText)
.withAttachment("stub text", stubFileText)
}
fun PsiJavaFileStub.findDelegate(classFqName: FqName): PsiClass {

View File

@@ -339,7 +339,7 @@ abstract class KtLightClassForSourceDeclaration(protected val classOrObject: KtC
.create(createNoCache(classOrObject), OUT_OF_CODE_BLOCK_MODIFICATION_COUNT)
}
private fun createNoCache(classOrObject: KtClassOrObject): KtLightClassForSourceDeclaration? {
fun createNoCache(classOrObject: KtClassOrObject): KtLightClassForSourceDeclaration? {
if (classOrObject.hasExpectModifier()) {
return null
}

View File

@@ -1,199 +0,0 @@
/*
* Copyright 2010-2016 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.asJava.elements;
import com.intellij.lang.Language;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.asJava.builder.LightMemberOriginForDeclaration;
import org.jetbrains.kotlin.idea.KotlinLanguage;
import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.psi.psiUtil.KtPsiUtilKt;
import java.util.Collections;
import java.util.List;
public class KtLightParameter extends LightParameter implements KtLightDeclaration<KtParameter, PsiParameter> {
private static String getName(PsiParameter delegate, int index) {
String name = delegate.getName();
return name != null ? name : "p" + index;
}
private final PsiModifierList modifierList;
private final PsiParameter delegate;
private final int index;
private final KtLightMethod method;
private KtLightIdentifier lightIdentifier = null;
public KtLightParameter(PsiParameter delegate, int index, KtLightMethod method) {
super(getName(delegate, index), delegate.getType(), method, KotlinLanguage.INSTANCE);
this.delegate = delegate;
this.index = index;
this.method = method;
if (method.getLightMemberOrigin() instanceof LightMemberOriginForDeclaration) {
this.modifierList = new KtLightSimpleModifierList(this, Collections.emptySet());
}
else {
this.modifierList = super.getModifierList();
}
}
@NotNull
@Override
public PsiModifierList getModifierList() {
return modifierList;
}
@NotNull
@Override
public PsiParameter getClsDelegate() {
return delegate;
}
@Nullable
@Override
public KtParameter getKotlinOrigin() {
KtDeclaration declaration = method.getKotlinOrigin();
if (declaration == null) return null;
int jetIndex = KtPsiUtilKt.isExtensionDeclaration(declaration) ? index - 1 : index;
if (jetIndex < 0) return null;
if (declaration instanceof KtFunction) {
List<KtParameter> paramList = ((KtFunction) declaration).getValueParameters();
return jetIndex < paramList.size() ? paramList.get(jetIndex) : null;
}
if (jetIndex != 0) return null;
KtPropertyAccessor setter = null;
if (declaration instanceof KtPropertyAccessor) {
KtPropertyAccessor accessor = (KtPropertyAccessor) declaration;
setter = accessor.isSetter() ? accessor : null;
}
else if (declaration instanceof KtProperty) {
setter = ((KtProperty) declaration).getSetter();
}
else if (declaration instanceof KtParameter) {
return (KtParameter) declaration;
}
return setter != null ? setter.getParameter() : null;
}
@NotNull
@Override
public PsiElement getNavigationElement() {
KtParameter origin = getKotlinOrigin();
return origin != null ? origin : super.getNavigationElement();
}
@Override
public boolean isValid() {
return method.isValid();
}
@Override
public PsiElement setName(@NonNls @NotNull String name) throws IncorrectOperationException {
KtParameter origin = getKotlinOrigin();
if (origin != null) {
origin.setName(name);
}
return this;
}
@Override
public PsiFile getContainingFile() {
return method.getContainingFile();
}
@NotNull
@Override
public Language getLanguage() {
return KotlinLanguage.INSTANCE;
}
@NotNull
@Override
public SearchScope getUseScope() {
KtParameter origin = getKotlinOrigin();
return origin != null ? origin.getUseScope() : new LocalSearchScope(this);
}
public KtLightMethod getMethod() {
return method;
}
@Override
public String getText() {
KtParameter origin = getKotlinOrigin();
return origin != null ? origin.getText() : "";
}
@Override
public TextRange getTextRange() {
KtParameter origin = getKotlinOrigin();
return origin != null ? origin.getTextRange() : TextRange.EMPTY_RANGE;
}
@Override
public PsiIdentifier getNameIdentifier() {
if (lightIdentifier == null) {
lightIdentifier = new KtLightIdentifier(this, getKotlinOrigin());
}
return lightIdentifier;
}
@Override
public PsiElement getParent() {
return getMethod().getParameterList();
}
@Override
public boolean isEquivalentTo(PsiElement another) {
KtParameter kotlinOrigin = getKotlinOrigin();
if (another instanceof KtLightParameter && kotlinOrigin != null) {
KtLightParameter anotherParam = (KtLightParameter) another;
return kotlinOrigin.equals(anotherParam.getKotlinOrigin()) && getClsDelegate().equals(anotherParam.getClsDelegate());
}
return super.isEquivalentTo(another);
}
@Override
public boolean equals(Object obj) {
return obj instanceof PsiElement && isEquivalentTo((PsiElement) obj);
}
@Override
public int hashCode() {
KtParameter kotlinOrigin = getKotlinOrigin();
if (kotlinOrigin != null) {
return kotlinOrigin.hashCode();
}
else {
return 0;
}
}
}

View File

@@ -0,0 +1,132 @@
/*
* 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.asJava.elements
import com.intellij.lang.Language
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.Computable
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.SearchScope
import com.intellij.util.IncorrectOperationException
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.asJava.builder.LightMemberOriginForDeclaration
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPropertyAccessor
import org.jetbrains.kotlin.psi.psiUtil.isExtensionDeclaration
class KtLightParameter(
override val clsDelegate: PsiParameter,
private val index: Int,
val method: KtLightMethod
) : LightParameter(clsDelegate.name ?: "p$index", clsDelegate.type, method, KotlinLanguage.INSTANCE),
KtLightDeclaration<KtParameter, PsiParameter> {
private val modifierList: PsiModifierList
private var lightIdentifier: KtLightIdentifier? = null
override val kotlinOrigin: KtParameter?
get() {
val declaration = method.kotlinOrigin ?: return null
val jetIndex = if (declaration.isExtensionDeclaration()) index - 1 else index
if (jetIndex < 0) return null
if (declaration is KtFunction) {
val paramList = declaration.valueParameters
return if (jetIndex < paramList.size) paramList[jetIndex] else null
}
if (jetIndex != 0) return null
val setter = when (declaration) {
is KtPropertyAccessor -> if (declaration.isSetter) declaration else null
is KtProperty -> declaration.setter
is KtParameter -> return declaration
else -> return null
}
return setter?.parameter
}
init {
if (method.lightMemberOrigin is LightMemberOriginForDeclaration) {
this.modifierList = KtLightSimpleModifierList(this, emptySet())
}
else {
this.modifierList = super.getModifierList()
}
}
override fun getModifierList(): PsiModifierList = modifierList
override fun getNavigationElement(): PsiElement = kotlinOrigin ?: super.getNavigationElement()
override fun isValid(): Boolean = method.isValid
@Throws(IncorrectOperationException::class)
override fun setName(@NonNls name: String): PsiElement {
kotlinOrigin?.setName(name)
return this
}
override fun getContainingFile(): PsiFile = method.containingFile
override fun getLanguage(): Language = KotlinLanguage.INSTANCE
override fun getUseScope(): SearchScope {
return kotlinOrigin?.useScope ?: LocalSearchScope(this)
}
override fun getText(): String = kotlinOrigin?.text ?: ""
override fun getTextRange(): TextRange = kotlinOrigin?.textRange ?: TextRange.EMPTY_RANGE
override fun getNameIdentifier(): PsiIdentifier? {
if (lightIdentifier == null) {
lightIdentifier = KtLightIdentifier(this, kotlinOrigin)
}
return lightIdentifier
}
override fun getParent(): PsiElement = method.parameterList
override fun isEquivalentTo(another: PsiElement?): Boolean {
val result = ApplicationManager.getApplication().runReadAction(Computable {
val kotlinOrigin = kotlinOrigin
if (another is KtLightParameter && kotlinOrigin != null) {
kotlinOrigin == another.kotlinOrigin && clsDelegate == another.clsDelegate
}
else {
null
}
})
result?.let { return it }
return super.isEquivalentTo(another)
}
override fun equals(other: Any?): Boolean {
return other is PsiElement && isEquivalentTo(other)
}
override fun hashCode(): Int = kotlinOrigin?.hashCode() ?: 0
}

View File

@@ -53,6 +53,12 @@ abstract class KtLightAbstractAnnotation(parent: PsiElement, computeDelegate: ()
override fun getParameterList() = clsDelegate.parameterList
override fun canNavigate(): Boolean = super<KtLightElementBase>.canNavigate()
override fun canNavigateToSource(): Boolean = super<KtLightElementBase>.canNavigateToSource()
override fun navigate(requestFocus: Boolean) = super<KtLightElementBase>.navigate(requestFocus)
open fun fqNameMatches(fqName: String): Boolean = qualifiedName == fqName
}
@@ -194,15 +200,20 @@ class KtLightAnnotationForSourceEntry(
delegate.initializers.mapIndexed { i, memberValue ->
wrapAnnotationValue(memberValue, this, {
originalExpression.let { ktOrigin ->
when (ktOrigin) {
is KtValueArgumentList -> ktOrigin.arguments.getOrNull(i)?.getArgumentExpression()
is KtCallElement -> ktOrigin.valueArguments.getOrNull(i)?.getArgumentExpression()
is KtCollectionLiteralExpression -> ktOrigin.getInnerExpressions().getOrNull(i)
when {
ktOrigin is KtValueArgumentList -> ktOrigin.arguments.getOrNull(i)?.getArgumentExpression()
ktOrigin is KtCallElement -> ktOrigin.valueArguments.getOrNull(i)?.getArgumentExpression()
ktOrigin is KtCollectionLiteralExpression -> ktOrigin.getInnerExpressions().getOrNull(i)
delegate.initializers.size == 1 -> ktOrigin
else -> null
}.also {
if (it == null)
LOG.error("error wrapping ${memberValue.javaClass} for ${ktOrigin?.javaClass} in ${ktOrigin?.containingFile}",
Attachment("source_fragments.txt", "origin: '${psiReport(ktOrigin)}', delegate: ${psiReport(delegate)}"))
Attachment(
"source_fragments.txt",
"origin: '${psiReport(ktOrigin)}', delegate: ${psiReport(delegate)}, parent: ${psiReport(parent)}"
)
)
}
}
})
@@ -283,6 +294,12 @@ class KtLightNonExistentAnnotation(parent: KtLightElement<*, *>) : KtLightElemen
override fun findDeclaredAttributeValue(attributeName: String?) = null
override fun getMetaData() = null
override fun getParameterList() = KtLightEmptyAnnotationParameterList(this)
override fun canNavigate(): Boolean = super<KtLightElementBase>.canNavigate()
override fun canNavigateToSource(): Boolean = super<KtLightElementBase>.canNavigateToSource()
override fun navigate(requestFocus: Boolean) = super<KtLightElementBase>.navigate(requestFocus)
}
class KtLightEmptyAnnotationParameterList(parent: PsiElement) : KtLightElementBase(parent), PsiAnnotationParameterList {

View File

@@ -0,0 +1,56 @@
== Test ==
enum class Test(f: () -> Unit) {
A(getFunc())
}
---------------------
L0:
1 <START>
v(f: () -> Unit)
magic[FAKE_INITIALIZER](f: () -> Unit) -> <v0>
w(f|<v0>)
v(A(getFunc()))
magic[FAKE_INITIALIZER](A(getFunc())) -> <v1>
w(A|<v1>)
mark(getFunc())
call(getFunc(), getFunc) -> <v2>
mark((getFunc()))
call((getFunc()), <init>|<v2>) -> <v3>
L1:
<END> NEXT:[<SINK>]
error:
<ERROR> PREV:[]
sink:
<SINK> PREV:[<ERROR>, <END>]
=====================
== getFunc ==
fun getFunc(): () -> Unit = {}
---------------------
L0:
1 <START>
mark({})
jmp?(L2) NEXT:[r({}) -> <v0>, d({})]
d({}) NEXT:[<SINK>]
L2 [after local declaration]:
r({}) -> <v0> PREV:[jmp?(L2)]
ret(*|<v0>) L1
L1:
<END> NEXT:[<SINK>]
error:
<ERROR> PREV:[]
sink:
<SINK> PREV:[<ERROR>, <END>, d({})]
=====================
== anonymous_0 ==
{}
---------------------
L3:
2 <START>
3 mark()
read (Unit)
L4:
2 <END> NEXT:[<SINK>]
error:
<ERROR> PREV:[]
sink:
<SINK> PREV:[<ERROR>, <END>]
=====================

View File

@@ -0,0 +1,5 @@
enum class Test(f: () -> Unit) {
A(getFunc())
}
fun getFunc(): () -> Unit = {}

View File

@@ -0,0 +1,19 @@
== Test ==
enum class Test(f: () -> Unit) {
A(getFunc())
}
---------------------
<v0>: {<: () -> Unit} NEW: magic[FAKE_INITIALIZER](f: () -> Unit) -> <v0>
<v1>: {<: Test} NEW: magic[FAKE_INITIALIZER](A(getFunc())) -> <v1>
getFunc() <v2>: {<: () -> Unit} NEW: call(getFunc(), getFunc) -> <v2>
(getFunc()) <v3>: * NEW: call((getFunc()), <init>|<v2>) -> <v3>
=====================
== getFunc ==
fun getFunc(): () -> Unit = {}
---------------------
{} <v0>: {<: () -> Unit} NEW: r({}) -> <v0>
=====================
== anonymous_0 ==
{}
---------------------
=====================

View File

@@ -0,0 +1,4 @@
$TESTDATA_DIR$/invalidFilename.args
$TESTDATA_DIR$/simple.js
-output-dir
$TEMP_DIR$/min

View File

@@ -0,0 +1,2 @@
warning: invalid file name '$TESTDATA_DIR$/invalidFilename.args'; must end either with '.js', '.zip' or '.jar'
OK

View File

@@ -0,0 +1 @@
// EXISTS: min/simple.js

View File

@@ -0,0 +1,3 @@
public class A {
public void foo(@org.checkerframework.checker.nullness.compatqual.NonNullDecl String x) {}
}

View File

@@ -0,0 +1,5 @@
$TESTDATA_DIR$/compatqualUsage.kt
$TESTDATA_DIR$/compatqual
$FOREIGN_ANNOTATIONS_DIR$
-d
$TEMP_DIR$

View File

@@ -0,0 +1,4 @@
compiler/testData/cli/jvm/compatqualUsage.kt:2:11: error: null can not be a value of a non-null type String
a.foo(null)
^
COMPILATION_ERROR

View File

@@ -0,0 +1,6 @@
-Xsupport-compatqual-checker-framework-annotations=disable
$TESTDATA_DIR$/compatqualUsage.kt
$TESTDATA_DIR$/compatqual
$FOREIGN_ANNOTATIONS_DIR$
-d
$TEMP_DIR$

View File

@@ -0,0 +1 @@
OK

View File

@@ -0,0 +1,6 @@
-Xsupport-compatqual-checker-framework-annotations=enable
$TESTDATA_DIR$/compatqualUsage.kt
$TESTDATA_DIR$/compatqual
$FOREIGN_ANNOTATIONS_DIR$
-d
$TEMP_DIR$

View File

@@ -0,0 +1,4 @@
compiler/testData/cli/jvm/compatqualUsage.kt:2:11: error: null can not be a value of a non-null type String
a.foo(null)
^
COMPILATION_ERROR

View File

@@ -0,0 +1,3 @@
fun bar(a: A) {
a.foo(null)
}

View File

@@ -0,0 +1,6 @@
-Xsupport-compatqual-checker-framework-annotations=true
$TESTDATA_DIR$/compatqualUsage.kt
$TESTDATA_DIR$/compatqual
$FOREIGN_ANNOTATIONS_DIR$
-d
$TEMP_DIR$

View File

@@ -0,0 +1,2 @@
error: unrecognized -Xsupport-compatqual-checker-framework-annotations option: true. Possible values are 'enable'/'disable'
COMPILATION_ERROR

View File

@@ -35,6 +35,11 @@ where advanced options include:
-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
-Xsupport-compatqual-checker-framework-annotations=enable|disable
Specify behavior for Checker Framework compatqual annotations (NullableDecl/NonNullDecl).
Default value is 'enable'
-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

View File

@@ -0,0 +1,20 @@
// FULL_JDK
// WITH_REFLECT
// IGNORE_BACKEND: JS, NATIVE
annotation class Anno(val value: String)
interface Test {
fun foo(@Anno("OK") a: String) = "123"
}
fun box(): String {
val testMethod = Class.forName("Test\$DefaultImpls").declaredMethods.single()
//return (::test.parameters.single().annotations.single() as Simple).value
val receiverAnnotations = (testMethod.parameters[0]).annotations
if (receiverAnnotations.isNotEmpty()) return "fail: receiver parameter should not have any annotations, but: ${receiverAnnotations.joinToString()}"
val value2 = ((testMethod.parameters[1]).annotations.single() as Anno).value
return value2
}

View File

@@ -0,0 +1,17 @@
// NO_CHECK_LAMBDA_INLINING
// FILE: 1.kt
package test
inline fun test(p: String, s: () -> () -> String = { { p } }) =
s()
val same = test("O")
// FILE: 2.kt
import test.*
fun box(): String {
val inlined = test("K")
return same() + inlined()
}

View File

@@ -0,0 +1,17 @@
// NO_CHECK_LAMBDA_INLINING
// FILE: 1.kt
package test
inline fun test(p: String, s: () -> () -> () -> String = { { { p } } }) =
s()
val same = test("O")
// FILE: 2.kt
import test.*
fun box(): String {
val inlined = test("K")
return same()() + inlined()()
}

View File

@@ -0,0 +1,24 @@
// NO_CHECK_LAMBDA_INLINING
// FILE: 1.kt
package test
interface Call {
fun run(): String
}
inline fun test(p: String, s: () -> Call = {
object : Call {
override fun run() = p
} as Call
}) = s()
val same = test("O")
// FILE: 2.kt
import test.*
fun box(): String {
val inlined = test("K")
return same.run() + inlined.run()
}

View File

@@ -0,0 +1,18 @@
// NO_CHECK_LAMBDA_INLINING
// FILE: 1.kt
package test
inline fun test(s: () -> () -> String = { { "OK" } }) =
s()
val same = test()
// FILE: 2.kt
import test.*
fun box(): String {
val inlined = test()
if (same() != "OK") return "fail 1: ${same()}"
return inlined()
}

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