Compare commits

...

302 Commits

Author SHA1 Message Date
Pavel V. Talanov
6db79146b1 ~~ completion test 2017-11-07 19:08:09 +03:00
Pavel V. Talanov
03d6595ea4 DRAFT: Refactor/fix getModuleInfo resolverForModuleInfo stuff
~ draft
2017-11-07 19:08:06 +03:00
Pavel V. Talanov
ad20d82334 Drop JsProjectDetector
It leads to undesired behaviour
    such as returning library source when only binaries are queried
It is redundant since js libraries do not include kotlin source files
    (real binary format is used for this purpose for along time now)
2017-11-07 19:08:02 +03:00
Pavel V. Talanov
14f2ede057 Test completion in script files
Test for 'JavaResolutionUtils.getJavaDescriptorResolver' failing with AE
Part of  EA-105435
2017-11-07 19:07:58 +03:00
Ilya Gorbunov
a005f4804e Strengthen deprecation for CharSequence.size in JS 2017-11-07 18:59:33 +03:00
Ilya Gorbunov
9305903e6c Remove deprecated pairwise function
It was replaced with zipWithNext.
2017-11-07 18:59:33 +03:00
Nikolay Krasko
329322e268 Increase stub version because of change in overload sorting
See commit f197f36e23
2017-11-07 18:00:23 +03:00
Mikhail Glukhikh
6c2eb06351 Do not report "unused receiver" on companion objects
So #KT-19560 Fixed
2017-11-07 17:28:13 +03:00
Nikolay Krasko
84ab397f25 Restrict 172 plugin to 172 ide only 2017-11-07 13:30:00 +03:00
Nicolay Mitropolsky
fab8187574 UAST: Complex test data moved to separate file (KT-20990) 2017-11-06 19:59:50 +03:00
Nicolay Mitropolsky
9730d50e10 UAST: yet another fight with string literals in string literals (KT-20990) 2017-11-06 19:59:50 +03:00
Alexey Andreev
132285ea03 JS: optimize loop over array.withIndex()
See KT-20932
2017-11-03 17:36:05 +03:00
Alexey Andreev
1be86e05ae JS: optimize range check for int and long
See KT-2218

Additionally, fix temporary variable elimination for && and ||
2017-11-03 17:35:17 +03:00
Alexey Andreev
43302ce00c JS: add missing members to kotlin.js.Date
See KT-20694
2017-11-03 17:31:25 +03:00
Alexey Andreev
0a31b4ccc1 JS: improve declarations for JSON object
See KT-20580
2017-11-03 17:31:22 +03:00
Alexey Andreev
bd7129d0d6 JS: fix non-abstract extension properties in interfaces
KT-20994
2017-11-03 17:29:44 +03:00
Pavel V. Talanov
9e061d3bbb Fix light class exception on empty multifile facade
Fix generating multifile facade with all members private (in bytecode)
leading to delegate not being generated for corresponding light class

 #KT-20966 Fixed
2017-11-03 16:44:53 +03:00
Alexey Sedunov
b20ffe76b7 Navigation: Support "Navigate/Related Symbol" for expects/actuals
#KT-20952 Fixed
2017-11-03 16:34:36 +03:00
Alexey Sedunov
b2e5e9dab5 Highlighting: Support implicit 'it' references
#KT-21002 Fixed
2017-11-03 16:34:36 +03:00
Alexey Sedunov
d1eaf444a6 Line markers: Do not show package in "Choose actual for" popup
#KT-20953 Fixed
2017-11-03 16:34:35 +03:00
Alexey Sedunov
327caa086b Gradle: Do not rely on isQualifiedModuleNamesEnabled() to predict module name
IDEA 173 uses resolve-level setting to control naming of imported modules

 #KT-20985 Fixed
2017-11-03 16:34:35 +03:00
Alexander Udalov
3ead2e9cd4 Use KotlinCoreEnvironment.createForTests in test code
createForProduction creates and caches JavaCoreApplicationEnvironment
instance, which can alter behavior of subsequent tests
2017-11-03 14:03:02 +01:00
Alexander Udalov
dddd1cdba5 Use JUnit 3 + KtUsefulTestCase instead of JUnit 4 in compiler tests
This is needed because KtUsefulTestCase performs useful cleanup at the
end of the test (namely, resets ApplicationManager#ourApplication to
null)
2017-11-03 14:03:02 +01:00
Alexander Udalov
3049b5d92f Remove logging in KotlinSuppressCache.isSuppressedByAnnotated
It produces lots of useless output in stderr when tests are run with
Gradle in the terminal
2017-11-02 17:15:59 +01:00
Alexander Udalov
b43b470b8f Move Java 8 tests generator to tests-java8, run it in "Generate Compiler Tests" 2017-11-02 17:13:05 +01:00
Alexander Udalov
f52ba44e90 Move JS tests generator to :js:js.tests, run it in "Generate Compiler Tests"
Also cleanup generateTestDataForReservedWords and make everything there
private
2017-11-02 17:12:46 +01:00
Alexander Udalov
8c6ed3e872 Generate IR tests in GenerateCompilerTests.kt 2017-11-02 17:12:46 +01:00
Ilya Gorbunov
61b78d7eda Make projectTests type of dependency transitive on testRuntime dependencies
`tests-jar` configuration now extends testRuntime instead of testCompile
(note that testRuntime extends testCompile),
and projectTests() dependency shortcut makes it transitive.

This is required to depend on test utility modules producing `-tests` jar instead of default one
without listing all their transitive dependencies.
2017-11-02 18:19:52 +03:00
Ilya Gorbunov
3cfb1fd6a7 Simplify dependency setup for jvm6 codegen test server 2017-11-02 18:18:58 +03:00
Simon Ogorodnik
339d06d040 Improve diagnosticMissingPackageFragment reporting
Single execution path to report missing package fragment problems

Split failures on PluginDeclarationProviderFactory site by
known reasons to improve exception analysis
2017-11-02 16:31:43 +03:00
Alexander Udalov
56a51c1d22 Do not treat annotation classes as interfaces in bridges codegen
From Kotlin's point of view, everything in annotation classes is
non-abstract. A class inheriting from an annotation has a non-abstract
fake override for each property of the annotation class constructor. But
because members of annotation classes themselves were considered as
abstract in the bridge-generating code (see
DescriptorBasedFunctionHandle.isAbstract), there was a situation where a
concrete fake override has only one declaration among overridden
descriptors and it was abstract. This situation is invalid (a concrete
fake override must have exactly one concrete super-declaration),
therefore an exception was thrown.

The fix is to avoid considering annotation class members abstract for
the purposes of bridge generation. It's reasonably safe because no
bridges should be ever generated for annotation subclasses anyway,
because annotations can only have members with simple return types
(final and non-generic).

Note that in KT-19928, the problem is reproducible because of an
incorrect "inexact analysis" in light classes where "Target" is resolved
to an annotation class kotlin.annotation.Target. This behavior of the
analysis in light classes seems to do no harm otherwise, so it's not a
goal of this commit to change anything in that regard

 #KT-19928 Fixed
2017-11-02 14:02:09 +01:00
Mikhail Glukhikh
8f98f00030 Explicit / implicit this: analyzeFully --> analyze 2017-11-02 14:07:57 +03:00
Mikhail Glukhikh
6a7cdc01a6 Fix 'this' case in implicit this inspection 2017-11-02 14:07:55 +03:00
Mikhail Glukhikh
64a51fe0d1 Implicit this inspection: minor cleanup 2017-11-02 14:07:46 +03:00
Kirill
89c4196c06 Add inspections for implicit and explicit 'this' #KT-4580 Fixed 2017-11-02 14:07:45 +03:00
Ilmir Usmanov
817f79520a Implement coroutineContext intrinsic
This intrinsic allows coroutine to access its context without suspention
and, furthermore, disabling tail-call optimization.
KT-17609: Fixed
2017-11-02 12:45:24 +03:00
Toshiaki Kameyama
0fffb9fb17 Introduce inspection for callables with implicit 'Nothing?' type
Inspection is reported only for vars and open callables
So #KT-21023 Fixed
2017-11-02 12:21:14 +03:00
Mikhail Glukhikh
bcbeab00d5 Slightly change IntentionBasedInspection status
Only constructor and not the whole class is now deprecated
2017-11-02 12:21:13 +03:00
Toshiaki Kameyama
9ea9ea1008 Add quick fix to add required target to annotation #KT-20484 Fixed 2017-11-02 11:07:53 +03:00
Toshiaki Kameyama
204d9e3423 Introduce inspection detecting self-assignment of properties
So #KT-20714 Fixed
2017-11-02 11:07:52 +03:00
Vyacheslav Gerasimov
ffa9478d0c Configure Kotlin: add mavenCentral() to repositories
Since kotlin stdlib depends on artifacts from mavenCentral() we should add it
 #KT-18719 Fixed
2017-11-01 23:57:20 +03:00
Ilya Gorbunov
093f796fc7 Write compiler and stdlib versions from gradle build 2017-11-01 17:26:18 +03:00
Ilya Gorbunov
6fe299cd5b Fix core:builtins:serialize task outputs 2017-11-01 17:09:10 +03:00
Ilya Gorbunov
be63f09f8f Remove some workarounds for extra properties and signing,
use new syntax for maven repo definition.
2017-11-01 17:09:10 +03:00
Ilya Gorbunov
4d4285824b Use Gradle 4.3 2017-11-01 17:09:10 +03:00
Dmitry Savvinov
e17610f378 Don't throw on recursion when computing member scope
When recursion is detected while computing
`ClassResolutionScopesSupport.scopeForMemberDeclarationResolution`,
create 'ThrowingLexicalScope' (as with other scopes), instead of
throwing ISE immediately. That allows to report error properly in cases
like in KT-18514

#KT-18514 Fixed
2017-11-01 15:57:56 +03:00
Simon Ogorodnik
d6143e2af6 Fix testData broken after KT-12797 2017-10-31 21:11:19 +03:00
Simon Ogorodnik
0a4860b4d7 Add instrumentation to locate not cleared MockApplication 2017-10-31 20:25:00 +03:00
Mikhail Glukhikh
f6a7327758 Remove ultimate tests from "Generate All Tests" configuration 2017-10-31 18:21:53 +03:00
Mikhail Glukhikh
50ebcfe09e Test generator: return back forgotten convert line separators 2017-10-31 18:05:20 +03:00
Dmitry Petrov
c2b9803933 Generate source information for synthesized data class members
For now, bind such elements to data class declaration.

 #KT-20443 Fixed
2017-10-31 17:34:32 +03:00
Dmitry Jemerov
44260cdc7c Working recognition of JUnit annotation in MP tests
(cherry picked from commit 3a21781)
2017-10-31 14:45:09 +01:00
Alexander Udalov
2ed3e88561 Create descriptors with Kotlin package name in decompiler/cls stub builder
(cherry picked from commit b2620d1)
2017-10-31 14:44:52 +01:00
Dmitry Jemerov
f93f502ebe Read package name in KotlinClassHeader and use it in decompiler
(cherry picked from commit 119d5ab)
2017-10-31 14:44:39 +01:00
Mikhail Glukhikh
d59276671f Related to KT-20631: don't report redundant blank Unit in lambda 2017-10-31 16:38:55 +03:00
Toshiaki Kameyama
0fd4cdb086 Fix false positive for "redundant super" in data class #KT-20981 Fixed 2017-10-31 15:15:19 +03:00
Mikhail Glukhikh
63ad89eeb0 Minor cleanup 2017-10-31 15:03:55 +03:00
Toshiaki Kameyama
ef71f7707d Introduce inspection to detect use of Unit as a standalone expression
So #KT-20631 Fixed
2017-10-31 14:51:06 +03:00
Toshiaki Kameyama
5f4233e4bf Don't suggest "Remove explicit type specification" for an annotated type
So #KT-20622 Fixed
2017-10-31 14:37:36 +03:00
Alexander Udalov
fbda2a4343 Do not use MockLibraryUtil in AbstractTopLevelMembersInvocationTest
MockLibraryUtil runs the compiler in the new class loader, which is
useful for IDE tests to avoid loading KotlinCoreEnvironment, but is not
needed and is suboptimal for compiler tests.

Also use another method in AbstractForeignAnnotationsTest to assert that
there are no files in the compiled libraries
2017-10-31 07:36:46 +01:00
Alexander Udalov
a64fc10e94 Extract compiler-executing code in AbstractCliTest to CompilerTestUtil 2017-10-31 07:36:46 +01:00
Alexander Udalov
8695c6a1e4 Extract GenerateCompilerTests out of GenerateTests
Rename the run configuration "Generate Tests" -> "Generate All Tests"
2017-10-31 07:36:46 +01:00
Alexander Udalov
d0274c3c53 Extract 'test-generator' module out of 'generators'
Also avoid using intellij API where kotlin-stdlib can be used instead
2017-10-31 07:36:45 +01:00
Alexander Udalov
d79b571781 Rename ultimate's GenerateTests -> GenerateUltimateTests, regenerate 2017-10-31 07:36:45 +01:00
Alexander Udalov
8786c951a6 Move compiler/tests-common-jvm6/{src -> tests}, adjust dependencies 2017-10-31 07:36:45 +01:00
Alexander Udalov
33549362cb Move compiler/tests-common/{src -> tests}, adjust dependencies 2017-10-31 07:36:45 +01:00
Alexander Udalov
c2276e2ccb Rename module ':compiler.tests-common' -> ':compiler:tests-common' 2017-10-31 07:36:45 +01:00
Alexander Udalov
ef00807a18 Refactor test class name computation in GenerateTests
Allow to pass the FQ name of the base test class, instead of the Class
object (to avoid dependencies on other modules)
2017-10-31 07:36:45 +01:00
Dmitry Jemerov
c009f94eea Restore task dependency which is needed to run the plugin correctly 2017-10-31 02:48:18 +01:00
Alexander Udalov
959299eeab Use project.findProperty instead of project.property where nullable is fine
findProperty throws MissingPropertyException if there's no such property
2017-10-30 15:53:06 +01:00
Alexander Udalov
ccd7bfa337 Add project property to change port for codegen tests on different JDKs 2017-10-30 15:40:17 +01:00
Alexander Udalov
152bcda2c8 Regenerate gradle/project-schema.json 2017-10-30 15:39:53 +01:00
Alexander Udalov
dfd24d166c Update bootstrap to 1.2.0-dev-439 2017-10-30 15:38:38 +01:00
Simon Ogorodnik
213ce01152 Update testData for completion, broken after KT-13220 2017-10-30 17:31:15 +03:00
Ilya Gorbunov
f878fa69c1 Android codegen tests: fix android SDK path in local.properties
The path should have slashes instead of backslashes even on Windows.
2017-10-30 16:48:39 +03:00
Ilya Gorbunov
1af692c957 Code style settings format changed in IDEA 173 2017-10-30 16:46:24 +03:00
Dmitry Petrov
cbef372e69 Recapture shared variables when calling local class constructor
When a local function or class A creates an instance of a local class B
capturing an outer variable 'x', it should use ref for 'x', but not the
value of 'x'.
2017-10-30 15:19:13 +03:00
Dmitry Petrov
7a156e4407 Give unique names to fields for captured local functions
When a local function is captured, corresponding field accesses are
later transformed by the inliner. It doesn't have enough information to
restore the original semantics completely, so it has to rely on field
names. Local functions can be overloaded or can have names matching
local variable names, in both cases we generated fields with the same
name for captured values.

Now, we use the same '$<local-class-number>' suffix for field names for
local functions as it is present in the corresponding local class name.
This allows to distinguish captured local functions from captured local
variables and between different overloads of a function with the same
name.

 #KT-19827 Fixed
 #KT-18639 Fixed
2017-10-30 15:19:13 +03:00
Dmitry Petrov
da99a100cc Additional constructor call normalization tests 2017-10-30 15:19:13 +03:00
Mikhail Glukhikh
149daa173c Do not report "unused receiver" on operator and infix functions
So #KT-16340 Fixed
2017-10-30 15:07:39 +03:00
Alexander Udalov
54990e16c1 Report error if tools.jar is not found in javac-wrapper 2017-10-30 12:36:55 +01:00
Mikhail Glukhikh
561d7749b1 Choose implementing module correctly in "create actual fix"
Take implements / expectedBy dependency into account
So #KT-20803 Fixed
2017-10-30 14:13:10 +03:00
Mikhail Glukhikh
f0da58531e Enhance AbstractQuickFixMultiModuleTest
Handle same files at different source roots correctly
2017-10-30 14:12:27 +03:00
Mikhail Glukhikh
cfd432614f Cleanup: QuickFixMultiModuleTest 2017-10-30 14:12:25 +03:00
Mikhail Glukhikh
64dbe07fdb Cleanup: UnusedReceiverParameterInspection 2017-10-30 14:12:16 +03:00
Alexey Andreev
1f643ddce8 JS: add test to prove that KT-11910 is not reproducible anymore 2017-10-30 13:12:12 +03:00
Alexey Andreev
6b43465ed8 JS: add tests to check if super.equals/hashCode works properly
See KT-8226
2017-10-30 13:12:10 +03:00
Alexey Andreev
e9e01b70a8 JS: fix super access to simple non-overridable properties
See KT-7653
2017-10-30 13:12:09 +03:00
Alexey Andreev
e488cf13ad JS: fix FE crashing when type argument count less than parameter count
See KT-20908
2017-10-30 13:10:35 +03:00
Alexey Andreev
a6e98c30d7 JS: fix crash when js function contains assignment with bad LHS
Fix KT-20905
2017-10-30 13:08:35 +03:00
Nicolay Mitropolsky
a11cf253df UAST: correct processing of string literals in string literals (KT-20990) 2017-10-30 11:29:51 +03:00
Yoshinori Isogai
11f9c055fd KT-20591: Show annotations in parameter info (#1358)
Show annotations in parameter info

 #KT-20591 Fixed
2017-10-27 22:59:04 +03:00
Alexander Udalov
2c4e023cba Minor, use extracted variable in LateinitIntrinsics.kt 2017-10-27 18:06:43 +02:00
Nikolay Krasko
d75656d571 Additional tests for overloads with type aliases and suspend
Failed attempts to reproduce KT-20782, but still may be useful.
2017-10-27 15:09:52 +03:00
Nikolay Krasko
2d7fe98e55 Don't resort deserialized descriptors based on renderer, preserve proto order
Use only names and types for sorting. Otherwise if deserialized descriptor
is rendered different from origin we might get Psi-Stub mismatch error.

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

 #KT-20782 Fixed
 #EA-109887 Fixed
2017-10-27 15:09:04 +03:00
Nikolay Krasko
1408c4bd44 Fix testdata for ParcelQuickFixTestGenerated 2017-10-27 14:56:03 +03:00
Nikolay Krasko
3186c31ba7 Initialize delegate runner before access in filter method 2017-10-27 14:56:02 +03:00
Denis Zharkov
2df4d9496a Fix incorrect UNINITIALIZED_ENUM_COMPANION diagnostic
#KT-20959 Fixed
2017-10-27 09:36:00 +03:00
Sergey Ryabov
b3b08514c5 Use consistent explicit FileTreeWalk named parameters 2017-10-27 05:38:43 +03:00
Artem Zinnatullin
b565b00930 Fix Gradle plugin task name in readme. 2017-10-27 02:55:44 +03:00
Sergey Ryabov
d6504d82b7 Fix the doc for String.format and String.Companion.format 2017-10-27 02:53:09 +03:00
Ilya Zorin
5541634187 Explicitly set utf-8 encoding for JavaCompile tasks 2017-10-26 21:34:50 +03:00
Ilya Gorbunov
e8e09dbbf8 Various improvements in collection samples #KT-20357
Merge some related samples,
add sample for building a sequence from Enumeration similar to building a list from Enumeration.
2017-10-26 21:28:47 +03:00
Alexey Belkov
72354559e5 Provide samples for list, collection and array related functions #KT-20357 2017-10-26 21:28:47 +03:00
Alexey Sedunov
97332aaeea MPP: Support Mocha/Protractor run configuration for common modules
This is useful when they are implemented by JavaScript modules
2017-10-26 20:59:40 +03:00
Alexey Sedunov
3319fdba6d Gradle: Import test output path for JavaScript modules 2017-10-26 20:59:40 +03:00
Nikolay Krasko
ef274ad43b Don't build light classes when usages in Kotlin local scope requested 2017-10-26 17:58:07 +03:00
Nikolay Krasko
189e2506d1 Refactoring: extract isOnlyKotlinSearch function 2017-10-26 17:58:06 +03:00
Nikolay Krasko
55996fa43d Minor: extract scope initialization out of cycle 2017-10-26 17:58:05 +03:00
Dmitry Petrov
28535a57d8 Fix issues with enum entry self-reference
Given a singleton class 'S' with possibly uninitialized static instance
(enum entry, interface companion object).
Such singleton can be referenced by name, or as an explicit or implicit
'this'.
For a given singleton class 'S' we
either use 'this@S' from context (local or captured),
or 'S' as a static instance.

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

Otherwise, a static instance should be used.
2017-10-26 16:11:58 +03:00
Dmitry Jemerov
dd9f12d2e5 Removed dependencies on removed tasks 2017-10-26 14:23:56 +02:00
Dmitry Jemerov
a1949e1d53 Add formatting rule for array literals
#KT-19599 Fixed
2017-10-26 14:10:12 +02:00
Nikolay Krasko
6420f50f2e Fix accessing nullable location() method 2017-10-26 13:15:51 +03:00
Ilya Gorbunov
3fe2298855 Do not run android codegen tests with plugin, introduce a separate task 2017-10-25 21:37:24 +03:00
Ilya Gorbunov
6c5d78d8d5 Remove deprecated build tasks 2017-10-25 21:37:24 +03:00
Ilya Gorbunov
ace9d0da94 Finalize math function parameter names
#KT-4900
2017-10-25 21:30:03 +03:00
Alexey Andreev
bbcf4f7caf JS: raise metadata version due to incompatible changes in 1.2 runtime 2017-10-25 20:18:04 +03:00
Alexey Andreev
85945e0a6d JS: add getFunctionById intrinsic 2017-10-25 20:18:04 +03:00
Alexey Andreev
aae67e154a JS: add intrinsic for !!. Use it instead of ternary conditionals
See KT-2976
2017-10-25 20:18:03 +03:00
Simon Ogorodnik
8631e898a7 KT-12797: Fix completion to show inner classes from base class
#KT-12797 fixed
2017-10-25 18:07:37 +03:00
Simon Ogorodnik
5778ace6b0 KT-20166: Replace type name when caret is at the end of param name
When caret is at the end ('f<caret>: Foo'), tokenAt was COLON,
not IDENTIFIER

#KT-20166 fixed
2017-10-25 18:07:01 +03:00
Simon Ogorodnik
d12f5c79a1 KT-20506: Fix completion suggests the same value recursively
Check for excludeNonInitializedVariable via PSI, not by
descriptors equality, because of bindingContext caching

#KT-20506 fixed
2017-10-25 18:05:46 +03:00
Simon Ogorodnik
cf160b5a07 Cleaner way to insert whitespace in doc comment 2017-10-25 17:54:48 +03:00
Simon Ogorodnik
98310d3bdb KT-20884: Support receiver reference in KDoc comments
#KT-20884 fixed
2017-10-25 17:54:47 +03:00
Simon Ogorodnik
94e39a4c6c KT-20888: Do not report missing documentation when inherit from lib
Find KDoc using DescriptorToSourceUtilsIde when required

 #KT-20888 fixed
2017-10-25 17:54:46 +03:00
Simon Ogorodnik
fb876e398c Correctly detect visibility in KDocMissingDocumentationInspection
#KT-20887 fixed
 #KT-20889 fixed
2017-10-25 17:54:45 +03:00
Simon Ogorodnik
f21e1c60e0 KT-20883: Add more details to MissingDocumentationInspection message
#KT-20883 fixed
2017-10-25 17:54:43 +03:00
Simon Ogorodnik
d28e9fd22d KT-20880: Fix AddDocumentationFix to add multiline comment
#KT-20880 fixed
2017-10-25 17:54:42 +03:00
Denis Zharkov
be630f93dd Postpone full resolution for a candidate known to be failed
It's necessary for performance, because there are some resolution
parts that actually can be omitted and at the same time they aren't
very cheap (like inference or value arguments types checking)
2017-10-25 16:33:04 +03:00
Nikolay Krasko
6a43743c98 Configure new projects with kotlin-stdlib-jdk7/8 (KT-20286)
No migration for old projects has been added yet.

 #KT-20286 Fixed
2017-10-25 15:01:10 +03:00
Pavel V. Talanov
b7b3caedcc IDELightClassContexts: fix light member mismatch on InlineOnly members 2017-10-25 14:48:32 +03:00
Mikhael Bogdanov
54d1a85430 Disable 'apiVersionAtLeast1.kt' test on Android 2017-10-25 13:43:48 +02:00
Mikhael Bogdanov
33c0e16b83 Disable some test on Android 2017-10-25 12:26:41 +02:00
Alexander Udalov
e73760d4ff Fix test data for empty LHS vs isInitialized
Ignore the "property imported from object" part on JS
2017-10-25 12:10:10 +02:00
Dmitry Petrov
42945d33ee Use !LANGUAGE directive in tests for enhanced nullability 2017-10-25 12:30:32 +03:00
Dmitry Petrov
706a3698ec Add box tests for new nullability assertions 2017-10-25 12:30:32 +03:00
Dmitry Petrov
2a7d555be4 Minor: move nullability assertion tests javaInterop/notNullAssertions 2017-10-25 12:30:32 +03:00
Dmitry Petrov
57602c420d Sanitize declaration return types
On JVM, strip @EnhancedNullability annotation from inferred types for
functions, properties, and local variables, so that these annotations
do not "escape" from Kotlin declarations.
2017-10-25 12:30:32 +03:00
Dmitry Petrov
2b924f44d8 Generate assertions for expressions with enhanced nullability
If an expression with type annotated with @EnhancedNullability is used
as a function expression body, or property initializer, or variable
initializer, and corresponding type can not contain null,
generate nullability assertions for this expression.
2017-10-25 12:30:32 +03:00
Dmitry Petrov
6c47b4a39c Language feature for nullability assertions on enhanced nullability 2017-10-25 12:30:32 +03:00
Alexey Tsvetkov
313cd4f7bc Turn off IC for multiplatform projects by default
Multiplatform IC is enabled when a corresponding platform property is enabled
and 'kotlin.incremental.multiplatform' is set to `true`.

See KT-20840
2017-10-25 01:12:34 +03:00
Ilya Chernikov
caca7c67f4 Fix "base" jar and "public" jar tasks archive name conflict
fixes KT-20877
2017-10-24 20:28:54 +02:00
Ilya Gorbunov
b88d74d29b Remove annotation processor example from maven build
It is already built with gradle and used only in gradle tests
2017-10-24 20:35:53 +03:00
Ilya Gorbunov
f456fa9697 Adjust gradle jvmargs
Remove memory options for gradle daemon and instead give more memory to kotlin compile daemon.
2017-10-24 20:35:50 +03:00
Ilya Gorbunov
97cf09b45a Do not fail build on TC when some tests fail, just report problem
Required to have green builds with failing tests muted.
2017-10-24 20:35:47 +03:00
Ilya Gorbunov
84c0e8dfb4 Enable coroutines in kotlin-stdlib-common 2017-10-24 20:35:43 +03:00
Ilya Gorbunov
40574949c7 Postpone some task configuration to execution phase 2017-10-24 19:59:45 +03:00
Ilya Gorbunov
b1dcab886b Remove deprecated task 2017-10-24 19:59:45 +03:00
Ilya Gorbunov
25988957f7 Remove duplicated string-to-number conversion tests
Actual ones are in StringNumberConversionTest.kt
2017-10-24 19:59:45 +03:00
Vyacheslav Gerasimov
b27334d2a0 Remove GradleProjectImportProvider and GradleProjectOpenProcessor 2017-10-24 19:50:19 +03:00
Nicolay Mitropolsky
1fa5152cb7 UAST: Fix for unsafe cast for class initializer (EA-109918) 2017-10-24 19:39:38 +03:00
Alexander Udalov
1a8be635b9 Use ServiceLoader instead of IntelliJ extensions for DefaultErrorMessages
#KT-10473 Fixed
2017-10-24 18:25:38 +02:00
Alexander Udalov
1c6dce3674 Do not use DefaultErrorMessages.Extension as IntelliJ extension in plugins 2017-10-24 18:22:04 +02:00
Alexander Udalov
58631053c7 Fix project scope "IDE" after migration to Gradle build
See https://www.jetbrains.com/help/idea/scope-language-syntax-reference.html
2017-10-24 18:22:04 +02:00
Alexey Tsvetkov
e83f1b138b Perform non-IC build when JS lib is changed 2017-10-24 16:28:57 +03:00
Mikhael Bogdanov
be6474593d Additionally run android tests with enabled D8 2017-10-24 15:26:21 +02:00
Mikhael Bogdanov
dd24ba6978 Convert CodegenTestsOnAndroidRunner to Kotlin 2017-10-24 15:26:21 +02:00
Mikhael Bogdanov
37300f7486 Rename CodegenTestsOnAndroidRunner.java to CodegenTestsOnAndroidRunner.kt 2017-10-24 15:26:20 +02:00
Mikhael Bogdanov
6f5d459e09 Reorganize build logic in AndroidTestGenerator.kt 2017-10-24 15:26:20 +02:00
Mikhael Bogdanov
e151b8f641 Update Android tests 2017-10-24 15:26:19 +02:00
Dmitry Jemerov
499cfb5772 Show "No SDK configured" notification only in JVM modules 2017-10-24 14:52:12 +02:00
Alexey Sedunov
8a9e28afdc Kotlin Facet: Ensure that API version <= language version after import
#KT-20603 Fixed
2017-10-24 15:43:52 +03:00
Alexey Sedunov
840825704a Misc: Skip duplicates in navigation tests 2017-10-24 15:43:52 +03:00
Alexey Sedunov
4cc1e22a5a Misc: Support light-methodless members in overrider search
In particular, support line markers for expect-class members
and navigation to expect-class members from corresponding base members
2017-10-24 15:43:51 +03:00
Alexey Sedunov
17abce2811 Misc: Support light-classless classes in inheritors search
In particular, support line markers for expect-classes
and navigation to expect-classes from their base class

 #KT-20329 Fixed
2017-10-24 15:43:51 +03:00
Alexey Sedunov
87f3d24f9b Misc: Protect freeArgs with FreezableVar 2017-10-24 15:43:51 +03:00
Alexey Sedunov
fa4e4cbb42 Formatter: Insert new line before/after type alias
#KT-20766 Fixed
2017-10-24 15:43:51 +03:00
Dmitry Petrov
f23dfdc0ac Mark operands of POP2 as don't touch in unused expression elimination
Fixes KT-20879.
2017-10-24 15:38:15 +03:00
Dmitry Jemerov
537600b3b3 Add dependency to kotlin-test-annotations-common to new MP projects
#KT-20833 Fixed
2017-10-24 14:18:34 +02:00
shiraji
d51fa6d87e Add description for MoveMemberToTopLevelIntention 2017-10-24 14:33:55 +03:00
Alexander Udalov
bafc75ade4 Fix isInitialized receiver generation for empty LHS
#KT-20774 Fixed
2017-10-24 11:26:01 +02:00
Mikhail Zarechenskiy
73b3efd628 Remove LANGUAGE_VERSION directive from blackBox codegen tests 2017-10-24 11:44:02 +03:00
Mikhail Zarechenskiy
7a934d74e5 Support !LANGUAGE directive in codegen tests
LANGUAGE_VERSION directive will be removed later, for now it's left for simplicity
2017-10-24 11:44:02 +03:00
Mikhail Glukhikh
1ed8aa1cc5 Drop CheckPartialBodyResolveAction 2017-10-24 10:06:09 +03:00
Mikhail Glukhikh
5a6f22cc95 Make editor in SelfTargetingIntention.invoke nullable
This prevents EA-105844 from happening.
Should fix KT-20899.
2017-10-24 10:05:10 +03:00
Dmitry Petrov
68870a16bb Remove CLI help on 'preserve-class-initialization' mode
See https://youtrack.jetbrains.com/issue/KT-19532#comment=27-2492178
2017-10-24 09:36:56 +03:00
Ilya Gorbunov
75c8b787c2 Fix maven tests
- Add required extra dependencies to install to local repo before test.
- Remove expected warning about runtime bundled into compiler because it is no more.
- Fix basedir reference in kapt-allopen test.
- Fix reflection tests after deprecated members removal.
2017-10-23 21:23:36 +03:00
Ilya Gorbunov
25feb23cfa Update maven-invoker-plugin to deal with missing mvn.bat in maven 3.3 2017-10-23 21:23:13 +03:00
Alexander Udalov
f2be34ca1c Support KClass<*> annotation arguments in serialization/deserialization
#KT-11586 Fixed
2017-10-23 19:16:44 +02:00
Mikhail Glukhikh
d0e8f99d60 ResolveElementCache: script can now be analyzable parent
So #KT-20096 Fixed
2017-10-23 19:19:04 +03:00
Simon Ogorodnik
cace6624e6 EA-105522, KT-20256: Fix TextRange.<init> "Invalid range specified"
Check when caret inside template, and don't try to create invalid
range then

 EA-105522 fixed
 #KT-20256 fixed
2017-10-23 17:32:39 +03:00
shiraji
31a1fb916a Implement an intention action to move a companion object member to top level
#KT-18828 Fixed

(cherry picked from commit 11f8f8b)
2017-10-23 17:29:28 +03:00
shiraji
7044e46756 Refactor common move member methods
(cherry picked from commit 2dd8148)
2017-10-23 17:29:27 +03:00
Alexey Andreev
6adb62f3a2 JS: prohibit declaration names that clash with JS builtin functions
See KT-18095, KT-17475, KT-18105, KT-5259
2017-10-23 17:19:52 +03:00
Alexey Andreev
e0eea15a4c Fix JS tests failing on Windows 2017-10-23 17:19:51 +03:00
Alexey Andreev
e1f8bac4d5 JS: several bugfixes in incremental compilation
1. Fix exported packages sometimes being mixed up
2. Fix metadata losing package fragments sometimes
3. Don't serialize empty packages to .meta.js
4. Preserve order of package fragments in .meta.js
5. In IC tests, compare textual representation of metadata rather
   than binary representation
2017-10-23 17:19:51 +03:00
Alexey Andreev
2fbecfdd9c Support generation of relative path in JS source maps in JPS builder
See KT-20820
2017-10-23 17:19:50 +03:00
Alexey Andreev
cb0482f53e JS: fix crash when js function contains for statement w/o initializer
Fix KT-20898
2017-10-23 17:19:49 +03:00
Alexey Andreev
d9d565d8b0 JS: use 'external' word instead of 'native' in diagnostic messages
See KT-20639
2017-10-23 17:19:48 +03:00
Nicolay Mitropolsky
8a34c48d56 AbstractUastTest: findUElementByTextFromPsi refactored for readability 2017-10-23 16:44:43 +03:00
Nicolay Mitropolsky
8e17bab56f UastKotlinPsiVariable: factory methods reformatting 2017-10-23 16:44:43 +03:00
Dmitry Jemerov
81615fa551 Correctly propagate dependencies in multiplatform projects with Android 2017-10-23 14:59:56 +02:00
Dmitry Jemerov
cc85ac44b3 Rename KotlinPlatformGradleDetector to KotlinGradleModelFacade 2017-10-23 14:59:56 +02:00
Dmitry Jemerov
f589c9baf0 Ignore "module per source set" option in Android projects 2017-10-23 14:59:56 +02:00
Dmitry Jemerov
14a30e09c6 Use binary path instead of name to locate libraries from Android deps 2017-10-23 14:59:56 +02:00
Toshiaki Kameyama
e76d8bc793 "Convert object literal to class" should create inner class if necessary #KT-20091 Fixed 2017-10-23 15:02:51 +03:00
Nicolay Mitropolsky
299a4b7f69 UAST: Fix for unsafe cast for annotation (EA-109738) 2017-10-23 10:57:00 +03:00
Nicolay Mitropolsky
c5fa7fb217 UAST: tests utils for bottom-top finding UElements moved to AbstractUastTest.kt 2017-10-23 10:57:00 +03:00
Zalim Bashorov
f9809d5a73 Minor: replace IGNORE_BACKEND with TARGET_BACKEND for the test what should be run only on JVM
The test was written to check the case for Platform Types which now exists only on JVM.
2017-10-20 21:02:10 +03:00
nickl
6a659f33b5 UastKotlinPsiVariable psiParent made lazy to eliminate recursion when building UAST parents 2017-10-20 19:46:49 +03:00
Anton Bannykh
b2e53644a5 JPS JS: fix friend path detection in projects imported from Gradle (KT-18963 fixed) 2017-10-20 19:16:14 +03:00
Mikhail Glukhikh
739b21f519 Introduce "add missing actual members" quick-fix #KT-18449 Fixed 2017-10-20 17:24:19 +03:00
Mikhail Glukhikh
1b0421d27b Fix search scope during inlining #KT-20251 Fixed
Do not use KotlinSourceFilterScope because build scripts are lost otherwise
2017-10-20 16:00:52 +03:00
Mikhail Glukhikh
26c1aec5df Related to DSGN-4505: change expect / actual icons to the new ones 2017-10-20 15:16:04 +03:00
Mikhail Glukhikh
4b8c04a3d6 Minor: fix typo 2017-10-20 15:16:03 +03:00
Toshiaki Kameyama
fa03632197 Convert lambda to reference: handle named arguments more precisely
For trailing lambda intention inserts parameter names for all arguments
if at least one argument used default value.
Otherwise it just keeps existing named arguments.

So #KT-20349 Fixed
2017-10-20 13:57:58 +03:00
Kirill Rakhman
4c4427c280 Replace return@forEach with continue in ConvertForEachToForLoopIntention
So #KT-17332 Fixed
2017-10-20 13:44:31 +03:00
Denis Zharkov
da52716bfd Fix wrong nullability enhancement for annotated java.lang.Object type
Effectively, this commit drops cached value for j.l.Object type
This cache was introduced when types were immutable, but they
became mutable after starting reading top-level TYPE_USE annotations,
that lead to changing shared JAVA_LANG_OBJECT_CLASSIFIER_TYPE instance

 #KT-20826 Fixed
2017-10-20 09:43:38 +03:00
Alexey Tsvetkov
3c9ef6d319 Compile kotlin-android-extensions-runtime for JDK 1.6 2017-10-20 00:02:46 +03:00
Sergey Igushkin
b921eb5cc9 Fix null returned from listFiles and not handled correctly.
(cherry picked from commit 8147ae8)
2017-10-19 23:30:15 +03:00
Anton Bannykh
e90c914802 JS: add kotlin-test testCompile dependency to JS module generated by multiplatform wizard (KT-20346, KT-20831, KT-20832 fixed) 2017-10-19 18:32:24 +03:00
Dmitry Savvinov
5b9b8778b5 Minor: rename 'mapToPlatformClasses' -> 'mapToPlatformIndependentClasses' 2017-10-19 18:21:56 +03:00
Dmitry Savvinov
58b815d842 Fix false USELESS_CAST in function with expression body
Note that current behaviour is made similar to the case with
properties initializers/accessors, which means that more complex
cases are not covered yet (see KT-20801) #KT-20802 fixed.
2017-10-19 18:21:56 +03:00
Dmitry Savvinov
a1778a7da8 Fix CAST_NEVER_SUCCEEDS when casting Nothing to some type 2017-10-19 18:21:56 +03:00
Nikolay Krasko
bd2fd1758f Use CompilerPathsEx.getOutputPaths for getting the full list of output dirs (KT-20789)
CompilerPathsEx.getOutputPaths isn't using OrderEnumerationHandler extension
so far and works badly when delegating runnners to gradle is enabled.

 #KT-20789 Fixed
2017-10-19 17:43:36 +03:00
Kartik Patodi
dc6c19d7ef Normalize files that are gotten from FileUtil.createTempDirectory
It's required to avoid getting different paths inside tools (compiler, ant etc) and in tests.
2017-10-19 16:12:13 +03:00
Ilya Chernikov
5284db8088 Add compiler proguard rule for keeping ProgressManager used in webdemo 2017-10-19 13:55:00 +02:00
Sergey Mashkov
fd12bd904b KT-20822 Maven: import multiplatform projects properly 2017-10-19 13:29:26 +03:00
Alexey Andreev
b781661279 JS: fix copying functions with default arguments across interfaces
Copy function to super interface first, then copy from interface
to class. Add interface set to JsClassModel for this purpose.

See KT-20625
2017-10-19 13:10:47 +03:00
Alexey Andreev
d4ea4983d8 JS: support integer overflow semantics for unary minus operator
See KT-19290
2017-10-19 12:59:09 +03:00
Dmitry Petrov
f25a5b5177 Use -Xnormalize-constructor-calls=enable for Kotlin/JVM compilation only 2017-10-19 11:17:56 +03:00
Simon Ogorodnik
7a991ddc25 KT-13220: Add completion for variable names
Using parameter name completion

#KT-13220 fixed
2017-10-18 19:11:13 +03:00
Alexey Sedunov
e65adeb029 Misc: Fix quickfix test data 2017-10-18 18:17:50 +03:00
Alexey Sedunov
b8fb002a8f Misc: Update keyword completion test data
It reflects top-level lateinit variables available since 1.2
2017-10-18 18:17:50 +03:00
Alexey Sedunov
d89a946c5a Misc: Update default language version in Maven import test 2017-10-18 18:17:50 +03:00
Alexey Sedunov
d6ee9c9068 Misc: Update member hierarchy test data to include new stdlib classes 2017-10-18 18:17:50 +03:00
Alexey Sedunov
83b10403d7 Misc: Drop test for implementing abstract members in expect-class
The "not implemented" error is not reported for such classes, so
quick fix is not available anymore (see KT-16099)
2017-10-18 18:17:50 +03:00
Alexey Sedunov
997aa12bcc Misc: Update configuration test data 2017-10-18 18:17:50 +03:00
Alexey Sedunov
2883a92b93 Create from Usage: Work around type renaming
This fixes test failure after changes in KotlinTypeFactory
2017-10-18 18:17:49 +03:00
Alexander Udalov
6820509f83 Regenerate gradle/project-schema.json 2017-10-18 12:48:16 +02:00
Alexander Udalov
6e410cb182 Make TypeConstructor.isFinal return false for enums
The reason is that before dc02b2e3ab and 8a0dcca957,
TypeConstructor.isFinal for some class descriptors
(DeserializedClassDescriptor, LazyJavaClassDescriptor,
MutableClassDescriptor) were implemented as `isFinalClass` (which is
`modality == FINAL && kind != ENUM_CLASS`), and all others as
`modality == FINAL` or simply true/false. This led to differences in
behavior depending on the exact instance of the class descriptor.
Now that TypeConstructor.isFinal is always `modality == FINAL`, some
tests (PseudoValueTestGenerated) fail because the finality of some type
constructors changed and these tests render final vs non-final type
constructors differently.

In this commit, TypeConstructor.isFinal is now made to behave safer,
i.e. considering enum class type constructor to be non-final (as was the
case earlier for some ClassDescriptor instances). Some diagnostics might
disappear (e.g. FINAL_UPPER_BOUND) but it doesn't look like a big deal
2017-10-18 12:45:45 +02:00
Alexander Udalov
825aff7ac6 Minor, do not produce trailing spaces in AbstractPseudoValueTest 2017-10-18 12:45:45 +02:00
Pavel V. Talanov
320c5f6f3a Try to approximate "build.gradle.kts" script dependencies on first access
This is a hacky solution to prevent whole file being highlighted as unresolved while we wait for gradle response
2017-10-17 18:49:48 +03:00
Pavel V. Talanov
1cdac78b32 ScriptDependenciesCache, refactor: use delegated properties 2017-10-17 18:49:40 +03:00
Alexey Tsvetkov
896dacc835 Fix android extensions maven dependencies
`kotlin-android-extensions-runtime` and `kotlin-android-extensions-compiler`
had `com.google.android:android` as a provided dependency, but
during transition to Kotlin Gradle build the dependency was declared
as `runtime` instead of `compileOnly`.
2017-10-17 18:35:28 +03:00
Ilya Gorbunov
eaa3b3ccf0 Enable publishing for kotlin-annotations-android 2017-10-17 17:32:22 +03:00
Stanislav Erokhin
0a2421d453 Disable annotation processor for javac by default in whole project 2017-10-17 17:25:25 +03:00
Sergey Igushkin
d453a2fc92 Use runtimeJar configuration instead of default for plugin markers. 2017-10-17 14:37:11 +03:00
Andrey Breslav
a0da37fd41 Fix the description file 2017-10-17 12:13:22 +02:00
Anton Bannykh
f92c4b7704 Fixed indentation 2017-10-17 13:04:35 +03:00
Anton Bannykh
6d6ce7cbab JS: publish to NPM sourcemaps and *.kjsm files 2017-10-17 13:04:35 +03:00
Nikolay Krasko
6804409fc5 Fix idea version to 2017.2.5 (172.4343.14) 2017-10-17 12:33:01 +03:00
Nikolay Krasko
0ce4873312 Extract variable for idea download 2017-10-17 12:33:01 +03:00
Nikolay Krasko
c4e3cc0705 Add read action for getting text
Fix "Read access is allowed... exception"
2017-10-17 12:33:01 +03:00
Nikolay Krasko
339b1a3895 Minor: cleanup 2017-10-17 12:33:01 +03:00
Nikolay Krasko
3fda173ced TypeDeclarationProvider should return null for irrelevant symbols
Otherwise other providers won't be checked.
2017-10-17 12:33:01 +03:00
Alexey Sedunov
9fe0681fb6 MPP: Fix implementing module search in Gradle runner 2017-10-16 23:55:28 +03:00
Alexey Sedunov
db34bae05b Gradle: Support 'expectedBy' configuration 2017-10-16 23:55:28 +03:00
Alexey Sedunov
a2a8335bab Gradle: Add dependencies for indirectly implemented modules
#KT-16926 Fixed
2017-10-16 23:55:28 +03:00
Sergey Igushkin
0a808528b7 Fix missing ReflectUtil, call the ctor through reflection manually. 2017-10-16 21:48:38 +02:00
Sergey Igushkin
e94e62be98 Add android-extensions-compiler content to kotlin-android-extensions 2017-10-16 21:48:36 +02:00
Ilya Chernikov
431d47a605 Fix dependencies rewriting and gradle integration tests after applying rewriting 2017-10-16 21:48:36 +02:00
Ilya Chernikov
050403d15b Use rewriteDeps task on the projects with runtime dependency on embeddable compiler...
which are using shaded dependencies
2017-10-16 21:48:35 +02:00
Ilya Chernikov
fb70227868 Move embeddable compiler shading logic to buildSrc, implement rewriteDeps task
the task takes a jar an a shading task (like the one that creates embeddable
compiler) and rewrites jar's dependencies to the shaded ones according the
the shade task.
2017-10-16 21:48:34 +02:00
Ilya Chernikov
5babf89245 Remove original jar artifact from archives when adding a new one by runtimeJar tasks 2017-10-16 21:48:33 +02:00
Yan Zhulanow
6fb1e269b4 Minor: Fix build, add missing Android library dependency JARs 2017-10-16 22:43:09 +03:00
Yan Zhulanow
43a1162b25 Evaluate: Fix for evaluating local variables captured by an inline function (KT-17514) 2017-10-16 21:25:44 +03:00
Yan Zhulanow
fed5bddde2 Android Extensions: Initial IC support (KT-14125) 2017-10-16 21:25:42 +03:00
Yan Zhulanow
1b5b9f1fbb Kapt: Support 'correctErrorTypes' in annotations (KT-19518) 2017-10-16 21:25:41 +03:00
Yan Zhulanow
91ed130286 Add additional diagnostic for EA-107110 2017-10-16 21:25:40 +03:00
Yan Zhulanow
58571dcf1d Fix KNPE in evaluator (EA-89384) 2017-10-16 21:25:39 +03:00
Yan Zhulanow
8c7f469030 Parcelable: Use @IgnoredOnParcel annotation instead of Transient cause it's inapplicable on properties (KT-20298) 2017-10-16 21:25:37 +03:00
Yan Zhulanow
cafd99660a Minor: Make class abstract to get rid of the warning in tests 2017-10-16 21:25:36 +03:00
Yan Zhulanow
27d3ed76a0 Android Extensions: Support non-latin identifiers (KT-20299) 2017-10-16 21:25:34 +03:00
Yan Zhulanow
eefad896a0 Kapt: Mark 'kapt.kotlin.generated' as a source root automatically in Android projects (KT-20269) 2017-10-16 21:25:33 +03:00
Yan Zhulanow
50ab054883 Kapt: Preserve kapt plugin options if there are also options from compiler plugins (KT-20257) 2017-10-16 21:25:32 +03:00
Yan Zhulanow
d89143e641 Kapt: Report info log messages as warnings
Otherwise the log messages are not visible until the "--info" options is provided in Gradle.
2017-10-16 21:25:31 +03:00
Yan Zhulanow
2034b1f075 Parcelable: Provide quick fixes for custom Parceler support 2017-10-16 21:25:29 +03:00
Yan Zhulanow
a63aca08f2 Parcelable: Support custom Parcelers in compiler plugin 2017-10-16 21:25:27 +03:00
Yan Zhulanow
7dbefc1613 Remove generic bound for Parceler 2017-10-16 21:25:25 +03:00
Yan Zhulanow
a4f06c9fa8 Kapt: Do not inline R.resType.resName constants in annotations (KT-18791) 2017-10-16 21:25:24 +03:00
Mikhail Glukhikh
eba2fdfe89 Fix inline test 2017-10-16 21:06:18 +03:00
Stanislav Erokhin
fde1ac5575 Add test for ExpectedTypeFromCast feature 2017-10-16 20:10:57 +03:00
Mikhail Glukhikh
3fb0354676 Minor: add / fix comments (related to KT-20752) 2017-10-16 20:00:47 +03:00
Alexey Andreev
46526db8f0 JS: fix behaviour of char-returning functions with multiple inheritance
See KT-19772
2017-10-16 18:56:33 +03:00
Ilya Gorbunov
13d6e96c2f Do not pack build.txt into jars, leave it only in artifact zip bundles 2017-10-16 18:48:09 +03:00
Ilya Gorbunov
3bea095618 Remove maven poms that are no longer submodules of the main project 2017-10-16 18:48:09 +03:00
Ilya Gorbunov
ef3b0e0ff0 Add kotlin-test parent project 2017-10-16 18:48:09 +03:00
Ilya Gorbunov
13086b4347 Exclude node_modules dir from kotlin-stdlib-js project
Minor: shorter IdeaModel configuration.
2017-10-16 18:48:09 +03:00
Ilya Gorbunov
65d9b0edb3 Migrate settings and run configurations from the former libraries subproject 2017-10-16 18:48:09 +03:00
Ilya Gorbunov
341edc3f86 Fork java compiler to ensure forkOptions are used 2017-10-16 18:48:09 +03:00
Ilya Gorbunov
93efc51843 Fix the obsolete form of -Xdump-declarations-to argument 2017-10-16 18:48:09 +03:00
Stanislav Erokhin
b9fa8d4d96 Support parenthesized left expression for ExpectedTypeFromCast 2017-10-16 18:28:57 +03:00
Pavel V. Talanov
539e655802 PluginDeclarationProviderFactory: improve diagnostic
Attempting to catch EA-103048
2017-10-16 18:18:36 +03:00
Mikhail Glukhikh
e73e4dcc6a Delay elvis-bound smart casts to version 1.3 2017-10-16 16:21:46 +03:00
Mikhail Glukhikh
a55c6f0c95 Don't register safe cast type info for unstable values
Important: to be removed in 1.3
So #KT-20752 Fixed
2017-10-16 16:21:45 +03:00
Denis Zharkov
8ae3dbdcfc Refine ClassDescriptor::isCommonFinalClass definition
Do not treat annotations as final classes as they are not final in Java

 #KT-20776 Fixed
2017-10-16 16:11:35 +03:00
Alexander Udalov
03baa51f82 Write isPreRelease into JvmBuildMetaInfo for non-stable language version 2017-10-16 15:09:37 +02:00
Alexander Udalov
8b0b334601 Extract shouldWritePreReleaseFlag(), use in JS as well as JVM
Fix the difference in behavior between JS and JVM
2017-10-16 15:09:36 +02:00
Alexander Udalov
0510c553c3 Mark class files as pre-release if language version > LATEST_STABLE
#KT-20547 Fixed
2017-10-16 15:09:36 +02:00
Alexander Udalov
3665255a2b Extract skipPreReleaseCheck out of DeserializationConfiguration.skipMetadataVersionCheck 2017-10-16 15:09:36 +02:00
Alexander Udalov
8a0dcca957 Do not consider 'expect' class type constructors final
Because even a final expected class can be actualized with an open
actual class and thus have subtypes in the platform code
2017-10-16 15:08:50 +02:00
Alexander Udalov
0a861fd4ed Minor, refine return type of AbstractClassTypeConstructor.getDeclarationDescriptor 2017-10-16 15:08:50 +02:00
Alexander Udalov
dc02b2e3ab Fix TypeConstructor.isFinal for synthetic class descriptors
As in LazyClassTypeConstructor.isFinal, check if the class modality is
Modality.FINAL
2017-10-16 15:08:50 +02:00
Alexander Udalov
2682837fd7 Support 'expect final' -> 'actual open' for callables
#KT-17944
2017-10-16 15:08:50 +02:00
Alexey Sedunov
ee9a6ca53e Introduce Type Parameter: Do not show duplicate dialog under write action
#KT-20335 Fixed
2017-10-16 16:04:39 +03:00
Alexey Sedunov
25b6dac7b5 Introduce Type Alias: Don't change non-nullable type to nullable alias
#KT-15840 Fixed
2017-10-16 16:04:39 +03:00
Alexey Sedunov
1c3a3cd651 Introduce Parameter: Forbid inside of default values 2017-10-16 16:04:39 +03:00
Alexey Sedunov
790b615fa1 Introduce Parameter: Fix parameter name validation
Respect existing parameter names and fix some exceptions

 #KT-19439 Fixed
 #KT-20402 Fixed
 #KT-20403 Fixed
2017-10-16 16:04:39 +03:00
Alexey Sedunov
bf3769f37e Introduce Parameter: Forbid inside of annotation entries
#KT-18594 Fixed
2017-10-16 16:04:38 +03:00
Alexey Sedunov
e2fd9a71df Rename: Search text occurrences by declaration FQ name
#KT-17949 Fixed
 #KT-15932 Fixed
2017-10-16 16:04:38 +03:00
Alexey Sedunov
e68f8d6d45 Kotlin Ultimate: Support Protractor run configurations for module directory 2017-10-16 16:04:38 +03:00
1261 changed files with 19112 additions and 6921 deletions

View File

@@ -81,12 +81,10 @@
<option name="TERNARY_OPERATION_SIGNS_ON_NEXT_LINE" value="true" />
<option name="FOR_STATEMENT_WRAP" value="5" />
<option name="ASSIGNMENT_WRAP" value="1" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
</codeStyleSettings>
<codeStyleSettings language="CoffeeScript">
<option name="ALIGN_MULTILINE_PARAMETERS_IN_CALLS" value="true" />
<option name="METHOD_PARAMETERS_WRAP" value="5" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
</codeStyleSettings>
<codeStyleSettings language="ECMA Script Level 4">
<option name="ELSE_ON_NEW_LINE" value="true" />
@@ -111,7 +109,6 @@
<option name="DOWHILE_BRACE_FORCE" value="1" />
<option name="WHILE_BRACE_FORCE" value="1" />
<option name="FOR_BRACE_FORCE" value="1" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
</codeStyleSettings>
<codeStyleSettings language="GSP">
<indentOptions>
@@ -145,7 +142,6 @@
<option name="WHILE_BRACE_FORCE" value="1" />
<option name="FOR_BRACE_FORCE" value="1" />
<option name="FIELD_ANNOTATION_WRAP" value="0" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
</codeStyleSettings>
<codeStyleSettings language="HTML">
<indentOptions>
@@ -192,7 +188,6 @@
<option name="WHILE_BRACE_FORCE" value="1" />
<option name="FOR_BRACE_FORCE" value="1" />
<option name="FIELD_ANNOTATION_WRAP" value="0" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
<indentOptions>
<option name="TAB_SIZE" value="8" />
</indentOptions>
@@ -217,7 +212,6 @@
<option name="DOWHILE_BRACE_FORCE" value="1" />
<option name="WHILE_BRACE_FORCE" value="1" />
<option name="FOR_BRACE_FORCE" value="1" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
</codeStyleSettings>
<codeStyleSettings language="Scala">
<option name="KEEP_BLANK_LINES_BEFORE_RBRACE" value="0" />
@@ -265,7 +259,6 @@
<option name="DOWHILE_BRACE_FORCE" value="1" />
<option name="WHILE_BRACE_FORCE" value="1" />
<option name="FOR_BRACE_FORCE" value="1" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
</codeStyleSettings>
<codeStyleSettings language="XML">
<indentOptions>
@@ -280,7 +273,6 @@
<option name="FINALLY_ON_NEW_LINE" value="true" />
<option name="ALIGN_MULTILINE_PARAMETERS_IN_CALLS" value="true" />
<option name="ALIGN_MULTILINE_BINARY_OPERATION" value="true" />
<option name="PARENT_SETTINGS_INSTALLED" value="true" />
</codeStyleSettings>
</code_scheme>
</component>

View File

@@ -1,10 +1,10 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Generate Tests" type="GradleRunConfiguration" factoryName="Gradle">
<configuration default="false" name="Generate All Tests" type="GradleRunConfiguration" factoryName="Gradle">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$/generators" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="scriptParameters" value="-x :ultimate:generateTests" />
<option name="taskDescriptions">
<list />
</option>

View File

@@ -0,0 +1,22 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Generate Compiler Tests" type="GradleRunConfiguration" factoryName="Gradle">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$/compiler" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value=":compiler:generateTests" />
<option value=":compiler:tests-java8:generateTests" />
<option value=":js:js.tests:generateTests" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<method />
</configuration>
</component>

View File

@@ -1,8 +1,8 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Regenerate standard library generated sources" type="GradleRunConfiguration" factoryName="Gradle">
<configuration default="false" name="Generate standard library sources" type="GradleRunConfiguration" factoryName="Gradle">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$/tools/kotlin-stdlib-gen" />
<option name="externalProjectPath" value="$PROJECT_DIR$/libraries/tools/kotlin-stdlib-gen" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">

View File

@@ -1,8 +1,8 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Binary compatibility tests, overwrite results" type="GradleRunConfiguration" factoryName="Gradle">
<configuration default="false" name="Test: public API binary compatibility validator, overwrite results" type="GradleRunConfiguration" factoryName="Gradle">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$/tools/binary-compatibility-validator" />
<option name="externalProjectPath" value="$PROJECT_DIR$/libraries/tools/binary-compatibility-validator" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value=" --tests * " />
<option name="taskDescriptions">
@@ -10,6 +10,7 @@
</option>
<option name="taskNames">
<list>
<option value=":kotlin-runtime:clean" />
<option value=":kotlin-stdlib:clean" />
<option value=":kotlin-reflect:clean" />
<option value=":tools:binary-compatibility-validator:cleanTest" />

2
.idea/scopes/IDE.xml generated
View File

@@ -1,3 +1,3 @@
<component name="DependencyValidationManager">
<scope name="IDE" pattern="file[idea]:src/*/||file[idea]:testData/*/||file[ide-common]:src/*/||file[idea-analysis]:src/*/||file[idea-android]:src/*/||file[idea-completion]:src/*/||file[idea-completion]:testData/*/||file[idea-core]:src/*/||file[idea-jps-common]:/*/||file[idea-live-templates]:/*/||file[idea-live-templates]:testData/*/||file[idea-repl]:/*/||src[idea-android-output-parser]:*..*" />
<scope name="IDE" pattern="file[idea_main]:*/||file[idea]:testData/*/||file[idea-formatter_main]:*/||file[ide-common_main]:*/||file[idea-android_main]:*/||file[idea-android-output-parser_main]:*/||file[idea]:idea-completion/testData/*/||file[idea-core_main]:*/||file[idea-gradle_main]:*/||file[idea-jps-common_main]:*/||file[idea-jvm_main]:*/||file[idea]:idea-live-templates/src/*/||file[idea]:idea-live-templates/testData/*/||file[idea-maven_main]:*/||file[idea-repl]:*/||file[idea-test-framework_main]:*/||file[kotlin-gradle-tooling_main]:*/" />
</component>

View File

@@ -73,7 +73,7 @@ on Windows.
- `install` - build and install all public artifacts into local maven repository
- `runIde` - build IDEA plugin and run IDEA with it
- `coreLibsTest` - build and run stdlib, reflect and kotlin-test tests
- `gradlePluginsTest` - build and run gradle plugin tests
- `gradlePluginTest` - build and run gradle plugin tests
- `compilerTest` - build and run all compiler tests
- `ideaPluginTest` - build and run all IDEA plugin tests

View File

@@ -75,14 +75,7 @@
</macrodef>
<target name="writeCompilerVersionToTemplateFile">
<mkdir dir="${version_substitute_dir}"/>
<substituteVersionInFile
target.file="${compiler.version.java}"
target.file.bk="${compiler.version.java.bk}"
target.file.versioned="${compiler.version.java.versioned}"
test.string="public static final String VERSION = &quot;@snapshot@&quot;;"
version="${compiler.version.number}"/>
<!-- empty, version is written in gradle build -->
</target>
<target name="writePluginVersionToTemplateFile">

View File

@@ -11,11 +11,14 @@ dependencies {
compileOnly(project(":js:js.serializer"))
compileOnly(project(":js:js.frontend"))
compileOnly(ideaSdkDeps("util"))
testCompileOnly(project(":compiler:cli-common"))
testCompile(projectTests(":compiler:tests-common"))
testCompile(commonDep("junit:junit"))
testCompile(project(":compiler.tests-common"))
testCompile(protobufFull())
testRuntime(projectDist(":kotlin-stdlib"))
testRuntime(projectDist(":kotlin-reflect"))
testCompile(projectDist(":kotlin-stdlib"))
testCompile(projectDist(":kotlin-reflect"))
testCompileOnly(ideaSdkDeps("openapi"))
testRuntime(projectDist(":kotlin-compiler"))
}
sourceSets {
@@ -31,4 +34,4 @@ testsJar()
projectTest()
publish()
publish()

View File

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

View File

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

View File

@@ -9,7 +9,7 @@ import org.jetbrains.kotlin.gradle.tasks.Kotlin2JsCompile
buildscript {
extra["defaultSnapshotVersion"] = "1.2-SNAPSHOT"
kotlinBootstrapFrom(BootstrapOption.TeamCity("1.2.0-dev-92", onlySuccessBootstrap = false))
kotlinBootstrapFrom(BootstrapOption.TeamCity("1.2.0-dev-439", onlySuccessBootstrap = false))
val repos = listOfNotNull(
bootstrapKotlinRepo,
@@ -23,7 +23,7 @@ buildscript {
repositories {
for (repo in repos) {
maven { setUrl(repo) }
maven(url = repo)
}
}
@@ -69,7 +69,7 @@ val scriptRuntimeCfg = configurations.create("scriptRuntime").extendsFrom(script
repositories {
for (repo in (rootProject.extra["repos"] as List<String>)) {
maven { setUrl(repo) }
maven(url = repo)
}
}
@@ -217,6 +217,7 @@ fun Task.listConfigurationContents(configName: String) {
val defaultJvmTarget = "1.8"
val defaultJavaHome = jdkPath(defaultJvmTarget!!)
val ignoreTestFailures by extra(project.findProperty("ignoreTestFailures")?.toString()?.toBoolean() ?: project.hasProperty("teamcity"))
allprojects {
@@ -236,14 +237,26 @@ allprojects {
}
configureJvmProject(javaHome!!, jvmTarget!!)
val commonCompilerArgs = listOf("-Xallow-kotlin-package")
tasks.withType<org.jetbrains.kotlin.gradle.dsl.KotlinCompile<*>> {
kotlinOptions {
languageVersion = kotlinLanguageVersion
apiVersion = kotlinLanguageVersion
freeCompilerArgs = listOf("-Xallow-kotlin-package", "-Xnormalize-constructor-calls=enable")
freeCompilerArgs = commonCompilerArgs
}
}
tasks.withType<org.jetbrains.kotlin.gradle.dsl.KotlinJvmCompile> {
kotlinOptions {
freeCompilerArgs = commonCompilerArgs + listOf("-Xnormalize-constructor-calls=enable")
}
}
tasks.withType(VerificationTask::class.java as Class<Task>) {
(this as VerificationTask).ignoreFailures = ignoreTestFailures
}
tasks.withType<Javadoc> {
enabled = false
}
@@ -289,11 +302,6 @@ task<Copy>("ideaPlugin") {
into("$ideaPluginDir/lib")
}
task("dist-plugin") {
dependsOn("ideaPlugin")
doFirst { logger.warn("'$name' task is deprecated, use '${dependsOn.last()}' instead") }
}
tasks {
"clean" {
doLast {
@@ -319,11 +327,6 @@ tasks {
}
}
"gradlePluginsTest" {
// deprecated
dependsOn("gradlePluginTest")
}
"gradlePluginIntegrationTest" {
dependsOn(":kotlin-gradle-plugin-integration-tests:check")
}
@@ -335,30 +338,15 @@ tasks {
":compiler:tests-java8:test")
}
"compiler-tests" {
dependsOn("jvmCompilerTest")
doFirst { logger.warn("'$name' task is deprecated, use '${dependsOn.last()}' instead") }
}
"jsCompilerTest" {
dependsOn(":js:js.tests:test")
}
"js-tests" {
dependsOn("jsCompilerTest")
doFirst { logger.warn("'$name' task is deprecated, use '${dependsOn.last()}' instead") }
}
"scriptingTest" {
dependsOn("dist")
dependsOn(":kotlin-script-util:test")
}
"scripting-tests" {
dependsOn("scriptingTest")
doFirst { logger.warn("'$name' task is deprecated, use '${dependsOn.last()}' instead") }
}
"compilerTest" {
dependsOn("jvmCompilerTest")
dependsOn("jsCompilerTest")
@@ -380,6 +368,9 @@ tasks {
dependsOn("examplesTest")
}
"androidCodegenTest" {
dependsOn(":compiler:android-tests:test")
}
"jps-tests" {
dependsOn("dist")
@@ -405,12 +396,11 @@ tasks {
"idea-plugin-additional-tests")
}
"android-tests" {
"android-ide-tests" {
dependsOn("dist")
dependsOn(":plugins:android-extensions-ide:test",
":idea:idea-android:test",
":kotlin-annotation-processing:test",
":compiler:android-tests:test")
":kotlin-annotation-processing:test")
}
"plugins-tests" {
@@ -422,20 +412,13 @@ tasks {
":kotlin-annotation-processing-gradle:test")
}
"other-tests" {
dependsOn("dist")
dependsOn(":kotlin-build-common:test",
":generators:test")
doFirst { logger.warn("'$name' task is deprecated") }
}
"ideaPluginTest" {
dependsOn(
"idea-plugin-tests",
"jps-tests",
"plugins-tests",
"android-tests",
"android-ide-tests",
":generators:test"
)
}
@@ -449,7 +432,7 @@ tasks {
"check" { dependsOn("test") }
}
the<IdeaModel>().apply {
configure<IdeaModel> {
module {
excludeDirs = files(
project.buildDir,
@@ -478,7 +461,10 @@ fun jdkPath(version: String): String = jdkPathIfFound(version)
fun Project.configureJvmProject(javaHome: String, javaVersion: String) {
tasks.withType<JavaCompile> {
options.isFork = true
options.forkOptions.javaHome = file(javaHome)
options.compilerArgs.add("-proc:none")
options.encoding = "UTF-8"
}
tasks.withType<KotlinCompile> {

View File

@@ -1,11 +1,12 @@
buildscript {
val buildSrcKotlinVersion: String by extra(findProperty("buildSrc.kotlin.version")?.toString() ?: embeddedKotlinVersion)
extra["buildSrcKotlinRepo"] = findProperty("buildSrc.kotlin.repo")
val buildSrcKotlinRepo: String? by extra(findProperty("buildSrc.kotlin.repo") as String?)
extra["versions.shadow"] = "2.0.1"
repositories {
extra["buildSrcKotlinRepo"]?.let {
maven { setUrl(it) }
buildSrcKotlinRepo?.let {
maven(url = it)
}
}
@@ -30,10 +31,11 @@ plugins {
repositories {
extra["buildSrcKotlinRepo"]?.let {
maven { setUrl(it) }
maven(url = it)
}
maven(url = "https://dl.bintray.com/kotlin/kotlin-dev") // for dex-method-list
// maven { setUrl("https://repo.gradle.org/gradle/libs-releases-local") }
jcenter()
}
dependencies {
@@ -42,6 +44,7 @@ dependencies {
// compile("net.rubygrapefruit:native-platform:0.14")
// TODO: adding the dep to the plugin breaks the build unexpectedly, resolve and uncomment
// compile("org.jetbrains.kotlin:kotlin-gradle-plugin:${rootProject.extra["bootstrap_kotlin_version"]}")
compile("com.github.jengelman.gradle.plugins:shadow:${property("versions.shadow")}")
}
samWithReceiver {

View File

@@ -62,3 +62,9 @@ var Project.jvmTarget: String?
var Project.javaHome: String?
get() = extra.takeIf { it.has("javaHome") }?.get("javaHome") as? String
set(v) { extra["javaHome"] = v }
fun Project.generator(fqName: String) = task<JavaExec> {
classpath = the<JavaPluginConvention>().sourceSets["test"].runtimeClasspath
main = fqName
workingDir = rootDir
}

View File

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

View File

@@ -66,7 +66,7 @@ fun Project.ideaUltimatePluginDeps(vararg artifactBaseNames: String, plugin: Str
fun Project.kotlinDep(artifactBaseName: String, version: String): String = "org.jetbrains.kotlin:kotlin-$artifactBaseName:$version"
fun DependencyHandler.projectDist(name: String): Dependency = project(name, configuration = "distJar").apply { isTransitive = false }
fun DependencyHandler.projectTests(name: String): Dependency = project(name, configuration = "tests-jar").apply { isTransitive = false }
fun DependencyHandler.projectTests(name: String): Dependency = project(name, configuration = "tests-jar")
fun DependencyHandler.projectRuntimeJar(name: String): Dependency = project(name, configuration = "runtimeJar")
fun DependencyHandler.projectArchives(name: String): Dependency = project(name, configuration = "archives")
fun DependencyHandler.projectClasses(name: String): Dependency = project(name, configuration = "classes-dirs")

View File

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

View File

@@ -4,7 +4,7 @@ import org.codehaus.groovy.runtime.InvokerHelper
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.maven.MavenDeployer
import org.gradle.api.artifacts.maven.MavenDeployment
import org.gradle.api.artifacts.maven.MavenResolver
import org.gradle.api.plugins.MavenRepositoryHandlerConvention
@@ -100,21 +100,16 @@ open class PublishedKotlinModule : Plugin<Project> {
var repository: MavenRemoteRepository by Delegates.notNull()
val signPom = rootProject.extra["signPom"] as groovy.lang.Closure<*>
repositories {
withConvention(MavenRepositoryHandlerConvention::class) {
mavenDeployer {
signPom.call(project, this as MavenDeployer)
withGroovyBuilder {
// TODO: Use with kotlin-dsl 0.12+ instead of signPom
// "beforeDeployment" {
// val signing = project.the<SigningExtension>()
// if (signing.isRequired)
// signing.signPom(this as MavenDeployment)
// }
"beforeDeployment" {
val signing = project.the<SigningExtension>()
if (signing.isRequired)
signing.signPom(delegate as MavenDeployment)
}
"repository"("url" to repoUrl)!!.also { repository = it as MavenRemoteRepository }.withGroovyBuilder {
if (username != null && password != null) {

View File

@@ -40,6 +40,16 @@ fun Project.projectTest(taskName: String = "test", body: Test.() -> Unit = {}):
}
}
doFirst {
val agent = tasks.findByPath(":test-instrumenter:jar")!!.outputs.files.singleFile
val args = project.findProperty("kotlin.test.instrumentation.args")?.let { "=$it" }.orEmpty()
jvmArgs("-javaagent:$agent$args")
}
dependsOn(":test-instrumenter:jar")
jvmArgs("-ea", "-XX:+HeapDumpOnOutOfMemoryError", "-Xmx1100m", "-XX:+UseCodeCacheFlushing", "-XX:ReservedCodeCacheSize=128m", "-Djna.nosys=true")
maxHeapSize = "1100m"
systemProperty("idea.is.unit.test", "true")
@@ -47,7 +57,6 @@ fun Project.projectTest(taskName: String = "test", body: Test.() -> Unit = {}):
environment("PROJECT_CLASSES_DIRS", the<JavaPluginConvention>().sourceSets.getByName("test").output.classesDirs.asPath)
environment("PROJECT_BUILD_DIR", buildDir)
systemProperty("jps.kotlin.home", rootProject.extra["distKotlinHomeDir"])
ignoreFailures = System.getenv("kotlin_build_ignore_test_failures")?.let { it == "yes" } ?: false
body()
}

View File

@@ -1,36 +0,0 @@
// Have to stay in the separate dir: attempt to move it to the source root dir lead to invalid import into IDEA
apply { plugin("kotlin") }
dependencies {
compile(project(":core"))
compile(project(":core::util.runtime"))
compile(project(":compiler:util"))
compile(project(":compiler:backend"))
compile(project(":compiler:frontend"))
compile(project(":compiler:frontend.java"))
compile(project(":compiler:util"))
compile(project(":compiler:cli-common"))
compile(project(":compiler:cli"))
compile(project(":compiler:light-classes"))
compile(project(":compiler:serialization"))
compile(project(":kotlin-preloader"))
compile(project(":compiler:daemon-common"))
compile(project(":kotlin-daemon-client"))
compile(project(":js:js.serializer"))
compile(project(":js:js.frontend"))
compile(project(":js:js.translator"))
compileOnly(project(":plugins:android-extensions-compiler"))
compile(project(":kotlin-test:kotlin-test-jvm"))
compile(project(":compiler:tests-common-jvm6"))
compile(commonDep("junit:junit"))
compile(ideaSdkCoreDeps("intellij-core"))
compile(ideaSdkDeps("openapi", "idea", "idea_rt"))
compile(preloadedDeps("dx", subdir = "android-5.0/lib"))
}
sourceSets {
"main" { java.srcDir("../compiler/tests-common") }
"test" {}
}

View File

@@ -6,18 +6,19 @@ jvmTarget = "1.6"
dependencies {
compile(project(":compiler:util"))
compile(project(":compiler:cli"))
compile(project(":compiler.tests-common"))
compile(project(":compiler:frontend"))
compile(project(":compiler:backend"))
compile(projectTests(":compiler:tests-common"))
compile(commonDep("junit:junit"))
compile(ideaSdkDeps("openapi"))
testCompile(project(":compiler:incremental-compilation-impl"))
testCompile(project(":core"))
testCompile(project(":compiler:frontend.java"))
testCompile(projectTests(":jps-plugin"))
testCompile(commonDep("junit:junit"))
testCompile(ideaSdkDeps("jps-model.jar", subdir = "jps"))
testCompile(ideaSdkDeps("groovy-all"))
testCompile(ideaSdkDeps("openapi", "idea"))
testCompile(ideaSdkDeps("idea", "idea_rt"))
testCompile(ideaSdkDeps("jps-build-test", subdir = "jps/test"))
testCompile(ideaSdkDeps("jps-builders"))
}

View File

@@ -1,175 +0,0 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.android.tests;
import com.intellij.util.PlatformUtils;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.android.tests.download.SDKDownloader;
import org.jetbrains.kotlin.android.tests.emulator.Emulator;
import org.jetbrains.kotlin.android.tests.gradle.GradleRunner;
import org.jetbrains.kotlin.android.tests.run.PermissionManager;
import org.junit.Assert;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CodegenTestsOnAndroidRunner {
private final PathManager pathManager;
public static TestSuite getTestSuite(PathManager pathManager) {
return new CodegenTestsOnAndroidRunner(pathManager).generateTestSuite();
}
private CodegenTestsOnAndroidRunner(PathManager pathManager) {
this.pathManager = pathManager;
}
private TestSuite generateTestSuite() {
TestSuite suite = new TestSuite("MySuite");
String resultOutput = runTests();
String reportFolder = pathManager.getTmpFolder() + "/build/outputs/androidTest-results/connected";
try {
List<TestCase> testCases = parseSingleReportInFolder(reportFolder);
for (TestCase aCase : testCases) {
suite.addTest(aCase);
}
Assert.assertNotEquals("There is no test results in report", 0, testCases.size());
}
catch (Exception e) {
throw new RuntimeException("Can't parse test results in " + reportFolder +"\n" + resultOutput);
}
return suite;
}
@Nullable
public String runTests() {
File rootForAndroidDependencies = new File(pathManager.getDependenciesRoot());
if (!rootForAndroidDependencies.exists()) {
rootForAndroidDependencies.mkdirs();
}
SDKDownloader downloader = new SDKDownloader(pathManager);
downloader.downloadAll();
downloader.unzipAll();
PermissionManager.setPermissions(pathManager);
Emulator emulator = new Emulator(pathManager, Emulator.ARM);
GradleRunner gradleRunner = new GradleRunner(pathManager);
gradleRunner.clean();
gradleRunner.build();
emulator.createEmulator();
String platformPrefixProperty = System.setProperty(PlatformUtils.PLATFORM_PREFIX_KEY, "Idea");
try {
emulator.startEmulator();
try {
emulator.waitEmulatorStart();
//runTestsViaAdb(emulator, gradleRunner);
return gradleRunner.connectedDebugAndroidTest();
}
catch (RuntimeException e) {
e.printStackTrace();
throw e;
}
finally {
emulator.stopEmulator();
}
}
catch (RuntimeException e) {
e.printStackTrace();
throw e;
}
finally {
if (platformPrefixProperty != null) {
System.setProperty(PlatformUtils.PLATFORM_PREFIX_KEY, platformPrefixProperty);
}
else {
System.clearProperty(PlatformUtils.PLATFORM_PREFIX_KEY);
}
emulator.finishEmulatorProcesses();
}
}
private String runTestsViaAdb(Emulator emulator, GradleRunner gradleRunner) {
gradleRunner.installDebugAndroidTest();
String result = emulator.runTestsViaAdb();
System.out.println(result);
gradleRunner.uninstallDebugAndroidTest();
return result;
}
private static List<TestCase> parseSingleReportInFolder(String reportFolder) throws
IOException,
SAXException,
ParserConfigurationException {
File folder = new File(reportFolder);
File[] files = folder.listFiles();
assert files != null;
assert files.length == 1;
File reportFile = files[0];
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(reportFile);
Element root = doc.getDocumentElement();
NodeList testCases = root.getElementsByTagName("testcase");
List<TestCase> result = new ArrayList(testCases.getLength());
for (int i = 0; i < testCases.getLength(); i++) {
Element item = (Element) testCases.item(i);
NodeList failure = item.getElementsByTagName("failure");
String name = item.getAttribute("name");
String clazz = item.getAttribute("classname");
if (failure.getLength() == 0) {
result.add(new TestCase(name) {
@Override
protected void runTest() throws Throwable {
}
});
}
else {
result.add(new TestCase(name) {
@Override
protected void runTest() throws Throwable {
Assert.fail(failure.item(0).getTextContent());
}
});
}
}
return result;
}
}

View File

@@ -0,0 +1,189 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.android.tests
import com.intellij.util.PlatformUtils
import junit.framework.TestCase
import junit.framework.TestSuite
import org.jetbrains.kotlin.android.tests.download.SDKDownloader
import org.jetbrains.kotlin.android.tests.emulator.Emulator
import org.jetbrains.kotlin.android.tests.gradle.GradleRunner
import org.jetbrains.kotlin.android.tests.run.PermissionManager
import org.junit.Assert
import org.w3c.dom.Element
import org.xml.sax.SAXException
import java.io.File
import java.io.IOException
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.parsers.ParserConfigurationException
class CodegenTestsOnAndroidRunner private constructor(private val pathManager: PathManager) {
private fun runTestsInEmulator(): TestSuite {
val rootSuite = TestSuite("Root")
downloadDependencies()
val emulator = Emulator(pathManager, Emulator.ARM)
emulator.createEmulator()
val gradleRunner = GradleRunner(pathManager)
//old dex
cleanAndBuildProject(gradleRunner)
try {
emulator.startEmulator()
try {
emulator.waitEmulatorStart()
runTestsOnEmulator(gradleRunner, TestSuite("Dex")).apply {
rootSuite.addTest(this)
}
enableD8(true)
runTestsOnEmulator(gradleRunner, TestSuite("D8")).apply {
(0 until this.countTestCases()).forEach {
val testCase = testAt(it) as TestCase
testCase.name += "_D8"
}
rootSuite.addTest(this)
}
}
catch (e: RuntimeException) {
e.printStackTrace()
throw e
}
finally {
emulator.stopEmulator()
}
}
catch (e: RuntimeException) {
e.printStackTrace()
throw e
}
finally {
emulator.finishEmulatorProcesses()
}
return rootSuite
}
private fun enableD8(enable: Boolean) {
val file = File(pathManager.androidTmpFolder, "gradle.properties")
val lines = file.readLines().map {
if (it.startsWith("android.enableD8=")) {
"android.enableD8=$enable"
}
else it
}
file.writeText(lines.joinToString("\n"))
}
private fun processReport(suite: TestSuite, resultOutput: String) {
val reportFolder = pathManager.tmpFolder + "/build/outputs/androidTest-results/connected"
try {
val testCases = parseSingleReportInFolder(reportFolder)
testCases.forEach { aCase -> suite.addTest(aCase) }
Assert.assertNotEquals("There is no test results in report", 0, testCases.size.toLong())
}
catch (e: Exception) {
throw RuntimeException("Can't parse test results in " + reportFolder + "\n" + resultOutput)
}
}
private fun runTestsOnEmulator(gradleRunner: GradleRunner, suite: TestSuite): TestSuite {
val platformPrefixProperty = System.setProperty(PlatformUtils.PLATFORM_PREFIX_KEY, "Idea")
try {
val resultOutput = gradleRunner.connectedDebugAndroidTest()
processReport(suite, resultOutput)
return suite
}
finally {
if (platformPrefixProperty != null) {
System.setProperty(PlatformUtils.PLATFORM_PREFIX_KEY, platformPrefixProperty)
}
else {
System.clearProperty(PlatformUtils.PLATFORM_PREFIX_KEY)
}
}
}
private fun downloadDependencies() {
val rootForAndroidDependencies = File(pathManager.dependenciesRoot)
if (!rootForAndroidDependencies.exists()) {
rootForAndroidDependencies.mkdirs()
}
val downloader = SDKDownloader(pathManager)
downloader.downloadAll()
downloader.unzipAll()
PermissionManager.setPermissions(pathManager)
}
companion object {
@JvmStatic
fun runTestsInEmulator(pathManager: PathManager): TestSuite {
return CodegenTestsOnAndroidRunner(pathManager).runTestsInEmulator()
}
private fun cleanAndBuildProject(gradleRunner: GradleRunner) {
gradleRunner.clean()
gradleRunner.build()
}
@Throws(IOException::class, SAXException::class, ParserConfigurationException::class)
private fun parseSingleReportInFolder(reportFolder: String): List<TestCase> {
val folder = File(reportFolder)
val files = folder.listFiles()!!
assert(files.size == 1)
val reportFile = files[0]
val dbFactory = DocumentBuilderFactory.newInstance()
val dBuilder = dbFactory.newDocumentBuilder()
val doc = dBuilder.parse(reportFile)
val root = doc.documentElement
val testCases = root.getElementsByTagName("testcase")
return (0 until testCases.length).map { i ->
val item = testCases.item(i) as Element
val failure = item.getElementsByTagName("failure")
val name = item.getAttribute("name")
val clazz = item.getAttribute("classname")
if (failure.length == 0) {
object : TestCase(name) {
@Throws(Throwable::class)
override fun runTest() {
}
}
}
else {
object : TestCase(name) {
@Throws(Throwable::class)
override fun runTest() {
Assert.fail(failure.item(0).textContent)
}
}
}
}
}
}
}

View File

@@ -68,6 +68,10 @@ public class PathManager {
return tmpFolder + "/src";
}
public String getAndroidTmpFolder() {
return tmpFolder;
}
public String getAndroidSdkRoot() {
return getDependenciesRoot() + "/android-sdk";
}

View File

@@ -17,10 +17,12 @@
package org.jetbrains.kotlin.android.tests;
import org.jetbrains.kotlin.jps.build.BaseKotlinJpsBuildTestCase;
import org.junit.Ignore;
import java.io.File;
import java.io.IOException;
@Ignore
public class AndroidJpsBuildTestCase extends BaseKotlinJpsBuildTestCase {
private static final String PROJECT_NAME = "android-module";
private static final String SDK_NAME = "Android_SDK";

View File

@@ -19,13 +19,17 @@ package org.jetbrains.kotlin.android.tests;
import com.google.common.io.Files;
import com.intellij.openapi.util.io.FileUtil;
import junit.framework.TestSuite;
import kotlin.io.FilesKt;
import org.jetbrains.annotations.NotNull;
import org.junit.runner.RunWith;
import org.junit.runners.AllTests;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class AndroidRunner extends TestSuite {
@RunWith(AllTests.class)
public class AndroidRunner {
private static PathManager pathManager;
@@ -49,7 +53,7 @@ public class AndroidRunner extends TestSuite {
CodegenTestsOnAndroidGenerator.generate(pathManager);
System.out.println("Run tests on android...");
TestSuite suite = CodegenTestsOnAndroidRunner.getTestSuite(pathManager);
TestSuite suite = CodegenTestsOnAndroidRunner.runTestsInEmulator(pathManager);
//AndroidJpsBuildTestCase indirectly depends on UsefulTestCase which compiled against java 8
//TODO: Need add separate run configuration for AndroidJpsBuildTestCase
//suite.addTest(new AndroidJpsBuildTestCase());
@@ -62,10 +66,11 @@ public class AndroidRunner extends TestSuite {
}
private static void writeAndroidSkdToLocalProperties() throws IOException {
System.out.println("Writing android sdk to local.properties: " + pathManager.getAndroidSdkRoot());
String sdkRoot = FilesKt.getInvariantSeparatorsPath(new File(pathManager.getAndroidSdkRoot()));
System.out.println("Writing android sdk to local.properties: " + sdkRoot);
File file = new File(pathManager.getTmpFolder() + "/local.properties");
try (FileWriter fw = new FileWriter(file)) {
fw.write("sdk.dir=" + pathManager.getAndroidSdkRoot());
fw.write("sdk.dir=" + sdkRoot);
}
}
}

View File

@@ -42,12 +42,14 @@ import org.jetbrains.kotlin.test.*;
import org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase;
import org.jetbrains.kotlin.utils.Printer;
import org.junit.Assert;
import org.junit.Ignore;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Ignore
public class CodegenTestsOnAndroidGenerator extends KtUsefulTestCase {
private final PathManager pathManager;

View File

@@ -123,6 +123,13 @@ public class SpecialFiles {
excludedFiles.add("closureOfInnerLocalClass.kt");
excludedFiles.add("closureWithSelfInstantiation.kt");
excludedFiles.add("quotedClassName.kt");
//wrong function resolution after package renaming
excludedFiles.add("apiVersionAtLeast1.kt");
//special flags
excludedFiles.add("inlineFunInConstructorCallWithEnabledNormalization.kt");
excludedFiles.add("kt9532_lv10.kt");
}
private SpecialFiles() {

View File

@@ -17,16 +17,19 @@
package org.jetbrains.kotlin.backend.common
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.PropertyGetterDescriptor
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.DescriptorEquivalenceForOverrides
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.descriptorUtil.module
val SUSPEND_COROUTINE_OR_RETURN_NAME = Name.identifier("suspendCoroutineOrReturn")
val COROUTINE_SUSPENDED_NAME = Name.identifier("COROUTINE_SUSPENDED")
val COROUTINES_INTRINSICS_PACKAGE_FQ_NAME = DescriptorUtils.COROUTINES_PACKAGE_FQ_NAME.child(Name.identifier("intrinsics"))
val COROUTINE_CONTEXT_FQ_NAME = COROUTINES_INTRINSICS_PACKAGE_FQ_NAME.child(Name.identifier("coroutineContext"))
fun FunctionDescriptor.isBuiltInSuspendCoroutineOrReturn(): Boolean {
if (name != SUSPEND_COROUTINE_OR_RETURN_NAME) return false
@@ -42,3 +45,7 @@ fun FunctionDescriptor.getBuiltInSuspendCoroutineOrReturn() =
module.getPackage(COROUTINES_INTRINSICS_PACKAGE_FQ_NAME).memberScope
.getContributedFunctions(SUSPEND_COROUTINE_OR_RETURN_NAME, NoLookupLocation.FROM_BACKEND)
.singleOrNull()
fun FunctionDescriptor.isBuiltInCoroutineContext() =
(this as? PropertyGetterDescriptor)?.correspondingProperty?.fqNameSafe == COROUTINE_CONTEXT_FQ_NAME

View File

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

View File

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

View File

@@ -51,6 +51,7 @@ import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
import org.jetbrains.kotlin.codegen.when.SwitchCodegen;
import org.jetbrains.kotlin.codegen.when.SwitchCodegenProvider;
import org.jetbrains.kotlin.config.ApiVersion;
import org.jetbrains.kotlin.config.LanguageFeature;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor;
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor;
@@ -307,7 +308,12 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
RuntimeAssertionInfo runtimeAssertionInfo = null;
if (selector instanceof KtExpression) {
runtimeAssertionInfo = bindingContext.get(JvmBindingContextSlices.RUNTIME_ASSERTION_INFO, (KtExpression) selector);
KtExpression expression = (KtExpression) selector;
runtimeAssertionInfo = bindingContext.get(JvmBindingContextSlices.RUNTIME_ASSERTION_INFO, expression);
if (runtimeAssertionInfo == null &&
state.getLanguageVersionSettings().supportsFeature(LanguageFeature.StrictJavaNullabilityAssertions)) {
runtimeAssertionInfo = bindingContext.get(JvmBindingContextSlices.BODY_RUNTIME_ASSERTION_INFO, expression);
}
}
if (BuiltinSpecialBridgesKt.isValueArgumentForCallToMethodWithTypeCheckBarrier(selector, bindingContext)) return stackValue;
@@ -1080,11 +1086,15 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
for (Map.Entry<DeclarationDescriptor, EnclosedValueDescriptor> entry : closure.getCaptureVariables().entrySet()) {
Type sharedVarType = typeMapper.getSharedVarType(entry.getKey());
DeclarationDescriptor declarationDescriptor = entry.getKey();
EnclosedValueDescriptor valueDescriptor = entry.getValue();
Type sharedVarType = typeMapper.getSharedVarType(declarationDescriptor);
boolean asSharedVar = sharedVarType != null;
if (sharedVarType == null) {
sharedVarType = typeMapper.mapType((VariableDescriptor) entry.getKey());
sharedVarType = typeMapper.mapType((VariableDescriptor) declarationDescriptor);
}
StackValue capturedVar = lookupOuterValue(entry.getValue());
StackValue capturedVar = lookupOuterValue(valueDescriptor, asSharedVar);
callGenerator.putCapturedValueOnStack(capturedVar, sharedVarType, paramIndex++);
}
@@ -1138,11 +1148,16 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
@NotNull
public StackValue lookupOuterValue(EnclosedValueDescriptor d) {
private StackValue lookupOuterValue(EnclosedValueDescriptor d, boolean asSharedVar) {
DeclarationDescriptor descriptor = d.getDescriptor();
for (LocalLookup.LocalLookupCase aCase : LocalLookup.LocalLookupCase.values()) {
if (aCase.isCase(descriptor)) {
return aCase.outerValue(d, this);
StackValue outerValue = aCase.outerValue(d, this);
if (asSharedVar && outerValue instanceof StackValue.FieldForSharedVar) {
StackValue.FieldForSharedVar fieldForSharedVar = (StackValue.FieldForSharedVar) outerValue;
return fieldForSharedVar.receiver;
}
return outerValue;
}
}
throw new IllegalStateException("Can't get outer value in " + this + " for " + d);
@@ -1221,7 +1236,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
@Nullable
private StackValue genCoroutineInstanceForSuspendLambda(@NotNull FunctionDescriptor suspendFunction) {
public StackValue genCoroutineInstanceForSuspendLambda(@NotNull FunctionDescriptor suspendFunction) {
if (!(suspendFunction instanceof AnonymousFunctionDescriptor)) return null;
ClassDescriptor suspendLambdaClassDescriptor = bindingContext.get(CodegenBinding.CLASS_FOR_CALLABLE, suspendFunction);
@@ -1717,12 +1732,22 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
private boolean shouldGenerateSingletonAsThisOrOuterFromContext(ClassDescriptor classDescriptor) {
return isPossiblyUninitializedSingleton(classDescriptor) &&
isInsideSingleton(classDescriptor) &&
isThisInitialized(classDescriptor);
}
if (!isPossiblyUninitializedSingleton(classDescriptor)) return false;
if (!isInsideSingleton(classDescriptor)) return false;
// We are inside a singleton class 'S' with possibly uninitialized static instance
// (enum entry, interface companion object).
// Such singleton can be referenced by name, or as an explicit or implicit 'this'.
// For a given singleton class 'S' we either use 'this@S' from context (local or captured),
// or 'S' as a static instance.
//
// Local or captured 'this@S' should be used if:
// - we are in the constructor for 'S',
// and corresponding instance is initialized by super or delegating constructor call;
// - we are in any other member of 'S' or any of its inner classes.
//
// Otherwise, a static instance should be used.
private boolean isThisInitialized(ClassDescriptor classDescriptor) {
CodegenContext context = this.context;
while (context != null) {
if (context instanceof ConstructorContext) {
@@ -1732,9 +1757,24 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
return constructorContext.isThisInitialized();
}
}
else if (context instanceof ClassContext) {
ClassDescriptor contextClass = ((ClassContext) context).getContextDescriptor();
if (isInInnerClassesChainFor(contextClass, classDescriptor)) {
return true;
}
}
context = context.getParentContext();
}
return true;
return false;
}
private static boolean isInInnerClassesChainFor(ClassDescriptor innerClass, ClassDescriptor outerClass) {
if (innerClass == outerClass) return true;
if (!innerClass.isInner()) return false;
DeclarationDescriptor containingDeclaration = innerClass.getContainingDeclaration();
if (!(containingDeclaration instanceof ClassDescriptor)) return false;
return isInInnerClassesChainFor((ClassDescriptor) containingDeclaration, outerClass);
}
@Nullable
@@ -2169,6 +2209,11 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
assert enclosingSuspendFunctionJvmView != null : "No JVM view function found for " + enclosingSuspendFunction;
return getContinuationParameterFromEnclosingSuspendFunctionDescriptor(enclosingSuspendFunctionJvmView);
}
@Nullable
public StackValue getContinuationParameterFromEnclosingSuspendFunctionDescriptor(@NotNull FunctionDescriptor enclosingSuspendFunctionJvmView) {
ValueParameterDescriptor continuationParameter =
enclosingSuspendFunctionJvmView.getValueParameters()
.get(enclosingSuspendFunctionJvmView.getValueParameters().size() - 1);
@@ -2784,7 +2829,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
@Nullable
private StackValue generateCallableReferenceReceiver(@NotNull ResolvedCall<?> resolvedCall) {
public StackValue generateCallableReferenceReceiver(@NotNull ResolvedCall<?> resolvedCall) {
CallableDescriptor descriptor = resolvedCall.getResultingDescriptor();
if (descriptor.getExtensionReceiverParameter() == null && descriptor.getDispatchReceiverParameter() == null) return null;

View File

@@ -77,7 +77,6 @@ import java.util.Set;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isNullableAny;
import static org.jetbrains.kotlin.codegen.AsmUtil.*;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isAnnotationOrJvmInterfaceWithoutDefaults;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isJvm8InterfaceWithDefaultsMember;
import static org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings.METHOD_FOR_FUNCTION;
import static org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.DECLARATION;
@@ -101,7 +100,7 @@ public class FunctionCodegen {
private final Function1<DeclarationDescriptor, Boolean> IS_PURE_INTERFACE_CHECKER = new Function1<DeclarationDescriptor, Boolean>() {
@Override
public Boolean invoke(DeclarationDescriptor descriptor) {
return JvmCodegenUtil.isAnnotationOrJvmInterfaceWithoutDefaults(descriptor, state);
return JvmCodegenUtil.isInterfaceWithoutDefaults(descriptor, state);
}
};
@@ -866,7 +865,7 @@ public class FunctionCodegen {
public void generateBridges(@NotNull FunctionDescriptor descriptor) {
if (descriptor instanceof ConstructorDescriptor) return;
if (owner.getContextKind() == OwnerKind.DEFAULT_IMPLS) return;
if (isAnnotationOrJvmInterfaceWithoutDefaults(descriptor.getContainingDeclaration(), state)) return;
if (IS_PURE_INTERFACE_CHECKER.invoke(descriptor.getContainingDeclaration())) return;
// equals(Any?), hashCode(), toString() never need bridges
if (isMethodOfAny(descriptor)) return;

View File

@@ -1338,7 +1338,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
private void generateTraitMethods() {
if (isAnnotationOrJvmInterfaceWithoutDefaults(descriptor, state)) return;
if (isInterfaceWithoutDefaults(descriptor, state)) return;
List<FunctionDescriptor> restrictedInheritance = new ArrayList<>();
for (Map.Entry<FunctionDescriptor, FunctionDescriptor> entry : CodegenUtil.getNonPrivateTraitMethods(descriptor).entrySet()) {

View File

@@ -42,7 +42,6 @@ import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils;
import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.resolve.inline.InlineUtil;
import org.jetbrains.kotlin.resolve.jvm.JvmConstantsKt;
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue;
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedCallableMemberDescriptor;
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor;
@@ -63,15 +62,12 @@ public class JvmCodegenUtil {
private JvmCodegenUtil() {
}
public static boolean isAnnotationOrJvmInterfaceWithoutDefaults(@NotNull DeclarationDescriptor descriptor, @NotNull GenerationState state) {
return isAnnotationOrJvmInterfaceWithoutDefaults(descriptor, state.isJvm8Target(), state.isJvm8TargetWithDefaults());
public static boolean isInterfaceWithoutDefaults(@NotNull DeclarationDescriptor descriptor, @NotNull GenerationState state) {
return isInterfaceWithoutDefaults(descriptor, state.isJvm8Target(), state.isJvm8TargetWithDefaults());
}
private static boolean isAnnotationOrJvmInterfaceWithoutDefaults(@NotNull DeclarationDescriptor descriptor, boolean isJvm8Target, boolean isJvm8TargetWithDefaults) {
if (!isJvmInterface(descriptor)) {
return false;
}
if (ANNOTATION_CLASS == ((ClassDescriptor) descriptor).getKind()) return true;
private static boolean isInterfaceWithoutDefaults(@NotNull DeclarationDescriptor descriptor, boolean isJvm8Target, boolean isJvm8TargetWithDefaults) {
if (!DescriptorUtils.isInterface(descriptor)) return false;
if (descriptor instanceof DeserializedClassDescriptor) {
SourceElement source = ((DeserializedClassDescriptor) descriptor).getSource();
@@ -91,7 +87,7 @@ public class JvmCodegenUtil {
}
public static boolean isJvm8InterfaceWithDefaults(@NotNull DeclarationDescriptor descriptor, boolean isJvm8Target, boolean isJvm8TargetWithDefaults) {
return DescriptorUtils.isInterface(descriptor) && !isAnnotationOrJvmInterfaceWithoutDefaults(descriptor, isJvm8Target, isJvm8TargetWithDefaults);
return DescriptorUtils.isInterface(descriptor) && !isInterfaceWithoutDefaults(descriptor, isJvm8Target, isJvm8TargetWithDefaults);
}
public static boolean isJvm8InterfaceWithDefaultsMember(@NotNull CallableMemberDescriptor descriptor, @NotNull GenerationState state) {

View File

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

View File

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

View File

@@ -106,14 +106,21 @@ public interface LocalLookup {
BindingContext bindingContext = state.getBindingContext();
Type localType = asmTypeForAnonymousClass(bindingContext, vd);
MutableClosure localFunClosure = bindingContext.get(CLOSURE, bindingContext.get(CLASS_FOR_CALLABLE, vd));
ClassDescriptor callableClass = bindingContext.get(CLASS_FOR_CALLABLE, vd);
assert callableClass != null : "No CLASS_FOR_CALLABLE:" + vd;
MutableClosure localFunClosure = bindingContext.get(CLOSURE, callableClass);
if (localFunClosure != null && JvmCodegenUtil.isConst(localFunClosure)) {
// This is an optimization: we can obtain an instance of a const closure simply by GETSTATIC ...$instance
// (instead of passing this instance to the constructor and storing as a field)
return StackValue.field(localType, localType, JvmAbi.INSTANCE_FIELD, true, StackValue.LOCAL_0, vd);
}
String fieldName = "$" + vd.getName();
String localFunClassName = callableClass.getName().asString();
int localClassIndexStart = localFunClassName.lastIndexOf('$');
String localFunSuffix = localClassIndexStart >= 0 ? localFunClassName.substring(localClassIndexStart) : "";
String fieldName = "$" + vd.getName() + localFunSuffix;
StackValue.StackValueWithSimpleReceiver innerValue = StackValue.field(localType, classType, fieldName, false,
StackValue.LOCAL_0, vd);

View File

@@ -17,9 +17,7 @@
package org.jetbrains.kotlin.codegen.coroutines
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.backend.common.COROUTINES_INTRINSICS_PACKAGE_FQ_NAME
import org.jetbrains.kotlin.backend.common.COROUTINE_SUSPENDED_NAME
import org.jetbrains.kotlin.backend.common.isBuiltInSuspendCoroutineOrReturn
import org.jetbrains.kotlin.backend.common.*
import org.jetbrains.kotlin.builtins.isBuiltinFunctionalType
import org.jetbrains.kotlin.codegen.StackValue
import org.jetbrains.kotlin.codegen.binding.CodegenBinding
@@ -66,6 +64,9 @@ val COROUTINES_JVM_INTERNAL_PACKAGE_FQ_NAME =
@JvmField
val CONTINUATION_ASM_TYPE = DescriptorUtils.CONTINUATION_INTERFACE_FQ_NAME.topLevelClassAsmType()
@JvmField
val COROUTINE_CONTEXT_ASM_TYPE = DescriptorUtils.COROUTINES_PACKAGE_FQ_NAME.child(Name.identifier("CoroutineContext")).topLevelClassAsmType()
@JvmField
val COROUTINE_IMPL_ASM_TYPE = COROUTINES_JVM_INTERNAL_PACKAGE_FQ_NAME.child(Name.identifier("CoroutineImpl")).topLevelClassAsmType()
@@ -76,6 +77,7 @@ private val INTERNAL_COROUTINE_INTRINSICS_OWNER_INTERNAL_NAME =
COROUTINES_JVM_INTERNAL_PACKAGE_FQ_NAME.child(Name.identifier("CoroutineIntrinsics")).topLevelClassInternalName()
private val NORMALIZE_CONTINUATION_METHOD_NAME = "normalizeContinuation"
private val GET_CONTEXT_METHOD_NAME = "getContext"
data class ResolvedCallWithRealDescriptor(val resolvedCall: ResolvedCall<*>, val fakeContinuationExpression: KtExpression)
@@ -287,6 +289,35 @@ fun createMethodNodeForSuspendCoroutineOrReturn(
return node
}
fun createMethodNodeForCoroutineContext(functionDescriptor: FunctionDescriptor): MethodNode {
assert(functionDescriptor.isBuiltInCoroutineContext()) {
"functionDescriptor must be kotlin.coroutines.intrinsics.coroutineContext property getter"
}
val node =
MethodNode(
Opcodes.ASM5,
Opcodes.ACC_STATIC,
"fake",
Type.getMethodDescriptor(COROUTINE_CONTEXT_ASM_TYPE, CONTINUATION_ASM_TYPE),
null, null
)
node.visitVarInsn(Opcodes.ALOAD, 0)
node.visitMethodInsn(
Opcodes.INVOKEINTERFACE,
CONTINUATION_ASM_TYPE.internalName,
GET_CONTEXT_METHOD_NAME,
Type.getMethodDescriptor(COROUTINE_CONTEXT_ASM_TYPE),
true
)
node.visitInsn(Opcodes.ARETURN)
node.visitMaxs(1, 1)
return node
}
@Suppress("UNCHECKED_CAST")
fun <D : CallableDescriptor?> D.unwrapInitialDescriptorForSuspendFunction(): D =
this.safeAs<SimpleFunctionDescriptor>()?.getUserData(INITIAL_DESCRIPTOR_FOR_SUSPEND_FUNCTION) as D ?: this

View File

@@ -18,12 +18,13 @@ package org.jetbrains.kotlin.codegen.inline
import com.intellij.psi.PsiElement
import com.intellij.util.ArrayUtil
import org.jetbrains.kotlin.backend.common.isBuiltInCoroutineContext
import org.jetbrains.kotlin.builtins.BuiltInsPackageFragment
import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.AsmUtil.getMethodAsmFlags
import org.jetbrains.kotlin.codegen.AsmUtil.isPrimitive
import org.jetbrains.kotlin.codegen.coroutines.createMethodNodeForSuspendCoroutineOrReturn
import org.jetbrains.kotlin.codegen.coroutines.isBuiltInSuspendCoroutineOrReturnInJvm
import org.jetbrains.kotlin.codegen.context.ClosureContext
import org.jetbrains.kotlin.codegen.coroutines.*
import org.jetbrains.kotlin.codegen.intrinsics.bytecode
import org.jetbrains.kotlin.codegen.intrinsics.classId
import org.jetbrains.kotlin.codegen.state.GenerationState
@@ -50,8 +51,6 @@ import org.jetbrains.kotlin.serialization.deserialization.descriptors.Deserializ
import org.jetbrains.kotlin.types.expressions.DoubleColonLHS
import org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils.isFunctionLiteral
import org.jetbrains.kotlin.types.expressions.LabelResolver
import org.jetbrains.kotlin.utils.DFS
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
@@ -225,6 +224,19 @@ abstract class InlineCodegen<out T: BaseExpressionCodegen>(
return true
}
private fun continuationValue(): StackValue {
assert(codegen is ExpressionCodegen) { "Expected ExpressionCodegen in coroutineContext inlining" }
codegen as ExpressionCodegen
val parentContext = codegen.context.parentContext
return if (parentContext is ClosureContext) {
val originalSuspendLambdaDescriptor = parentContext.originalSuspendLambdaDescriptor ?: error("No original lambda descriptor found")
codegen.genCoroutineInstanceForSuspendLambda(originalSuspendLambdaDescriptor) ?: error("No stack value for coroutine instance of lambda found")
}
else
codegen.getContinuationParameterFromEnclosingSuspendFunctionDescriptor(codegen.context.functionDescriptor) ?: error("No stack value for continuation parameter of suspend function")
}
protected fun inlineCall(nodeAndSmap: SMAPAndMethodNode, callDefault: Boolean): InlineResult {
assert(delayedHiddenWriting == null) { "'putHiddenParamsIntoLocals' should be called after 'processAndPutHiddenParameters(true)'" }
defaultSourceMapper.callSiteMarker = CallSiteMarker(codegen.lastLineNumber)
@@ -252,6 +264,9 @@ abstract class InlineCodegen<out T: BaseExpressionCodegen>(
addInlineMarker(codegen.v, true)
}
if (functionDescriptor.isBuiltInCoroutineContext())
invocationParamBuilder.addNextValueParameter(CONTINUATION_ASM_TYPE, false, continuationValue(), 0)
val parameters = invocationParamBuilder.buildParameters()
val info = RootInliningContext(
@@ -458,24 +473,28 @@ abstract class InlineCodegen<out T: BaseExpressionCodegen>(
state: GenerationState,
sourceCompilerForInline: SourceCompilerForInline
): SMAPAndMethodNode {
if (isSpecialEnumMethod(functionDescriptor)) {
val arguments = resolvedCall!!.typeArguments
when {
isSpecialEnumMethod(functionDescriptor) -> {
val arguments = resolvedCall!!.typeArguments
val node = createSpecialEnumMethodBody(
codegen,
functionDescriptor.name.asString(),
arguments.keys.single().defaultType,
state.typeMapper
)
return SMAPAndMethodNode(node, SMAPParser.parseOrCreateDefault(null, null, "fake", -1, -1))
}
else if (functionDescriptor.isBuiltInSuspendCoroutineOrReturnInJvm()) {
return SMAPAndMethodNode(
createMethodNodeForSuspendCoroutineOrReturn(
functionDescriptor, state.typeMapper
),
val node = createSpecialEnumMethodBody(
codegen,
functionDescriptor.name.asString(),
arguments.keys.single().defaultType,
state.typeMapper
)
return SMAPAndMethodNode(node, SMAPParser.parseOrCreateDefault(null, null, "fake", -1, -1))
}
functionDescriptor.isBuiltInSuspendCoroutineOrReturnInJvm() ->
return SMAPAndMethodNode(
createMethodNodeForSuspendCoroutineOrReturn(functionDescriptor, state.typeMapper),
SMAPParser.parseOrCreateDefault(null, null, "fake", -1, -1)
)
)
functionDescriptor.isBuiltInCoroutineContext() ->
return SMAPAndMethodNode(
createMethodNodeForCoroutineContext(functionDescriptor),
SMAPParser.parseOrCreateDefault(null, null, "fake", -1, -1)
)
}
val asmMethod = if (callDefault)

View File

@@ -69,7 +69,7 @@ internal const val THIS = "this"
internal const val THIS_0 = "this$0"
internal const val FIRST_FUN_LABEL = "$$$$\$ROOT$$$$$"
internal const val SPECIAL_TRANSFORMATION_NAME = "\$special"
internal const val INLINE_TRANSFORMATION_SUFFIX = "\$inlined"
const val INLINE_TRANSFORMATION_SUFFIX = "\$inlined"
internal const val INLINE_CALL_TRANSFORMATION_SUFFIX = "$" + INLINE_TRANSFORMATION_SUFFIX
internal const val INLINE_FUN_THIS_0_SUFFIX = "\$inline_fun"
internal const val DEFAULT_LAMBDA_FAKE_CALL = "$$\$DEFAULT_LAMBDA_FAKE_CALL$$$"

View File

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

View File

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

View File

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

View File

@@ -29,13 +29,14 @@ val testDistProjects = listOf(
":kotlin-test:kotlin-test-jvm",
":kotlin-test:kotlin-test-junit",
":kotlin-test:kotlin-test-js",
":kotlin-daemon-client",
":kotlin-preloader",
":plugins:android-extensions-compiler",
":kotlin-ant",
":kotlin-annotations-jvm",
":kotlin-annotations-android")
val testJvm6ServerRuntime by configurations.creating
dependencies {
depDistProjects.forEach {
testCompile(projectDist(it))
@@ -43,16 +44,24 @@ dependencies {
testCompile(commonDep("junit:junit"))
testCompileOnly(projectDist(":kotlin-test:kotlin-test-jvm"))
testCompileOnly(projectDist(":kotlin-test:kotlin-test-junit"))
testCompile(project(":compiler.tests-common"))
testCompile(project(":compiler:tests-common-jvm6"))
testCompile(projectTests(":compiler:tests-common"))
testCompile(projectTests(":generators:test-generator"))
testCompile(project(":compiler:ir.ir2cfg"))
testCompile(project(":compiler:ir.tree")) // used for deepCopyWithSymbols call that is removed by proguard from the compiler TODO: make it more straightforward
testCompileOnly(project(":kotlin-daemon-client"))
otherCompilerModules.forEach {
testCompileOnly(project(it))
}
testCompile(ideaSdkDeps("openapi", "idea", "util", "asm-all", "commons-httpclient-3.1-patched"))
testRuntime(projectDist(":kotlin-compiler"))
testRuntime(projectDist(":kotlin-daemon-client"))
testRuntime(preloadedDeps("dx", subdir = "android-5.0/lib"))
testRuntime(ideaSdkCoreDeps("*.jar"))
testRuntime(ideaSdkDeps("*.jar"))
testRuntime(files("${System.getProperty("java.home")}/../lib/tools.jar"))
testJvm6ServerRuntime(projectTests(":compiler:tests-common-jvm6"))
}
sourceSets {
@@ -82,9 +91,9 @@ projectTest {
systemProperty("kotlin.test.script.classpath", the<JavaPluginConvention>().sourceSets.getByName("test").output.classesDirs.joinToString(File.pathSeparator))
}
evaluationDependsOn(":compiler:tests-common-jvm6")
fun Project.codegenTest(taskName: String, jdk: String, body: Test.() -> Unit): Test = projectTest(taskName) {
fun Project.codegenTest(target: Int, jvm: Int,
jdk: String = "JDK_${if (jvm <= 8) "1" else ""}$jvm",
body: Test.() -> Unit): Test = projectTest("codegenTarget${target}Jvm${jvm}Test") {
dependsOn(*testDistProjects.map { "$it:dist" }.toTypedArray())
workingDir = rootDir
@@ -99,34 +108,25 @@ fun Project.codegenTest(taskName: String, jdk: String, body: Test.() -> Unit): T
}
body()
doFirst {
val jdkPath = project.property(jdk) ?: error("$jdk is not optional to run this test")
val jdkPath = project.findProperty(jdk) ?: error("$jdk is not optional to run this test")
executable = "$jdkPath/bin/java"
println("Running test with $executable")
}
}.also {
task(taskName.replace(Regex("-[a-z]"), { it.value.takeLast(1).toUpperCase() })) {
dependsOn(it)
group = "verification"
}
group = "verification"
}
codegenTest("codegen-target6-jvm6-test", "JDK_18") {
dependsOn(":compiler:tests-common-jvm6:build")
codegenTest(target = 6, jvm = 6, jdk = "JDK_18") {
dependsOn(testJvm6ServerRuntime)
//TODO make port flexible
val port = "5100"
val port = project.findProperty("kotlin.compiler.codegen.tests.port")?.toString() ?: "5100"
var jdkProcess: Process? = null
doFirst {
logger.info("Configuring JDK 6 server...")
val jdkPath = project.property("JDK_16") ?: error("JDK_16 is not optional to run this test")
val jdkPath = project.findProperty("JDK_16") ?: error("JDK_16 is not optional to run this test")
val executable = "$jdkPath/bin/java"
val main = "org.jetbrains.kotlin.test.clientserver.TestProcessServer"
val classpath = getSourceSetsFrom(":compiler:tests-common-jvm6")["main"].output.asPath + ":" +
getSourceSetsFrom(":kotlin-stdlib")["main"].output.asPath + ":" +
getSourceSetsFrom(":kotlin-stdlib")["builtins"].output.asPath + ":" +
getSourceSetsFrom(":kotlin-test:kotlin-test-jvm")["main"].output.asPath
val classpath = testJvm6ServerRuntime.asPath
logger.debug("Server classpath: $classpath")
@@ -150,19 +150,21 @@ codegenTest("codegen-target6-jvm6-test", "JDK_18") {
}
}
codegenTest("codegen-target6-jvm9-test", "JDK_9") {
codegenTest(target = 6, jvm = 9) {
systemProperty("kotlin.test.default.jvm.target", "1.6")
}
codegenTest("codegen-target8-jvm8-test", "JDK_18") {
codegenTest(target = 8, jvm = 8) {
systemProperty("kotlin.test.default.jvm.target", "1.8")
}
codegenTest("codegen-target8-jvm9-test", "JDK_9") {
codegenTest(target = 8, jvm = 9) {
systemProperty("kotlin.test.default.jvm.target", "1.8")
}
codegenTest("codegen-target9-jvm9-test", "JDK_9") {
codegenTest(target = 9, jvm = 9) {
systemProperty("kotlin.test.default.jvm.target", "1.8")
systemProperty("kotlin.test.substitute.bytecode.1.8.to.1.9", "true")
}
val generateTests by generator("org.jetbrains.kotlin.generators.tests.GenerateCompilerTestsKt")

View File

@@ -16,7 +16,6 @@
package org.jetbrains.kotlin.cli.common.arguments
import org.jetbrains.kotlin.utils.SmartList
import java.io.Serializable
abstract class CommonToolArguments : Freezable(), Serializable {
@@ -24,7 +23,7 @@ abstract class CommonToolArguments : Freezable(), Serializable {
@JvmStatic private val serialVersionUID = 0L
}
var freeArgs: MutableList<String> = SmartList()
var freeArgs: List<String> by FreezableVar(emptyList())
@Transient var errors: ArgumentParseErrors = ArgumentParseErrors()

View File

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

View File

@@ -16,7 +16,7 @@
package org.jetbrains.kotlin.cli.common.arguments
import com.intellij.util.SmartList
import org.jetbrains.kotlin.utils.SmartList
import kotlin.reflect.KClass
import kotlin.reflect.KMutableProperty1
import kotlin.reflect.full.findAnnotation
@@ -100,12 +100,14 @@ fun <A : CommonToolArguments> parseCommandLineArguments(args: List<String>, resu
return argument.value == arg
}
val freeArgs = ArrayList<String>()
var i = 0
loop@ while (i < args.size) {
val arg = args[i++]
if (freeArgsStarted) {
result.freeArgs.add(arg)
freeArgs.add(arg)
continue
}
if (arg == FREE_ARGS_DELIMITER) {
@@ -118,7 +120,7 @@ fun <A : CommonToolArguments> parseCommandLineArguments(args: List<String>, resu
when {
arg.startsWith(ADVANCED_ARGUMENT_PREFIX) -> errors.unknownExtraFlags.add(arg)
arg.startsWith("-") -> errors.unknownArgs.add(arg)
else -> result.freeArgs.add(arg)
else -> freeArgs.add(arg)
}
continue
}
@@ -148,6 +150,8 @@ fun <A : CommonToolArguments> parseCommandLineArguments(args: List<String>, resu
updateField(property, result, value, argument.delimiter)
}
result.freeArgs += freeArgs
}
private fun <A : CommonToolArguments> updateField(property: KMutableProperty1<A, Any?>, result: A, value: Any, delimiter: String) {

View File

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

View File

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

View File

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

View File

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

View File

@@ -20,7 +20,7 @@ import com.intellij.mock.MockProject
import com.sun.tools.javac.util.Context
import org.jetbrains.kotlin.asJava.LightClassGenerationSupport
import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.STRONG_WARNING
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.ERROR
import org.jetbrains.kotlin.cli.jvm.config.jvmClasspathRoots
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.JVMConfigurationKeys
@@ -48,7 +48,7 @@ object JavacWrapperRegistrar {
Class.forName(JAVAC_CONTEXT_CLASS)
}
catch (e: ClassNotFoundException) {
messageCollector.report(STRONG_WARNING, "'$JAVAC_CONTEXT_CLASS' class can't be found ('tools.jar' is not found)")
messageCollector.report(ERROR, "'$JAVAC_CONTEXT_CLASS' class can't be found ('tools.jar' is not found)")
return false
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -57,6 +57,7 @@ abstract class ResolverForProject<M : ModuleInfo> {
abstract fun tryGetResolverForModule(moduleInfo: M): ResolverForModule?
abstract fun descriptorForModule(moduleInfo: M): ModuleDescriptor
abstract fun resolverForModuleDescriptor(descriptor: ModuleDescriptor): ResolverForModule
abstract fun diagnoseUnknownModuleInfo(infos: List<ModuleInfo>): Nothing
abstract val name: String
abstract val allModules: Collection<M>
@@ -70,8 +71,9 @@ class EmptyResolverForProject<M : ModuleInfo> : ResolverForProject<M>() {
override fun tryGetResolverForModule(moduleInfo: M): ResolverForModule? = null
override fun resolverForModuleDescriptor(descriptor: ModuleDescriptor): ResolverForModule = throw IllegalStateException("$descriptor is not contained in this resolver")
override fun descriptorForModule(moduleInfo: M) = throw IllegalStateException("Should not be called for $moduleInfo")
override fun descriptorForModule(moduleInfo: M) = diagnoseUnknownModuleInfo(listOf(moduleInfo))
override val allModules: Collection<M> = listOf()
override fun diagnoseUnknownModuleInfo(infos: List<ModuleInfo>) = throw IllegalStateException("Should not be called for $infos")
}
class ResolverForProjectImpl<M : ModuleInfo>(
@@ -164,11 +166,14 @@ class ResolverForProjectImpl<M : ModuleInfo>(
override fun descriptorForModule(moduleInfo: M): ModuleDescriptorImpl {
if (!isCorrectModuleInfo(moduleInfo)) {
throw AssertionError("$name does not know how to resolve $moduleInfo")
diagnoseUnknownModuleInfo(listOf(moduleInfo))
}
return doGetDescriptorForModule(moduleInfo)
}
override fun diagnoseUnknownModuleInfo(infos: List<ModuleInfo>) =
throw AssertionError("$name does not know how to resolve $infos")
private fun doGetDescriptorForModule(module: M): ModuleDescriptorImpl {
if (module in modules) {
return projectContext.storageManager.compute {

View File

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

View File

@@ -27,6 +27,7 @@ import org.jetbrains.kotlin.config.LanguageFeature;
import org.jetbrains.kotlin.config.LanguageVersion;
import org.jetbrains.kotlin.config.LanguageVersionSettings;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.diagnostics.rendering.DiagnosticRenderer;
import org.jetbrains.kotlin.lexer.KtKeywordToken;
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken;
import org.jetbrains.kotlin.lexer.KtTokens;
@@ -980,11 +981,12 @@ public interface Errors {
DiagnosticFactory0<PsiElement> NON_LOCAL_SUSPENSION_POINT = DiagnosticFactory0.create(ERROR);
DiagnosticFactory1<PsiElement, CallableDescriptor> ILLEGAL_SUSPEND_FUNCTION_CALL = DiagnosticFactory1.create(ERROR);
DiagnosticFactory1<PsiElement, CallableDescriptor> ILLEGAL_SUSPEND_PROPERTY_ACCESS = DiagnosticFactory1.create(ERROR);
DiagnosticFactory0<PsiElement> ILLEGAL_RESTRICTED_SUSPENDING_FUNCTION_CALL = DiagnosticFactory0.create(ERROR);
DiagnosticFactory2<PsiElement, String, String> PLUGIN_ERROR = DiagnosticFactory2.create(ERROR);
DiagnosticFactory2<PsiElement, String, String> PLUGIN_WARNING = DiagnosticFactory2.create(WARNING);
DiagnosticFactory2<PsiElement, String, String> PLUGIN_INFO = DiagnosticFactory2.create(INFO);
DiagnosticFactory1<PsiElement, RenderedDiagnostic<?>> PLUGIN_ERROR = DiagnosticFactory1.create(ERROR);
DiagnosticFactory1<PsiElement, RenderedDiagnostic<?>> PLUGIN_WARNING = DiagnosticFactory1.create(WARNING);
DiagnosticFactory1<PsiElement, RenderedDiagnostic<?>> PLUGIN_INFO = DiagnosticFactory1.create(INFO);
// Function contracts
DiagnosticFactory1<KtElement, String> ERROR_IN_CONTRACT_DESCRIPTION = DiagnosticFactory1.create(ERROR);

View File

@@ -0,0 +1,30 @@
/*
* 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.diagnostics
import org.jetbrains.kotlin.diagnostics.rendering.DiagnosticRenderer
class RenderedDiagnostic<D : Diagnostic>(
val diagnostic: D,
val renderer: DiagnosticRenderer<D>
) {
val text = renderer.render(diagnostic)
val factory: DiagnosticFactory<*> get() = diagnostic.factory
override fun toString() = text
}

View File

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

View File

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

View File

@@ -1263,11 +1263,11 @@ public class KotlinParsing extends AbstractKotlinParsing {
LOCAL(true, false),
SCRIPT_TOPLEVEL(true, true);
public final boolean desctructuringAllowed;
public final boolean destructuringAllowed;
public final boolean accessorsAllowed;
PropertyParsingMode(boolean desctructuringAllowed, boolean accessorsAllowed) {
this.desctructuringAllowed = desctructuringAllowed;
PropertyParsingMode(boolean destructuringAllowed, boolean accessorsAllowed) {
this.destructuringAllowed = destructuringAllowed;
this.accessorsAllowed = accessorsAllowed;
}
}
@@ -1295,7 +1295,7 @@ public class KotlinParsing extends AbstractKotlinParsing {
if (multiDeclaration) {
PsiBuilder.Marker multiDecl = mark();
parseMultiDeclarationName(propertyNameFollow);
errorIf(multiDecl, !mode.desctructuringAllowed, "Destructuring declarations are only allowed for local variables/values");
errorIf(multiDecl, !mode.destructuringAllowed, "Destructuring declarations are only allowed for local variables/values");
}
else {
parseFunctionOrPropertyName(receiverTypeDeclared, "property", propertyNameFollow, /*nameRequired = */ true);

View File

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

View File

@@ -114,9 +114,8 @@ class SyntheticClassOrObjectDescriptor(
private inner class SyntheticTypeConstructor(storageManager: StorageManager) : AbstractClassTypeConstructor(storageManager) {
override fun getParameters(): List<TypeParameterDescriptor> = emptyList()
override fun isFinal(): Boolean = true
override fun isDenotable(): Boolean = true
override fun getDeclarationDescriptor(): ClassifierDescriptor = thisDescriptor
override fun getDeclarationDescriptor(): ClassDescriptor = thisDescriptor
override fun computeSupertypes(): Collection<KotlinType> = syntheticSupertypes
override val supertypeLoopChecker: SupertypeLoopChecker = SupertypeLoopChecker.EMPTY
}

View File

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

View File

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

View File

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

View File

@@ -23,7 +23,9 @@ import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.SYNTHESIZE
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.descriptors.synthetic.SyntheticMemberDescriptor
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.scopes.receivers.ExtensionReceiver
import org.jetbrains.kotlin.resolve.source.getPsi
import java.util.*
@@ -51,7 +53,20 @@ object DescriptorToSourceUtils {
return result
}
// TODO Fix in descriptor
@JvmStatic private fun getSourceForExtensionReceiverParameterDescriptor(descriptor: ReceiverParameterDescriptor): PsiElement? {
// Only for extension receivers
if (descriptor.source != SourceElement.NO_SOURCE || descriptor.value !is ExtensionReceiver) return null
val containingDeclaration = descriptor.containingDeclaration as? CallableDescriptor ?: return null
val psi = containingDeclaration.source.getPsi() as? KtCallableDeclaration ?: return null
return psi.receiverTypeReference
}
@JvmStatic fun getSourceFromDescriptor(descriptor: DeclarationDescriptor): PsiElement? {
if (descriptor is ReceiverParameterDescriptor) {
getSourceForExtensionReceiverParameterDescriptor(descriptor)?.let { return it }
}
return (descriptor as? DeclarationDescriptorWithSource)?.source?.getPsi()
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -706,15 +706,15 @@ class CandidateResolver(
candidateResolveMode == CandidateResolveMode.FULLY || candidateCall.status.possibleTransformToSuccess()
private inline fun <D : CallableDescriptor> CallCandidateResolutionContext<D>.check(
checker: CallCandidateResolutionContext<D>.() -> Unit
crossinline checker: CallCandidateResolutionContext<D>.() -> Unit
) {
if (shouldContinue()) checker()
if (shouldContinue()) checker() else candidateCall.addRemainingTasks { checker() }
}
private inline fun <D : CallableDescriptor> CallCandidateResolutionContext<D>.checkAndReport(
checker: CallCandidateResolutionContext<D>.() -> ResolutionStatus
crossinline checker: CallCandidateResolutionContext<D>.() -> ResolutionStatus
) {
if (shouldContinue()) {
check {
candidateCall.addStatus(checker())
}
}

View File

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

View File

@@ -22,12 +22,15 @@ import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.coroutines.hasSuspendFunctionType
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtThisExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.descriptorUtil.hasRestrictsSuspensionAnnotation
import org.jetbrains.kotlin.resolve.inline.InlineUtil
import org.jetbrains.kotlin.resolve.scopes.HierarchicalScope
@@ -42,17 +45,21 @@ import org.jetbrains.kotlin.utils.addToStdlib.safeAs
object CoroutineSuspendCallChecker : CallChecker {
private val ALLOWED_SCOPE_KINDS = setOf(LexicalScopeKind.FUNCTION_INNER_SCOPE, LexicalScopeKind.FUNCTION_HEADER_FOR_DESTRUCTURING)
private val COROUTINE_CONTEXT_FQ_NAME = FqName("kotlin.coroutines.experimental.intrinsics.coroutineContext")
override fun check(resolvedCall: ResolvedCall<*>, reportOn: PsiElement, context: CallCheckerContext) {
val descriptor = resolvedCall.candidateDescriptor as? FunctionDescriptor ?: return
if (!descriptor.isSuspend) return
val descriptor = resolvedCall.candidateDescriptor
when (descriptor) {
is FunctionDescriptor -> if (!descriptor.isSuspend) return
is PropertyDescriptor -> if (descriptor.fqNameSafe != COROUTINE_CONTEXT_FQ_NAME) return
else -> return
}
val enclosingSuspendFunction =
context.scope
.parentsWithSelf.firstOrNull {
it is LexicalScope && it.kind in ALLOWED_SCOPE_KINDS &&
it.ownerDescriptor.safeAs<FunctionDescriptor>()?.isSuspend == true
}?.cast<LexicalScope>()?.ownerDescriptor?.cast<FunctionDescriptor>()
val enclosingSuspendFunction = context.scope
.parentsWithSelf.firstOrNull {
it is LexicalScope && it.kind in ALLOWED_SCOPE_KINDS &&
it.ownerDescriptor.safeAs<FunctionDescriptor>()?.isSuspend == true
}?.cast<LexicalScope>()?.ownerDescriptor?.cast<FunctionDescriptor>()
when {
enclosingSuspendFunction != null -> {
@@ -70,7 +77,10 @@ object CoroutineSuspendCallChecker : CallChecker {
checkRestrictsSuspension(enclosingSuspendFunction, resolvedCall, reportOn, context)
}
else -> {
context.trace.report(Errors.ILLEGAL_SUSPEND_FUNCTION_CALL.on(reportOn, resolvedCall.candidateDescriptor))
when (descriptor) {
is FunctionDescriptor -> context.trace.report(Errors.ILLEGAL_SUSPEND_FUNCTION_CALL.on(reportOn, resolvedCall.candidateDescriptor))
is PropertyDescriptor -> context.trace.report(Errors.ILLEGAL_SUSPEND_PROPERTY_ACCESS.on(reportOn, resolvedCall.candidateDescriptor))
}
}
}
}

View File

@@ -16,6 +16,8 @@
package org.jetbrains.kotlin.resolve.calls.model;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.descriptors.CallableDescriptor;
@@ -42,6 +44,10 @@ public interface MutableResolvedCall<D extends CallableDescriptor> extends Resol
void markCallAsCompleted();
void addRemainingTasks(Function0<Unit> task);
void performRemainingTasks();
boolean isCompleted();

View File

@@ -19,6 +19,8 @@ package org.jetbrains.kotlin.resolve.calls.model;
import com.google.common.collect.Maps;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.SmartList;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.descriptors.CallableDescriptor;
@@ -81,6 +83,7 @@ public class ResolvedCallImpl<D extends CallableDescriptor> implements MutableRe
private Boolean hasInferredReturnType = null;
private boolean completed = false;
private KotlinType smartCastDispatchReceiverType = null;
private Queue<Function0<Unit>> remainingTasks = null;
private ResolvedCallImpl(
@NotNull ResolutionCandidate<D> candidate,
@@ -283,7 +286,7 @@ public class ResolvedCallImpl<D extends CallableDescriptor> implements MutableRe
for (int i = 0; i < candidateDescriptor.getValueParameters().size(); ++i) {
arguments.add(null);
}
for (Map.Entry<ValueParameterDescriptor, ResolvedValueArgument> entry : valueArguments.entrySet()) {
ValueParameterDescriptor parameterDescriptor = entry.getKey();
ResolvedValueArgument value = entry.getValue();
@@ -299,7 +302,7 @@ public class ResolvedCallImpl<D extends CallableDescriptor> implements MutableRe
return null;
}
}
return arguments;
}
@@ -353,6 +356,23 @@ public class ResolvedCallImpl<D extends CallableDescriptor> implements MutableRe
constraintSystem = null;
tracing = null;
completed = true;
remainingTasks = null;
}
@Override
public void addRemainingTasks(Function0<Unit> task) {
if (remainingTasks == null) {
remainingTasks = new ArrayDeque<>();
}
remainingTasks.add(task);
}
@Override
public void performRemainingTasks() {
if (remainingTasks == null) return;
while (!remainingTasks.isEmpty()) {
remainingTasks.poll().invoke();
}
}
@Override

View File

@@ -96,9 +96,14 @@ internal class DelegatingDataFlowInfo private constructor(
nullability: Nullability,
languageVersionSettings: LanguageVersionSettings,
typeInfo: SetMultimap<DataFlowValue, KotlinType>? = null,
affectReceiver: Boolean = true
affectReceiver: Boolean = true,
// TODO: remove me in version 1.3! I'm very dirty hack!
// In normal circumstances this should be always true
recordUnstable: Boolean = true
): Boolean {
map.put(value, nullability)
if (value.isStable || recordUnstable) {
map.put(value, nullability)
}
val identifierInfo = value.identifierInfo
if (affectReceiver && !nullability.canBeNull() &&
@@ -108,7 +113,8 @@ internal class DelegatingDataFlowInfo private constructor(
val receiverType = identifierInfo.receiverType
if (identifierInfo.safe && receiverType != null) {
val receiverValue = DataFlowValue(identifierInfo.receiverInfo, receiverType)
putNullabilityAndTypeInfo(map, receiverValue, nullability, languageVersionSettings, typeInfo)
putNullabilityAndTypeInfo(map, receiverValue, nullability,
languageVersionSettings, typeInfo, recordUnstable = recordUnstable)
}
}
is IdentifierInfo.SafeCast -> {
@@ -118,12 +124,16 @@ internal class DelegatingDataFlowInfo private constructor(
languageVersionSettings.supportsFeature(LanguageFeature.SafeCastCheckBoundSmartCasts)) {
val subjectValue = DataFlowValue(identifierInfo.subjectInfo, subjectType)
putNullabilityAndTypeInfo(map, subjectValue, nullability, languageVersionSettings, typeInfo)
typeInfo?.put(subjectValue, targetType)
putNullabilityAndTypeInfo(map, subjectValue, nullability,
languageVersionSettings, typeInfo, recordUnstable = false)
if (subjectValue.isStable) {
typeInfo?.put(subjectValue, targetType)
}
}
}
is IdentifierInfo.Variable -> identifierInfo.bound?.let {
putNullabilityAndTypeInfo(map, it, nullability, languageVersionSettings, typeInfo)
putNullabilityAndTypeInfo(map, it, nullability,
languageVersionSettings, typeInfo, recordUnstable = recordUnstable)
}
}
}

View File

@@ -38,7 +38,6 @@ import org.jetbrains.kotlin.resolve.calls.callResolverUtil.isInfixCall
import org.jetbrains.kotlin.resolve.calls.callUtil.createLookupLocation
import org.jetbrains.kotlin.resolve.calls.context.*
import org.jetbrains.kotlin.resolve.calls.inference.CoroutineInferenceSupport
import org.jetbrains.kotlin.resolve.calls.model.KotlinCallKind
import org.jetbrains.kotlin.resolve.calls.model.*
import org.jetbrains.kotlin.resolve.calls.results.OverloadResolutionResultsImpl
import org.jetbrains.kotlin.resolve.calls.results.ResolutionResultsHandler
@@ -56,6 +55,7 @@ import org.jetbrains.kotlin.types.ErrorUtils
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.types.isDynamic
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.sure
import java.lang.IllegalStateException
import java.util.*
@@ -208,12 +208,15 @@ class NewResolutionOldInference(
val callCandidateResolutionContext = CallCandidateResolutionContext.create(
resolvedCall, basicCallContext, candidateTrace, tracing, basicCallContext.call,
CandidateResolveMode.FULLY // todo
CandidateResolveMode.EXIT_ON_FIRST_ERROR
)
candidateResolver.performResolutionForCandidateCall(callCandidateResolutionContext, basicCallContext.checkArguments) // todo
val diagnostics = listOfNotNull(createPreviousResolveError(resolvedCall.status))
MyCandidate(diagnostics, resolvedCall)
MyCandidate(diagnostics, resolvedCall) {
resolvedCall.performRemainingTasks()
listOfNotNull(createPreviousResolveError(resolvedCall.status))
}
}
if (basicCallContext.collectAllCandidates) {
val allCandidates = towerResolver.runWithEmptyTowerData(KnownResultProcessor(resolvedCandidates),
@@ -315,12 +318,26 @@ class NewResolutionOldInference(
override val isDebuggerContext: Boolean get() = resolutionContext.isDebuggerContext
}
internal data class MyCandidate(
val diagnostics: List<KotlinCallDiagnostic>,
val resolvedCall: MutableResolvedCall<*>
internal class MyCandidate(
// Diagnostics that are already computed
// if resultingApplicability is successful they must be the same as `diagnostics`,
// otherwise they might be a bit different but result remains unsuccessful
val eagerDiagnostics: List<KotlinCallDiagnostic>,
val resolvedCall: MutableResolvedCall<*>,
finalDiagnosticsComputation: (() -> List<KotlinCallDiagnostic>)? = null
) : Candidate {
override val resultingApplicability: ResolutionCandidateApplicability = getResultApplicability(diagnostics)
override val isSuccessful get() = resultingApplicability.isSuccess
val diagnostics: List<KotlinCallDiagnostic> by lazy(LazyThreadSafetyMode.NONE) {
finalDiagnosticsComputation?.invoke() ?: eagerDiagnostics
}
operator fun component1() = diagnostics
operator fun component2() = resolvedCall
override val resultingApplicability: ResolutionCandidateApplicability by lazy(LazyThreadSafetyMode.NONE) {
getResultApplicability(diagnostics)
}
override val isSuccessful = getResultApplicability(eagerDiagnostics).isSuccess
}
private inner class CandidateFactoryImpl(
@@ -366,16 +383,27 @@ class NewResolutionOldInference(
val callCandidateResolutionContext = CallCandidateResolutionContext.create(
candidateCall, basicCallContext, candidateTrace, tracing, basicCallContext.call,
CandidateResolveMode.FULLY // todo
CandidateResolveMode.EXIT_ON_FIRST_ERROR
)
candidateResolver.performResolutionForCandidateCall(callCandidateResolutionContext, basicCallContext.checkArguments) // todo
val diagnostics = (towerCandidate.diagnostics +
checkInfixAndOperator(basicCallContext.call, towerCandidate.descriptor) +
createPreviousResolveError(candidateCall.status)).filterNotNull() // todo
return MyCandidate(diagnostics, candidateCall)
val diagnostics = createDiagnosticsForCandidate(towerCandidate, candidateCall)
return MyCandidate(diagnostics, candidateCall) {
candidateCall.performRemainingTasks()
createDiagnosticsForCandidate(towerCandidate, candidateCall)
}
}
private fun createDiagnosticsForCandidate(
towerCandidate: CandidateWithBoundDispatchReceiver,
candidateCall: ResolvedCallImpl<CallableDescriptor>
): List<ResolutionDiagnostic> =
mutableListOf<ResolutionDiagnostic>().apply {
addAll(towerCandidate.diagnostics)
addAll(checkInfixAndOperator(basicCallContext.call, towerCandidate.descriptor))
addIfNotNull(createPreviousResolveError(candidateCall.status))
}
private fun checkInfixAndOperator(call: Call, descriptor: CallableDescriptor): List<ResolutionDiagnostic> {
if (descriptor !is FunctionDescriptor || ErrorUtils.isError(descriptor)) return emptyList()
if (descriptor.name != name && (name == OperatorNameConventions.UNARY_PLUS || name == OperatorNameConventions.UNARY_MINUS)) {
@@ -405,7 +433,9 @@ class NewResolutionOldInference(
"Variable call must be success: $variable"
}
return MyCandidate(variable.diagnostics + invoke.diagnostics, resolvedCallImpl)
return MyCandidate(variable.eagerDiagnostics + invoke.eagerDiagnostics, resolvedCallImpl) {
variable.diagnostics + invoke.diagnostics
}
}
override fun factoryForVariable(stripExplicitReceiver: Boolean): CandidateFactory<MyCandidate> {

View File

@@ -397,7 +397,7 @@ object ExpectedActualDeclarationChecker : DeclarationChecker {
if (b.hasStableParameterNames() && !equalsBy(aParams, bParams, ValueParameterDescriptor::getName)) return Incompatible.ParameterNames
if (!equalsBy(aTypeParams, bTypeParams, TypeParameterDescriptor::getName)) return Incompatible.TypeParameterNames
if (a.modality != b.modality) return Incompatible.Modality
if (!areCompatibleModalities(a.modality, b.modality)) return Incompatible.Modality
if (a.visibility != b.visibility) return Incompatible.Visibility
areCompatibleTypeParameters(aTypeParams, bTypeParams, platformModule, substitutor).let { if (it != Compatible) return it }
@@ -535,7 +535,7 @@ object ExpectedActualDeclarationChecker : DeclarationChecker {
val bTypeParams = b.declaredTypeParameters
if (aTypeParams.size != bTypeParams.size) return Incompatible.TypeParameterCount
if (a.modality != b.modality && !(a.modality == Modality.FINAL && b.modality == Modality.OPEN)) return Incompatible.Modality
if (!areCompatibleModalities(a.modality, b.modality)) return Incompatible.Modality
if (a.visibility != b.visibility) return Incompatible.Visibility
@@ -556,6 +556,11 @@ object ExpectedActualDeclarationChecker : DeclarationChecker {
return Compatible
}
private fun areCompatibleModalities(a: Modality, b: Modality): Boolean {
return a == Modality.FINAL && b == Modality.OPEN ||
a == b
}
private fun areCompatibleClassScopes(
a: ClassDescriptor,

View File

@@ -741,7 +741,7 @@ private class ConstantExpressionEvaluatorVisitor(
override fun visitClassLiteralExpression(expression: KtClassLiteralExpression, expectedType: KotlinType?): CompileTimeConstant<*>? {
val type = trace.getType(expression)!!
if (type.isError) return null
return KClassValue(type).wrap()
return factory.createKClassValue(type).wrap()
}
private fun resolveArguments(valueArguments: List<ValueArgument>, expectedType: KotlinType): List<CompileTimeConstant<*>?> {

View File

@@ -17,7 +17,6 @@
package org.jetbrains.kotlin.resolve.diagnostics
import com.google.common.collect.ImmutableSet
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.psi.PsiElement
import com.intellij.util.containers.ContainerUtil
@@ -53,8 +52,6 @@ interface DiagnosticSuppressor {
}
abstract class KotlinSuppressCache {
private val LOG = Logger.getInstance(DiagnosticsWithSuppression::class.java)
private val ADDITIONAL_SUPPRESS_STRING_PROVIDERS = ExtensionProvider.create(SuppressStringProvider.EP_NAME)
private val DIAGNOSTIC_SUPPRESSORS = ExtensionProvider.create(DiagnosticSuppressor.EP_NAME)
@@ -121,12 +118,6 @@ abstract class KotlinSuppressCache {
This way we need no more lookups than the number of suppress() annotations from here to the root.
*/
protected fun isSuppressedByAnnotated(suppressionKey: String, severity: Severity, annotated: KtAnnotated, debugDepth: Int): Boolean {
if (LOG.isDebugEnabled) {
LOG.debug("Annotated: ", annotated.name)
LOG.debug("Depth: ", debugDepth)
LOG.debug("Cache size: ", suppressors.size, "\n")
}
val suppressor = getOrCreateSuppressor(annotated)
if (suppressor.isSuppressed(suppressionKey, severity)) return true

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -60,7 +60,7 @@ class ClassResolutionScopesSupport(
createInheritanceScope(inheritanceScopeWithoutMe(), classDescriptor, classDescriptor, withCompanionObject = false)
}
val scopeForMemberDeclarationResolution: () -> LexicalScope = storageManager.createLazyValue {
val scopeForMemberDeclarationResolution: () -> LexicalScope = storageManager.createLazyValue(onRecursion = createThrowingLexicalScope) {
val scopeWithGenerics = scopeWithGenerics(inheritanceScopeWithMe())
LexicalScopeImpl(scopeWithGenerics, classDescriptor, true, classDescriptor.thisAsReceiverParameter, LexicalScopeKind.CLASS_MEMBER_SCOPE)
}
@@ -116,7 +116,9 @@ class ClassResolutionScopesSupport(
createLazyValueWithPostCompute(compute, onRecursion, {})
companion object {
private val createThrowingLexicalScope: (Boolean) -> LexicalScope = { ThrowingLexicalScope() }
private val createThrowingLexicalScope: (Boolean) -> LexicalScope = {
ThrowingLexicalScope()
}
}
}

View File

@@ -650,11 +650,6 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
return parameters.invoke();
}
@Override
public boolean isFinal() {
return getModality() == Modality.FINAL;
}
@Override
public boolean isDenotable() {
return true;
@@ -662,7 +657,7 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
@Override
@NotNull
public ClassifierDescriptor getDeclarationDescriptor() {
public ClassDescriptor getDeclarationDescriptor() {
return LazyClassDescriptor.this;
}

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