Compare commits

..

316 Commits

Author SHA1 Message Date
Igor Chevdar
3a35ba7e58 Fixed WrappedClassDescriptor 2019-01-23 11:16:19 +03:00
Pavel Punegov
d0fb059d58 Update K/N to 1.1.1-release-6082 2019-01-23 11:15:38 +03:00
Roman Artemev
27d3a1e534 Update 1.3.20 ChangeLog 2019-01-21 19:17:24 +03:00
Yan Zhulanow
2027d58ef3 Remove Android Extensions from the default JPS classpath 2019-01-21 18:50:51 +03:00
Pavel Punegov
8f5ca82b26 Update to 1.1.0-release-5988 for 1.3.20 2019-01-21 17:43:35 +03:00
Mikhail Glukhikh
0d9c30a311 Use correct project for settings.gradle manipulations #KT-29333 Fixed
Otherwise we get an error "Element from alien project".
See details in added comment.
2019-01-21 13:57:44 +03:00
Ilya Chernikov
76b8319fbe Change default jvmTarget for scripts compilation via jvmhost to 1.8
#KT-29319 fixed
2019-01-18 18:10:32 +01:00
Ilya Chernikov
069857c12c Implement test for #KT-29301, #KT-29296 and #KT-29293 2019-01-18 18:10:31 +01:00
Ilya Chernikov
5ab6472a4d Keep ivy resolvers in the main-kts.jar
#KT-29301 fixed
2019-01-18 18:10:31 +01:00
Ilya Chernikov
5306e3f88a Implement and use helpers for economical classpath update in script configs 2019-01-18 18:10:30 +01:00
Ilya Chernikov
97a8739182 Allow explicit nulls for props with default, allow null as base classloader for evaluation
and use proper default evaluation configuration if not supplied explicitly;
also add reset method to the properties builder and containsKey method to
the properties collection
#KT-29296 fixed
2019-01-18 18:10:29 +01:00
Ilya Chernikov
1623ed027d Add stdlib, etc. to the script dependencies on compilation
#KT-29293 fixed
2019-01-18 18:10:29 +01:00
Alexander Podkhalyuzin
e0226ce5dd Removed usages to deprecated API, which is going to be removed in 2019.1
(cherry picked from commit 36b2640ab7)
2019-01-18 18:33:24 +03:00
Ilya Gorbunov
e1734fbbda Document that sorting is stable in each platform
#KT-12473 Fixed

(cherry picked from commit 0ac85ad715)
2019-01-18 17:47:53 +03:00
Ilya Gorbunov
d2a0a2a0de Ensure stable sorting in MutableList.sort/sortWith
MutableList.sortWith now works correctly in JS_IR backend too

#KT-12473

(cherry picked from commit 56672c2564)
2019-01-18 17:47:53 +03:00
Ilmir Usmanov
59c5ab7d8e Do not mark fake inliner variables as alive
This prevents them from spilling.
 #KT-29317 Fixed

(cherry picked from commit e8c52e0a8f)
2019-01-18 17:05:47 +03:00
Ilmir Usmanov
8ed766e628 Add regression test
#KT-29327

(cherry picked from commit 7e4e1b9a4d)
2019-01-18 16:44:46 +03:00
Ilmir Usmanov
ad12184e14 Revert "Simplify tail-call optimisation check"
This reverts commit a5bcd3495e.

 #KT-27190: Open
 #KT-29327: Fixed

(cherry picked from commit dc6bb4cd08)
2019-01-18 16:44:12 +03:00
Ilmir Usmanov
4f6971339d Fix test data 2019-01-17 14:23:54 +03:00
Ilmir Usmanov
9ee4cab849 Put default value to vars iff they are not boxed
#KT-24672 Fixed
2019-01-17 14:23:47 +03:00
Alexander Udalov
e2de2fc059 Make CommonToolArguments.nullable
#KT-28974 Fixed

(cherry picked from commit 05c25342ad)
2019-01-16 14:58:32 +01:00
Pavel Punegov
eae3cf9f32 Update to 1.1.0-rc2-5686 2019-01-14 22:49:44 +03:00
Yan Zhulanow
825dd7abe9 Fix testJavacIsLoadedOnce() kapt integration test 2019-01-14 17:38:15 +03:00
Ilya Matveev
ffc235b730 Allow setting test binary linker options using a test compilation
#KT-29254 Fixed
2019-01-14 20:45:08 +07:00
Dmitry Savvinov
9ff115514e Get rid of FUNCTOR slice, use lazy value in ContractDecription instead
Functor is an imperative representation of function's contract (contrary
to ContractDescription, which is a declarative one). ContractDescription
is convenient when we deal with sources of contracts declarations
(binaries, source), while Functors are convenient for analyzing code
with contracts.

It means that we have to convert ContractDescription into Functor when
we start working with contracts. This computation isn't trivial, and
Functor and ContractDescription are in 1-1 correspondence, so we would
like to cache Functor for each ContractDescription somewhere.

We used to do this in binding trace, in slice FUNCTOR.

Now, it turns out that this approach causes "Rewrite at slice"
exception, see KT-28847. We won't go into details of why that happens
here, you can see the issue comments for details (but be prepared for the
very long and nitty-gritty story)

This commit removes the problematic slice and introduces another
approach, where Functor is attached to the ContractDescription, computed
lazily and cached here.

^KT-28847 Fixed
2019-01-14 12:04:08 +03:00
Dmitry Savvinov
dc1e44813c Add test on rewrite at slice FUNCTOR 2019-01-14 12:04:07 +03:00
Alexander Podkhalyuzin
016e103755 Implemented KotlinResolveScopeEnlarger for modules
Before that we had dependency to iml file, which is incorrect

(cherry picked from commit 893479bd5e)
2019-01-14 10:55:05 +03:00
Ting-Yuan Huang
12e03c34c6 Allow specifying isolation mode for KAPT workers
There are a few isolation modes for Gradle workers. KAPT uses 2 of them.

IsolationMode.NONE is the default. It runs workers in Gradle daemon and
is more memory efficient.

IsolationMode.PROCESS forks workers into individual processes. This
keeps some resource leaking annotation processors from affecting the
rest of compilation.

Users can specify kapt.workers.isolation=process, if they need to use
some annotation processor that are known to be resource leaking.
2019-01-11 23:51:20 +03:00
Ilya Gorbunov
65c6dd9e1a Clarify how elements of arrays are compared by contentEquals function
Add clarification only for the particular group of overloads including
 arrays of object and floating point numbers.

#KT-22942 Fixed

(cherry picked from commit 23950042f6)
2019-01-11 21:37:57 +03:00
Ilya Gorbunov
6c7cbfc09c Improve Any.equals/hashCode docs
- add code formatting
- remove 'reference' adjective, as Kotlin doesn't distinguish primitives from reference types
- add the requirement of inequality to null
- replace inaccurate note with a link to the reference (relates to KT-26604)

#KT-14866

(cherry picked from commit ef278ea030)
2019-01-11 21:37:55 +03:00
Ilya Gorbunov
74d06c63e6 Provide stable sorting when JS engine sorting doesn't look stable
#KT-12473

(cherry picked from commit 51eb21d44b)
2019-01-11 21:37:54 +03:00
Ilya Gorbunov
01a3accd53 Remove specialization of toTypedArray for LongArray and BooleanArray in JS
The default implementation for primitive arrays returns an array of correct type.

#KT-29187 Fixed

(cherry picked from commit 7c3c454654)
2019-01-11 21:37:52 +03:00
Ilya Gorbunov
da23ed15af Update copyright in generated stdlib sources
(cherry picked from commit fcef876c7e)
2019-01-11 21:37:51 +03:00
Sergey Igushkin
5cd7d6414d Fixes for review KOTLIN-CR-2599
* Move source artifacts to KotlinVariant classes (since joint Android
 variants may have multiple source artifacts, make it a set)

* Change lowerSpinalCaseName to dashSeparatedName (doesn't transform
 the strings to lower case inside)

* Don't transform the project name to lower case (in the future, it may
 be reasonable to stop transforming the target and component names, too)
 Still transform the target names and the component names.
 Currently, this is the way we don't break existing publications and may
 still reconsider this in the future.

* Add a workaround for a list of GString's assigned to
 publishLibraryVariants

* Check for Android library variants existence in a more strict way,
 report existing variants that are not library variants.

(cherry picked from commit 8bc7ac32f3)
2019-01-11 20:44:57 +03:00
Sergey Igushkin
0544745a5c Properly setup localToProject attribute in jvmWithJava (KT-29035)
A dependency on a multiplatform module with a jvmWithJava target failed
to resolve because the 'apiElements' and 'runtimeElements'
configurations didn't have the attribute 'localToProject' set to
'public'.

Those configurations need to have have the attribute set as per the
fix of KT-28795, but it doesn't happen.

Issue #KT-29035 Fixed

(cherry picked from commit 7e6527ca65)
2019-01-11 20:44:41 +03:00
Sergey Igushkin
1651e94bb8 Expose 'allKotlinSourceSets' in KotlinCompilation (KT-28749)
As KotlinCompilation only contains the directly added source sets in its
`kotlinSourceSets` property, we need to provide a convenient way to
collect the whole source sets hierarchy for a compilation.

We added internal `allKotlinSourceSets` some time ago, and it seems
reasonable to expose it as public API.

Issue #KT-28749 Fixed

(cherry picked from commit 0abd044800)
2019-01-11 20:44:14 +03:00
Sergey Igushkin
2c359a61ff Link the 'api' configuration to 'apiElements' (KT-28355)
As we introduced the 'api' configurations for Kotlin source sets, the
Java plugin did not link these configurations to its 'apiElements', and
those dependencies would only get published with the 'runtime' scope
through the 'implementation' configuration.

To fix this, manually specify that 'apiElements' extendsFrom 'api'.

Issue #KT-28355 Fixed

(cherry picked from commit 0cf95f84cb)
2019-01-11 20:43:59 +03:00
Sergey Igushkin
a5ef558355 Fix transitive dependencies overriding default Kotlin version (KT-28820)
In Gradle 5.0, the 'prefer' function semantics has changed, and now a
transitive dependency version wins over the 'preferred' one. Instead,
'require' has been introduced in 5.0 with the old semantics.

Our users expect that the default Kotlin dependency version will be
at least as new as the plugin version, so we now need to use 'require'
with Gradle 5.0+

Issue KT-28820 Fixed

(cherry picked from commit 82f13b90e6)
2019-01-11 20:43:40 +03:00
Sergey Igushkin
e9bfd0b3c2 Always rewrite dependencies in POMs when publishing an MPP (KT-28482)
As non-Gradle consumers and Gradle consumers with metadata disabled
cannot read Gradle metadata, in POMs (the only source of dependencies
for the consumers mentioned above), we should publish the dependencies
on modules with metadata as the target artifact IDs rather than the root
MPP module ID (e.g. 'foo-jvm' rather than 'foo').

To do that, we rewrite the POMs of the publications even when Gradle
metadata is enabled. Note: in the POMs, a project dependency is already
written in the form of the artifact ID of the root Kotlin software
component, so it complicates the dependencies rewriting a little.

To rewrite third-party dependencies, we detect dependencies that
resolved to no artifact and have a single child in the Gradle
dependencies graph of the resolved configuration – this is what a
dependency looks like which was redirected to another module via
'available-at'.

Issue #KT-28482 Fixed

(cherry picked from commit f9c45c30a2)
2019-01-11 20:43:13 +03:00
Sergey Igushkin
669d7ae9c3 Fix failure when creating a compilation in afterEvaluate (KT-28896)
To configure a compilation's sources, we run an action in
`whenEvaluated { ... }`, expecting that the compilation's task already
exists. This was not true with compilations created from a user build
script or a 3rd-party plugin in `afterEvaluate { ... }`.

Fix this by expecting that a task may possibly not exist at that point,
and also using `whenEvaluated { ... }` instead of
`afterEvaluate { ... }` in several places that are executed for each new
compilation as a workaround for
https://github.com/gradle/gradle/issues/1135.

Issue #KT-28896 Fixed

(cherry picked from commit 2fd524f1c0)
2019-01-11 20:42:54 +03:00
Sergey Igushkin
60d8f6eabd Publish Android variants from multiplatform projects
Also update the code for rewriting the dependencies, as Android variants
have their dependencies configurations formed a bit differently, and
also introduce the logic for choosing the right component by the
configuration name the dependency resolves to.

Issue #KT-27535 Fixed

(cherry picked from commit de5e86ae9f)
2019-01-11 20:42:32 +03:00
Sergey Igushkin
8791ce1685 Restructure source JARs logic, move it to components management
Move the logic of attaching a source JAR to a publication to the
components management part, as building a source JAR will be done
differently for Android.

(cherry picked from commit 9a2dce7ea5)
2019-01-11 20:42:19 +03:00
Sergey Igushkin
f42336950f Allow a target to have multiple publications, restructure the code
Instead of exposing a single `component` in a target, allow it to have a
set of `components`, then create a Maven publication for each of the
components.

Move `createUsageContexts` to private API since a target that has
multiple publications may need to create the usage contexts for those
publications differently.

Move some of the components technical stuff to interfaces
`DelegatedToPublication` and
`ComponentWithCoordinatesDelegatedToPublication` in order to reuse it
later for Android's components.

(cherry picked from commit d211bd53c9)
2019-01-11 20:41:54 +03:00
Sergey Igushkin
726901291e refactor: Support creating AndroidProjectHandler from outside the plugin
(cherry picked from commit a6b55cc5d7)
2019-01-11 20:41:32 +03:00
Ilya Gorbunov
f7712fc351 Avoid hitting max argument limit in String(chars)
Rewrite CharArray to String conversions to appending chars one by one.

Refine parameter checking in String(chars, offset, length) to adhere to
the common exception contract and document it.

#KT-29003

(cherry picked from commit 30c769c19a)
2019-01-11 19:33:57 +03:00
Pavel Punegov
4fa215eb47 Replace class instantiation with object in JS tests
(cherry picked from commit dc8cb103c5)
2019-01-11 17:45:00 +03:00
Pavel Punegov
84f173e75a DefaultAsserter object. Add function to replace constructor invoke.
(cherry picked from commit 1c4ecd287d)
2019-01-11 17:44:41 +03:00
Pavel Punegov
1a885cf1f4 Make kotlin.test asserter be ThreadLocal
(cherry picked from commit ac0f612781)
2019-01-11 17:44:24 +03:00
Pavel Punegov
898cbf974a Exclude native annotations in JS IR tests
(cherry picked from commit 4b3693bf37)
2019-01-11 17:42:53 +03:00
Pavel Punegov
386a3ee83e Add ThreadLocal and SharedImmutable native annotations as OptionalExpectation
to kotlin.native.concurrent

(cherry picked from commit 122ec85bf0)
2019-01-11 17:42:22 +03:00
Mikhael Bogdanov
392ab05f5f Delete dead code on last optimization step, otherwise ASM will split exception table on it.
ASM has logic that splits exception tables in MethodWriter.computeAllFrames:
     // Loop over all the basic blocks and visit the stack map frames that must be stored in the
     // StackMapTable attribute. Also replace unreachable code with NOP* ATHROW, and remove it from
     // exception handler ranges.
     ...
     firstHandler = Handler.removeRange(firstHandler, basicBlock, nextBasicBlock);
     ...
  https://gitlab.ow2.org/asm/asm/issues/317867

  #KT-28546 Fixed

(cherry picked from commit 2bdf68ad67)
2019-01-11 15:29:57 +01:00
Mikhael Bogdanov
547c6ab897 Temporary disable line numbers generation for default values from expect declarations
Proper SMAP support for default values from expect declarations is required.
 Default value in expect declaration could has line number that
 exceed line count in actual file that causes an error

  #KT-23739 Fixed
  #KT-29174 Open

(cherry picked from commit 306a982722)
2019-01-11 15:29:50 +01:00
Andrey Uskov
231e5679b1 Create Kotlin SDK on load or import project with JS/Common modules
#KT-22590 Fixed
2019-01-11 17:05:24 +03:00
Andrey Uskov
03389cd249 Fix scope detection for MPP projects
#KT-27718 Fixed
#KT-28626 Fixed
2019-01-11 17:04:52 +03:00
Andrey Uskov
42c53b5d76 Change task creation with task registration in Kotlin plugin
#KT-27657 Fixed

(cherry picked from commit b6aed5b98a)
2019-01-11 17:03:56 +03:00
Mikhail Zarechenskiy
d303ae5c28 Fix dependency for Gradle integration tests module
After d5ebe2e6
2019-01-11 14:48:04 +03:00
Mikhail Glukhikh
b47636ba9d IDEA plugin: remove "Show FIR action" and fir-view without fir.enabled
#KT-28813 Fixed
(it's planned to include FIR in artifacts after 1.3.30)

(cherry picked from commit 4fd773a38b)
2019-01-11 13:50:15 +03:00
Sergey Rostov
911748fde2 JPS: exclude source roots from other targets
Previously `findJavaRootDescriptor` was return source root for random
module. This cause build errors for mpp (same file may appear in
multiple source roots of common and platform modules)

#KT-28988 Fixed

(cherry picked from commit 75e59fdc46)
2019-01-11 13:18:01 +03:00
Dmitry Savvinov
682f15f248 Introduce specific version of NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY for KT-28061
In 1.3.0 there was introduced KT-28061 bug, which caused some of the
NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY diagnostics to be lost (turning
"red" code into "green")

500dc11514 fixes the bug and returns
lost diagnostics back. This commit adds additional information for some
of the cases where diagnostics were list and then brought back (for the
user sanity).

The heuristic used for detecting cases which need additional information
is simple: if function has return in in-place called lambda, and
NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY should be reported, then we
enhance it with additional information.

^KT-28061 Fixed
2019-01-11 11:46:30 +03:00
Ilya Matveev
91b08d374b Fix linkTaskName getters of K/N compilations 2019-01-11 13:23:05 +07:00
Ilya Matveev
0cc417c97b Support getting the default K/N test binary from a compilation
Fix for https://github.com/JetBrains/kotlin-native/issues/2487
2019-01-11 13:22:58 +07:00
Mikhail Zarechenskiy
169155d854 Reorganize dependencies around kotlin-compiler.jar
#KT-26807 Fixed
2019-01-11 00:19:44 +03:00
Ilya Gorbunov
3f8f53cb8c Remove redundant clause from 'until' function docs
(cherry picked from commit 9289a2c573)
2019-01-10 22:56:00 +03:00
Bernhard Posselt
6fc756c4c0 Add documentation on how merging works for toMap() for Iterables, Arrays and Sequences
(cherry picked from commits 300f68e0d8, 19906f13ea)
2019-01-10 22:54:39 +03:00
Denis Zharkov
6a8ef4ac1a Fix exception in ultra-light classes in case of complex mpp hierarchy
Without the introduced override, default implementation of isEquivalentTo
runs delegate computation of `another` that is illegal
for KtUltraLightClass

^KT-28912 Fixed
2019-01-10 14:12:10 +03:00
Ilya Matveev
4aaf36131f One more fix for MinGW path in K/N runner 2019-01-10 18:02:47 +07:00
Ilya Chernikov
f2e1b0bc22 Add import support to main-kts, with test 2019-01-10 10:56:37 +01:00
Ilya Chernikov
ec6b1dc1e5 Add shared script instances support, fix and refactor evaluation accordingly
also fix arguments order in the evaluator
2019-01-10 10:56:37 +01:00
Ilya Chernikov
aa2315f378 Add mapping function for transformations with ResultsWithDiagnostics
also improve chaining helpers
2019-01-10 10:56:37 +01:00
Ilya Chernikov
28b91ce848 [minor] add comment to the "Fix locking in script definition provider" commit 2019-01-10 10:56:36 +01:00
Ilya Chernikov
3c7e57d9c4 [minor] fix scripting test on windows 2019-01-10 10:56:36 +01:00
Yan Zhulanow
dfd163af34 Fix 'CommandLineProcessor' extension point calling, switch it to using ServiceLoaderLite 2019-01-09 22:05:53 +03:00
Yan Zhulanow
8b24dd98f6 Remove JPS support for Android Extensions 2019-01-09 22:05:49 +03:00
Ilya Matveev
4b4a709e86 Fix MinGW path in Kotlin/Native runner 2019-01-09 20:48:21 +07:00
Mikhael Bogdanov
0c4c6860be Add tests for Obsolete issues
#KT-18977 Obsolete

(cherry picked from commit f7ce8c18c6)
2019-01-09 10:22:08 +01:00
Mikhael Bogdanov
d6fcc35f17 Add test for Obsolete issues
#KT-15956 Obsolete
 #KT-15751 Obsolete
 #KT-16417 Obsolete
 #KT-21787 Obsolete

(cherry picked from commit 9a059809bf)
2019-01-08 14:05:05 +01:00
Mikhael Bogdanov
0602baa38e Avoid ConcurrentModificationException
#KT-26384 Fixed

(cherry picked from commit 6a19e45e27)
2019-01-08 13:58:30 +01:00
Mikhael Bogdanov
c9ac71dd8d Proper resort variables on inlining lowered ir closures
Original problem is that lowered ir closures doesn't meet inliner expectations
 about captured variable position in inlining method.
 E.g.: Call 'foo(valueParam) { capturedParam }' to
  inline function 'foo' with declaration

      inline fun foo(valueParam: Foo, inlineParamWithCaptured: Bar.() ->) ....

 is reorganized through inlining to equivalent call foo(valueParam, capturedParam1, cp2 ...).
 But lowered closure for lambda parameter has totally different parameters order:

     fun loweredLambda$x(extensionReceiver, captured1, cp2..., valueParam1, vp2...)

 So before inlining lowered closure should be transformed to

     fun loweredLambda$x(extensionReceiver, valueParam1, vp2..., captured1, cp2..)

 #KT-28547 Fixed

(cherry picked from commit 02d9c526e2)
2019-01-03 08:42:52 +01:00
Mikhael Bogdanov
e04959a939 Update copyright in generated FIR related stuff
(cherry picked from commit fcf8ea44b2)
2019-01-03 08:30:53 +01:00
Mikhael Bogdanov
a399539094 Regenerate builtins
(cherry picked from commit dfee1787e5)
2019-01-03 08:30:46 +01:00
Mikhael Bogdanov
d71e0fc7c3 Update copyright in generated non-compiler tests
(cherry picked from commit e963c52c80)
2019-01-03 08:30:38 +01:00
Mikhael Bogdanov
ac870129df Add test for obsolete KT-17431 issue
#KT-17431 Obsolete

(cherry picked from commit e0bcba5c0e)
2019-01-03 08:30:28 +01:00
Mikhael Bogdanov
7f485172a8 Update copyright in generated compiler tests
(cherry picked from commit cf47bc0130)
2019-01-03 08:29:53 +01:00
Mikhael Bogdanov
df4cbd50d6 Properly find invoke method on default lambda inlining
In general case parameter type could differ from actual default lambda type.
  E.g.: fun inlineFun(s: (Child) -> Base = { a: Base -> a as Child}),
  where type of default lambda is '(Base) -> Child'.
  In such case we should find somehow actual invoke method in bytecode knowing
  only name, number of parameters and that's actual invoke is non-synthetic
  regardless of bridge one.

  #KT-21946 Fixed

(cherry picked from commit 6bf70a5dd2)
2019-01-03 08:29:09 +01:00
Ilmir Usmanov
066ecd5308 Fix test data 2018-12-28 20:02:27 +03:00
Ilmir Usmanov
30c7b3cc1d Support val initialization in non-inline function with EXACTLY_ONCE effect
by generating a box for the value.
 #KT-26126 Fixed
2018-12-28 15:22:24 +03:00
Ilmir Usmanov
38bc99d792 Put default value (null or zero) to slot for uninitialized values
This way range of the variable is correct in LVT.
 #KT-24672 Fixed
2018-12-28 15:22:20 +03:00
Alexander Udalov
88ed2e268f Fix loading default Java annotation values in actual typealias from binary classes
#KT-22704 Fixed

(cherry picked from commit 8ab9226805)
2018-12-28 13:03:34 +01:00
Alexander Udalov
720a35bc26 Use fast .class file reading implementation in boxAgainstJava tests
Since these tests compile Kotlin code against compiled Java code, it's
only reasonable to use the same .class file reading implementation as is
used in production for the same purpose

(cherry picked from commit 3fee84b966)
2018-12-28 13:03:32 +01:00
Ilmir Usmanov
e141441bf5 Update test data
#KT-28309
2018-12-28 14:42:05 +03:00
Ilmir Usmanov
f50f9d069f Do not spill fake variables
#KT-28309
2018-12-28 14:42:04 +03:00
Ilmir Usmanov
c4f99b850b Add continuation parameter of suspend lambda's invoke to frame map
thus it will not overlap with $i$a and $i$f fake variables.
 #KT-28309
2018-12-28 14:42:03 +03:00
Ilmir Usmanov
8e3eb04271 Set type of inliner's fake variable slots to int by storing 0
Otherwise, D8 drops the whole LVT.
 #KT-28309 Fixed
2018-12-28 14:42:02 +03:00
Nicolay Mitropolsky
75987697db Light-annotations: fix for reading class-literal varargs (KT-29027, IDEA-204252)
(cherry picked from commit ebd6caaa71)
2018-12-28 11:50:38 +03:00
Nikolay Krasko
1c93018db4 Remove assertion with selection in 1.3.20 2018-12-27 21:32:54 +03:00
Mikhail Glukhikh
6fa26c5356 Improve expect / actual markers on one line
Before this commit, only one-line enums and annotation classes were
considered. Now we can have enum header on one line and
some entries on another lines, and it still works.
Same with primary constructor parameters.

#KT-22637 Fixed

(cherry picked from commit 8de2ff2163)
2018-12-27 20:24:01 +03:00
Mikhail Glukhikh
e97009bd49 Do not report "redundant arrow" with parameters without expected type
#KT-29049 Fixed
Part of KT-29005

(cherry picked from commit cdef811c55)
2018-12-27 20:23:43 +03:00
Nikolay Krasko
6ae156c8a4 Add UI options for comments generation (KT-5590)
#KT-5590 Fixed
2018-12-27 19:56:22 +03:00
Dmitry Petrov
595d55707c Support inline classes in javaObjectType/javaPrimitiveType
#KT-28290
2018-12-27 15:27:21 +03:00
Natalia Selezneva
9fbc71475b Scratch: move 'Make module' checkbox closer to modules combobox
(cherry picked from commit 022b21efa0)

^KT-28910
2018-12-27 09:01:29 +03:00
Natalia Selezneva
a13c744533 Set scratch file extension using API for IDEA 182 or higher
(cherry picked from commit 404c3ea57b)
2018-12-27 09:01:09 +03:00
Natalia Selezneva
f2f1e923ee Script tests: check that script is highlighted
(cherry picked from commit 6eff314b9d)
2018-12-27 09:00:53 +03:00
Natalia Selezneva
0905c6ba27 Refactoring: move scratch options to ScratchFile from ScratchPanel
(cherry picked from commit d389c9fd85)
2018-12-27 09:00:40 +03:00
Natalia Selezneva
0ebe31af73 Scratch: do not show error message when scratch execution is cancelled by user
(cherry picked from commit a408711f37)
2018-12-27 09:00:29 +03:00
Natalia Selezneva
846fb60c91 Refactoring: unify methods to report errors in scratches
(cherry picked from commit 2fbbf2400d)
2018-12-27 09:00:17 +03:00
Natalia Selezneva
ce36fc594f Refactoring: move test output handler to separate class
(cherry picked from commit 2f32c6e164)
2018-12-27 09:00:03 +03:00
Natalia Selezneva
9e6db690d5 Refactoring: add composite output handler to avoid multiple forEach calls
(cherry picked from commit 392e69c690)
2018-12-27 08:59:50 +03:00
Natalia Selezneva
1702c8df25 Scratch: implement stop action
(cherry picked from commit 2511f70bd9)

^KT-28643 Fixed
2018-12-27 08:59:38 +03:00
Natalia Selezneva
88fcbdd079 Scratch: get scratch panel from selected editor
CommonDataKeys.EDITOR key isn't present for some events (for example when user click on isRepl checkbox on scratch panel or there isn't any file open in the editor)

(cherry picked from commit d403514cee)

^KT-28045 Fixed
2018-12-27 08:59:13 +03:00
Natalia Selezneva
8015483db6 Refactoring: use output handlers to make action enabled or disabled
(cherry picked from commit 59a32ff94d)
2018-12-27 08:58:48 +03:00
Leonid Startsev
e644c05b31 Make serialization plugin for Maven consistent with all other plugins:
Use correct import handler because old one was not working in IDE
Change maven artifact id to match pattern from other plugins

(cherry picked from commit 662c1b6d4a)
2018-12-26 18:54:39 +03:00
Mikhail Glukhikh
1220ef51b5 Support '.toType()' and literal fixes related to unsigned type mismatch
#KT-26836 Fixed

(cherry picked from commit 8420fceb8c)
2018-12-26 18:43:54 +03:00
Mikhail Glukhikh
624a4802b4 Do not suggest cast for SIGNED_CONSTANT_CONVERTED_TO_UNSIGNED
Related to KT-27590

(cherry picked from commit 73b6148407)
2018-12-26 18:43:39 +03:00
Mikhail Glukhikh
7aef1a9073 Suggest quick-fixes for SIGNED_CONSTANT_CONVERTED_TO_UNSIGNED
#KT-27590 Fixed

(cherry picked from commit d7ce79cc76)
2018-12-26 18:43:24 +03:00
Mikhail Glukhikh
774b5408b6 More tests for KT-28997, fix isLocal for anonymous object in script
(cherry picked from commit a9147ff446)
2018-12-26 18:43:10 +03:00
Mikhail Glukhikh
ac867bb063 Fix light class generation for local classes in scripts
Before this commit, we used script context for all classes
defined in script. However, for local classes in scripts it's mistake,
and now we generate them as usual, despite of the fact we are in script.

#KT-28997 Fixed

(cherry picked from commit 661ac711c0)
2018-12-26 18:42:56 +03:00
Mikhail Glukhikh
9583b05160 Extract 'PsiElement.hasJavaResolutionFacade()' (related to KT-28199)
(cherry picked from commit 7d51be17c8)
2018-12-26 18:42:40 +03:00
Mikhail Glukhikh
a0e3340a03 Launch constructor delegation search only for elements from a file
This should fix EA-133791

(cherry picked from commit d599bb160f)
2018-12-26 18:42:22 +03:00
Mikhail Glukhikh
7b68e5b74e Launch convention method reference search only for elements from a file
#KT-28199 Fixed

(cherry picked from commit 399ec5c961)
2018-12-26 18:42:06 +03:00
Nikolay Krasko
debc248a78 Check file is valid before executing toPsiFile (EA-133882) 2018-12-26 15:47:07 +03:00
Nikolay Krasko
297f5eefb2 Consider qualified name is null if some part is null (EA-126499) 2018-12-26 15:46:59 +03:00
Natalia Selezneva
1751e7ca78 Kotlin code fragments in markdown should have script definition because they are parsed as scripts
(cherry picked from commit 9dc57567e4)
2018-12-26 08:59:40 +03:00
Natalia Selezneva
30b5535dc1 Create one instance of StandardIdeScriptDefinition per project
ScriptModuleInfo for scripts outside source roots in compared by virtualFile and script definition.
So when we use ScriptDefinitionsManaged.getDefaultScriptDefinition we shouldn't create a new one on each call

EA-132810 - assert: DiagnoseUnknownModuleInfoReporter.report

(cherry picked from commit 4e6fb84bae)
2018-12-26 08:59:05 +03:00
Natalia Selezneva
973622bc60 Remove ScriptModificationListener from 183 branch
Since 183 changes in .gradle.kts files are tracked correctly by platform and notification 'Gradle project needs to be imported' is shown when those files are modified

(cherry picked from commit ba2f211384)
2018-12-26 08:58:45 +03:00
Natalia Selezneva
cfa3422644 Scripts: fix NPE during accessing ScriptDependenciesCache
Getting value from SLRUMap needs write lock, because it can move value from one queue to another
EA-105195 Fixed

(cherry picked from commit 6042a3a0f7)
2018-12-26 08:58:28 +03:00
Natalia Selezneva
00a4365752 Fix 'Invalid file' exception during script dependencies update
Fix EA-125840 - assert: FileManagerImpl.findFile

(cherry picked from commit 8ceae8bd6d)
2018-12-26 08:58:11 +03:00
Natalia Selezneva
cfd030ac8d Fix order of initialization of project language version in ConfigureKotlinTest
Project.getLanguageVersion with contextModule == null returns latest stable version.
But Module.getLanguageVersion save it's version to project setting if useProjectSettings checkbox is selected.
So Project.getLanguageVersion can return different versions before and after invocation Module.getLanguageVersion

(cherry picked from commit 816a8d74a2)
2018-12-26 08:57:53 +03:00
Andrey Uskov
6230af0f3b Fix reimport of Kotlin projects created via wizard
#KT-27941 Fixed
2018-12-24 17:11:29 +03:00
Ilmir Usmanov
0fa22c3327 Obtain correct captured suspend local function
if we call the function inside, for example, lambda.
 #KT-28844 Fixed
2018-12-24 15:58:38 +03:00
Mikhail Zarechenskiy
9ba0202d59 Prohibit JvmOverloads on constructors of annotation classes
In LV >= 1.4 & -progressive

 #KT-25702 Fixed
2018-12-24 12:51:40 +03:00
Mikhail Zarechenskiy
a967c47d1c Prohibit type parameters for local variables in LV >= 1.4 & -progressive
#KT-8341 Fixed
2018-12-24 12:51:38 +03:00
Mikhail Zarechenskiy
e8fea9d4ef Fix mapping of platform inline class types
For the inline class:
 ```
 inline class IC(val x: Int)
 ```

 Type (IC..IC?) should be mapped to the wrapper `IC`
 because it can hold object and also because it does so for primitives

 #KT-28983 Fixed
2018-12-24 12:51:36 +03:00
Ilya Chernikov
cc5cf643a8 Implement script filename extensions discovery via artifact transforms
to avoid using never-up-to-date task and make discovery cacheable and
checkable for up-to-dateness
#KT-28469 fixed
2018-12-21 15:48:38 +01:00
Ilya Chernikov
20a631a838 Fix script filename extension discovery from asm-readed class
and improve diagnostics on definition loading failure
2018-12-21 15:48:37 +01:00
Shagen Ogandzhanian
c6e5a5d72a Support named constructors in idl-backed code generation
this resolves https://youtrack.jetbrains.com/issue/KT-27361
2018-12-21 15:31:12 +01:00
Ilya Gorbunov
a6bad98241 Fix current Kotlin version to avoid changing it in local builds
(cherry picked from commit 7c7c11e916)
2018-12-21 17:24:34 +03:00
Ilya Gorbunov
7cf16d9af6 Fix link to sealed classes doc page
#KT-28829 Fixed

(cherry picked from commit 68f898153c)
2018-12-21 17:24:33 +03:00
Ilya Gorbunov
59eeb287c9 Minor: fix Random companion reference in docs
Random's companion is named 'Default' rather than 'Companion'

(cherry picked from commit 614139755c)
2018-12-21 17:24:31 +03:00
Ilya Matveev
2e14313bc8 Fix K/N test for windows: rename target usage 2018-12-21 13:04:41 +03:00
Ilya Matveev
1872b3dd1d Fix native binary tests for Windows 2018-12-21 13:04:41 +03:00
Ilya Chernikov
4c3ac350c9 [minor] use psi original file if virtual file is not available...
for script dependencies, fixes completion tests
2018-12-20 22:06:56 +01:00
Ilya Chernikov
44f8e92c6f Introduce script names and location ids, use them in diagnostics and...
for virtual file names. Also fix compiled script serialization.
2018-12-20 22:06:55 +01:00
Ilya Chernikov
f279ae5576 [minor] add missing dependency 2018-12-20 22:06:55 +01:00
Ilya Chernikov
e4f4619f37 Implement script dependencies collection tests 2018-12-20 22:06:54 +01:00
Ilya Chernikov
bff63fe902 [minor] refactor scripting tests: extract cli testdata into separate dir, remove annotation 2018-12-20 22:06:53 +01:00
Ilya Chernikov
7b6cd7305a Refactor core env: extract script compilation dependencies collection 2018-12-20 22:06:53 +01:00
Ilya Chernikov
7640718805 [minor] fix compilation - avoid proguarding of addToStdLib.kt 2018-12-20 22:06:52 +01:00
Ilya Chernikov
8830387118 Implement import test, fix import support in compiler and evaluator 2018-12-20 22:06:51 +01:00
Ilya Chernikov
908b8a4b4e Implement imported scripts evaluation and construction 2018-12-20 22:06:51 +01:00
Ilya Chernikov
3430aa24ec Implement script import support in the compiler 2018-12-20 22:06:50 +01:00
Ilya Chernikov
f3b206227a Implement simple "add to compilation" functionality for scripts
(incomplete import - scripts added to the compilation but not yet
imported into scope)
Base functionality needed for #KT-27960
2018-12-20 22:06:49 +01:00
Toshiaki Kameyama
a1d2a5ac82 Add "Convert to also" intention
#KT-28699 Fixed

(cherry picked from commit 6a4c6eacd7)
2018-12-20 15:04:49 +03:00
Mikhail Glukhikh
fc33aa9552 OverrideMemberChooserObject refactoring: introduce MemberGenerateMode
(cherry picked from commit 93882736ed)
2018-12-20 15:04:21 +03:00
Mikhail Glukhikh
2c0ecedb5a Create expect/actual class: fix inline class generation
#KT-28744 Fixed
#KT-28745 Fixed

(cherry picked from commit ca3d758fba)
2018-12-20 15:04:07 +03:00
Mikhail Glukhikh
3ba7339a46 MPP JVM/JS wizard: fix classpath of 'run' task #KT-28869 Fixed
(cherry picked from commit d3a5b0dcd6)
2018-12-20 15:03:27 +03:00
Mikhail Glukhikh
e449f18fc0 MPP wizard tests: use 1.3.20-eap-25
(cherry picked from commit 55666f3f03)
2018-12-20 15:03:08 +03:00
Vasily Levchenko
7def3c19dc Update Kotlin/Native: RC2 1.1.0.5323 2018-12-19 12:33:59 +03:00
Vasily Levchenko
fc46a7704c Update Kotlin/Native: RC2 1.1.0.5323 2018-12-19 00:12:46 +03:00
Shagen Ogandzhanian
4d06db6852 Support ClipboardEvent in definitions generated from idl 2018-12-18 15:11:06 +01:00
Shagen Ogandzhanian
883dbfe138 Introduce TrackEvent, MediaStreamTrackEvent-related IDL definitions 2018-12-18 15:10:58 +01:00
Alexey Tsvetkov
d6f388845d Refactor: move logging code to org.jetbrains.kotlin.gradle.logging 2018-12-18 15:29:55 +03:00
Alexey Tsvetkov
2e9a596b53 Report compiler messages from daemon in Gradle thread
#KT-28836 fixed

RMI messages are reported from RMI threads.
When Gradle logger is used from non-Gradle thread,
messages are not grouped in command-line
and they are not shown in build scans.
To fix this, we store all messages from Kotlin daemon
in a buffer, then report them from a Gradle thread.
2018-12-18 15:29:55 +03:00
Alexey Tsvetkov
da86804719 Use task's logger where appropriate
KT-28836

Using project's logger prevents messages
from showing in task's output (in command-line and build scans)
2018-12-18 15:29:55 +03:00
Ilya Matveev
2bbbf9677f Add a klib export method consuming a configure action 2018-12-18 18:08:20 +07:00
Ilya Matveev
543671227d Don't create run tasks for non-host targets 2018-12-18 18:08:20 +07:00
Ilya Matveev
5b5262eedf Change executable of a run task when binary's baseName is changed 2018-12-18 18:08:20 +07:00
Ilya Matveev
42ad282dee Add tests for new binaries DSL 2018-12-18 18:08:20 +07:00
Ilya Matveev
23b0143688 Fix existing MPP tests 2018-12-18 18:08:20 +07:00
Ilya Matveev
1e782311e5 Don't hardcode a toolchain path for K/N on Windows 2018-12-18 18:08:20 +07:00
Ilya Matveev
7eae8ccc09 Fix error message about incorrect kotlin.native.home property 2018-12-18 18:08:20 +07:00
Ilya Matveev
375e46b91f Support aggregate tasks to build binaries per compilation 2018-12-18 18:08:20 +07:00
Ilya Matveev
cfdfdcb954 Support free compiler args for binaries 2018-12-18 18:08:20 +07:00
Ilya Matveev
819c6e5a51 Allow changing base name for a Kotlin/Native binary 2018-12-18 18:08:20 +07:00
Ilya Matveev
2b1d2ea2fe Support bitcode embedding for frameworks 2018-12-18 18:08:20 +07:00
Ilya Matveev
e20444e441 Support -Xexport-library for K/N in the MPP plugin 2018-12-18 18:08:20 +07:00
Ilya Matveev
c71c2fba05 Provide aggregate link tasks 2018-12-18 18:08:20 +07:00
Ilya Matveev
fb5095f94e Provide an extended DSL for final native binaries
In 1.3.0 only basic settings for final native binaries (e.g.
executables or frameworks) are available. They allow a user to
specify what kinds of binaries should be produced from one or another
compilation but they don't allow specifying different options for
different binaries or creating more than 2 (debug and release)
binaries of the same kind (e.g. executable) from the same
compilation. Also link tasks for these binaries are created after
project evaluation thus they are inaccessible for a user outside
of an afterEvaluate block.

This patch adds an extended binary DSL allowing a user to declare
binaries independently from compilations and to specify different
options (e.g. linker arguments) for different binaries. Also
link tasks for binaries declared in this DSL are created at a
configuration time so user can access them outside of an
afterEvaluate block.

Also this patch adds creating run tasks for all executables
declared in the buildscript (KT-28106)

Initial DSL methods for binaries declaration are still supported.

Kotlin DSL example is the following:

kotlin {
    macosX64 {
        binaries {
            // Create debug and release executable with
            // a name prefix 'Foo'.
            // Two domain objects will be created:
            // fooDebugExecutable and fooReleaseExecutable
            executable("Foo", listOf(RELEASE, DEBUG)) {
                compilation = compilations["foo"]
                entryPoint = "foo.main"
                linkerOpts.add("-Llib/path")
                println(runTask.name)
            }

            // Name prefix and build types are optional.
            // debugFramework and releaseFramework are created here.
            framework()
        }
    }
}
2018-12-18 18:08:20 +07:00
Mikhail Zarechenskiy
ac77446657 Fix unbound class literals for inline classes
#KT-28361 Fixed
2018-12-18 11:37:54 +03:00
Denis Zharkov
7c66d0e3a6 Minor. Add a comment to KtLightElement::givenAnnotations 2018-12-18 09:32:27 +03:00
Denis Zharkov
c7634fb41a Create annotation arguments in ultra-light classes via PsiElementFactory 2018-12-18 09:32:27 +03:00
Denis Zharkov
d634db2d82 Restrict search scope for KtUltraLightParameter
^KT-28365 Fixed
2018-12-18 09:32:27 +03:00
Denis Zharkov
43482f60ae Fix throws-list for case of kotlin.Throwable in ultra-light classes 2018-12-18 09:32:27 +03:00
Denis Zharkov
b940b64d06 Do not generate no-arg constructor for sealed ultra-light class 2018-12-18 09:32:27 +03:00
Denis Zharkov
72e42ba2cb Support annotation based on descriptor in ultra-light classes
It helps to generate properly the annotations for delegates
Also note in test, that annotations in Base class have really weird
text of arguments and also don't have names
2018-12-18 09:32:27 +03:00
Denis Zharkov
20766dce65 Minor. Introduce typeMapper val into UltraLightSupport
To avoid multiple creation
2018-12-18 09:32:27 +03:00
Sergey Igushkin
34199c5d92 Fix Gradle 5.0 deprecation warnings:
* DefaultSourceDirectorySet constructor is deprecated -> objects()
* IvyRepository.layout('pattern') { } is deprecated -> patternLayout { }

Issue #KT-26808 Fixed

(cherry picked from commit 67e82a54e5)
2018-12-17 20:07:46 +03:00
Sergey Igushkin
816976035b Fix the localToProject attribute schema for Gradle 4.10.2+
In Gradle 4.10.2, a change was made in the attributes disambiguation
process: if some of the candidates have a single attribute value and
others don't have that attribute (i.e. have a null value), the
disambiguation rule for that attribute doesn't get called.
Effectively, null values are excluded from disambiguation, but still may
cause ambiguity (sic!)

See: https://github.com/gradle/gradle/issues/6747#issuecomment-445921139

This change affected our attribute `localToProject` that we use to
disambiguate the deprecated but still consumable configurations like
`compile`, `runtime`, `testCompile`, `testRuntime` from those
configurations which should have priority during project dependency
resolution: the `*Element` ones. Our scheme marked the former
configurations with the attribute and the latter were not marked, with
a disambiguation rule that preferred null values.

To fix this logic with Gradle 4.10.2, we instead mark both kinds of
configurations with the attribute, which now has a value 'public'
that is preferred by the rule over the other values. We also make sure
that the attribute doesn't leak into the published Gradle metadata, as
it is only needed for project-to-project dependencies resolution.

Issue #KT-28795 Fixed

(cherry picked from commit 557fb07f44)
2018-12-17 20:07:46 +03:00
Sergey Igushkin
8df408122f Workaround for ConcurrentModificationException in KotlinModelBuilder
In Gradle 5.0, iterating over the `.withType<...>()` result below
caused a ConcurrentModificationException. Workaround that by first
collecting the items into a list.

(cherry picked from commit 2349aaf488)
2018-12-17 20:07:45 +03:00
Sergey Igushkin
f349b92896 Fix some tests for Gradle 5.0 and update some dependency versions
* Introduce GradleVersionRequired.InRange and thus prevent older
tests (e.g. Android 2.3.0) from running with newer Gradle versions

* Add a task outputs pattern suitable for Gradle 5.0

* Run some of the Android tests with AGP 3.1.0 (and Gradle 4.4) instead
of 3.0.0 to ensure compatibility with Gradle 5.0

* Update test projects according to Gradle 5.0 dropped deprecated
features: classesDir, left-shift operator, default org.gradle.util.*
imports

* Fix a Gradle test after Gradle 5.0 changed `publishing` behavior to
run the closure eagerly rather than after evaluation

(cherry picked from commit d7522e2283)
2018-12-17 20:07:45 +03:00
Sergey Igushkin
f221a6794b Advance test Gradle version to 5.0
(cherry picked from commit 5f21ced26b)
2018-12-17 20:07:45 +03:00
Shagen Ogandzhanian
037b7a5f5e Introduce idl definition for SVGMaskElement 2018-12-17 16:25:15 +01:00
Alexey Tsvetkov
39af8f3994 Enable JS IC by default
#KT-28842 Fixed
2018-12-17 15:46:42 +03:00
Alexey Tsvetkov
fd192f811e Add project property to disable AP discovery in compile classpath
AP discovery in compile classpath can be disabled in all subprojects
by adding "kapt.include.compile.classpath = false" to 'gradle.properties' file.

KT-24530

The setting can be overrided per project by using KAPT DSL
in a 'build.gradle' file:
```
kapt {
    includeCompileClasspath = false
}
```
2018-12-17 15:42:22 +03:00
Mikhael Bogdanov
d83e2afcdf Use last ASM version to read binaries
#KT-28798 Fixed

(cherry picked from commit 1a0c3dfaa6)
2018-12-17 12:20:23 +01:00
Yan Zhulanow
45e5013097 Fix a compilation error after rebase 2018-12-17 18:47:13 +09:00
Alexey Tsvetkov
24aa636283 Test that javac is loaded once when worker is reused 2018-12-16 04:29:38 +03:00
Ting-Yuan Huang
2884cfc9e4 Cache classloaders for tools.jar and kapt in Gradle workers
#KT-28852 fixed

The loaders and hence some classes were repeatedly loaded and
jit-compiled everytime when KaptExecution were dispatched. Those
classes, like JavaCompiler, can be very large and therefore created a
significant overhead. In some projects, the overhead accounted for more
than 40% of total CPU time of annotation processing.

This change tries to cache the classloaders so that they won't be
reloaded and re-jitted.
2018-12-16 04:29:34 +03:00
Alexey Tsvetkov
2cc7bab0ff Run in-process compiler in separate thread
The compiler uses thread local values,
so when the compiler runs Gradle's thread,
it leaks classes preventing
a compiler's classloader from being collected.

    #KT-28037 fixed
2018-12-16 03:32:42 +03:00
Alexey Tsvetkov
f3bef7e48b Minor: remove unused util 2018-12-16 03:32:39 +03:00
Alexey Tsvetkov
7717921574 Print stacktrace to Gradle logger instead of writing directly to stderr 2018-12-16 03:32:36 +03:00
Shagen Ogandzhanian
08180d95e9 Introduce better typing for on[event-name] attributes from idl
see https://upsource.jetbrains.com/kotlin/review/KOTLIN-CR-2548
2018-12-14 16:22:39 +01:00
Denis Zharkov
318f8e2891 Transform KotlinClassFinder::findKotlinClass to extension 2018-12-14 11:51:24 +03:00
Denis Zharkov
724fa51fb4 Avoid multiple subsequent reading of the same class-file in front-end
^KT-23466 Fixed
2018-12-14 11:51:24 +03:00
Denis Zharkov
68aa525877 Minor. Reformat BinaryJavaClass 2018-12-14 11:51:24 +03:00
Denis Zharkov
51c4a10276 Convert JavaClassFinder.java to kotlin 2018-12-14 11:51:24 +03:00
Denis Zharkov
75572882a3 Convert JavaClassFinder.java to kotlin: rename file 2018-12-14 11:51:24 +03:00
Denis Zharkov
b731b02eda Minor. Reformat LazyJavaPackageScope.kt 2018-12-14 11:51:24 +03:00
Shagen Ogandzhanian
f5d28808c8 Introduce PointerEvent-related definitions
* Resolves https://youtrack.jetbrains.com/issue/KT-23932
 * Backed by review https://upsource.jetbrains.com/kotlin/branch/KT-23932-POINTER-EVENT-FROM-REMOTE-IDL
2018-12-13 21:46:59 +01:00
Shagen Ogandzhanian
5b206eeee6 Support float initializers in fun params generated from idl definitions 2018-12-13 21:46:40 +01:00
Shagen Ogandzhanian
f29926006b Add mininal test suite to idl2k, remove deprecated ANTLRFileStream 2018-12-13 21:42:42 +01:00
Alexey Tsvetkov
9dc11b2dd7 Make AbstractJvmAbiContentTest system independent 2018-12-13 21:23:20 +03:00
Alexey Tsvetkov
4422fd220a Register classpath as inputs of SmartJavaExec tasks 2018-12-13 21:23:17 +03:00
Ilya Chernikov
0731ad4bf0 [minor] get rid of obsolete "environment" wording 2018-12-13 18:04:43 +01:00
Ilya Chernikov
7dc3797e85 Refactor scripting - rename env vars to provided properties everywhere 2018-12-13 18:04:42 +01:00
Ilya Chernikov
4c81b4d4a7 Add generic interfaces to dependency resolvers 2018-12-13 18:04:42 +01:00
Ilya Chernikov
2c907e800a Add script config refinement before compilation into API 2018-12-13 18:04:41 +01:00
Ilya Chernikov
fe16ac8628 Add UrlScriptSource 2018-12-13 18:04:40 +01:00
Ilya Chernikov
a11dd0a7b5 [minor] copy utility fun to reduce dependencies 2018-12-13 18:04:39 +01:00
Ilya Chernikov
3bd19503b0 Fix vararg argument mapping for generic args convertor 2018-12-13 18:04:39 +01:00
Roman Artemev
c52204359b Update changelog 1.3.20 EAP1 2018-12-13 19:41:51 +03:00
Ivan Gavrilovic
51fc596aa9 Complete Java usage tracker if analysis extension finishes (KT-27487)
In cases when kapt compiler plugin runs in stubs generation mode,
Java usage tracker was not completed. This caused issues with
the incremental compilation if Java files changed.

E.g. if a constant defined in Java source file changed, stubs
would not be recompiled because the Java usage tracker would
not report changed type. This commit fixes that issue.
2018-12-13 17:13:41 +03:00
Alexander Udalov
0cfbd1a27f Fix isInitialized for companion lateinit properties
Instead of trying to access a missing field `Foo.foo`, call the
synthetic accessor `Foo.access$getFoo$cp` which, as per previous commit,
no longer contains the lateinit assertion

 #KT-21862 Fixed

(cherry picked from commit 8c74312cf6)
2018-12-13 14:13:02 +01:00
Alexander Udalov
5da0d8f060 Move lateinit assertion for companion property to companion object
Previously, for a property named `x` in the companion object of a class
named `Foo`, we generated:
- `Foo.access$getX$cp`, consisting of `GETFIELD Foo.x` and lateinit
  assertion
- `Foo.Companion.getX`, consisting of `INVOKEVIRTUAL Foo.access$getX$cp`

Now, we generate:
- `Foo.access$getX$cp`, consisting of `GETFIELD Foo.x`
- `Foo.Companion.getX`, consisting of `INVOKEVIRTUAL Foo.access$getX$cp`
  and lateinit assertion

The reason is that this way we can avoid generating another accessor and
reuse `Foo.access$getX$cp` in case `isInitialized` is called on a
lateinit property from companion.

For private properties, getX is not generated, but instead the assertion
is generated on each access to the field (which can be improved, see
KT-28331). The same happens for access to non-private properties from
inside the same context where they're declared.

 #KT-21862 In Progress

(cherry picked from commit 43413fcc44)
2018-12-13 14:13:00 +01:00
Alexander Udalov
d0969e77dd Minor, reformat & fix warnings in intermediateValueForProperty
(cherry picked from commit 8617365983)
2018-12-13 14:12:59 +01:00
Mikhail Glukhikh
b4101ef2ae Add "Ambiguous context due to scope receiver in suspend fun" inspection
#KT-28696 Fixed

(cherry picked from commit a15b47c93c)
2018-12-12 18:22:53 +03:00
Mikhail Glukhikh
edd4f283c6 Refactor "change type to mutable" in suspicious collection reassignment
Related to KT-20626

(cherry picked from commit 42fa6ce6f0)
2018-12-12 18:22:40 +03:00
Mikhail Glukhikh
7d07329292 Change description of boolean argument/augmented assignment inspections
(cherry picked from commit b17ee60c6f)
2018-12-12 18:22:26 +03:00
Mikhail Glukhikh
1eadec5432 Boolean literal arguments: check previous arg, fix all args in a row
(cherry picked from commit 13b09f532c)
2018-12-12 18:22:11 +03:00
Mikhail Glukhikh
0a33859eb2 Boolean literal arguments: do not highlight with single boolean argument
(cherry picked from commit 235b50d86e)
2018-12-12 18:21:59 +03:00
Mikhail Glukhikh
9a0f3f9e57 Boolean literal arguments: don't report on a call, just on an element
(cherry picked from commit d31e0b9632)
2018-12-12 18:21:44 +03:00
Toshiaki Kameyama
2a7bb8d13e Introduce "Boolean literal arguments" inspection #KT-2029 Fixed
(cherry picked from commit 0d7116aa5d)
2018-12-12 18:21:25 +03:00
Mikhail Glukhikh
fc9b41a05c Augmented list assignment inspection: add "replace with ordinary" fix
Relates to KT-20626

(cherry picked from commit aa9e48b9b6)
2018-12-12 18:21:11 +03:00
Mikhail Glukhikh
ac16907f1c Don't highlight "replace with +=" for read-only collections
Related to KT-20626

(cherry picked from commit ed8305995e)
2018-12-12 18:20:58 +03:00
Mikhail Glukhikh
c24bbff948 Add "Suspicious collection reassignment" inspection #KT-20626 Fixed
(cherry picked from commit c560aada3d)
2018-12-12 18:20:44 +03:00
Mikhail Glukhikh
410123d0f7 Introduce KtReferenceSearch to use LocalSearchScope, when possible
This fixes a set of problems in J2K tests in 183
#KT-28368 Fixed

(cherry picked from commit 3e936f64bf)
2018-12-12 18:20:28 +03:00
Leonid Startsev
04cb2265d8 Declare real external symbols for overriden by synthetic function
instead of unbound

Unbound symbols were throwing an exception on attempt to analyze them
in the other parts of compiler and are generally incorrect

(cherry picked from commit fdf4f02dde)
2018-12-12 17:31:54 +03:00
Yan Zhulanow
d5e1fc24e0 Evaluator: Render inline class values using its toString() implementation (KT-27414) 2018-12-12 21:42:21 +09:00
Yan Zhulanow
7725f0d1d7 Kapt: Switch to more appropriate way of converting URIs to Files 2018-12-12 21:42:20 +09:00
Yan Zhulanow
6e3494d83c Fix Android Lint tests (182 bunch only) 2018-12-12 21:42:19 +09:00
Yan Zhulanow
3cfee99ac6 Remove Lint tests for annotation argument API check.
Looks like newer Lint API checker ignores type usage in annotations, so these tests are no more needed.
2018-12-12 21:42:18 +09:00
Yan Zhulanow
68cd113d83 Fix testSimple() for "Remove Parcelable" action 2018-12-12 21:42:17 +09:00
Yan Zhulanow
8de34046a8 AllOpen: Update test data (enum constructors are now private) 2018-12-12 21:42:16 +09:00
Yan Zhulanow
a2be50a223 Update debugger test data, fix the current behavior 2018-12-12 21:42:15 +09:00
Yan Zhulanow
700a7c68eb Remove a magic constant from 'KotlinLambdaMethodFilter' 2018-12-12 21:42:14 +09:00
Yan Zhulanow
d7d066d081 Revert "Remove unneeded usage of the blocking invokeInManagerThread() (KT-24282)"
This reverts commit 6c868701
2018-12-12 21:42:13 +09:00
Yan Zhulanow
a30b4af7a4 Uast: Update test data (enum constructors are now private) 2018-12-12 21:42:12 +09:00
Yan Zhulanow
55097c09a0 NoArg: Update test data (enum constructors are now private) 2018-12-12 21:42:11 +09:00
Yan Zhulanow
09c97d7a18 Kapt: Update test data (stub converter tests) 2018-12-12 21:42:10 +09:00
Yan Zhulanow
9ac928aa1b Add missing 'disallowRootAccess()' to debugger and stub tests 2018-12-12 21:42:09 +09:00
Yan Zhulanow
5322dbe3fe Fix backend tests after changing format of synthetic variables for inline functions 2018-12-12 21:42:09 +09:00
Yan Zhulanow
3927e7615a Fix quick evaluation for array expressions (KT-13268) 2018-12-12 21:42:08 +09:00
Yan Zhulanow
3a3bd4826f Fix breakpoints for the same inline function nested calls (KT-22366)
This commit changes the format of the synthetic local variables for inline functions.
2018-12-12 21:42:07 +09:00
Yan Zhulanow
148ac0471d Remove unneeded usage of the blocking invokeInManagerThread() (KT-24282) 2018-12-12 21:42:06 +09:00
Yan Zhulanow
2eba1714bc Fix evaluation for captured inline classes (KT-28487) 2018-12-12 21:42:05 +09:00
Yan Zhulanow
758db84e53 Fix evaluation for static interface methods declared in Java (KT-23585) 2018-12-12 21:42:04 +09:00
Yan Zhulanow
75f8025d6a Fix source mapping for stepping into package facades from libraries (KT-28028) 2018-12-12 21:42:03 +09:00
Yan Zhulanow
e41d8ca122 Add a LookupLocation to 'getSyntheticExtensionProperties()', use it in 'DebuggerFieldSyntheticScopeProvider' 2018-12-12 21:42:02 +09:00
Yan Zhulanow
d0b71643b7 Evaluate: Enable 'foo_field' convention only for Jvm/Common code 2018-12-12 21:42:01 +09:00
Yan Zhulanow
80d1c9a7de Refactoring: Replace 'ParametersDescriptor' with a simple 'List' 2018-12-12 21:42:00 +09:00
Yan Zhulanow
4b060b68fe Evaluate: Support synthetic 'field' variable evaluation (KT-28342) 2018-12-12 21:41:59 +09:00
Yan Zhulanow
2d10730233 Minor: Move changeSuperToMagicAccessor() function to its single use site, J2K it 2018-12-12 21:41:58 +09:00
Yan Zhulanow
53a2fb7302 Kapt: Preserve 'getJarPathForClass()' (used in kapt-cli) 2018-12-12 21:41:57 +09:00
Yan Zhulanow
09d0cba192 Evaluate: Use '<name>_field' syntax for field value evaluation (KT-14075) 2018-12-12 21:41:56 +09:00
Yan Zhulanow
a5b19826e7 Provide a default implementation for 'SyntheticScope' 2018-12-12 21:41:55 +09:00
Denis Zharkov
863be9369a Add diagnostic for calling ConcurrentHashMap::contains by convention
^KT-18053 Fixed
2018-12-12 15:38:42 +03:00
Mikhail Glukhikh
92e125413d Do not modify highlighting settings for non-Kotlin files #KT-28716 Fixed
(cherry picked from commit 3889bb05d6)
2018-12-12 14:24:07 +03:00
Alexey Tsvetkov
6aebc695ec Minor: replace UsefulTestCase with KtUsefulTestCase
For some reason assertSameLinesWithFile from UsefulTestCase
fails with exception on TeamCity, whereas the one KtUsefulTestCase
does not
2018-12-12 12:01:45 +03:00
Alexey Tsvetkov
1bb75ac2ec Exclude InsnList from proguard
It is used by jvm-abi-gen plugin
2018-12-12 12:01:43 +03:00
Roman
1e2115ba83 Merge pull request #2024 from JetBrains/rr/gradle/native-update-1.1.0-rc1-5227
Update Kotlin/Native: RC1 1.1.0.5227
2018-12-12 08:04:57 +03:00
Alexey Tsvetkov
34dd6062fd Exclude local variables and try catch blocks of non-inline functions from ABI 2018-12-11 22:51:51 +03:00
Alexey Tsvetkov
e7cea0239a Check descriptor visibility before excluding method from ABI class 2018-12-11 22:51:48 +03:00
Alexey Tsvetkov
962a52ef0d Minor: rename const according to style guide 2018-12-11 22:51:44 +03:00
Alexey Tsvetkov
6a50cd8a11 Attempt to fix ABI tests on TC
Locally they work fine
2018-12-11 22:51:40 +03:00
Alexey Tsvetkov
b96d77db63 Disable removing private/synthetic/local classes temporarily 2018-12-11 22:51:36 +03:00
Alexey Tsvetkov
fe9287a20e Report output classes 2018-12-11 22:51:33 +03:00
Alexey Tsvetkov
d30eb186fd Reuse BytecodeListingTextCollectingVisitor in tests 2018-12-11 22:51:29 +03:00
Alexey Tsvetkov
b8c0d0f589 Reuse TransformationMethodVisitor in ABI gen plugin 2018-12-11 22:51:25 +03:00
Alexey Tsvetkov
e6b1e1df3a Convert TransformationMethodVisitor: step 2 2018-12-11 22:51:22 +03:00
Alexey Tsvetkov
f7d4aae815 Convert TransformationMethodVisitor: step 1 2018-12-11 22:51:18 +03:00
Alexey Tsvetkov
da5bfd6bea Minor fixes after review 2018-12-11 22:51:12 +03:00
Alexey Tsvetkov
d0c59dc73f Exclude nested classes of private classes from ABI classes 2018-12-11 22:51:07 +03:00
Alexey Tsvetkov
79b9f2fdf2 Report locations of errors in ABI classes tests 2018-12-11 22:51:03 +03:00
Alexey Tsvetkov
1207568c60 Add tests for compilation against abi classes 2018-12-11 22:51:00 +03:00
Alexey Tsvetkov
0bcec43b9a Add tests for non-compatible ABI changes 2018-12-11 22:50:56 +03:00
Alexey Tsvetkov
0c5ccbe6eb Exclude clinit from ABI classes 2018-12-11 22:50:52 +03:00
Alexey Tsvetkov
d3d027bc2d Exclude synthetic classes from ABI classes 2018-12-11 22:50:48 +03:00
Alexey Tsvetkov
278afe0691 Minor: extract function 2018-12-11 22:50:44 +03:00
Alexey Tsvetkov
6854ed319b Delay I/O when transforming ABI classes 2018-12-11 22:50:41 +03:00
Alexey Tsvetkov
07d3842de8 Remove unused cosntant pool entries from ABI classes 2018-12-11 22:50:37 +03:00
Alexey Tsvetkov
c66ce278e2 Exclude private typealiases from ABI classes 2018-12-11 22:50:33 +03:00
Alexey Tsvetkov
9a76ea227d Exclude local and private classes from ABI classes 2018-12-11 22:50:29 +03:00
Alexey Tsvetkov
ecbe37085b Exclude non-inline method bodies from ABI classes 2018-12-11 22:50:25 +03:00
Alexey Tsvetkov
5dc88796d9 Exclude private members from ABI classes 2018-12-11 22:50:22 +03:00
Alexey Tsvetkov
bf3debdfb2 Add plugin for JVM ABI classes generation
#KT-25128 Fixed

ABI class generation is implemented as a compiler plugin.
Command-line usage:
1. Add a path to 'jvm-abi-gen.jar' to the plguin classpath argument
(`-Xplugin`). By default the jar is located at
'kotlinc/lib/jvm-abi-gen.jar' in the kotlinc distribution archive.
2. Specify an output directory for ABI classes via
`-Pplugin:org.jetbrains.kotlin.jvm.abi:outputDir=<DIR>`.
2018-12-11 22:50:18 +03:00
Toshiaki Kameyama
9bb9bdd0a5 Assign backing field: don't add empty line
#KT-28694 Fixed

(cherry picked from commit 07ffac72cf)
2018-12-11 22:20:58 +03:00
Mikhail Glukhikh
5bf88069db For each parameter not used: handle char sequences correctly
An enhancement for KT-27209

(cherry picked from commit b143a1c8f7)
2018-12-11 22:20:25 +03:00
Mikhail Glukhikh
f874b8aebd Disable extract actions on non-JVM classes #KT-28476 Fixed
(cherry picked from commit 833f564f0e)
2018-12-11 22:20:08 +03:00
Mikhail Glukhikh
2873aaf4e2 For each parameter not used: introduce "replace with repeat"
An enhancement for KT-27209

(cherry picked from commit 11909a86a8)
2018-12-11 22:19:52 +03:00
Mikhail Glukhikh
daab8d4e14 For each parameter not used: cleanup
(cherry picked from commit e06c995516)
2018-12-11 22:19:34 +03:00
Mikhail Glukhikh
df648dbb06 Redundant arrow: don't report on forEach call with underscore
#KT-27209 Fixed

(cherry picked from commit 9aa1d1495b)
2018-12-11 22:19:17 +03:00
Mikhail Glukhikh
c4d52e0a80 Redundant arrow: support removing of 'it ->' #KT-28631 Fixed
(cherry picked from commit c8c485d27e)
2018-12-11 22:18:31 +03:00
Ilya Chernikov
6988ab0a4f Fix locking in script definition provider
fixes possible parallel modifications on definitions loading, e.g.
as in https://github.com/shyiko/ktlint/issues/287
2018-12-11 15:24:22 +01:00
Denis Zharkov
630502e17d Unwrap InvocationTargetException in dependency injection
^KT-28348 Fixed
2018-12-11 16:14:17 +03:00
Denis Zharkov
0cc6ece8dc Optimize searching constructor delegation calls
^KT-28755 Fixed
2018-12-11 16:14:17 +03:00
Denis Zharkov
b6dcebb08e Minor. Reformat usagesSearch/utils.kt 2018-12-11 16:14:17 +03:00
Alexey Tsvetkov
196193c238 Deprecate AP discovery in compile configurations in Gradle
#KT-24368 Fixed
2018-12-11 16:10:54 +03:00
Alexey Tsvetkov
e04c080e89 Add option to disable AP discovery in compile classpath
#KT-24530 Fixed

To disable discovery and enable avoidance for kapt tasks,
use "kapt.includeCompileClasspath = false"
2018-12-11 16:10:51 +03:00
Vasily Levchenko
b8f92714ac Update Kotlin/Native: RC1 1.1.0.5227 2018-12-11 15:33:42 +03:00
Simon Ogorodnik
ac052ce52a Support overriding module/library/sdk for particular light PsiClass
To support light R classes
2018-12-11 15:01:54 +03:00
Denis Zharkov
83934bfd14 Temporary remove some tests after a fix for KT-24937
Otherwise, our project is failed to be indexed
2018-12-11 12:03:52 +03:00
Denis Zharkov
7214d36a49 Relax assertion in parser for a recovery case with annotations
^KT-24937 Fixed
2018-12-11 12:03:44 +03:00
Yan Zhulanow
43eb3e4042 ServiceLoaderLite: Support paths with spaces (KT-28527) 2018-12-11 17:46:51 +09:00
Dmitry Petrov
6b6c3e7ff3 KT-28585 Fix boxing for values of captured vars of inline class type 2018-12-10 15:08:55 +03:00
Dmitry Petrov
3ab2da1226 KT-28405 Fix toString for inline classes with underlying arrays 2018-12-10 15:08:48 +03:00
Dmitry Savvinov
d51be4cd77 Fix missed returned expression if the last expression was condition jump
See ticket comments for the detailed description

^KT-28061 Fixed
2018-12-10 13:45:20 +03:00
Dmitry Savvinov
68889d839d Add test on in-place lambda with return + safecall
Currently, diagnostics behavior is undesired. The next commit fixes it

^KT-28061 In Progress
2018-12-10 13:45:15 +03:00
21522 changed files with 992872 additions and 641748 deletions

15
.bunch
View File

@@ -1,7 +1,10 @@
191
192
183
182_183
as33_182_183
as34_183
as35
182
181_182
173_181_182
as31_173_181_182
as32_181_182
as33_182
as34
191
cidr183

25
.gitignore vendored
View File

@@ -2,7 +2,7 @@
.idea/shelf
/android.tests.dependencies
/confluence/target
/dependencies/repo
/dependencies
/dist
/local
/gh-pages
@@ -15,6 +15,10 @@ workspace.xml
*.versionsBackup
/idea/testData/debugger/tinyApp/classes*
/jps-plugin/testData/kannotator
/ultimate/dependencies
/ultimate/ideaSDK
/ultimate/out
/ultimate/tmp
/js/js.translator/testData/out/
/js/js.translator/testData/out-min/
.gradle/
@@ -25,30 +29,13 @@ build/
!**/testData/**/*.iml
.idea/libraries/Gradle*.xml
.idea/libraries/Maven*.xml
.idea/artifacts/PILL_*.xml
.idea/artifacts
.idea/modules
.idea/runConfigurations/JPS_*.xml
.idea/runConfigurations/PILL_*.xml
.idea/libraries
.idea/modules.xml
.idea/gradle.xml
.idea/compiler.xml
.idea/inspectionProfiles/profiles_settings.xml
.idea/.name
.idea/artifacts/dist_auto_*
.idea/artifacts/dist.xml
.idea/artifacts/ideaPlugin.xml
.idea/artifacts/kotlinc.xml
.idea/artifacts/kotlin_compiler_jar.xml
.idea/artifacts/kotlin_plugin_jar.xml
.idea/artifacts/kotlin_jps_plugin_jar.xml
.idea/artifacts/kotlin_daemon_client_jar.xml
.idea/artifacts/kotlin_imports_dumper_compiler_plugin_jar.xml
.idea/artifacts/kotlin_main_kts_jar.xml
.idea/artifacts/kotlin_compiler_client_embeddable_jar.xml
.idea/artifacts/kotlin_reflect_jar.xml
kotlin-ultimate/
node_modules/
.rpt2_cache/
libraries/tools/kotlin-test-nodejs-runner/lib/
local.properties

8
.idea/ant.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AntConfiguration">
<buildFile url="file://$PROJECT_DIR$/libraries/build-docs.xml">
<maximumHeapSize value="1024" />
</buildFile>
</component>
</project>

View File

@@ -1,8 +0,0 @@
<component name="ArtifactManager">
<artifact build-on-make="true" name="dist_root">
<output-path>$PROJECT_DIR$/dist</output-path>
<root id="root">
<element id="artifact" artifact-name="dist" />
</root>
</artifact>
</component>

View File

@@ -1,7 +1,7 @@
<component name="CopyrightManager">
<copyright>
<option name="allowReplaceRegexp" value="JetBrains" />
<option name="notice" value="Copyright 2010-&amp;#36;today.year JetBrains s.r.o. and Kotlin Programming Language contributors.&#10;Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file." />
<option name="notice" value="Copyright 2010-&amp;#36;today.year JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license &#10;that can be found in the license/LICENSE.txt file." />
<option name="myName" value="apache" />
</copyright>
</component>

View File

@@ -3,12 +3,7 @@
<words>
<w>cidr</w>
<w>foldable</w>
<w>instrumentator</w>
<w>jdks</w>
<w>protobuf</w>
<w>redirector</w>
<w>remapper</w>
<w>unpresent</w>
</words>
</dictionary>
</component>

View File

@@ -10,7 +10,6 @@
<w>infos</w>
<w>intrinsics</w>
<w>kdoc</w>
<w>lateinit</w>
<w>memoize</w>
<w>memoized</w>
<w>multiline</w>
@@ -19,15 +18,11 @@
<w>preloader</w>
<w>preloading</w>
<w>preprocess</w>
<w>proximities</w>
<w>redeclarations</w>
<w>reparsed</w>
<w>smap</w>
<w>subclassed</w>
<w>subgraph</w>
<w>substep</w>
<w>tailrec</w>
<w>typealias</w>
</words>
</dictionary>
</component>

View File

@@ -3,14 +3,12 @@
<words>
<w>debuggee</w>
<w>deserializes</w>
<w>destructured</w>
<w>hacky</w>
<w>impls</w>
<w>kapt</w>
<w>parceler</w>
<w>repl</w>
<w>uast</w>
<w>unbox</w>
<w>unboxed</w>
<w>unmute</w>
</words>

View File

@@ -21,6 +21,7 @@
</inspection_tool>
<inspection_tool class="BooleanMethodIsAlwaysInverted" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="BusyWait" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="CStyleArrayDeclaration" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="CastConflictsWithInstanceof" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="CastToIncompatibleInterface" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="ChainedEquality" enabled="false" level="WARNING" enabled_by_default="true" />
@@ -75,7 +76,6 @@
<option name="m_ignoreLoopsWithoutConditions" value="false" />
</inspection_tool>
<inspection_tool class="ForLoopThatDoesntUseLoopVariable" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="GrPackage" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="HtmlUnknownTag" enabled="true" level="WARNING" enabled_by_default="true">
<option name="myValues">
<value>
@@ -98,22 +98,24 @@
<inspection_tool class="IncompatibleAPI" enabled="true" level="ERROR" enabled_by_default="true">
<option name="problems">
<list>
<Problem reference="com.intellij.util.JdomKt#element" reason="Removed in 191" />
<Problem reference="com.intellij.util.AstLoadingFilter" reason="Absent in 181. Almost all methods were renamed in 183. Use org.jetbrains.kotlin.util.AstLoadingFilter instead." />
<Problem reference="com.intellij.codeInspection.reference.RefFile#getPsiElement" reason="Absent in 182. Use psiFile extension instead." />
<Problem reference="com.intellij.execution.JavaRunConfigurationExtensionManager#getInstance" reason="Can't be used in Kotlin, because method was replaced with property after J2K in 183. Use JavaRunConfigurationExtensionManagerUtil instead." />
<Problem reference="com.intellij.openapi.progress.ProgressManager#getProgressIndicator" reason="Not null starting from 181. Use getProgressIndicatorNullable instead." />
<Problem reference="com.intellij.testFramework.PlatformTestCase#createModuleAt" reason="Not static anymore in 181 after 7dacf096c47d2125e17031c71a037b63ab00ec53" />
<Problem reference="com.intellij.testFramework.PlatformTestCase#doCreateRealModuleIn" reason="Not static anymore in 181 after 7dacf096c47d2125e17031c71a037b63ab00ec53" />
<Problem reference="com.intellij.openapi.progress.ProgressManager#getProgressIndicator" reason="Nullable in 181. Temporary use progressIndicatorNullable instead." />
<Problem reference="org.jetbrains.java.decompiler.main.decompiler.BaseDecompiler#addSpace" reason="Method was replaced with outher methods in 182. Use addSpaceEx instead." />
<Problem reference="com.intellij.psi.codeStyle.CommonCodeStyleSettings#copyFrom" reason="Absent in 173. Use CompatibilityKt.copyFromEx instead." />
<Problem reference="com.intellij.psi.codeStyle.CommonCodeStyleSettingsManager#copy" reason="Removed since 181. Use CompatibilityKt.copyFromEx instead." />
<Problem reference="com.intellij.notification.NotificationAction#createSimple" reason="Absent in 173." />
<Problem reference="com.intellij.notification.NotificationAction#create" reason="Absent in 173." />
<Problem reference="com.intellij.util.JdomKt#element" reason="Removed in 191" />
<Problem reference="com.intellij.execution.JavaRunConfigurationExtensionManager#getInstance" reason="Can't be used in Kotlin, because method was replaced with property after J2K in 183. Use JavaRunConfigurationExtensionManagerUtil instead." />
<Problem reference="com.intellij.execution.configurations.RunConfigurationBase" reason="Generalized in 183. Use RunConfigurationBaseAny instead in signatures." />
<Problem reference="com.intellij.execution.configurations.LocatableConfigurationBase" reason="Generalized in 183. Use LocatableConfigurationBaseAny instead in signatures." />
<Problem reference="com.intellij.execution.configurations.ModuleBasedConfiguration" reason="Generalized in 183. Use ModuleBasedConfigurationElement instead." />
<Problem reference="com.intellij.util.AstLoadingFilter" reason="Absent in 181. Almost all methods were renamed in 183. Use org.jetbrains.kotlin.util.AstLoadingFilter instead." />
<Problem reference="com.intellij.testFramework.codeInsight.hierarchy.HierarchyViewTestFixture" reason="Absent in &lt;= 181. Use org.jetbrains.kotlin.test.HierarchyViewTestFixture instead." />
<Problem reference="org.jetbrains.kotlin.test.HierarchyViewTestFixtureCompat" reason="Do not use the wrapper for 181 directly. Use org.jetbrains.kotlin.test.HierarchyViewTestFixture instead." />
<Problem reference="com.intellij.psi.codeStyle.CodeStyleSettingsProvider" reason="Additional method is introduced in 183 instead of deprecated one. Use CodeStyleSettingsProviderCompat instead." />
<Problem reference="com.intellij.openapi.ui.popup.PopupChooserBuilder#PopupChooserBuilder(javax.swing.JList)" reason="Generified in 182. Use PopupChooserBuilderWrapper instead." />
<Problem reference="com.intellij.openapi.editor.event.EditorFactoryListener" reason="Default implementations were added in 183. Use EditorFactoryListenerWrapper for inheritance instead." />
<Problem reference="com.intellij.openapi.diagnostic.LoggerKt#debugOrInfoIfTestMode" reason="Absent in 182." />
<Problem reference="com.intellij.psi.search.PsiSearchHelper.SERVICE" reason="Deprecated since 182. Use psiSearchHelperInstance() instead." />
<Problem reference="org.jetbrains.kotlin.idea.reporter.ITNReporterCompat#submit" reason="parentComponent is nullable in AS" />
<Problem reference="com.intellij.diagnostic.ITNReporter#submit" reason="parentComponent is nullable in AS" />
<Problem reference="com.intellij.codeInspection.dataFlow.Nullness" reason="Deprecated since 182. Use org.jetbrains.kotlin.idea.util.compat.Nullability instead." />
</list>
</option>
</inspection_tool>
@@ -266,10 +268,6 @@
<option name="ignoreObjectMethods" value="true" />
<option name="ignoreAnonymousClassMethods" value="false" />
</inspection_tool>
<inspection_tool class="MissingRecentApi" enabled="true" level="ERROR" enabled_by_default="true">
<option name="sinceBuildString" value="182.0" />
<option name="untilBuildString" value="192.SNAPSHOT" />
</inspection_tool>
<inspection_tool class="MisspelledCompareTo" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="MisspelledEquals" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="MisspelledHashcode" enabled="true" level="WARNING" enabled_by_default="true" />
@@ -301,6 +299,16 @@
<inspection_tool class="PackageName" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="namePattern" value="[a-z_][a-z\d_]*(\.[a-z_][a-zA-Z\d_]*)*" />
</inspection_tool>
<inspection_tool class="ProblematicAPIUsage" enabled="true" level="ERROR" enabled_by_default="true">
<option name="problems">
<list>
<Problem reference="com.intellij.testFramework.PlatformTestCase#createModuleAt" reason="Not static anymore in 181 after 7dacf096c47d2125e17031c71a037b63ab00ec53" />
<Problem reference="com.intellij.testFramework.PlatformTestCase#doCreateRealModuleIn" reason="Not static anymore in 181 after 7dacf096c47d2125e17031c71a037b63ab00ec53" />
<Problem reference="com.intellij.openapi.progress.ProgressManager#getProgressIndicator" reason="Nullable in 181. Temporary use progressIndicatorNullable instead." />
<Problem reference="com.intellij.testFramework.fixtures.CodeInsightTestFixture#getProjectDisposable" reason="Method was introduced in 173 and absent in 172. Use getProjectDisposableEx instead. (95eaf81e0ea497f8c69263c11fd3202d28a7a1b2)" />
</list>
</option>
</inspection_tool>
<inspection_tool class="ProtectedMemberInFinalClass" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="PublicFieldAccessedInSynchronizedContext" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="PyCompatibilityInspection" enabled="true" level="ERROR" enabled_by_default="true">
@@ -316,11 +324,16 @@
</inspection_tool>
<inspection_tool class="SSBasedInspection" enabled="true" level="WARNING" enabled_by_default="true">
<searchConfiguration name="SwingUtilities.invokeLater" text="SwingUtilities.invokeLater($runnable$)" recursive="false" caseInsensitive="false" type="JAVA">
<constraint name="Instance" regexp="SwingUtilities" minCount="0" target="true" within="" contains="" />
<constraint name="MethodCall" within="" contains="" />
<constraint name="Parameter" minCount="0" maxCount="2147483647" within="" contains="" />
<constraint name="__context__" within="" contains="" />
<constraint name="runnable" within="" contains="" />
</searchConfiguration>
<replaceConfiguration name="DirectCallOfDispose" text="$Instance$.dispose()" recursive="false" caseInsensitive="false" type="JAVA" reformatAccordingToStyle="true" shortenFQN="true" replacement="Disposer.dispose($Instance$)">
<constraint name="Instance" regexp="super" nameOfExprType="Disposable" withinHierarchy="true" exprTypeWithinHierarchy="true" minCount="0" negateName="true" within="" contains="" />
<constraint name="MethodCall" target="true" within="" contains="" />
<constraint name="Parameter" minCount="0" maxCount="2147483647" within="" contains="" />
<constraint name="__context__" within="" contains="" />
</replaceConfiguration>
<replaceConfiguration name="new Object[0]" text="new Object[0]" recursive="false" caseInsensitive="true" type="JAVA" reformatAccordingToStyle="true" shortenFQN="true" replacement="com.intellij.util.ArrayUtil.EMPTY_OBJECT_ARRAY" />
@@ -384,7 +397,6 @@
</inspection_tool>
<inspection_tool class="StringEquality" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="StringEqualsEmptyString" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="StringOperationCanBeSimplifiedMerged" />
<inspection_tool class="SwitchStatementWithConfusingDeclaration" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="SynchronizeOnThis" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="SystemOutErr" enabled="true" level="WARNING" enabled_by_default="true">

View File

@@ -1,6 +1,7 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="PROJECT_PROFILE" value="idea.default" />
<option name="USE_PROJECT_PROFILE" value="true" />
<version value="1.0" />
</settings>
</component>

8
.idea/misc.xml generated
View File

@@ -47,8 +47,6 @@
</option>
</component>
<component name="NullableNotNullManager">
<option name="myDefaultNullable" value="org.jetbrains.annotations.Nullable" />
<option name="myDefaultNotNull" value="org.jetbrains.annotations.NotNull" />
<option name="myNullables">
<value>
<list size="9">
@@ -86,9 +84,6 @@
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="false" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
<component name="PsiViewerSettings">
<option name="splitDividerLocation" value="35" />
</component>
<component name="SuppressABINotification">
<option name="modulesWithSuppressedNotConfigured">
<set>
@@ -105,7 +100,4 @@
<option name="autoscroll" value="false" />
<option name="showOnlyWarnings" value="false" />
</component>
<component name="intellij-api-watcher-check-current-project">
<option name="shouldCheckCurrentProject" value="true" />
</component>
</project>

View File

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

View File

@@ -1,4 +0,0 @@
## Code of Conduct
This project and the corresponding community is governed by the [JetBrains Open Source and Community Code of Conduct](https://confluence.jetbrains.com/display/ALL/JetBrains+Open+Source+and+Community+Code+of+Conduct). Please make sure you read it.

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
[![official project](https://jb.gg/badges/official.svg)](https://confluence.jetbrains.com/display/ALL/JetBrains+on+GitHub)
[![official project](http://jb.gg/badges/official.svg)](https://confluence.jetbrains.com/display/ALL/JetBrains+on+GitHub)
[![TeamCity (simple build status)](https://img.shields.io/teamcity/http/teamcity.jetbrains.com/s/Kotlin_dev_Compiler.svg)](https://teamcity.jetbrains.com/viewType.html?buildTypeId=Kotlin_dev_Compiler&branch_Kotlin_dev=%3Cdefault%3E&tab=buildTypeStatusDiv)
[![Maven Central](https://img.shields.io/maven-central/v/org.jetbrains.kotlin/kotlin-maven-plugin.svg)](https://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.jetbrains.kotlin%22)
[![GitHub license](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg?style=flat)](https://www.apache.org/licenses/LICENSE-2.0)
[![Maven Central](https://img.shields.io/maven-central/v/org.jetbrains.kotlin/kotlin-maven-plugin.svg)](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.jetbrains.kotlin%22)
[![GitHub license](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg?style=flat)](http://www.apache.org/licenses/LICENSE-2.0)
# Kotlin Programming Language
@@ -15,7 +15,7 @@ Welcome to [Kotlin](https://kotlinlang.org/)! Some handy links:
* [Forum](https://discuss.kotlinlang.org/)
* [Kotlin Blog](https://blog.jetbrains.com/kotlin/)
* [Follow Kotlin on Twitter](https://twitter.com/kotlin)
* [Public Slack channel](https://slack.kotlinlang.org/)
* [Public Slack channel](http://slack.kotlinlang.org/)
* [TeamCity CI build](https://teamcity.jetbrains.com/project.html?tab=projectOverview&projectId=Kotlin)
## Editing Kotlin
@@ -41,11 +41,7 @@ For local development, if you're not working on bytecode generation or the stand
You also can use [Gradle properties](https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_properties_and_system_properties) to setup JDK_* variables.
> Note: The JDK 6 for MacOS is not available on Oracle's site. You can [download it here](https://support.apple.com/kb/DL1572).
On Windows you might need to add long paths setting to the repo:
git config core.longpaths true
> Note: The JDK 6 for MacOS is not available on Oracle's site. You can [download it here](https://support.apple.com/kb/DL1572).
## Building
@@ -87,7 +83,7 @@ Refer to [libraries/ReadMe.md](libraries/ReadMe.md) for details.
### Building for different versions of IntelliJ IDEA and Android Studio
Kotlin plugin is intended to work with several recent versions of IntelliJ IDEA and Android Studio. Each platform is allowed to have a different set of features and might provide a slightly different API. Instead of using several parallel Git branches, project stores everything in a single branch, but files may have counterparts with version extensions (\*.as32, \*.172, \*.181). The primary file is expected to be replaced with its counterpart when targeting non-default platform.
Kotlin plugin is indented to work with several recent versions of IntelliJ IDEA and Android Studio. Each platform is allowed to have a different set of features and might provide a slightly different API. Instead of using several parallel Git branches, project stores everything in a single branch, but files may have counterparts with version extensions (\*.as32, \*.172, \*.181). The primary file is expected to be replaced with its counterpart when targeting non-default platform.
More detailed description of this scheme can be found at https://github.com/JetBrains/bunches/blob/master/ReadMe.md.
@@ -137,4 +133,49 @@ includeBuild('/path/to/kotlin') {
# Contributing
Please be sure to review Kotlin's [contributing guidelines](docs/contributing.md) to learn how to help the project.
We love contributions! There's [lots to do on Kotlin](https://youtrack.jetbrains.com/issues/KT) and on the
[standard library](https://youtrack.jetbrains.com/issues/KT?q=%23Kotlin%20%23Unresolved%20and%20(links:%20KT-2554,%20KT-4089%20or%20%23Libraries)) so why not chat with us
about what you're interested in doing? Please join the #kontributors channel in [our Slack chat](http://slack.kotlinlang.org/)
and let us know about your plans.
If you want to find some issues to start off with, try [this query](https://youtrack.jetbrains.com/issues/KT?q=tag:%20%7BUp%20For%20Grabs%7D%20and%20State:%20Open) which should find all open Kotlin issues that are marked as "up-for-grabs".
Currently only committers can assign issues to themselves so just add a comment if you're starting work on it.
A nice gentle way to contribute would be to review the [standard library docs](https://kotlinlang.org/api/latest/jvm/stdlib/index.html)
and find classes or functions which are not documented very well and submit a patch.
In particular it'd be great if all functions included a nice example of how to use it such as for the
[`hashMapOf()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/hash-map-of.html) function.
This is implemented using the [`@sample`](https://github.com/JetBrains/kotlin/blob/1.1.0/libraries/stdlib/src/kotlin/collections/Maps.kt#L91)
macro to include code from a test function. The benefits of this approach are twofold; First, the API's documentation is improved via beneficial examples that help new users and second, the code coverage is increased.
Some of the code in the standard library is created by generating code from templates. See the [README](libraries/stdlib/ReadMe.md) in the stdlib section for how to run the code generator. The existing templates can be used as examples for creating new ones.
Also the [JavaScript back-end](https://github.com/JetBrains/kotlin/blob/master/js/ReadMe.md) could really use your help. See the [JavaScript contribution section](https://github.com/JetBrains/kotlin/blob/master/js/ReadMe.md) for more details.
If you want to contribute a new language feature, it is important to discuss it through a [KEEP](https://github.com/Kotlin/KEEP) first and get an approval from the language designers. This way you'll make sure your work will be in line with the overall language evolution plan and no other design decisions or considerations will block its acceptance.
## Submitting patches
The best way to submit a patch is to [fork the project on GitHub](https://help.github.com/articles/fork-a-repo/) and then send us a
[pull request](https://help.github.com/articles/creating-a-pull-request/) via [GitHub](https://github.com).
If you create your own fork, it might help to enable rebase by default
when you pull by executing
``` bash
git config --global pull.rebase true
```
This will avoid your local repo having too many merge commits
which will help keep your pull request simple and easy to apply.
## Checklist
Before submitting the pull request, make sure that you can say "YES" to each point in this short checklist:
- You provided the link to the related issue(s) from YouTrack
- You made a reasonable amount of changes related only to the provided issues
- You can explain changes made in the pull request
- You ran the build locally and verified new functionality
- You ran related tests locally and they passed
- You do not have merge commits in the pull request

View File

@@ -8,7 +8,7 @@ plugins {
dependencies {
compile(commonDep("org.apache.ant", "ant"))
compile(project(":kotlin-preloader"))
compile(kotlinStdlib())
compile(project(":kotlin-stdlib"))
}
sourceSets {
@@ -17,5 +17,9 @@ sourceSets {
}
runtimeJar {
manifest.attributes["Class-Path"] = "$compilerManifestClassPath kotlin-preloader.jar"
from("$projectDir/src") { include("**/*.xml") }
manifest.attributes.put("Class-Path", "$compilerManifestClassPath kotlin-preloader.jar")
}
dist()

View File

@@ -129,7 +129,7 @@ class KotlinCompilerAdapter : Javac13() {
}
companion object {
private val KOTLIN_EXTENSIONS = listOf("kt", "kts")
private val KOTLIN_EXTENSIONS = Arrays.asList("kt", "kts")
private fun filterOutKotlinSources(files: Array<File>): Array<File> {
return files.filterNot {

View File

@@ -14,14 +14,14 @@ dependencies {
compileOnly(project(":js:js.serializer"))
compileOnly(project(":js:js.frontend"))
compileOnly(intellijCoreDep()) { includeJars("intellij-core") }
compileOnly(intellijDep()) { includeJars("asm-all", "trove4j", "util", rootProject = rootProject) }
compileOnly(intellijDep()) { includeJars("annotations", "asm-all", "trove4j", "util", rootProject = rootProject) }
compileOnly(project(":kotlin-reflect-api"))
testCompileOnly(project(":compiler:cli-common"))
testCompile(projectTests(":compiler:tests-common"))
testCompile(commonDep("junit:junit"))
testCompile(protobufFull())
testCompile(kotlinStdlib())
testCompile(project(":kotlin-stdlib"))
testCompileOnly(intellijDep()) { includeJars("openapi") }
testRuntime(project(":kotlin-reflect"))
@@ -32,12 +32,12 @@ sourceSets {
"test" { projectDefault() }
}
publish()
runtimeJar()
sourcesJar()
javadocJar()
testsJar()
projectTest(parallel = true)
projectTest()
publish()

View File

@@ -1,6 +1,6 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.build

View File

@@ -1,6 +1,6 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.build

View File

@@ -1,6 +1,6 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.build

View File

@@ -1,6 +1,6 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.build

View File

@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.compilerRunner;
import com.intellij.util.containers.ContainerUtil;
import kotlin.collections.CollectionsKt;
import kotlin.jvm.JvmClassMappingKt;
import kotlin.reflect.KClass;
@@ -24,7 +25,6 @@ import kotlin.reflect.KVisibility;
import kotlin.reflect.full.KClasses;
import kotlin.reflect.jvm.ReflectJvmMapping;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.cli.common.arguments.Argument;
import org.jetbrains.kotlin.cli.common.arguments.CommonToolArguments;
import org.jetbrains.kotlin.cli.common.arguments.InternalArgument;
@@ -60,7 +60,7 @@ public class ArgumentUtils {
@NotNull List<String> result
) throws IllegalAccessException, InstantiationException, InvocationTargetException {
for (KProperty1 property : KClasses.getMemberProperties(clazz)) {
Argument argument = findInstance(property.getAnnotations(), Argument.class);
Argument argument = ContainerUtil.findInstance(property.getAnnotations(), Argument.class);
if (argument == null) continue;
if (property.getVisibility() != KVisibility.PUBLIC) continue;
@@ -90,14 +90,4 @@ public class ArgumentUtils {
}
}
}
@Nullable
private static <T> T findInstance(Iterable<? super T> iterable, Class<T> clazz) {
for (Object item : iterable) {
if (clazz.isInstance(item)) {
return clazz.cast(item);
}
}
return null;
}
}

View File

@@ -16,15 +16,15 @@
package org.jetbrains.kotlin.compilerRunner;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class OutputItemsCollectorImpl implements OutputItemsCollector {
private final List<SimpleOutputItem> outputs = new ArrayList<>();
private final List<SimpleOutputItem> outputs = ContainerUtil.newArrayList();
@Override
public void add(Collection<File> sourceFiles, File outputFile) {

View File

@@ -45,10 +45,7 @@ interface IncrementalCacheCommon {
/**
* Incremental cache common for JVM and JS for specifit ClassName type
*/
abstract class AbstractIncrementalCache<ClassName>(
workingDir: File,
protected val pathConverter: FileToPathConverter
) : BasicMapsOwner(workingDir), IncrementalCacheCommon {
abstract class AbstractIncrementalCache<ClassName>(workingDir: File) : BasicMapsOwner(workingDir), IncrementalCacheCommon {
companion object {
private val SUBTYPES = "subtypes"
private val SUPERTYPES = "supertypes"
@@ -73,16 +70,17 @@ abstract class AbstractIncrementalCache<ClassName>(
private val subtypesMap = registerMap(SubtypesMap(SUBTYPES.storageFile))
private val supertypesMap = registerMap(SupertypesMap(SUPERTYPES.storageFile))
protected val classFqNameToSourceMap = registerMap(ClassFqNameToSourceMap(CLASS_FQ_NAME_TO_SOURCE.storageFile, pathConverter))
protected val classFqNameToSourceMap = registerMap(ClassFqNameToSourceMap(CLASS_FQ_NAME_TO_SOURCE.storageFile))
internal abstract val sourceToClassesMap: AbstractSourceToOutputMap<ClassName>
internal abstract val dirtyOutputClassesMap: AbstractDirtyClassesMap<ClassName>
/**
* A file X is a complementary to a file Y if they contain corresponding expect/actual declarations.
* Complementary files should be compiled together during IC so the compiler does not complain
* about missing parts.
* TODO: provide a better solution (maintain an index of expect/actual declarations akin to IncrementalPackagePartProvider)
*/
private val complementaryFilesMap = registerMap(ComplementarySourceFilesMap(COMPLEMENTARY_FILES.storageFile, pathConverter))
private val complementaryFilesMap = registerMap(FilesMap(COMPLEMENTARY_FILES.storageFile))
override fun classesFqNamesBySources(files: Iterable<File>): Collection<FqName> =
files.flatMapTo(HashSet()) { sourceToClassesMap.getFqNames(it) }
@@ -155,17 +153,14 @@ abstract class AbstractIncrementalCache<ClassName>(
removedFqNames.forEach { classFqNameToSourceMap.remove(it) }
}
protected class ClassFqNameToSourceMap(
storageFile: File,
private val pathConverter: FileToPathConverter
) :
protected class ClassFqNameToSourceMap(storageFile: File) :
BasicStringMap<String>(storageFile, EnumeratorStringDescriptor(), PathStringDescriptor) {
operator fun set(fqName: FqName, sourceFile: File) {
storage[fqName.asString()] = pathConverter.toPath(sourceFile)
storage[fqName.asString()] = sourceFile.canonicalPath
}
operator fun get(fqName: FqName): File? =
storage[fqName.asString()]?.let(pathConverter::toFile)
storage[fqName.asString()]?.let(::File)
fun remove(fqName: FqName) {
storage.remove(fqName.asString())

View File

@@ -1,6 +1,6 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.incremental

View File

@@ -1,6 +1,17 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.incremental
@@ -10,10 +21,14 @@ import java.io.File
interface ICReporter {
fun report(message: () -> String)
fun reportVerbose(message: () -> String)
fun reportCompileIteration(incremental: Boolean, sourceFiles: Collection<File>, exitCode: ExitCode)
fun reportMarkDirtyClass(affectedFiles: Iterable<File>, classFqName: String)
fun reportMarkDirtyMember(affectedFiles: Iterable<File>, scope: String, name: String)
fun reportMarkDirty(affectedFiles: Iterable<File>, reason: String)
}
// used in Gradle plugin
@Suppress("unused")
fun reportCompileIteration(sourceFiles: Collection<File>, exitCode: ExitCode) {}
fun pathsAsString(files: Iterable<File>): String =
files.joinToString { it.canonicalPath }
fun pathsAsString(vararg files: File): String =
pathsAsString(files.toList())
}

View File

@@ -1,36 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.incremental
import java.io.File
abstract class ICReporterBase(private val pathsBase: File? = null) : ICReporter {
override fun reportMarkDirtyClass(affectedFiles: Iterable<File>, classFqName: String) {
reportMarkDirty(affectedFiles, "dirty class $classFqName")
}
override fun reportMarkDirtyMember(affectedFiles: Iterable<File>, scope: String, name: String) {
reportMarkDirty(affectedFiles, "dirty member $scope#$name")
}
override fun reportMarkDirty(affectedFiles: Iterable<File>, reason: String) {
affectedFiles.forEach { file ->
reportVerbose { "${pathsAsString(file)} is marked dirty: $reason" }
}
}
protected fun relativizeIfPossible(files: Iterable<File>): List<File> =
files.map { it.relativeOrCanonical() }
protected fun pathsAsString(files: Iterable<File>): String =
relativizeIfPossible(files).map { it.path }.sorted().joinToString()
protected fun pathsAsString(vararg files: File): String =
pathsAsString(files.toList())
protected fun File.relativeOrCanonical(): File =
pathsBase?.let { relativeToOrNull(it) } ?: canonicalFile
}

View File

@@ -19,7 +19,10 @@ package org.jetbrains.kotlin.incremental
import com.intellij.util.io.DataExternalizer
import org.jetbrains.kotlin.incremental.js.IncrementalResultsConsumerImpl
import org.jetbrains.kotlin.incremental.js.TranslationResultValue
import org.jetbrains.kotlin.incremental.storage.*
import org.jetbrains.kotlin.incremental.storage.BasicStringMap
import org.jetbrains.kotlin.incremental.storage.DirtyClassesFqNameMap
import org.jetbrains.kotlin.incremental.storage.SourceToFqNameMap
import org.jetbrains.kotlin.incremental.storage.StringToLongMapExternalizer
import org.jetbrains.kotlin.metadata.ProtoBuf
import org.jetbrains.kotlin.metadata.deserialization.NameResolverImpl
import org.jetbrains.kotlin.metadata.deserialization.getExtensionOrNull
@@ -27,31 +30,25 @@ import org.jetbrains.kotlin.metadata.js.JsProtoBuf
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.name.parentOrNull
import org.jetbrains.kotlin.serialization.deserialization.getClassId
import org.jetbrains.kotlin.serialization.js.JsSerializerProtocol
import java.io.DataInput
import java.io.DataOutput
import java.io.File
open class IncrementalJsCache(
cachesDir: File,
pathConverter: FileToPathConverter
) : AbstractIncrementalCache<FqName>(cachesDir, pathConverter) {
open class IncrementalJsCache(cachesDir: File) : AbstractIncrementalCache<FqName>(cachesDir) {
companion object {
private const val TRANSLATION_RESULT_MAP = "translation-result"
private const val INLINE_FUNCTIONS = "inline-functions"
private const val HEADER_FILE_NAME = "header.meta"
private const val PACKAGE_META_FILE = "packages-meta"
private val TRANSLATION_RESULT_MAP = "translation-result"
private val INLINE_FUNCTIONS = "inline-functions"
private val HEADER_FILE_NAME = "header.meta"
fun hasHeaderFile(cachesDir: File) = File(cachesDir, HEADER_FILE_NAME).exists()
}
override val sourceToClassesMap = registerMap(SourceToFqNameMap(SOURCE_TO_CLASSES.storageFile, pathConverter))
override val sourceToClassesMap = registerMap(SourceToFqNameMap(SOURCE_TO_CLASSES.storageFile))
override val dirtyOutputClassesMap = registerMap(DirtyClassesFqNameMap(DIRTY_OUTPUT_CLASSES.storageFile))
private val translationResults = registerMap(TranslationResultMap(TRANSLATION_RESULT_MAP.storageFile, pathConverter))
private val inlineFunctions = registerMap(InlineFunctionsMap(INLINE_FUNCTIONS.storageFile, pathConverter))
private val packageMetadata = registerMap(PackageMetadataMap(PACKAGE_META_FILE.storageFile))
private val translationResults = registerMap(TranslationResultMap(TRANSLATION_RESULT_MAP.storageFile))
private val inlineFunctions = registerMap(InlineFunctionsMap(INLINE_FUNCTIONS.storageFile))
private val dirtySources = hashSetOf<File>()
@@ -66,12 +63,6 @@ open class IncrementalJsCache(
}
override fun markDirty(removedAndCompiledSources: Collection<File>) {
removedAndCompiledSources.forEach { sourceFile ->
// The common prefix of all FQN parents has to be the file package
sourceToClassesMap[sourceFile].map { it.parentOrNull()?.asString() ?: "" }.minBy { it.length }?.let {
packageMetadata.remove(it)
}
}
super.markDirty(removedAndCompiledSources)
dirtySources.addAll(removedAndCompiledSources)
}
@@ -81,7 +72,7 @@ open class IncrementalJsCache(
for ((srcFile, data) in translatedFiles) {
dirtySources.remove(srcFile)
val (binaryMetadata, binaryAst, inlineData) = data
val (binaryMetadata, binaryAst) = data
val oldProtoMap = translationResults[srcFile]?.metadata?.let { getProtoData(srcFile, it) } ?: emptyMap()
val newProtoMap = getProtoData(srcFile, binaryMetadata)
@@ -98,16 +89,12 @@ open class IncrementalJsCache(
changesCollector.collectProtoChanges(oldProtoMap[classId], newProtoMap[classId])
}
translationResults.put(srcFile, binaryMetadata, binaryAst, inlineData)
translationResults.put(srcFile, binaryMetadata, binaryAst)
}
for ((srcFile, inlineDeclarations) in incrementalResults.inlineFunctions) {
inlineFunctions.process(srcFile, inlineDeclarations, changesCollector)
}
for ((packageName, metadata) in incrementalResults.packageMetadata) {
packageMetadata.put(packageName, metadata)
}
}
private fun registerOutputForFile(srcFile: File, name: FqName) {
@@ -126,20 +113,14 @@ open class IncrementalJsCache(
}
fun nonDirtyPackageParts(): Map<File, TranslationResultValue> =
hashMapOf<File, TranslationResultValue>().apply {
for (file in translationResults.keys()) {
if (file !in dirtySources) {
put(file, translationResults[file]!!)
hashMapOf<File, TranslationResultValue>().apply {
for (path in translationResults.keys()) {
val file = File(path)
if (file !in dirtySources) {
put(file, translationResults[path]!!)
}
}
}
}
fun packageMetadata(): Map<String, ByteArray> = hashMapOf<String, ByteArray>().apply {
for (fqNameString in packageMetadata.keys()) {
put(fqNameString, packageMetadata[fqNameString]!!)
}
}
}
private object TranslationResultValueExternalizer : DataExternalizer<TranslationResultValue> {
@@ -149,9 +130,6 @@ private object TranslationResultValueExternalizer : DataExternalizer<Translation
output.writeInt(value.binaryAst.size)
output.write(value.binaryAst)
output.writeInt(value.inlineData.size)
output.write(value.inlineData)
}
override fun read(input: DataInput): TranslationResultValue {
@@ -163,46 +141,39 @@ private object TranslationResultValueExternalizer : DataExternalizer<Translation
val binaryAst = ByteArray(binaryAstSize)
input.readFully(binaryAst)
val inlineDataSize = input.readInt()
val inlineData = ByteArray(inlineDataSize)
input.readFully(inlineData)
return TranslationResultValue(metadata = metadata, binaryAst = binaryAst, inlineData = inlineData)
return TranslationResultValue(metadata = metadata, binaryAst = binaryAst)
}
}
private class TranslationResultMap(
storageFile: File,
private val pathConverter: FileToPathConverter
) :
BasicStringMap<TranslationResultValue>(storageFile, TranslationResultValueExternalizer) {
private class TranslationResultMap(storageFile: File) : BasicStringMap<TranslationResultValue>(storageFile, TranslationResultValueExternalizer) {
override fun dumpValue(value: TranslationResultValue): String =
"Metadata: ${value.metadata.md5()}, Binary AST: ${value.binaryAst.md5()}, InlineData: ${value.inlineData.md5()}"
"Metadata: ${value.metadata.md5()}, Binary AST: ${value.binaryAst.md5()}"
fun put(sourceFile: File, newMetadata: ByteArray, newBinaryAst: ByteArray, newInlineData: ByteArray) {
storage[pathConverter.toPath(sourceFile)] =
TranslationResultValue(metadata = newMetadata, binaryAst = newBinaryAst, inlineData = newInlineData)
fun put(file: File, newMetadata: ByteArray, newBinaryAst: ByteArray) {
storage[file.canonicalPath] = TranslationResultValue(metadata = newMetadata, binaryAst = newBinaryAst)
}
operator fun get(sourceFile: File): TranslationResultValue? =
storage[pathConverter.toPath(sourceFile)]
operator fun get(file: File): TranslationResultValue? =
storage[file.canonicalPath]
fun keys(): Collection<File> =
storage.keys.map { pathConverter.toFile(it) }
operator fun get(key: String): TranslationResultValue? =
storage[key]
fun remove(sourceFile: File, changesCollector: ChangesCollector) {
val path = pathConverter.toPath(sourceFile)
val protoBytes = storage[path]!!.metadata
val protoMap = getProtoData(sourceFile, protoBytes)
fun keys(): Collection<String> =
storage.keys
fun remove(file: File, changesCollector: ChangesCollector) {
val protoBytes = storage[file.canonicalPath]!!.metadata
val protoMap = getProtoData(file, protoBytes)
for ((_, protoData) in protoMap) {
changesCollector.collectProtoChanges(oldData = protoData, newData = null)
}
storage.remove(path)
storage.remove(file.canonicalPath)
}
}
fun getProtoData(sourceFile: File, metadata: ByteArray): Map<ClassId, ProtoData> {
fun getProtoData(sourceFile: File, metadata: ByteArray): Map<ClassId, ProtoData> {
val classes = hashMapOf<ClassId, ProtoData>()
val proto = ProtoBuf.PackageFragment.parseFrom(metadata, JsSerializerProtocol.extensionRegistry)
val nameResolver = NameResolverImpl(proto.strings, proto.qualifiedNames)
@@ -221,17 +192,15 @@ fun getProtoData(sourceFile: File, metadata: ByteArray): Map<ClassId, ProtoData>
return classes
}
private class InlineFunctionsMap(
storageFile: File,
private val pathConverter: FileToPathConverter
) : BasicStringMap<Map<String, Long>>(storageFile, StringToLongMapExternalizer) {
private class InlineFunctionsMap(storageFile: File) : BasicStringMap<Map<String, Long>>(storageFile, StringToLongMapExternalizer) {
fun process(srcFile: File, newMap: Map<String, Long>, changesCollector: ChangesCollector) {
val key = pathConverter.toPath(srcFile)
val key = srcFile.canonicalPath
val oldMap = storage[key] ?: emptyMap()
if (newMap.isNotEmpty()) {
storage[key] = newMap
} else {
}
else {
storage.remove(key)
}
@@ -243,40 +212,9 @@ private class InlineFunctionsMap(
}
fun remove(sourceFile: File) {
storage.remove(pathConverter.toPath(sourceFile))
storage.remove(sourceFile.canonicalPath)
}
override fun dumpValue(value: Map<String, Long>): String =
value.dumpMap { java.lang.Long.toHexString(it) }
}
private object ByteArrayExternalizer : DataExternalizer<ByteArray> {
override fun save(output: DataOutput, value: ByteArray) {
output.writeInt(value.size)
output.write(value)
}
override fun read(input: DataInput): ByteArray {
val size = input.readInt()
val array = ByteArray(size)
input.readFully(array)
return array
}
}
private class PackageMetadataMap(storageFile: File) : BasicStringMap<ByteArray>(storageFile, ByteArrayExternalizer) {
fun put(packageName: String, newMetadata: ByteArray) {
storage[packageName] = newMetadata
}
fun remove(packageName: String) {
storage.remove(packageName)
}
fun keys() = storage.keys
operator fun get(packageName: String) = storage[packageName]
override fun dumpValue(value: ByteArray): String = "Package metadata: ${value.md5()}"
value.dumpMap { java.lang.Long.toHexString(it) }
}

View File

@@ -43,12 +43,8 @@ val KOTLIN_CACHE_DIRECTORY_NAME = "kotlin"
open class IncrementalJvmCache(
private val targetDataRoot: File,
targetOutputDir: File?,
pathConverter: FileToPathConverter
) : AbstractIncrementalCache<JvmClassName>(
workingDir = File(targetDataRoot, KOTLIN_CACHE_DIRECTORY_NAME),
pathConverter = pathConverter
), IncrementalCache {
targetOutputDir: File?
) : AbstractIncrementalCache<JvmClassName>(File(targetDataRoot, KOTLIN_CACHE_DIRECTORY_NAME)), IncrementalCache {
companion object {
private val PROTO_MAP = "proto"
private val CONSTANTS_MAP = "constants"
@@ -62,7 +58,7 @@ open class IncrementalJvmCache(
private val MODULE_MAPPING_FILE_NAME = "." + ModuleMapping.MAPPING_FILE_EXT
}
override val sourceToClassesMap = registerMap(SourceToJvmNameMap(SOURCE_TO_CLASSES.storageFile, pathConverter))
override val sourceToClassesMap = registerMap(SourceToJvmNameMap(SOURCE_TO_CLASSES.storageFile))
override val dirtyOutputClassesMap = registerMap(DirtyClassesJvmNameMap(DIRTY_OUTPUT_CLASSES.storageFile))
private val protoMap = registerMap(ProtoMap(PROTO_MAP.storageFile))
@@ -72,8 +68,7 @@ open class IncrementalJvmCache(
private val partToMultifileFacade = registerMap(MultifileClassPartMap(MULTIFILE_CLASS_PARTS.storageFile))
private val inlineFunctionsMap = registerMap(InlineFunctionsMap(INLINE_FUNCTIONS.storageFile))
// todo: try to use internal names only?
private val internalNameToSource = registerMap(InternalNameToSourcesMap(INTERNAL_NAME_TO_SOURCE.storageFile, pathConverter))
// gradle only
private val internalNameToSource = registerMap(InternalNameToSourcesMap(INTERNAL_NAME_TO_SOURCE.storageFile))
private val javaSourcesProtoMap = registerMap(JavaSourcesProtoMap(JAVA_SOURCES_PROTO_MAP.storageFile))
private val outputDir by lazy(LazyThreadSafetyMode.NONE) { requireNotNull(targetOutputDir) { "Target is expected to have output directory" } }
@@ -355,7 +350,7 @@ open class IncrementalJvmCache(
private fun getConstantsMap(bytes: ByteArray): Map<String, Any> {
val result = HashMap<String, Any>()
ClassReader(bytes).accept(object : ClassVisitor(Opcodes.API_VERSION) {
ClassReader(bytes).accept(object : ClassVisitor(Opcodes.ASM5) {
override fun visitField(access: Int, name: String, desc: String, signature: String?, value: Any?): FieldVisitor? {
val staticFinal = Opcodes.ACC_STATIC or Opcodes.ACC_FINAL or Opcodes.ACC_PRIVATE
if (value != null && access and staticFinal == Opcodes.ACC_STATIC or Opcodes.ACC_FINAL) {
@@ -445,16 +440,14 @@ open class IncrementalJvmCache(
override fun dumpValue(value: String): String = value
}
inner class InternalNameToSourcesMap(
storageFile: File,
private val pathConverter: FileToPathConverter
) : BasicStringMap<Collection<String>>(storageFile, EnumeratorStringDescriptor(), PathCollectionExternalizer) {
operator fun set(internalName: String, sourceFiles: Collection<File>) {
storage[internalName] = pathConverter.toPaths(sourceFiles)
inner class InternalNameToSourcesMap(storageFile: File) :
BasicStringMap<Collection<String>>(storageFile, EnumeratorStringDescriptor(), PathCollectionExternalizer) {
operator fun set(internalName: String, sourceFiles: Iterable<File>) {
storage[internalName] = sourceFiles.map { it.canonicalPath }
}
operator fun get(internalName: String): Collection<File> =
pathConverter.toFiles(storage[internalName] ?: emptyList())
(storage[internalName] ?: emptyList()).map(::File)
fun remove(internalName: String) {
storage.remove(internalName)
@@ -477,7 +470,7 @@ open class IncrementalJvmCache(
val result = HashMap<String, Long>()
ClassReader(bytes).accept(object : ClassVisitor(Opcodes.API_VERSION) {
ClassReader(bytes).accept(object : ClassVisitor(Opcodes.ASM5) {
override fun visitMethod(
access: Int,
name: String,
@@ -485,9 +478,9 @@ open class IncrementalJvmCache(
signature: String?,
exceptions: Array<out String>?
): MethodVisitor? {
val dummyClassWriter = ClassWriter(Opcodes.API_VERSION)
val dummyClassWriter = ClassWriter(Opcodes.ASM5)
return object : MethodVisitor(Opcodes.API_VERSION, dummyClassWriter.visitMethod(0, name, desc, null, exceptions)) {
return object : MethodVisitor(Opcodes.ASM5, dummyClassWriter.visitMethod(0, name, desc, null, exceptions)) {
override fun visitEnd() {
val jvmName = name + desc
if (jvmName !in inlineFunctions) return

View File

@@ -1,33 +0,0 @@
/*
* Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.incremental
import java.io.File
import java.io.Serializable
data class IncrementalModuleEntry(
private val projectPath: String,
val name: String,
val buildDir: File,
val buildHistoryFile: File
) : Serializable {
companion object {
private const val serialVersionUID = 0L
}
}
class IncrementalModuleInfo(
val projectRoot: File,
val dirToModule: Map<File, IncrementalModuleEntry>,
val nameToModules: Map<String, Set<IncrementalModuleEntry>>,
val jarToClassListFile: Map<File, File>,
// only for js and mpp
val jarToModule: Map<File, IncrementalModuleEntry>
) : Serializable {
companion object {
private const val serialVersionUID = 0L
}
}

View File

@@ -71,7 +71,7 @@ class JavaClassesSerializerExtension : KotlinSerializerExtensionBase(BuiltInSeri
override fun serializeProperty(
descriptor: PropertyDescriptor,
proto: ProtoBuf.Property.Builder,
versionRequirementTable: MutableVersionRequirementTable?,
versionRequirementTable: MutableVersionRequirementTable,
childSerializer: DescriptorSerializer
) {
super.serializeProperty(descriptor, proto, versionRequirementTable, childSerializer)

View File

@@ -30,18 +30,15 @@ import java.io.IOException
import java.util.*
open class LookupStorage(
targetDataDir: File,
pathConverter: FileToPathConverter
) : BasicMapsOwner(targetDataDir) {
open class LookupStorage(targetDataDir: File) : BasicMapsOwner(targetDataDir) {
companion object {
private val DELETED_TO_SIZE_TRESHOLD = 0.5
private val MINIMUM_GARBAGE_COLLECTIBLE_SIZE = 10000
}
private val countersFile = "counters".storageFile
private val idToFile = registerMap(IdToFileMap("id-to-file".storageFile, pathConverter))
private val fileToId = registerMap(FileToIdMap("file-to-id".storageFile, pathConverter))
private val idToFile = registerMap(IdToFileMap("id-to-file".storageFile))
private val fileToId = registerMap(FileToIdMap("file-to-id".storageFile))
private val lookupMap = registerMap(LookupMap("lookups".storageFile))
@Volatile
@@ -155,7 +152,7 @@ open class LookupStorage(
size = 0
deletedCount = 0
for ((file, oldId) in oldFileToId.entries.sortedBy { it.key.path }) {
for ((file, oldId) in oldFileToId.entries) {
val newId = addFileIfNeeded(file)
oldIdToNewId[oldId] = newId
}
@@ -177,19 +174,11 @@ open class LookupStorage(
flush(false)
}
@TestOnly
fun dump(lookupSymbols: Set<LookupSymbol>): String {
@TestOnly fun dump(lookupSymbols: Set<LookupSymbol>, basePath: File? = null): String {
flush(false)
val sb = StringBuilder()
val p = Printer(sb)
p.println("====== File to id map")
p.println(fileToId.dump())
p.println("====== Id to file map")
p.println(idToFile.dump())
val lookupsStrings = lookupSymbols.groupBy { LookupSymbolKey(it.name, it.scope) }
for (lookup in lookupMap.keys.sorted()) {
@@ -197,11 +186,12 @@ open class LookupStorage(
val key = if (lookup in lookupsStrings) {
lookupsStrings[lookup]!!.map { "${it.scope}#${it.name}" }.sorted().joinToString(", ")
} else {
}
else {
lookup.toString()
}
val value = fileIds.map { it.toString() }.sorted().joinToString(", ")
val value = fileIds.map { idToFile[it]?.let { if (basePath == null) it.absolutePath else it.toRelativeString(basePath) } ?: it.toString() }.sorted().joinToString(", ")
p.println("$key -> $value")
}

View File

@@ -16,6 +16,8 @@
package org.jetbrains.kotlin.incremental
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.kotlin.build.GeneratedFile
import org.jetbrains.kotlin.build.GeneratedJvmClass
import org.jetbrains.kotlin.build.JvmSourceRoot
@@ -29,10 +31,8 @@ import org.jetbrains.kotlin.modules.TargetId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.progress.CompilationCanceledStatus
import org.jetbrains.kotlin.synthetic.SAM_LOOKUP_NAME
import org.jetbrains.kotlin.utils.addToStdlib.flattenTo
import java.io.File
import java.util.*
import kotlin.collections.HashSet
const val DELETE_MODULE_FILE_PROPERTY = "kotlin.delete.module.file.after.build"
@@ -65,23 +65,11 @@ fun makeModuleFile(
friendDirs
)
val scriptFile = File.createTempFile("kjps", sanitizeJavaIdentifier(name) + ".script.xml")
scriptFile.writeText(builder.asText().toString())
val scriptFile = File.createTempFile("kjps", StringUtil.sanitizeJavaIdentifier(name) + ".script.xml")
FileUtil.writeToFile(scriptFile, builder.asText().toString())
return scriptFile
}
private fun sanitizeJavaIdentifier(string: String) =
buildString {
for (char in string) {
if (char.isJavaIdentifierPart()) {
if (length == 0 && !char.isJavaIdentifierStart()) {
append('_')
}
append(char)
}
}
}
fun makeCompileServices(
incrementalCaches: Map<TargetId, IncrementalCache>,
lookupTracker: LookupTracker,
@@ -142,7 +130,7 @@ fun ChangesCollector.getDirtyData(
val dirtyClassesFqNames = HashSet<FqName>()
for (change in changes()) {
reporter.reportVerbose { "Process $change" }
reporter.report { "Process $change" }
if (change is ChangeInfo.SignatureChanged) {
val fqNames = if (!change.areSubclassesAffected) listOf(change.fqName) else withSubtypes(change.fqName, caches)
@@ -155,7 +143,8 @@ fun ChangesCollector.getDirtyData(
val name = classFqName.shortName().identifier
dirtyLookupSymbols.add(LookupSymbol(name, scope))
}
} else if (change is ChangeInfo.MembersChanged) {
}
else if (change is ChangeInfo.MembersChanged) {
val fqNames = withSubtypes(change.fqName, caches)
// need to recompile subtypes because changed member might break override
dirtyClassesFqNames.addAll(fqNames)
@@ -172,16 +161,16 @@ fun ChangesCollector.getDirtyData(
}
fun mapLookupSymbolsToFiles(
lookupStorage: LookupStorage,
lookupSymbols: Iterable<LookupSymbol>,
reporter: ICReporter,
excludes: Set<File> = emptySet()
lookupStorage: LookupStorage,
lookupSymbols: Iterable<LookupSymbol>,
reporter: ICReporter,
excludes: Set<File> = emptySet()
): Set<File> {
val dirtyFiles = HashSet<File>()
for (lookup in lookupSymbols) {
val affectedFiles = lookupStorage.get(lookup).map(::File).filter { it !in excludes }
reporter.reportMarkDirtyMember(affectedFiles, scope = lookup.scope, name = lookup.name)
reporter.report { "${lookup.scope}#${lookup.name} caused recompilation of: ${reporter.pathsAsString(affectedFiles)}" }
dirtyFiles.addAll(affectedFiles)
}
@@ -194,22 +183,19 @@ fun mapClassesFqNamesToFiles(
reporter: ICReporter,
excludes: Set<File> = emptySet()
): Set<File> {
val fqNameToAffectedFiles = HashMap<FqName, MutableSet<File>>()
val dirtyFiles = HashSet<File>()
for (cache in caches) {
for (classFqName in classesFqNames) {
val srcFile = cache.getSourceFileIfClass(classFqName)
for (dirtyClassFqName in classesFqNames) {
val srcFile = cache.getSourceFileIfClass(dirtyClassFqName)
if (srcFile == null || srcFile in excludes || srcFile.isJavaFile()) continue
fqNameToAffectedFiles.getOrPut(classFqName) { HashSet() }.add(srcFile)
reporter.report { ("Class $dirtyClassFqName caused recompilation of: ${reporter.pathsAsString(srcFile)}") }
dirtyFiles.add(srcFile)
}
}
for ((classFqName, affectedFiles) in fqNameToAffectedFiles) {
reporter.reportMarkDirtyClass(affectedFiles, classFqName.asString())
}
return fqNameToAffectedFiles.values.flattenTo(HashSet())
return dirtyFiles
}
fun withSubtypes(

View File

@@ -1,6 +1,6 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.incremental.js
@@ -18,7 +18,4 @@ class IncrementalDataProviderFromCache(private val cache: IncrementalJsCache) :
override val metadataVersion: IntArray
get() = JsMetadataVersion.INSTANCE.toArray() // TODO: store and load correct metadata version
override val packageMetadata: Map<String, ByteArray>
get() = cache.packageMetadata()
}

View File

@@ -1,30 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.incremental.storage
import org.jetbrains.kotlin.incremental.dumpCollection
import java.io.File
class ComplementarySourceFilesMap(
storageFile: File,
private val pathConverter: FileToPathConverter
) : BasicStringMap<Collection<String>>(storageFile, PathStringDescriptor, StringCollectionExternalizer) {
operator fun set(sourceFile: File, complementaryFiles: Collection<File>) {
storage[pathConverter.toPath(sourceFile)] = pathConverter.toPaths(complementaryFiles)
}
operator fun get(sourceFile: File): Collection<File> {
val paths = storage[pathConverter.toPath(sourceFile)].orEmpty()
return pathConverter.toFiles(paths)
}
override fun dumpValue(value: Collection<String>) =
value.dumpCollection()
fun remove(file: File): Collection<File> =
get(file).also { storage.remove(pathConverter.toPath(file)) }
}

View File

@@ -18,27 +18,26 @@ package org.jetbrains.kotlin.incremental.storage
import java.io.File
internal class FileToIdMap(
file: File,
private val pathConverter: FileToPathConverter
) : BasicStringMap<Int>(file, IntExternalizer) {
internal class FileToIdMap(file: File) : BasicMap<File, Int>(file, FileKeyDescriptor, IntExternalizer) {
override fun dumpKey(key: File): String = key.toString()
override fun dumpValue(value: Int): String = value.toString()
operator fun get(file: File): Int? = storage[pathConverter.toPath(file)]
operator fun get(file: File): Int? = storage[file]
operator fun set(file: File, id: Int) {
storage[pathConverter.toPath(file)] = id
storage[file] = id
}
fun remove(file: File) {
storage.remove(pathConverter.toPath(file))
storage.remove(file)
}
fun toMap(): Map<File, Int> {
val result = HashMap<File, Int>()
for (key in storage.keys) {
val value = storage[key] ?: continue
result[pathConverter.toFile(key)] = value
result[key] = value
}
return result
}

View File

@@ -1,25 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.incremental.storage
import java.io.File
interface FileToPathConverter {
fun toPath(file: File): String
fun toFile(path: String): File
}
fun FileToPathConverter.toPaths(files: Collection<File>): List<String> =
files.map { toPath(it) }
fun FileToPathConverter.toFiles(paths: Collection<String>): List<File> =
paths.map { toFile(it) }
object FileToCanonicalPathConverter : FileToPathConverter {
override fun toPath(file: File): String = file.canonicalPath
override fun toFile(path: String): File = File(path)
}

View File

@@ -0,0 +1,26 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.incremental.storage
import org.jetbrains.kotlin.incremental.dumpCollection
import java.io.File
class FilesMap(storageFile: File)
: BasicStringMap<Collection<String>>(storageFile, PathStringDescriptor, StringCollectionExternalizer) {
operator fun set(sourceFile: File, outputFiles: Collection<File>) {
storage[sourceFile.absolutePath] = outputFiles.map { it.absolutePath }
}
operator fun get(sourceFile: File): Collection<File> =
storage[sourceFile.absolutePath].orEmpty().map(::File)
override fun dumpValue(value: Collection<String>) =
value.dumpCollection()
fun remove(file: File): Collection<File> =
get(file).also { storage.remove(file.absolutePath) }
}

View File

@@ -16,24 +16,20 @@
package org.jetbrains.kotlin.incremental.storage
import com.intellij.util.io.EnumeratorStringDescriptor
import com.intellij.util.io.ExternalIntegerKeyDescriptor
import java.io.File
internal class IdToFileMap(
file: File,
private val pathConverter: FileToPathConverter
) : BasicMap<Int, String>(file, ExternalIntegerKeyDescriptor(), EnumeratorStringDescriptor.INSTANCE) {
internal class IdToFileMap(file: File) : BasicMap<Int, File>(file, ExternalIntegerKeyDescriptor(), FileKeyDescriptor) {
override fun dumpKey(key: Int): String = key.toString()
override fun dumpValue(value: String): String = value
override fun dumpValue(value: File): String = value.toString()
operator fun get(id: Int): File? = storage[id]?.let { pathConverter.toFile(it) }
operator fun get(id: Int): File? = storage[id]
operator fun contains(id: Int): Boolean = id in storage
operator fun set(id: Int, file: File) {
storage[id] = pathConverter.toPath(file)
storage[id] = file
}
fun remove(id: Int) {

View File

@@ -21,40 +21,32 @@ import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import java.io.File
internal class SourceToJvmNameMap(
storageFile: File,
pathConverter: FileToPathConverter
) : AbstractSourceToOutputMap<JvmClassName>(JvmClassNameTransformer, storageFile, pathConverter)
internal class SourceToFqNameMap(
storageFile: File,
pathConverter: FileToPathConverter
) : AbstractSourceToOutputMap<FqName>(FqNameTransformer, storageFile, pathConverter)
internal class SourceToJvmNameMap(storageFile: File) : AbstractSourceToOutputMap<JvmClassName>(JvmClassNameTransformer, storageFile)
internal class SourceToFqNameMap(storageFile: File) : AbstractSourceToOutputMap<FqName>(FqNameTransformer, storageFile)
internal abstract class AbstractSourceToOutputMap<Name>(
private val nameTransformer: NameTransformer<Name>,
storageFile: File,
private val pathConverter: FileToPathConverter
private val nameTransformer: NameTransformer<Name>,
storageFile: File
) : BasicStringMap<Collection<String>>(storageFile, PathStringDescriptor, StringCollectionExternalizer) {
fun clearOutputsForSource(sourceFile: File) {
remove(pathConverter.toPath(sourceFile))
remove(sourceFile.absolutePath)
}
fun add(sourceFile: File, className: Name) {
storage.append(pathConverter.toPath(sourceFile), nameTransformer.asString(className))
storage.append(sourceFile.absolutePath, nameTransformer.asString(className))
}
fun contains(sourceFile: File): Boolean =
pathConverter.toPath(sourceFile) in storage
sourceFile.absolutePath in storage
operator fun get(sourceFile: File): Collection<Name> =
storage[pathConverter.toPath(sourceFile)].orEmpty().map(nameTransformer::asName)
storage[sourceFile.absolutePath].orEmpty().map(nameTransformer::asName)
fun getFqNames(sourceFile: File): Collection<FqName> =
storage[pathConverter.toPath(sourceFile)].orEmpty().map(nameTransformer::asFqName)
storage[sourceFile.absolutePath].orEmpty().map(nameTransformer::asFqName)
override fun dumpValue(value: Collection<String>) =
value.dumpCollection()
value.dumpCollection()
private fun remove(path: String) {
storage.remove(path)

View File

@@ -177,6 +177,20 @@ object PathStringDescriptor : EnumeratorStringDescriptor() {
override fun isEqual(val1: String, val2: String?) = FileUtil.pathsEqual(val1, val2)
}
object FileKeyDescriptor : KeyDescriptor<File> {
override fun read(input: DataInput): File = File(input.readUTF())
override fun save(output: DataOutput, value: File) {
output.writeUTF(value.canonicalPath)
}
override fun getHashCode(value: File?): Int =
FileUtil.FILE_HASHING_STRATEGY.computeHashCode(value)
override fun isEqual(val1: File?, val2: File?): Boolean =
FileUtil.FILE_HASHING_STRATEGY.equals(val1, val2)
}
open class CollectionExternalizer<T>(
private val elementExternalizer: DataExternalizer<T>,
private val newCollection: () -> MutableCollection<T>

View File

@@ -16,6 +16,8 @@
package org.jetbrains.kotlin.modules
import com.intellij.openapi.util.io.FileUtil.toSystemIndependentName
import com.intellij.openapi.util.text.StringUtil.escapeXml
import org.jetbrains.kotlin.build.JvmSourceRoot
import org.jetbrains.kotlin.cli.common.modules.ModuleXmlParser.*
import org.jetbrains.kotlin.config.IncrementalCompilation
@@ -135,13 +137,6 @@ class KotlinModuleXmlBuilder {
}
private fun getEscapedPath(sourceFile: File): String {
return escapeXml(sourceFile.invariantSeparatorsPath)
}
private companion object {
private val xmlEscapeReplacement = mapOf("<" to "&lt;", ">" to "&gt;", "&" to "&amp;", "'" to "&#39;", "\"" to "&quot;")
private val xmlEscapeRegex = Regex(xmlEscapeReplacement.keys.joinToString("|", "(?:", ")") { Regex.escape(it) })
private fun escapeXml(string: String) = string.replace(xmlEscapeRegex) { xmlEscapeReplacement.getValue(it.value) }
return escapeXml(toSystemIndependentName(sourceFile.path))
}
}

View File

@@ -205,7 +205,7 @@ private fun kjsmToString(kjsmFile: File): String {
}
private fun sourceMapFileToString(sourceMapFile: File, generatedJsFile: File): String {
val sourceMapParseResult = SourceMapParser.parse(sourceMapFile.readText())
val sourceMapParseResult = SourceMapParser.parse(StringReader(sourceMapFile.readText()))
return when (sourceMapParseResult) {
is SourceMapSuccess -> {
val bytesOut = ByteArrayOutputStream()

View File

@@ -19,7 +19,6 @@ package org.jetbrains.kotlin.incremental.testingUtils
import com.intellij.openapi.util.io.FileUtil
import java.io.File
import java.util.*
import kotlin.math.max
private val COMMANDS = listOf("new", "touch", "delete")
private val COMMANDS_AS_REGEX_PART = COMMANDS.joinToString("|")
@@ -167,7 +166,7 @@ class TouchFile(path: String, private val touchPolicy: TouchPolicy) : Modificati
TouchPolicy.TIMESTAMP -> {
val oldLastModified = file.lastModified()
//Mac OS and some versions of Linux truncate timestamp to nearest second
file.setLastModified(max(System.currentTimeMillis(), oldLastModified + 1000))
file.setLastModified(Math.max(System.currentTimeMillis(), oldLastModified + 1000))
}
TouchPolicy.CHECKSUM -> {
file.appendText(" ")

View File

@@ -2643,9 +2643,7 @@ public final class DebugProtoBuf {
* - Array&lt;String&gt;::class, if array_dimension_count = 1
* - Array&lt;Array&lt;String&gt;&gt;::class, if array_dimension_count = 2
* - etc.
* Since it's very difficult to represent Kotlin-specific type aspects (nullability, type projections) of array arguments
* in class literals on JVM, we don't bother to do represent this in our format as well.
* So, for example, values `Array&lt;Array&lt;in B?&gt;&gt;::class` and `Array&lt;out Array&lt;B&gt;&gt;?&gt;::class` will be represented exactly the same here.
* Other forms of array class literals are not supported by this format, see KT-26568
* </pre>
*/
boolean hasArrayDimensionCount();
@@ -2659,9 +2657,7 @@ public final class DebugProtoBuf {
* - Array&lt;String&gt;::class, if array_dimension_count = 1
* - Array&lt;Array&lt;String&gt;&gt;::class, if array_dimension_count = 2
* - etc.
* Since it's very difficult to represent Kotlin-specific type aspects (nullability, type projections) of array arguments
* in class literals on JVM, we don't bother to do represent this in our format as well.
* So, for example, values `Array&lt;Array&lt;in B?&gt;&gt;::class` and `Array&lt;out Array&lt;B&gt;&gt;?&gt;::class` will be represented exactly the same here.
* Other forms of array class literals are not supported by this format, see KT-26568
* </pre>
*/
int getArrayDimensionCount();
@@ -3224,9 +3220,7 @@ public final class DebugProtoBuf {
* - Array&lt;String&gt;::class, if array_dimension_count = 1
* - Array&lt;Array&lt;String&gt;&gt;::class, if array_dimension_count = 2
* - etc.
* Since it's very difficult to represent Kotlin-specific type aspects (nullability, type projections) of array arguments
* in class literals on JVM, we don't bother to do represent this in our format as well.
* So, for example, values `Array&lt;Array&lt;in B?&gt;&gt;::class` and `Array&lt;out Array&lt;B&gt;&gt;?&gt;::class` will be represented exactly the same here.
* Other forms of array class literals are not supported by this format, see KT-26568
* </pre>
*/
public boolean hasArrayDimensionCount() {
@@ -3242,9 +3236,7 @@ public final class DebugProtoBuf {
* - Array&lt;String&gt;::class, if array_dimension_count = 1
* - Array&lt;Array&lt;String&gt;&gt;::class, if array_dimension_count = 2
* - etc.
* Since it's very difficult to represent Kotlin-specific type aspects (nullability, type projections) of array arguments
* in class literals on JVM, we don't bother to do represent this in our format as well.
* So, for example, values `Array&lt;Array&lt;in B?&gt;&gt;::class` and `Array&lt;out Array&lt;B&gt;&gt;?&gt;::class` will be represented exactly the same here.
* Other forms of array class literals are not supported by this format, see KT-26568
* </pre>
*/
public int getArrayDimensionCount() {
@@ -4373,9 +4365,7 @@ public final class DebugProtoBuf {
* - Array&lt;String&gt;::class, if array_dimension_count = 1
* - Array&lt;Array&lt;String&gt;&gt;::class, if array_dimension_count = 2
* - etc.
* Since it's very difficult to represent Kotlin-specific type aspects (nullability, type projections) of array arguments
* in class literals on JVM, we don't bother to do represent this in our format as well.
* So, for example, values `Array&lt;Array&lt;in B?&gt;&gt;::class` and `Array&lt;out Array&lt;B&gt;&gt;?&gt;::class` will be represented exactly the same here.
* Other forms of array class literals are not supported by this format, see KT-26568
* </pre>
*/
public boolean hasArrayDimensionCount() {
@@ -4391,9 +4381,7 @@ public final class DebugProtoBuf {
* - Array&lt;String&gt;::class, if array_dimension_count = 1
* - Array&lt;Array&lt;String&gt;&gt;::class, if array_dimension_count = 2
* - etc.
* Since it's very difficult to represent Kotlin-specific type aspects (nullability, type projections) of array arguments
* in class literals on JVM, we don't bother to do represent this in our format as well.
* So, for example, values `Array&lt;Array&lt;in B?&gt;&gt;::class` and `Array&lt;out Array&lt;B&gt;&gt;?&gt;::class` will be represented exactly the same here.
* Other forms of array class literals are not supported by this format, see KT-26568
* </pre>
*/
public int getArrayDimensionCount() {
@@ -4409,9 +4397,7 @@ public final class DebugProtoBuf {
* - Array&lt;String&gt;::class, if array_dimension_count = 1
* - Array&lt;Array&lt;String&gt;&gt;::class, if array_dimension_count = 2
* - etc.
* Since it's very difficult to represent Kotlin-specific type aspects (nullability, type projections) of array arguments
* in class literals on JVM, we don't bother to do represent this in our format as well.
* So, for example, values `Array&lt;Array&lt;in B?&gt;&gt;::class` and `Array&lt;out Array&lt;B&gt;&gt;?&gt;::class` will be represented exactly the same here.
* Other forms of array class literals are not supported by this format, see KT-26568
* </pre>
*/
public Builder setArrayDimensionCount(int value) {
@@ -4430,9 +4416,7 @@ public final class DebugProtoBuf {
* - Array&lt;String&gt;::class, if array_dimension_count = 1
* - Array&lt;Array&lt;String&gt;&gt;::class, if array_dimension_count = 2
* - etc.
* Since it's very difficult to represent Kotlin-specific type aspects (nullability, type projections) of array arguments
* in class literals on JVM, we don't bother to do represent this in our format as well.
* So, for example, values `Array&lt;Array&lt;in B?&gt;&gt;::class` and `Array&lt;out Array&lt;B&gt;&gt;?&gt;::class` will be represented exactly the same here.
* Other forms of array class literals are not supported by this format, see KT-26568
* </pre>
*/
public Builder clearArrayDimensionCount() {

View File

@@ -4613,7 +4613,7 @@ public final class DebugJvmProtoBuf {
* <code>extend .org.jetbrains.kotlin.metadata.Class { ... }</code>
*
* <pre>
* If absent, assumed to be "main" (JvmProtoBufUtil.DEFAULT_MODULE_NAME)
* If absent, assumed to be JvmAbi.DEFAULT_MODULE_NAME
* </pre>
*/
public static final

View File

@@ -1,25 +1,23 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.api.Project
import java.util.*
import java.io.File
import org.gradle.api.tasks.bundling.Jar
import org.gradle.plugins.ide.idea.model.IdeaModel
import org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import org.jetbrains.kotlin.gradle.tasks.Kotlin2JsCompile
import proguard.gradle.ProGuardTask
import org.gradle.kotlin.dsl.*
buildscript {
extra["defaultSnapshotVersion"] = "1.3-SNAPSHOT"
// when updating please also update JPS artifacts configuration: https://jetbrains.quip.com/zzGUAYSJ6gv3/JPS-Build-update-bootstrap
kotlinBootstrapFrom(BootstrapOption.TeamCity("1.3.50-dev-526", onlySuccessBootstrap = false))
kotlinBootstrapFrom(BootstrapOption.TeamCity("1.3.20-dev-1708", onlySuccessBootstrap = false))
repositories {
repositories.withRedirector(project) {
bootstrapKotlinRepo?.let(::maven)
val cacheRedirectorEnabled = findProperty("cacheRedirectorEnabled")?.toString()?.toBoolean() == true
if (cacheRedirectorEnabled) {
maven("https://cache-redirector.jetbrains.com/plugins.gradle.org/m2")
} else {
maven("https://plugins.gradle.org/m2")
}
maven("https://plugins.gradle.org/m2")
}
// a workaround for kotlin compiler classpath in kotlin project: sometimes gradle substitutes
@@ -32,16 +30,15 @@ buildscript {
classpath("com.gradle.publish:plugin-publish-plugin:0.9.7")
classpath(kotlin("gradle-plugin", bootstrapKotlinVersion))
classpath("net.sf.proguard:proguard-gradle:6.1.0")
classpath("net.sf.proguard:proguard-gradle:5.3.3")
classpath("org.jetbrains.dokka:dokka-gradle-plugin:0.9.17")
}
}
plugins {
`build-scan`
`build-scan` version "1.15"
idea
id("jps-compatible")
id("org.jetbrains.gradle.plugin.idea-ext")
}
pill {
@@ -59,11 +56,11 @@ buildScan {
}
val configuredJdks: List<JdkId> =
getConfiguredJdks().also {
it.forEach { jdkId ->
logger.info("Using ${jdkId.majorVersion} home: ${jdkId.homeDir}")
getConfiguredJdks().also {
it.forEach {
logger.info("Using ${it.majorVersion} home: ${it.homeDir}")
}
}
}
val defaultSnapshotVersion: String by extra
val buildNumber by extra(findProperty("build.number")?.toString() ?: defaultSnapshotVersion)
@@ -78,7 +75,19 @@ allprojects {
extra["kotlin_root"] = rootDir
val jpsBootstrap by configurations.creating
val cidrKotlinPlugin by configurations.creating
val appcodeKotlinPlugin by configurations.creating
val clionKotlinPlugin by configurations.creating
val includeCidr by extra(project.getBooleanProperty("cidrPluginsEnabled") ?: false)
dependencies {
if (includeCidr) {
cidrKotlinPlugin(project(":prepare:cidr-plugin", "runtimeJar"))
appcodeKotlinPlugin(project(":prepare:appcode-plugin", "runtimeJar"))
clionKotlinPlugin(project(":prepare:clion-plugin", "runtimeJar"))
}
}
val commonBuildDir = File(rootDir, "build")
val distDir by extra("$rootDir/dist")
@@ -87,20 +96,13 @@ val distLibDir = "$distKotlinHomeDir/lib"
val commonLocalDataDir = "$rootDir/local"
val ideaSandboxDir = "$commonLocalDataDir/ideaSandbox"
val ideaUltimateSandboxDir = "$commonLocalDataDir/ideaUltimateSandbox"
val artifactsDir = "$distDir/artifacts"
val ideaPluginDir = "$artifactsDir/ideaPlugin/Kotlin"
val ideaUltimatePluginDir = "$artifactsDir/ideaUltimatePlugin/Kotlin"
extra["ktorExcludesForDaemon"] = listOf(
"org.jetbrains.kotlin" to "kotlin-reflect",
"org.jetbrains.kotlin" to "kotlin-stdlib",
"org.jetbrains.kotlin" to "kotlin-stdlib-common",
"org.jetbrains.kotlin" to "kotlin-stdlib-jdk8",
"org.jetbrains.kotlin" to "kotlin-stdlib-jdk7",
"org.jetbrains.kotlinx" to "kotlinx-coroutines-jdk8",
"org.jetbrains.kotlinx" to "kotlinx-coroutines-core",
"org.jetbrains.kotlinx" to "kotlinx-coroutines-core-common"
)
val clionSandboxDir = "$commonLocalDataDir/clionSandbox"
val appcodeSandboxDir = "$commonLocalDataDir/appcodeSandbox"
val ideaPluginDir = "$distDir/artifacts/ideaPlugin/Kotlin"
val ideaUltimatePluginDir = "$distDir/artifacts/ideaUltimatePlugin/Kotlin"
val cidrPluginDir = "$distDir/artifacts/cidrPlugin/Kotlin"
val appcodePluginDir = "$distDir/artifacts/appcodePlugin/Kotlin"
val clionPluginDir = "$distDir/artifacts/clionPlugin/Kotlin"
// TODO: use "by extra()" syntax where possible
extra["distLibDir"] = project.file(distLibDir)
@@ -108,8 +110,13 @@ extra["libsDir"] = project.file(distLibDir)
extra["commonLocalDataDir"] = project.file(commonLocalDataDir)
extra["ideaSandboxDir"] = project.file(ideaSandboxDir)
extra["ideaUltimateSandboxDir"] = project.file(ideaUltimateSandboxDir)
extra["clionSandboxDir"] = project.file(ideaSandboxDir)
extra["appcodeSandboxDir"] = project.file(ideaSandboxDir)
extra["ideaPluginDir"] = project.file(ideaPluginDir)
extra["ideaUltimatePluginDir"] = project.file(ideaUltimatePluginDir)
extra["cidrPluginDir"] = project.file(cidrPluginDir)
extra["appcodePluginDir"] = project.file(appcodePluginDir)
extra["clionPluginDir"] = project.file(clionPluginDir)
extra["isSonatypeRelease"] = false
// Work-around necessary to avoid setting null javaHome. Will be removed after support of lazy task configuration
@@ -131,33 +138,20 @@ fun checkJDK() {
if (jdkChecked) {
return
}
val unpresentJdks = JdkMajorVersion.values()
.filter { it.isMandatory() }
.map { it.name }
.filter { extra[it] == jdkNotFoundConst }
.toList()
if (unpresentJdks.isNotEmpty()) {
throw GradleException("Please set environment variable" +
(if (unpresentJdks.size > 1) "s" else "") +
": " + unpresentJdks.joinToString() +
" to point to corresponding JDK installation.")
var unpresentJdks = JdkMajorVersion.values().filter { it.isMandatory() }.map { it -> it.name }.filter { it == null || extra[it] == jdkNotFoundConst }.toList()
if (!unpresentJdks.isEmpty()) {
throw GradleException("Please set environment variable${if (unpresentJdks.size > 1) "s" else ""}: ${unpresentJdks.joinToString()} to point to corresponding JDK installation.")
}
jdkChecked = true
}
rootProject.apply {
from(rootProject.file("gradle/versions.gradle.kts"))
from(rootProject.file("gradle/report.gradle.kts"))
from(rootProject.file("gradle/javaInstrumentation.gradle.kts"))
from(rootProject.file("gradle/jps.gradle.kts"))
from(rootProject.file("versions.gradle.kts"))
from(rootProject.file("report.gradle.kts"))
}
IdeVersionConfigurator.setCurrentIde(this)
extra["versions.protobuf"] = "2.6.1"
extra["versions.protobuf-java"] = "2.6.1"
extra["versions.javax.inject"] = "1"
extra["versions.jsr305"] = "1.3.9"
extra["versions.jansi"] = "1.16"
@@ -166,9 +160,8 @@ extra["versions.junit"] = "4.12"
extra["versions.javaslang"] = "2.0.6"
extra["versions.ant"] = "1.8.2"
extra["versions.android"] = "2.3.1"
val coroutinesVersion = if (Platform[192].orHigher()) "1.2.1" else "1.1.1"
extra["versions.kotlinx-coroutines-core"] = coroutinesVersion
extra["versions.kotlinx-coroutines-jdk8"] = coroutinesVersion
extra["versions.kotlinx-coroutines-core"] = "1.0.1"
extra["versions.kotlinx-coroutines-jdk8"] = "1.0.1"
extra["versions.json"] = "20160807"
extra["versions.native-platform"] = "0.14"
extra["versions.ant-launcher"] = "1.8.0"
@@ -178,114 +171,105 @@ extra["versions.jflex"] = "1.7.0"
extra["versions.markdown"] = "0.1.25"
extra["versions.trove4j"] = "1.0.20181211"
// NOTE: please, also change KTOR_NAME in pathUtil.kt and all versions in corresponding jar names in daemon tests.
extra["versions.ktor-network"] = "1.0.1"
if (!project.hasProperty("versions.kotlin-native")) {
extra["versions.kotlin-native"] = "1.3.50-dev-11052"
}
val isTeamcityBuild = project.kotlinBuildProperties.isTeamcityBuild
val intellijUltimateEnabled by extra(project.kotlinBuildProperties.intellijUltimateEnabled)
val isTeamcityBuild = project.hasProperty("teamcity") || System.getenv("TEAMCITY_VERSION") != null
val intellijUltimateEnabled = project.getBooleanProperty("intellijUltimateEnabled") ?: isTeamcityBuild
val effectSystemEnabled by extra(project.getBooleanProperty("kotlin.compiler.effectSystemEnabled") ?: false)
val newInferenceEnabled by extra(project.getBooleanProperty("kotlin.compiler.newInferenceEnabled") ?: false)
val intellijSeparateSdks = project.getBooleanProperty("intellijSeparateSdks") ?: false
extra["intellijUltimateEnabled"] = intellijUltimateEnabled
extra["intellijSeparateSdks"] = intellijSeparateSdks
extra["IntellijCoreDependencies"] =
listOf(
if (Platform[191].orHigher()) "asm-all-7.0.1" else "asm-all",
"guava",
"jdom",
"jna",
"log4j",
"picocontainer",
"snappy-in-java",
"streamex",
"trove4j"
)
listOf("annotations",
if (Platform[191].orHigher()) "asm-all-7.0" else "asm-all",
"guava",
"jdom",
"jna",
"log4j",
"picocontainer",
"snappy-in-java",
"streamex",
"trove4j")
extra["compilerModules"] = arrayOf(
":compiler:util",
":compiler:container",
":compiler:resolution",
":compiler:serialization",
":compiler:psi",
":compiler:frontend",
":compiler:frontend.common",
":compiler:frontend.java",
":compiler:cli-common",
":compiler:ir.tree",
":compiler:ir.psi2ir",
":compiler:ir.backend.common",
":compiler:backend.jvm",
":compiler:backend.js",
":compiler:ir.serialization.common",
":compiler:ir.serialization.js",
":kotlin-util-io",
":kotlin-util-klib",
":compiler:backend-common",
":compiler:backend",
":compiler:plugin-api",
":compiler:light-classes",
":compiler:cli",
":compiler:cli-js",
":compiler:incremental-compilation-impl",
":js:js.ast",
":js:js.serializer",
":js:js.parser",
":js:js.frontend",
":js:js.translator",
":js:js.dce",
":compiler",
":kotlin-build-common",
":core:metadata",
":core:metadata.jvm",
":core:descriptors",
":core:descriptors.jvm",
":core:deserialization",
":core:util.runtime",
":core:type-system",
":compiler:fir:cones",
":compiler:fir:resolve",
":compiler:fir:tree",
":compiler:fir:psi2fir",
":compiler:fir:fir2ir",
":compiler:fir:java"
":compiler:util",
":compiler:container",
":compiler:resolution",
":compiler:serialization",
":compiler:psi",
*if (project.findProperty("fir.enabled") == "true") {
arrayOf(
":compiler:fir:cones",
":compiler:fir:resolve",
":compiler:fir:tree",
":compiler:fir:psi2fir"
)
} else {
emptyArray()
},
":compiler:frontend",
":compiler:frontend.java",
":compiler:frontend.script",
":compiler:cli-common",
":compiler:daemon-common",
":compiler:daemon",
":compiler:ir.tree",
":compiler:ir.psi2ir",
":compiler:ir.backend.common",
":compiler:backend.js",
":compiler:backend-common",
":compiler:backend",
":compiler:plugin-api",
":compiler:light-classes",
":compiler:cli",
":compiler:incremental-compilation-impl",
":js:js.ast",
":js:js.serializer",
":js:js.parser",
":js:js.frontend",
":js:js.translator",
":js:js.dce",
":compiler",
":kotlin-build-common",
":core:metadata",
":core:metadata.jvm",
":core:descriptors",
":core:descriptors.jvm",
":core:deserialization",
":core:util.runtime"
)
val coreLibProjects = listOfNotNull(
":kotlin-stdlib",
":kotlin-stdlib-common",
":kotlin-stdlib-js",
// Local builds are disabled at the request of the lib team
// TODO: Enable when tests are fixed
":kotlin-stdlib-js-ir".takeIf { isTeamcityBuild },
":kotlin-stdlib-jdk7",
":kotlin-stdlib-jdk8",
":kotlin-test:kotlin-test-common",
":kotlin-test:kotlin-test-jvm",
":kotlin-test:kotlin-test-junit",
":kotlin-test:kotlin-test-junit5",
":kotlin-test:kotlin-test-testng",
":kotlin-test:kotlin-test-js",
":kotlin-reflect"
val coreLibProjects = listOf(
":kotlin-stdlib",
":kotlin-stdlib-common",
":kotlin-stdlib-js",
":kotlin-stdlib-jre7",
":kotlin-stdlib-jre8",
":kotlin-stdlib-jdk7",
":kotlin-stdlib-jdk8",
":kotlin-test:kotlin-test-common",
":kotlin-test:kotlin-test-jvm",
":kotlin-test:kotlin-test-junit",
":kotlin-test:kotlin-test-junit5",
":kotlin-test:kotlin-test-testng",
":kotlin-test:kotlin-test-js",
":kotlin-reflect"
)
val gradlePluginProjects = listOf(
":kotlin-gradle-plugin",
":kotlin-gradle-plugin:plugin-marker",
":kotlin-gradle-plugin-api",
":kotlin-gradle-plugin",
":kotlin-gradle-plugin:plugin-marker",
":kotlin-gradle-plugin-api",
// ":kotlin-gradle-plugin-integration-tests", // TODO: build fails
":kotlin-allopen",
":kotlin-allopen:plugin-marker",
":kotlin-annotation-processing-gradle",
":kotlin-noarg",
":kotlin-noarg:plugin-marker",
":kotlin-sam-with-receiver"
":kotlin-allopen",
":kotlin-allopen:plugin-marker",
":kotlin-annotation-processing-gradle",
":kotlin-noarg",
":kotlin-noarg:plugin-marker",
":kotlin-sam-with-receiver"
)
apply {
@@ -314,29 +298,28 @@ val ignoreTestFailures by extra(project.findProperty("ignoreTestFailures")?.toSt
allprojects {
configurations.maybeCreate("embedded")
jvmTarget = defaultJvmTarget
javaHome = defaultJavaHome
if (defaultJavaHome != null) {
javaHome = defaultJavaHome
} else {
logger.error("Could not find default java home. Please set environment variable JDK_${defaultJavaHome} to point to JDK ${defaultJavaHome} installation.")
}
// There are problems with common build dir:
// - some tests (in particular js and binary-compatibility-validator depend on the fixed (default) location
// - idea seems unable to exclude common buildDir from indexing
// - idea seems unable to exclude common builddir from indexing
// therefore it is disabled by default
// buildDir = File(commonBuildDir, project.name)
val mirrorRepo: String? = findProperty("maven.repository.mirror")?.toString()
repositories {
kotlinBuildLocalRepo(project)
intellijSdkRepo(project)
androidDxJarRepo(project)
mirrorRepo?.let(::maven)
jcenter()
maven(protobufRepo)
maven(intellijRepo)
maven("https://dl.bintray.com/kotlin/ktor")
maven("https://kotlin.bintray.com/kotlin-dependencies")
bootstrapKotlinRepo?.let(::maven)
internalKotlinRepo?.let(::maven)
jcenter()
}
configureJvmProject(javaHome!!, jvmTarget!!)
@@ -344,7 +327,6 @@ allprojects {
val commonCompilerArgs = listOfNotNull(
"-Xallow-kotlin-package",
"-Xread-deserialized-contracts",
"-Xjvm-default=compatibility",
"-Xprogressive".takeIf { hasProperty("test.progressive.mode") } // TODO: change to "-progressive" after bootstrap
)
@@ -370,6 +352,10 @@ allprojects {
enabled = false
}
task<Jar>("javadocJar") {
classifier = "javadoc"
}
tasks.withType<Jar> {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
@@ -389,30 +375,21 @@ allprojects {
fun File.toProjectRootRelativePathOrSelf() = (relativeToOrNull(rootDir)?.takeUnless { it.startsWith("..") } ?: this).path
fun FileCollection.printClassPath(role: String) =
println("${project.path} $role classpath:\n ${joinToString("\n ") { it.toProjectRootRelativePathOrSelf() }}")
println("${project.path} $role classpath:\n ${joinToString("\n ") { it.toProjectRootRelativePathOrSelf() } }")
try {
javaPluginConvention()
} catch (_: UnknownDomainObjectException) {
null
}?.let { javaConvention ->
try { javaPluginConvention() } catch (_: UnknownDomainObjectException) { null }?.let { javaConvention ->
task("printCompileClasspath") { doFirst { javaConvention.sourceSets["main"].compileClasspath.printClassPath("compile") } }
task("printRuntimeClasspath") { doFirst { javaConvention.sourceSets["main"].runtimeClasspath.printClassPath("runtime") } }
task("printTestCompileClasspath") { doFirst { javaConvention.sourceSets["test"].compileClasspath.printClassPath("test compile") } }
task("printTestRuntimeClasspath") { doFirst { javaConvention.sourceSets["test"].runtimeClasspath.printClassPath("test runtime") } }
}
run configureCompilerClasspath@{
run configureCompilerClasspath@ {
val bootstrapCompilerClasspath by rootProject.buildscript.configurations
configurations.findByName("kotlinCompilerClasspath")?.let {
dependencies.add(it.name, files(bootstrapCompilerClasspath))
}
}
// Aggregate task for build related checks
tasks.register("checkBuild")
apply(from = "$rootDir/gradle/cacheRedirector.gradle.kts")
}
}
@@ -437,8 +414,13 @@ gradle.taskGraph.whenReady {
}
}
val dist = tasks.register("dist") {
dependsOn(":kotlin-compiler:dist")
val dist by task<Copy> {
val childDistTasks = getTasksByName("dist", true) - this@task
dependsOn(childDistTasks)
into(distDir)
from(files("compiler/cli/bin")) { into("kotlinc/bin") }
from(files("license")) { into("kotlinc/license") }
}
val copyCompilerToIdeaPlugin by task<Copy> {
@@ -449,7 +431,8 @@ val copyCompilerToIdeaPlugin by task<Copy> {
val ideaPlugin by task<Task> {
dependsOn(copyCompilerToIdeaPlugin)
dependsOn(":prepare:idea-plugin:ideaPlugin")
val childIdeaPluginTasks = getTasksByName("ideaPlugin", true) - this@task
dependsOn(childIdeaPluginTasks)
}
tasks {
@@ -462,30 +445,28 @@ tasks {
create("cleanupArtifacts") {
doLast {
delete(artifactsDir)
}
}
listOf("clean", "assemble", "install", "dist").forEach { taskName ->
create("coreLibs${taskName.capitalize()}") {
coreLibProjects.forEach { projectName -> dependsOn("$projectName:$taskName") }
delete(ideaPluginDir)
delete(ideaUltimatePluginDir)
delete(cidrPluginDir)
delete(appcodePluginDir)
delete(clionPluginDir)
}
}
create("coreLibsTest") {
(coreLibProjects + listOf(
":kotlin-stdlib:samples",
":kotlin-test:kotlin-test-js:kotlin-test-js-it",
":kotlinx-metadata-jvm",
":tools:binary-compatibility-validator"
":kotlin-stdlib:samples",
":kotlin-test:kotlin-test-js:kotlin-test-js-it",
":kotlinx-metadata-jvm",
":tools:binary-compatibility-validator"
)).forEach {
dependsOn("$it:check")
dependsOn(it + ":check")
}
}
create("gradlePluginTest") {
gradlePluginProjects.forEach {
dependsOn("$it:check")
dependsOn(it + ":check")
}
}
@@ -495,12 +476,10 @@ tasks {
create("jvmCompilerTest") {
dependsOn("dist")
dependsOn(
":compiler:test",
":compiler:container:test",
":compiler:tests-java8:test",
":compiler:tests-spec:remoteRunTests"
)
dependsOn(":compiler:test",
":compiler:container:test",
":compiler:tests-java8:test",
":compiler:tests-spec:remoteRunTests")
dependsOn(":plugins:jvm-abi-gen:test")
}
@@ -509,27 +488,15 @@ tasks {
dependsOn(":js:js.tests:runMocha")
}
create("firCompilerTest") {
dependsOn(":compiler:fir:psi2fir:test")
dependsOn(":compiler:fir:resolve:test")
dependsOn(":compiler:fir:fir2ir:test")
}
create("scriptingTest") {
dependsOn("dist")
dependsOn(":kotlin-script-util:test")
dependsOn(":kotlin-scripting-compiler:test")
dependsOn(":kotlin-scripting-jvm-host-test:test")
dependsOn(":kotlin-scripting-jsr223-test:test")
dependsOn(":kotlin-scripting-jvm-host-test:embeddableTest")
dependsOn(":kotlin-scripting-jsr223-test:embeddableTest")
dependsOn(":kotlin-main-kts-test:test")
dependsOn(":kotlin-scripting-jvm-host:test")
}
create("compilerTest") {
dependsOn("jvmCompilerTest")
dependsOn("jsCompilerTest")
dependsOn("firCompilerTest")
dependsOn("scriptingTest")
dependsOn(":kotlin-build-common:test")
@@ -576,59 +543,45 @@ tasks {
create("idea-plugin-additional-tests") {
dependsOn("dist")
dependsOn(
":idea:idea-gradle:test",
":idea:idea-gradle-native:test",
":idea:idea-maven:test",
":j2k:test",
":nj2k:test",
":idea:jvm-debugger:jvm-debugger-core:test",
":idea:jvm-debugger:jvm-debugger-evaluation:test",
":idea:jvm-debugger:jvm-debugger-sequence:test",
":idea:jvm-debugger:eval4j:test"
)
dependsOn(":idea:idea-gradle:test",
":idea:idea-maven:test",
":j2k:test",
":eval4j:test")
}
create("idea-plugin-tests") {
dependsOn("dist")
dependsOn(
"idea-plugin-main-tests",
"idea-plugin-additional-tests"
)
dependsOn("idea-plugin-main-tests",
"idea-plugin-additional-tests")
}
create("android-ide-tests") {
dependsOn("dist")
dependsOn(
":plugins:android-extensions-ide:test",
":idea:idea-android:test",
":kotlin-annotation-processing:test"
)
dependsOn(":plugins:android-extensions-ide:test",
":idea:idea-android:test",
":kotlin-annotation-processing:test")
}
create("plugins-tests") {
dependsOn("dist")
dependsOn(
":kotlin-annotation-processing:test",
":kotlin-source-sections-compiler-plugin:test",
":kotlin-allopen-compiler-plugin:test",
":kotlin-noarg-compiler-plugin:test",
":kotlin-sam-with-receiver-compiler-plugin:test",
":plugins:uast-kotlin:test",
":kotlin-annotation-processing-gradle:test",
":kotlinx-serialization-compiler-plugin:test",
":kotlinx-serialization-ide-plugin:test"
)
dependsOn(":kotlin-annotation-processing:test",
":kotlin-source-sections-compiler-plugin:test",
":kotlin-allopen-compiler-plugin:test",
":kotlin-noarg-compiler-plugin:test",
":kotlin-sam-with-receiver-compiler-plugin:test",
":plugins:uast-kotlin:test",
":kotlin-annotation-processing-gradle:test",
":kotlinx-serialization-ide-plugin:test")
}
create("ideaPluginTest") {
dependsOn(
"idea-plugin-tests",
"jps-tests",
"plugins-tests",
"android-ide-tests",
":generators:test"
"idea-plugin-tests",
"jps-tests",
"plugins-tests",
"android-ide-tests",
":generators:test"
)
}
@@ -663,27 +616,16 @@ val zipCompiler by task<Zip> {
}
}
val zipStdlibTests by task<Zip> {
destinationDirectory.set(file(distDir))
archiveFileName.set("kotlin-stdlib-tests.zip")
from("libraries/stdlib/common/test") { into("common") }
from("libraries/stdlib/test") { into("test") }
doLast {
logger.lifecycle("Stdlib tests are packed to ${archiveFile.get()}")
}
}
val zipTestData by task<Zip> {
dependsOn(zipStdlibTests)
destinationDirectory.set(file(distDir))
archiveFileName.set("kotlin-test-data.zip")
isZip64 = true
destinationDir = file(distDir)
archiveName = "kotlin-test-data.zip"
from("compiler/testData") { into("compiler") }
from("idea/testData") { into("ide") }
from("idea/idea-completion/testData") { into("ide/completion") }
from("compiler/tests-common/tests/org/jetbrains/kotlin/coroutineTestUtil.kt") { into("compiler") }
from("libraries/stdlib/common/test") { into("stdlib/common") }
from("libraries/stdlib/test") { into("stdlib/test") }
doLast {
logger.lifecycle("Test data packed to ${archiveFile.get()}")
logger.lifecycle("Test data packed to $archivePath")
}
}
@@ -711,14 +653,74 @@ val zipPlugin by task<Zip> {
}
}
fun cidrPlugin(product: String, pluginDir: String) = tasks.creating(Copy::class.java) {
if (!includeCidr) {
throw GradleException("CIDR plugins require 'cidrPluginsEnabled' property turned on")
}
val prepareCidrPlugin = getTasksByName("cidrPlugin", true)
val prepareCurrentPlugin = (getTasksByName(product.toLowerCase() + "Plugin", true) - this)
prepareCurrentPlugin.forEach { it.mustRunAfter(prepareCidrPlugin) }
dependsOn(ideaPlugin)
dependsOn(prepareCidrPlugin)
dependsOn(prepareCurrentPlugin)
into(pluginDir)
from(ideaPluginDir) {
exclude("lib/kotlin-plugin.jar")
exclude("lib/android-lint.jar")
exclude("lib/android-ide.jar")
exclude("lib/android-output-parser-ide.jar")
exclude("lib/android-extensions-ide.jar")
exclude("lib/android-extensions-compiler.jar")
exclude("lib/kapt3-idea.jar")
exclude("lib/jps-ide.jar")
exclude("lib/jps/**")
exclude("kotlinc/**")
exclude("lib/maven-ide.jar")
}
from(cidrKotlinPlugin) { into("lib") }
from(configurations[product.toLowerCase() + "KotlinPlugin"]) { into("lib") }
}
fun zipCidrPlugin(product: String, productVersion: String) = tasks.creating(Zip::class.java) {
// Note: "cidrPluginVersion" has different format and semantics from "pluginVersion" used in IJ and AS plugins.
val cidrPluginVersion = project.findProperty("cidrPluginVersion") as String? ?: "beta-1"
val destPath = project.findProperty("pluginZipPath") as String?
?: "$distDir/artifacts/kotlin-plugin-$kotlinVersion-$product-$cidrPluginVersion-$productVersion.zip"
val destFile = File(destPath)
destinationDir = destFile.parentFile
archiveName = destFile.name
from(tasks[product.toLowerCase() + "Plugin"])
into("Kotlin")
setExecutablePermissions()
doLast {
logger.lifecycle("Plugin artifacts packed to $archivePath")
}
}
if (includeCidr) {
val appcodePlugin by cidrPlugin("AppCode", appcodePluginDir)
val appcodeVersion = extra["versions.appcode"] as String
val zipAppCodePlugin by zipCidrPlugin("AppCode", appcodeVersion)
val clionPlugin by cidrPlugin("CLion", clionPluginDir)
val clionVersion = extra["versions.clion"] as String
val zipCLionPlugin by zipCidrPlugin("CLion", clionVersion)
}
configure<IdeaModel> {
module {
excludeDirs = files(
project.buildDir,
commonLocalDataDir,
".gradle",
"dependencies",
"dist"
project.buildDir,
commonLocalDataDir,
".gradle",
"dependencies",
"dist"
).toSet()
}
}
@@ -726,7 +728,7 @@ configure<IdeaModel> {
fun jdkPath(version: String): String {
val jdkName = "JDK_${version.replace(".", "")}"
val jdkMajorVersion = JdkMajorVersion.valueOf(jdkName)
return configuredJdks.find { it.majorVersion == jdkMajorVersion }?.homeDir?.canonicalPath ?: jdkNotFoundConst
return configuredJdks.find { it.majorVersion == jdkMajorVersion }?.homeDir?.canonicalPath?:jdkNotFoundConst
}
@@ -743,7 +745,6 @@ fun Project.configureJvmProject(javaHome: String, javaVersion: String) {
tasks.withType<KotlinCompile> {
kotlinOptions.jdkHome = javaHome
kotlinOptions.jvmTarget = javaVersion
kotlinOptions.freeCompilerArgs += "-Xjvm-default=compatibility"
}
tasks.withType<Test> {
@@ -788,3 +789,12 @@ tasks.create("findShadowJarsInClasspath").doLast {
project.checkConfig("testCompileClasspath")
}
}
allprojects {
afterEvaluate {
if (cacheRedirectorEnabled()) {
logger.info("Redirecting repositories for $displayName")
repositories.redirect()
}
}
}

View File

@@ -1,19 +1,15 @@
import java.util.Properties
extra["versions.shadow"] = "4.0.3"
extra["versions.native-platform"] = "0.14"
buildscript {
val cacheRedirectorEnabled = findProperty("cacheRedirectorEnabled")?.toString()?.toBoolean() == true
val buildSrcKotlinVersion: String by extra(findProperty("buildSrc.kotlin.version")?.toString() ?: embeddedKotlinVersion)
val buildSrcKotlinRepo: String? by extra(findProperty("buildSrc.kotlin.repo") as String?)
extra["versions.shadow"] = "2.0.2"
extra["versions.native-platform"] = "0.14"
repositories {
if (cacheRedirectorEnabled) {
maven("https://cache-redirector.jetbrains.com/jcenter.bintray.com")
} else {
jcenter()
}
buildSrcKotlinRepo?.let {
@@ -63,15 +59,12 @@ fun Project.getBooleanProperty(name: String): Boolean? = this.findProperty(name)
}
rootProject.apply {
from(rootProject.file("../gradle/versions.gradle.kts"))
from(rootProject.file("../versions.gradle.kts"))
}
val flags = LocalBuildProperties(project)
val isTeamcityBuild = flags.isTeamcityBuild
val intellijUltimateEnabled by extra(flags.intellijUltimateEnabled)
val isTeamcityBuild = project.hasProperty("teamcity") || System.getenv("TEAMCITY_VERSION") != null
val intellijUltimateEnabled by extra(project.getBooleanProperty("intellijUltimateEnabled") ?: isTeamcityBuild)
val intellijSeparateSdks by extra(project.getBooleanProperty("intellijSeparateSdks") ?: false)
val verifyDependencyOutput by extra( getBooleanProperty("kotlin.build.dependency.output.verification") ?: isTeamcityBuild)
extra["intellijReleaseType"] = if (extra["versions.intellijSdk"]?.toString()?.endsWith("SNAPSHOT") == true)
"snapshots"
@@ -80,29 +73,28 @@ else
extra["versions.androidDxSources"] = "5.0.0_r2"
extra["customDepsOrg"] = "kotlin.build"
extra["customDepsOrg"] = "kotlin.build.custom.deps"
repositories {
maven("https://jetbrains.bintray.com/intellij-third-party-dependencies/")
maven("https://plugins.gradle.org/m2/")
jcenter()
if (cacheRedirectorEnabled) {
maven("https://cache-redirector.jetbrains.com/jcenter.bintray.com")
}
extra["buildSrcKotlinRepo"]?.let {
maven(url = it)
}
jcenter()
}
dependencies {
compile(kotlin("stdlib", embeddedKotlinVersion))
compile("net.rubygrapefruit:native-platform:${property("versions.native-platform")}")
compile("net.rubygrapefruit:native-platform-windows-amd64:${property("versions.native-platform")}")
compile("net.rubygrapefruit:native-platform-windows-i386:${property("versions.native-platform")}")
compile("com.jakewharton.dex:dex-method-list:3.0.0")
compile("com.github.jengelman.gradle.plugins:shadow:${property("versions.shadow")}")
compile("org.jetbrains.intellij.deps:asm-all:7.0.1")
compile("gradle.plugin.org.jetbrains.gradle.plugin.idea-ext:gradle-idea-ext:0.5")
compile("org.ow2.asm:asm-all:6.0_BETA")
}
samWithReceiver {
@@ -112,39 +104,4 @@ samWithReceiver {
fun Project.`samWithReceiver`(configure: org.jetbrains.kotlin.samWithReceiver.gradle.SamWithReceiverExtension.() -> Unit): Unit =
extensions.configure("samWithReceiver", configure)
tasks["build"].dependsOn(":prepare-deps:build")
allprojects {
tasks.register("checkBuild")
afterEvaluate {
apply(from = "$rootDir/../gradle/cacheRedirector.gradle.kts")
}
}
// TODO: hide these classes in special gradle plugin for kotlin-ultimate which will support local.properties
class LocalBuildPropertiesProvider(private val project: Project) {
private val localProperties: Properties = Properties()
val rootProjectDir: File = project.rootProject.rootDir.parentFile
init {
rootProjectDir.resolve("local.properties").takeIf { it.isFile }?.let {
it.reader().use(localProperties::load)
}
}
fun getString(name: String): String? = project.findProperty(name)?.toString() ?: localProperties[name]?.toString()
fun getBoolean(name: String): Boolean = getString(name)?.toBoolean() == true
}
class LocalBuildProperties(project: Project) {
val propertiesProvider = LocalBuildPropertiesProvider(project)
val isTeamcityBuild = propertiesProvider.getString("teamcity") != null || System.getenv("TEAMCITY_VERSION") != null
val intellijUltimateEnabled =
(propertiesProvider.getBoolean("intellijUltimateEnabled") || isTeamcityBuild)
&& propertiesProvider.rootProjectDir.resolve("kotlin-ultimate").exists()
}
tasks["build"].dependsOn(":prepare-deps:android-dx:build", ":prepare-deps:intellij-sdk:build")

View File

@@ -1,4 +1,7 @@
org.gradle.jvmargs=-Duser.country=US -Dkotlin.daemon.jvm.options=-Xmx1600m -Dfile.encoding=UTF-8
org.gradle.daemon=true
org.gradle.parallel=false
org.gradle.configureondemand=false
org.gradle.jvmargs=-Duser.country=US -Dkotlin.daemon.jvm.options=-Xmx1600m
cacheRedirectorEnabled=true

View File

@@ -0,0 +1,11 @@
org.gradle.daemon=true
org.gradle.parallel=false
org.gradle.configureondemand=false
org.gradle.jvmargs=-Duser.country=US -Dkotlin.daemon.jvm.options=-Xmx1600m
cacheRedirectorEnabled=true
#buildSrc.kotlin.repo=https://jcenter.bintray.com
#buildSrc.kotlin.version=1.1.50
intellijUltimateEnabled=false

View File

@@ -0,0 +1,11 @@
org.gradle.daemon=true
org.gradle.parallel=false
org.gradle.configureondemand=false
org.gradle.jvmargs=-Duser.country=US -Dkotlin.daemon.jvm.options=-Xmx1600m
cacheRedirectorEnabled=true
#buildSrc.kotlin.repo=https://jcenter.bintray.com
#buildSrc.kotlin.version=1.1.50
intellijUltimateEnabled=false

View File

@@ -1,4 +1,7 @@
org.gradle.jvmargs=-Duser.country=US -Dkotlin.daemon.jvm.options=-Xmx1600m -Dfile.encoding=UTF-8
org.gradle.daemon=true
org.gradle.parallel=false
org.gradle.configureondemand=false
org.gradle.jvmargs=-Duser.country=US -Dkotlin.daemon.jvm.options=-Xmx1600m
cacheRedirectorEnabled=true

View File

@@ -1,4 +1,7 @@
org.gradle.jvmargs=-Duser.country=US -Dkotlin.daemon.jvm.options=-Xmx1600m -Dfile.encoding=UTF-8
org.gradle.daemon=true
org.gradle.parallel=false
org.gradle.configureondemand=false
org.gradle.jvmargs=-Duser.country=US -Dkotlin.daemon.jvm.options=-Xmx1600m
cacheRedirectorEnabled=true

View File

@@ -1,8 +0,0 @@
org.gradle.jvmargs=-Duser.country=US -Dkotlin.daemon.jvm.options=-Xmx1600m -Dfile.encoding=UTF-8
cacheRedirectorEnabled=true
#buildSrc.kotlin.repo=https://jcenter.bintray.com
#buildSrc.kotlin.version=1.1.50
intellijUltimateEnabled=false

View File

@@ -0,0 +1,109 @@
import org.gradle.api.publish.ivy.internal.artifact.FileBasedIvyArtifact
import org.gradle.api.publish.ivy.internal.publication.DefaultIvyConfiguration
import org.gradle.api.publish.ivy.internal.publication.DefaultIvyPublicationIdentity
import org.gradle.api.publish.ivy.internal.publisher.IvyDescriptorFileGenerator
import java.io.File
import org.gradle.internal.os.OperatingSystem
import org.gradle.jvm.tasks.Jar
val toolsOs by lazy {
when {
OperatingSystem.current().isWindows -> "windows"
OperatingSystem.current().isMacOsX -> "macosx"
OperatingSystem.current().isLinux -> "linux"
else -> {
logger.error("Unknown operating system for android tools: ${OperatingSystem.current().name}")
""
}
}
}
val buildToolsVersion = rootProject.extra["versions.androidBuildTools"] as String
val dxSourcesVersion = rootProject.extra["versions.androidDxSources"] as String
repositories {
ivy {
artifactPattern("https://dl.google.com/android/repository/[artifact]_[revision](-[classifier]).[ext]")
artifactPattern("https://android.googlesource.com/platform/dalvik/+archive/android-$dxSourcesVersion/[artifact].[ext]")
metadataSources {
artifact()
}
}
}
val customDepsRepoDir = File(buildDir, "repo")
val customDepsOrg: String by rootProject.extra
val dxModuleName = "android-dx"
val dxRevision = buildToolsVersion
val dxRepoModuleDir = File(customDepsRepoDir, "$customDepsOrg/$dxModuleName/$dxRevision")
val buildToolsZip by configurations.creating
val dxSourcesTar by configurations.creating
dependencies {
buildToolsZip("google:build-tools:$buildToolsVersion:$toolsOs@zip")
dxSourcesTar("google:dx:0@tar.gz")
}
val unzipDxJar by tasks.creating {
dependsOn(buildToolsZip)
inputs.files(buildToolsZip)
outputs.files(File(dxRepoModuleDir, "dx.jar"))
doFirst {
project.copy {
from(zipTree(buildToolsZip.singleFile).files)
include("**/dx.jar")
into(dxRepoModuleDir)
}
}
}
val dxSourcesTargetDir = File(buildDir, "dx_src")
val untarDxSources by tasks.creating {
dependsOn(dxSourcesTar)
inputs.files(dxSourcesTar)
outputs.dir(dxSourcesTargetDir)
doFirst {
project.copy {
from(tarTree(dxSourcesTar.singleFile))
include("src/**")
includeEmptyDirs = false
into(dxSourcesTargetDir)
}
}
}
val prepareDxSourcesJar by tasks.creating(Jar::class) {
dependsOn(untarDxSources)
from("$dxSourcesTargetDir/src")
destinationDir = dxRepoModuleDir
baseName = "dx"
classifier = "sources"
}
val prepareIvyXml by tasks.creating {
dependsOn(unzipDxJar, prepareDxSourcesJar)
inputs.files(unzipDxJar, prepareDxSourcesJar)
val ivyFile = File(dxRepoModuleDir, "$dxModuleName.ivy.xml")
outputs.file(ivyFile)
doLast {
with(IvyDescriptorFileGenerator(DefaultIvyPublicationIdentity(customDepsOrg, dxModuleName, dxRevision))) {
addConfiguration(DefaultIvyConfiguration("default"))
addConfiguration(DefaultIvyConfiguration("sources"))
addArtifact(FileBasedIvyArtifact(File(dxRepoModuleDir, "dx.jar"), DefaultIvyPublicationIdentity(customDepsOrg, "dx", dxRevision)).also { it.conf = "default" })
addArtifact(FileBasedIvyArtifact(File(dxRepoModuleDir, "dx-sources.jar"), DefaultIvyPublicationIdentity(customDepsOrg, "dx", dxRevision)).also { it.conf = "sources" })
writeTo(ivyFile)
}
}
}
val build by tasks.creating {
dependsOn(unzipDxJar, prepareDxSourcesJar, prepareIvyXml)
}
val clean by tasks.creating(Delete::class) {
delete(dxRepoModuleDir)
delete(buildDir)
}

View File

@@ -1,431 +0,0 @@
@file:Suppress("PropertyName", "HasPlatformType", "UnstableApiUsage")
import org.gradle.internal.os.OperatingSystem
import java.io.Closeable
import java.io.FileWriter
import java.io.OutputStreamWriter
import java.net.URI
import java.text.SimpleDateFormat
import java.util.*
import javax.xml.stream.XMLOutputFactory
plugins {
base
}
val verifyDependencyOutput: Boolean by rootProject.extra
val intellijUltimateEnabled: Boolean by rootProject.extra
val intellijReleaseType: String by rootProject.extra
val intellijVersion = rootProject.extra["versions.intellijSdk"] as String
val asmVersion = rootProject.findProperty("versions.jar.asm-all") as String?
val androidStudioRelease = rootProject.findProperty("versions.androidStudioRelease") as String?
val androidStudioBuild = rootProject.findProperty("versions.androidStudioBuild") as String?
val intellijSeparateSdks: Boolean by rootProject.extra
val installIntellijCommunity = !intellijUltimateEnabled || intellijSeparateSdks
val installIntellijUltimate = intellijUltimateEnabled
val intellijVersionDelimiterIndex = intellijVersion.indexOfAny(charArrayOf('.', '-'))
if (intellijVersionDelimiterIndex == -1) {
error("Invalid IDEA version $intellijVersion")
}
val platformBaseVersion = intellijVersion.substring(0, intellijVersionDelimiterIndex)
logger.info("verifyDependencyOutput: $verifyDependencyOutput")
logger.info("intellijUltimateEnabled: $intellijUltimateEnabled")
logger.info("intellijVersion: $intellijVersion")
logger.info("androidStudioRelease: $androidStudioRelease")
logger.info("androidStudioBuild: $androidStudioBuild")
logger.info("intellijSeparateSdks: $intellijSeparateSdks")
logger.info("installIntellijCommunity: $installIntellijCommunity")
logger.info("installIntellijUltimate: $installIntellijUltimate")
val androidStudioOs by lazy {
when {
OperatingSystem.current().isWindows -> "windows"
OperatingSystem.current().isMacOsX -> "mac"
OperatingSystem.current().isLinux -> "linux"
else -> {
logger.error("Unknown operating system for android tools: ${OperatingSystem.current().name}")
""
}
}
}
repositories {
if (androidStudioRelease != null) {
ivy {
url = URI("https://dl.google.com/dl/android/studio/ide-zips/$androidStudioRelease")
patternLayout {
artifact("[artifact]-[revision]-$androidStudioOs.[ext]")
}
metadataSources {
artifact()
}
}
}
maven("https://www.jetbrains.com/intellij-repository/$intellijReleaseType")
maven("https://plugins.jetbrains.com/maven")
maven("https://jetbrains.bintray.com/intellij-third-party-dependencies/")
}
val intellij by configurations.creating
val intellijUltimate by configurations.creating
val androidStudio by configurations.creating
val sources by configurations.creating
val jpsStandalone by configurations.creating
val intellijCore by configurations.creating
val nodeJSPlugin by configurations.creating
/**
* Special repository for annotations.jar required for idea runtime only.
*
* See IntellijDependenciesKt.intellijRuntimeAnnotations for more details.
*/
val intellijRuntimeAnnotations = "intellij-runtime-annotations"
val customDepsRepoDir = rootProject.rootDir.parentFile.resolve("dependencies/repo")
val customDepsOrg: String by rootProject.extra
val customDepsRevision = intellijVersion
val repoDir = File(customDepsRepoDir, customDepsOrg)
dependencies {
if (androidStudioRelease != null) {
val extension = if (androidStudioOs == "linux" && androidStudioRelease.startsWith("3.5"))
"tar.gz"
else
"zip"
androidStudio("google:android-studio-ide:$androidStudioBuild@$extension")
} else {
if (installIntellijCommunity) {
intellij("com.jetbrains.intellij.idea:ideaIC:$intellijVersion")
}
if (installIntellijUltimate) {
intellijUltimate("com.jetbrains.intellij.idea:ideaIU:$intellijVersion")
}
}
if (asmVersion != null) {
sources("org.jetbrains.intellij.deps:asm-all:$asmVersion:sources@jar")
}
sources("com.jetbrains.intellij.idea:ideaIC:$intellijVersion:sources@jar")
jpsStandalone("com.jetbrains.intellij.idea:jps-standalone:$intellijVersion")
intellijCore("com.jetbrains.intellij.idea:intellij-core:$intellijVersion")
if (intellijUltimateEnabled) {
nodeJSPlugin("com.jetbrains.plugins:NodeJS:${rootProject.extra["versions.idea.NodeJS"]}@zip")
}
}
val makeIntellijCore = buildIvyRepositoryTask(intellijCore, customDepsOrg, customDepsRepoDir)
val makeIntellijAnnotations by tasks.creating(Copy::class.java) {
dependsOn(makeIntellijCore)
from(repoDir.resolve("intellij-core/$intellijVersion/artifacts/annotations.jar"))
val targetDir = File(repoDir, "$intellijRuntimeAnnotations/$intellijVersion")
into(targetDir)
val ivyFile = File(targetDir, "$intellijRuntimeAnnotations.ivy.xml")
outputs.files(ivyFile)
doLast {
writeIvyXml(
customDepsOrg,
intellijRuntimeAnnotations,
intellijVersion,
intellijRuntimeAnnotations,
targetDir,
targetDir,
targetDir,
allowAnnotations = true
)
}
}
val mergeSources by tasks.creating(Jar::class.java) {
dependsOn(sources)
from(provider { sources.map(::zipTree) })
destinationDirectory.set(File(repoDir, sources.name))
archiveBaseName.set("intellij")
archiveClassifier.set("sources")
archiveVersion.set(intellijVersion)
}
val sourcesFile = mergeSources.outputs.files.singleFile
val makeIde = if (androidStudioBuild != null) {
buildIvyRepositoryTask(
androidStudio,
customDepsOrg,
customDepsRepoDir,
if (androidStudioOs == "mac")
::skipContentsDirectory
else
::skipToplevelDirectory
)
} else {
val task = if (installIntellijUltimate) {
buildIvyRepositoryTask(intellijUltimate, customDepsOrg, customDepsRepoDir, null, sourcesFile)
} else {
buildIvyRepositoryTask(intellij, customDepsOrg, customDepsRepoDir, null, sourcesFile)
}
task.configure {
dependsOn(mergeSources)
}
task
}
val buildJpsStandalone = buildIvyRepositoryTask(jpsStandalone, customDepsOrg, customDepsRepoDir, null, sourcesFile)
val buildNodeJsPlugin = buildIvyRepositoryTask(nodeJSPlugin, customDepsOrg, customDepsRepoDir, ::skipToplevelDirectory, sourcesFile)
tasks.named("build") {
dependsOn(
makeIntellijCore,
makeIde,
buildJpsStandalone,
makeIntellijAnnotations
)
if (installIntellijUltimate) {
dependsOn(buildNodeJsPlugin)
}
}
// Task to delete legacy repo locations
tasks.create("cleanLegacy", Delete::class.java) {
delete("$projectDir/android-dx")
delete("$projectDir/intellij-sdk")
}
tasks.named<Delete>("clean") {
delete(customDepsRepoDir)
}
fun buildIvyRepositoryTask(
configuration: Configuration,
organization: String,
repoDirectory: File,
pathRemap: ((String) -> String)? = null,
sources: File? = null
) = tasks.register("buildIvyRepositoryFor${configuration.name.capitalize()}") {
fun ResolvedArtifact.moduleDirectory(): File =
File(repoDirectory, "$organization/${moduleVersion.id.name}/${moduleVersion.id.version}")
dependsOn(configuration)
inputs.files(configuration)
if (verifyDependencyOutput) {
outputs.dir(provider {
configuration.resolvedConfiguration.resolvedArtifacts.single().moduleDirectory()
})
} else {
outputs.upToDateWhen {
configuration.resolvedConfiguration.resolvedArtifacts.single()
.moduleDirectory()
.exists()
}
}
doFirst {
configuration.resolvedConfiguration.resolvedArtifacts.single().run {
val moduleDirectory = moduleDirectory()
val artifactsDirectory = File(moduleDirectory(), "artifacts")
logger.info("Unpacking ${file.name} into ${artifactsDirectory.absolutePath}")
copy {
val fileTree = when (extension) {
"tar.gz" -> tarTree(file)
"zip" -> zipTree(file)
else -> error("Unsupported artifact extension: $extension")
}
from(fileTree.matching {
exclude("**/plugins/Kotlin/**")
})
into(artifactsDirectory)
if (pathRemap != null) {
eachFile {
path = pathRemap(path)
}
}
includeEmptyDirs = false
}
writeIvyXml(
organization,
moduleVersion.id.name,
moduleVersion.id.version,
moduleVersion.id.name,
File(artifactsDirectory, "lib"),
File(artifactsDirectory, "lib"),
File(moduleDirectory, "ivy"),
*listOfNotNull(sources).toTypedArray()
)
val pluginsDirectory = File(artifactsDirectory, "plugins")
if (pluginsDirectory.exists()) {
file(File(artifactsDirectory, "plugins"))
.listFiles { file: File -> file.isDirectory }
.forEach {
writeIvyXml(
organization,
it.name,
moduleVersion.id.version,
it.name,
File(it, "lib"),
File(it, "lib"),
File(moduleDirectory, "ivy"),
*listOfNotNull(sources).toTypedArray()
)
}
}
}
}
}
fun writeIvyXml(
organization: String,
moduleName: String,
version: String,
fileName: String,
baseDir: File,
artifactDir: File,
targetDir: File,
vararg sourcesJar: File,
allowAnnotations: Boolean = false
) {
fun shouldIncludeIntellijJar(jar: File) =
jar.isFile
&& jar.extension == "jar"
&& !jar.name.startsWith("kotlin-")
&& (allowAnnotations || jar.name != "annotations.jar") // see comments for [intellijAnnotations] above
val ivyFile = targetDir.resolve("$fileName.ivy.xml")
ivyFile.parentFile.mkdirs()
with(XMLWriter(FileWriter(ivyFile))) {
document("UTF-8", "1.0") {
element("ivy-module") {
attribute("version", "2.0")
attribute("xmlns:m", "http://ant.apache.org/ivy/maven")
emptyElement("info") {
attributes(
"organisation" to organization,
"module" to moduleName,
"revision" to version,
"publication" to SimpleDateFormat("yyyyMMddHHmmss").format(Date())
)
}
element("configurations") {
listOf("default", "sources").forEach { configurationName ->
emptyElement("conf") {
attributes("name" to configurationName, "visibility" to "public")
}
}
}
element("publications") {
artifactDir.listFiles()?.filter(::shouldIncludeIntellijJar)?.forEach { jarFile ->
val relativeName = jarFile.toRelativeString(baseDir).removeSuffix(".jar")
emptyElement("artifact") {
attributes(
"name" to relativeName,
"type" to "jar",
"ext" to "jar",
"conf" to "default"
)
}
}
sourcesJar.forEach { jarFile ->
emptyElement("artifact") {
val sourcesArtifactName = jarFile.name
.substringBeforeLast("-")
.substringBeforeLast("-")
attributes(
"name" to sourcesArtifactName,
"type" to "jar",
"ext" to "jar",
"conf" to "sources",
"m:classifier" to "sources"
)
}
}
}
}
}
close()
}
}
fun skipToplevelDirectory(path: String) = path.substringAfter('/')
fun skipContentsDirectory(path: String) = path.substringAfter("Contents/")
class XMLWriter(private val outputStreamWriter: OutputStreamWriter) : Closeable {
private val xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(outputStreamWriter)
private var depth = 0
private val indent = " "
fun document(encoding: String, version: String, init: XMLWriter.() -> Unit) = apply {
xmlStreamWriter.writeStartDocument(encoding, version)
init()
xmlStreamWriter.writeEndDocument()
}
fun element(name: String, init: XMLWriter.() -> Unit) = apply {
writeIndent()
xmlStreamWriter.writeStartElement(name)
depth += 1
init()
depth -= 1
writeIndent()
xmlStreamWriter.writeEndElement()
}
fun emptyElement(name: String, init: XMLWriter.() -> Unit) = apply {
writeIndent()
xmlStreamWriter.writeEmptyElement(name)
init()
}
fun attribute(name: String, value: String): Unit = xmlStreamWriter.writeAttribute(name, value)
fun attributes(vararg attributes: Pair<String, String>) {
attributes.forEach { attribute(it.first, it.second) }
}
private fun writeIndent() {
xmlStreamWriter.writeCharacters("\n")
repeat(depth) {
xmlStreamWriter.writeCharacters(indent)
}
}
override fun close() {
xmlStreamWriter.flush()
xmlStreamWriter.close()
outputStreamWriter.close()
}
}

View File

@@ -0,0 +1,273 @@
@file:Suppress("PropertyName")
import org.gradle.api.publish.ivy.internal.artifact.FileBasedIvyArtifact
import org.gradle.api.publish.ivy.internal.publication.DefaultIvyConfiguration
import org.gradle.api.publish.ivy.internal.publication.DefaultIvyPublicationIdentity
import org.gradle.api.publish.ivy.internal.publisher.IvyDescriptorFileGenerator
import java.io.File
import org.gradle.internal.os.OperatingSystem
val cacheRedirectorEnabled = findProperty("cacheRedirectorEnabled")?.toString()?.toBoolean() == true
val intellijUltimateEnabled: Boolean by rootProject.extra
val intellijReleaseType: String by rootProject.extra
val intellijVersion = rootProject.extra["versions.intellijSdk"] as String
val androidStudioRelease = rootProject.findProperty("versions.androidStudioRelease") as String?
val androidStudioBuild = rootProject.findProperty("versions.androidStudioBuild") as String?
val intellijSeparateSdks: Boolean by rootProject.extra
val installIntellijCommunity = !intellijUltimateEnabled || intellijSeparateSdks
val installIntellijUltimate = intellijUltimateEnabled
val intellijVersionDelimiterIndex = intellijVersion.indexOfAny(charArrayOf('.', '-'))
if (intellijVersionDelimiterIndex == -1) {
error("Invalid IDEA version $intellijVersion")
}
val platformBaseVersion = intellijVersion.substring(0, intellijVersionDelimiterIndex)
logger.info("intellijUltimateEnabled: $intellijUltimateEnabled")
logger.info("intellijVersion: $intellijVersion")
logger.info("androidStudioRelease: $androidStudioRelease")
logger.info("androidStudioBuild: $androidStudioBuild")
logger.info("intellijSeparateSdks: $intellijSeparateSdks")
logger.info("installIntellijCommunity: $installIntellijCommunity")
logger.info("installIntellijUltimate: $installIntellijUltimate")
val studioOs by lazy {
when {
OperatingSystem.current().isWindows -> "windows"
OperatingSystem.current().isMacOsX -> "mac"
OperatingSystem.current().isLinux -> "linux"
else -> {
logger.error("Unknown operating system for android tools: ${OperatingSystem.current().name}")
""
}
}
}
repositories {
if (androidStudioRelease != null) {
ivy {
if (cacheRedirectorEnabled) {
artifactPattern("https://cache-redirector.jetbrains.com/dl.google.com/dl/android/studio/ide-zips/$androidStudioRelease/[artifact]-[revision]-$studioOs.zip")
}
artifactPattern("https://dl.google.com/dl/android/studio/ide-zips/$androidStudioRelease/[artifact]-[revision]-$studioOs.zip")
metadataSources {
artifact()
}
}
}
if (cacheRedirectorEnabled) {
maven("https://cache-redirector.jetbrains.com/www.jetbrains.com/intellij-repository/$intellijReleaseType")
maven("https://cache-redirector.jetbrains.com/plugins.jetbrains.com/maven")
}
maven("https://www.jetbrains.com/intellij-repository/$intellijReleaseType")
maven("https://plugins.jetbrains.com/maven")
}
val intellij by configurations.creating
val intellijUltimate by configurations.creating
val sources by configurations.creating
val `jps-standalone` by configurations.creating
val `jps-build-test` by configurations.creating
val `intellij-core` by configurations.creating
val `plugins-NodeJS` by configurations.creating
val customDepsRepoDir = File(buildDir, "repo")
val customDepsOrg: String by rootProject.extra
val customDepsRevision = intellijVersion
val customDepsRepoModulesDir = File(customDepsRepoDir, "$customDepsOrg/$customDepsRevision")
val repoDir = customDepsRepoModulesDir
dependencies {
if (androidStudioRelease != null) {
intellij("google:android-studio-ide:$androidStudioBuild")
} else {
if (installIntellijCommunity) {
intellij("com.jetbrains.intellij.idea:ideaIC:$intellijVersion")
}
if (installIntellijUltimate) {
intellijUltimate("com.jetbrains.intellij.idea:ideaIU:$intellijVersion")
}
}
sources("com.jetbrains.intellij.idea:ideaIC:$intellijVersion:sources@jar")
`jps-standalone`("com.jetbrains.intellij.idea:jps-standalone:$intellijVersion")
`jps-build-test`("com.jetbrains.intellij.idea:jps-build-test:$intellijVersion")
`intellij-core`("com.jetbrains.intellij.idea:intellij-core:$intellijVersion")
if (intellijUltimateEnabled) {
`plugins-NodeJS`("com.jetbrains.plugins:NodeJS:${rootProject.extra["versions.idea.NodeJS"]}@zip")
}
}
fun Task.configureExtractFromConfigurationTask(sourceConfig: Configuration,
pathRemap: (String) -> String = { it },
extractor: (Configuration) -> Any) {
dependsOn(sourceConfig)
inputs.files(sourceConfig)
val targetDir = File(repoDir, sourceConfig.name)
outputs.dirs(targetDir)
doFirst {
project.copy {
from(extractor(sourceConfig))
into(targetDir)
eachFile {
path = pathRemap(path)
}
}
}
}
fun removePathPrefix(path: String): String {
if (androidStudioRelease == null) return path
val slashes = if (studioOs == "mac") 2 else 1
var result = path
repeat(slashes) {
result = result.substringAfter('/')
}
return result
}
val unzipIntellijSdk by tasks.creating {
configureExtractFromConfigurationTask(intellij, pathRemap = { removePathPrefix(it) }) {
zipTree(it.singleFile).matching {
exclude("**/plugins/Kotlin/**")
}
}
}
val unzipIntellijUltimateSdk by tasks.creating {
configureExtractFromConfigurationTask(intellijUltimate) {
zipTree(it.singleFile).matching {
exclude("plugins/Kotlin/**")
}
}
}
val unzipIntellijCore by tasks.creating { configureExtractFromConfigurationTask(`intellij-core`) { zipTree(it.singleFile) } }
val unzipJpsStandalone by tasks.creating { configureExtractFromConfigurationTask(`jps-standalone`) { zipTree(it.singleFile) } }
val copyIntellijSdkSources by tasks.creating(Copy::class.java) {
from(sources)
into(File(repoDir, sources.name))
}
val copyJpsBuildTest by tasks.creating { configureExtractFromConfigurationTask(`jps-build-test`) { it.singleFile } }
val unzipNodeJSPlugin by tasks.creating { configureExtractFromConfigurationTask(`plugins-NodeJS`) { zipTree(it.singleFile) } }
fun writeIvyXml(moduleName: String, fileName: String, jarFiles: FileCollection, baseDir: File, sourcesJar: File?) {
with(IvyDescriptorFileGenerator(DefaultIvyPublicationIdentity(customDepsOrg, moduleName, intellijVersion))) {
addConfiguration(DefaultIvyConfiguration("default"))
addConfiguration(DefaultIvyConfiguration("sources"))
jarFiles.asFileTree.files.forEach { jarFile ->
if (jarFile.isFile && jarFile.extension == "jar") {
val relativeName = jarFile.toRelativeString(baseDir).removeSuffix(".jar")
addArtifact(
FileBasedIvyArtifact(jarFile, DefaultIvyPublicationIdentity(customDepsOrg, relativeName, intellijVersion)).also {
it.conf = "default"
}
)
}
}
if (sourcesJar != null) {
val sourcesArtifactName = sourcesJar.name.substringBefore("-")
addArtifact(
FileBasedIvyArtifact(sourcesJar, DefaultIvyPublicationIdentity(customDepsOrg, sourcesArtifactName, intellijVersion)).also {
it.conf = "sources"
it.classifier = "sources"
}
)
}
writeTo(File(customDepsRepoModulesDir, "$fileName.ivy.xml"))
}
}
val prepareIvyXmls by tasks.creating {
dependsOn(unzipIntellijCore, unzipJpsStandalone, copyIntellijSdkSources, copyJpsBuildTest)
val intellijSdkDir = File(repoDir, intellij.name)
val intellijUltimateSdkDir = File(repoDir, intellijUltimate.name)
if (installIntellijCommunity) {
dependsOn(unzipIntellijSdk)
inputs.dir(intellijSdkDir)
outputs.file(File(repoDir, "${intellij.name}.ivy.xml"))
}
if (installIntellijUltimate) {
dependsOn(unzipIntellijUltimateSdk)
inputs.dir(intellijUltimateSdkDir)
outputs.file(File(repoDir, "${intellijUltimate.name}.ivy.xml"))
}
val flatDeps = listOf(`intellij-core`, `jps-standalone`, `jps-build-test`)
flatDeps.forEach {
inputs.dir(File(repoDir, it.name))
outputs.file(File(repoDir, "${it.name}.ivy.xml"))
}
inputs.dir(File(repoDir, sources.name))
if (intellijUltimateEnabled) {
dependsOn(unzipNodeJSPlugin)
inputs.dir(File(repoDir, `plugins-NodeJS`.name))
outputs.file(File(repoDir, "${`plugins-NodeJS`.name}.ivy.xml"))
}
doFirst {
val sourcesFile = if (sources.isEmpty) null else File(repoDir, "${sources.name}/${sources.singleFile.name}")
if (installIntellijCommunity) {
val libDir = File(intellijSdkDir, "lib")
writeIvyXml(intellij.name,
intellij.name,
fileTree(libDir).filter {
it.parentFile == libDir && !it.name.startsWith("kotlin-")
},
libDir,
sourcesFile)
File(intellijSdkDir, "plugins").listFiles { it: File -> it.isDirectory }.forEach {
writeIvyXml(it.name, "intellij.plugin.${it.name}", files("$it/lib/"), File(it, "lib"), sourcesFile)
}
}
if (installIntellijUltimate) {
val libDir = File(intellijUltimateSdkDir, "lib")
writeIvyXml(intellij.name, // important! the module name should be "intellij"
intellijUltimate.name,
fileTree(libDir).filter {
it.parentFile == libDir && !it.name.startsWith("kotlin-")
},
libDir,
sourcesFile)
File(intellijUltimateSdkDir, "plugins").listFiles { it: File -> it.isDirectory }.forEach {
writeIvyXml(it.name, "intellijUltimate.plugin.${it.name}", files("$it/lib/"), File(it, "lib"), sourcesFile)
}
}
flatDeps.forEach {
writeIvyXml(it.name, it.name, files("$repoDir/${it.name}"), File(repoDir, it.name), sourcesFile)
}
if (intellijUltimateEnabled) {
val nodeJsBaseDir = "${`plugins-NodeJS`.name}/NodeJS/lib"
writeIvyXml("NodeJS", `plugins-NodeJS`.name, files("$repoDir/$nodeJsBaseDir"), File(repoDir, nodeJsBaseDir), sourcesFile)
}
}
}
val build by tasks.creating {
dependsOn(prepareIvyXmls)
}
val clean by tasks.creating(Delete::class) {
delete(customDepsRepoModulesDir)
delete(buildDir)
}

View File

@@ -1,64 +1,15 @@
pluginManagement {
repositories {
if (cacheRedirectorEnabled == 'true') {
logger.info("Using cache redirector for settings.gradle pluginManagement")
maven {
url "https://cache-redirector.jetbrains.com/plugins.gradle.org/m2"
}
} else {
gradlePluginPortal()
}
gradlePluginPortal()
}
}
include "prepare-deps"
def flags = new LocalBuildProperties(settings as Settings)
if (flags.includeCidrPlugins) {
logger.info("Including CIDR plugins in buildSrc/settings.gradle")
include ":prepare-deps:kotlin-native-platform-deps"
project(":prepare-deps:kotlin-native-platform-deps").projectDir = file("${flags.propertiesProvider.rootProjectDir}/kotlin-ultimate/buildSrc/prepare-deps/kotlin-native-platform-deps")
} else {
logger.info("NOT including CIDR plugins in buildSrc/settings.gradle")
}
class LocalBuildPropertiesProvider {
private Settings settings
private Properties localProperties = new Properties()
File rootProjectDir
LocalBuildPropertiesProvider(Settings settings) {
this.settings = settings
this.rootProjectDir = settings.rootProject.projectDir.parentFile
File propertiesFile = new File(rootProjectDir, 'local.properties')
if (propertiesFile.isFile()) {
propertiesFile.withInputStream { localProperties.load(it) }
}
}
String getString(String name) {
if (settings.hasProperty(name)) {
return settings[name]?.toString()
} else {
return localProperties[name]?.toString()
}
}
Boolean getBoolean(String name) {
return Boolean.parseBoolean(getString(name))
}
}
class LocalBuildProperties {
LocalBuildPropertiesProvider propertiesProvider
boolean includeCidrPlugins
LocalBuildProperties(Settings settings) {
propertiesProvider = new LocalBuildPropertiesProvider(settings)
includeCidrPlugins = propertiesProvider.getBoolean('cidrPluginsEnabled') && new File(propertiesProvider.rootProjectDir, 'kotlin-ultimate').exists()
}
}
include "prepare-deps:android-dx",
"prepare-deps:intellij-sdk"

View File

@@ -0,0 +1,15 @@
@file:Suppress("unused") // usages in build scripts are not tracked properly
import org.gradle.api.Project
import org.gradle.api.artifacts.dsl.RepositoryHandler
import org.gradle.api.artifacts.repositories.IvyArtifactRepository
import org.gradle.kotlin.dsl.extra
import java.io.File
fun RepositoryHandler.androidDxJarRepo(project: Project): IvyArtifactRepository = ivy {
val baseDir = File("${project.rootDir}/buildSrc/prepare-deps/android-dx/build/repo")
ivyPattern("${baseDir.canonicalPath}/[organisation]/[module]/[revision]/[module].ivy.xml")
artifactPattern("${baseDir.canonicalPath}/[organisation]/[module]/[revision]/[artifact](-[classifier]).jar")
}
fun Project.androidDxJar() = "kotlin.build.custom.deps:android-dx:${rootProject.extra["versions.androidBuildTools"]}"

View File

@@ -7,14 +7,10 @@ import org.gradle.kotlin.dsl.*
var Project.bootstrapKotlinVersion: String
get() = this.property("bootstrapKotlinVersion") as String
private set(value) { this.extra["bootstrapKotlinVersion"] = value }
var Project.bootstrapKotlinRepo: String?
get() = this.property("bootstrapKotlinRepo") as String?
private set(value) { this.extra["bootstrapKotlinRepo"] = value }
val Project.internalKotlinRepo: String?
get() = bootstrapKotlinRepo?.replace("artifacts/content/maven/", "artifacts/content/internal/repo")
fun Project.kotlinBootstrapFrom(defaultSource: BootstrapOption) {
val customVersion = project.findProperty("bootstrap.kotlin.version") as String?
val customRepo = project.findProperty("bootstrap.kotlin.repo") as String?

View File

@@ -1,6 +1,6 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
import org.gradle.api.Project
@@ -26,7 +26,7 @@ fun CompatibilityPredicate.or(other: CompatibilityPredicate): CompatibilityPredi
}
enum class Platform : CompatibilityPredicate {
P181, P182, P183, P191, P192;
P173, P181, P182, P183, P191;
val version: Int = name.drop(1).toInt()
@@ -41,16 +41,16 @@ enum class Platform : CompatibilityPredicate {
}
enum class Ide(val platform: Platform) : CompatibilityPredicate {
IJ173(Platform.P173),
IJ181(Platform.P181),
IJ182(Platform.P182),
IJ183(Platform.P183),
IJ191(Platform.P191),
IJ192(Platform.P192),
AS31(Platform.P173),
AS32(Platform.P181),
AS33(Platform.P182),
AS34(Platform.P183),
AS35(Platform.P183);
AS34(Platform.P183);
val kind = Kind.values().first { it.shortName == name.take(2) }
val version = name.dropWhile { !it.isDigit() }.toInt()

View File

@@ -1,6 +1,6 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
import org.gradle.api.tasks.JavaExec

View File

@@ -4,17 +4,13 @@ import org.gradle.jvm.tasks.Jar
import org.gradle.kotlin.dsl.task
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
fun Project.smartJavaExec(configure: JavaExec.() -> Unit) = task<JavaExec> {
fun Project.smartJavaExec(configure: JavaExec.() -> Unit) = task<JavaExec> javaExec@{
configure()
passClasspathInJar()
}
// Moves the classpath into a jar metadata, to shorten the command line length and to avoid hitting the limit on Windows
fun JavaExec.passClasspathInJar() {
val jarTask = project.task("${name}WriteClassPath", Jar::class) {
val classpath = classpath
val main = main
@@ -32,16 +28,21 @@ fun JavaExec.passClasspathInJar() {
)
}
}
archiveName = "$main.${this@passClasspathInJar.name}.classpath.container.$extension"
archiveName = "$main.${this@javaExec.name}.classpath.container.$extension"
destinationDir = temporaryDir
}
dependsOn(jarTask)
doFirst {
main = "-jar"
classpath = project.files()
args = listOf(jarTask.outputs.files.singleFile.path) + args.orEmpty()
val copyArgs = args.orEmpty().toList()
args(jarTask.outputs.files.singleFile)
args(copyArgs)
}
}

View File

@@ -1,25 +1,39 @@
@file:Suppress("unused") // usages in build scripts are not tracked properly
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.artifacts.ConfigurablePublishArtifact
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.ConfigurationContainer
import org.gradle.api.artifacts.component.ProjectComponentIdentifier
import org.gradle.api.*
import org.gradle.api.artifacts.*
import org.gradle.api.tasks.*
import org.gradle.kotlin.dsl.*
import org.gradle.api.file.DuplicatesStrategy
import org.gradle.api.file.SourceDirectorySet
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.AbstractCopyTask
import org.gradle.api.tasks.Copy
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.Upload
import org.gradle.api.tasks.javadoc.Javadoc
import org.gradle.jvm.tasks.Jar
import org.gradle.kotlin.dsl.*
import java.io.File
// can be used now only for the non-published projects, due to conflicts in the "archives" config
// TODO: fix the problem above
fun Project.classesDirsArtifact(): FileCollection {
task("uploadArchives") {
// hides rule-based task with the same name, which appears to be broken in this project
}
val classesDirsCfg = configurations.getOrCreate("classes-dirs")
val classesDirs = mainSourceSet.output.classesDirs
val classesTask = tasks["classes"]
afterEvaluate {
classesDirs.files.forEach {
addArtifact(classesDirsCfg, classesTask, it)
}
}
return classesDirs
}
private const val MAGIC_DO_NOT_CHANGE_TEST_JAR_TASK_NAME = "testJar"
@@ -37,26 +51,14 @@ fun Project.testsJar(body: Jar.() -> Unit = {}): Jar {
}
}
var Project.artifactsRemovedDiagnosticFlag: Boolean
get() = extra.has("artifactsRemovedDiagnosticFlag") && extra["artifactsRemovedDiagnosticFlag"] == true
set(value) {
extra["artifactsRemovedDiagnosticFlag"] = value
}
fun Project.removeArtifacts(configuration: Configuration, task: Task) {
configuration.artifacts.removeAll { artifact ->
artifact.file in task.outputs.files
}
artifactsRemovedDiagnosticFlag = true
}
fun Project.noDefaultJar() {
tasks.findByName("jar")?.let { defaultJarTask ->
defaultJarTask.enabled = false
defaultJarTask.actions = emptyList()
configurations.forEach { cfg ->
removeArtifacts(cfg, defaultJarTask)
cfg.artifacts.removeAll { artifact ->
artifact.file in defaultJarTask.outputs.files
}
}
}
}
@@ -69,18 +71,12 @@ fun Project.runtimeJarArtifactBy(task: Task, artifactRef: Any, body: Configurabl
}
}
fun <T : Jar> Project.runtimeJar(task: T, body: T.() -> Unit = {}): T {
fun<T: Jar> Project.runtimeJar(task: T, body: T.() -> Unit = {}): T {
extra["runtimeJarTask"] = task
tasks.findByName("jar")?.let { defaultJarTask ->
removeArtifacts(configurations.getOrCreate("archives"), defaultJarTask)
configurations.getOrCreate("archives").artifacts.removeAll { (it as? ArchivePublishArtifact)?.archiveTask?.let { it == defaultJarTask } ?: false }
}
return task.apply {
configurations.findByName("embedded")?.let { embedded ->
dependsOn(embedded)
from {
embedded.map(::zipTree)
}
}
setupPublicJar(project.the<BasePluginConvention>().archivesBaseName)
setDuplicatesStrategy(DuplicatesStrategy.EXCLUDE)
body()
@@ -90,45 +86,37 @@ fun <T : Jar> Project.runtimeJar(task: T, body: T.() -> Unit = {}): T {
fun Project.runtimeJar(body: Jar.() -> Unit = {}): Jar = runtimeJar(getOrCreateTask("jar", body), { })
fun Project.sourcesJar(body: Jar.() -> Unit = {}): TaskProvider<Jar> {
val task = tasks.register<Jar>("sourcesJar") {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
archiveClassifier.set("sources")
from(project.mainSourceSet.allSource)
project.configurations.findByName("embedded")?.let { embedded ->
from(provider {
embedded.resolvedConfiguration
.resolvedArtifacts
.map { it.id.componentIdentifier }
.filterIsInstance<ProjectComponentIdentifier>()
.map { project(it.projectPath).mainSourceSet.allSource }
})
fun Project.sourcesJar(sourceSet: String? = "main", body: Jar.() -> Unit = {}): Jar =
getOrCreateTask("sourcesJar") {
setDuplicatesStrategy(DuplicatesStrategy.EXCLUDE)
classifier = "sources"
try {
if (sourceSet != null) {
project.pluginManager.withPlugin("java-base") {
from(project.javaPluginConvention().sourceSets[sourceSet].allSource)
}
}
} catch (e: UnknownDomainObjectException) {
// skip default sources location
}
body()
project.addArtifact("archives", this, this)
}
body()
}
addArtifact("archives", task)
addArtifact("sources", task)
return task
}
fun Project.javadocJar(body: Jar.() -> Unit = {}): Jar = getOrCreateTask("javadocJar") {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
classifier = "javadoc"
tasks.findByName("javadoc")?.let { it as Javadoc }?.takeIf { it.enabled }?.let {
dependsOn(it)
from(it.destinationDir)
}
body()
project.addArtifact("archives", this, this)
}
fun Project.javadocJar(body: Jar.() -> Unit = {}): Jar =
getOrCreateTask("javadocJar") {
setDuplicatesStrategy(DuplicatesStrategy.EXCLUDE)
classifier = "javadoc"
tasks.findByName("javadoc")?.let{ it as Javadoc }?.takeIf { it.enabled }?.let {
dependsOn(it)
from(it.destinationDir)
}
body()
project.addArtifact("archives", this, this)
}
fun Project.standardPublicJars() {
fun Project.standardPublicJars(): Unit {
runtimeJar()
sourcesJar()
javadocJar()
@@ -137,10 +125,6 @@ fun Project.standardPublicJars() {
fun Project.publish(body: Upload.() -> Unit = {}): Upload {
apply<plugins.PublishedKotlinModule>()
if (artifactsRemovedDiagnosticFlag) {
error("`publish()` should be called before removing artifacts typically done in `noDefaultJar()` or `runtimeJar()` call")
}
afterEvaluate {
if (configurations.findByName("classes-dirs") != null)
throw GradleException("classesDirsArtifact() is incompatible with publish(), see sources comments for details")
@@ -151,6 +135,50 @@ fun Project.publish(body: Upload.() -> Unit = {}): Upload {
}
}
fun Project.ideaPlugin(subdir: String = "lib", body: AbstractCopyTask.() -> Unit): Copy {
val thisProject = this
val pluginTask = task<Copy>("ideaPlugin") {
body()
into(File(rootProject.extra["ideaPluginDir"].toString(), subdir).path)
rename("-${java.util.regex.Pattern.quote(thisProject.version.toString())}", "")
}
task("idea-plugin") {
dependsOn(pluginTask)
}
return pluginTask
}
fun Project.ideaPlugin(subdir: String = "lib"): Copy = ideaPlugin(subdir) {
runtimeJarTaskIfExists()?.let {
from(it)
}
}
fun Project.dist(targetDir: File? = null,
targetName: String? = null,
fromTask: Task? = null,
body: AbstractCopyTask.() -> Unit = {}): AbstractCopyTask {
val distJarCfg = configurations.getOrCreate("distJar")
val distLibDir: File by rootProject.extra
val distJarName = targetName ?: (the<BasePluginConvention>().archivesBaseName + ".jar")
val thisProject = this
return task<Copy>("dist") {
body()
(fromTask ?: runtimeJarTaskIfExists())?.let {
from(it)
if (targetName != null) {
rename(it.outputs.files.singleFile.name, targetName)
}
}
rename("-${java.util.regex.Pattern.quote(thisProject.version.toString())}", "")
into(targetDir ?: distLibDir)
project.addArtifact(distJarCfg, this, File(targetDir ?: distLibDir, distJarName))
}
}
private fun Project.runtimeJarTaskIfExists(): Task? =
if (extra.has("runtimeJarTask")) extra["runtimeJarTask"] as Task
else tasks.findByName("jar")
@@ -178,12 +206,7 @@ fun Project.addArtifact(configuration: Configuration, task: Task, artifactRef: A
}
fun Project.addArtifact(configurationName: String, task: Task, artifactRef: Any, body: ConfigurablePublishArtifact.() -> Unit = {}) =
addArtifact(configurations.getOrCreate(configurationName), task, artifactRef, body)
fun <T : Task> Project.addArtifact(configurationName: String, task: TaskProvider<T>, body: ConfigurablePublishArtifact.() -> Unit = {}) {
configurations.maybeCreate(configurationName)
artifacts.add(configurationName, task, body)
}
addArtifact(configurations.getOrCreate(configurationName), task, artifactRef, body)
fun Project.cleanArtifacts() {
configurations["archives"].artifacts.let { artifacts ->

View File

@@ -1,115 +0,0 @@
import org.gradle.api.Project
import org.gradle.api.initialization.Settings
import org.gradle.api.internal.DynamicObjectAware
import java.io.File
import java.util.*
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
interface PropertiesProvider {
val rootProjectDir: File
fun getProperty(key: String): Any?
}
class KotlinBuildProperties(
private val propertiesProvider: PropertiesProvider
) {
private val localProperties: Properties = Properties()
init {
val localPropertiesFile = propertiesProvider.rootProjectDir.resolve("local.properties")
if (localPropertiesFile.isFile) {
localPropertiesFile.reader().use(localProperties::load)
}
}
private operator fun get(key: String): Any? = localProperties.getProperty(key) ?: propertiesProvider.getProperty(key)
private fun getBoolean(key: String, default: Boolean = false): Boolean =
(this[key]?.toString()?.toBoolean() ?: default) == true
val isJpsBuildEnabled: Boolean = getBoolean("jpsBuild")
val isInIdeaSync: Boolean = run {
// "idea.sync.active" was introduced in 2019.1
System.getProperty("idea.sync.active")?.toBoolean() == true || let {
// before 2019.1 there is "idea.active" that was true only on sync,
// but since 2019.1 "idea.active" present in task execution too.
// So let's check Idea version
val majorIdeaVersion = System.getProperty("idea.version")
?.split(".")
?.getOrNull(0)
val isBeforeIdea2019 = majorIdeaVersion == null || majorIdeaVersion.toInt() < 2019
isBeforeIdea2019 && System.getProperty("idea.active")?.toBoolean() == true
}
}
val isInJpsBuildIdeaSync: Boolean
get() = isJpsBuildEnabled && isInIdeaSync
val includeJava9: Boolean
get() = !isInJpsBuildIdeaSync && getBoolean("kotlin.build.java9", true)
val useBootstrapStdlib: Boolean
get() = isInJpsBuildIdeaSync || getBoolean("kotlin.build.useBootstrapStdlib", false)
val kotlinUltimateExists: Boolean = propertiesProvider.rootProjectDir.resolve("kotlin-ultimate").exists()
val includeCidrPlugins: Boolean = kotlinUltimateExists && getBoolean("cidrPluginsEnabled")
val isTeamcityBuild: Boolean = getBoolean("teamcity") || System.getenv("TEAMCITY_VERSION") != null
val intellijUltimateEnabled: Boolean
get() {
val explicitlyEnabled = getBoolean("intellijUltimateEnabled")
if (!kotlinUltimateExists && explicitlyEnabled) {
error("intellijUltimateEnabled property is set, while kotlin-ultimate repository is not provided")
}
return kotlinUltimateExists && (explicitlyEnabled || isTeamcityBuild)
}
val postProcessing: Boolean get() = isTeamcityBuild || getBoolean("kotlin.build.postprocessing", true)
val relocation: Boolean get() = postProcessing
val proguard: Boolean get() = postProcessing && getBoolean("kotlin.build.proguard")
val jsIrDist: Boolean get() = getBoolean("kotlin.stdlib.js.ir.dist")
}
private const val extensionName = "kotlinBuildProperties"
class ProjectProperties(val project: Project) : PropertiesProvider {
override val rootProjectDir: File
get() = project.projectDir
override fun getProperty(key: String): Any? = project.findProperty(key)
}
val Project.kotlinBuildProperties: KotlinBuildProperties
get() = rootProject.extensions.findByName(extensionName) as KotlinBuildProperties?
?: KotlinBuildProperties(ProjectProperties(rootProject)).also {
rootProject.extensions.add(extensionName, it)
}
class SettingsProperties(val settings: Settings) : PropertiesProvider {
override val rootProjectDir: File
get() = settings.rootDir
override fun getProperty(key: String): Any? {
val obj = (settings as DynamicObjectAware).asDynamicObject
return if (obj.hasProperty(key)) obj.getProperty(key) else null
}
}
fun getKotlinBuildPropertiesForSettings(settings: Any) = (settings as Settings).kotlinBuildProperties
val Settings.kotlinBuildProperties: KotlinBuildProperties
get() = extensions.findByName(extensionName) as KotlinBuildProperties?
?: KotlinBuildProperties(SettingsProperties(this)).also {
extensions.add(extensionName, it)
}

View File

@@ -1,44 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
import org.gradle.api.Action
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.NamedDomainObjectProvider
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.ExternalModuleDependency
import org.gradle.api.artifacts.ModuleDependency
import org.gradle.api.artifacts.dsl.DependencyHandler
import org.gradle.kotlin.dsl.accessors.runtime.addDependencyTo
import org.gradle.kotlin.dsl.accessors.runtime.addExternalModuleDependencyTo
import org.gradle.kotlin.dsl.add
val NamedDomainObjectContainer<Configuration>.embedded: NamedDomainObjectProvider<Configuration> get() = named("embedded")
fun DependencyHandler.embedded(dependencyNotation: Any): Dependency? =
add("embedded", dependencyNotation)
fun DependencyHandler.embedded(
dependencyNotation: String,
dependencyConfiguration: Action<ExternalModuleDependency>
): ExternalModuleDependency =
addDependencyTo(this, "embedded", dependencyNotation, dependencyConfiguration)
fun DependencyHandler.embedded(
group: String,
name: String,
version: String? = null,
configuration: String? = null,
classifier: String? = null,
ext: String? = null,
dependencyConfiguration: Action<ExternalModuleDependency>? = null
): ExternalModuleDependency = addExternalModuleDependencyTo(
this, "embedded", group, name, version, configuration, classifier, ext, dependencyConfiguration
)
fun <T : ModuleDependency> DependencyHandler.embedded(
dependency: T,
dependencyConfiguration: T.() -> Unit
): T = add("embedded", dependency, dependencyConfiguration)

View File

@@ -1,6 +1,6 @@
/*
* Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package tasks

View File

@@ -1,21 +1,16 @@
@file:Suppress("unused")
@file:Suppress("unused") // usages in build scripts are not tracked properly
// 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.artifacts.ProjectDependency
import org.gradle.api.artifacts.dsl.DependencyHandler
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.tasks.AbstractCopyTask
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.kotlin.dsl.extra
import org.gradle.kotlin.dsl.project
import java.io.File
val Project.isSnapshotIntellij get() = rootProject.extra["versions.intellijSdk"].toString().endsWith("SNAPSHOT")
val Project.intellijRepo get() = "https://www.jetbrains.com/intellij-repository/" + if (isSnapshotIntellij) "snapshots" else "releases"
fun Project.commonDep(coord: String): String {
val parts = coord.split(':')
@@ -33,18 +28,13 @@ fun Project.commonDep(group: String, artifact: String, vararg suffixesAndClassif
}
fun Project.commonVer(group: String, artifact: String) =
when {
rootProject.extra.has("versions.$artifact") -> rootProject.extra["versions.$artifact"]
rootProject.extra.has("versions.$group") -> rootProject.extra["versions.$group"]
else -> throw GradleException("Neither versions.$artifact nor versions.$group is defined in the root project's extra")
}
when {
rootProject.extra.has("versions.$artifact") -> rootProject.extra["versions.$artifact"]
rootProject.extra.has("versions.$group") -> rootProject.extra["versions.$group"]
else -> throw GradleException("Neither versions.$artifact nor versions.$group is defined in the root project's extra")
}
fun Project.preloadedDeps(
vararg artifactBaseNames: String,
baseDir: File = File(rootDir, "dependencies"),
subdir: String? = null,
optional: Boolean = false
): ConfigurableFileCollection {
fun Project.preloadedDeps(vararg artifactBaseNames: String, baseDir: File = File(rootDir, "dependencies"), subdir: String? = null, optional: Boolean = false): ConfigurableFileCollection {
val dir = if (subdir != null) File(baseDir, subdir) else baseDir
if (!dir.exists() || !dir.isDirectory) {
if (optional) return files()
@@ -52,17 +42,9 @@ fun Project.preloadedDeps(
}
val matchingFiles = dir.listFiles { file -> artifactBaseNames.any { file.matchMaybeVersionedArtifact(it) } }
if (matchingFiles == null || matchingFiles.size < artifactBaseNames.size) {
throw GradleException(
"Not all matching artifacts '${artifactBaseNames.joinToString()}' found in the '$dir' " +
"(missing: ${artifactBaseNames.filterNot { request ->
matchingFiles.any {
it.matchMaybeVersionedArtifact(
request
)
}
}.joinToString()};" +
" found: ${matchingFiles?.joinToString { it.name }})"
)
throw GradleException("Not all matching artifacts '${artifactBaseNames.joinToString()}' found in the '$dir' " +
"(missing: ${artifactBaseNames.filterNot { request -> matchingFiles.any { it.matchMaybeVersionedArtifact(request) } }.joinToString()};" +
" found: ${matchingFiles?.joinToString { it.name }})")
}
return files(*matchingFiles.map { it.canonicalPath }.toTypedArray())
}
@@ -73,34 +55,23 @@ fun Project.ideaUltimatePreloadedDeps(vararg artifactBaseNames: String, subdir:
else files()
}
fun Project.kotlinDep(artifactBaseName: String, version: String, classifier: String? = null): String =
listOfNotNull("org.jetbrains.kotlin:kotlin-$artifactBaseName:$version", classifier).joinToString(":")
fun Project.kotlinStdlib(suffix: String? = null, classifier: String? = null): Any {
return if (kotlinBuildProperties.useBootstrapStdlib)
kotlinDep(listOfNotNull("stdlib", suffix).joinToString("-"), bootstrapKotlinVersion, classifier)
else
dependencies.project(listOfNotNull(":kotlin-stdlib", suffix).joinToString("-"), classifier)
}
fun Project.kotlinBuiltins(): Any =
if (kotlinBuildProperties.useBootstrapStdlib) "org.jetbrains.kotlin:builtins:$bootstrapKotlinVersion"
else dependencies.project(":core:builtins")
fun Project.kotlinDep(artifactBaseName: String, version: String): String = "org.jetbrains.kotlin:kotlin-$artifactBaseName:$version"
@Deprecated("Depend on the default configuration instead", ReplaceWith("project(name)"))
fun DependencyHandler.projectDist(name: String): ProjectDependency = project(name)
fun DependencyHandler.projectTests(name: String): ProjectDependency = project(name, configuration = "tests-jar")
fun DependencyHandler.projectRuntimeJar(name: String): ProjectDependency = project(name, configuration = "runtimeJar")
fun DependencyHandler.projectArchives(name: String): ProjectDependency = project(name, configuration = "archives")
fun DependencyHandler.projectClasses(name: String): ProjectDependency = project(name, configuration = "classes-dirs")
val Project.protobufVersion: String get() = findProperty("versions.protobuf") as String
val protobufLiteProject = ":custom-dependencies:protobuf-lite"
val protobufRelocatedProject = ":custom-dependencies:protobuf-relocated"
fun DependencyHandler.protobufLite(): ProjectDependency =
project(protobufLiteProject, configuration = "default").apply { isTransitive = false }
val protobufLiteTask = "$protobufLiteProject:prepare"
val Project.protobufRepo: String
get() =
"https://teamcity.jetbrains.com/guestAuth/app/rest/builds/buildType:(id:Kotlin_Protobuf),status:SUCCESS,pinned:true,tag:$protobufVersion/artifacts/content/internal/repo/"
fun Project.protobufLite(): String = "org.jetbrains.kotlin:protobuf-lite:$protobufVersion"
fun Project.protobufFull(): String = "org.jetbrains.kotlin:protobuf-relocated:$protobufVersion"
val Project.kotlinNativeVersion: String get() = property("versions.kotlin-native") as String
fun DependencyHandler.protobufFull(): ProjectDependency =
project(protobufRelocatedProject, configuration = "default").apply { isTransitive = false }
fun File.matchMaybeVersionedArtifact(baseName: String) = name.matches(baseName.toMaybeVersionedJarRegex())
@@ -122,6 +93,8 @@ private fun String.toMaybeVersionedJarRegex(): Regex {
return Regex(if (hasJarExtension) escaped else "$escaped(-\\d.*)?\\.jar") // TODO: consider more precise version part of the regex
}
fun Project.firstFromJavaHomeThatExists(vararg paths: String, jdkHome: File = File(this.property("JDK_18") as String)): File? =
paths.map { File(jdkHome, it) }.firstOrNull { it.exists() }.also {
if (it == null)
@@ -132,8 +105,48 @@ fun Project.toolsJar(jdkHome: File = File(this.property("JDK_18") as String)): F
firstFromJavaHomeThatExists("lib/tools.jar", jdkHome = jdkHome)
val compilerManifestClassPath
get() = "annotations-13.0.jar kotlin-stdlib.jar kotlin-reflect.jar kotlin-script-runtime.jar trove4j.jar"
get() = "kotlin-stdlib.jar kotlin-reflect.jar kotlin-script-runtime.jar trove4j.jar"
object EmbeddedComponents {
val CONFIGURATION_NAME = "embedded"
val CONFIGURATION_NAME = "embeddedComponents"
}
fun AbstractCopyTask.fromEmbeddedComponents() {
val embeddedComponents = project.configurations.getByName(EmbeddedComponents.CONFIGURATION_NAME)
if (this is ShadowJar) {
from(embeddedComponents)
} else {
dependsOn(embeddedComponents)
from {
embeddedComponents.map { file ->
if (file.isDirectory)
project.files(file)
else
project.zipTree(file)
}
}
}
}
// TODO: it seems incomplete, find and add missing dependencies
val testDistProjects = listOf(
"", // for root project
":kotlin-stdlib:jvm-minimal-for-test",
":kotlin-compiler",
":kotlin-script-runtime",
":kotlin-stdlib",
":kotlin-stdlib-jre7",
":kotlin-stdlib-jre8",
":kotlin-stdlib-jdk7",
":kotlin-stdlib-jdk8",
":kotlin-stdlib-js",
":kotlin-reflect",
":kotlin-test:kotlin-test-jvm",
":kotlin-test:kotlin-test-junit",
":kotlin-test:kotlin-test-js",
":kotlin-preloader",
":plugins:android-extensions-compiler",
":kotlin-ant",
":kotlin-annotations-jvm",
":kotlin-annotations-android"
)

View File

@@ -1,40 +0,0 @@
@file:Suppress("PackageDirectoryMismatch")
package org.jetbrains.kotlin.ideaExt
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.plugins.ExtensionAware
import org.gradle.kotlin.dsl.configure
import org.gradle.plugins.ide.idea.model.IdeaProject
import org.jetbrains.gradle.ext.*
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
fun org.gradle.api.Project.idea(configure: org.gradle.plugins.ide.idea.model.IdeaModel.() -> Unit): Unit =
(this as org.gradle.api.plugins.ExtensionAware).extensions.configure("idea", configure)
fun IdeaProject.settings(block: ProjectSettings.() -> Unit) =
(this@settings as ExtensionAware).extensions.configure(block)
fun ProjectSettings.compiler(block: IdeaCompilerConfiguration.() -> Unit) =
(this@compiler as ExtensionAware).extensions.configure(block)
fun ProjectSettings.delegateActions(block: ActionDelegationConfig.() -> Unit) =
(this@delegateActions as ExtensionAware).extensions.configure(block)
fun ProjectSettings.runConfigurations(block: DefaultRunConfigurationContainer.() -> Unit) =
(this@runConfigurations as ExtensionAware).extensions.configure("runConfigurations", block)
inline fun <reified T: RunConfiguration> DefaultRunConfigurationContainer.defaults(noinline block: T.() -> Unit) =
defaults(T::class.java, block)
fun DefaultRunConfigurationContainer.junit(name: String, block: JUnit.() -> Unit) =
create(name, JUnit::class.java, block)
fun DefaultRunConfigurationContainer.application(name: String, block: Application.() -> Unit) =
create(name, Application::class.java, block)
fun ProjectSettings.ideArtifacts(block: NamedDomainObjectContainer<org.jetbrains.gradle.ext.TopLevelArtifact>.() -> Unit) =
(this@ideArtifacts as ExtensionAware).extensions.configure("ideArtifacts", block)

View File

@@ -1,4 +1,4 @@
@file:Suppress("unused")
@file:Suppress("unused") // usages in build scripts are not tracked properly
/*
* Copyright 2010-2017 JetBrains s.r.o.
@@ -23,12 +23,13 @@ import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.FileCollection
import org.gradle.api.internal.ConventionTask
import org.gradle.api.plugins.ExtensionAware
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.*
import org.gradle.api.tasks.compile.AbstractCompile
import org.gradle.kotlin.dsl.*
import java.io.File
fun Project.configureFormInstrumentation() {
fun Project.configureInstrumentation() {
plugins.matching { it::class.java.canonicalName.startsWith("org.jetbrains.kotlin.gradle.plugin") }.all {
// When we change the output classes directory, Gradle will automatically configure
// the test compile tasks to use the instrumented classes. Normally this is fine,
@@ -45,8 +46,8 @@ fun Project.configureFormInstrumentation() {
val testCompile = tasks.findByName("compileTestKotlin") as AbstractCompile?
testCompile?.doFirst {
testCompile.classpath = (testCompile.classpath
- mainSourceSet.output.classesDirs
+ files((mainSourceSet as ExtensionAware).extra.get("classesDirsCopy")))
- mainSourceSet.output.classesDirs
+ files((mainSourceSet as ExtensionAware).extra.get("classesDirsCopy")))
}
}
@@ -67,8 +68,7 @@ fun Project.configureFormInstrumentation() {
logger.info("Saving old sources dir for project ${project.name}")
val instrumentedClassesDir = File(project.buildDir, "classes/${sourceSetParam.name}-instrumented")
(sourceSetParam.output.classesDirs as ConfigurableFileCollection).setFrom(instrumentedClassesDir)
val instrumentTask =
project.tasks.create(sourceSetParam.getTaskName("instrument", "classes"), IntelliJInstrumentCodeTask::class.java)
val instrumentTask = project.tasks.create(sourceSetParam.getTaskName("instrument", "classes"), IntelliJInstrumentCodeTask::class.java)
instrumentTask.apply {
dependsOn(sourceSetParam.classesTaskName).onlyIf { !classesDirsCopy.isEmpty }
sourceSet = sourceSetParam
@@ -100,9 +100,6 @@ open class IntelliJInstrumentCodeTask : ConventionTask() {
@Input
var originalClassesDirs: FileCollection? = null
@get:Input
var instrumentNotNull: Boolean = false
@get:InputFiles
val sourceDirs: FileCollection
get() = project.files(sourceSet!!.allSource.srcDirs.filter { !sourceSet!!.resources.contains(it) && it.exists() })
@@ -112,30 +109,21 @@ open class IntelliJInstrumentCodeTask : ConventionTask() {
@TaskAction
fun instrumentClasses() {
logger.info(
"input files are: ${originalClassesDirs?.joinToString(
"; ",
transform = { "'${it.name}'${if (it.exists()) "" else " (does not exists)"}" })}"
)
logger.info("input files are: ${originalClassesDirs?.joinToString("; ", transform = { "'${it.name}'${if (it.exists()) "" else " (does not exists)" }"})}")
output.deleteRecursively()
copyOriginalClasses()
val classpath = instrumentationClasspath!!
ant.withGroovyBuilder {
"taskdef"(
"name" to "instrumentIdeaExtensions",
"classpath" to classpath.asPath,
"loaderref" to LOADER_REF,
"classname" to "com.intellij.ant.InstrumentIdeaExtensions"
)
"taskdef"("name" to "instrumentIdeaExtensions",
"classpath" to classpath.asPath,
"loaderref" to LOADER_REF,
"classname" to "com.intellij.ant.InstrumentIdeaExtensions")
}
logger.info("Compiling forms and instrumenting code with nullability preconditions")
if (instrumentNotNull) {
prepareNotNullInstrumenting(classpath.asPath)
}
val instrumentNotNull = prepareNotNullInstrumenting(classpath.asPath)
instrumentCode(sourceDirs, instrumentNotNull)
}
@@ -146,15 +134,14 @@ open class IntelliJInstrumentCodeTask : ConventionTask() {
}
}
private fun prepareNotNullInstrumenting(classpath: String) {
private fun prepareNotNullInstrumenting(classpath: String): Boolean {
ant.withGroovyBuilder {
"typedef"(
"name" to "skip",
"classpath" to classpath,
"loaderref" to LOADER_REF,
"classname" to FILTER_ANNOTATION_REGEXP_CLASS
)
"typedef"("name" to "skip",
"classpath" to classpath,
"loaderref" to LOADER_REF,
"classname" to FILTER_ANNOTATION_REGEXP_CLASS)
}
return true
}
private fun instrumentCode(srcDirs: FileCollection, instrumentNotNull: Boolean) {
@@ -162,22 +149,20 @@ open class IntelliJInstrumentCodeTask : ConventionTask() {
// Instrumentation needs to have access to sources of forms for inclusion
val depSourceDirectorySets = project.configurations["compile"].dependencies.withType(ProjectDependency::class.java)
.map { p -> p.dependencyProject.mainSourceSet.allSource.sourceDirectories }
.map { p -> p.dependencyProject.mainSourceSet.allSource.sourceDirectories }
val instrumentationClasspath =
depSourceDirectorySets.fold(sourceSet!!.compileClasspath) { acc, v -> acc + v }.asPath.also {
logger.info("Using following dependency source dirs: $it")
}
depSourceDirectorySets.fold(sourceSet!!.compileClasspath) { acc, v -> acc + v }.asPath.also {
logger.info("Using following dependency source dirs: $it")
}
logger.info("Running instrumentIdeaExtensions with srcdir=${srcDirs.asPath}}, destdir=$output and classpath=$instrumentationClasspath")
ant.withGroovyBuilder {
"instrumentIdeaExtensions"(
"srcdir" to srcDirs.asPath,
"destdir" to output,
"classpath" to instrumentationClasspath,
"includeantruntime" to false,
"instrumentNotNull" to instrumentNotNull
) {
"instrumentIdeaExtensions"("srcdir" to srcDirs.asPath,
"destdir" to output,
"classpath" to instrumentationClasspath,
"includeantruntime" to false,
"instrumentNotNull" to instrumentNotNull) {
if (instrumentNotNull) {
ant.withGroovyBuilder {
"skip"("pattern" to "kotlin/Metadata")

View File

@@ -0,0 +1,180 @@
@file:Suppress("unused") // usages in build scripts are not tracked properly
/*
* 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.
*/
import org.gradle.api.Project
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.ProjectDependency
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.FileCollection
import org.gradle.api.internal.ConventionTask
import org.gradle.api.plugins.ExtensionAware
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.*
import org.gradle.api.tasks.compile.AbstractCompile
import org.gradle.kotlin.dsl.*
import java.io.File
fun Project.configureInstrumentation() {
plugins.matching { it::class.java.canonicalName.startsWith("org.jetbrains.kotlin.gradle.plugin") }.all {
// When we change the output classes directory, Gradle will automatically configure
// the test compile tasks to use the instrumented classes. Normally this is fine,
// however, it causes problems for Kotlin projects:
// The "internal" modifier can be used to restrict access to the same module.
// To make it possible to use internal methods from the main source set in test classes,
// the Kotlin Gradle plugin adds the original output directory of the Java task
// as "friendly directory" which makes it possible to access internal members
// of the main module. Also this directory should be available on classpath during compilation
// This fails when we change the classes dir. The easiest fix is to prepend the
// classes from the "friendly directory" to the compile classpath.
val testCompile = tasks.findByName("compileTestKotlin") as AbstractCompile?
testCompile?.doFirst {
testCompile.classpath = (testCompile.classpath
- mainSourceSet.output.classesDirs
+ files((mainSourceSet as ExtensionAware).extra.get("classesDirsCopy")))
}
}
val instrumentationClasspathCfg = configurations.create("instrumentationClasspath")
dependencies {
instrumentationClasspathCfg(intellijDep()) { includeJars("javac2", "jdom", "asm-all", "jgoodies-forms", rootProject = rootProject) }
}
afterEvaluate {
sourceSets.all { sourceSetParam ->
// This copy will ignore filters, but they are unlikely to be used.
val classesDirs = (sourceSetParam.output.classesDirs as ConfigurableFileCollection).from as Collection<Any>
val classesDirsCopy = project.files(classesDirs.toTypedArray()).filter { it.exists() }
(sourceSetParam as ExtensionAware).extra.set("classesDirsCopy", classesDirsCopy)
logger.info("Saving old sources dir for project ${project.name}")
val instrumentedClassesDir = File(project.buildDir, "classes/${sourceSetParam.name}-instrumented")
(sourceSetParam.output.classesDirs as ConfigurableFileCollection).setFrom(instrumentedClassesDir)
val instrumentTask = project.tasks.create(sourceSetParam.getTaskName("instrument", "classes"), IntelliJInstrumentCodeTask::class.java)
instrumentTask.apply {
dependsOn(sourceSetParam.classesTaskName).onlyIf { !classesDirsCopy.isEmpty }
sourceSet = sourceSetParam
instrumentationClasspath = instrumentationClasspathCfg
originalClassesDirs = classesDirsCopy
output = instrumentedClassesDir
}
instrumentTask.outputs.dir(instrumentedClassesDir)
// Ensure that our task is invoked when the source set is built
sourceSetParam.compiledBy(instrumentTask)
@Suppress("UNUSED_EXPRESSION")
true
}
}
}
@CacheableTask
open class IntelliJInstrumentCodeTask : ConventionTask() {
companion object {
private const val FILTER_ANNOTATION_REGEXP_CLASS = "com.intellij.ant.ClassFilterAnnotationRegexp"
private const val LOADER_REF = "java2.loader"
}
var sourceSet: SourceSet? = null
var instrumentationClasspath: Configuration? = null
@Input
var originalClassesDirs: FileCollection? = null
@get:InputFiles
val sourceDirs: FileCollection
get() = project.files(sourceSet!!.allSource.srcDirs.filter { !sourceSet!!.resources.contains(it) && it.exists() })
@get:OutputDirectory
lateinit var output: File
@TaskAction
fun instrumentClasses() {
logger.info("input files are: ${originalClassesDirs?.joinToString("; ", transform = { "'${it.name}'${if (it.exists()) "" else " (does not exists)" }"})}")
output.deleteRecursively()
copyOriginalClasses()
val classpath = instrumentationClasspath!!
ant.withGroovyBuilder {
"taskdef"("name" to "instrumentIdeaExtensions",
"classpath" to classpath.asPath,
"loaderref" to LOADER_REF,
"classname" to "com.intellij.ant.InstrumentIdeaExtensions")
}
logger.info("Compiling forms and instrumenting code with nullability preconditions")
val instrumentNotNull = prepareNotNullInstrumenting(classpath.asPath)
instrumentCode(sourceDirs, instrumentNotNull)
}
private fun copyOriginalClasses() {
project.copy {
from(originalClassesDirs)
into(output)
}
}
private fun prepareNotNullInstrumenting(classpath: String): Boolean {
ant.withGroovyBuilder {
"typedef"("name" to "skip",
"classpath" to classpath,
"loaderref" to LOADER_REF,
"classname" to FILTER_ANNOTATION_REGEXP_CLASS)
}
return true
}
private fun instrumentCode(srcDirs: FileCollection, instrumentNotNull: Boolean) {
val headlessOldValue = System.setProperty("java.awt.headless", "true")
// Instrumentation needs to have access to sources of forms for inclusion
val depSourceDirectorySets = project.configurations["compile"].dependencies.withType(ProjectDependency::class.java)
.map { p -> p.dependencyProject.mainSourceSet.allSource.sourceDirectories }
val instrumentationClasspath =
depSourceDirectorySets.fold(sourceSet!!.compileClasspath) { acc, v -> acc + v }.asPath.also {
logger.info("Using following dependency source dirs: $it")
}
logger.info("Running instrumentIdeaExtensions with srcdir=${srcDirs.asPath}}, destdir=$output and classpath=$instrumentationClasspath")
ant.withGroovyBuilder {
"instrumentIdeaExtensions"("srcdir" to srcDirs.asPath,
"destdir" to output,
"classpath" to instrumentationClasspath,
"includeantruntime" to false,
"instrumentNotNull" to instrumentNotNull) {
if (instrumentNotNull) {
ant.withGroovyBuilder {
"skip"("pattern" to "kotlin/Metadata")
}
}
}
}
if (headlessOldValue != null) {
System.setProperty("java.awt.headless", headlessOldValue)
} else {
System.clearProperty("java.awt.headless")
}
}
}

View File

@@ -0,0 +1,170 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused") // usages in build scripts are not tracked properly
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.artifacts.ModuleDependency
import org.gradle.api.artifacts.dsl.RepositoryHandler
import org.gradle.api.artifacts.repositories.IvyArtifactRepository
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.JavaExec
import org.gradle.kotlin.dsl.*
import java.io.File
private fun Project.intellijRepoDir() = File("${project.rootDir.absoluteFile}/buildSrc/prepare-deps/intellij-sdk/build/repo")
fun RepositoryHandler.intellijSdkRepo(project: Project): IvyArtifactRepository = ivy {
val baseDir = project.intellijRepoDir()
val intellijEnforceCommunitySdk = project.getBooleanProperty("intellijEnforceCommunitySdk") == true
setUrl(baseDir)
if (!intellijEnforceCommunitySdk) {
ivyPattern("${baseDir.canonicalPath}/[organisation]/[revision]/[module]Ultimate.ivy.xml")
ivyPattern("${baseDir.canonicalPath}/[organisation]/[revision]/intellijUltimate.plugin.[module].ivy.xml")
artifactPattern("${baseDir.canonicalPath}/[organisation]/[revision]/[module]Ultimate/lib/[artifact](-[classifier]).jar")
artifactPattern("${baseDir.canonicalPath}/[organisation]/[revision]/intellijUltimate/plugins/[module]/lib/[artifact](-[classifier]).jar")
}
ivyPattern("${baseDir.canonicalPath}/[organisation]/[revision]/[module].ivy.xml")
ivyPattern("${baseDir.canonicalPath}/[organisation]/[revision]/intellij.plugin.[module].ivy.xml")
ivyPattern("${baseDir.canonicalPath}/[organisation]/[revision]/plugins-[module].ivy.xml")
artifactPattern("${baseDir.canonicalPath}/[organisation]/[revision]/[module]/lib/[artifact](-[classifier]).jar")
artifactPattern("${baseDir.canonicalPath}/[organisation]/[revision]/intellij/plugins/[module]/lib/[artifact](-[classifier]).jar")
artifactPattern("${baseDir.canonicalPath}/[organisation]/[revision]/plugins-[module]/[module]/lib/[artifact](-[classifier]).jar")
artifactPattern("${baseDir.canonicalPath}/[organisation]/[revision]/[module]/[artifact].jar")
artifactPattern("${baseDir.canonicalPath}/[organisation]/[revision]/[module]/[artifact](-[revision])(-[classifier]).jar")
artifactPattern("${baseDir.canonicalPath}/[organisation]/[revision]/sources/[artifact]-[revision]-[classifier].[ext]")
metadataSources {
ivyDescriptor()
}
}
fun Project.intellijDep(module: String = "intellij") = "kotlin.build.custom.deps:$module:${rootProject.extra["versions.intellijSdk"]}"
fun Project.intellijCoreDep() = intellijDep("intellij-core")
fun Project.intellijPluginDep(plugin: String) = intellijDep(plugin)
fun Project.intellijUltimateDep() = intellijDep("intellij")
fun Project.intellijUltimatePluginDep(plugin: String) = intellijDep(plugin)
fun ModuleDependency.includeJars(vararg names: String, rootProject: Project? = null) {
names.forEach {
var baseName = it.removeSuffix(".jar")
if (rootProject != null && rootProject.extra.has("ignore.jar.$baseName")) {
return@forEach
}
if (rootProject != null && rootProject.extra.has("versions.jar.$baseName")) {
baseName += "-${rootProject.extra["versions.jar.$baseName"]}"
}
artifact {
name = baseName
type = "jar"
extension = "jar"
}
}
}
// Workaround. Top-level Kotlin function in a default package can't be called from a non-default package
object IntellijRootUtils {
fun getRepositoryRootDir(project: Project): File = with (project.rootProject) {
return File(intellijRepoDir(), "kotlin.build.custom.deps/${extra["versions.intellijSdk"]}")
}
fun getIntellijRootDir(project: Project): File = with (project.rootProject) {
return File(getRepositoryRootDir(this), "intellij${if (isIntellijCommunityAvailable()) "" else "Ultimate"}")
}
}
fun ModuleDependency.includeIntellijCoreJarDependencies(project: Project) =
includeJars(*(project.rootProject.extra["IntellijCoreDependencies"] as List<String>).toTypedArray(), rootProject = project.rootProject)
fun ModuleDependency.includeIntellijCoreJarDependencies(project: Project, jarsFilterPredicate: (String) -> Boolean) =
includeJars(*(project.rootProject.extra["IntellijCoreDependencies"] as List<String>).filter { jarsFilterPredicate(it) }.toTypedArray(), rootProject = project.rootProject)
fun Project.isIntellijCommunityAvailable() = !(rootProject.extra["intellijUltimateEnabled"] as Boolean) || rootProject.extra["intellijSeparateSdks"] as Boolean
fun Project.isIntellijUltimateSdkAvailable() = (rootProject.extra["intellijUltimateEnabled"] as Boolean)
fun Project.intellijRootDir() = IntellijRootUtils.getIntellijRootDir(project)
fun Project.intellijUltimateRootDir() =
if (isIntellijUltimateSdkAvailable())
File(intellijRepoDir(), "kotlin.build.custom.deps/${rootProject.extra["versions.intellijSdk"]}/intellijUltimate")
else
throw GradleException("intellij ultimate SDK is not available")
fun DependencyHandlerScope.excludeInAndroidStudio(rootProject: Project, block: DependencyHandlerScope.() -> Unit) {
if (!rootProject.extra.has("versions.androidStudioRelease")) {
block()
}
}
fun Project.runIdeTask(name: String, ideaPluginDir: File, ideaSandboxDir: File, body: JavaExec.() -> Unit): JavaExec {
return task<JavaExec>(name) {
val ideaSandboxConfigDir = File(ideaSandboxDir, "config")
classpath = mainSourceSet.runtimeClasspath
main = "com.intellij.idea.Main"
workingDir = File(intellijRootDir(), "bin")
jvmArgs(
"-Xmx1250m",
"-XX:ReservedCodeCacheSize=240m",
"-XX:+HeapDumpOnOutOfMemoryError",
"-ea",
"-Didea.is.internal=true",
"-Didea.debug.mode=true",
"-Didea.system.path=$ideaSandboxDir",
"-Didea.config.path=$ideaSandboxConfigDir",
"-Dapple.laf.useScreenMenuBar=true",
"-Dapple.awt.graphics.UseQuartz=true",
"-Dsun.io.useCanonCaches=false",
"-Dplugin.path=${ideaPluginDir.absolutePath}"
)
if (rootProject.findProperty("versions.androidStudioRelease") != null) {
jvmArgs("-Didea.platform.prefix=AndroidStudio")
}
if (project.hasProperty("noPCE")) {
jvmArgs("-Didea.ProcessCanceledException=disabled")
}
args()
doFirst {
val disabledPluginsFile = File(ideaSandboxConfigDir, "disabled_plugins.txt")
val disabledPluginsContents = disabledPluginsFile.takeIf { it.isFile }?.readLines()
val filteredContents = disabledPluginsContents?.filterNot { it.contains("org.jetbrains.kotlin") }
if (filteredContents != null && filteredContents.size != disabledPluginsContents.size) {
with(disabledPluginsFile.printWriter()) {
filteredContents.forEach(this::println)
}
}
}
body()
}
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
import org.gradle.api.Project
import org.gradle.api.artifacts.dsl.RepositoryHandler
import org.gradle.api.artifacts.repositories.MavenArtifactRepository
import java.net.URI
// https://youtrack.jetbrains.com/issue/ADM-23180
val mirroredUrls = listOf(
"https://dl.bintray.com/groovy/maven",
"https://dl.bintray.com/kotlin/kotlin-dev",
"https://dl.bintray.com/kotlin/kotlin-eap",
"https://dl.google.com/dl/android/maven2",
"https://dl.google.com/go",
"https://download.jetbrains.com",
"https://jcenter.bintray.com",
"https://jetbrains.bintray.com/dekaf",
"https://jetbrains.bintray.com/intellij-jdk",
"https://jetbrains.bintray.com/intellij-plugin-service",
"https://jetbrains.bintray.com/intellij-third-party-dependencies",
"https://jetbrains.bintray.com/markdown",
"https://jetbrains.bintray.com/teamcity-rest-client",
"https://jetbrains.bintray.com/test-discovery",
"https://jetbrains.bintray.com/jediterm",
"https://jitpack.io",
"https://maven.exasol.com/artifactory/exasol-releases",
"https://plugins.gradle.org/m2",
"https://plugins.jetbrains.com/maven",
"https://repo.grails.org/grails/core",
"https://repo.jenkins-ci.org/releases",
"https://repo.spring.io/milestone",
"https://repo1.maven.org/maven2",
"https://services.gradle.org",
"https://www.jetbrains.com/intellij-repository",
"https://www.myget.org/F/intellij-go-snapshots/maven",
"https://www.myget.org/F/rd-snapshots/maven",
"https://www.myget.org/F/rd-model-snapshots/maven",
"https://www.python.org/ftp",
"https://dl.google.com/dl/android/studio/ide-zips",
"https://dl.bintray.com/kotlin/ktor",
"https://cdn.azul.com/zulu/bin"
)
fun URI.toCacheRedirectorUri() = URI("https://cache-redirector.jetbrains.com/$host/$path")
fun RepositoryHandler.redirect() = filterIsInstance<MavenArtifactRepository>().forEach { repository ->
val uri = repository.url
if (uri.toString().trimEnd('/') in mirroredUrls) {
repository.url = uri.toCacheRedirectorUri()
}
}
fun Project.cacheRedirectorEnabled(): Boolean = findProperty("cacheRedirectorEnabled")?.toString()?.toBoolean() == true
fun RepositoryHandler.withRedirector(project: Project, configuration: RepositoryHandler.() -> Unit) {
configuration()
if (project.cacheRedirectorEnabled()) {
redirect()
}
}

View File

@@ -43,7 +43,7 @@ private val javaVersionRegex = Regex("""(?:1\.)?(\d+)(\.\d+)?([+-_]\w+){0,3}""")
fun MutableCollection<JdkId>.addIfBetter(project: Project, version: String, id: String, homeDir: File): Boolean {
val matchString = javaMajorVersionRegex.matchEntire(version)?.groupValues?.get(1)
val majorJdkVersion = when (matchString) {
val majorJersion = when (matchString) {
"6" -> JdkMajorVersion.JDK_16
"7" -> JdkMajorVersion.JDK_17
"8" -> JdkMajorVersion.JDK_18
@@ -53,9 +53,9 @@ fun MutableCollection<JdkId>.addIfBetter(project: Project, version: String, id:
return false
}
}
val prev = find { it.majorVersion == majorJdkVersion }
val prev = find { it.majorVersion == majorJersion }
if (prev == null) {
add(JdkId(false, majorJdkVersion, version, homeDir))
add(JdkId(false, majorJersion, version, homeDir))
return true
}
if (prev.explicit) return false

View File

@@ -1,208 +0,0 @@
/*
* 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.
*/
// usages in build scripts are not tracked properly
@file:Suppress("unused")
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.artifacts.ModuleDependency
import org.gradle.api.artifacts.dsl.RepositoryHandler
import org.gradle.api.artifacts.repositories.IvyArtifactRepository
import org.gradle.api.tasks.JavaExec
import org.gradle.kotlin.dsl.*
import java.io.File
private fun Project.kotlinBuildLocalRepoDir() = File("${project.rootDir.absoluteFile}/dependencies/repo")
private fun Project.ideModuleName() = when (IdeVersionConfigurator.currentIde.kind) {
Ide.Kind.AndroidStudio -> "android-studio-ide"
Ide.Kind.IntelliJ -> {
if (kotlinBuildProperties.intellijUltimateEnabled) "ideaIU" else "ideaIC"
}
}
private fun Project.ideModuleVersion() = when (IdeVersionConfigurator.currentIde.kind) {
Ide.Kind.AndroidStudio -> rootProject.findProperty("versions.androidStudioBuild")
Ide.Kind.IntelliJ -> rootProject.findProperty("versions.intellijSdk")
}
fun RepositoryHandler.kotlinBuildLocalRepo(project: Project): IvyArtifactRepository = ivy {
val baseDir = project.kotlinBuildLocalRepoDir()
url = baseDir.toURI()
patternLayout {
ivy("[organisation]/[module]/[revision]/[module].ivy.xml")
ivy("[organisation]/[module]/[revision]/ivy/[module].ivy.xml")
ivy("[organisation]/${project.ideModuleName()}/[revision]/ivy/[module].ivy.xml") // bundled plugins
artifact("[organisation]/[module]/[revision]/artifacts/lib/[artifact](-[classifier]).[ext]")
artifact("[organisation]/[module]/[revision]/artifacts/[artifact](-[classifier]).[ext]")
artifact("[organisation]/${project.ideModuleName()}/[revision]/artifacts/plugins/[module]/lib/[artifact](-[classifier]).[ext]") // bundled plugins
artifact("[organisation]/sources/[artifact]-[revision](-[classifier]).[ext]")
artifact("[organisation]/[module]/[revision]/[artifact](-[classifier]).[ext]")
}
metadataSources {
ivyDescriptor()
}
}
fun Project.intellijDep(module: String? = null) = "kotlin.build:${module ?: ideModuleName()}:${ideModuleVersion()}"
fun Project.intellijCoreDep() = "kotlin.build:intellij-core:${rootProject.extra["versions.intellijSdk"]}"
fun Project.jpsStandalone() = "kotlin.build:jps-standalone:${rootProject.extra["versions.intellijSdk"]}"
fun Project.nodeJSPlugin() = "kotlin.build:NodeJS:${rootProject.extra["versions.idea.NodeJS"]}"
fun Project.androidDxJar() = "org.jetbrains.kotlin:android-dx:${rootProject.extra["versions.androidBuildTools"]}"
fun Project.jpsBuildTest() = "com.jetbrains.intellij.idea:jps-build-test:${rootProject.extra["versions.intellijSdk"]}"
/**
* Runtime version of annotations that are already in Kotlin stdlib (historically Kotlin has older version of this one).
*
* SHOULD NOT BE USED IN COMPILE CLASSPATH!
*
* `@NonNull`, `@Nullabe` from `idea/annotations.jar` has `TYPE` target which leads to different types treatment in Kotlin compiler.
* On the other hand, `idea/annotations.jar` contains org/jetbrains/annotations/Async annations which is required for IDEA debugger.
*
* So, we are excluding `annotaions.jar` from all other `kotlin.build` and using this one for runtime only
* to avoid accidentally including `annotations.jar` by calling `intellijDep()`.
*/
fun Project.intellijRuntimeAnnotations() = "kotlin.build:intellij-runtime-annotations:${rootProject.extra["versions.intellijSdk"]}"
fun Project.intellijPluginDep(plugin: String) = intellijDep(plugin)
fun Project.intellijUltimateDep() = intellijDep("ideaIU")
fun Project.intellijUltimatePluginDep(plugin: String) = intellijDep(plugin)
fun ModuleDependency.includeJars(vararg names: String, rootProject: Project? = null) {
names.forEach {
var baseName = it.removeSuffix(".jar")
if (rootProject != null && rootProject.extra.has("ignore.jar.$baseName")) {
return@forEach
}
if (rootProject != null && rootProject.extra.has("versions.jar.$baseName")) {
baseName += "-${rootProject.extra["versions.jar.$baseName"]}"
}
artifact {
name = baseName
type = "jar"
extension = "jar"
}
}
}
// Workaround. Top-level Kotlin function in a default package can't be called from a non-default package
object IntellijRootUtils {
fun getRepositoryRootDir(project: Project): File = with(project.rootProject) {
return File(kotlinBuildLocalRepoDir(), "kotlin.build")
}
fun getIntellijRootDir(project: Project): File = with(project.rootProject) {
return File(
getRepositoryRootDir(this),
"${ideModuleName()}/${ideModuleVersion()}/artifacts"
)
}
}
fun ModuleDependency.includeIntellijCoreJarDependencies(project: Project) =
includeJars(*(project.rootProject.extra["IntellijCoreDependencies"] as List<String>).toTypedArray(), rootProject = project.rootProject)
fun ModuleDependency.includeIntellijCoreJarDependencies(project: Project, jarsFilterPredicate: (String) -> Boolean) =
includeJars(
*(project.rootProject.extra["IntellijCoreDependencies"] as List<String>).filter { jarsFilterPredicate(it) }.toTypedArray(),
rootProject = project.rootProject
)
fun Project.isIntellijCommunityAvailable() =
!(rootProject.extra["intellijUltimateEnabled"] as Boolean) || rootProject.extra["intellijSeparateSdks"] as Boolean
fun Project.isIntellijUltimateSdkAvailable() = (rootProject.extra["intellijUltimateEnabled"] as Boolean)
fun Project.intellijRootDir() = IntellijRootUtils.getIntellijRootDir(project)
fun Project.intellijUltimateRootDir() =
if (isIntellijUltimateSdkAvailable())
File(kotlinBuildLocalRepoDir(), "kotlin.build/ideaIU/${rootProject.extra["versions.intellijSdk"]}/artifacts")
else
throw GradleException("intellij ultimate SDK is not available")
fun DependencyHandlerScope.excludeInAndroidStudio(rootProject: Project, block: DependencyHandlerScope.() -> Unit) {
if (!rootProject.extra.has("versions.androidStudioRelease")) {
block()
}
}
fun Project.runIdeTask(name: String, ideaPluginDir: File, ideaSandboxDir: File, body: JavaExec.() -> Unit): JavaExec {
return task<JavaExec>(name) {
val ideaSandboxConfigDir = File(ideaSandboxDir, "config")
classpath = mainSourceSet.runtimeClasspath
main = "com.intellij.idea.Main"
workingDir = File(intellijRootDir(), "bin")
jvmArgs(
"-Xmx1250m",
"-XX:ReservedCodeCacheSize=240m",
"-XX:+HeapDumpOnOutOfMemoryError",
"-ea",
"-Didea.debug.mode=true",
"-Didea.system.path=$ideaSandboxDir",
"-Didea.config.path=$ideaSandboxConfigDir",
"-Dapple.laf.useScreenMenuBar=true",
"-Dapple.awt.graphics.UseQuartz=true",
"-Dsun.io.useCanonCaches=false",
"-Dplugin.path=${ideaPluginDir.absolutePath}"
)
if (rootProject.findProperty("versions.androidStudioRelease") != null) {
jvmArgs("-Didea.platform.prefix=AndroidStudio")
}
if (project.hasProperty("noPCE")) {
jvmArgs("-Didea.ProcessCanceledException=disabled")
}
jvmArgs("-Didea.is.internal=${project.findProperty("idea.is.internal") ?: true}")
project.findProperty("idea.args")?.let { arguments ->
jvmArgs(arguments.toString().split(" "))
}
args()
doFirst {
val disabledPluginsFile = File(ideaSandboxConfigDir, "disabled_plugins.txt")
val disabledPluginsContents = disabledPluginsFile.takeIf { it.isFile }?.readLines()
val filteredContents = disabledPluginsContents?.filterNot { it.contains("org.jetbrains.kotlin") }
if (filteredContents != null && filteredContents.size != disabledPluginsContents.size) {
with(disabledPluginsFile.printWriter()) {
filteredContents.forEach(this::println)
}
}
}
body()
}
}

View File

@@ -2,30 +2,27 @@
package org.jetbrains.kotlin.pill
import org.gradle.api.artifacts.*
import org.gradle.api.artifacts.component.*
class DependencyMapper(val predicate: (ResolvedArtifact) -> Boolean, val mapping: (ResolvedArtifact) -> MappedDependency?) {
companion object {
fun forProject(path: String, mapping: (ResolvedArtifact) -> MappedDependency?): DependencyMapper {
return DependencyMapper(
predicate = { artifact ->
val identifier = artifact.id.componentIdentifier as? ProjectComponentIdentifier
identifier?.projectPath == path
},
mapping = mapping
)
}
fun forModule(group: String, module: String, version: String?, mapping: (ResolvedArtifact) -> MappedDependency?): DependencyMapper {
return DependencyMapper(
predicate = { artifact ->
val identifier = artifact.id.componentIdentifier as? ModuleComponentIdentifier
identifier?.group == group && identifier?.module == module && (version == null || identifier?.version == version)
},
mapping = mapping
)
}
}
class DependencyMapper(
val predicate: (ResolvedDependency) -> Boolean,
vararg val configurations: String,
val mapping: (ResolvedDependency) -> MappedDependency?
) {
constructor(
group: String,
module: String,
vararg configurations: String,
version: String? = null,
mapping: (ResolvedDependency) -> MappedDependency?
) : this(
{ dep ->
dep.moduleGroup == group
&& dep.moduleName == module
&& (version == null || dep.moduleVersion == version)
},
configurations = *configurations,
mapping = mapping
)
}
class MappedDependency(val main: PDependency?, val deferred: List<PDependency> = emptyList())

View File

@@ -1,94 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@file:Suppress("PackageDirectoryMismatch")
package org.jetbrains.kotlin.pill
import java.io.File
import org.gradle.api.Project
import org.gradle.api.tasks.SourceSet
import org.gradle.api.artifacts.*
import org.gradle.api.artifacts.component.*
data class PDependencies(val main: List<PDependency>, val deferred: List<PDependency>) {
fun join(): List<PDependency> {
return main + deferred
}
}
fun Project.resolveDependencies(
configuration: Configuration,
forTests: Boolean,
dependencyMappers: List<DependencyMapper>,
withEmbedded: Boolean = false
): PDependencies {
val dependencies = mutableListOf<PDependency>()
val deferred = mutableListOf<PDependency>()
nextArtifact@ for (artifact in configuration.resolvedConfiguration.resolvedArtifacts) {
val identifier = artifact.id.componentIdentifier
for (mapper in dependencyMappers) {
if (mapper.predicate(artifact)) {
val mapped = mapper.mapping(artifact)
if (mapped != null) {
mapped.main?.let { dependencies += it }
deferred += mapped.deferred
}
continue@nextArtifact
}
}
fun addProjectDependency(projectPath: String) {
val project = rootProject.findProject(projectPath) ?: error("Cannot find project $projectPath")
fun addSourceSet(name: String, suffix: String): Boolean {
val sourceSet = project.sourceSets?.findByName(name)?.takeIf { !it.allSource.isEmpty() } ?: return false
dependencies += PDependency.Module(project.pillModuleName + '.' + suffix)
return true
}
if (forTests && artifact.classifier == "tests") {
addSourceSet(SourceSet.TEST_SOURCE_SET_NAME, "test") || addSourceSet(SourceSet.MAIN_SOURCE_SET_NAME, "src")
} else {
addSourceSet(SourceSet.MAIN_SOURCE_SET_NAME, "src")
}
if (withEmbedded) {
val embeddedConfiguration = project.configurations.findByName(EmbeddedComponents.CONFIGURATION_NAME)
if (embeddedConfiguration != null) {
dependencies += resolveDependencies(embeddedConfiguration, forTests, dependencyMappers, withEmbedded).join()
}
}
}
when (identifier) {
is ProjectComponentIdentifier -> addProjectDependency(identifier.projectPath)
is LibraryBinaryIdentifier -> addProjectDependency(identifier.projectPath)
is ModuleComponentIdentifier -> {
val file = artifact.file
val library = PLibrary(file.name, classes = listOf(file))
dependencies += PDependency.ModuleLibrary(library)
}
}
}
val existingFiles = mutableSetOf<File>()
for (dependency in configuration.dependencies) {
if (dependency !is SelfResolvingDependency) {
continue
}
val files = dependency.resolve().filter { it !in existingFiles }.takeIf { it.isNotEmpty() } ?: continue
existingFiles.addAll(files)
val library = PLibrary(dependency.name, classes = files.toList())
deferred += PDependency.ModuleLibrary(library)
}
return PDependencies(dependencies, deferred)
}

View File

@@ -5,7 +5,6 @@ package org.jetbrains.kotlin.pill
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.api.Project
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.ProjectDependency
import org.gradle.api.internal.file.copy.SingleParentCopySpec
import org.gradle.api.plugins.JavaPlugin
import org.gradle.api.tasks.Copy
@@ -35,10 +34,6 @@ sealed class ArtifactElement {
myChildren += child
}
fun add(children: List<ArtifactElement>) {
myChildren += children
}
abstract fun render(context: PathContext): xml
fun renderRecursively(context: PathContext): xml {
@@ -107,37 +102,99 @@ sealed class ArtifactElement {
}
}
fun generateKotlinPluginArtifactFile(rootProject: Project, dependencyMappers: List<DependencyMapper>): PFile {
fun generateKotlinPluginArtifactFile(rootProject: Project): PFile {
val mainIdeaPluginTask = rootProject.tasks.getByName("ideaPlugin")
val gradleArtifactDir = File(rootProject.extra["ideaPluginDir"] as File, "lib")
val ideaPluginTasks = mainIdeaPluginTask.taskDependencies
.getDependencies(mainIdeaPluginTask)
.filter { it.name == "ideaPlugin" }
.filterIsInstance<Copy>()
val root = Root()
fun Project.getProject(name: String) = findProject(name) ?: error("Cannot find project $name")
val prepareIdeaPluginProject = rootProject.getProject(":prepare:idea-plugin")
// Copy kotlinc directory
root.add(Directory("kotlinc").apply {
val kotlincDirectory = rootProject.extra["distKotlinHomeDir"].toString()
add(DirectoryCopy(File(kotlincDirectory)))
})
root.add(Directory("lib").apply {
val librariesConfiguration = prepareIdeaPluginProject.configurations.getByName("libraries")
add(getArtifactElements(rootProject, librariesConfiguration, dependencyMappers, false))
for (task in ideaPluginTasks) {
val spec = task.rootSpec.children.filterIsInstance<SingleParentCopySpec>().singleOrNull()
?: error("Copy spec is not unique in ${rootProject.name}. Available specs: ${task.rootSpec.children}")
add(Directory("jps").apply {
val prepareJpsPluginProject = rootProject.getProject(":kotlin-jps-plugin")
add(Archive(prepareJpsPluginProject.name + ".jar").apply {
val jpsPluginConfiguration = prepareIdeaPluginProject.configurations.getByName("jpsPlugin")
add(getArtifactElements(rootProject, jpsPluginConfiguration, dependencyMappers, true))
})
})
val sourcePaths = spec.sourcePaths
for (sourcePath in sourcePaths) {
if (sourcePath is ShadowJar) {
if (sourcePath.project.path == ":prepare:idea-plugin") {
val kotlinPluginJar = Archive(sourcePath.archiveName).also { root.getDirectory("lib").add(it) }
add(Archive("kotlin-plugin.jar").apply {
add(FileCopy(File(rootProject.projectDir, "resources/kotlinManifest.properties")))
kotlinPluginJar.add(FileCopy(File(rootProject.projectDir, "resources/kotlinManifest.properties")))
val embeddedConfiguration = prepareIdeaPluginProject.configurations.getByName(EmbeddedComponents.CONFIGURATION_NAME)
add(getArtifactElements(rootProject, embeddedConfiguration, dependencyMappers, true))
})
})
for (jarFile in sourcePath.project.configurations.getByName("packedJars").resolve()) {
kotlinPluginJar.add(ExtractedDirectory(jarFile))
}
@Suppress("UNCHECKED_CAST")
for (projectPath in sourcePath.project.extra["projectsToShadow"] as List<String>) {
val jpsModuleName = rootProject.findProject(projectPath)!!.name + ".src"
kotlinPluginJar.add(ModuleOutput(jpsModuleName))
}
continue
}
}
fun fileCopySnapshotAware(file: File): FileCopy {
val SHAPSHOT_JAR_SUFFIX = "-SNAPSHOT.jar"
if (file.name.endsWith(SHAPSHOT_JAR_SUFFIX)) {
return FileCopy(file, file.name.dropLast(SHAPSHOT_JAR_SUFFIX.length).substringBeforeLast("-") + ".jar")
}
return FileCopy(file)
}
when (sourcePath) {
is Jar -> {
val targetDir = ("lib/" + task.destinationDir.toRelativeString(gradleArtifactDir)).withoutSlash()
val archiveForJar = Archive(sourcePath.project.name + ".jar").apply {
if (task.project.plugins.hasPlugin(JavaPlugin::class.java)) {
add(ModuleOutput(sourcePath.project.name + ".src"))
}
root.getDirectory(targetDir).add(this)
}
val embeddedComponents = sourcePath.project.configurations
.findByName(EmbeddedComponents.CONFIGURATION_NAME)?.resolvedConfiguration
if (embeddedComponents != null) {
val configuration = CollectedConfiguration(embeddedComponents, Scope.COMPILE)
for (dependencyInfo in listOf(configuration).collectDependencies()) {
val dependency = (dependencyInfo as? DependencyInfo.ResolvedDependencyInfo)?.dependency ?: continue
if (dependency.isModuleDependency) {
archiveForJar.add(ModuleOutput(dependency.moduleName + ".src"))
} else if (dependency.configuration == "tests-jar" || dependency.configuration == "jpsTest") {
error("Test configurations are not allowed here")
} else {
for (file in dependency.moduleArtifacts.map { it.file }) {
archiveForJar.add(ExtractedDirectory(file))
}
}
}
}
}
is Configuration -> {
require(sourcePath.name == "sideJars") { "Configurations other than 'sideJars' are not supported" }
for (file in sourcePath.resolve()) {
root.getDirectory("lib").add(fileCopySnapshotAware(file))
}
}
else -> error("${task.name} Unexpected task type ${task.javaClass.name}")
}
}
}
val artifact = PArtifact("KotlinPlugin", File(rootProject.projectDir, "out/artifacts/Kotlin"), root)
return PFile(
@@ -146,37 +203,3 @@ fun generateKotlinPluginArtifactFile(rootProject: Project, dependencyMappers: Li
)
}
private fun getArtifactElements(
rootProject: Project,
configuration: Configuration,
dependencyMappers: List<DependencyMapper>,
extractDependencies: Boolean
): List<ArtifactElement> {
val dependencies = rootProject.resolveDependencies(configuration, false, dependencyMappers, withEmbedded = true).join()
val artifacts = mutableListOf<ArtifactElement>()
for (dependency in dependencies) {
when (dependency) {
is PDependency.Module -> {
val moduleOutput = ModuleOutput(dependency.name)
if (extractDependencies) {
artifacts += moduleOutput
} else {
artifacts += Archive(dependency.name + ".jar").apply {
add(moduleOutput)
}
}
}
is PDependency.Library -> artifacts += ProjectLibrary(dependency.name)
is PDependency.ModuleLibrary -> {
val files = dependency.library.classes
if (extractDependencies) files.mapTo(artifacts) { ExtractedDirectory(it) }
else files.mapTo(artifacts) { FileCopy(it) }
}
}
}
return artifacts
}

View File

@@ -1,6 +1,6 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
@file:Suppress("PackageDirectoryMismatch")
@@ -33,11 +33,13 @@ data class PProject(
data class PModule(
val name: String,
val bundleName: String,
val rootDirectory: File,
val moduleFile: File,
val contentRoots: List<PContentRoot>,
val orderRoots: List<POrderRoot>,
val moduleForProductionSources: PModule? = null
val moduleForProductionSources: PModule? = null,
val group: String? = null
)
data class PContentRoot(
@@ -62,6 +64,8 @@ data class PSourceRootKotlinOptions(
val apiVersion: String?,
val languageVersion: String?,
val jvmTarget: String?,
val addCompilerBuiltIns: Boolean?,
val loadBuiltInsFromDependencies: Boolean?,
val extraArguments: List<String>
) {
fun intersect(other: PSourceRootKotlinOptions) = PSourceRootKotlinOptions(
@@ -71,6 +75,8 @@ data class PSourceRootKotlinOptions(
if (apiVersion == other.apiVersion) apiVersion else null,
if (languageVersion == other.languageVersion) languageVersion else null,
if (jvmTarget == other.jvmTarget) jvmTarget else null,
if (addCompilerBuiltIns == other.addCompilerBuiltIns) addCompilerBuiltIns else null,
if (loadBuiltInsFromDependencies == other.loadBuiltInsFromDependencies) loadBuiltInsFromDependencies else null,
extraArguments.intersect(other.extraArguments).toList()
)
}
@@ -96,8 +102,7 @@ data class PLibrary(
val javadoc: List<File> = emptyList(),
val sources: List<File> = emptyList(),
val annotations: List<File> = emptyList(),
val dependencies: List<PLibrary> = emptyList(),
val originalName: String = name
val dependencies: List<PLibrary> = emptyList()
) {
fun attachSource(file: File): PLibrary {
return this.copy(sources = this.sources + listOf(file))
@@ -130,7 +135,7 @@ fun parse(project: Project, libraries: List<PLibrary>, context: ParserContext):
*/
private val CONFIGURATION_MAPPING = mapOf(
listOf("runtime") to Scope.RUNTIME,
listOf("compile", "embedded") to Scope.COMPILE,
listOf("compile") to Scope.COMPILE,
listOf("compileOnly") to Scope.PROVIDED
)
@@ -157,7 +162,7 @@ private fun ParserContext.parseModules(project: Project, excludedProjects: List<
var productionSourcesModule: PModule? = null
fun getModuleFile(suffix: String = ""): File {
val relativePath = File(project.projectDir, project.pillModuleName + suffix + ".iml")
val relativePath = File(project.projectDir, project.name + suffix + ".iml")
.toRelativeString(project.rootProject.projectDir)
return File(project.rootProject.projectDir, ".idea/modules/$relativePath")
@@ -172,12 +177,13 @@ private fun ParserContext.parseModules(project: Project, excludedProjects: List<
var dependencies = parseDependencies(project, mainRoot.forTests)
if (productionContentRoots.isNotEmpty() && mainRoot.forTests) {
val productionModuleDependency = PDependency.Module(project.pillModuleName + ".src")
val productionModuleDependency = PDependency.Module(project.name + ".src")
dependencies += POrderRoot(productionModuleDependency, Scope.COMPILE, true)
}
val module = PModule(
project.pillModuleName + nameSuffix,
project.name + nameSuffix,
project.name,
mainRoot.path,
getModuleFile(nameSuffix),
roots,
@@ -193,12 +199,13 @@ private fun ParserContext.parseModules(project: Project, excludedProjects: List<
}
val mainModuleFileRelativePath = when (project) {
project.rootProject -> File(project.rootProject.projectDir, project.rootProject.name + ".iml")
project.rootProject -> File(project.rootProject.projectDir, project.name + ".iml")
else -> getModuleFile()
}
modules += PModule(
project.pillModuleName,
project.name,
project.name,
project.projectDir,
mainModuleFileRelativePath,
listOf(PContentRoot(project.projectDir, false, emptyList(), allExcludedDirs)),
@@ -235,56 +242,53 @@ private fun parseSourceRoots(project: Project): List<PSourceRoot> {
val sourceRoots = mutableListOf<PSourceRoot>()
val sourceSets = project.sourceSets
if (sourceSets != null) {
for (sourceSet in sourceSets) {
val kotlinCompileTask = kotlinTasksBySourceSet[sourceSet.name]
val kind = if (sourceSet.isTestSourceSet) Kind.TEST else Kind.PRODUCTION
for (sourceSet in project.sourceSets) {
val kotlinCompileTask = kotlinTasksBySourceSet[sourceSet.name]
val kind = if (sourceSet.name == SourceSet.TEST_SOURCE_SET_NAME) Kind.TEST else Kind.PRODUCTION
fun Any.getKotlin(): SourceDirectorySet {
val kotlinMethod = javaClass.getMethod("getKotlin")
val oldIsAccessible = kotlinMethod.isAccessible
try {
kotlinMethod.isAccessible = true
return kotlinMethod(this) as SourceDirectorySet
} finally {
kotlinMethod.isAccessible = oldIsAccessible
}
fun Any.getKotlin(): SourceDirectorySet {
val kotlinMethod = javaClass.getMethod("getKotlin")
val oldIsAccessible = kotlinMethod.isAccessible
try {
kotlinMethod.isAccessible = true
return kotlinMethod(this) as SourceDirectorySet
} finally {
kotlinMethod.isAccessible = oldIsAccessible
}
}
val kotlinSourceDirectories = (sourceSet as HasConvention).convention
.plugins["kotlin"]?.getKotlin()?.srcDirs
val kotlinSourceDirectories = (sourceSet as HasConvention).convention
.plugins["kotlin"]?.getKotlin()?.srcDirs
?: emptySet()
val directories = (sourceSet.java.sourceDirectories.files + kotlinSourceDirectories).toList()
.filter { it.exists() }
.takeIf { it.isNotEmpty() }
val directories = (sourceSet.java.sourceDirectories.files + kotlinSourceDirectories).toList()
.filter { it.exists() }
.takeIf { it.isNotEmpty() }
?: continue
val kotlinOptions = kotlinCompileTask?.let { getKotlinOptions(it) }
val kotlinOptions = kotlinCompileTask?.let { getKotlinOptions(it) }
for (resourceRoot in sourceSet.resources.sourceDirectories.files) {
if (!resourceRoot.exists() || resourceRoot in directories) {
continue
}
val resourceRootKind = when (kind) {
Kind.PRODUCTION -> Kind.RESOURCES
Kind.TEST -> Kind.TEST_RESOURCES
else -> error("Invalid source root kind $kind")
}
sourceRoots += PSourceRoot(resourceRoot, resourceRootKind, kotlinOptions)
for (resourceRoot in sourceSet.resources.sourceDirectories.files) {
if (!resourceRoot.exists() || resourceRoot in directories) {
continue
}
for (directory in directories) {
sourceRoots += PSourceRoot(directory, kind, kotlinOptions)
val resourceRootKind = when (kind) {
Kind.PRODUCTION -> Kind.RESOURCES
Kind.TEST -> Kind.TEST_RESOURCES
else -> error("Invalid source root kind $kind")
}
for (root in parseResourceRootsProcessedByProcessResourcesTask(project, sourceSet)) {
if (sourceRoots.none { it.path == root.path }) {
sourceRoots += root
}
sourceRoots += PSourceRoot(resourceRoot, resourceRootKind, kotlinOptions)
}
for (directory in directories) {
sourceRoots += PSourceRoot(directory, kind, kotlinOptions)
}
for (root in parseResourceRootsProcessedByProcessResourcesTask(project, sourceSet)) {
if (sourceRoots.none { it.path == root.path }) {
sourceRoots += root
}
}
}
@@ -294,8 +298,9 @@ private fun parseSourceRoots(project: Project): List<PSourceRoot> {
private fun parseResourceRootsProcessedByProcessResourcesTask(project: Project, sourceSet: SourceSet): List<PSourceRoot> {
val isMainSourceSet = sourceSet.name == SourceSet.MAIN_SOURCE_SET_NAME
val isTestSourceSet = sourceSet.name == SourceSet.TEST_SOURCE_SET_NAME
val resourceRootKind = if (sourceSet.isTestSourceSet) PSourceRoot.Kind.TEST_RESOURCES else PSourceRoot.Kind.RESOURCES
val resourceRootKind = if (isTestSourceSet) PSourceRoot.Kind.TEST_RESOURCES else PSourceRoot.Kind.RESOURCES
val taskNameBase = "processResources"
val taskName = if (isMainSourceSet) taskNameBase else sourceSet.name + taskNameBase.capitalize()
val task = project.tasks.findByName(taskName) as? ProcessResources ?: return emptyList()
@@ -314,26 +319,20 @@ private fun parseResourceRootsProcessedByProcessResourcesTask(project: Project,
return roots.map { PSourceRoot(it, resourceRootKind, null) }
}
private val SourceSet.isTestSourceSet: Boolean
get() = name == SourceSet.TEST_SOURCE_SET_NAME
|| name.endsWith("Test")
|| name.endsWith("Tests")
private fun getKotlinOptions(kotlinCompileTask: Any): PSourceRootKotlinOptions? {
val compileArguments = run {
val method = kotlinCompileTask::class.java.getMethod("getSerializedCompilerArguments")
method.isAccessible = true
method.invoke(kotlinCompileTask) as List<String>
}
val compileArguments = kotlinCompileTask.invokeInternal("getSerializedCompilerArguments") as List<String>
fun parseBoolean(name: String) = compileArguments.contains("-$name")
fun parseString(name: String) = compileArguments.dropWhile { it != "-$name" }.drop(1).firstOrNull()
val addCompilerBuiltins = "Xadd-compiler-builtins"
val loadBuiltinsFromDependencies = "Xload-builtins-from-dependencies"
fun isOptionForScriptingCompilerPlugin(option: String)
= option.startsWith("-Xplugin=") && option.contains("kotlin-scripting-compiler")
val extraArguments = compileArguments.filter {
it.startsWith("-X") && !isOptionForScriptingCompilerPlugin(it)
&& it != "-$addCompilerBuiltins" && it != "-$loadBuiltinsFromDependencies"
}
return PSourceRootKotlinOptions(
@@ -343,6 +342,8 @@ private fun getKotlinOptions(kotlinCompileTask: Any): PSourceRootKotlinOptions?
parseString("api-version"),
parseString("language-version"),
parseString("jvm-target"),
parseBoolean(addCompilerBuiltins),
parseBoolean(loadBuiltinsFromDependencies),
extraArguments
)
}
@@ -360,25 +361,93 @@ private fun Any.invokeInternal(name: String, instance: Any = this): Any? {
}
private fun ParserContext.parseDependencies(project: Project, forTests: Boolean): List<POrderRoot> {
val configurations = project.configurations
val configurationMapping = if (forTests) TEST_CONFIGURATION_MAPPING else CONFIGURATION_MAPPING
val mainRoots = mutableListOf<POrderRoot>()
val deferredRoots = mutableListOf<POrderRoot>()
with(project.configurations) {
val mainRoots = mutableListOf<POrderRoot>()
val deferredRoots = mutableListOf<POrderRoot>()
for ((configurationNames, scope) in configurationMapping) {
for (configurationName in configurationNames) {
val configuration = configurations.findByName(configurationName) ?: continue
val (main, deferred) = project.resolveDependencies(configuration, forTests, dependencyMappers)
mainRoots += main.map { POrderRoot(it, scope) }
deferredRoots += deferred.map { POrderRoot(it, scope) }
fun collectConfigurations(): List<CollectedConfiguration> {
val configurations = mutableListOf<CollectedConfiguration>()
for ((configurationNames, scope) in configurationMapping) {
for (configurationName in configurationNames) {
val configuration = findByName(configurationName)?.also { it.resolve() } ?: continue
val extraDependencies = resolveExtraDependencies(configuration)
configurations += CollectedConfiguration(configuration.resolvedConfiguration, scope, extraDependencies)
}
}
return configurations
}
}
return removeDuplicates(mainRoots + deferredRoots)
nextDependency@ for (dependencyInfo in collectConfigurations().collectDependencies()) {
val scope = dependencyInfo.scope
if (dependencyInfo is DependencyInfo.CustomDependencyInfo) {
val files = dependencyInfo.files
val library = PLibrary(files.firstOrNull()?.nameWithoutExtension ?: "unnamed", classes = files)
mainRoots += POrderRoot(PDependency.ModuleLibrary(library), scope)
continue
}
val dependency = (dependencyInfo as DependencyInfo.ResolvedDependencyInfo).dependency
for (mapper in dependencyMappers) {
if (dependency.configuration in mapper.configurations && mapper.predicate(dependency)) {
val mappedDependency = mapper.mapping(dependency)
if (mappedDependency != null) {
val mainDependency = mappedDependency.main
if (mainDependency != null) {
mainRoots += POrderRoot(mainDependency, scope)
}
for (deferredDep in mappedDependency.deferred) {
deferredRoots += POrderRoot(deferredDep, scope)
}
}
continue@nextDependency
}
}
mainRoots += if (dependency.isModuleDependency && scope != Scope.TEST) {
POrderRoot(PDependency.Module(dependency.moduleName + ".src"), scope)
} else if (dependency.configuration == "tests-jar" || dependency.configuration == "jpsTest") {
POrderRoot(
PDependency.Module(dependency.moduleName + ".test"),
scope,
isProductionOnTestDependency = true
)
} else {
val classes = dependency.moduleArtifacts.map { it.file }
val library = PLibrary(dependency.moduleName, classes)
POrderRoot(PDependency.ModuleLibrary(library), scope)
}
}
return removeDuplicates(mainRoots + deferredRoots)
}
}
fun removeDuplicates(roots: List<POrderRoot>): List<POrderRoot> {
private fun resolveExtraDependencies(configuration: Configuration): List<File> {
return configuration.dependencies
.filterIsInstance<SelfResolvingDependency>()
.map { it.resolve() }
.filter { isGradleApiDependency(it) }
.flatMap { it }
}
private fun isGradleApiDependency(files: Iterable<File>): Boolean {
return listOf("gradle-api", "groovy-all").all { dep ->
files.any { it.extension == "jar" && it.name.startsWith("$dep-") }
}
}
private fun removeDuplicates(roots: List<POrderRoot>): List<POrderRoot> {
val dependenciesByScope = roots.groupBy { it.scope }.mapValues { it.value.mapTo(mutableSetOf()) { it.dependency } }
fun dependenciesFor(scope: Scope) = dependenciesByScope[scope] ?: emptySet<PDependency>()
@@ -411,11 +480,59 @@ fun removeDuplicates(roots: List<POrderRoot>): List<POrderRoot> {
return result.toList()
}
val Project.pillModuleName: String
get() = path.removePrefix(":").replace(':', '.')
data class CollectedConfiguration(
val configuration: ResolvedConfiguration,
val scope: Scope,
val extraDependencies: List<File> = emptyList())
val Project.sourceSets: SourceSetContainer?
get() {
val convention = project.convention.findPlugin(JavaPluginConvention::class.java) ?: return null
return convention.sourceSets
sealed class DependencyInfo(val scope: Scope) {
class ResolvedDependencyInfo(scope: Scope, val dependency: ResolvedDependency) : DependencyInfo(scope)
class CustomDependencyInfo(scope: Scope, val files: List<File>) : DependencyInfo(scope)
}
val ResolvedDependency.isModuleDependency
get() = configuration in JpsCompatiblePlugin.MODULE_CONFIGURATIONS
fun List<CollectedConfiguration>.collectDependencies(): List<DependencyInfo> {
val dependencies = mutableListOf<DependencyInfo>()
val unprocessed = LinkedList<DependencyInfo>()
val existing = mutableSetOf<Pair<Scope, ResolvedDependency>>()
for ((configuration, scope, extraDependencies) in this) {
for (dependency in configuration.firstLevelModuleDependencies) {
unprocessed += DependencyInfo.ResolvedDependencyInfo(scope, dependency)
}
if (!extraDependencies.isEmpty()) {
unprocessed += DependencyInfo.CustomDependencyInfo(scope, extraDependencies)
}
}
while (unprocessed.isNotEmpty()) {
val info = unprocessed.removeAt(0)
dependencies += info
info as? DependencyInfo.ResolvedDependencyInfo ?: continue
val data = Pair(info.scope, info.dependency)
existing += data
for (child in info.dependency.children) {
if (Pair(info.scope, child) in existing) {
continue
}
unprocessed += DependencyInfo.ResolvedDependencyInfo(info.scope, child)
}
}
return dependencies
}
private val Project.sourceSets: SourceSetContainer
get() {
lateinit var result: SourceSetContainer
project.configure<JavaPluginConvention> { result = sourceSets }
return result
}

View File

@@ -13,37 +13,51 @@ import java.io.File
class PillConfigurablePlugin : Plugin<Project> {
override fun apply(project: Project) {
project.configurations.maybeCreate(EmbeddedComponents.CONFIGURATION_NAME)
project.configurations.create(EmbeddedComponents.CONFIGURATION_NAME)
project.extensions.create("pill", PillExtension::class.java)
}
}
class JpsCompatiblePlugin : Plugin<Project> {
companion object {
val MODULE_CONFIGURATIONS = arrayOf("apiElements", "runtimeElements")
private fun mapper(module: String, vararg configurations: String): DependencyMapper {
return DependencyMapper("org.jetbrains.kotlin", module, *configurations) { MappedDependency(PDependency.Library(module)) }
}
private fun getDependencyMappers(projectLibraries: List<PLibrary>): List<DependencyMapper> {
val mappersForKotlinLibrariesExeptStdlib = projectLibraries
.filter { it.name != "kotlin-stdlib" }
.map { DependencyMapper.forProject(it.originalName) { MappedDependency(PDependency.Library(it.name)) } }
.mapTo(mutableListOf()) { mapper(it.name, "default", "distJar", *MODULE_CONFIGURATIONS) }
val disabledModuleMappers = listOf(
":kotlin-stdlib-common",
":core:builtins",
":kotlin-compiler",
":kotlin-compiler-embeddable",
":kotlin-test:kotlin-test-common",
":kotlin-test:kotlin-test-annotations-common"
).map { DependencyMapper.forProject(it) { null } }
return listOf(
DependencyMapper.forProject(":kotlin-stdlib") {
return mappersForKotlinLibrariesExeptStdlib + listOf(
DependencyMapper("org.jetbrains.kotlin", "kotlin-stdlib", "distJar", *MODULE_CONFIGURATIONS) {
MappedDependency(
PDependency.Library("kotlin-stdlib"),
listOf(PDependency.Library("annotations-13.0"))
)
},
DependencyMapper.forProject(":kotlin-test:kotlin-test-jvm") { MappedDependency(PDependency.Library("kotlin-test-jvm")) },
DependencyMapper.forProject(":kotlin-reflect-api") { MappedDependency(PDependency.Library("kotlin-reflect")) }
) + mappersForKotlinLibrariesExeptStdlib + disabledModuleMappers
DependencyMapper("org.jetbrains", "annotations", "default", version = "13.0") {
MappedDependency(
null,
listOf(PDependency.Library("annotations-13.0"))
)
},
DependencyMapper("org.jetbrains.kotlin", "kotlin-reflect-api", *MODULE_CONFIGURATIONS) {
MappedDependency(PDependency.Library("kotlin-reflect"))
},
DependencyMapper("org.jetbrains.kotlin", "kotlin-compiler-embeddable", "runtimeJar") { null },
DependencyMapper("org.jetbrains.kotlin", "kotlin-stdlib-js", "distJar") { null },
DependencyMapper("org.jetbrains.kotlin", "kotlin-compiler", "runtimeJar") { null },
DependencyMapper("org.jetbrains.kotlin", "compiler", *MODULE_CONFIGURATIONS) { null },
DependencyMapper("kotlin.build.custom.deps", "android", "default") { dep ->
val (sdkCommon, otherJars) = dep.moduleArtifacts.map { it.file }.partition { it.name == "sdk-common.jar" }
val mainLibrary = PDependency.ModuleLibrary(PLibrary(dep.moduleName, otherJars))
val deferredLibrary = PDependency.ModuleLibrary(PLibrary(dep.moduleName + "-deferred", sdkCommon))
MappedDependency(mainLibrary, listOf(deferredLibrary))
}
)
}
fun getProjectLibraries(rootProject: Project): List<PLibrary> {
@@ -64,8 +78,7 @@ class JpsCompatiblePlugin : Plugin<Project> {
PLibrary(
library.name,
classes = listOf(File(libraryPath, "$archivesBaseName.jar")).filterExisting(),
sources = listOf(File(libraryPath, "$archivesBaseName-sources.jar")).filterExisting(),
originalName = library.path
sources = listOf(File(libraryPath, "$archivesBaseName-sources.jar")).filterExisting()
)
}
@@ -128,20 +141,17 @@ class JpsCompatiblePlugin : Plugin<Project> {
}
val projectLibraries = getProjectLibraries(rootProject)
val dependencyMappers = getDependencyMappers(projectLibraries)
val parserContext = ParserContext(dependencyMappers, variant)
val parserContext = ParserContext(getDependencyMappers(projectLibraries), variant)
val jpsProject = parse(rootProject, projectLibraries, parserContext)
.mapLibraries(this::attachPlatformSources, this::attachAsmSources)
generateKotlinPluginArtifactFile(rootProject).write()
val files = render(jpsProject)
removeExistingIdeaLibrariesAndModules()
removeJpsAndPillRunConfigurations()
removeAllArtifactConfigurations()
generateKotlinPluginArtifactFile(rootProject, dependencyMappers).write()
removeJpsRunConfigurations()
copyRunConfigurations()
setOptionsForDefaultJunitRunConfiguration(rootProject)
@@ -153,8 +163,7 @@ class JpsCompatiblePlugin : Plugin<Project> {
initEnvironment(project)
removeExistingIdeaLibrariesAndModules()
removeJpsAndPillRunConfigurations()
removeAllArtifactConfigurations()
removeJpsRunConfigurations()
}
private fun removeExistingIdeaLibrariesAndModules() {
@@ -162,17 +171,10 @@ class JpsCompatiblePlugin : Plugin<Project> {
File(projectDir, ".idea/modules").deleteRecursively()
}
private fun removeJpsAndPillRunConfigurations() {
private fun removeJpsRunConfigurations() {
File(projectDir, ".idea/runConfigurations")
.walk()
.filter { (it.name.startsWith("JPS_") || it.name.startsWith("Pill_")) && it.extension.toLowerCase() == "xml" }
.forEach { it.delete() }
}
private fun removeAllArtifactConfigurations() {
File(projectDir, ".idea/artifacts")
.walk()
.filter { it.extension.toLowerCase() == "xml" }
.filter { it.name.startsWith("JPS_") && it.extension.toLowerCase() == "xml" }
.forEach { it.delete() }
}
@@ -261,8 +263,7 @@ class JpsCompatiblePlugin : Plugin<Project> {
addOrReplaceOptionValue("idea.home.path", platformDirProjectRelative)
addOrReplaceOptionValue("ideaSdk.androidPlugin.path", platformDirProjectRelative + "/plugins/android/lib")
addOrReplaceOptionValue("robolectric.classpath", robolectricClasspath)
addOrReplaceOptionValue("use.jps", "true")
addOrReplaceOptionValue("kotlinVersion", project.rootProject.extra["kotlinVersion"].toString())
addOrReplaceOptionValue("use.pill", "true")
val isAndroidStudioBunch = project.findProperty("versions.androidStudioRelease") != null
addOrReplaceOptionValue("idea.platform.prefix", if (isAndroidStudioBunch) "AndroidStudio" else null)
@@ -298,7 +299,7 @@ class JpsCompatiblePlugin : Plugin<Project> {
}
private fun attachPlatformSources(library: PLibrary): PLibrary {
val platformSourcesJar = File(platformDir, "../../../sources/intellij-$platformVersion-sources.jar")
val platformSourcesJar = File(platformDir, "../sources/ideaIC-$platformVersion-sources.jar")
if (library.classes.any { it.startsWith(platformDir) }) {
return library.attachSource(platformSourcesJar)

View File

@@ -31,7 +31,12 @@ private fun renderModulesFile(project: PProject) = PFile(
for (module in project.modules) {
val moduleFilePath = pathContext(module.moduleFile)
xml("module", "fileurl" to "file://$moduleFilePath", "filepath" to moduleFilePath)
if (module.group != null) {
xml("module", "fileurl" to "file://$moduleFilePath", "filepath" to moduleFilePath, "group" to module.group)
} else {
xml("module", "fileurl" to "file://$moduleFilePath", "filepath" to moduleFilePath)
}
}
}
}
@@ -80,8 +85,10 @@ private fun renderModule(project: PProject, module: PModule) = PFile(
kotlinCompileOptions.noStdlib.option("noStdlib")
kotlinCompileOptions.noReflect.option("noReflect")
module.name.option("moduleName")
kotlinCompileOptions.moduleName.option("moduleName")
xml("option", "name" to "jvmTarget", "value" to platformVersion)
kotlinCompileOptions.addCompilerBuiltIns.option("addCompilerBuiltIns")
kotlinCompileOptions.loadBuiltInsFromDependencies.option("loadBuiltInsFromDependencies")
kotlinCompileOptions.languageVersion.option("languageVersion")
kotlinCompileOptions.apiVersion.option("apiVersion")
@@ -197,4 +204,4 @@ private fun renderLibraryToXml(library: PLibrary, pathContext: PathContext, name
}
}
fun PLibrary.renderName() = name.takeIf { it != "unspecified" } ?: classes.first().nameWithoutExtension
fun PLibrary.renderName() = name?.takeIf { it != "unspecified" } ?: classes.first().nameWithoutExtension

View File

@@ -1,6 +1,6 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
import com.jakewharton.dex.*

View File

@@ -1,8 +1,15 @@
import org.gradle.api.Project
import org.gradle.api.tasks.SourceSet
import org.gradle.api.tasks.SourceSetContainer
@file:Suppress("unused") // usages in build scripts are not tracked properly
inline fun Project.sourceSets(crossinline body: SourceSetsBuilder.() -> Unit) = SourceSetsBuilder(this).body()
import org.gradle.api.*
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.*
import org.gradle.kotlin.dsl.*
import org.gradle.language.jvm.tasks.ProcessResources
//import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet
inline fun Project.sourceSets(crossinline body: SourceSetsBuilder.() -> Unit) =
SourceSetsBuilder(this).body()
class SourceSetsBuilder(val project: Project) {
@@ -33,6 +40,23 @@ val SourceSet.projectDefault: Project.() -> Unit
}
}
// TODO: adding KotlinSourceSet dep to the plugin breaks the build unexpectedly, resolve and uncomment
//val SourceSet.kotlin: SourceDirectorySet
// get() =
// (this as HasConvention)
// .convention
// .getPlugin(KotlinSourceSet::class.java)
// .kotlin
//
//
//fun SourceSet.kotlin(action: SourceDirectorySet.() -> Unit) =
// kotlin.action()
fun Project.getSourceSetsFrom(projectPath: String): SourceSetContainer {
evaluationDependsOn(projectPath)
return project(projectPath).sourceSets
}
val Project.sourceSets: SourceSetContainer
get() = javaPluginConvention().sourceSets

View File

@@ -1,7 +1,7 @@
@file:Suppress("unused") // usages in build scripts are not tracked properly
import org.gradle.api.logging.Logger
import org.jetbrains.org.objectweb.asm.*
import org.objectweb.asm.*
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
@@ -23,7 +23,7 @@ fun stripMetadata(logger: Logger, classNamePattern: String, inFile: File, outFil
var changed = false
val classWriter = ClassWriter(0)
val classVisitor = object : ClassVisitor(Opcodes.API_VERSION, classWriter) {
val classVisitor = object : ClassVisitor(Opcodes.ASM5, classWriter) {
override fun visitAnnotation(desc: String, visible: Boolean): AnnotationVisitor? {
if (Type.getType(desc).internalName == "kotlin/Metadata") {
changed = true

View File

@@ -25,13 +25,10 @@ import org.gradle.api.tasks.testing.Test
import org.gradle.kotlin.dsl.extra
import org.gradle.kotlin.dsl.project
import org.gradle.kotlin.dsl.task
import java.io.File
import java.lang.Character.isLowerCase
import java.lang.Character.isUpperCase
import java.nio.file.Files
import java.nio.file.Path
fun Project.projectTest(taskName: String = "test", parallel: Boolean = false, body: Test.() -> Unit = {}): Test = getOrCreateTask(taskName) {
fun Project.projectTest(taskName: String = "test", body: Test.() -> Unit = {}): Test = getOrCreateTask(taskName) {
doFirst {
val commandLineIncludePatterns = (filter as? DefaultTestFilter)?.commandLineIncludePatterns ?: emptySet()
val patterns = filter.includePatterns + commandLineIncludePatterns
@@ -101,36 +98,6 @@ fun Project.projectTest(taskName: String = "test", parallel: Boolean = false, bo
environment("PROJECT_BUILD_DIR", buildDir)
systemProperty("jps.kotlin.home", rootProject.extra["distKotlinHomeDir"]!!)
systemProperty("kotlin.ni", if (rootProject.hasProperty("newInferenceTests")) "true" else "false")
var subProjectTempRoot: Path? = null
doFirst {
val teamcity = rootProject.findProperty("teamcity") as? Map<Any?, *>
val systemTempRoot =
// TC by default doesn't switch `teamcity.build.tempDir` to 'java.io.tmpdir' so it could cause to wasted disk space
// Should be fixed soon on Teamcity side
(teamcity?.get("teamcity.build.tempDir") as? String)
?: System.getProperty("java.io.tmpdir")
systemTempRoot.let {
subProjectTempRoot = Files.createTempDirectory(File(systemTempRoot).toPath(), project.name + "Project_" + taskName + "_")
systemProperty("java.io.tmpdir", subProjectTempRoot.toString())
}
}
doLast {
subProjectTempRoot?.let {
try {
delete(it)
} catch (e: Exception) {
project.logger.warn("Can't delete test temp root folder $it", e.printStackTrace())
}
}
}
if (parallel) {
maxParallelForks =
project.findProperty("kotlin.test.maxParallelForks")?.toString()?.toInt()
?: Math.max(Runtime.getRuntime().availableProcessors() / 2, 1)
}
body()
}
@@ -155,7 +122,7 @@ private fun Task.useAndroidConfiguration(systemPropertyName: String, configName:
.also {
dependencies.add(
configName,
dependencies.project(":dependencies:android-sdk", configuration = configName)
dependencies.project(":custom-dependencies:android-sdk", configuration = configName)
)
}
}

View File

@@ -0,0 +1,8 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="[JPS] All Compiler Tests" type="CompoundRunConfigurationType" factoryName="Compound Run Configuration">
<toRun type="JUnit" name="[JPS] Compiler Tests" />
<toRun type="JUnit" name="[JPS] JS Backend Tests" />
<toRun type="JUnit" name="[JPS] Java 8 Tests" />
<method />
</configuration>
</component>

View File

@@ -0,0 +1,37 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="[JPS] All IDEA Plugin Tests" type="JUnit" factoryName="JUnit">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea">
<pattern>
<option name="PATTERN" value="org.jetbrains.kotlin.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<module name="idea.test" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="PACKAGE_NAME" value="org.jetbrains.kotlin" />
<option name="MAIN_CLASS_NAME" value="" />
<option name="METHOD_NAME" value="" />
<option name="TEST_OBJECT" value="package" />
<option name="VM_PARAMETERS" value="-ea -XX:+HeapDumpOnOutOfMemoryError -Xmx1250m -XX:+UseCodeCacheFlushing -XX:ReservedCodeCacheSize=128m -Djna.nosys=true -Duse.pill=true -Didea.home.path=$IDEA_HOME_PATH$" />
<option name="PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<envs />
<patterns />
<RunnerSettings RunnerId="Debug">
<option name="DEBUG_PORT" value="" />
<option name="TRANSPORT" value="0" />
<option name="LOCAL" value="true" />
</RunnerSettings>
<RunnerSettings RunnerId="Profile " />
<RunnerSettings RunnerId="Run" />
<ConfigurationWrapper RunnerId="Debug" />
<ConfigurationWrapper RunnerId="Run" />
<method />
</configuration>
</component>

View File

@@ -0,0 +1,35 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="[JPS] Compiler Tests" type="JUnit" factoryName="JUnit">
<module name="compiler.test" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="org.jetbrains.kotlin.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="PACKAGE_NAME" value="org.jetbrains.kotlin" />
<option name="MAIN_CLASS_NAME" value="" />
<option name="METHOD_NAME" value="" />
<option name="TEST_OBJECT" value="package" />
<option name="VM_PARAMETERS" value="-ea -XX:+HeapDumpOnOutOfMemoryError -Xmx1024m -XX:+UseCodeCacheFlushing -XX:ReservedCodeCacheSize=128m -Djna.nosys=true -Duse.pill=true -Didea.home.path=$IDEA_HOME_PATH$" />
<option name="PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<patterns />
<RunnerSettings RunnerId="Debug">
<option name="DEBUG_PORT" value="" />
<option name="TRANSPORT" value="0" />
<option name="LOCAL" value="true" />
</RunnerSettings>
<RunnerSettings RunnerId="Profile " />
<RunnerSettings RunnerId="Run" />
<ConfigurationWrapper RunnerId="Debug" />
<ConfigurationWrapper RunnerId="Run" />
<method />
</configuration>
</component>

View File

@@ -0,0 +1,8 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="[JPS] Generate All Tests" type="Application" factoryName="Application">
<option name="MAIN_CLASS_NAME" value="org.jetbrains.kotlin.pill.generateAllTests.Main" />
<module name="generate-all-tests.test" />
<option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$" />
<method />
</configuration>
</component>

View File

@@ -0,0 +1,41 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="[JPS] IDEA" type="Application" factoryName="Application" singleton="true">
<log_file alias="idea.log" path="$PROJECT_DIR$/ideaSDK/system-idea/log/idea.log" />
<option name="MAIN_CLASS_NAME" value="com.intellij.idea.Main" />
<module name="idea-runner" />
<option name="VM_PARAMETERS" value="-Xmx1250m -XX:ReservedCodeCacheSize=240m -XX:+HeapDumpOnOutOfMemoryError -ea -Didea.is.internal=true -Didea.debug.mode=true -Didea.system.path=$PROJECT_DIR$/local/ideaSandbox -Didea.config.path=$PROJECT_DIR$/local/ideaSandbox/config -Dapple.laf.useScreenMenuBar=true -Dapple.awt.graphics.UseQuartz=true -Dsun.io.useCanonCaches=false -Dplugin.path=$PROJECT_DIR$/out/artifacts/Kotlin $ADDITIONAL_IDEA_ARGS$" />
<option name="WORKING_DIRECTORY" value="file://$IDEA_HOME_PATH$" />
<RunnerSettings RunnerId="Debug">
<option name="DEBUG_PORT" value="" />
<option name="TRANSPORT" value="0" />
<option name="LOCAL" value="true" />
</RunnerSettings>
<RunnerSettings RunnerId="JavaRebel">
<option name="bootstrapPath" />
<option name="jrebelArgs" value="" />
<option name="loggingEnabled" value="false" />
<option name="useBootstrapDefaults" value="true" />
</RunnerSettings>
<RunnerSettings RunnerId="JavaRebel Debug">
<option name="bootstrapPath" />
<option name="debugPort" value="" />
<option name="jrebelArgs" value="" />
<option name="loggingEnabled" value="false" />
<option name="transport" value="0" />
<option name="useBootstrapDefaults" value="true" />
<option name="DEBUG_PORT" value="" />
<option name="TRANSPORT" value="0" />
<option name="LOCAL" value="true" />
</RunnerSettings>
<RunnerSettings RunnerId="Profile " />
<RunnerSettings RunnerId="Run" />
<ConfigurationWrapper RunnerId="Debug" />
<ConfigurationWrapper RunnerId="Profile " />
<ConfigurationWrapper RunnerId="Run" />
<method>
<option name="BuildArtifacts" enabled="true">
<artifact name="KotlinPlugin" />
</option>
</method>
</configuration>
</component>

View File

@@ -0,0 +1,41 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="[JPS] IDEA (No ProcessCanceledException)" type="Application" factoryName="Application" singleton="true">
<log_file alias="idea.log" path="$PROJECT_DIR$/ideaSDK/system-idea/log/idea.log" />
<option name="MAIN_CLASS_NAME" value="com.intellij.idea.Main" />
<module name="idea-runner" />
<option name="VM_PARAMETERS" value="-Xmx1250m -XX:ReservedCodeCacheSize=240m -XX:+HeapDumpOnOutOfMemoryError -ea -Didea.is.internal=true -Didea.debug.mode=true -Didea.system.path=$PROJECT_DIR$/local/ideaSandbox -Didea.config.path=$PROJECT_DIR$/local/ideaSandbox/config -Dapple.laf.useScreenMenuBar=true -Dapple.awt.graphics.UseQuartz=true -Dsun.io.useCanonCaches=false -Dplugin.path=$PROJECT_DIR$/out/artifacts/Kotlin -Didea.ProcessCanceledException=disabled $ADDITIONAL_IDEA_ARGS$" />
<option name="WORKING_DIRECTORY" value="file://$IDEA_HOME_PATH$" />
<RunnerSettings RunnerId="Debug">
<option name="DEBUG_PORT" value="" />
<option name="TRANSPORT" value="0" />
<option name="LOCAL" value="true" />
</RunnerSettings>
<RunnerSettings RunnerId="JavaRebel">
<option name="bootstrapPath" />
<option name="jrebelArgs" value="" />
<option name="loggingEnabled" value="false" />
<option name="useBootstrapDefaults" value="true" />
</RunnerSettings>
<RunnerSettings RunnerId="JavaRebel Debug">
<option name="bootstrapPath" />
<option name="debugPort" value="" />
<option name="jrebelArgs" value="" />
<option name="loggingEnabled" value="false" />
<option name="transport" value="0" />
<option name="useBootstrapDefaults" value="true" />
<option name="DEBUG_PORT" value="" />
<option name="TRANSPORT" value="0" />
<option name="LOCAL" value="true" />
</RunnerSettings>
<RunnerSettings RunnerId="Profile " />
<RunnerSettings RunnerId="Run" />
<ConfigurationWrapper RunnerId="Debug" />
<ConfigurationWrapper RunnerId="Profile " />
<ConfigurationWrapper RunnerId="Run" />
<method>
<option name="BuildArtifacts" enabled="true">
<artifact name="KotlinPlugin" />
</option>
</method>
</configuration>
</component>

View File

@@ -0,0 +1,28 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="[JPS] JS Backend Tests" type="JUnit" factoryName="JUnit">
<module name="js.tests.test" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="PACKAGE_NAME" value="org.jetbrains.kotlin.js.test" />
<option name="MAIN_CLASS_NAME" value="" />
<option name="METHOD_NAME" value="" />
<option name="TEST_OBJECT" value="package" />
<option name="VM_PARAMETERS" value="-ea -XX:+HeapDumpOnOutOfMemoryError -Xmx1250m -XX:+UseCodeCacheFlushing -Djna.nosys=true -Duse.pill=true -Dkotlin.js.skipMinificationTest=false" />
<option name="PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<patterns />
<RunnerSettings RunnerId="Debug">
<option name="DEBUG_PORT" value="" />
<option name="TRANSPORT" value="0" />
<option name="LOCAL" value="true" />
</RunnerSettings>
<RunnerSettings RunnerId="Run" />
<ConfigurationWrapper RunnerId="Debug" />
<ConfigurationWrapper RunnerId="Run" />
<method />
</configuration>
</component>

View File

@@ -0,0 +1,35 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="[JPS] JVM Backend Tests" type="JUnit" factoryName="JUnit">
<module name="compiler.test" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="org.jetbrains.kotlin.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="PACKAGE_NAME" value="org.jetbrains.kotlin.codegen" />
<option name="MAIN_CLASS_NAME" value="" />
<option name="METHOD_NAME" value="" />
<option name="TEST_OBJECT" value="package" />
<option name="VM_PARAMETERS" value="-ea -XX:+HeapDumpOnOutOfMemoryError -Xmx1024m -XX:+UseCodeCacheFlushing -XX:ReservedCodeCacheSize=128m -Djna.nosys=true -Duse.pill=true -Didea.home.path=$IDEA_HOME_PATH$" />
<option name="PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<patterns />
<RunnerSettings RunnerId="Debug">
<option name="DEBUG_PORT" value="" />
<option name="TRANSPORT" value="0" />
<option name="LOCAL" value="true" />
</RunnerSettings>
<RunnerSettings RunnerId="Profile " />
<RunnerSettings RunnerId="Run" />
<ConfigurationWrapper RunnerId="Debug" />
<ConfigurationWrapper RunnerId="Run" />
<method />
</configuration>
</component>

View File

@@ -0,0 +1,26 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="[JPS] Java 8 Tests" type="JUnit" factoryName="JUnit">
<module name="tests-java8.test" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="org.jetbrains.kotlin.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="true" />
<option name="ALTERNATIVE_JRE_PATH" value="1.8" />
<option name="PACKAGE_NAME" value="org.jetbrains.kotlin" />
<option name="MAIN_CLASS_NAME" value="" />
<option name="METHOD_NAME" value="" />
<option name="TEST_OBJECT" value="package" />
<option name="VM_PARAMETERS" value="-ea -XX:+HeapDumpOnOutOfMemoryError -XX:+UseCodeCacheFlushing -XX:ReservedCodeCacheSize=128m -Djna.nosys=true -Duse.pill=true -Dkotlin.colors.enabled=false -Didea.home.path=$IDEA_HOME_PATH$" />
<option name="PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<patterns />
<method />
</configuration>
</component>

View File

@@ -0,0 +1,21 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="[JPS] Refresh JPS Model" type="GradleRunConfiguration" factoryName="Gradle" singleton="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="pill" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<method />
</configuration>
</component>

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