Compare commits

..

547 Commits

Author SHA1 Message Date
Ilya Gorbunov
994eceabc0 Deprecate dropWhileTo and takeWhileTo on CharSequences.
(cherry picked from commit 14f17e7)
2016-01-19 07:14:30 +03:00
Ilya Gorbunov
e46544cc5e Deprecate 'comparator { ... }' in favor of Comparator SAM-constructor. Provide SAM-like constructor for JS.
(cherry picked from commit 5bbce7a)
2016-01-19 07:14:18 +03:00
Ilya Gorbunov
c0668334b4 Move comparison related functions to kotlin.comparisons, update imports in stdlib.
(cherry picked from commit 67ef790)
2016-01-19 07:14:06 +03:00
Ilya Gorbunov
1ad2c6e4a7 Deprecate getOrImplicitDefault to make it private later.
(cherry picked from commit c250921)
2016-01-19 07:13:50 +03:00
Ilya Gorbunov
26b3c06963 Provide mutableSetOf and mutableMapOf
#KT-9663 Fixed
(cherry picked from commit aafd790)
2016-01-19 07:13:38 +03:00
Ilya Gorbunov
362f1641b8 Provide mutableListOf.
Deprecate linkedListOf.
#KT-9663
(cherry picked from commit fe8ba4d)
2016-01-19 07:13:27 +03:00
Stanislav Erokhin
889126cc25 Possible fix for KT-10603. 2016-01-18 19:47:12 +03:00
Mikhail Glukhikh
000b14d86e Diagnostic message fixed for 'PRIVATE_SETTER_FOR_OPEN_PROPERTY'
(cherry picked from commit 380e2dd)
2016-01-18 14:07:18 +03:00
Valentin Kipyatkov
258ae08a6e "Rename on import" hides importing of the same symbol by other imports with the original name
(cherry picked from commit 5a079de)
2016-01-18 13:11:05 +03:00
Valentin Kipyatkov
a0d9271e00 Do not use incorrect import
(cherry picked from commit 4704188)
2016-01-18 13:07:15 +03:00
Valentin Kipyatkov
3ceba38a78 Minor
(cherry picked from commit 866f3f1)
2016-01-18 13:07:05 +03:00
Valentin Kipyatkov
c28e9b0f3c Renamed class
(cherry picked from commit 8984368)
2016-01-18 13:06:53 +03:00
Mikhail Glukhikh
5b23a86f6e Cleanup: DataFlowAnalyzer, ignore MethodMayBeStatic for SmartCastManager
(cherry picked from commit c48c3fc)
2016-01-18 10:05:39 +03:00
Mikhail Glukhikh
8c1cd3a1ed Separate UNSAFE_IMPLICIT_INVOKE_CALL diagnostics introduced (see KT-8252)
(cherry picked from commit 6157ebe)
2016-01-18 10:05:30 +03:00
Mikhail Glukhikh
ab7c2cb82a Minor
(cherry picked from commit fe11b5a)
2016-01-18 10:05:14 +03:00
Mikhail Glukhikh
b707da415c Nullable function-like property call is prohibited now #KT-8252 Fixed
(cherry picked from commit 1049d4c)
2016-01-18 10:05:01 +03:00
Mikhail Glukhikh
ddfdff0b30 initialDataFlowInfoForArguments introduced in CallExpressionResolver methods #KT-10175 Fixed
(cherry picked from commit 0f80df7)
2016-01-18 10:03:47 +03:00
Mikhail Glukhikh
e7c81388b7 Get rid of MutableDataFlorInfoForArguments.setInitialDataFlowInfo
(cherry picked from commit 16d97ab)
2016-01-18 10:03:35 +03:00
Mikhail Glukhikh
b00d05ecad Minor refactoring of getQualifiedExpressionTypeInfo
(cherry picked from commit 5ceb973)
2016-01-18 10:03:15 +03:00
Pavel V. Talanov
f5ead3507a Avoid throwing on trying to obtain module info by some unexpected light element 2016-01-17 14:02:44 +03:00
Pavel V. Talanov
a4b9c32933 Analyze local variable declarations in expression position
Fixes exception on invalid code "val c = 1 < val Int.f: Int = 3"
2016-01-17 14:02:44 +03:00
Pavel V. Talanov
8839e9f707 Minor: prettify code after autoconversion 2016-01-17 14:02:43 +03:00
Pavel V. Talanov
4f9b441a66 Refactor: extract type checking code for local variables to a separate component, extract code that creates descriptors for local variable out of DescriptorResolver 2016-01-17 14:02:43 +03:00
Pavel V. Talanov
e4116624c3 AnnotationUtil: Do not throw on ErrorValue constant 2016-01-17 14:02:42 +03:00
Pavel V. Talanov
4dd91c0a81 Minor: fix missed error marker in test data 2016-01-17 14:02:42 +03:00
Pavel V. Talanov
47ad2370e3 Do not build light classes for local classes when the there is no class descriptor
These cases should be dealt with and this is only a way to degrade gracefully
2016-01-17 14:02:41 +03:00
Pavel V. Talanov
39598530d5 Parse local interfaces in expression position 2016-01-17 14:02:41 +03:00
Pavel V. Talanov
fa98553461 Create class descriptors for local classes in illegal positions
Typecheck code in illegal selector position
Fixes exceptions on "val p = A.class" erroneous code
2016-01-17 14:02:40 +03:00
Pavel V. Talanov
94369a24d5 Fix codegen predictor for properties and property accessors 2016-01-17 14:02:40 +03:00
Pavel V. Talanov
036828b923 Add and use KtPropertyAccessor#getProperty() 2016-01-17 14:02:39 +03:00
Pavel V. Talanov
5f27032bae IDELightClassGenerationSupport: fix a problem when marking source root as both source and library source led to SO
# KT-10413 Fixed
2016-01-17 14:02:39 +03:00
Pavel V. Talanov
cee7724d9f Minor, ProjectRootsUtil: extract a couple of utils and use them 2016-01-17 14:02:38 +03:00
Pavel V. Talanov
a86fcf1141 Add better diagnostic for "could not create stub for nested class" failures 2016-01-17 14:02:38 +03:00
Pavel V. Talanov
02262534db Fix an exception caused by objects literals in supertype list not considered local 2016-01-17 14:02:36 +03:00
Ilya Gorbunov
2706dd1d8e Annotate Iterable.forEach and Map.forEach with HidesMembers.
#KT-10538 Fixed
#KT-10479 Fixed
(cherry picked from commit 3d5e415)
2016-01-16 18:48:39 +03:00
Ilya Gorbunov
2b1b54bc28 Hide listFiles as it's no more preferred by overload resolution over synthetic SAM invocations.
#KT-10652 Fixed
(cherry picked from commit 56ddd49)
2016-01-16 17:51:23 +03:00
Ilya Gorbunov
0cd0f54b21 Rename defaultBufferSize to DEFAULT_BUFFER_SIZE.
(cherry picked from commit a64c1ff)
2016-01-16 17:51:00 +03:00
Ilya Gorbunov
24522175e5 J2K: Avoid to convert to deprecated String methods, namely toByteArray.
(cherry picked from commit ddcafdd)
2016-01-16 17:50:52 +03:00
Ilya Gorbunov
74d7d109b9 Deprecate functions taking charset name as string.
(cherry picked from commit ac15807)
2016-01-16 17:50:47 +03:00
Stanislav Erokhin
fe5df28123 Create new HidesMembers annotation 2016-01-15 23:39:44 +03:00
Dmitry Jemerov
62f92f2453 streamlined plugin update logic
(cherry picked from commit 63dd0fc)
2016-01-15 19:20:27 +01:00
Dmitry Jemerov
839c1d29d3 plugin autoupdate fixed: always provide plugin descriptor with new version number to plugin downloader
(cherry picked from commit 765d58b)
2016-01-15 19:20:16 +01:00
NataliaUkhorskaya
ecddf5ee20 Gradle plugin: fix compatibility with android-gradle plugin 2.0.0-alpha5
#KT-10676 Fixed
(cherry picked from commit d4fcb59)
2016-01-15 20:59:10 +03:00
Michael Bogdanov
b7b099e795 Prohibit super calls with default parameters
(cherry picked from commit 9b3d974)
2016-01-15 17:55:54 +03:00
Dmitry Petrov
292055276d KT-10646, KT-10647:
Move IMPLICIT_CAST_TO_UNIT_OR_ANY to ControlFlowInformationProvider
(where checks for 'if' and 'when' used as expressions are performed).
(cherry picked from commit f54de08)
2016-01-15 16:07:54 +03:00
Dmitry Petrov
90491cf683 KT-6646, KT-10482:
when a method (or a property getter) returns Nothing, emit
  ACONST_NULL
  ATHROW
after a call so that class files verifier knows that this is an exit point in a method.
Note that if an inline method returning Nothing throws an exception explicitly
(or via a chain of inline methods), this code will be deleted by DCE.
(cherry picked from commit b736880)
2016-01-15 16:07:53 +03:00
Dmitry Petrov
d4c55159bd Drop "substitute with upper bounds" mode for calls with mapped arguments
(we don't need it since we build constraint system for generic types).
Cleanup tests.
(cherry picked from commit 74c1390)
2016-01-15 16:07:53 +03:00
Dmitry Petrov
b7451c6e2b Check specificity relation for generant types of the constraint system.
Otherwise we can't properly chose between 'dynamic' and generic type.
(cherry picked from commit 4b3290d)
2016-01-15 16:07:53 +03:00
Dmitry Petrov
3941ac308d stdlib fixes:
- 'sequence(initialValue: T?, ...)' should have LowPriorityInOverloadResolution
(otherwise 'sequence({...}, {...})' is ambiguous).
- 'copyOf' and 'copyOfRange' should be defined for 'Array<T>' only
('Array<out T>' version always loses to 'Array<T>', since the second one
is always more specific).
(cherry picked from commit c97294a)
2016-01-15 16:07:53 +03:00
Dmitry Petrov
28f7ed010b Use constraint system for comparing for specificity against a generic signature.
Drop "discrimiate generics" mode where it's unneeded.
(cherry picked from commit 02daeac)
2016-01-15 16:07:52 +03:00
Yan Zhulanow
9a19322bac More precise diagnostic messages about "operator modifier is not applicable" 2016-01-15 20:14:27 +09:00
Yan Zhulanow
cca091991f "Inapplicable operator modifier" and "Inapplicable infix modifier" are now errors 2016-01-15 20:14:27 +09:00
Stanislav Erokhin
3933b8a48f Change resolution priority about implicit receivers and synthesized member-like descriptors.
Change resolution to consider extensions to implicit receiver before members of another implicit receiver.
Make synthesized member-like extensions resolve right after the members.

#KT-10510 Fixed
#KT-10219 Fixed
2016-01-14 21:37:39 +03:00
Stanislav Erokhin
a69bd11a77 Minor. Extract tower data creation to separate function. 2016-01-14 21:36:26 +03:00
Stanislav Erokhin
e3d45d22ac Move levels to TowerResolver 2016-01-14 21:36:25 +03:00
Zalim Bashorov
d6b04166c0 Don't fail when create IncrementalCacheImpl for target without output directory, and fail when try to use this info instead.
#KT-10505 Fixed
(cherry picked from commit c1dbfee)
2016-01-14 21:26:24 +03:00
Zalim Bashorov
dbcb91a118 Don't fail when output directory not specified for "friend" build target
#KT-10505 Fixed
(cherry picked from commit d9af947)
2016-01-14 21:25:52 +03:00
Zalim Bashorov
58b1cf42ae Report error when output directory not specified for build target
#KT-10505 Fixed
(cherry picked from commit 3df091e)
2016-01-14 21:25:39 +03:00
Valentin Kipyatkov
6221c76578 KT-10664 No code completion after variable initialized with elvis
#KT-10664 Fixed
(cherry picked from commit 7c6a33a)
2016-01-14 19:24:25 +03:00
Nikolay Krasko
7ffda5d985 Bootstrap against beta5 and temporary disable auto-increment 2016-01-14 17:24:16 +03:00
Mikhail Glukhikh
c40227d93f Implicit exhaustive whens now have exception in else branch #KT-8700 Fixed
(cherry picked from commit 7d6ccc4)
2016-01-14 16:30:31 +03:00
Mikhail Glukhikh
6b411b900e Implicit exhaustive when check for definite variable initialization (KT-8700)
(cherry picked from commit 011a9f2)
2016-01-14 16:30:28 +03:00
Mikhail Glukhikh
95cad01d97 ControlFlowInfo introduced to store variable states, related refactoring
(cherry picked from commit 52c3fb0)
2016-01-14 16:30:24 +03:00
Mikhail Glukhikh
0893dafab3 InitState / VariableUseState / VariableControlFlowState moved to a separate file
(cherry picked from commit 0f3997c)
2016-01-14 16:30:20 +03:00
Mikhail Glukhikh
118b619da3 PseudocodeVariablesData converted to Kotlin
(cherry picked from commit 4c4456c)
2016-01-14 16:30:16 +03:00
Mikhail Glukhikh
195bbfe1ba PseudocodeVariablesData.java --> PseudocodeVariablesData.kt
(cherry picked from commit 7179b37)
2016-01-14 16:30:12 +03:00
Mikhail Glukhikh
8dd3f438d8 Exhaustive whens without else and 'Nothing' as the result are considered 'implicit exhaustive'
(cherry picked from commit b938949)
2016-01-14 16:30:08 +03:00
Mikhail Glukhikh
741cdbe0a3 Introduced binding context storage for implicit exhaustive when (KT-8700)
(cherry picked from commit d62d7dd)
2016-01-14 16:30:04 +03:00
Mikhail Glukhikh
94b39326de CFG exhaustive when else instruction for KT-8700
(cherry picked from commit b805ce0)
2016-01-14 16:30:00 +03:00
Mikhail Glukhikh
c3432df3c8 Implemented missed checks for local functions #KT-10449 Fixed
Relevant code/test fixes
(cherry picked from commit 99a32b9)
2016-01-14 16:29:56 +03:00
Mikhail Glukhikh
c5a84077f0 Implicit callable type check refactoring, additional check for property with explicit Nothing type
(cherry picked from commit 15746cb)
2016-01-14 16:29:52 +03:00
Mikhail Glukhikh
7f36a3ea3a Intersection types are no more allowed in signatures #KT-10244 Fixed
(cherry picked from commit 6b8b39a)
2016-01-14 16:29:48 +03:00
Denis Zharkov
edf7200e5d Adjust type approximation to broken code and missing dependencies
- Do not run approximation if arguments number is different
- Add nullable Any? as supertype to MissingDependencyErrorClass

The latter is needed because otherwise TypeArgument.isConsistent became false
2016-01-14 15:38:07 +03:00
Denis Zharkov
8bf0f32b18 Fix supertypes calculation for types with projections
Use captured types as replacement for non top-level entries

 #KT-7296 Fixed
2016-01-14 15:38:06 +03:00
Denis Zharkov
9d08d51377 Fix captured approximation for case of flexible types
#KT-9294 Fixed
2016-01-14 15:38:05 +03:00
Denis Zharkov
fb09160d87 Make project compilable after member scope refinement 2016-01-14 15:38:05 +03:00
Denis Zharkov
30796c5dd2 Replace type entries of JsContext<*> with JsContext<JsNode>
It's needed to make method calls (e.g. replaceMe) on it typesafe,
otherwise it's value parameter type is subtype of captured
2016-01-14 15:38:04 +03:00
Denis Zharkov
69ba93fa16 Refine type from property setter parameter on assignment
In most cases these types are equals, the only known exception is
var-property contained in projected type member scope (see test data)
2016-01-14 15:38:04 +03:00
Denis Zharkov
bc06c0b264 Refine member scope for types with projections
Instead of erasing descriptors with conflicting substitution,
use invariant CapturedType(<projection>) as replacement for type parameter
within default member scope.

After substitution leave such types 'as is' everywhere except return types,
use common approximation for them.

 #KT-9294 In Progress
 #KT-5411 Fixed
 #KT-8647 Fixed

 #KT-9462 Fixed
 #KT-9893 Fixed
 #KT-7581 Fixed
 #KT-7296 In Progress
2016-01-14 15:38:03 +03:00
Denis Zharkov
009794dfd2 Extract and normalize member scope calculation
Basically it's wrong to use original types' member scope
as a worker for SubstitutionScope.
Member scope should always be determined by type constructor's default one
and substitution/arguments

 #KT-10448 Fixed
2016-01-14 15:38:00 +03:00
Denis Zharkov
cbaf84754c Minor. Add tests checking not-null assertions
More precisely these tests check cases when expected type
was somehow obtained from captured type (in member scope with projections)
2016-01-14 15:35:51 +03:00
Denis Zharkov
14d3208b7a Introduce CustomSubstitutionCapability.substitutionToComposeWith
Mainly it's needed to prevent creation of subsituions composition
everytime we replacing arguments, because it's both unoptimal and wrong

When replace arguments in `A<E, F>` with <String, E> you got `A<String, String>`
as a result, that is unexpected.

But composition is only needed when previous substituion was abnormal
(e.g. RawSubsitution that should actually wrap new arguments), see RawTypes tests
2016-01-14 15:35:51 +03:00
Denis Zharkov
9cfc11d0df Preserve type capabilities of captured type 2016-01-14 15:35:50 +03:00
Denis Zharkov
499ddeec82 Minor. Cleanup code 2016-01-14 15:35:50 +03:00
Denis Zharkov
63508c8e66 Minor. Move declaration closer to usages and optimize imports 2016-01-14 15:35:49 +03:00
Denis Zharkov
0e5b1ed884 Replace unchecked 'is' on local class with unchecked 'as'
It became unchecked after latest changes (see parent commit)
2016-01-14 15:35:48 +03:00
Denis Zharkov
8469003416 Fix type parameter list for local classes
Add captured parameters from enclosing functions

 #KT-9584 Fixed
2016-01-14 15:35:48 +03:00
Denis Zharkov
fb0e6c758d Clean project code after #KT-3996 fix
No overload resolution ambiguity in smart-casts
2016-01-14 15:35:47 +03:00
Denis Zharkov
7166b69c5f Fix wrong contract assumption
Currently SamAdapterOverridabilityCondition can be called
even for incompatible descriptors

 #KT-10486 Fixed
2016-01-14 15:35:47 +03:00
Nikolay Krasko
53f92f35d4 Remove assert that isn't valid in UpSource (UP-5742) 2016-01-12 21:41:54 +03:00
Michael Bogdanov
b4840bddc5 Always generate ACC_SUPER flag for all classes; Fix for KT-10260: java.lang.VerifyError in Android 4.x when Instant Run is used
#KT-10260 Fixed
(cherry picked from commit 0274ce4)
2016-01-11 13:02:34 +03:00
Pavel V. Talanov
3b253d10f3 Fix a problem caused by getting project using an invalid psi element 2015-12-23 16:47:40 +03:00
Yan Zhulanow
19c3382a19 Always compile Android projects without JDK in classpath #KT-10479 2015-12-23 16:43:47 +03:00
Dmitry Petrov
65a1c7b040 Fix KT-10472: compare all overloads including varargs in a single pass. 2015-12-22 17:10:55 +03:00
Stanislav Erokhin
0cffd955ea Hack for unavailable archive.apache.org: use bintray.com instead
(cherry picked from commit de6f520)
2015-12-22 16:47:43 +03:00
Nikolay Krasko
3847dd9794 Make add test lib quick-fix applicable only when there is unresolved import 2015-12-22 16:24:08 +03:00
Nikolay Krasko
bc5911e64b Add library for Gradle 2015-12-22 16:24:07 +03:00
Nikolay Krasko
6f96192e2f Determine maven library version from kotlin-stdlib 2015-12-22 16:24:07 +03:00
Nikolay Krasko
9f378345fc Add libraries to maven 2015-12-22 16:24:07 +03:00
Nikolay Krasko
760052b917 Add kotlin-test.jar to classpath quickfix 2015-12-22 16:24:07 +03:00
Sergey Mashkov
035fe187c1 kotlin-test: exclude OnlyInpuType from dist kotlin-test as well 2015-12-21 15:50:46 +03:00
Sergey Mashkov
e1a0caa27b kotlin-test: exclude OnlyInputTypes annotation from jar 2015-12-21 15:50:38 +03:00
Sergey Mashkov
e0061f5f37 rename kotlin.test to kotlin-test 2015-12-21 15:50:27 +03:00
Nikolay Krasko
128ddd5237 Enable version auto-increment and bootstrapping 2015-12-21 13:52:18 +03:00
Dmitry Petrov
b8094b2073 Prohibit functions (and constructors) with multiple vararg parameters.
(cherry picked from commit fab072e)
2015-12-21 13:28:27 +03:00
Andrey Breslav
e3924564ed Reserve "async* {}", extend the quick-fix 2015-12-21 07:07:15 +03:00
Andrey Breslav
3bb8d69760 Minor. Additional test for "async {}" 2015-12-21 07:07:15 +03:00
Stanislav Erokhin
c926c135ca Completion fix for reserved 'async' syntax 2015-12-21 07:07:15 +03:00
Nikolay Krasko
8714672ced Quick fix for deprecated async syntax 2015-12-21 07:07:15 +03:00
Ilya Gorbunov
bbc8941d76 Deprecate IndexingIterable and IndexingIterator and provide Iterator.withIndex() instead of the latter. 2015-12-19 09:58:28 +03:00
Ilya Gorbunov
2a18ab2d76 Deprecate some top-level constants to make 'em private later. 2015-12-19 09:58:26 +03:00
Ilya Chernikov
280c41a64d Working around cancellation-related exception in case of different versions of daemon and client 2015-12-18 22:20:59 +01:00
Stanislav Erokhin
9e986db840 Minor. run generate tests 2015-12-18 22:54:05 +03:00
Stanislav Erokhin
bcaa755c4e Fix compilation.
- rename isFinal extension property to avoid ambiguity with synthetic property in DeserializedClassTypeConstructor
- add explicit parameter to lambda File.listFiles
- return true from lambda Query.forEach
2015-12-18 22:49:26 +03:00
Stanislav Erokhin
1574dc78df Synthetic extensions wins against top-level extension. 2015-12-18 22:49:25 +03:00
Stanislav Erokhin
e8a697cb6d Removed methods about synthetic from ImportingScope. 2015-12-18 22:49:24 +03:00
Stanislav Erokhin
fe9cbd982d Extract SyntheticScopes to injection component 2015-12-18 22:49:23 +03:00
Sergey Mashkov
3b08e5e547 kotlin-test: rename projects to eliminate possible mess 2015-12-18 22:17:48 +03:00
Sergey Mashkov
a97e623d04 kotlin-test: binary compatibility for fail function 2015-12-18 22:17:48 +03:00
Sergey Mashkov
f21b6a4777 Ant task to copy dist as a bootstrap compiler 2015-12-18 22:17:47 +03:00
Sergey Mashkov
fe4f51617c Add kotlin.test dependency to kotlin-compiler-embeddable 2015-12-18 22:17:47 +03:00
Sergey Mashkov
790524e391 Add library kotlin-test to IDEA project 2015-12-18 22:17:47 +03:00
Sergey Mashkov
f1783530ac Replace test assertions in the prod code with require 2015-12-18 22:17:47 +03:00
Sergey Mashkov
e25d31618c Fix tests 2015-12-18 22:16:04 +03:00
Sergey Mashkov
b57d2ff702 Add kotlin.test library to build distribution and provide for tests 2015-12-18 22:16:04 +03:00
Sergey Mashkov
7aae2bd452 kotlin-test: Remove javaClass as is in runtime now 2015-12-18 22:16:04 +03:00
Sergey Mashkov
a5b098c4a7 kotlin.test: Rename jvm module to junit 2015-12-18 22:16:04 +03:00
Sergey Mashkov
149ce70ce2 Move testing from stdlib to js.stdlib 2015-12-18 22:16:04 +03:00
Sergey Mashkov
1867abbbe7 Add kotlin.test library 2015-12-18 22:16:04 +03:00
Sergey Mashkov
dd36ef5712 Remove kunit 2015-12-18 22:16:04 +03:00
Andrey Breslav
6155d836a5 'async' reserved in front of function literals 2015-12-18 21:20:54 +03:00
Andrey Breslav
75ab0dd509 'sealed' reserved in front of when 2015-12-18 21:20:54 +03:00
Andrey Breslav
c36eeadab1 Minor. Constant used instead of constructor 2015-12-18 21:20:54 +03:00
Dmitry Petrov
09f53ea0bb Select most specific overloaded function/property by explicitly used arguments only.
Major rewrite of OverloadingConflictResolver.
2015-12-18 18:30:16 +03:00
Dmitry Petrov
52f0e0bc93 J2K: OverloadingConflictResolver.kt - convert to Kotlin 2015-12-18 18:30:16 +03:00
Dmitry Petrov
ca6153e8f1 J2K: OverloadingConflictResolver.kt 2015-12-18 18:30:16 +03:00
Ilya Gorbunov
03816373b3 Primitive array constructor-like functions with init lambda.
#KT-8831

Update testData and resolve ambiguity in newArray test
2015-12-18 17:54:09 +03:00
Natalia Ukhorskaya
513c4a4562 J2K: transform loops with double, float and char range with while
#KT-899 Fixed
2015-12-18 16:14:17 +03:00
Natalia Ukhorskaya
ecdef71580 J2K: cast right operand of equals for primitive types to left operand type
#KT-9997 Fixed
2015-12-18 16:14:16 +03:00
Natalia Ukhorskaya
1d787ed222 J2K: Insert initializer type for properties with primitive type if necessary 2015-12-18 16:14:15 +03:00
Ilya Gorbunov
188119aa83 Prepare to treat keys mapped to null same way as missing keys in Map extensions: getOrElse, getOrPut, getOrImplicitDefault. 2015-12-18 15:24:03 +03:00
Stanislav Erokhin
8b5a194dd6 Do not discriminate synthesized candidates.
#KT-9965 Fixed
2015-12-18 15:08:19 +03:00
Stanislav Erokhin
1b6f96ac2b Minor. update diagnostics/ReadMe.md 2015-12-18 15:08:18 +03:00
Alexey Sedunov
2fb3c727a7 Misc: Cleanup "org.jetbrains.kotlin.idea.intentions" package 2015-12-18 15:05:48 +03:00
Alexey Sedunov
3fca8f765c Misc: Cleanup "org.jetbrains.kotlin.idea.quickfix" package 2015-12-18 15:05:46 +03:00
Alexey Sedunov
ad55c8fb96 Misc: Cleanup "org.jetbrains.kotlin.idea.refactoring" package 2015-12-18 15:05:43 +03:00
Alexey Sedunov
f745f27694 Change Signature: Check syntactic validity of types. Warn about unresolved types 2015-12-18 15:05:40 +03:00
Alexey Sedunov
784b250de8 Change Signature: Fix rendering of unresolved types in overriding members 2015-12-18 15:05:39 +03:00
Alexey Sedunov
05ec9cc424 Initialize Property in Constructor Quick-Fix: Disable clearing of ShortenReferences waiting set 2015-12-18 15:05:37 +03:00
Alexey Sedunov
fd79145b73 Change Signature: Represent parameter/receiver types using KotlinTypeInfo 2015-12-18 15:05:36 +03:00
Alexey Sedunov
e558581667 Change Signature: Represent return type using KotlinTypeInfo 2015-12-18 15:05:34 +03:00
Alexey Sedunov
24951e8a38 J2K: KtTypeCodeFragment.java 2015-12-18 15:05:33 +03:00
Alexey Sedunov
6fe48243c7 J2K: KtTypeCodeFragment.java (rename to .kt) 2015-12-18 15:05:31 +03:00
Alexey Sedunov
594ad27952 Change Signature: Implement proper resolution of type code fragments
#KT-9210 Fixed
2015-12-18 15:05:29 +03:00
Alexey Sedunov
cfe1c44260 Introduce Variable: Add type argument to initializer if they can't be inferred from the context
#KT-5466 Fixed
2015-12-18 15:05:27 +03:00
Alexey Sedunov
ea8da18338 Inline Variable: Highlight usages in current file even if the variable is used in other files 2015-12-18 15:05:24 +03:00
Alexey Sedunov
4e36edb5d6 Inline Variable: Remove invalid imports and perform reference lengthening/shortening when inlining non-local declaration
#KT-8884 Fixed
2015-12-18 15:05:23 +03:00
Michael Bogdanov
44bdac6e11 Added file name to exception on indexing file mappings 2015-12-18 14:25:46 +03:00
Ilya Gorbunov
055c71e8d0 Provide minWith and maxWith to find maximum and minimum values according to the given comparator.
#KT-9002 Fixed
2015-12-18 00:00:52 +03:00
Ilya Gorbunov
b5e637bed5 Rename toMap with selector and transform to toMapBy 2015-12-17 22:50:44 +03:00
Ilya Gorbunov
544bc9a70c Introduce toMap with key-value pair selector.
#KT-6657
2015-12-17 22:50:43 +03:00
Ilya Gorbunov
2966420d24 Harden deprecation level for synchronized helper functions.
Make migration helper classes deprecated-hidden, although it doesn't affect anything.
2015-12-17 22:48:13 +03:00
Stanislav Erokhin
7521b89b3e Resolve unaryPlus as plus with error. 2015-12-17 20:21:01 +03:00
Denis Zharkov
1a6f9b8d1c Do not build inner type for error classes
#KT-10409 Fixed
2015-12-17 19:56:38 +03:00
Denis Zharkov
0d7c8635b3 Refine INSTANCE_ACCESS_BEFORE_SUPER_CALL check
- Detect usages of unitialized `this` as extension receiver argument
- Make it work within object literal created before super call

 #KT-9120 Fixed
 #KT-8289 Fixed
2015-12-17 19:56:38 +03:00
Zalim Bashorov
ba180f915a Minor: uncomment code fragments in ic tests which already should work 2015-12-17 19:41:25 +03:00
Zalim Bashorov
d9b67ae0ef Minor: use ".touch" extension instead of ".new" in incremental compilation tests when it possible 2015-12-17 19:41:24 +03:00
Mikhail Glukhikh
fe57a9e48f Setter visibility must be worse or the same as property visibility 2015-12-17 19:03:06 +03:00
Mikhail Glukhikh
f5989aa4f2 CallableMemberDescriptor.isOverridable / ClassDescriptor.isFinal refactoring
Extra JvmField and integer constants tests
2015-12-17 18:11:41 +03:00
Mikhail Glukhikh
91621704a2 Additional information to catch EA-75872 2015-12-17 17:30:30 +03:00
Evgeny Gerashchenko
16f482f723 Merge pull request #797 from JetBrains/rr/kt8365
KT-8365 Bogus "Receiver never used" warning when receiver is used in invoke() convention call
2015-12-17 17:38:24 +04:00
Alexey Tsvetkov
7384d25cb3 Prohibit Array<Nothing> 2015-12-17 16:26:26 +03:00
Mikhail Glukhikh
35f788a89c INAPPLICABLE_FIELD_TARGET_NO_BACKING_FIELD deleted (not necessary already) 2015-12-17 15:07:07 +03:00
Mikhail Glukhikh
3fb04aceb9 Check backing field availability for AnnotationTarget.FIELD #KT-10387 Fixed
Some duplicated checks deleted (UseSiteTargetChecker / JvmFieldApplicabilityChecker)
2015-12-17 15:06:58 +03:00
Mikhail Glukhikh
f55574df36 Code fix: TestOnly on a property without backing field 2015-12-17 15:06:51 +03:00
Michael Bogdanov
ca9e8fc5a7 Fix for KT-5910: Can't call Throwable() in Kotlin
#KT-5910 Fixed
2015-12-17 14:09:15 +03:00
Natalia Ukhorskaya
d40e9ffc13 Do not convert anonymous object to lambda if its function is recursive
#KT-10348 Fixed
2015-12-17 13:39:36 +03:00
Evgeny Gerashchenko
9aa38d99fb KT-8365 Bogus "Receiver never used" warning when receiver is used in invoke() convention call
#KT-8365 fixed
2015-12-17 13:31:43 +03:00
Evgeny Gerashchenko
2e6d82a72b Minor. Green code. 2015-12-17 13:06:27 +03:00
Natalia Ukhorskaya
43476bd773 Do not drop negation if resulting type isn't boolean 2015-12-17 11:11:33 +03:00
Natalia Ukhorskaya
f84b3414c8 Remove outdated test: generic property should have a receiver 2015-12-17 11:11:32 +03:00
Natalia Ukhorskaya
4b1edf7bb0 Intention tests: add directive to skip errors before 2015-12-17 11:11:31 +03:00
Natalia Ukhorskaya
7e6495618b ChangeVariableMutability: diagnostic can be reported on constructor parameter
#KT-10416 Fixed
2015-12-17 11:11:31 +03:00
Natalia Ukhorskaya
fc7c45d4d0 NegatedExpressionWithDemorgansLaw may produce code with error 2015-12-17 11:11:30 +03:00
Natalia Ukhorskaya
7f0065c806 Fix OperatorToFunctionIntention: insert function literal expressions to arguments correctly 2015-12-17 11:11:29 +03:00
Natalia Ukhorskaya
6bfbec8c88 ConvertAssertToIf may produce code with error
// TODO: we could generate anonymous function instead of lambda expression when there is a return
2015-12-17 11:11:28 +03:00
Natalia Ukhorskaya
ce3d53d2ee Intention tests: add operator modifier in some tests 2015-12-17 11:11:27 +03:00
Natalia Ukhorskaya
2c29f6f5ab ConvertIfWithThrowToAssertIntention: generate assert with lazy argument 2015-12-17 11:11:26 +03:00
Natalia Ukhorskaya
2dc1ba1d62 Intention 'remove explicit lambda parameter' may break code, do not check error in tests for it 2015-12-17 11:11:26 +03:00
Natalia Ukhorskaya
269676ee2e Intention tests: skip errors check for tests that fix some error 2015-12-17 11:11:25 +03:00
Natalia Ukhorskaya
abd7ed5c70 Fix intention for when: insert '||' instead of ',' 2015-12-17 11:11:24 +03:00
Natalia Ukhorskaya
6a3ac66208 Intention tests: add runtime where necessary 2015-12-17 11:11:23 +03:00
Natalia Ukhorskaya
78d737f3f4 Check errors in Intentions tests by default 2015-12-17 11:11:22 +03:00
Natalia Ukhorskaya
cc259c2d15 Intention convert object literal to lambda should add parameters if there are more than one 2015-12-17 11:11:22 +03:00
Natalia Ukhorskaya
5e231db631 J2K: convert method from Map (Java8) with cast to java.util.Map
#KT-10400 Fixed
2015-12-17 11:11:21 +03:00
Natalia Ukhorskaya
3f7b8554dd J2K: parenthesize receiver if needed
#KT-10121 Fixed
2015-12-17 11:11:20 +03:00
Natalia Ukhorskaya
a520e93b5b J2K: don't automatically convert Java code when pasting to a string literal in Kotlin
#KT-7759 Fixed
2015-12-17 11:11:19 +03:00
Natalia Ukhorskaya
f3a6c541ec J2K: Convert usages of kotlin functions from library correctly
#KT-6115 Fixed
2015-12-17 11:11:18 +03:00
Natalia Ukhorskaya
693e158759 Intention to convert anonymous function to lambda 2015-12-17 11:11:18 +03:00
Natalia Ukhorskaya
c79ffbac5c Run code cleanup on j2k module 2015-12-17 11:11:16 +03:00
Natalia Ukhorskaya
a983e6cf60 J2K: Do not convert string literal with escaped symbols automaticaly during java to kotlin conversion
#KT-9942 Fixed
2015-12-17 11:11:16 +03:00
Natalia Ukhorskaya
68101eeffa J2K: do not drop formatting for expressions with operator 2015-12-17 11:11:15 +03:00
Natalia Ukhorskaya
293b8eeda8 Minor: fix IDEA(win) run configuration 2015-12-17 11:11:14 +03:00
Michael Bogdanov
7a1d789e9a Added InliningLambdaContext 2015-12-17 09:52:28 +03:00
Michael Bogdanov
ebbc68dfae isInlineFunction renamed to isInlineMethodContext 2015-12-17 09:52:27 +03:00
Michael Bogdanov
9cad1a912a Choose proper context for accessor generation: skip inline ones; Fix for KT-6102: Bypass synthetic accessor when inlining lambda which calls private member
#KT-6102 Fixed
2015-12-17 09:51:41 +03:00
Michael Bogdanov
033698c51d Added crossinline field to MethodContext 2015-12-17 09:50:54 +03:00
Michael Bogdanov
b0a7706812 Test for obsolete KT-5445: Bad access to protected data in getfield
#KT-5445 Obsolete
2015-12-17 09:50:39 +03:00
Dmitry Jemerov
179498d971 UI for enabling EAP channel for plugin updates 2015-12-16 19:59:56 +01:00
Alexey Tsvetkov
5330248f6e Add checkbox for experimental incremental compilation; Make simple incremental compilation on by default 2015-12-16 21:52:39 +03:00
Alexander Udalov
0ba0ea5e1f Report 'unsupported' on synthetic Java property references
#KT-8575 Open
2015-12-16 19:50:15 +03:00
Alexander Udalov
dc84445e2e Inherit KProperty interfaces from function types
To be able to write the following: listOfStrings.map(String::length)
2015-12-16 19:48:28 +03:00
Mikhail Glukhikh
f25f0db10e Fixed long / double / float value merge in OptimizationBasicInterpreter #KT-7401 Fixed 2015-12-16 17:45:38 +03:00
Stanislav Erokhin
75089a3af8 Revert "Project configuration: Add sources to kotlin-runtime library"
This is workaround for KT-10413.
This reverts commit 623ecd2503.
2015-12-16 12:53:56 +03:00
Stanislav Erokhin
c725ed47f5 Replaced ReceiverValue.NO_RECEIVER to null. 2015-12-15 23:09:20 +03:00
Stanislav Erokhin
3692318c38 Minor. Removed ReceiverValue.IRRELEVANT_RECEIVER. 2015-12-15 23:08:41 +03:00
Pavel V. Talanov
56cd29dff2 Increase file size limit of compiler to 20 (was 2.5) megabytes (compiler will not read files larger than that)
Current IDEA api makes it possible to increase that to a higher value only by passing system property on compiler startup
2015-12-15 20:24:11 +03:00
Pavel V. Talanov
8d5d1b7dcc LightClassUtil: files can no longer "belong to builtIns" 2015-12-15 20:22:14 +03:00
Pavel V. Talanov
bd9221beaa Minor, fix test data for KotlinGoToTest 2015-12-15 20:22:13 +03:00
Pavel V. Talanov
623ecd2503 Project configuration: Add sources to kotlin-runtime library 2015-12-15 20:22:12 +03:00
Pavel V. Talanov
ca38a50e1a Test data: fix test data for LineMarkerTest 2015-12-15 20:22:12 +03:00
Pavel V. Talanov
4fdc77f86f Minor, mark component functions as operator in test data for ReferenceResolveWithLibTest 2015-12-15 20:22:11 +03:00
Pavel V. Talanov
6a780f01bd Replace calls to QuickFixUtil.canModify by calls to canRefactor
Fix ChangeFunctionSignatureFix#isAvailable
2015-12-15 20:22:10 +03:00
Pavel V. Talanov
a667aa2f71 Tests: add runtime (and runtime sources) to some tests that rely on being able to resolve references to built ins 2015-12-15 20:22:09 +03:00
Pavel V. Talanov
539b84b561 Minor, stricter check for when deciding whether to build light class for decompiled declaration 2015-12-15 20:22:09 +03:00
Pavel V. Talanov
ddde372fad Upgrade BuiltInsReferenceResolverTest 2015-12-15 20:22:08 +03:00
Pavel V. Talanov
ef134ffb1b ProjectDescriptorWithStdlibSources includes source files for builtIns 2015-12-15 20:22:07 +03:00
Pavel V. Talanov
0099c10e4e Drop BuiltInsReferenceResolver 2015-12-15 20:22:07 +03:00
Pavel V. Talanov
3f0d71411e KtDecompiledFile: hack to be able to navigate to builtIns on jvm
Which sometimes are loaded differently than they are rendered (see BuiltInClassesAreSerializableOnJvm)
2015-12-15 20:22:06 +03:00
Pavel V. Talanov
b5568f9ace findDecompiledDeclaration: rewrite using stub indices 2015-12-15 20:22:05 +03:00
Pavel V. Talanov
7ccdbfd596 Minor, rename file 2015-12-15 20:22:04 +03:00
Pavel V. Talanov
01b79f640f DecompiledNavigationUtils -> findDecompiledDeclaration() 2015-12-15 20:22:04 +03:00
Pavel V. Talanov
d89b609960 J2K DecompiledNavigationUtils: rename file 2015-12-15 20:22:03 +03:00
Pavel V. Talanov
9ad6685310 J2K DecompiledNavigationUtils: autoconvert 2015-12-15 20:22:02 +03:00
Zalim Bashorov
976fbf32ba Minor: use List instead of Array as container in chained scopes 2015-12-15 20:07:37 +03:00
Zalim Bashorov
5008a66a5b ChainedScope -> ChainedMemberScope 2015-12-15 20:07:36 +03:00
Zalim Bashorov
674a15daa1 Disable test until KT-10405 not fixed 2015-12-15 20:07:35 +03:00
Zalim Bashorov
8fa2e28729 Add usages of inherited static members from nested object 2015-12-15 20:07:33 +03:00
Zalim Bashorov
e201268f46 Remove unnecessary scopes 2015-12-15 19:41:18 +03:00
Zalim Bashorov
8c4deb80e5 Extract to property path to js.stdlib output dir and fix statistics for generated js files 2015-12-15 19:41:17 +03:00
Zalim Bashorov
0b6e100aff Fix compilation 2015-12-15 19:41:16 +03:00
Zalim Bashorov
51a8d5b9f0 Allow to use static members from companion object's parents 2015-12-15 19:41:15 +03:00
Zalim Bashorov
69c2668530 Don't allow to use own members when resolve super constructor call in (companion) object 2015-12-15 19:41:14 +03:00
Zalim Bashorov
e9ea4cc953 Don't allow to use own nested classes when resolve header of (companion) object 2015-12-15 19:41:13 +03:00
Zalim Bashorov
38522f60ea Minor: add helper function createLazyValue with onRecursion 2015-12-15 19:41:12 +03:00
Denis Zharkov
7756644eb1 Introduce KClass<T>.javaPrimitiveType and KClass<T>.javaObjectType
#KT-6319 Fixed
2015-12-15 16:18:31 +03:00
Denis Zharkov
154657a374 Fix wildcards for invariant arguments
See test with Java, we want preserve the invariant that if return type and
value parameter types are same in Kotlin, than we can use such return-value
as argument for that parameter
2015-12-15 16:18:31 +03:00
Denis Zharkov
5df2a58003 Minor. Adjust generic parameter naming 2015-12-15 16:18:31 +03:00
Denis Zharkov
b4bb92d136 Fix overload resolution ambiguity for types intersection
There are two different forms of types intestion:
1. Type parameters with multiple bounds
2. Smart casts

The problem was that when member scope of type intersection contained
effective duplicates and that lead to overload resolution ambiguity in
strange cases like `x.hashCode()`

For first type we do effectively the same thing as when building member
scope for class extending several interfaces: group all descriptors by
both-way-overridability relation and then choose most-specific in each
group.

For smart casts we do basically the same thing but with special
treatments:
1. From all descriptors that _equal_ to most specific we choose
   the one that works without smartcast if possible (i.e. we choose first from candidates list)
2. If smart-cast value seems to be unstable we use only member scope
   of receiver type + all descriptors from smart cast possible types
   that has incompatible signature. If we'd include all of them and
   choose one as more specific, and it would lead to false
   SMART_CAST_IMPOSIBLE (see test unstableSmartCast.kt)

 #KT-3996 Fixed
 #KT-10315 Fixed
2015-12-15 16:18:31 +03:00
Denis Zharkov
8d0c3281cd Choose first non-flexible when selecting most specific 2015-12-15 16:18:31 +03:00
Dmitry Petrov
02311538d6 Refactor createAntBindFakeOverride.
Drop unneeded helper functions from overridingUtils.kt
2015-12-15 16:18:30 +03:00
Ilya Gorbunov
19a6cc74de Build Markdown from sources tagged with forKotlin tag 2015-12-15 16:08:55 +03:00
Dmitry Jemerov
c83b6ed3a5 Inspection for migrating Kotlin stdlib API usages in Java code 2015-12-15 12:45:40 +01:00
Alexey Sedunov
3dfb9d2e5e Inline Variable: Move string template processing to InlineValHandler as it violates contract of the PsiElement.replace() 2015-12-15 13:31:35 +03:00
Alexey Sedunov
b5fad71b18 Inline Variable: Warn about non-Kotlin usages
#KT-8885 Fixed
2015-12-15 13:31:34 +03:00
Alexey Sedunov
ffb382e3bc PSI: Delete succeeding semicolon along with KtElement
#KT-5487 Fixed
2015-12-15 13:31:33 +03:00
Alexey Sedunov
d0b9b6a3b4 Introduce Parameter: Support conversion of local variables
#KT-9170 Fixed
2015-12-15 13:31:32 +03:00
Alexey Sedunov
fff011f60a Unit Test Tooling: Fix order of test method generation actions
#KT-9740 Fixed
2015-12-15 13:31:31 +03:00
Alexey Sedunov
258a6328a8 Pull Up: Default to "Make abstract" when moving to interface
#KT-9832 Fixed
2015-12-15 13:31:29 +03:00
Alexey Sedunov
04c6ea78c7 Name Suggester: Allow any Kotlin identifier in suggested names
#KT-10332 Fixed
2015-12-15 13:31:28 +03:00
Alexey Sedunov
ee9eb55b59 Extract Function: Fix NPE on parameter disabling. Fix parameter swapping 2015-12-15 13:31:27 +03:00
Mikhail Glukhikh
49e7417741 "as" in binary / unary expressions now checked only for original type conversion #KT-10384 Fixed
Also #KT-10386 Fixed
2015-12-15 12:02:33 +03:00
Mikhail Glukhikh
233e8e58e8 Code cleanup: get rid of unnecessary !! / as, fake warning comments and issues 2015-12-15 12:00:58 +03:00
Ilya Gorbunov
4ffd60cf52 Correct deprecation messages. 2015-12-14 21:07:33 +03:00
Ilya Gorbunov
43ce8222fc Soften deprecation level to ease migrations. 2015-12-14 21:05:13 +03:00
Pavel V. Talanov
46798ed845 Module configuration: 'idea-completion' depends on 'idea' at runtime
So that plugin.xml is in classpath when running completion tests separately
2015-12-14 17:35:17 +03:00
Stanislav Erokhin
cd80d9408d Extension function wins against function with no receiver 2015-12-14 16:49:29 +03:00
Dmitry Jemerov
a7503303d5 diagnostics for EA-73611 2015-12-14 13:28:45 +01:00
Mikhail Glukhikh
d2fce9b16d CFA classes rename: remove 'Kotlin' prefix 2015-12-14 15:25:43 +03:00
Dmitry Jemerov
8db3fb03f9 remove support for "package.foo.bar" syntax inside files 2015-12-14 13:22:54 +01:00
Mikhail Glukhikh
19084b8182 Additional codegen test for KT-10107 2015-12-14 12:52:43 +03:00
Mikhail Glukhikh
fdc9e9d7f5 Delegated properties never require backing field #KT-10107 Fixed 2015-12-14 12:26:37 +03:00
Ilya Gorbunov
9d753f24b7 Do not create regex to split path by directory separator char. 2015-12-14 06:31:44 +03:00
Ilya Gorbunov
a4f82a2dc4 Sensible behavior for File.startsWith and File.endsWith 2015-12-14 06:10:26 +03:00
Ilya Gorbunov
d2e22dc794 Fix tests on linux.
Add tests for File.startsWith
2015-12-14 06:10:24 +03:00
Ilya Gorbunov
645c78e2f4 Do not use assert in test, use assertTrue or assertEquals 2015-12-14 06:10:22 +03:00
Ilya Gorbunov
cb71e05c51 Deprecate File.directory, root, rootName as properties with unclear behavior. 2015-12-14 06:10:21 +03:00
Ilya Gorbunov
7c9b53c75c Do not convert separatorsToSystem in file path extensions.
Do not require network host in network share root to contain dot.
File.root now is always non-null to be consistent with File.toComponents().root.
Introduce invariantSeparatorsPath property.
Deprecate relativeTo to make it return File later. Introduce toRelativeString instead.
Introduce relativeToOrNull and relativeToOrSelf extensions.
2015-12-14 06:10:18 +03:00
Ilya Gorbunov
52eb9e4276 Refactor FilePathComponents: rename properties, deprecate constructor, rename filePathComponents extension. 2015-12-14 06:09:55 +03:00
Ilya Gorbunov
8deefd56db Rename FileTreeWalk public parameters and builder methods.
Directory filtering now is performed in newly introduced onEnter predicate.
2015-12-14 05:16:06 +03:00
Ilya Gorbunov
e24dbcefb6 Move all mutable state from FileTreeWalk to its iterator implementation, allowing this sequence to be iterated several times.
Introduce SingleFileState for single file walks.
Do not check isDirectory in DirectoryState constructor unless assertions are enabled.
2015-12-14 05:16:04 +03:00
Ilya Gorbunov
061803d7b1 Compare root of FilePathComponents according to case-sensitivity rules of current file system. 2015-12-14 05:16:02 +03:00
Ilya Gorbunov
4f2887df64 FileTreeWalk tests: do not remove failed directory from stack as leave is also called on failed dirs. 2015-12-14 05:16:01 +03:00
Ilya Gorbunov
162b152133 Improve File.relativeTo handling relative paths. Paths are normalized before calculating relative path. "x".relativeTo("../y") now is considered to have incompatible roots. 2015-12-14 05:15:59 +03:00
Ilya Gorbunov
9f5a972816 Improve resolve and resolveSibling for relative paths. 2015-12-14 05:15:57 +03:00
Ilya Gorbunov
923effe11d Change FilePathComponents parsing for file with empty name to enhance finding relative path between relative paths. 2015-12-14 05:15:55 +03:00
Ilya Gorbunov
6301c707cd Ensure resolveTo fails as expected.
Change UNC paths not to be misinterpreted on *nix.
2015-12-14 05:15:53 +03:00
Ilya Gorbunov
c23c2dbe85 FileTreeWalk: correct usage not to filter out subdirectories 2015-12-14 05:15:52 +03:00
Ilya Gorbunov
515d2cd3e7 FileTreeWalk.filter was dropped, use treeFilter otherwise filtering result becomes different.
Refactor walking tests.
2015-12-14 05:15:50 +03:00
Ilya Gorbunov
27551a8399 Make some io test classes non-nested as it's not supported by runners. 2015-12-14 05:15:48 +03:00
Ilya Gorbunov
33967a09f6 Unify minBy and maxBy for Maps with other families. 2015-12-14 04:56:47 +03:00
Ilya Gorbunov
33b366b9b9 Relax upper bound of T for minBy and maxBy to be nullable.
Swap type parameters of minBy and maxBy.
#KT-10099 Fixed
2015-12-14 04:56:45 +03:00
Ilya Gorbunov
58e93d5e1b Update testData for LoadBuiltinsTest and BuiltInDecompilerTest 2015-12-14 04:29:28 +03:00
Ilya Gorbunov
bf9d50ccc4 Fix testData for LookupTracker 2015-12-14 04:29:27 +03:00
Ilya Gorbunov
59a9e2549c Fix tests: codegen, completion, decompiler consistency, quickdoc, intentions, navigation, reference resolver, quick fixes 2015-12-14 04:29:25 +03:00
Ilya Gorbunov
f55b421853 Partially support default imports when analyzing ReplaceWith annotation pattern. 2015-12-14 04:29:23 +03:00
Ilya Gorbunov
d296d91272 Fix fq-names of top-level extensions in intentions. 2015-12-14 04:29:21 +03:00
Ilya Gorbunov
5df94da216 Fix fq-name of listOf in extract function. 2015-12-14 04:29:20 +03:00
Ilya Gorbunov
4dde59368c Fix tests not to duplicate array constructor definitions as they are available now in builtins. 2015-12-14 04:29:18 +03:00
Ilya Gorbunov
f509937037 Move array constructors to builtins module back to kotlin package. 2015-12-14 04:29:11 +03:00
Ilya Gorbunov
5aff07561d Move jvm annotations and class mapping intrinsics to runtime.jvm module to kotlin.jvm package.
Make annotationClass to be a property.
Deprecate with error javaClass property on KClass<T>
2015-12-14 03:51:07 +03:00
Ilya Gorbunov
feff5b2327 Stdlib generators: change values back to function. 2015-12-14 03:49:59 +03:00
Ilya Gorbunov
2d85c437cd Final moves: BigInteger and BigDecimal operations 2015-12-14 03:49:58 +03:00
Ilya Gorbunov
0ab33ab075 Final moves: map delegating accessors and timing utils, provide deprecated methods in the old place 2015-12-14 03:49:56 +03:00
Ilya Gorbunov
597f2c0a8c Final moves: map delegating accessors and timing utils 2015-12-14 03:49:55 +03:00
Ilya Gorbunov
16fbdcf107 For migration: provide deprecated classes inheriting multifile facade classes moved out of kotlin package. 2015-12-14 03:49:53 +03:00
Ilya Gorbunov
ae3135c770 For migration: Make an option "Xmultifile-facades-open" for compiler to generate open multifile facade classes. 2015-12-14 03:49:51 +03:00
Ilya Gorbunov
594d981094 Provide deprecated AbstractIterator in the old package kotlin.support. 2015-12-14 03:49:49 +03:00
Ilya Gorbunov
91b920f18e Move IndexedValue, IndexingIterable and IndexingIterator back to kotlin package 2015-12-14 03:49:48 +03:00
Ilya Gorbunov
871c5c66b4 Move code between packages (JS) 2015-12-14 03:49:46 +03:00
Ilya Gorbunov
dd2ae15531 Move code between packages. 2015-12-14 03:49:45 +03:00
Ilya Gorbunov
81e7826568 Move generated code between packages. 2015-12-14 03:49:43 +03:00
Alexander Udalov
477e25ae2f Remove Intrinsic annotation from *arrayOf functions 2015-12-14 03:49:41 +03:00
Ilya Gorbunov
09191622e5 Fix testData: import became not required. 2015-12-14 01:07:51 +03:00
Ilya Gorbunov
42565129ee Add packages kotlin.collections, kotlin.ranges, kotlin.sequences, and kotlin.text to default imports. 2015-12-14 01:07:49 +03:00
Alexander Udalov
65c5c99c68 Render decompiled annotations on enum entries 2015-12-13 17:49:44 +03:00
Alexander Udalov
6f347f351a Load annotations on compiled Kotlin enum entries
#KT-10339 Fixed
2015-12-13 03:52:42 +03:00
Alexander Udalov
3e2eb8c1a0 Serialize/deserialize annotations on enum entries
#KT-10338 Fixed
2015-12-13 03:52:41 +03:00
Alexander Udalov
5e421b4024 Improve type parameter bound diagnostic location
If there's only one erroneous bound (vast majority of cases), report it on the
bound; otherwise (to avoid reporting it several times) report on the type
parameter declaration
2015-12-13 02:06:07 +03:00
Michael Bogdanov
39d9b35e27 Force resolve companion in light class generation 2015-12-12 11:41:37 +03:00
Michael Bogdanov
a849f3f5d4 Fixed filtering error 2015-12-12 11:41:37 +03:00
Michael Bogdanov
4ad113d836 Removed redundant check 2015-12-12 11:41:36 +03:00
Michael Bogdanov
7c7786f7d0 Generate private methods in TraitImpl as private, don't generate delegation to private trait methods 2015-12-12 11:41:36 +03:00
Michael Bogdanov
a2d644f708 Fix for KT-9958: NoSuchMethodError when we call protected method from companion object
#KT-9958 Fixed
2015-12-12 11:41:35 +03:00
Michael Bogdanov
a7eea6e4dd Get rid of NeedSyntheticChecker 2015-12-12 11:41:35 +03:00
Denis Zharkov
b443f605ed Minor. Add load-java test checking that SamAdapterOverridabilityCondition is on 2015-12-11 22:41:03 +03:00
Denis Zharkov
871fe7680b Load special override as HIDDEN in case of signature clash
#KT-10151 Fixed
2015-12-11 22:41:03 +03:00
Denis Zharkov
45c0bc3610 Add 'subClassDescriptor' parameter to ExternalOverridabilityCondition 2015-12-11 22:41:03 +03:00
Denis Zharkov
417ff281ee Split getOverriddenBuiltinWithJvmDescriptor into two extensions 2015-12-11 22:41:02 +03:00
Mikhail Glukhikh
fe78f944a6 Private setter for open property: is now an error, not a warning 2015-12-11 18:54:40 +03:00
Mikhail Glukhikh
00504a3f6d Private setter for open property: take containing class modality into account #KT-10325 Fixed 2015-12-11 18:54:28 +03:00
Dmitry Jemerov
470dfc9bec remove "Jet" from names of classes related to resolve/scopes 2015-12-11 16:07:13 +01:00
Stanislav Erokhin
39b6637c7c Fix exception from InvokeProcessor when we get invoke from extension function type. 2015-12-11 17:01:04 +03:00
Stanislav Erokhin
616bb444ec Minor. strip explicit receiver for variable call if needed. 2015-12-11 17:01:03 +03:00
Stanislav Erokhin
1890b8cbd3 Removed InvokeOnExtensionFunctionWithExplicitReceiverFix 2015-12-11 17:01:03 +03:00
Stanislav Erokhin
dd24fd47f7 Update control flow test data for tower resolution algorithm
- locals win
- drop old invokeExtension convention
2015-12-11 17:01:02 +03:00
Stanislav Erokhin
79b30dddf9 Update lookupTracker test data for tower resolution algorithm 2015-12-11 17:01:02 +03:00
Alexander Udalov
239502368a Update test data for tower resolution algorithm
- locals win
- unary calls to plus/minus are not supported in favor of unaryPlus/unaryMinus
- unqualified nested classes are temporarily reported as unresolved
- function without receiver win against extension function
- explicit import win against star import
2015-12-11 17:01:02 +03:00
Stanislav Erokhin
66a031f7a0 Do not enter in recursion for implicit invoke on variable with un inferred type 2015-12-11 17:01:01 +03:00
Stanislav Erokhin
1dca49cecc Workaround for tower resolution algorithm in kotlin code. Will be investigated. 2015-12-11 17:01:01 +03:00
Stanislav Erokhin
cbe1ffed55 Use new tower resolution algorithm by default 2015-12-11 17:01:00 +03:00
Natalia Ukhorskaya
f699adda33 Stepping: skip methods deleting to static method call of DefaultImpl.
Support smart step into interface methods with implementation
 #KT-4803 Fixed
2015-12-11 16:21:05 +03:00
Natalia Ukhorskaya
ea8de883ac Implement 'Skip simple getters' for debugger 2015-12-11 16:21:04 +03:00
Michael Bogdanov
b950bf0e6e Fix for KT-10259: Proguard can't find generated lambda class of lambda nested inside object?.let lambda
#Fixed KT-10259
2015-12-11 16:14:59 +03:00
Michael Bogdanov
9452c200a0 Keep typeRemapper in inlining context instead of hashMap for transformed types 2015-12-11 16:14:58 +03:00
Mikhail Glukhikh
6fb871a088 A set of additional tests for complex expressions DFA 2015-12-11 15:17:37 +03:00
Mikhail Glukhikh
d024045638 Data flow values for Elvis / parenthesized expressions, smart casts on them 2015-12-11 15:17:29 +03:00
Mikhail Glukhikh
745a3aeeac Accurate representation of smart casts on complex expressions 2015-12-11 15:17:25 +03:00
Mikhail Glukhikh
7cd867b936 DFA: take into account if / else and when expression assignments #KT-10002 Fixed
Also #KT-7479 Fixed
2015-12-11 15:17:22 +03:00
Mikhail Glukhikh
e7fc6bcc6e BuiltIns refactoring: getEnumEntry 2015-12-11 11:11:46 +03:00
Mikhail Glukhikh
c8b50eec1e Enum.values: deprecation (warning) --> deprecation (error) 2015-12-11 11:11:42 +03:00
Mikhail Glukhikh
521b216602 Migration: Enum.values to Enum.values() 2015-12-11 11:11:38 +03:00
Mikhail Glukhikh
3254641c5a Local sealed classes: warning --> error 2015-12-11 11:11:34 +03:00
Dmitry Petrov
0fe74a8b43 COMMA_IN_WHEN_CONDITION_WITHOUT_ARGUMENT is an ERROR now.
Migrated code.
Updated test data in IDE tests.
Dropped whenWithRangeTestsAndMultiConditions.kt:
"Introduce subject" is not applicable to 'when' with ||-ed conditions.
2015-12-11 10:43:16 +03:00
Alexey Tsvetkov
199827635f Reserve 'typeof' as a keyword 2015-12-10 21:26:41 +03:00
Alexey Sedunov
4c3f620255 Minor: Fix compilation 2015-12-10 21:03:44 +03:00
Alexey Sedunov
f87d2d1fcc Introduce Refactorings: Implement trimming renderer for expression
chooser. Do not suggest parenthesized expressions
 #KT-9028 Fixed
2015-12-10 20:07:26 +03:00
Alexey Sedunov
ae2fc19fe5 Introduce Parameter/Lambda Parameter: Parenthesize binary expressions if operation reference starts with a new line 2015-12-10 20:07:24 +03:00
Alexey Sedunov
354e1dc337 Extract Function: Parenthesize binary expressions if operation reference starts with a new line 2015-12-10 20:07:23 +03:00
Alexey Sedunov
1824f10f07 Introduce Variable: Parenthesize binary expressions if operation references starts with a new line
#KT-3933 Fixed
2015-12-10 20:07:22 +03:00
Alexey Sedunov
ffc8b6fd89 Safe Delete: Move test classes and test data to refactoring directory 2015-12-10 20:06:34 +03:00
Alexey Sedunov
a76f43b66c Safe Delete: Skip internal usages of class constructors when deleting class itself
#KT-8857 Fixed
2015-12-10 20:06:31 +03:00
Alexey Sedunov
f50059a11a Create from Usage: Implement "Create function" on callable references
#KT-10283 Fixed
2015-12-10 20:06:30 +03:00
Alexey Sedunov
87aebd2cdf Create from Usage: Forbid "Create local variable/parameter/property" on callable references
#KT-10283 In Progress
2015-12-10 20:06:27 +03:00
Alexey Sedunov
44743aade5 Create from Usage: Allow type parameters in the receiver position
#KT-7497 Fixed
2015-12-10 20:06:26 +03:00
Alexey Sedunov
76cf284b77 Introduce Variable: Do not suggest type-based names for multi-declaration entries if component function corresponds to value parameter
#KT-10287 Fixed
2015-12-10 20:06:24 +03:00
Yan Zhulanow
15faa6610c Android Extensions: do not cache package fragment provider with synthetic properties (KT-10318) 2015-12-10 19:38:38 +03:00
Yan Zhulanow
ac9a1350c2 Application package from manifest file has a higher priority than the applicationId value in build.gradle (KT-10320) 2015-12-10 19:38:38 +03:00
Dmitry Jemerov
009e3f9cd7 rename PSI classes according to current terminology:
KtMultiDeclaration(Entry) -> KtDestructuringDeclaration(Entry)
KtFunctionLiteralExpression -> KtLambdaExpression
KtFunctionLiteralArgument -> KtLambdaArgument
KtDelegationSpecifierList -> KtSuperTypeList
KtDelegationSpecifier -> KtSuperTypeListEntry
KtDelegatorToSuperClass -> KtSuperTypeEntry
KtDelegatorToSuperCall -> KtSuperTypeCallEntry
KtDelegationByExpressionSpecifier ->KtDelegatedSuperTypeEntry
2015-12-10 16:15:13 +01:00
Alexey Tsvetkov
ef4b3c99f4 Minor: remove default values for markChunk parameters 2015-12-10 18:03:20 +03:00
Alexey Tsvetkov
6a74b1c8bf Rebuild only kotlin when cache version is changed 2015-12-10 18:03:17 +03:00
Alexey Tsvetkov
49778d2fb6 Minor: move buildFinished closer to buildStarted 2015-12-10 18:03:13 +03:00
Natalia Ukhorskaya
d10c3ffbe4 Fix exception in EE for inline function invocation
#KT-10217 Fixed
2015-12-10 14:42:00 +03:00
Natalia Ukhorskaya
58d62fde4d Add test for smart step into in method with default args
#KT-4803 In Progress
2015-12-10 14:41:58 +03:00
Natalia Ukhorskaya
1dbe560734 Run Code Clean up for org.jetbrains.kotlin.idea.debugger 2015-12-10 14:41:56 +03:00
Natalia Ukhorskaya
1ca6c695e6 Remove println() from debugger testData 2015-12-10 14:41:53 +03:00
Natalia Ukhorskaya
9b8e5c5684 Refactor KotlinDebuggerTestCase to avoid StubIndexReindex between test invocation 2015-12-10 14:41:51 +03:00
Natalia Ukhorskaya
42119b311d Skip whitespaces as context elements of codeFragmnets
#KT-10171 Fixed
2015-12-10 14:41:49 +03:00
Natalia Ukhorskaya
49e484d796 Do not throw exception analyzing imports in KtCodeFragments 2015-12-10 14:41:47 +03:00
Natalia Ukhorskaya
08c29b7325 Fix step out from inline function literal placed at one line
#KT-10187 Fixed
2015-12-10 13:11:40 +03:00
Natalia Ukhorskaya
3b3dbbab04 Evaluate expression for variable of function type
#KT-10199 Fixed
2015-12-10 13:11:39 +03:00
Natalia Ukhorskaya
2bc2d81486 Debugger: correctly box parameter types in case of generics
#KT-10180 Fixed
2015-12-10 13:11:39 +03:00
Pavel V. Talanov
280e00981f Load java: load annotations on enum entries 2015-12-10 11:12:23 +03:00
Pavel V. Talanov
fb19552920 Mark enum entries that are deprecated in Kotlin as deprecated in bytecode 2015-12-10 11:12:22 +03:00
Zalim Bashorov
5bf8b4d946 Allow to use "static" part of class in own constructors by short name, including in primary constructor 2015-12-09 21:42:32 +03:00
Mikhail Glukhikh
f319b1b93a Sealed classes are not taken into account in live templates 2015-12-09 19:27:50 +03:00
Mikhail Glukhikh
9a4eb2a368 Refactoring: ClassDescriptor.isFinal, no more Modality.isOverridable 2015-12-09 19:27:47 +03:00
Mikhail Glukhikh
fb406bfc24 Refactoring: CallableMemberDescriptor.isOverridable 2015-12-09 19:27:04 +03:00
Mikhail Glukhikh
c73f01927a 'sealed' is now not 'final' by default + related code changes #KT-10266 Fixed 2015-12-09 19:19:04 +03:00
Mikhail Glukhikh
5b72afe8a0 J2K: Modality.kt 2015-12-09 19:19:00 +03:00
Mikhail Glukhikh
d80206376a Modality.java --> Modality.kt 2015-12-09 19:18:56 +03:00
Nikolay Krasko
8e71006e86 Add test JDK 8 module to be able reparse IDEA step 2015-12-09 19:16:37 +03:00
Pavel V. Talanov
da02ed9057 GroupingMessageCollector: ensure that messages without location are reported first
Should fix CompileKotlinAgainstCustomBinariesTest.testIncompleteHierarchyInJava(Kotlin) tests
2015-12-09 18:54:15 +03:00
Pavel V. Talanov
2e971b13aa KotlinGoToTest: test go to for builtIn classes and functions 2015-12-09 18:51:32 +03:00
Pavel V. Talanov
7e6bed7ad8 Decompiled text: should always render all modifiers even if we don't feel like it 2015-12-09 18:51:31 +03:00
Pavel V. Talanov
fee19ad9de CallableClsStubBuilder: correctly decide whether callable is extension 2015-12-09 18:51:30 +03:00
Pavel V. Talanov
deb6410a5c Add test for builtIn stub builder and decompiler
These test are by no means exhaustive, the correctness of the subsystem relies on it sharing code with well-tested js-decompilation
2015-12-09 18:51:30 +03:00
Pavel V. Talanov
5cc04e41fe Enable keyword highlighting in .kotlin_class, .kotlin_package files 2015-12-09 18:51:29 +03:00
Pavel V. Talanov
c40d6af1e5 Decompile builtins (kotlin_class and kotlin_package files)
The main purpose of this is to be able to index builtin declarations and enable go to symbol/class functionality in ide
Also it makes sense to show builtin classes (Any, Int ...) as classes when browsing kotlin-runtime.jar

Refactor decompiler code to eliminate existing and potential duplication
Share the code between js (kjsm) decompilation and builtin decompilation heavily
2015-12-09 18:51:28 +03:00
Pavel V. Talanov
6164566cad Extract duplicate logic between javascript and builtins serialization/deserialization 2015-12-09 18:51:27 +03:00
Pavel V. Talanov
34c3c04ead Implement NameResolverImpl#getPackageFqName(index) 2015-12-09 18:51:26 +03:00
Pavel V. Talanov
5846769b43 J2K NameResolverImpl: convert 2015-12-09 18:51:26 +03:00
Pavel V. Talanov
9ff6be6f0f J2K NameResolverImpl: rename file 2015-12-09 18:51:25 +03:00
Pavel V. Talanov
e458534c93 Write package_fq_name to for Package message when serializing builtins 2015-12-09 18:51:24 +03:00
Pavel V. Talanov
f05de6d6eb Add package_fq_name field extension to builtins.proto 2015-12-09 18:51:24 +03:00
Pavel V. Talanov
9a2442bba6 Decompiler, refactor: reduce the number of classes needed to define a decompiler 2015-12-09 18:51:23 +03:00
Pavel V. Talanov
dc34d4fc31 Decompiler, minor: fix some strange code 2015-12-09 18:51:22 +03:00
Pavel V. Talanov
136e8d9d02 Refactor: repackage decompiler code and explicitly extract class file and js metafile parts 2015-12-09 18:51:21 +03:00
Dmitry Petrov
70c200d265 Fix diagnostic messages for properties.
Fix IDE tests.
Update quick fixes in IDE
(TODO: review new inheritance-related diagnostics with regards to quick fixes)
2015-12-09 17:43:48 +03:00
Dmitry Petrov
94bea54db3 Change "most specific return type" definition for fake overrides.
Given overridden descriptors D = d[i].
1. Find D*, subset of D:
  returnType(d* from D*) <: returnType(d) for each d from D.
  Always prefer var to val.
2. Prefer non-flexible return type to flexible.

Check for var/val overrides properly
(NB: this will report PROPERTY_TYPE_MISMATCH_ON_OVERRIDE
for all properties, not just overrides involving vars as it was before).
2015-12-09 17:43:48 +03:00
Dmitry Petrov
594039ac42 Delegation and overrides:
- Tests.
- No need for a separate diagnostic message regarding
return/property type conflict on override by delegation:
it is always a conflict of inherited signatures.
2015-12-09 17:43:48 +03:00
Dmitry Petrov
84824b1024 Fix KT-10194: skip incorrect delegates. 2015-12-09 17:43:48 +03:00
Dmitry Petrov
ef72c594c4 KT-1934 & KT-10197:
Naive approximation for fake overriding signature:
use upper bound for flexible types.
Check delegation errors.
2015-12-09 17:43:47 +03:00
Dmitry Petrov
6e2d42daf9 J2K: DelegationResolver.kt: convert to Kotlin 2015-12-09 17:43:47 +03:00
Dmitry Petrov
8f5df45edc J2K: DelegationResolver.kt 2015-12-09 17:43:47 +03:00
Dmitry Petrov
2fcb7e532b KT-1934: Fixing synthetic accessors hierarchy 2015-12-09 17:43:47 +03:00
Dmitry Petrov
135c30323b KT-1934 Check inherited signatures for compatibility
Overridden signatures should have compatible return types
(equal types for 'var').
Only relevant overrides should be taken into account.
Refactor inherited signatures check,
introduce a strategy interface for problem reporting.
2015-12-09 17:43:47 +03:00
Dmitry Jemerov
18e343d405 Merge pull request #795 from mcgee/KT-10124
#KT-10124 Fixed
2015-12-09 15:28:31 +01:00
Dmitry Jemerov
863e32c5cd Merge pull request #791 from mcgee/KT-9938
#KT-9938 Fixed
2015-12-09 15:17:31 +01:00
Andrey Breslav
83189013c6 Minor. Drop deprecated unary operator names from JS back-end 2015-12-09 17:10:30 +03:00
Andrey Breslav
0a0e4f1ba2 Minor. Clean up the code in OperatorChecker.kt 2015-12-09 17:10:30 +03:00
Andrey Breslav
3eeab68261 Signature checks fixed for plus() and minus() 2015-12-09 17:10:30 +03:00
Andrey Breslav
421f84e05a Error messages fixed for deprecations that have been made errors 2015-12-09 17:10:30 +03:00
Andrey Breslav
434082cadb 'yield' reserved as a keyword 2015-12-09 17:10:30 +03:00
Alexey Tsvetkov
e6bba01798 Increment cache version
Wildcard generation could cause source level incompatibility, so we should rebuild
2015-12-09 16:23:35 +03:00
Alexey Tsvetkov
c567376e35 Save class hierarchy to incremental caches
Author:    Alexey Tsvetkov <Alexey.Tsvetkov@jetbrains.com>
2015-12-09 16:23:35 +03:00
Alexey Tsvetkov
6ba5dcaa06 Simplify collection externalizers 2015-12-09 16:23:35 +03:00
Nikolay Krasko
8a95f23a23 Adjust formatting for FILE_ANNOTATION_LIST 2015-12-09 16:01:56 +03:00
Nikolay Krasko
966ad9d3b6 Move idea-repl module to ide group 2015-12-09 16:01:55 +03:00
Nikolay Krasko
a2d6bd09f3 Minor: allow to use ${file} directive in action text to reference file name 2015-12-09 16:01:53 +03:00
Nikolay Krasko
3374ac7606 Minor: More tests for warnings suppression 2015-12-09 16:01:52 +03:00
Nikolay Krasko
3c5b02e54a Minor: better diagnostic message in tests 2015-12-09 16:01:50 +03:00
Nikolay Krasko
789738c45f Minor: add fqname to dictionary 2015-12-09 16:01:49 +03:00
Dmitry Jemerov
e97e82d119 use terms "lambda expression" and "anonymous function" instead of "function literal" and "function expression" 2015-12-09 13:55:40 +01:00
mcgee
4a0e33003b #KT-9938 Fixed
Top level test case is added
2015-12-09 07:32:41 +03:00
Alexander Udalov
9a01c0d9cb Test that no delegated properties are used in critical classes in reflection 2015-12-08 22:59:00 +03:00
Stanislav Erokhin
cfed28c2ff Use CastImplicitClassReceiver for implicit this with smart cast 2015-12-08 20:42:55 +03:00
Stanislav Erokhin
b7e4fdf4d5 Add extensionReceiver to ScopeTowerLevel & use it in ImportingScopeBasedTowerLevel 2015-12-08 20:42:55 +03:00
Dmitry Jemerov
57b5588498 rename "Jet" to "Kotlin" in CFG classes 2015-12-08 16:54:09 +01:00
Dmitry Jemerov
3275542426 one more missing invokeLater() for plugin update checks (EA-76738 - Throwable: DebugUtil.currentStackTrace) 2015-12-08 16:45:40 +01:00
Dmitry Jemerov
d65c8fb06c double-check action parameters (EA-76026 - KNPE: ShowExpressionTypeAction.actionPerformed) 2015-12-08 16:45:39 +01:00
Dmitry Jemerov
0ec57e7fee add missing scope checks for highlight usages (EA-75896)
#KT-10038 Fixed
2015-12-08 16:45:19 +01:00
Stanislav Erokhin
10a13e737e Minor. Add isComputing to DeferredType 2015-12-08 17:29:55 +03:00
Stanislav Erokhin
11410000b4 Minor. Do not resolve implicit invoke for callable reference 2015-12-08 17:29:55 +03:00
Stanislav Erokhin
859a8adc31 Fix priority for functions without infix or operator modifier 2015-12-08 17:29:54 +03:00
Stanislav Erokhin
64b101785f Minor. Introduce util function 2015-12-08 17:29:54 +03:00
Alexey Sedunov
e82e4bcfc8 Inline Variable: Show error message on attempt to inline unused declaration 2015-12-08 16:21:08 +03:00
Alexey Sedunov
5c88a1c63e Inline Variable: Parenthesize arguments of the form "e1 < e2" if the next argument has the form "e1 > e2"
#KT-8261 Fixed
2015-12-08 16:21:07 +03:00
Alexey Sedunov
b2bdb8ed02 Inline Variable: Inline string template entries
#KT-7654 Fixed
2015-12-08 16:21:05 +03:00
Alexey Sedunov
0af2243245 J2K: KotlinInlineValHandler (conversion and refactoring) 2015-12-08 16:21:03 +03:00
Alexey Sedunov
2fef2763ab J2K: KotlinInlineValHandler (rename to .kt) 2015-12-08 16:21:02 +03:00
Alexey Sedunov
f4135a0a9f J2K: AbstractInlineTest 2015-12-08 16:21:00 +03:00
Alexey Sedunov
9df3ce018b J2K: AbstractInlineTest (rename to .kt) 2015-12-08 16:20:58 +03:00
Alexey Sedunov
f6b374f829 Inline Variable: Fix dialog text for non-local variables
#KT-6365 Fixed
2015-12-08 16:20:57 +03:00
Alexey Sedunov
e517cbcf78 Quick Fixes: Implement "Rename unresolved reference" fix
#KT-8795 Fixed
2015-12-08 16:20:56 +03:00
Alexey Sedunov
d850d7bbad Change Signature: Parenthesize functional type of receiver in the signature preview
#KT-8737 Fixed
2015-12-08 16:20:53 +03:00
Alexey Sedunov
8f8acf7a83 Pull Up: Drop default parameter values in function which becomes overriding. Disable function with default values if target class is the Java one
#KT-9833 Fixed
2015-12-08 16:20:52 +03:00
Alexey Sedunov
80051b8303 Create from Usage: Locate new declaration using RangeMarker
#KT-9197 Fixed
2015-12-08 16:20:50 +03:00
Alexey Sedunov
99c88cb0c5 Line Marking: Use new-style icons for Kotlin test classes/functions
#KT-10235 Fixed
2015-12-08 16:20:48 +03:00
Alexey Sedunov
8fcda32287 Unit Test Tooling: Support Go to Test/Create Test actions for top-level declarations
#KT-10133 Fixed
2015-12-08 16:20:47 +03:00
Denis Zharkov
ecac0f177b Fix order of type parameters loaded from PSI
#KT-10285 Fixed
2015-12-08 15:46:34 +03:00
Mikhail Glukhikh
d08f6f8238 DataFlowInfo Refactoring: getNullability() --> getCollectedNullability(); getPossibleTypes() --> getCollectedTypes() 2015-12-08 11:23:44 +03:00
Mikhail Glukhikh
57b3bc0496 Regression: getPredictableNullability for unnecessary safe call check #KT-10276 Fixed 2015-12-08 11:23:35 +03:00
Mikhail Glukhikh
2330ce2c28 Optimization: do not collect not-null types in DataFlowInfo.equate 2015-12-08 11:22:33 +03:00
Mikhail Glukhikh
5c9e55f3fb DFA bug fix: assignment of unstable to stable uses predictable type set (see test) 2015-12-08 10:13:38 +03:00
Mikhail Glukhikh
2e73bcb3a6 DFA bug fix: assignment of unstable to stable uses predictable nullability (see test) 2015-12-08 10:13:34 +03:00
Mikhail Glukhikh
96d0c4a1db Nullability bug fix in the source code 2015-12-08 10:13:22 +03:00
Mikhail Glukhikh
bfad9bd87f More exact unnecessary not-null assertion message #KT-3688 Fixed 2015-12-08 10:13:14 +03:00
Stanislav Erokhin
75245b3046 Rewrite TowerLevels. 2015-12-08 00:16:17 +03:00
Stanislav Erokhin
11c86405bf Fix ClassKind for Serializable and change ClassKind to INTERFACE for error classes. 2015-12-08 00:16:16 +03:00
Stanislav Erokhin
f2e60a0e11 Minor. Have to deal with error descriptors like previous resolution does. 2015-12-08 00:16:16 +03:00
Anton Sukhonosenko
da5f71773a #KT-9938 Fixed
Code review fixes
2015-12-07 22:48:47 +03:00
Zalim Bashorov
1e0b133e19 Find Nothing only in own arguments of generic type to make type raw and generate ''?" for contravariant position instead of use raw type 2015-12-07 19:25:59 +03:00
Alexander Udalov
fa77808319 Rename UpperBoundCheckerTask -> UpperBoundCheckRequest 2015-12-07 15:47:47 +03:00
Alexander Udalov
2dce7ad1e2 Add test on "inconsistent type parameter bounds"
It seems that all tests on that diagnostic were replaced in previous commits by
"repeated bound" and "no other bounds except a type parameter bound"
diagnostics
2015-12-07 15:47:47 +03:00
Alexander Udalov
d3c17ec337 Report error when type parameter has a type parameter bound and any other bound
To prevent issues with erasure on JVM: it's unclear what such type parameter
should be erased to
2015-12-07 15:47:47 +03:00
Alexander Udalov
b1fa740341 Do not report "inconsistent bounds" when there are repeated bounds
Also slightly refactor DeclarationsChecker#checkSupertypesForConsistency
2015-12-07 15:47:47 +03:00
Alexander Udalov
5fbb9bfe3b Report error on repeated upper bounds for type parameters 2015-12-07 15:47:47 +03:00
Alexander Udalov
21e64e02bd Report error on more than one class bound for type parameters
Such code may behave unexpectedly when compiled to JVM
2015-12-07 15:47:47 +03:00
Alexander Udalov
5541224288 Minor, add test on annotation on type argument 2015-12-07 15:47:47 +03:00
Anton Sukhonosenko
6b49ac6b46 #KT-9938 Fixed 2015-12-06 01:44:57 +03:00
Ilya Gorbunov
dc70c0d31e Move sequence interface definition to a separate file.
Merge SequnceJVM content into Sequences.
2015-12-05 02:40:27 +03:00
Ilya Gorbunov
a15ca7c374 Minor: rename file with sequences 2015-12-05 02:40:25 +03:00
Mikhail Glukhikh
5729855e4f Type parameter as result type: more precise expected type definition #KT-5385 Fixed
Tests for KT-5385 KT-10223 KT-7800 KT-7817 + something related
2015-12-04 19:00:24 +03:00
Natalia Ukhorskaya
51abb021bc Correct resource path for flavors in android-extensions-plugin 2015-12-04 17:21:37 +03:00
Natalia Ukhorskaya
c523817213 Do not cache AndroidModule in IDEAndroidLayoutXmlManager 2015-12-04 17:21:36 +03:00
Mikhail Glukhikh
408dd9bc9d Optimization: data flow info no more stores supertypes of the variable original type as possible types (dynamic is an exception) 2015-12-04 11:40:16 +03:00
Denis Zharkov
9c73502bdc Partially revert "Fix project source to overcome bootstrap problem"
Adjust code to new generic signatures generated by Kotlin compiler
This reverts commit 0fd2484bc9.
2015-12-04 10:19:48 +03:00
Nikolay Krasko
a19708693b Update kotlin run configuration editor
- Remove deprecated component for selecting JRE
- Update module selector
2015-12-04 01:03:26 +03:00
Nikolay Krasko
8683582c40 Fix red code in AbstractEditorForEvaluateExpressionTest.kt 2015-12-03 18:59:55 +03:00
Nikolay Krasko
703f39f492 Add icon for the project 2015-12-03 18:59:55 +03:00
Denis Zharkov
95cecdbc42 Support overrides of generic methods with erased version in Java 2015-12-03 18:19:36 +03:00
Denis Zharkov
4f06cece37 Refactor external overidability conditions
Before this change they could only negatively affect on result
Now they may force success result

Also refine overridavility condition for java fields:
two java fields having the same name are seen as overrides even
if they have different type
2015-12-03 18:19:36 +03:00
Denis Zharkov
8838e46578 Do not create KotlinTypeImpl with error scope while erasing
See assertion in KotlinTypeImpl init block
2015-12-03 18:19:36 +03:00
Denis Zharkov
e2b51f30ed Extract 'doSubstitute' parameters into SubstitutionConfiguration 2015-12-03 18:19:36 +03:00
Natalia Ukhorskaya
a197fc8cb8 Fix NoSuchMethod in android-extensions-plugin
#KT-10263 Fixed
2015-12-03 16:17:24 +03:00
Michael Bogdanov
4b8017e34b Fix for KT-7999: Wrong result when use nullable types as reified parameter, KT-8043: Unsafe cast to reified parameter throws NPE instead of TypeCastException
#KT-7999 Fixed
  #KT-8043 Fixed

~
2015-12-03 15:09:54 +03:00
Dmitry Jemerov
3478a6fb6c download markdown tagged with forKotlin, not latest build from master 2015-12-03 11:57:55 +01:00
Dmitry Jemerov
ce9012c352 fix compilation after changes in markdown library 2015-12-02 19:44:46 +01:00
Alexey Tsvetkov
d53cd3c70b Save system properties in incremental jps tests 2015-12-02 20:56:38 +03:00
Alexey Tsvetkov
73444ce59b Minor: refactor shouldRebuildBecauseVersionChanged 2015-12-02 20:56:37 +03:00
Alexey Tsvetkov
7fff17ba7c Minor: rename CACHE_DIRECTORY_NAME->KOTLIN_CACHE_DIRECTORY_NAME 2015-12-02 20:56:37 +03:00
Alexey Tsvetkov
7063e1f56a Do not mark dirty same files 2015-12-02 20:56:37 +03:00
Alexey Tsvetkov
4800cff87f Do not recompile files compiled in current round 2015-12-02 20:56:37 +03:00
Alexey Tsvetkov
19089f8b17 Prevent processing changes if all kotlin in chunk was rebuilt 2015-12-02 20:56:37 +03:00
Alexey Tsvetkov
87f09ab5b0 Introduce FSOperationsHelper to mark files dirty 2015-12-02 20:56:37 +03:00
Alexey Tsvetkov
98e0905eb3 Minor: add java to test case 2015-12-02 20:56:37 +03:00
Alexey Tsvetkov
3d3d670cd7 Minor: move check inside hasDirtyOrRemovedKotlin 2015-12-02 20:56:37 +03:00
Alexey Tsvetkov
60a8db1c6c Do not use USER_DATA to preserve data between compilation rounds 2015-12-02 20:56:36 +03:00
Alexey Tsvetkov
a447c39f69 Kotlin incremental cache version change should not affect java only modules 2015-12-02 20:56:36 +03:00
Alexey Tsvetkov
b1b0da5228 Minor: add description to key 2015-12-02 20:56:36 +03:00
Alexey Tsvetkov
c9012b10c5 Simplify lazy caches tests 2015-12-02 20:56:36 +03:00
Alexey Tsvetkov
aea6ad0f0c Move CacheVersion properties to constructor 2015-12-02 20:56:36 +03:00
Alexey Tsvetkov
e90dc047bd Test turning incremental compilation on/off 2015-12-02 20:56:36 +03:00
Alexey Tsvetkov
a8b551e518 Test versioning of experimental incremental compilation 2015-12-02 20:56:36 +03:00
Alexey Tsvetkov
69c906014f Enable separate versioning for experimental incremental compilation 2015-12-02 20:56:35 +03:00
Pavel V. Talanov
d20fb5ddd7 BuilderFactoryForDuplicateSignatureDiagnostics: report diagnostics lazily 2015-12-02 20:44:53 +03:00
Dmitry Jemerov
05a62c5892 avoid unnecessary reads of file content during indexing 2015-12-02 18:09:19 +01:00
Dmitry Jemerov
f9306d9c3c KotlinBinaryClassCache: J2K 2015-12-02 18:09:18 +01:00
Dmitry Jemerov
3abbdb4d15 KotlinBinaryClassCache: rename to .kt 2015-12-02 18:09:17 +01:00
Anton Sukhonosenko
5bc70b3150 #KT-10124 Fixed 2015-12-02 20:03:13 +03:00
Mikhail Glukhikh
dd3b85dca3 Pseudocode refactoring: repeatPart + repeatWhole 2015-12-02 18:15:03 +03:00
Mikhail Glukhikh
ea3a65d0b8 Additional tests for KT-10243 2015-12-02 18:14:59 +03:00
Pavel V. Talanov
b9ce9f8576 Script, IDE: tweak extract based refactorings to behave better in scripts
Fix not being able to invoke introduce variable for top level script expression
Prohibit introduce parameter and introduce property for scripts on top level
Basic test for introduce function (produces red code atm)
2015-12-02 15:14:25 +03:00
Alexey Sedunov
ffd8863875 Extract Function: Add support for member extension properties 2015-12-02 13:54:05 +03:00
Alexey Sedunov
39b46bb3ef Extract Function: Add support for member extension functions 2015-12-02 13:54:04 +03:00
Alexey Sedunov
6abf13be41 Extract Function: Consider member property with invoke() a receiver candidate
#KT-9774 Fixed
2015-12-02 13:54:03 +03:00
Alexey Sedunov
03e1480476 Extraction Engine: Get rid of explicit element offset manipulation and use copyable user data instead 2015-12-02 13:54:02 +03:00
Alexey Sedunov
44bc937499 Shorten References: Fix removal of explicit companion references in the position of callee expression
#KT-10102
2015-12-02 13:54:01 +03:00
Alexey Sedunov
2dcc38b92f Create from Usage: Forbid "Create parameter/local variable/property" on label references
#KT-10119 Fixed
2015-12-02 13:54:00 +03:00
Alexey Sedunov
3c87ccc5ff Move File: Reimplement Move dialog for Kotlin files. Do not show "Search for references" option (consider it true in all cases)
#KT-10118 Fixed
2015-12-02 13:53:59 +03:00
Alexey Sedunov
bcadfd4661 Introduce Variable: Suggest choosing between single variable and
multi-declaration. Forbid multi-declaration for collections and arrays
 #KT-10242 Fixed
2015-12-02 13:46:47 +03:00
Ilya Chernikov
c1c6d0ee3a fixes after review 2015-12-02 10:30:56 +01:00
Ilya Chernikov
6313ecac1c another attempt to fix parallel compilation - enabling keepalive in compiler use sites, but in jps taking parallel compilation option into account, so it should be now not set in tests 2015-12-02 10:30:56 +01:00
Mikhail Glukhikh
60e457167d Creating deep copy of local function declaration instructions in CFA, regression test #KT-10243 Fixed 2015-12-01 23:40:50 +03:00
Stanislav Erokhin
36206ddf6d Minor. Enable assertion for dist. 2015-12-01 20:44:27 +03:00
Ilya Gorbunov
b7a50b333e Better replacement for containsAll, removeAll, retainAll with incompatible types. 2015-12-01 20:35:46 +03:00
Alexander Udalov
2821448dd8 Minor, simplify kdoc for KClass#qualifiedName 2015-12-01 20:20:48 +03:00
Stanislav Erokhin
8807cd828f Removed MemberScope.getPackage 2015-12-01 15:38:04 +03:00
Stanislav Erokhin
846fb397c4 Collect all candidates for completion 2015-12-01 15:38:04 +03:00
Stanislav Erokhin
2b66af29aa Added debug info 2015-12-01 15:38:03 +03:00
Stanislav Erokhin
22b14cfc5c Fix missing smart casts 2015-12-01 15:38:03 +03:00
Stanislav Erokhin
3776e5698f Removed hidden descriptors from new resolve 2015-12-01 15:38:03 +03:00
Stanislav Erokhin
e92c314b46 Base dynamic support in new resolve 2015-12-01 15:38:02 +03:00
Stanislav Erokhin
2987576a0a Minor. fix applicability level for UsedSmartCastForDispatchReceiver 2015-12-01 15:38:02 +03:00
Stanislav Erokhin
5edadfe8ea Refactor ScopeTowerProcessor 2015-12-01 15:38:01 +03:00
Stanislav Erokhin
bc49825f55 Fix testLib test 2015-12-01 15:38:01 +03:00
4129 changed files with 51128 additions and 20249 deletions

2
.idea/ant.xml generated
View File

@@ -3,7 +3,7 @@
<component name="AntConfiguration">
<buildFile url="file://$PROJECT_DIR$/compiler/frontend/buildLexer.xml" />
<buildFile url="file://$PROJECT_DIR$/build.xml">
<antCommandLine value="-J-XX:MaxPermSize=100m" />
<antCommandLine value="-J-XX:MaxPermSize=100m -J-ea" />
<maximumHeapSize value="1024" />
</buildFile>
<buildFile url="file://$PROJECT_DIR$/update_dependencies.xml" />

View File

@@ -2,6 +2,7 @@
<dictionary name="Nikolay.Krasko">
<words>
<w>accessors</w>
<w>fqname</w>
<w>goto</w>
<w>gradle</w>
<w>intrinsics</w>

BIN
.idea/icon.png generated Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

13
.idea/libraries/kotlin_test.xml generated Normal file
View File

@@ -0,0 +1,13 @@
<component name="libraryTable">
<library name="kotlin-test">
<CLASSES>
<root url="jar://$PROJECT_DIR$/dependencies/bootstrap-compiler/Kotlin/kotlinc/lib/kotlin-test.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="file://$PROJECT_DIR$/libraries/kotlin.test/shared/src/main/kotlin" />
<root url="file://$PROJECT_DIR$/libraries/kotlin.test/shared/src/main/kotlin.jvm" />
<root url="file://$PROJECT_DIR$/libraries/kotlin.test/junit/src/main/kotlin" />
</SOURCES>
</library>
</component>

3
.idea/modules.xml generated
View File

@@ -40,7 +40,7 @@
<module fileurl="file://$PROJECT_DIR$/idea/idea-core/idea-core.iml" filepath="$PROJECT_DIR$/idea/idea-core/idea-core.iml" group="ide" />
<module fileurl="file://$PROJECT_DIR$/idea/idea-jps-common/idea-jps-common.iml" filepath="$PROJECT_DIR$/idea/idea-jps-common/idea-jps-common.iml" group="ide" />
<module fileurl="file://$PROJECT_DIR$/idea/idea-live-templates/idea-live-templates.iml" filepath="$PROJECT_DIR$/idea/idea-live-templates/idea-live-templates.iml" group="ide" />
<module fileurl="file://$PROJECT_DIR$/idea/idea-repl/idea-repl.iml" filepath="$PROJECT_DIR$/idea/idea-repl/idea-repl.iml" />
<module fileurl="file://$PROJECT_DIR$/idea/idea-repl/idea-repl.iml" filepath="$PROJECT_DIR$/idea/idea-repl/idea-repl.iml" group="ide" />
<module fileurl="file://$PROJECT_DIR$/idea-runner/idea-runner.iml" filepath="$PROJECT_DIR$/idea-runner/idea-runner.iml" group="ide" />
<module fileurl="file://$PROJECT_DIR$/idea/idea-test-framework/idea-test-framework.iml" filepath="$PROJECT_DIR$/idea/idea-test-framework/idea-test-framework.iml" group="ide" />
<module fileurl="file://$PROJECT_DIR$/compiler/preloader/instrumentation/instrumentation.iml" filepath="$PROJECT_DIR$/compiler/preloader/instrumentation/instrumentation.iml" group="compiler/cli" />
@@ -62,6 +62,7 @@
<module fileurl="file://$PROJECT_DIR$/core/reflection.jvm/reflection.jvm.iml" filepath="$PROJECT_DIR$/core/reflection.jvm/reflection.jvm.iml" group="core" />
<module fileurl="file://$PROJECT_DIR$/core/runtime.jvm/runtime.jvm.iml" filepath="$PROJECT_DIR$/core/runtime.jvm/runtime.jvm.iml" group="core" />
<module fileurl="file://$PROJECT_DIR$/compiler/serialization/serialization.iml" filepath="$PROJECT_DIR$/compiler/serialization/serialization.iml" group="compiler" />
<module fileurl="file://$PROJECT_DIR$/temp-jdk8/temp-jdk8.iml" filepath="$PROJECT_DIR$/temp-jdk8/temp-jdk8.iml" />
<module fileurl="file://$PROJECT_DIR$/compiler/util/util.iml" filepath="$PROJECT_DIR$/compiler/util/util.iml" />
<module fileurl="file://$PROJECT_DIR$/core/util.runtime/util.runtime.iml" filepath="$PROJECT_DIR$/core/util.runtime/util.runtime.iml" group="core" />
</modules>

View File

@@ -5,7 +5,7 @@
<option name="VM_PARAMETERS" value="-Xmx800m -XX:ReservedCodeCacheSize=64m -XX:MaxPermSize=450m -XX:+HeapDumpOnOutOfMemoryError -ea -Didea.is.internal=true -Didea.debug.mode=true -Didea.system.path=../system-idea -Didea.config.path=../config-idea -Dapple.laf.useScreenMenuBar=true -Dapple.awt.graphics.UseQuartz=true -Dsun.io.useCanonCaches=false -Dplugin.path=$PROJECT_DIR$/out/artifacts/Kotlin -Dkotlin.internal.mode.enabled=true -Didea.additional.classpath=${JAVA_HOME}\lib\tools.jar,../idea-kotlin-runtime/kotlin-runtime.jar,../idea-kotlin-runtime/kotlin-reflect.jar" />
<option name="PROGRAM_PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$/ideaSDK/bin" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="true" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" value="1.7" />
<option name="ENABLE_SWING_INSPECTOR" value="false" />
<option name="ENV_VARIABLES" />

View File

@@ -158,11 +158,11 @@
<print-file-size-statistic path="${kotlin-home}/lib" file-name="kotlin-reflect.jar"/>
<print-file-size-statistic path="${kotlin-home}/lib" file-name="kotlin-jslib.jar"/>
<print-file-size-statistic path="${output}" file-name="kotlin.js"/>
<print-file-size-statistic path="${output}" file-name="builtins.js"/>
<print-file-size-statistic path="${output}" file-name="builtins.meta.js"/>
<print-file-size-statistic path="${output}" file-name="stdlib.js"/>
<print-file-size-statistic path="${output}" file-name="stdlib.meta.js"/>
<print-file-size-statistic path="${js.stdlib.output.dir}" file-name="kotlin.js"/>
<print-file-size-statistic path="${js.stdlib.output.dir}" file-name="builtins.js"/>
<print-file-size-statistic path="${js.stdlib.output.dir}" file-name="builtins.meta.js"/>
<print-file-size-statistic path="${js.stdlib.output.dir}" file-name="stdlib.js"/>
<print-file-size-statistic path="${js.stdlib.output.dir}" file-name="stdlib.meta.js"/>
</target>
<target name="post_build" depends="zipArtifacts, revertTemplateFiles, printStatistics, remove_internal_artifacts, dont_remove_internal_artifacts"/>

View File

@@ -12,8 +12,10 @@
<property name="bootstrap.compiler.home" value="${bootstrap.home}/Kotlin/kotlinc"/>
<property name="bootstrap.runtime" value="${bootstrap.compiler.home}/lib/kotlin-runtime.jar"/>
<property name="bootstrap.reflect" value="${bootstrap.compiler.home}/lib/kotlin-reflect.jar"/>
<property name="bootstrap.kotlin.test" value="${bootstrap.compiler.home}/lib/kotlin-test.jar" />
<property name="output" value="${basedir}/dist"/>
<property name="js.stdlib.output.dir" value="${output}/js"/>
<property name="intermediate-sources" value="out/src" />
<property name="kotlin-home" value="${output}/kotlinc"/>
<property name="build.number" value="snapshot"/>
@@ -55,6 +57,7 @@
<path id="classpath">
<file file="${bootstrap.runtime}"/>
<file file="${bootstrap.kotlin.test}" />
<file file="${bootstrap.reflect}"/>
<fileset dir="${idea.sdk}" includes="core/*.jar"/>
<pathelement location="${protobuf.jar}"/>
@@ -177,19 +180,33 @@
<sequential if:true="${bootstrap.or.local.build}">
<copy file="${bootstrap.runtime}" tofile="${kotlin-home}/lib/kotlin-runtime-internal-bootstrap.jar"/>
<copy file="${bootstrap.reflect}" tofile="${kotlin-home}/lib/kotlin-reflect-internal-bootstrap.jar"/>
<copy file="${bootstrap.kotlin.test}" tofile="${kotlin-home}/lib/kotlin-test-internal-bootstrap.jar" failonerror="false"/>
<jar destfile="${kotlin-home}/lib/kotlin-reflect-internal-bootstrap.jar" update="true">
<manifest>
<attribute name="Class-Path" value="kotlin-runtime-internal-bootstrap.jar"/>
</manifest>
</jar>
<jar destfile="${kotlin-home}/lib/kotlin-test-internal-bootstrap.jar" update="true">
<manifest>
<attribute name="Class-Path" value="kotlin-runtime-internal-bootstrap.jar"/>
</manifest>
</jar>
</sequential>
<sequential unless:true="${bootstrap.or.local.build}">
<copy file="${bootstrap.runtime}" todir="${kotlin-home}/lib"/>
<copy file="${bootstrap.reflect}" todir="${kotlin-home}/lib"/>
<copy file="${bootstrap.kotlin.test}" todir="${kotlin-home}/lib"/>
</sequential>
</target>
<target name="copy-dist-to-bootstrap">
<delete dir="${basedir}/dependencies/bootstrap-compiler/Kotlin/kotlinc" />
<copy todir="${basedir}/dependencies/bootstrap-compiler/Kotlin/kotlinc">
<fileset dir="${basedir}/dist/kotlinc" />
</copy>
</target>
<target name="compiler-sources">
<jar jarfile="${output}/kotlin-compiler-sources.jar">
<!-- TODO How to convert it from pathset or dirset ? -->
@@ -308,13 +325,13 @@
<kotlin-pp src="libraries/stdlib/src" output="${intermediate-sources}/stdlib/js" profile="JS" />
<new-kotlin2js output="${output}/js/${compiled.builtins.js}">
<new-kotlin2js output="${js.stdlib.output.dir}/${compiled.builtins.js}">
<src>
<fileset refid="kotlin.builtin.files"/>
</src>
</new-kotlin2js>
<new-kotlin2js output="${output}/js/${compiled.stdlib.js}">
<new-kotlin2js output="${js.stdlib.output.dir}/${compiled.stdlib.js}">
<src>
<resources refid="js.lib.files"/>
</src>
@@ -334,7 +351,7 @@
prettyprint="true"
languagein="ECMASCRIPT5_STRICT"
warning="${warningLevel}"
output="${output}/js/kotlin.js">
output="${js.stdlib.output.dir}/kotlin.js">
<sources dir="${stdlib.js.dir}">
<file name="kotlin_lib_ecma5.js"/>
@@ -343,11 +360,11 @@
<file name="long.js"/>
</sources>
<sources dir="${output}/js">
<sources dir="${js.stdlib.output.dir}">
<file name="${compiled.builtins.js}"/>
</sources>
<sources dir="${output}/js">
<sources dir="${js.stdlib.output.dir}">
<file name="${compiled.stdlib.js}"/>
</sources>
@@ -362,7 +379,7 @@
<jar jarfile="${kotlin-home}/lib/kotlin-jslib.jar" duplicate="fail">
<zipfileset file="${kotlin-home}/build.txt" prefix="META-INF"/>
<zipfileset dir="${output}/js" prefix="">
<zipfileset dir="${js.stdlib.output.dir}" prefix="">
<include name="kotlin.js"/>
<include name="${compiled.stdlib.meta.js}"/>
<include name="stdlib/**"/>
@@ -781,7 +798,7 @@
</target>
<target name="stdlib">
<new-kotlinc output="${output}/classes/stdlib" moduleName="kotlin-stdlib">
<new-kotlinc output="${output}/classes/stdlib" moduleName="kotlin-stdlib" additionalOptions="-Xmultifile-facades-open">
<src>
<include name="libraries/stdlib/src"/>
</src>
@@ -791,6 +808,20 @@
</new-kotlinc>
</target>
<target name="kotlin.test">
<new-kotlinc output="${output}/classes/kotlin.test" moduleName="kotlin-test">
<src>
<include name="libraries/kotlin.test/shared/src/main/kotlin" />
<include name="libraries/kotlin.test/shared/src/main/kotlin.jvm" />
<include name="libraries/kotlin.test/junit/src/main/kotlin" />
</src>
<class-path>
<pathelement path="${output}/classes/builtins"/>
<pathelement path="libraries/lib/junit-4.11.jar"/>
</class-path>
</new-kotlinc>
</target>
<target name="core">
<new-kotlinc output="${output}/classes/core" moduleName="kotlin-core">
<src>
@@ -935,15 +966,23 @@
</pack-runtime-jar>
</target>
<target name="pack-kotlin-test">
<pack-runtime-jar jar-name="kotlin-test.jar" implementation-title="${manifest.impl.title.kotlin.test}">
<jar-content>
<fileset dir="${output}/classes/kotlin.test" includes="**/*" excludes="kotlin/internal/OnlyInputTypes*,kotlin/internal"/>
</jar-content>
</pack-runtime-jar>
</target>
<target name="runtime"
depends="builtins,stdlib,core,reflection,pack-runtime,pack-runtime-sources"/>
<target name="dist"
depends="clean,init,prepare-dist,preloader,runner,serialize-builtins,compiler,compiler-sources,ant-tools,jdk-annotations,android-sdk-annotations,runtime,kotlin-js-stdlib,android-compiler-plugin,daemon-client"
depends="clean,init,prepare-dist,preloader,runner,serialize-builtins,compiler,compiler-sources,ant-tools,jdk-annotations,android-sdk-annotations,runtime,kotlin.test,pack-kotlin-test,kotlin-js-stdlib,android-compiler-plugin,daemon-client"
description="Builds redistributables from sources"/>
<target name="dist-quick"
depends="clean,init,prepare-dist,preloader,serialize-builtins,compiler-quick,ant-tools,jdk-annotations,android-sdk-annotations,runtime,kotlin-js-stdlib,android-compiler-plugin"
depends="clean,init,prepare-dist,preloader,serialize-builtins,compiler-quick,ant-tools,jdk-annotations,android-sdk-annotations,runtime,kotlin.test,pack-kotlin-test,kotlin-js-stdlib,android-compiler-plugin"
description="Builds everything, but classes are reused from project out dir, doesn't run proguard and javadoc"/>
<target name="dist-quick-compiler-only"

View File

@@ -93,14 +93,14 @@ public class CodegenUtil {
}
@NotNull
public static Map<FunctionDescriptor, FunctionDescriptor> getTraitMethods(ClassDescriptor descriptor) {
public static Map<FunctionDescriptor, FunctionDescriptor> getNonPrivateTraitMethods(ClassDescriptor descriptor) {
Map<FunctionDescriptor, FunctionDescriptor> result = new LinkedHashMap<FunctionDescriptor, FunctionDescriptor>();
for (DeclarationDescriptor declaration : DescriptorUtils.getAllDescriptors(descriptor.getDefaultType().getMemberScope())) {
if (!(declaration instanceof CallableMemberDescriptor)) continue;
CallableMemberDescriptor inheritedMember = (CallableMemberDescriptor) declaration;
CallableMemberDescriptor traitMember = ImplKt.findTraitImplementation(inheritedMember);
if (traitMember == null) continue;
if (traitMember == null || Visibilities.isPrivate(traitMember.getVisibility())) continue;
assert traitMember.getModality() != Modality.ABSTRACT : "Cannot delegate to abstract trait method: " + inheritedMember;
@@ -140,7 +140,7 @@ public class CodegenUtil {
}
@NotNull
public static ClassDescriptor getSuperClassByDelegationSpecifier(@NotNull KtDelegationSpecifier specifier, @NotNull BindingContext bindingContext) {
public static ClassDescriptor getSuperClassBySuperTypeListEntry(@NotNull KtSuperTypeListEntry specifier, @NotNull BindingContext bindingContext) {
KotlinType superType = bindingContext.get(BindingContext.TYPE, specifier.getTypeReference());
assert superType != null : "superType should not be null: " + specifier.getText();

View File

@@ -31,37 +31,41 @@ public object CodegenUtilKt {
// class Foo : Bar by baz
// descriptor = Foo
// toTrait = Bar
// toInterface = Bar
// delegateExpressionType = typeof(baz)
// return Map<member of Foo, corresponding member of typeOf(baz)>
@JvmStatic
public fun getDelegates(
descriptor: ClassDescriptor,
toTrait: ClassDescriptor,
toInterface: ClassDescriptor,
delegateExpressionType: KotlinType? = null
): Map<CallableMemberDescriptor, CallableDescriptor> {
if (delegateExpressionType?.isDynamic() ?: false) return mapOf();
return descriptor.getDefaultType().getMemberScope().getContributedDescriptors().asSequence()
return descriptor.defaultType.memberScope.getContributedDescriptors().asSequence()
.filterIsInstance<CallableMemberDescriptor>()
.filter { it.getKind() == CallableMemberDescriptor.Kind.DELEGATION }
.filter { it.kind == CallableMemberDescriptor.Kind.DELEGATION }
.asIterable()
.sortedWith(MemberComparator.INSTANCE)
.keysToMapExceptNulls {
delegatingMember ->
val actualDelegates = DescriptorUtils.getAllOverriddenDescriptors(delegatingMember)
.filter { it.getContainingDeclaration() == toTrait }
.map {
.mapNotNull {
overriddenDescriptor ->
val scope = (delegateExpressionType ?: toTrait.getDefaultType()).getMemberScope()
val name = overriddenDescriptor.getName()
if (overriddenDescriptor.containingDeclaration == toInterface) {
val scope = (delegateExpressionType ?: toInterface.defaultType).memberScope
val name = overriddenDescriptor.name
// this is the actual member of delegateExpressionType that we are delegating to
(scope.getContributedFunctions(name, NoLookupLocation.FROM_BACKEND) + scope.getContributedVariables(name, NoLookupLocation.FROM_BACKEND))
.first {
(listOf(it) + DescriptorUtils.getAllOverriddenDescriptors(it)).map { it.getOriginal() }.contains(overriddenDescriptor.getOriginal())
}
// this is the actual member of delegateExpressionType that we are delegating to
(scope.getContributedFunctions(name, NoLookupLocation.FROM_BACKEND) + scope.getContributedVariables(name, NoLookupLocation.FROM_BACKEND))
.firstOrNull {
(listOf(it) + DescriptorUtils.getAllOverriddenDescriptors(it))
.map { it.original }
.contains(overriddenDescriptor.original)
}
}
else null
}
assert(actualDelegates.size() <= 1) { "Many delegates found for $delegatingMember: $actualDelegates" }

View File

@@ -41,6 +41,14 @@ public class AccessorForConstructorDescriptor(
override fun substitute(substitutor: TypeSubstitutor) = super.substitute(substitutor) as ConstructorDescriptor
override fun copy(
newOwner: DeclarationDescriptor?, modality: Modality?, visibility: Visibility?, kind: CallableMemberDescriptor.Kind?, copyOverrides: Boolean
): AccessorForConstructorDescriptor {
throw UnsupportedOperationException("Trying to copy synthetic accessor $this")
}
override fun getOriginal(): AccessorForConstructorDescriptor = this
init {
initialize(
DescriptorUtils.getReceiverParameterType(extensionReceiverParameter),

View File

@@ -226,9 +226,9 @@ public class AsmUtil {
int flags = getVisibilityAccessFlag(functionDescriptor);
flags |= getVarargsFlag(functionDescriptor);
flags |= getDeprecatedAccessFlag(functionDescriptor);
if (DeprecationUtilKt.isAnnotatedAsHidden(functionDescriptor)
if (DeprecationUtilKt.isHiddenInResolution(functionDescriptor)
|| functionDescriptor instanceof PropertyAccessorDescriptor
&& DeprecationUtilKt.isAnnotatedAsHidden(((PropertyAccessorDescriptor) functionDescriptor).getCorrespondingProperty())) {
&& DeprecationUtilKt.isHiddenInResolution(((PropertyAccessorDescriptor) functionDescriptor).getCorrespondingProperty())) {
flags |= ACC_SYNTHETIC;
}
return flags;
@@ -325,9 +325,6 @@ public class AsmUtil {
private static Integer specialCaseVisibility(@NotNull MemberDescriptor memberDescriptor) {
DeclarationDescriptor containingDeclaration = memberDescriptor.getContainingDeclaration();
Visibility memberVisibility = memberDescriptor.getVisibility();
if (isJvmInterface(containingDeclaration)) {
return memberVisibility == Visibilities.PRIVATE ? NO_FLAG_PACKAGE_PRIVATE : ACC_PUBLIC;
}
if (memberVisibility == Visibilities.LOCAL && memberDescriptor instanceof CallableMemberDescriptor) {
return ACC_PUBLIC;
@@ -379,11 +376,6 @@ public class AsmUtil {
}
}
if (memberDescriptor instanceof PropertyDescriptor &&
((PropertyDescriptor) memberDescriptor).isConst() || hasJvmFieldAnnotation(memberDescriptor)) {
return null;
}
return null;
}

View File

@@ -90,7 +90,7 @@ public class CallBasedArgumentGenerator extends ArgumentGenerator {
}
@Override
protected void reorderArgumentsIfNeeded(@NotNull List actualArgsWithDeclIndex) {
protected void reorderArgumentsIfNeeded(@NotNull List<ArgumentAndDeclIndex> actualArgsWithDeclIndex) {
callGenerator.reorderArgumentsIfNeeded(actualArgsWithDeclIndex, valueParameterTypes);
}
}

View File

@@ -26,6 +26,7 @@ import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.DescriptorUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -51,11 +52,19 @@ public abstract class ClassBodyCodegen extends MemberCodegen<KtClassOrObject> {
@Override
protected void generateBody() {
List<KtObjectDeclaration> companions = new ArrayList<KtObjectDeclaration>();
if (kind != OwnerKind.DEFAULT_IMPLS) {
//generate nested classes first and only then generate class body. It necessary to access to nested CodegenContexts
for (KtDeclaration declaration : myClass.getDeclarations()) {
if (shouldProcessFirst(declaration)) {
generateDeclaration(declaration);
//Generate companions after class body generation (need to record all synthetic accessors)
if (declaration instanceof KtObjectDeclaration && ((KtObjectDeclaration) declaration).isCompanion()) {
companions.add((KtObjectDeclaration) declaration);
CodegenUtilKt.populateCompanionBackingFieldNamesToOuterContextIfNeeded((KtObjectDeclaration) declaration, context, state);
}
else {
generateDeclaration(declaration);
}
}
}
}
@@ -66,6 +75,14 @@ public abstract class ClassBodyCodegen extends MemberCodegen<KtClassOrObject> {
}
}
generatePrimaryConstructorProperties();
generateConstructors();
generateDefaultImplsIfNeeded();
for (KtObjectDeclaration companion : companions) {
generateDeclaration(companion);
}
if (!DescriptorUtils.isInterface(descriptor)) {
for (DeclarationDescriptor memberDescriptor : DescriptorUtils.getAllDescriptors(descriptor.getDefaultType().getMemberScope())) {
if (memberDescriptor instanceof CallableMemberDescriptor) {
@@ -88,8 +105,14 @@ public abstract class ClassBodyCodegen extends MemberCodegen<KtClassOrObject> {
}
}
}
}
protected void generateConstructors() {
}
protected void generateDefaultImplsIfNeeded() {
generatePrimaryConstructorProperties();
}
private static boolean shouldProcessFirst(KtDeclaration declaration) {

View File

@@ -57,7 +57,6 @@ import org.jetbrains.kotlin.lexer.KtTokens;
import org.jetbrains.kotlin.load.java.descriptors.SamConstructorDescriptor;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.renderer.DescriptorRenderer;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.BindingContextUtils;
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils;
@@ -669,7 +668,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
});
}
else {
KtMultiDeclaration multiParameter = forExpression.getMultiParameter();
KtDestructuringDeclaration multiParameter = forExpression.getDestructuringParameter();
assert multiParameter != null;
// E tmp<e> = tmp<iterator>.next()
@@ -687,15 +686,15 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
assignToLoopParameter();
if (forExpression.getLoopParameter() == null) {
KtMultiDeclaration multiParameter = forExpression.getMultiParameter();
KtDestructuringDeclaration multiParameter = forExpression.getDestructuringParameter();
assert multiParameter != null;
generateMultiVariables(multiParameter.getEntries());
}
}
private void generateMultiVariables(List<KtMultiDeclarationEntry> entries) {
for (KtMultiDeclarationEntry variableDeclaration : entries) {
private void generateMultiVariables(List<KtDestructuringDeclarationEntry> entries) {
for (KtDestructuringDeclarationEntry variableDeclaration : entries) {
final VariableDescriptor componentDescriptor = bindingContext.get(VARIABLE, variableDeclaration);
@SuppressWarnings("ConstantConditions") final Type componentAsmType = asmType(componentDescriptor.getReturnType());
@@ -1332,7 +1331,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
@Override
public StackValue visitFunctionLiteralExpression(@NotNull KtFunctionLiteralExpression expression, StackValue receiver) {
public StackValue visitLambdaExpression(@NotNull KtLambdaExpression expression, StackValue receiver) {
if (Boolean.TRUE.equals(bindingContext.get(BLOCK, expression))) {
return gen(expression.getFunctionLiteral().getBodyExpression());
}
@@ -1569,9 +1568,9 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
private void putDescriptorIntoFrameMap(@NotNull KtElement statement) {
if (statement instanceof KtMultiDeclaration) {
KtMultiDeclaration multiDeclaration = (KtMultiDeclaration) statement;
for (KtMultiDeclarationEntry entry : multiDeclaration.getEntries()) {
if (statement instanceof KtDestructuringDeclaration) {
KtDestructuringDeclaration multiDeclaration = (KtDestructuringDeclaration) statement;
for (KtDestructuringDeclarationEntry entry : multiDeclaration.getEntries()) {
putLocalVariableIntoFrameMap(entry);
}
}
@@ -1609,9 +1608,9 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@NotNull Label blockEnd,
@NotNull List<Function<StackValue, Void>> leaveTasks
) {
if (statement instanceof KtMultiDeclaration) {
KtMultiDeclaration multiDeclaration = (KtMultiDeclaration) statement;
for (KtMultiDeclarationEntry entry : multiDeclaration.getEntries()) {
if (statement instanceof KtDestructuringDeclaration) {
KtDestructuringDeclaration multiDeclaration = (KtDestructuringDeclaration) statement;
for (KtDestructuringDeclarationEntry entry : multiDeclaration.getEntries()) {
addLeaveTaskToRemoveLocalVariableFromFrameMap(entry, blockEnd, leaveTasks);
}
}
@@ -2072,7 +2071,10 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
PropertyGetterDescriptor getter = descriptor.getGetter();
if (getter != null) {
Call call = bindingContext.get(DELEGATED_PROPERTY_CALL, getter);
return call != null ? ((ReceiverValue) call.getExplicitReceiver()).getType() : null;
if (call != null) {
assert call.getExplicitReceiver() != null : "No explicit receiver for call:" + call;
return ((ReceiverValue) call.getExplicitReceiver()).getType();
}
}
return null;
}
@@ -2120,7 +2122,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
if (isBackingFieldInClassCompanion && forceField) {
fieldAccessorKind = FieldAccessorKind.IN_CLASS_COMPANION;
}
else if (syntheticBackingField && context.getParentContext().getContextDescriptor() != containingDeclaration) {
else if (syntheticBackingField && context.getFirstCrossInlineOrNonInlineContext().getParentContext().getContextDescriptor() != containingDeclaration) {
fieldAccessorKind = FieldAccessorKind.FIELD_FROM_LOCAL;
}
boolean isStaticBackingField = DescriptorUtils.isStaticDeclaration(propertyDescriptor) ||
@@ -2161,13 +2163,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
if (!skipPropertyAccessors) {
if (!couldUseDirectAccessToProperty(propertyDescriptor, true, isDelegatedProperty, context)) {
if (isSuper && !isJvmInterface(containingDeclaration)) {
CodegenContext c = context.findParentContextWithDescriptor(superCallTarget);
assert c != null : "Couldn't find a context for a super-call: " + propertyDescriptor;
if (c != context.getParentContext()) {
propertyDescriptor = (PropertyDescriptor) c.getAccessor(propertyDescriptor, superCallTarget);
}
}
propertyDescriptor = context.getAccessorForSuperCallIfNeeded(propertyDescriptor, superCallTarget);
propertyDescriptor = context.accessibleDescriptor(propertyDescriptor, superCallTarget);
@@ -2251,8 +2247,8 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
final SamType samType = bindingContext.get(SAM_VALUE, probablyParenthesizedExpression);
if (samType == null || expression == null) return null;
if (expression instanceof KtFunctionLiteralExpression) {
return genClosure(((KtFunctionLiteralExpression) expression).getFunctionLiteral(), samType);
if (expression instanceof KtLambdaExpression) {
return genClosure(((KtLambdaExpression) expression).getFunctionLiteral(), samType);
}
if (expression instanceof KtNamedFunction) {
@@ -2300,22 +2296,11 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
descriptor = originalIfSamAdapter;
}
// $default method is not private, so you need no accessor to call it
return usesDefaultArguments(resolvedCall)
return CallUtilKt.usesDefaultArguments(resolvedCall)
? descriptor
: context.accessibleDescriptor(descriptor, getSuperCallTarget(resolvedCall.getCall()));
}
private static boolean usesDefaultArguments(@NotNull ResolvedCall<?> resolvedCall) {
List<ResolvedValueArgument> valueArguments = resolvedCall.getValueArgumentsByIndex();
if (valueArguments == null) return false;
for (ResolvedValueArgument argument : valueArguments) {
if (argument instanceof DefaultValueArgument) return true;
}
return false;
}
@NotNull
public StackValue invokeFunction(@NotNull ResolvedCall<?> resolvedCall, @NotNull StackValue receiver) {
return invokeFunction(resolvedCall.getCall(), resolvedCall, receiver);
@@ -2325,15 +2310,8 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
public StackValue invokeFunction(@NotNull Call call, @NotNull ResolvedCall<?> resolvedCall, @NotNull StackValue receiver) {
FunctionDescriptor fd = accessibleFunctionDescriptor(resolvedCall);
ClassDescriptor superCallTarget = getSuperCallTarget(call);
boolean superCall = superCallTarget != null;
if (superCall && !isJvmInterface(fd.getContainingDeclaration())) {
CodegenContext c = context.findParentContextWithDescriptor(superCallTarget);
assert c != null : "Couldn't find a context for a super-call: " + fd;
if (c != context.getParentContext()) {
fd = (FunctionDescriptor) c.getAccessor(fd, superCallTarget);
}
}
fd = context.getAccessorForSuperCallIfNeeded(fd, superCallTarget);
Collection<ExpressionCodegenExtension> codegenExtensions = ExpressionCodegenExtension.Companion.getInstances(state.getProject());
if (!codegenExtensions.isEmpty()) {
@@ -2344,7 +2322,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
}
Callable callable = resolveToCallable(fd, superCall, resolvedCall);
Callable callable = resolveToCallable(fd, superCallTarget != null, resolvedCall);
return callable.invokeMethodWithArguments(resolvedCall, receiver, this);
}
@@ -2433,6 +2411,12 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
callGenerator.genCall(callableMethod, resolvedCall, defaultMaskWasGenerated, this);
KotlinType returnType = resolvedCall.getResultingDescriptor().getReturnType();
if (returnType != null && KotlinBuiltIns.isNothing(returnType)) {
v.aconst(null);
v.athrow();
}
}
@NotNull
@@ -2483,9 +2467,8 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
else {
mappings.addParameterMappingToNewParameter(
key.getName().getIdentifier(),
parameterDescriptor.getName().getIdentifier()
);
key.getName().getIdentifier(), type,
parameterDescriptor.getName().getIdentifier());
}
}
return getOrCreateCallGenerator(
@@ -2494,7 +2477,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
@NotNull
public StackValue generateReceiverValue(@NotNull ReceiverValue receiverValue, boolean isSuper) {
public StackValue generateReceiverValue(@Nullable ReceiverValue receiverValue, boolean isSuper) {
if (receiverValue instanceof ImplicitClassReceiver) {
ClassDescriptor receiverDescriptor = ((ImplicitClassReceiver) receiverValue).getDeclarationDescriptor();
if (DescriptorUtils.isCompanionObject(receiverDescriptor)) {
@@ -2758,7 +2741,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@NotNull KtElement element,
@NotNull VariableDescriptor variableDescriptor,
@NotNull VariableDescriptor target,
@NotNull ReceiverValue dispatchReceiver
@Nullable ReceiverValue dispatchReceiver
) {
ClassDescriptor classDescriptor = CodegenBinding.anonymousClassForCallable(bindingContext, variableDescriptor);
@@ -3276,7 +3259,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
@Override
public StackValue visitMultiDeclaration(@NotNull KtMultiDeclaration multiDeclaration, StackValue receiver) {
public StackValue visitDestructuringDeclaration(@NotNull KtDestructuringDeclaration multiDeclaration, StackValue receiver) {
KtExpression initializer = multiDeclaration.getInitializer();
if (initializer == null) return StackValue.none();
@@ -3293,7 +3276,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
v.store(tempVarIndex, initializerAsmType);
StackValue.Local local = StackValue.local(tempVarIndex, initializerAsmType);
for (KtMultiDeclarationEntry variableDeclaration : multiDeclaration.getEntries()) {
for (KtDestructuringDeclarationEntry variableDeclaration : multiDeclaration.getEntries()) {
ResolvedCall<FunctionDescriptor> resolvedCall = bindingContext.get(COMPONENT_RESOLVED_CALL, variableDeclaration);
assert resolvedCall != null : "Resolved call is null for " + variableDeclaration.getText();
Call call = makeFakeCall(initializerAsReceiver);
@@ -3689,13 +3672,8 @@ The "returned" value of try expression with no finally is either the last expres
}
if (opToken != KtTokens.AS_SAFE) {
if (!TypeUtils.isNullableType(rightType)) {
v.dup();
Label nonnull = new Label();
v.ifnonnull(nonnull);
genThrow(v, "kotlin/TypeCastException", "null cannot be cast to non-null type " +
DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(rightType));
v.mark(nonnull);
if (!TypeUtils.isNullableType(rightType) && !TypeUtils.isReifiedTypeParameter(rightType)) {
CodegenUtilKt.generateNullCheckForNonSafeAs(v, rightType);
}
}
else {
@@ -3759,7 +3737,7 @@ The "returned" value of try expression with no finally is either the last expres
if (leaveExpressionOnStack) {
v.dup();
}
CodegenUtilKt.generateIsCheck(v, kotlinType, new Function1<InstructionAdapter, Unit>() {
CodegenUtilKt.generateIsCheck(v, kotlinType.isMarkedNullable() && !TypeUtils.isReifiedTypeParameter(kotlinType), new Function1<InstructionAdapter, Unit>() {
@Override
public Unit invoke(InstructionAdapter adapter) {
generateInstanceOfInstruction(kotlinType);
@@ -3794,8 +3772,8 @@ The "returned" value of try expression with no finally is either the last expres
parentCodegen.getReifiedTypeParametersUsages().
addUsedReifiedParameter(typeParameterDescriptor.getName().asString());
}
v.visitLdcInsn(typeParameterDescriptor.getName().asString());
boolean putNullableFlag = ReifiedTypeInliner.isNullableMarkerInstruction(markerMethodName) && type.isMarkedNullable();
v.visitLdcInsn(typeParameterDescriptor.getName().asString() + (putNullableFlag ? "?" : ""));
v.invokestatic(
IntrinsicMethods.INTRINSICS_CLASS_NAME, markerMethodName,
Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class)), false
@@ -3821,8 +3799,9 @@ The "returned" value of try expression with no finally is either the last expres
return StackValue.operation(resultType, new Function1<InstructionAdapter, Unit>() {
@Override
public Unit invoke(InstructionAdapter v) {
SwitchCodegen switchCodegen =
SwitchCodegenUtil.buildAppropriateSwitchCodegenIfPossible(expression, isStatement, ExpressionCodegen.this);
SwitchCodegen switchCodegen = SwitchCodegenUtil.buildAppropriateSwitchCodegenIfPossible(
expression, isStatement, isExhaustive(expression, isStatement), ExpressionCodegen.this
);
if (switchCodegen != null) {
switchCodegen.generate();
return Unit.INSTANCE$;
@@ -3868,9 +3847,7 @@ The "returned" value of try expression with no finally is either the last expres
}
if (!hasElse && nextCondition != null) {
v.mark(nextCondition);
if (!isStatement) {
putUnitInstanceOntoStackForNonExhaustiveWhen(expression);
}
putUnitInstanceOntoStackForNonExhaustiveWhen(expression, isStatement);
}
markLineNumber(expression, isStatement);
@@ -3883,14 +3860,24 @@ The "returned" value of try expression with no finally is either the last expres
});
}
private boolean isExhaustive(@NotNull KtWhenExpression whenExpression, boolean isStatement) {
if (isStatement) {
return Boolean.TRUE.equals(bindingContext.get(BindingContext.IMPLICIT_EXHAUSTIVE_WHEN, whenExpression));
}
else {
return Boolean.TRUE.equals(bindingContext.get(BindingContext.EXHAUSTIVE_WHEN, whenExpression));
}
}
public void putUnitInstanceOntoStackForNonExhaustiveWhen(
@NotNull KtWhenExpression expression
@NotNull KtWhenExpression whenExpression,
boolean isStatement
) {
if (Boolean.TRUE.equals(bindingContext.get(BindingContext.EXHAUSTIVE_WHEN, expression))) {
if (isExhaustive(whenExpression, isStatement)) {
// when() is supposed to be exhaustive
genThrow(v, "kotlin/NoWhenBranchMatchedException", null);
}
else {
else if (!isStatement) {
// non-exhaustive when() with no else -> Unit must be expected
StackValue.putUnitInstance(v);
}

View File

@@ -221,8 +221,6 @@ public class FunctionCodegen {
}
endVisit(mv, null, origin.getElement());
methodContext.recordSyntheticAccessorIfNeeded(functionDescriptor, bindingContext);
}
private void generateMethodAnnotations(
@@ -373,11 +371,11 @@ public class FunctionCodegen {
else {
FrameMap frameMap = createFrameMap(parentCodegen.state, functionDescriptor, signature, isStaticMethod(context.getContextKind(),
functionDescriptor));
if (context.isInlineFunction()) {
if (context.isInlineMethodContext()) {
functionFakeIndex = frameMap.enterTemp(Type.INT_TYPE);
}
if (context.isInliningLambda()) {
if (context instanceof InlineLambdaContext) {
lambdaFakeIndex = frameMap.enterTemp(Type.INT_TYPE);
}
@@ -398,7 +396,7 @@ public class FunctionCodegen {
Type thisType = getThisTypeForFunction(functionDescriptor, context, typeMapper);
generateLocalVariableTable(mv, signature, functionDescriptor, thisType, methodBegin, methodEnd, context.getContextKind());
if (context.isInlineFunction() && functionFakeIndex != -1) {
if (context.isInlineMethodContext() && functionFakeIndex != -1) {
mv.visitLocalVariable(
JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION + functionDescriptor.getName().asString(),
Type.INT_TYPE.getDescriptor(), null,
@@ -406,7 +404,7 @@ public class FunctionCodegen {
functionFakeIndex);
}
if (context.isInliningLambda() && thisType != null && lambdaFakeIndex != -1) {
if (context instanceof InlineLambdaContext && thisType != null && lambdaFakeIndex != -1) {
String name = thisType.getClassName();
int indexOfLambdaOrdinal = name.lastIndexOf("$");
if (indexOfLambdaOrdinal > 0) {
@@ -555,7 +553,7 @@ public class FunctionCodegen {
// If the function doesn't have a physical declaration among super-functions, it's a SAM adapter or alike and doesn't need bridges
if (CallResolverUtilKt.isOrOverridesSynthesized(descriptor)) return;
boolean isSpecial = SpecialBuiltinMembers.getOverriddenBuiltinWithDifferentJvmDescriptor(descriptor) != null;
boolean isSpecial = SpecialBuiltinMembers.getOverriddenBuiltinReflectingJvmDescriptor(descriptor) != null;
Set<Bridge<Method>> bridgesToGenerate;
if (!isSpecial) {
@@ -589,7 +587,7 @@ public class FunctionCodegen {
}
if (!descriptor.getKind().isReal() && isAbstractMethod(descriptor, OwnerKind.IMPLEMENTATION)) {
CallableDescriptor overridden = SpecialBuiltinMembers.getOverriddenBuiltinWithDifferentJvmDescriptor(descriptor);
CallableDescriptor overridden = SpecialBuiltinMembers.getOverriddenBuiltinReflectingJvmDescriptor(descriptor);
assert overridden != null;
Method method = typeMapper.mapSignature(descriptor).getAsmMethod();
@@ -911,7 +909,7 @@ public class FunctionCodegen {
iv.ifnonnull(afterBarrier);
}
else {
CodegenUtilKt.generateIsCheck(iv, kotlinType, new Function1<InstructionAdapter, Unit>() {
CodegenUtilKt.generateIsCheck(iv, kotlinType.isMarkedNullable(), new Function1<InstructionAdapter, Unit>() {
@Override
public Unit invoke(InstructionAdapter adapter) {
TypeIntrinsics.instanceOf(adapter, kotlinType, boxType(delegateParameterType));

View File

@@ -36,8 +36,6 @@ import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
import java.util.*;
import static org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue.NO_RECEIVER;
public class FunctionReferenceGenerationStrategy extends FunctionGenerationStrategy.CodegenBased<FunctionDescriptor> {
private final ResolvedCall<?> resolvedCall;
private final FunctionDescriptor referencedFunction;
@@ -82,13 +80,13 @@ public class FunctionReferenceGenerationStrategy extends FunctionGenerationStrat
}
}
@NotNull
@Nullable
@Override
public ReceiverValue getExtensionReceiver() {
return extensionReceiver;
}
@NotNull
@Nullable
@Override
public ReceiverValue getDispatchReceiver() {
return dispatchReceiver;
@@ -119,7 +117,7 @@ public class FunctionReferenceGenerationStrategy extends FunctionGenerationStrat
}
}
else {
Call call = CallMaker.makeCall(fakeExpression, NO_RECEIVER, null, fakeExpression, fakeArguments);
Call call = CallMaker.makeCall(fakeExpression, null, null, fakeExpression, fakeArguments);
result = codegen.invokeFunction(call, fakeResolvedCall, StackValue.none());
}
@@ -157,13 +155,13 @@ public class FunctionReferenceGenerationStrategy extends FunctionGenerationStrat
}
}
@NotNull
@Nullable
private ReceiverValue computeAndSaveReceiver(
@NotNull JvmMethodSignature signature,
@NotNull ExpressionCodegen codegen,
@Nullable ReceiverParameterDescriptor receiver
) {
if (receiver == null) return NO_RECEIVER;
if (receiver == null) return null;
KtExpression receiverExpression = KtPsiFactoryKt
.KtPsiFactory(state.getProject()).createExpression("callableReferenceFakeReceiver");

View File

@@ -98,6 +98,8 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
private List<PropertyAndDefaultValue> companionObjectPropertiesToCopy;
private final DelegationFieldsInfo delegationFieldsInfo;
private final List<Function2<ImplementationBodyCodegen, ClassBuilder, Unit>> additionalTasks =
new ArrayList<Function2<ImplementationBodyCodegen, ClassBuilder, Unit>>();
@@ -112,6 +114,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
super(aClass, context, v, state, parentCodegen);
this.classAsmType = typeMapper.mapClass(descriptor);
this.isLocal = isLocal;
delegationFieldsInfo = getDelegationFieldsInfo(myClass.getSuperTypeListEntries());
}
@Override
@@ -227,8 +230,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
@Override
protected void generateBody() {
super.generateBody();
protected void generateDefaultImplsIfNeeded() {
if (isInterface(descriptor) && !isLocal) {
Type defaultImplsType = state.getTypeMapper().mapDefaultImpls(descriptor);
ClassBuilder defaultImplsBuilder =
@@ -237,7 +239,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
CodegenContext parentContext = context.getParentContext();
assert parentContext != null : "Parent context of interface declaration should not be null";
ClassContext defaultImplsContext = parentContext.intoClass(descriptor, OwnerKind.DEFAULT_IMPLS, state);
ClassContext defaultImplsContext = parentContext.intoDefaultImplsClass(descriptor, (ClassContext) context, state);
new InterfaceImplBodyCodegen(myClass, defaultImplsContext, defaultImplsBuilder, state, this).generate();
}
}
@@ -371,7 +373,31 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
generateCompanionObjectBackingFieldCopies();
DelegationFieldsInfo delegationFieldsInfo = getDelegationFieldsInfo(myClass.getDelegationSpecifiers());
generateTraitMethods();
generateDelegates(delegationFieldsInfo);
if (!isInterface(descriptor) || kind == OwnerKind.DEFAULT_IMPLS) {
generateSyntheticAccessors();
}
generateEnumMethods();
generateFunctionsForDataClasses();
new CollectionStubMethodGenerator(state, descriptor, functionCodegen, v).generate();
generateToArray();
genClosureFields(context.closure, v, typeMapper);
for (ExpressionCodegenExtension extension : ExpressionCodegenExtension.Companion.getInstances(state.getProject())) {
extension.generateClassSyntheticParts(v, state, myClass, descriptor);
}
}
@Override
protected void generateConstructors() {
try {
lookupConstructorExpressionsInClosureIfPresent();
generatePrimaryConstructor(delegationFieldsInfo);
@@ -388,26 +414,6 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
catch (RuntimeException e) {
throw new RuntimeException("Error generating constructors of class " + myClass.getName() + " with kind " + kind, e);
}
generateTraitMethods();
generateDelegates(delegationFieldsInfo);
generateSyntheticAccessors();
generateEnumMethods();
generateFunctionsForDataClasses();
new CollectionStubMethodGenerator(state, descriptor, functionCodegen, v).generate();
generateToArray();
genClosureFields(context.closure, v, typeMapper);
for (ExpressionCodegenExtension extension : ExpressionCodegenExtension.Companion.getInstances(state.getProject())) {
extension.generateClassSyntheticParts(v, state, myClass, descriptor);
}
}
private boolean isGenericToArrayPresent() {
@@ -958,10 +964,6 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
DefaultParameterValueLoader.DEFAULT, null);
new DefaultParameterValueSubstitutor(state).generatePrimaryConstructorOverloadsIfNeeded(constructorDescriptor, v, kind, myClass);
if (isCompanionObject(descriptor)) {
context.recordSyntheticAccessorIfNeeded(constructorDescriptor, bindingContext);
}
}
private void generateSecondaryConstructor(@NotNull ConstructorDescriptor constructorDescriptor) {
@@ -1012,9 +1014,9 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
}
for (KtDelegationSpecifier specifier : myClass.getDelegationSpecifiers()) {
if (specifier instanceof KtDelegatorByExpressionSpecifier) {
genCallToDelegatorByExpressionSpecifier(iv, codegen, (KtDelegatorByExpressionSpecifier) specifier, fieldsInfo);
for (KtSuperTypeListEntry specifier : myClass.getSuperTypeListEntries()) {
if (specifier instanceof KtDelegatedSuperTypeEntry) {
genCallToDelegatorByExpressionSpecifier(iv, codegen, (KtDelegatedSuperTypeEntry) specifier, fieldsInfo);
}
}
@@ -1153,41 +1155,41 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
return StackValue.field(type, classAsmType, name, false, StackValue.none());
}
}
private final Map<KtDelegatorByExpressionSpecifier, Field> fields = new HashMap<KtDelegatorByExpressionSpecifier, Field>();
private final Map<KtDelegatedSuperTypeEntry, Field> fields = new HashMap<KtDelegatedSuperTypeEntry, Field>();
@NotNull
public Field getInfo(KtDelegatorByExpressionSpecifier specifier) {
public Field getInfo(KtDelegatedSuperTypeEntry specifier) {
return fields.get(specifier);
}
private void addField(KtDelegatorByExpressionSpecifier specifier, PropertyDescriptor propertyDescriptor) {
private void addField(KtDelegatedSuperTypeEntry specifier, PropertyDescriptor propertyDescriptor) {
fields.put(specifier,
new Field(typeMapper.mapType(propertyDescriptor), propertyDescriptor.getName().asString(), false));
}
private void addField(KtDelegatorByExpressionSpecifier specifier, Type type, String name) {
private void addField(KtDelegatedSuperTypeEntry specifier, Type type, String name) {
fields.put(specifier, new Field(type, name, true));
}
}
@NotNull
private DelegationFieldsInfo getDelegationFieldsInfo(@NotNull List<KtDelegationSpecifier> delegationSpecifiers) {
private DelegationFieldsInfo getDelegationFieldsInfo(@NotNull List<KtSuperTypeListEntry> delegationSpecifiers) {
DelegationFieldsInfo result = new DelegationFieldsInfo();
int n = 0;
for (KtDelegationSpecifier specifier : delegationSpecifiers) {
if (specifier instanceof KtDelegatorByExpressionSpecifier) {
KtExpression expression = ((KtDelegatorByExpressionSpecifier) specifier).getDelegateExpression();
for (KtSuperTypeListEntry specifier : delegationSpecifiers) {
if (specifier instanceof KtDelegatedSuperTypeEntry) {
KtExpression expression = ((KtDelegatedSuperTypeEntry) specifier).getDelegateExpression();
PropertyDescriptor propertyDescriptor = CodegenUtil.getDelegatePropertyIfAny(expression, descriptor, bindingContext);
if (CodegenUtil.isFinalPropertyWithBackingField(propertyDescriptor, bindingContext)) {
result.addField((KtDelegatorByExpressionSpecifier) specifier, propertyDescriptor);
result.addField((KtDelegatedSuperTypeEntry) specifier, propertyDescriptor);
}
else {
KotlinType expressionType = expression != null ? bindingContext.getType(expression) : null;
Type asmType =
expressionType != null ? typeMapper.mapType(expressionType) : typeMapper.mapType(getSuperClass(specifier));
result.addField((KtDelegatorByExpressionSpecifier) specifier, asmType, "$delegate_" + n);
result.addField((KtDelegatedSuperTypeEntry) specifier, asmType, "$delegate_" + n);
}
n++;
}
@@ -1196,14 +1198,14 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
@NotNull
private ClassDescriptor getSuperClass(@NotNull KtDelegationSpecifier specifier) {
return CodegenUtil.getSuperClassByDelegationSpecifier(specifier, bindingContext);
private ClassDescriptor getSuperClass(@NotNull KtSuperTypeListEntry specifier) {
return CodegenUtil.getSuperClassBySuperTypeListEntry(specifier, bindingContext);
}
private void genCallToDelegatorByExpressionSpecifier(
InstructionAdapter iv,
ExpressionCodegen codegen,
KtDelegatorByExpressionSpecifier specifier,
KtDelegatedSuperTypeEntry specifier,
DelegationFieldsInfo fieldsInfo
) {
KtExpression expression = specifier.getDelegateExpression();
@@ -1248,7 +1250,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
}
private void lookupReceiver(@NotNull ReceiverValue value) {
private void lookupReceiver(@Nullable ReceiverValue value) {
if (value instanceof ImplicitReceiver) {
if (value instanceof ExtensionReceiver) {
ReceiverParameterDescriptor parameter =
@@ -1303,9 +1305,9 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
}
for (KtDelegationSpecifier specifier : myClass.getDelegationSpecifiers()) {
if (specifier instanceof KtDelegatorByExpressionSpecifier) {
KtExpression delegateExpression = ((KtDelegatorByExpressionSpecifier) specifier).getDelegateExpression();
for (KtSuperTypeListEntry specifier : myClass.getSuperTypeListEntries()) {
if (specifier instanceof KtDelegatedSuperTypeEntry) {
KtExpression delegateExpression = ((KtDelegatedSuperTypeEntry) specifier).getDelegateExpression();
assert delegateExpression != null;
delegateExpression.accept(visitor);
}
@@ -1331,7 +1333,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
private void generateTraitMethods() {
if (isInterface(descriptor)) return;
for (Map.Entry<FunctionDescriptor, FunctionDescriptor> entry : CodegenUtil.getTraitMethods(descriptor).entrySet()) {
for (Map.Entry<FunctionDescriptor, FunctionDescriptor> entry : CodegenUtil.getNonPrivateTraitMethods(descriptor).entrySet()) {
FunctionDescriptor traitFun = entry.getKey();
//skip java 8 default methods
if (!(traitFun instanceof JavaCallableMemberDescriptor)) {
@@ -1559,7 +1561,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
@Override
protected void reorderArgumentsIfNeeded(@NotNull List args) {
protected void reorderArgumentsIfNeeded(@NotNull List<ArgumentAndDeclIndex> args) {
}
}
@@ -1571,7 +1573,8 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
for (KtEnumEntry enumEntry : enumEntries) {
ClassDescriptor descriptor = getNotNull(bindingContext, BindingContext.CLASS, enumEntry);
FieldVisitor fv = v.newField(JvmDeclarationOriginKt.OtherOrigin(enumEntry, descriptor), ACC_PUBLIC | ACC_ENUM | ACC_STATIC | ACC_FINAL,
int isDeprecated = KotlinBuiltIns.isDeprecated(descriptor) ? ACC_DEPRECATED : 0;
FieldVisitor fv = v.newField(JvmDeclarationOriginKt.OtherOrigin(enumEntry, descriptor), ACC_PUBLIC | ACC_ENUM | ACC_STATIC | ACC_FINAL | isDeprecated,
descriptor.getName().asString(), classAsmType.getDescriptor(), null, null);
AnnotationCodegen.forField(fv, typeMapper).genAnnotations(descriptor, null);
}
@@ -1619,7 +1622,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
iv.aconst(enumEntry.getName());
iv.iconst(ordinal);
List<KtDelegationSpecifier> delegationSpecifiers = enumEntry.getDelegationSpecifiers();
List<KtSuperTypeListEntry> delegationSpecifiers = enumEntry.getSuperTypeListEntries();
if (delegationSpecifiers.size() == 1 && !enumEntryNeedSubclass(bindingContext, enumEntry)) {
ResolvedCall<?> resolvedCall = CallUtilKt.getResolvedCallWithAssert(delegationSpecifiers.get(0), bindingContext);
@@ -1637,11 +1640,11 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
private void generateDelegates(DelegationFieldsInfo delegationFieldsInfo) {
for (KtDelegationSpecifier specifier : myClass.getDelegationSpecifiers()) {
if (specifier instanceof KtDelegatorByExpressionSpecifier) {
DelegationFieldsInfo.Field field = delegationFieldsInfo.getInfo((KtDelegatorByExpressionSpecifier) specifier);
for (KtSuperTypeListEntry specifier : myClass.getSuperTypeListEntries()) {
if (specifier instanceof KtDelegatedSuperTypeEntry) {
DelegationFieldsInfo.Field field = delegationFieldsInfo.getInfo((KtDelegatedSuperTypeEntry) specifier);
generateDelegateField(field);
KtExpression delegateExpression = ((KtDelegatorByExpressionSpecifier) specifier).getDelegateExpression();
KtExpression delegateExpression = ((KtDelegatedSuperTypeEntry) specifier).getDelegateExpression();
KotlinType delegateExpressionType = delegateExpression != null ? bindingContext.getType(delegateExpression) : null;
generateDelegates(getSuperClass(specifier), delegateExpressionType, field);
}

View File

@@ -51,7 +51,7 @@ public class InterfaceImplBodyCodegen(
override fun generateDeclaration() {
v.defineClass(
myClass, V1_6, ACC_PUBLIC or ACC_FINAL,
myClass, V1_6, ACC_PUBLIC or ACC_FINAL or ACC_SUPER,
typeMapper.mapDefaultImpls(descriptor).internalName,
null, "java/lang/Object", ArrayUtil.EMPTY_STRING_ARRAY
)
@@ -63,7 +63,7 @@ public class InterfaceImplBodyCodegen(
if (DescriptorUtils.isLocal(descriptor)) return null
val classDescriptorImpl = ClassDescriptorImpl(
descriptor, Name.identifier(JvmAbi.DEFAULT_IMPLS_CLASS_NAME),
Modality.FINAL, Collections.emptyList(), SourceElement.NO_SOURCE)
Modality.FINAL, ClassKind.CLASS, Collections.emptyList(), SourceElement.NO_SOURCE)
classDescriptorImpl.initialize(MemberScope.Empty, emptySet(), null)
return classDescriptorImpl
@@ -103,6 +103,8 @@ public class InterfaceImplBodyCodegen(
}
}
}
generateSyntheticAccessors()
}
private fun generateDelegationToSuperTraitImpl(descriptor: FunctionDescriptor, implementation: FunctionDescriptor) {

View File

@@ -134,12 +134,13 @@ public class JvmCodegenUtil {
@NotNull PropertyDescriptor property,
boolean forGetter,
boolean isDelegated,
@NotNull MethodContext context
@NotNull MethodContext contextBeforeInline
) {
if (JetTypeMapper.isAccessor(property)) return false;
CodegenContext context = contextBeforeInline.getFirstCrossInlineOrNonInlineContext();
// Inline functions can't use direct access because a field may not be visible at the call site
if (context.isInlineFunction()) {
if (context.isInlineMethodContext()) {
return false;
}
@@ -164,7 +165,7 @@ public class JvmCodegenUtil {
return Visibilities.isPrivate(property.getVisibility()) || accessor.getModality() == FINAL;
}
private static boolean isDebuggerContext(@NotNull MethodContext context) {
private static boolean isDebuggerContext(@NotNull CodegenContext context) {
KtFile file = DescriptorToSourceUtils.getContainingFile(context.getContextDescriptor());
return file != null && CodeFragmentUtilKt.getSuppressDiagnosticsInDebugMode(file);
}

View File

@@ -46,7 +46,6 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt;
import org.jetbrains.kotlin.resolve.jvm.AsmTypes;
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKt;
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature;
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue;
import org.jetbrains.kotlin.resolve.scopes.receivers.TransientReceiver;
import org.jetbrains.kotlin.resolve.source.KotlinSourceElementKt;
import org.jetbrains.kotlin.storage.LockBasedStorageManager;
@@ -65,8 +64,7 @@ import static org.jetbrains.kotlin.codegen.AsmUtil.calculateInnerClassAccessFlag
import static org.jetbrains.kotlin.codegen.AsmUtil.isPrimitive;
import static org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.SYNTHESIZED;
import static org.jetbrains.kotlin.resolve.BindingContext.VARIABLE;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.isCompanionObject;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.isStaticDeclaration;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.*;
import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.*;
import static org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin.NO_ORIGIN;
import static org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKt.Synthetic;
@@ -281,7 +279,8 @@ public abstract class MemberCodegen<T extends KtElement/* TODO: & JetDeclaration
protected void writeOuterClassAndEnclosingMethod() {
CodegenContext context = this.context.getParentContext();
while (context instanceof MethodContext && ((MethodContext) context).isInliningLambda()) {
while (context instanceof InlineLambdaContext) {
// If this is a lambda which will be inlined, skip its MethodContext and enclosing ClosureContext
//noinspection ConstantConditions
context = context.getParentContext().getParentContext();
@@ -525,7 +524,7 @@ public abstract class MemberCodegen<T extends KtElement/* TODO: & JetDeclaration
//noinspection ConstantConditions
value = createOrGetClInitCodegen().generatePropertyReference(
delegatedProperties.get(i).getDelegate(), property, property,
dispatchReceiver != null ? new TransientReceiver(dispatchReceiver.getType()) : ReceiverValue.NO_RECEIVER
dispatchReceiver != null ? new TransientReceiver(dispatchReceiver.getType()) : null
);
}
@@ -684,7 +683,7 @@ public abstract class MemberCodegen<T extends KtElement/* TODO: & JetDeclaration
((AccessorForCallableDescriptor) accessorDescriptor).getSuperCallTarget() != null
);
boolean hasDispatchReceiver = !isStaticDeclaration(functionDescriptor);
boolean hasDispatchReceiver = !isStaticDeclaration(functionDescriptor) && !isInterface(functionDescriptor.getContainingDeclaration());
int reg = hasDispatchReceiver ? 1 : 0;
boolean accessorIsConstructor = accessorDescriptor instanceof AccessorForConstructorDescriptor;
if (!accessorIsConstructor && functionDescriptor instanceof ConstructorDescriptor) {

View File

@@ -38,6 +38,7 @@ import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.MemberComparator
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import org.jetbrains.kotlin.resolve.jvm.diagnostics.MultifileClass
import org.jetbrains.kotlin.resolve.jvm.diagnostics.MultifileClassPart
import org.jetbrains.kotlin.resolve.jvm.diagnostics.OtherOrigin
@@ -50,6 +51,7 @@ import org.jetbrains.kotlin.serialization.deserialization.descriptors.Deserializ
import org.jetbrains.org.objectweb.asm.MethodVisitor
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
import java.util.*
public class MultifileClassCodegen(
@@ -86,12 +88,18 @@ public class MultifileClassCodegen(
val singleSourceFile = if (previouslyCompiledCallables.isNotEmpty()) null else filesWithCallables.singleOrNull()
classBuilder.defineClass(singleSourceFile, Opcodes.V1_6, FACADE_CLASS_ATTRIBUTES,
classBuilder.defineClass(singleSourceFile, Opcodes.V1_6,
if (state.generateOpenMultifileClasses) OPEN_FACADE_CLASS_ATTRIBUTES else FACADE_CLASS_ATTRIBUTES,
facadeClassType.internalName,
null, "java/lang/Object", ArrayUtil.EMPTY_STRING_ARRAY)
if (singleSourceFile != null) {
classBuilder.visitSource(singleSourceFile.name, null)
}
if (state.generateOpenMultifileClasses) {
generateMultifileFacadeClassConstructor(classBuilder, originFile)
}
classBuilder
}
@@ -148,6 +156,16 @@ public class MultifileClassCodegen(
MemberCodegen.genClassOrObject(packagePartContext, classOrObject, state, null)
}
private fun generateMultifileFacadeClassConstructor(classBuilder: ClassBuilder, originFile: KtFile?) {
val mv = classBuilder.newMethod(JvmDeclarationOrigin.NO_ORIGIN, Opcodes.ACC_PUBLIC, "<init>", "()V", null, null)
val v = InstructionAdapter(mv)
v.load(0, facadeClassType)
v.invokespecial("java/lang/Object", "<init>", "()V", false)
v.visitInsn(Opcodes.RETURN)
FunctionCodegen.endVisit(v, "multifile class constructor", originFile)
}
private fun generatePart(
file: KtFile,
generateCallableMemberTasks: MutableMap<CallableMemberDescriptor, () -> Unit>,
@@ -279,7 +297,8 @@ public class MultifileClassCodegen(
}
companion object {
private val FACADE_CLASS_ATTRIBUTES = Opcodes.ACC_PUBLIC or Opcodes.ACC_FINAL
private val FACADE_CLASS_ATTRIBUTES = Opcodes.ACC_PUBLIC or Opcodes.ACC_FINAL or Opcodes.ACC_SUPER
private val OPEN_FACADE_CLASS_ATTRIBUTES = Opcodes.ACC_PUBLIC or Opcodes.ACC_SUPER
private fun getOnlyPackageFragment(packageFqName: FqName, files: Collection<KtFile>, bindingContext: BindingContext): PackageFragmentDescriptor? {
val fragments = SmartList<PackageFragmentDescriptor>()

View File

@@ -46,7 +46,7 @@ public class MultifileClassPartCodegen(
override fun generateDeclaration() {
v.defineClass(element, Opcodes.V1_6,
Opcodes.ACC_FINAL or Opcodes.ACC_SYNTHETIC,
Opcodes.ACC_FINAL or Opcodes.ACC_SYNTHETIC or Opcodes.ACC_SUPER,
filePartType.internalName,
null,
"java/lang/Object",

View File

@@ -154,7 +154,7 @@ public class MutableClassDescriptor extends ClassDescriptorBase implements Class
this.typeConstructor = TypeConstructorImpl.createForClass(
this,
Annotations.Companion.getEMPTY(),
!getModality().isOverridable(),
ModalityKt.isFinalClass(this),
getName().asString(),
typeParameters,
supertypes

View File

@@ -63,7 +63,7 @@ public class PackagePartCodegen extends MemberCodegen<KtFile> {
@Override
protected void generateDeclaration() {
v.defineClass(element, V1_6,
ACC_PUBLIC | ACC_FINAL,
ACC_PUBLIC | ACC_FINAL | ACC_SUPER,
packagePartType.getInternalName(),
null,
"java/lang/Object",

View File

@@ -127,8 +127,6 @@ public class PropertyCodegen {
if (isAccessorNeeded(declaration, descriptor, setter)) {
generateSetter(declaration, descriptor, setter);
}
context.recordSyntheticAccessorIfNeeded(descriptor, bindingContext);
}
private void genBackingFieldAndAnnotations(@NotNull KtNamedDeclaration declaration, @NotNull PropertyDescriptor descriptor, boolean isParameter) {

View File

@@ -47,11 +47,11 @@ public class PropertyReferenceCodegen(
classBuilder: ClassBuilder,
private val classDescriptor: ClassDescriptor,
private val target: VariableDescriptor,
dispatchReceiver: ReceiverValue
dispatchReceiver: ReceiverValue?
) : MemberCodegen<KtElement>(state, parentCodegen, context, expression, classBuilder) {
private val asmType = typeMapper.mapClass(classDescriptor)
private val dispatchReceiverType = if (dispatchReceiver.exists()) dispatchReceiver.type else null
private val dispatchReceiverType = dispatchReceiver?.type
private val extensionReceiverType = target.extensionReceiverParameter?.type

View File

@@ -70,6 +70,7 @@ public class SamWrapperCodegen {
samType.getJavaClassDescriptor().getContainingDeclaration(),
fqName.shortName(),
Modality.FINAL,
ClassKind.CLASS,
Collections.singleton(samType.getType()),
SourceElement.NO_SOURCE
);
@@ -85,7 +86,7 @@ public class SamWrapperCodegen {
ClassBuilder cv = state.getFactory().newVisitor(JvmDeclarationOriginKt.OtherOrigin(erasedInterfaceFunction), asmType, file);
cv.defineClass(file,
V1_6,
ACC_FINAL,
ACC_FINAL | ACC_SUPER,
asmType.getInternalName(),
null,
OBJECT_TYPE.getInternalName(),

View File

@@ -88,7 +88,7 @@ public class ScriptCodegen extends MemberCodegen<KtScript> {
v.defineClass(scriptDeclaration,
V1_6,
ACC_PUBLIC,
ACC_PUBLIC | ACC_SUPER,
classType.getInternalName(),
null,
"java/lang/Object",

View File

@@ -23,6 +23,7 @@ import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.builtins.PrimitiveType;
import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicMethods;
import org.jetbrains.kotlin.codegen.intrinsics.JavaClassProperty;
@@ -45,6 +46,7 @@ import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodParameterKind;
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodParameterSignature;
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue;
import org.jetbrains.kotlin.synthetic.SamAdapterExtensionFunctionDescriptor;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.org.objectweb.asm.Label;
import org.jetbrains.org.objectweb.asm.Type;
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
@@ -502,19 +504,19 @@ public abstract class StackValue {
}
ReceiverValue callExtensionReceiver = (ReceiverValue) resolvedCall.getExtensionReceiver();
if (callDispatchReceiver.exists() || callExtensionReceiver.exists()
if (callDispatchReceiver != null || callExtensionReceiver != null
|| isLocalFunCall(callableMethod) || isCallToMemberObjectImportedByName(resolvedCall)) {
ReceiverParameterDescriptor dispatchReceiverParameter = descriptor.getDispatchReceiverParameter();
ReceiverParameterDescriptor extensionReceiverParameter = descriptor.getExtensionReceiverParameter();
if (descriptor.getOriginal() instanceof SamAdapterExtensionFunctionDescriptor) {
callDispatchReceiver = callExtensionReceiver;
callExtensionReceiver = ReceiverValue.NO_RECEIVER;
callExtensionReceiver = null;
dispatchReceiverParameter = extensionReceiverParameter;
extensionReceiverParameter = null;
}
boolean hasExtensionReceiver = callExtensionReceiver.exists();
boolean hasExtensionReceiver = callExtensionReceiver != null;
StackValue dispatchReceiver = platformStaticCallIfPresent(
genReceiver(hasExtensionReceiver ? none() : receiver, codegen, resolvedCall, callableMethod, callDispatchReceiver, false),
descriptor
@@ -532,11 +534,11 @@ public abstract class StackValue {
@NotNull ExpressionCodegen codegen,
@NotNull ResolvedCall resolvedCall,
@Nullable Callable callableMethod,
ReceiverValue receiverValue,
@Nullable ReceiverValue receiverValue,
boolean isExtension
) {
if (receiver == none()) {
if (receiverValue.exists()) {
if (receiverValue != null) {
return codegen.generateReceiverValue(receiverValue, false);
}
else if (isLocalFunCall(callableMethod) && !isExtension) {
@@ -548,7 +550,7 @@ public abstract class StackValue {
return singleton(((ImportedFromObjectCallableDescriptor) resolvedCall.getResultingDescriptor()).getContainingObject(), codegen.typeMapper);
}
}
else if (receiverValue.exists()) {
else if (receiverValue != null) {
return receiver;
}
return none();
@@ -834,7 +836,7 @@ public abstract class StackValue {
ReceiverValue receiverParameter = (ReceiverValue) resolvedGetCall.getExtensionReceiver();
int receiverIndex = -1;
if (receiverParameter.exists()) {
if (receiverParameter != null) {
Type type = codegen.typeMapper.mapType(receiverParameter.getType());
receiverIndex = frame.enterTemp(type);
v.store(receiverIndex, type);
@@ -842,7 +844,7 @@ public abstract class StackValue {
ReceiverValue dispatchReceiver = resolvedGetCall.getDispatchReceiver();
int thisIndex = -1;
if (dispatchReceiver.exists()) {
if (dispatchReceiver != null) {
thisIndex = frame.enterTemp(OBJECT_TYPE);
v.store(thisIndex, OBJECT_TYPE);
}
@@ -863,14 +865,14 @@ public abstract class StackValue {
throw new UnsupportedOperationException();
}
if (resolvedSetCall.getDispatchReceiver().exists()) {
if (resolvedSetCall.getExtensionReceiver().exists()) {
if (resolvedSetCall.getDispatchReceiver() != null) {
if (resolvedSetCall.getExtensionReceiver() != null) {
codegen.generateReceiverValue(resolvedSetCall.getDispatchReceiver(), false).put(OBJECT_TYPE, v);
}
v.load(realReceiverIndex, realReceiverType);
}
else {
if (resolvedSetCall.getExtensionReceiver().exists()) {
if (resolvedSetCall.getExtensionReceiver() != null) {
v.load(realReceiverIndex, realReceiverType);
}
else {
@@ -970,8 +972,8 @@ public abstract class StackValue {
}
}
if (call.getDispatchReceiver().exists()) {
if (call.getExtensionReceiver().exists()) {
if (call.getDispatchReceiver() != null) {
if (call.getExtensionReceiver() != null) {
return false;
}
}
@@ -1090,6 +1092,12 @@ public abstract class StackValue {
else {
getter.genInvokeInstruction(v);
coerce(getter.getReturnType(), type, v);
KotlinType returnType = descriptor.getReturnType();
if (returnType != null && KotlinBuiltIns.isNothing(returnType)) {
v.aconst(null);
v.athrow();
}
}
}

View File

@@ -98,6 +98,7 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
correctContainerForLambda(callableDescriptor, element),
Name.special("<closure-" + simpleName + ">"),
Modality.FINAL,
ClassKind.CLASS,
supertypes,
KotlinSourceElementKt.toSourceElement(element)
);
@@ -128,7 +129,7 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
if (element instanceof KtObjectDeclaration &&
element.getParent() instanceof KtObjectLiteralExpression &&
child instanceof KtDelegationSpecifierList) {
child instanceof KtSuperTypeList) {
// If we're passing an anonymous object's super call, it means "container" is ConstructorDescriptor of that object.
// To reach outer context, we should call getContainingDeclaration() twice
// TODO: this is probably not entirely correct, mostly because DECLARATION_TO_DESCRIPTOR can return null
@@ -177,7 +178,7 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
@Override
public void visitEnumEntry(@NotNull KtEnumEntry enumEntry) {
if (enumEntry.getDeclarations().isEmpty()) {
for (KtDelegationSpecifier specifier : enumEntry.getDelegationSpecifiers()) {
for (KtSuperTypeListEntry specifier : enumEntry.getSuperTypeListEntries()) {
specifier.accept(this);
}
return;
@@ -247,7 +248,7 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
String name = inventAnonymousClassName();
recordClosure(classDescriptor, name);
KtDelegationSpecifierList delegationSpecifierList = object.getDelegationSpecifierList();
KtSuperTypeList delegationSpecifierList = object.getSuperTypeList();
if (delegationSpecifierList != null) {
delegationSpecifierList.accept(this);
}
@@ -263,8 +264,8 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
}
@Override
public void visitFunctionLiteralExpression(@NotNull KtFunctionLiteralExpression expression) {
KtFunctionLiteral functionLiteral = expression.getFunctionLiteral();
public void visitLambdaExpression(@NotNull KtLambdaExpression lambdaExpression) {
KtFunctionLiteral functionLiteral = lambdaExpression.getFunctionLiteral();
FunctionDescriptor functionDescriptor =
(FunctionDescriptor) bindingContext.get(DECLARATION_TO_DESCRIPTOR, functionLiteral);
// working around a problem with shallow analysis
@@ -277,7 +278,7 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
classStack.push(classDescriptor);
nameStack.push(name);
super.visitFunctionLiteralExpression(expression);
super.visitLambdaExpression(lambdaExpression);
nameStack.pop();
classStack.pop();
}
@@ -431,8 +432,8 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
}
@Override
public void visitDelegationToSuperCallSpecifier(@NotNull KtDelegatorToSuperCall call) {
super.visitDelegationToSuperCallSpecifier(call);
public void visitSuperTypeCallEntry(@NotNull KtSuperTypeCallEntry call) {
super.visitSuperTypeCallEntry(call);
checkSamCall(call);
}

View File

@@ -61,6 +61,9 @@ public final class PsiCodegenPredictor {
// TODO: Method won't work for declarations inside companion objects
// TODO: Method won't give correct class name for traits implementations
if (declaration instanceof KtPropertyAccessor) {
return getPredefinedJvmInternalName(((KtPropertyAccessor) declaration).getProperty(), fileClassesProvider);
}
KtDeclaration parentDeclaration = KtStubbedPsiUtil.getContainingDeclaration(declaration);
String parentInternalName;
@@ -73,8 +76,8 @@ public final class PsiCodegenPredictor {
else {
KtFile containingFile = declaration.getContainingKtFile();
if (declaration instanceof KtNamedFunction) {
Name name = ((KtNamedFunction) declaration).getNameAsName();
if (declaration instanceof KtNamedFunction || declaration instanceof KtProperty) {
Name name = ((KtNamedDeclaration) declaration).getNameAsName();
return name == null ? null : FileClasses.getFileClassInternalName(fileClassesProvider, containingFile) + "$" + name.asString();
}

View File

@@ -25,7 +25,7 @@ import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.load.java.BuiltinMethodsWithSpecialGenericSignature
import org.jetbrains.kotlin.load.java.BuiltinMethodsWithSpecialGenericSignature.getSpecialSignatureInfo
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.load.java.getOverriddenBuiltinWithDifferentJvmDescriptor
import org.jetbrains.kotlin.load.java.getOverriddenBuiltinReflectingJvmDescriptor
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtPsiUtil
import org.jetbrains.kotlin.resolve.BindingContext
@@ -51,7 +51,7 @@ object BuiltinSpecialBridgesUtil {
val functionHandle = DescriptorBasedFunctionHandle(function)
val fake = !functionHandle.isDeclaration
val overriddenBuiltin = function.getOverriddenBuiltinWithDifferentJvmDescriptor()!!
val overriddenBuiltin = function.getOverriddenBuiltinReflectingJvmDescriptor()!!
val reachableDeclarations = findAllReachableDeclarations(function)
@@ -99,7 +99,7 @@ object BuiltinSpecialBridgesUtil {
): Boolean {
if (BuiltinMethodsWithSpecialGenericSignature.getDefaultValueForOverriddenBuiltinFunction(this) == null) return false
val builtin = getOverriddenBuiltinWithDifferentJvmDescriptor()!!
val builtin = getOverriddenBuiltinReflectingJvmDescriptor()!!
return signatureByDescriptor(this) == signatureByDescriptor(builtin)
}
}
@@ -134,7 +134,7 @@ private fun <Signature> needGenerateSpecialBridge(
|| originalOverridden.containingDeclaration is JavaClassDescriptor
|| DescriptorUtils.isInterface(originalOverridden.containingDeclaration)) return@firstOverridden false
val overriddenSpecial = originalOverridden.getOverriddenBuiltinWithDifferentJvmDescriptor()?.original ?: return@firstOverridden false
val overriddenSpecial = originalOverridden.getOverriddenBuiltinReflectingJvmDescriptor()?.original ?: return@firstOverridden false
signatureByDescriptor(originalOverridden) != signatureByDescriptor(overriddenSpecial)
} != null) return false

View File

@@ -17,17 +17,25 @@
package org.jetbrains.kotlin.codegen
import org.jetbrains.kotlin.codegen.context.FieldOwnerContext
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.load.java.BuiltinMethodsWithSpecialGenericSignature.SpecialSignatureInfo
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.types.ErrorUtils
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.org.objectweb.asm.Label
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
fun generateIsCheck(
v: InstructionAdapter,
type: KotlinType,
isNullable: Boolean,
generateInstanceOfInstruction: (InstructionAdapter) -> Unit
) {
if (type.isMarkedNullable) {
if (isNullable) {
val nope = Label()
val end = Label()
@@ -51,6 +59,39 @@ fun generateIsCheck(
}
}
fun generateNullCheckForNonSafeAs(
v: InstructionAdapter,
type: KotlinType
) {
with(v) {
dup()
val nonnull = Label()
ifnonnull(nonnull)
AsmUtil.genThrow(v, "kotlin/TypeCastException", "null cannot be cast to non-null type " + DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(type))
mark(nonnull)
}
}
public fun SpecialSignatureInfo.replaceValueParametersIn(sourceSignature: String?): String?
= valueParametersSignature?.let { sourceSignature?.replace("^\\(.*\\)".toRegex(), "($it)") }
fun populateCompanionBackingFieldNamesToOuterContextIfNeeded(companion: KtObjectDeclaration, outerContext: FieldOwnerContext<*>, state: GenerationState) {
val descriptor = state.bindingContext.get(BindingContext.CLASS, companion)
if (descriptor == null || ErrorUtils.isError(descriptor)) {
return
}
if (!AsmUtil.isCompanionObjectWithBackingFieldsInOuter(descriptor)) {
return
}
val properties = companion.declarations.filterIsInstance<KtProperty>()
properties.forEach {
val variableDescriptor = state.bindingContext.get(BindingContext.VARIABLE, it)
if (variableDescriptor is PropertyDescriptor) {
outerContext.getFieldName(variableDescriptor, it.hasDelegate())
}
}
}

View File

@@ -19,6 +19,7 @@ package org.jetbrains.kotlin.codegen.context;
import kotlin.jvm.functions.Function0;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.ReadOnly;
import org.jetbrains.kotlin.codegen.*;
import org.jetbrains.kotlin.codegen.binding.MutableClosure;
import org.jetbrains.kotlin.codegen.state.GenerationState;
@@ -27,7 +28,6 @@ import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.load.java.JavaVisibilities;
import org.jetbrains.kotlin.load.java.descriptors.SamConstructorDescriptor;
import org.jetbrains.kotlin.psi.KtFile;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.storage.LockBasedStorageManager;
import org.jetbrains.kotlin.storage.NullableLazyValue;
@@ -37,7 +37,7 @@ import org.jetbrains.org.objectweb.asm.Type;
import java.util.*;
import static org.jetbrains.kotlin.codegen.AsmUtil.getVisibilityAccessFlag;
import static org.jetbrains.kotlin.resolve.BindingContext.NEED_SYNTHETIC_ACCESSOR;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isJvmInterface;
import static org.jetbrains.org.objectweb.asm.Opcodes.ACC_PRIVATE;
import static org.jetbrains.org.objectweb.asm.Opcodes.ACC_PROTECTED;
@@ -267,6 +267,10 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
return new MultifileClassFacadeContext(descriptor, this, multifileClassType, filePartType);
}
public ClassContext intoDefaultImplsClass(ClassDescriptor descriptor, ClassContext interfaceContext, GenerationState state) {
return new DefaultImplsClassContext(state.getTypeMapper(), descriptor, OwnerKind.DEFAULT_IMPLS, this, null, interfaceContext);
}
@NotNull
public ClassContext intoClass(ClassDescriptor descriptor, OwnerKind kind, GenerationState state) {
if (descriptor.isCompanionObject()) {
@@ -279,11 +283,7 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
}
ClassContext classContext = new ClassContext(state.getTypeMapper(), descriptor, kind, this, null);
//We can't call descriptor.getCompanionObjectDescriptor() on light class generation
// because it triggers companion light class generation via putting it to BindingContext.CLASS
// (so MemberCodegen doesn't skip it in genClassOrObject).
if (state.getTypeMapper().getClassBuilderMode() != ClassBuilderMode.LIGHT_CLASSES &&
descriptor.getCompanionObjectDescriptor() != null) {
if (descriptor.getCompanionObjectDescriptor() != null) {
//We need to create companion object context ahead of time
// because otherwise we can't generate synthetic accessor for private members in companion object
classContext.intoClass(descriptor.getCompanionObjectDescriptor(), OwnerKind.IMPLEMENTATION, state);
@@ -298,12 +298,12 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
@NotNull
public MethodContext intoFunction(FunctionDescriptor descriptor) {
return new MethodContext(descriptor, getContextKind(), this, null, false);
return new MethodContext(descriptor, getContextKind(), this, null);
}
@NotNull
public MethodContext intoInlinedLambda(FunctionDescriptor descriptor) {
return new MethodContext(descriptor, getContextKind(), this, null, true);
public MethodContext intoInlinedLambda(FunctionDescriptor descriptor, boolean isCrossInline) {
return new InlineLambdaContext(descriptor, getContextKind(), this, null, isCrossInline);
}
@NotNull
@@ -365,11 +365,24 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
}
@NotNull
public <D extends CallableMemberDescriptor> D getAccessor(@NotNull D descriptor, @Nullable ClassDescriptor superCallTarget) {
private <D extends CallableMemberDescriptor> D getAccessor(@NotNull D descriptor, @Nullable ClassDescriptor superCallTarget) {
return getAccessor(descriptor, FieldAccessorKind.NORMAL, null, superCallTarget);
}
@SuppressWarnings("unchecked")
@NotNull
public <D extends CallableMemberDescriptor> D getAccessorForSuperCallIfNeeded(@NotNull D descriptor, @Nullable ClassDescriptor superCallTarget) {
if (superCallTarget != null && !isJvmInterface(descriptor.getContainingDeclaration())) {
CodegenContext afterInline = getFirstCrossInlineOrNonInlineContext();
CodegenContext c = afterInline.findParentContextWithDescriptor(superCallTarget);
assert c != null : "Couldn't find a context for a super-call: " + descriptor;
if (c != afterInline.getParentContext()) {
return (D) c.getAccessor(descriptor, superCallTarget);
}
}
return descriptor;
}
@NotNull
public <D extends CallableMemberDescriptor> D getAccessor(
@NotNull D possiblySubstitutedDescriptor,
@@ -502,32 +515,27 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
}
@NotNull
@ReadOnly
public Collection<? extends AccessorForCallableDescriptor<?>> getAccessors() {
return accessors == null ? Collections.<AccessorForCallableDescriptor<CallableMemberDescriptor>>emptySet() : accessors.values();
}
@SuppressWarnings("unchecked")
@NotNull
public <D extends CallableMemberDescriptor> D accessibleDescriptor(
@NotNull D descriptor,
@Nullable ClassDescriptor superCallTarget
) {
CodegenContext properContext = getFirstCrossInlineOrNonInlineContext();
DeclarationDescriptor enclosing = descriptor.getContainingDeclaration();
boolean isInliningContext = isInlineMethodContext();
boolean isInliningContext = properContext.isInlineMethodContext();
if (!isInliningContext && (
!hasThisDescriptor() ||
enclosing == getThisDescriptor() ||
enclosing == getClassOrPackageParentContext().getContextDescriptor())) {
!properContext.hasThisDescriptor() ||
enclosing == properContext.getThisDescriptor() ||
enclosing == properContext.getClassOrPackageParentContext().getContextDescriptor())) {
return descriptor;
}
return accessibleDescriptorIfNeeded(descriptor, superCallTarget, isInliningContext);
}
public void recordSyntheticAccessorIfNeeded(@NotNull CallableMemberDescriptor descriptor, @NotNull BindingContext bindingContext) {
if (hasThisDescriptor() && Boolean.TRUE.equals(bindingContext.get(NEED_SYNTHETIC_ACCESSOR, descriptor))) {
// Not a super call because neither constructors nor private members can be targets of super calls
accessibleDescriptorIfNeeded(descriptor, /* superCallTarget = */ null, false);
}
return (D) properContext.accessibleDescriptorIfNeeded(descriptor, superCallTarget, isInliningContext);
}
@SuppressWarnings("unchecked")
@@ -632,7 +640,7 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
}
@Nullable
public CodegenContext findChildContext(@NotNull DeclarationDescriptor child) {
protected CodegenContext findChildContext(@NotNull DeclarationDescriptor child) {
return childContexts == null ? null : childContexts.get(child);
}
@@ -640,18 +648,12 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
return value instanceof StackValue.Field && ((StackValue.Field) value).isStaticPut;
}
private boolean isInsideInliningContext() {
CodegenContext current = this;
while (current != null) {
if (current instanceof MethodContext && ((MethodContext) current).isInlineFunction()) {
return true;
}
current = current.getParentContext();
}
public boolean isInlineMethodContext() {
return false;
}
private boolean isInlineMethodContext() {
return this instanceof MethodContext && ((MethodContext) this).isInlineFunction();
@NotNull
public CodegenContext getFirstCrossInlineOrNonInlineContext() {
return this;
}
}

View File

@@ -34,7 +34,7 @@ public class ConstructorContext extends MethodContext {
@NotNull CodegenContext parent,
@Nullable MutableClosure closure
) {
super(contextDescriptor, kind, parent, closure, false);
super(contextDescriptor, kind, parent, closure);
}
@Override

View File

@@ -0,0 +1,44 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.codegen.context
import org.jetbrains.kotlin.codegen.AccessorForCallableDescriptor
import org.jetbrains.kotlin.codegen.OwnerKind
import org.jetbrains.kotlin.codegen.state.JetTypeMapper
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
class DefaultImplsClassContext(
typeMapper: JetTypeMapper,
contextDescriptor: ClassDescriptor,
contextKind: OwnerKind,
parentContext: CodegenContext<*>?,
localLookup: ((DeclarationDescriptor) -> Boolean)?,
val interfaceContext: ClassContext
) : ClassContext(typeMapper, contextDescriptor, contextKind, parentContext, localLookup) {
override fun getCompanionObjectContext(): CodegenContext<*>? {
return interfaceContext.companionObjectContext
}
override fun getAccessors(): Collection<AccessorForCallableDescriptor<*>> {
val accessors = super.getAccessors()
val alreadyExistKeys = accessors.map ({ Pair(it.calleeDescriptor, it.superCallTarget) })
val filtered = interfaceContext.accessors.toMap ({ Pair(it.calleeDescriptor, it.superCallTarget) }, {it}) - alreadyExistKeys
return accessors + filtered.values
}
}

View File

@@ -0,0 +1,43 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.codegen.context
import org.jetbrains.kotlin.codegen.OwnerKind
import org.jetbrains.kotlin.codegen.binding.MutableClosure
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
class InlineLambdaContext(
functionDescriptor: FunctionDescriptor,
contextKind: OwnerKind,
parentContext: CodegenContext<*>,
closure: MutableClosure?,
val isCrossInline: Boolean
) : MethodContext(functionDescriptor, contextKind, parentContext, closure) {
override fun getFirstCrossInlineOrNonInlineContext(): CodegenContext<*> {
if (isCrossInline) return this
val parent = parentContext as? ClosureContext ?:
throw AssertionError("Parent of inlining lambda body should be ClosureContext, but: $parentContext")
val grandParent = parent.parentContext ?:
throw AssertionError("Parent context of lambda class context should exist: $contextDescriptor")
return grandParent.firstCrossInlineOrNonInlineContext
}
}

View File

@@ -32,7 +32,6 @@ import org.jetbrains.org.objectweb.asm.Label;
import org.jetbrains.org.objectweb.asm.Type;
public class MethodContext extends CodegenContext<CallableMemberDescriptor> {
private final boolean isInliningLambda;
private Label methodStartLabel;
private Label methodEndLabel;
@@ -44,12 +43,10 @@ public class MethodContext extends CodegenContext<CallableMemberDescriptor> {
@NotNull FunctionDescriptor functionDescriptor,
@NotNull OwnerKind contextKind,
@NotNull CodegenContext parentContext,
@Nullable MutableClosure closure,
boolean isInliningLambda
@Nullable MutableClosure closure
) {
super(JvmCodegenUtil.getDirectMember(functionDescriptor), contextKind, parentContext, closure,
parentContext.hasThisDescriptor() ? parentContext.getThisDescriptor() : null, null);
this.isInliningLambda = isInliningLambda;
this.functionDescriptor = functionDescriptor;
}
@@ -117,14 +114,10 @@ public class MethodContext extends CodegenContext<CallableMemberDescriptor> {
return "Method: " + getContextDescriptor();
}
public boolean isInlineFunction() {
public boolean isInlineMethodContext() {
return InlineUtil.isInline(getContextDescriptor());
}
public boolean isInliningLambda() {
return isInliningLambda;
}
@NotNull
public FunctionDescriptor getFunctionDescriptor() {
return functionDescriptor;

View File

@@ -16,7 +16,6 @@
package org.jetbrains.kotlin.codegen.inline;
import com.intellij.openapi.util.Pair;
import com.intellij.util.ArrayUtil;
import kotlin.jvm.functions.Function0;
import org.jetbrains.annotations.NotNull;
@@ -28,10 +27,7 @@ import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.codegen.state.JetTypeMapper;
import org.jetbrains.org.objectweb.asm.*;
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
import org.jetbrains.org.objectweb.asm.tree.AbstractInsnNode;
import org.jetbrains.org.objectweb.asm.tree.FieldInsnNode;
import org.jetbrains.org.objectweb.asm.tree.MethodNode;
import org.jetbrains.org.objectweb.asm.tree.VarInsnNode;
import org.jetbrains.org.objectweb.asm.tree.*;
import java.util.*;
@@ -66,8 +62,6 @@ public class AnonymousObjectTransformer {
private final Map<String, List<String>> fieldNames = new HashMap<String, List<String>>();
private final TypeRemapper typeRemapper;
public AnonymousObjectTransformer(
@NotNull String objectInternalName,
@NotNull InliningContext inliningContext,
@@ -82,12 +76,12 @@ public class AnonymousObjectTransformer {
this.newLambdaType = newLambdaType;
reader = InlineCodegenUtil.buildClassReaderByInternalName(state, objectInternalName);
typeRemapper = new TypeRemapper(inliningContext.typeMapping);
transformationResult = InlineResult.create();
}
@NotNull
public InlineResult doTransform(@NotNull AnonymousObjectGeneration anonymousObjectGen, @NotNull FieldRemapper parentRemapper) {
final List<InnerClassNode> innerClassNodes = new ArrayList<InnerClassNode>();
ClassBuilder classBuilder = createClassBuilder();
final List<MethodNode> methodsToTransform = new ArrayList<MethodNode>();
@@ -102,6 +96,11 @@ public class AnonymousObjectTransformer {
super.visit(version, access, name, signature, superName, interfaces);
}
@Override
public void visitInnerClass(String name, String outerName, String innerName, int access) {
innerClassNodes.add(new InnerClassNode(name, outerName, innerName, access));
}
@Override
public void visitOuterClass(@NotNull String owner, String name, String desc) {
InliningContext parent = inliningContext.getParent();
@@ -193,7 +192,7 @@ public class AnonymousObjectTransformer {
String oldFunReturnType = returnType.getInternalName();
String newFunReturnType = funResult.getChangedTypes().get(oldFunReturnType);
if (newFunReturnType != null) {
typeRemapper.addAdditionalMappings(oldFunReturnType, newFunReturnType);
inliningContext.typeRemapper.addAdditionalMappings(oldFunReturnType, newFunReturnType);
}
}
deferringMethods.add(deferringVisitor);
@@ -207,6 +206,10 @@ public class AnonymousObjectTransformer {
SourceMapper.Companion.flushToClassBuilder(sourceMapper, classBuilder);
for (InnerClassNode node : innerClassNodes) {
classBuilder.getVisitor().visitInnerClass(node.name, node.outerName, node.innerName, node.access);
}
classBuilder.done();
anonymousObjectGen.setNewLambdaType(newLambdaType);
@@ -237,7 +240,7 @@ public class AnonymousObjectTransformer {
@NotNull ParametersBuilder capturedBuilder,
boolean isConstructor
) {
ReifiedTypeParametersUsages typeParametersToReify = inliningContext.reifedTypeInliner.reifyInstructions(sourceNode.instructions);
ReifiedTypeParametersUsages typeParametersToReify = inliningContext.reifedTypeInliner.reifyInstructions(sourceNode);
Parameters parameters = isConstructor ? capturedBuilder.buildParameters() : getMethodParametersWithCaptured(capturedBuilder, sourceNode);
RegeneratedLambdaFieldRemapper remapper =
@@ -345,7 +348,7 @@ public class AnonymousObjectTransformer {
@NotNull
private ClassBuilder createClassBuilder() {
ClassBuilder classBuilder = state.getFactory().newVisitor(NO_ORIGIN, newLambdaType, inliningContext.getRoot().callElement.getContainingFile());
return new RemappingClassBuilder(classBuilder, typeRemapper);
return new RemappingClassBuilder(classBuilder, inliningContext.typeRemapper);
}
@NotNull

View File

@@ -36,6 +36,7 @@ import org.jetbrains.kotlin.modules.TargetId;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.renderer.DescriptorRenderer;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils;
import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.resolve.calls.callUtil.CallUtilKt;
@@ -245,7 +246,7 @@ public class InlineCodegen extends CallGenerator {
private InlineResult inlineCall(SMAPAndMethodNode nodeAndSmap) {
MethodNode node = nodeAndSmap.getNode();
ReifiedTypeParametersUsages reificationResult = reifiedTypeInliner.reifyInstructions(node.instructions);
ReifiedTypeParametersUsages reificationResult = reifiedTypeInliner.reifyInstructions(node);
generateClosuresBodies();
//through generation captured parameters will be added to invocationParamBuilder
@@ -309,7 +310,7 @@ public class InlineCodegen extends CallGenerator {
MethodContext parentContext = codegen.getContext();
MethodContext context = parentContext.intoClosure(descriptor, codegen, typeMapper).intoInlinedLambda(descriptor);
MethodContext context = parentContext.intoClosure(descriptor, codegen, typeMapper).intoInlinedLambda(descriptor, info.isCrossInline);
JvmMethodSignature jvmMethodSignature = typeMapper.mapSignature(descriptor);
Method asmMethod = jvmMethodSignature.getAsmMethod();
@@ -538,26 +539,34 @@ public class InlineCodegen extends CallGenerator {
}
/*lambda or callable reference*/
public static boolean isInliningParameter(KtExpression expression, ValueParameterDescriptor valueParameterDescriptor) {
public boolean isInliningParameter(KtExpression expression, ValueParameterDescriptor valueParameterDescriptor) {
//TODO deparenthisise typed
KtExpression deparenthesized = KtPsiUtil.deparenthesize(expression);
if (deparenthesized instanceof KtCallableReferenceExpression) {
// TODO: support inline of property references passed to inlinable function parameters
SimpleFunctionDescriptor functionReference = state.getBindingContext().get(BindingContext.FUNCTION, deparenthesized);
if (functionReference == null) return false;
}
return InlineUtil.isInlineLambdaParameter(valueParameterDescriptor) &&
isInlinableParameterExpression(deparenthesized);
}
protected static boolean isInlinableParameterExpression(KtExpression deparenthesized) {
return deparenthesized instanceof KtFunctionLiteralExpression ||
return deparenthesized instanceof KtLambdaExpression ||
deparenthesized instanceof KtNamedFunction ||
deparenthesized instanceof KtCallableReferenceExpression;
}
public void rememberClosure(KtExpression expression, Type type, int parameterIndex) {
public void rememberClosure(KtExpression expression, Type type, ValueParameterDescriptor parameter) {
KtExpression lambda = KtPsiUtil.deparenthesize(expression);
assert isInlinableParameterExpression(lambda) : "Couldn't find inline expression in " + expression.getText();
LambdaInfo info = new LambdaInfo(lambda, typeMapper);
ParameterInfo closureInfo = invocationParamBuilder.addNextValueParameter(type, true, null, parameterIndex);
LambdaInfo info = new LambdaInfo(lambda, typeMapper, parameter.isCrossinline());
ParameterInfo closureInfo = invocationParamBuilder.addNextValueParameter(type, true, null, parameter.getIndex());
closureInfo.setLambda(info);
expressionMap.put(closureInfo.getIndex(), info);
}
@@ -630,7 +639,7 @@ public class InlineCodegen extends CallGenerator {
int parameterIndex
) {
if (isInliningParameter(argumentExpression, valueParameterDescriptor)) {
rememberClosure(argumentExpression, parameterType, valueParameterDescriptor.getIndex());
rememberClosure(argumentExpression, parameterType, valueParameterDescriptor);
}
else {
StackValue value = codegen.gen(argumentExpression);
@@ -778,7 +787,7 @@ public class InlineCodegen extends CallGenerator {
@Override
public void reorderArgumentsIfNeeded(
@NotNull List actualArgsWithDeclIndex, @NotNull List valueParameterTypes
@NotNull List<ArgumentAndDeclIndex> actualArgsWithDeclIndex, @NotNull List<? extends Type> valueParameterTypes
) {
}

View File

@@ -29,6 +29,7 @@ import org.jetbrains.kotlin.codegen.MemberCodegen;
import org.jetbrains.kotlin.codegen.binding.CodegenBinding;
import org.jetbrains.kotlin.codegen.context.CodegenContext;
import org.jetbrains.kotlin.codegen.context.CodegenContextUtil;
import org.jetbrains.kotlin.codegen.context.InlineLambdaContext;
import org.jetbrains.kotlin.codegen.context.MethodContext;
import org.jetbrains.kotlin.codegen.optimization.common.UtilKt;
import org.jetbrains.kotlin.codegen.state.GenerationState;
@@ -131,7 +132,7 @@ public class InlineCodegenUtil {
CodegenContext<?> parentContext = context.getParentContext();
while (parentContext != null) {
if (parentContext instanceof MethodContext) {
if (((MethodContext) parentContext).isInlineFunction()) {
if (((MethodContext) parentContext).isInlineMethodContext()) {
//just init default one to one mapping
codegen.getOrCreateSourceMapper();
break;
@@ -311,8 +312,7 @@ public class InlineCodegenUtil {
}
}
public static void insertNodeBefore(@NotNull MethodNode from, @NotNull MethodNode to, @NotNull AbstractInsnNode beforeNode) {
InsnList instructions = to.instructions;
public static void insertNodeBefore(@NotNull MethodNode from, @NotNull InsnList instructions, @NotNull AbstractInsnNode beforeNode) {
ListIterator<AbstractInsnNode> iterator = from.instructions.iterator();
while (iterator.hasNext()) {
AbstractInsnNode next = iterator.next();
@@ -320,6 +320,10 @@ public class InlineCodegenUtil {
}
}
public static void insertNodeBefore(@NotNull MethodNode from, @NotNull MethodNode to, @NotNull AbstractInsnNode beforeNode) {
insertNodeBefore(from, to.instructions, beforeNode);
}
public static MethodNode createEmptyMethodNode() {
return new MethodNode(API, 0, "fake", "()V", null, null);
@@ -395,7 +399,7 @@ public class InlineCodegenUtil {
}
public static boolean isFinallyMarkerRequired(@NotNull MethodContext context) {
return context.isInlineFunction() || context.isInliningLambda();
return context.isInlineMethodContext() || context instanceof InlineLambdaContext;
}
public static int getConstant(AbstractInsnNode ins) {

View File

@@ -35,7 +35,7 @@ public class InliningContext {
public final NameGenerator nameGenerator;
public final Map<String, String> typeMapping;
public final TypeRemapper typeRemapper;
public final ReifiedTypeInliner reifedTypeInliner;
@@ -48,7 +48,7 @@ public class InliningContext {
@NotNull Map<Integer, LambdaInfo> map,
@NotNull GenerationState state,
@NotNull NameGenerator nameGenerator,
@NotNull Map<String, String> typeMapping,
@NotNull TypeRemapper typeRemapper,
@NotNull ReifiedTypeInliner reifedTypeInliner,
boolean isInliningLambda,
boolean classRegeneration
@@ -57,7 +57,7 @@ public class InliningContext {
expressionMap = map;
this.state = state;
this.nameGenerator = nameGenerator;
this.typeMapping = typeMapping;
this.typeRemapper = typeRemapper;
this.reifedTypeInliner = reifedTypeInliner;
this.isInliningLambda = isInliningLambda;
this.classRegeneration = classRegeneration;
@@ -78,13 +78,12 @@ public class InliningContext {
}
public InliningContext subInlineWithClassRegeneration(@NotNull NameGenerator generator,
@NotNull Map<String, String> additionalTypeMappings,
@NotNull Map<String, String> newTypeMappings,
@NotNull AnonymousObjectGeneration anonymousObjectGeneration
) {
Map<String, String> newTypeMappings = new HashMap<String, String>(typeMapping);
newTypeMappings.putAll(additionalTypeMappings);
return new RegeneratedClassContext(this, expressionMap, state, generator,
newTypeMappings, reifedTypeInliner, isInliningLambda, anonymousObjectGeneration);
new TypeRemapper(typeRemapper, newTypeMappings),
reifedTypeInliner, isInliningLambda, anonymousObjectGeneration);
}
public InliningContext subInline(NameGenerator generator, Map<String, String> additionalTypeMappings, boolean isInliningLambda) {
@@ -97,10 +96,8 @@ public class InliningContext {
boolean isInliningLambda,
boolean isRegeneration
) {
Map<String, String> newTypeMappings = new HashMap<String, String>(typeMapping);
newTypeMappings.putAll(additionalTypeMappings);
return new InliningContext(this, expressionMap, state, generator,
newTypeMappings, reifedTypeInliner, isInliningLambda, isRegeneration);
new TypeRemapper(typeRemapper, additionalTypeMappings), reifedTypeInliner, isInliningLambda, isRegeneration);
}
public boolean isRoot() {

View File

@@ -25,7 +25,7 @@ import org.jetbrains.kotlin.codegen.state.JetTypeMapper;
import org.jetbrains.kotlin.descriptors.ClassDescriptor;
import org.jetbrains.kotlin.descriptors.FunctionDescriptor;
import org.jetbrains.kotlin.psi.KtExpression;
import org.jetbrains.kotlin.psi.KtFunctionLiteralExpression;
import org.jetbrains.kotlin.psi.KtLambdaExpression;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.jvm.AsmTypes;
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature;
@@ -50,6 +50,8 @@ public class LambdaInfo implements CapturedParamOwner, LabelOwner {
private final CalculatedClosure closure;
public final boolean isCrossInline;
private SMAPAndMethodNode node;
private List<CapturedParamDesc> capturedVars;
@@ -60,9 +62,10 @@ public class LambdaInfo implements CapturedParamOwner, LabelOwner {
private final Type closureClassType;
LambdaInfo(@NotNull KtExpression expr, @NotNull JetTypeMapper typeMapper) {
this.expression = expr instanceof KtFunctionLiteralExpression ?
((KtFunctionLiteralExpression) expr).getFunctionLiteral() : expr;
LambdaInfo(@NotNull KtExpression expr, @NotNull JetTypeMapper typeMapper, boolean isCrossInline) {
this.isCrossInline = isCrossInline;
this.expression = expr instanceof KtLambdaExpression ?
((KtLambdaExpression) expr).getFunctionLiteral() : expr;
this.typeMapper = typeMapper;
BindingContext bindingContext = typeMapper.getBindingContext();

View File

@@ -78,7 +78,7 @@ public class MethodInliner {
public MethodInliner(
@NotNull MethodNode node,
@NotNull Parameters parameters,
@NotNull InliningContext parent,
@NotNull InliningContext inliningContext,
@NotNull FieldRemapper nodeRemapper,
boolean isSameModule,
@NotNull String errorPrefix,
@@ -86,12 +86,12 @@ public class MethodInliner {
) {
this.node = node;
this.parameters = parameters;
this.inliningContext = parent;
this.inliningContext = inliningContext;
this.nodeRemapper = nodeRemapper;
this.isSameModule = isSameModule;
this.errorPrefix = errorPrefix;
this.sourceMapper = sourceMapper;
this.typeMapper = parent.state.getTypeMapper();
this.typeMapper = inliningContext.state.getTypeMapper();
this.result = InlineResult.create();
}
@@ -153,8 +153,9 @@ public class MethodInliner {
final Iterator<AnonymousObjectGeneration> iterator = anonymousObjectGenerations.iterator();
final TypeRemapper remapper = TypeRemapper.createFrom(currentTypeMapping);
RemappingMethodAdapter remappingMethodAdapter = new RemappingMethodAdapter(resultNode.access, resultNode.desc, resultNode,
new TypeRemapper(currentTypeMapping));
remapper);
final int markerShift = InlineCodegenUtil.calcMarkerShift(parameters, node);
InlineAdapter lambdaInliner = new InlineAdapter(remappingMethodAdapter, parameters.getArgsSizeOnStack(), sourceMapper) {
@@ -167,7 +168,7 @@ public class MethodInliner {
//TODO: need poping of type but what to do with local funs???
String oldClassName = anonymousObjectGen.getOwnerInternalName();
String newClassName = inliningContext.nameGenerator.genLambdaClassName();
currentTypeMapping.put(oldClassName, newClassName);
remapper.addMapping(oldClassName, newClassName);
AnonymousObjectTransformer transformer =
new AnonymousObjectTransformer(oldClassName,
inliningContext
@@ -261,7 +262,14 @@ public class MethodInliner {
visitFieldInsn(Opcodes.GETSTATIC, capturedParamDesc.getContainingLambdaName(),
"$$$" + capturedParamDesc.getFieldName(), capturedParamDesc.getType().getDescriptor());
}
super.visitMethodInsn(opcode, anonymousObjectGen.getNewLambdaType().getInternalName(), name, anonymousObjectGen.getNewConstructorDescriptor(), itf);
String newInternalName = anonymousObjectGen.getNewLambdaType().getInternalName();
super.visitMethodInsn(opcode, newInternalName, name, anonymousObjectGen.getNewConstructorDescriptor(), itf);
//TODO: add new inner class also for other contexts
if (inliningContext.getParent() instanceof RegeneratedClassContext) {
inliningContext.getParent().typeRemapper.addAdditionalMappings(anonymousObjectGen.getOwnerInternalName(), newInternalName);
}
anonymousObjectGen = null;
} else {
super.visitMethodInsn(opcode, changeOwnerForExternalPackage(owner, opcode), name, desc, itf);
@@ -551,7 +559,7 @@ public class MethodInliner {
}
private boolean isAlreadyRegenerated(@NotNull String owner) {
return inliningContext.typeMapping.containsKey(owner);
return inliningContext.typeRemapper.hasNoAdditionalMapping(owner);
}
@Nullable

View File

@@ -30,12 +30,12 @@ public class RegeneratedClassContext extends InliningContext {
@NotNull Map<Integer, LambdaInfo> map,
@NotNull GenerationState state,
@NotNull NameGenerator nameGenerator,
@NotNull Map<String, String> typeMapping,
@NotNull TypeRemapper typeRemapper,
@NotNull ReifiedTypeInliner reifiedTypeInliner,
boolean isInliningLambda,
@NotNull AnonymousObjectGeneration anonymousObjectGeneration
) {
super(parent, map, state, nameGenerator, typeMapping, reifiedTypeInliner, isInliningLambda, true);
super(parent, map, state, nameGenerator, typeRemapper, reifiedTypeInliner, isInliningLambda, true);
this.anonymousObjectGeneration = anonymousObjectGeneration;
}

View File

@@ -18,16 +18,22 @@ package org.jetbrains.kotlin.codegen.inline
import com.google.common.collect.ImmutableSet
import org.jetbrains.kotlin.codegen.context.MethodContext
import org.jetbrains.kotlin.codegen.generateIsCheck
import org.jetbrains.kotlin.codegen.generateNullCheckForNonSafeAs
import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicMethods
import org.jetbrains.kotlin.codegen.intrinsics.TypeIntrinsics
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.org.objectweb.asm.MethodVisitor
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
import org.jetbrains.org.objectweb.asm.signature.SignatureReader
import org.jetbrains.org.objectweb.asm.signature.SignatureWriter
import org.jetbrains.org.objectweb.asm.tree.*
private class ParameterNameAndNullability(val name: String, val nullable: Boolean)
public class ReifiedTypeInliner(private val parametersMapping: ReifiedTypeParameterMappings?) {
companion object {
@@ -64,15 +70,23 @@ public class ReifiedTypeInliner(private val parametersMapping: ReifiedTypeParame
Type.getMethodDescriptor(Type.VOID_TYPE), false
);
}
@JvmStatic
public fun isNullableMarkerInstruction(marker: String) = INSTANCEOF_MARKER_METHOD_NAME == marker ||
CHECKCAST_MARKER_METHOD_NAME == marker
}
private var maxStackSize = 0
/**
* @return set of type parameters' identifiers contained in markers that should be reified further
* e.g. when we're generating inline function containing reified T
* and another function containing reifiable parts is inlined into that function
*/
public fun reifyInstructions(instructions: InsnList): ReifiedTypeParametersUsages {
public fun reifyInstructions(node: MethodNode): ReifiedTypeParametersUsages {
if (parametersMapping == null) return ReifiedTypeParametersUsages()
val instructions = node.instructions
maxStackSize = 0
var result = ReifiedTypeParametersUsages()
for (insn in instructions.toArray()) {
if (isParametrisedReifiedMarker(insn)) {
@@ -83,6 +97,7 @@ public class ReifiedTypeInliner(private val parametersMapping: ReifiedTypeParame
}
}
node.maxStack = node.maxStack + maxStackSize
return result
}
@@ -127,20 +142,25 @@ public class ReifiedTypeInliner(private val parametersMapping: ReifiedTypeParame
* or null if it shouldn't
*/
private fun processReifyMarker(insn: MethodInsnNode, instructions: InsnList): String? {
val mapping = getTypeParameterMapping(insn) ?: return null
val parameter = getParameter(insn) ?: return null
val mapping = parametersMapping?.get(parameter.name) ?: return null
val kotlinType =
if (isNullableMarkerInstruction(insn.name) && parameter.nullable)
TypeUtils.makeNullable(mapping.type)
else
mapping.type
val asmType = mapping.asmType
if (asmType != null) {
val jetType = mapping.type ?: return null
// process* methods return false if marker should be reified further
// or it's invalid (may be emitted explicitly in code)
// they return true if instruction is reified and marker can be deleted
if (when (insn.name) {
NEW_ARRAY_MARKER_METHOD_NAME -> processNewArray(insn, asmType)
CHECKCAST_MARKER_METHOD_NAME -> processCheckcast(insn, instructions, jetType, asmType, safe = false)
SAFE_CHECKCAST_MARKER_METHOD_NAME -> processCheckcast(insn, instructions, jetType, asmType, safe = true)
INSTANCEOF_MARKER_METHOD_NAME -> processInstanceof(insn, instructions, jetType, asmType)
CHECKCAST_MARKER_METHOD_NAME -> processCheckcast(insn, instructions, kotlinType, asmType, safe = false)
SAFE_CHECKCAST_MARKER_METHOD_NAME -> processCheckcast(insn, instructions, kotlinType, asmType, safe = true)
INSTANCEOF_MARKER_METHOD_NAME -> processInstanceof(insn, instructions, kotlinType, asmType)
JAVA_CLASS_MARKER_METHOD_NAME -> processJavaClass(insn, asmType)
else -> false
}) {
@@ -150,7 +170,8 @@ public class ReifiedTypeInliner(private val parametersMapping: ReifiedTypeParame
return null
} else {
instructions.set(insn.getPrevious()!!, LdcInsnNode(mapping.newName))
val nullableSuffix = if (isNullableMarkerInstruction(insn.name) && kotlinType.isMarkedNullable) "?" else ""
instructions.set(insn.previous!!, LdcInsnNode(mapping.newName + nullableSuffix))
return mapping.newName
}
}
@@ -158,20 +179,66 @@ public class ReifiedTypeInliner(private val parametersMapping: ReifiedTypeParame
private fun processNewArray(insn: MethodInsnNode, parameter: Type) =
processNextTypeInsn(insn, parameter, Opcodes.ANEWARRAY)
private fun processCheckcast(insn: MethodInsnNode, instructions: InsnList, jetType: KotlinType, asmType: Type, safe: Boolean) =
private fun processCheckcast(insn: MethodInsnNode,
instructions: InsnList,
jetType: KotlinType,
asmType: Type,
safe: Boolean) =
rewriteNextTypeInsn(insn, Opcodes.CHECKCAST) { instanceofInsn: AbstractInsnNode ->
if (instanceofInsn !is TypeInsnNode) return false
addNullCheckForAsIfNeeded(insn.previous!!, instructions, jetType, safe)
TypeIntrinsics.checkcast(instanceofInsn, instructions, jetType, asmType, safe)
return true
}
private fun addNullCheckForAsIfNeeded(insn: AbstractInsnNode, instructions: InsnList, jetType: KotlinType, safe: Boolean) {
if (!safe && !TypeUtils.isNullableType(jetType)) {
val methodNode = MethodNode(InlineCodegenUtil.API)
generateNullCheckForNonSafeAs(InstructionAdapter(methodNode), jetType)
InlineCodegenUtil.insertNodeBefore(methodNode, instructions, insn)
maxStackSize = Math.max(maxStackSize, 4)
}
}
private fun processInstanceof(insn: MethodInsnNode, instructions: InsnList, jetType: KotlinType, asmType: Type) =
rewriteNextTypeInsn(insn, Opcodes.INSTANCEOF) { instanceofInsn: AbstractInsnNode ->
if (instanceofInsn !is TypeInsnNode) return false
addNullCheckForIsIfNeeded(insn, instructions, jetType)
TypeIntrinsics.instanceOf(instanceofInsn, instructions, jetType, asmType)
return true
}
private fun addNullCheckForIsIfNeeded(insn: AbstractInsnNode, instructions: InsnList, type: KotlinType) {
if (TypeUtils.isNullableType(type)) {
val instanceOf = insn.next
insertNullCheckAround(instructions, insn.previous!!, instanceOf)
maxStackSize = Math.max(maxStackSize, 2)
}
}
private fun insertNullCheckAround(instructions: InsnList, start: AbstractInsnNode, end: AbstractInsnNode) {
val methodNode = MethodNode(InlineCodegenUtil.API)
var splitIndex: Int = -1
generateIsCheck(InstructionAdapter(methodNode), true) {
splitIndex = methodNode.instructions.size()
}
assert(splitIndex >= 0) {
"Split index should be non-negative, but $splitIndex"
}
val nullCheckInsns = methodNode.instructions.toArray()
nullCheckInsns.take(splitIndex).forEach {
instructions.insertBefore(start, it)
}
nullCheckInsns.drop(splitIndex).reversed().forEach {
instructions.insert(end, it)
}
}
inline private fun rewriteNextTypeInsn(
marker: MethodInsnNode,
expectedNextOpcode: Int,
@@ -195,17 +262,16 @@ public class ReifiedTypeInliner(private val parametersMapping: ReifiedTypeParame
return true
}
private fun getParameterName(insn: MethodInsnNode): String? {
private fun getParameter(insn: MethodInsnNode): ParameterNameAndNullability? {
val prev = insn.getPrevious()!!
return when (prev.getOpcode()) {
val parameterNameWithFlag = when (prev.getOpcode()) {
Opcodes.LDC -> (prev as LdcInsnNode).cst as String
else -> null
else -> return null
}
}
private fun getTypeParameterMapping(insn: MethodInsnNode): ReifiedTypeParameterMapping? {
return parametersMapping?.get(getParameterName(insn) ?: return null)
val parameterName = if (parameterNameWithFlag.endsWith("?")) parameterNameWithFlag.dropLast(1) else parameterNameWithFlag
return ParameterNameAndNullability(parameterName, parameterName !== parameterNameWithFlag)
}
}
@@ -216,8 +282,8 @@ public class ReifiedTypeParameterMappings() {
mappingsByName[name] = ReifiedTypeParameterMapping(name, type, asmType, newName = null, signature = signature)
}
public fun addParameterMappingToNewParameter(name: String, newName: String) {
mappingsByName[name] = ReifiedTypeParameterMapping(name, type = null, asmType = null, newName = newName, signature = null)
public fun addParameterMappingToNewParameter(name: String, type: KotlinType, newName: String) {
mappingsByName[name] = ReifiedTypeParameterMapping(name, type = type, asmType = null, newName = newName, signature = null)
}
operator fun get(name: String): ReifiedTypeParameterMapping? {
@@ -226,7 +292,7 @@ public class ReifiedTypeParameterMappings() {
}
public class ReifiedTypeParameterMapping(
val name: String, val type: KotlinType?, val asmType: Type?, val newName: String?, val signature: String?
val name: String, val type: KotlinType, val asmType: Type?, val newName: String?, val signature: String?
)
public class ReifiedTypeParametersUsages {

View File

@@ -21,7 +21,6 @@ import org.jetbrains.kotlin.codegen.context.CodegenContext;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.psi.KtElement;
import java.util.Collections;
import java.util.Map;
public class RootInliningContext extends InliningContext {
@@ -38,7 +37,7 @@ public class RootInliningContext extends InliningContext {
@NotNull String classNameToInline,
@NotNull ReifiedTypeInliner inliner
) {
super(null, map, state, nameGenerator, Collections.<String, String>emptyMap(), inliner, false, false);
super(null, map, state, nameGenerator, TypeRemapper.createEmpty(), inliner, false, false);
this.callElement = callElement;
this.startContext = startContext;
this.classNameToInline = classNameToInline;

View File

@@ -23,14 +23,43 @@ import java.util.HashMap;
import java.util.Map;
public class TypeRemapper extends Remapper {
//typeMapping field could be changed outside through method processing
private final Map<String, String> typeMapping;
private Map<String, String> additionalMappings;
//typeMapping could be changed outside through method processing
public TypeRemapper(@NotNull Map<String, String> typeMapping) {
//typeMapping field could be changed outside through method processing
private TypeRemapper(@NotNull Map<String, String> typeMapping) {
this.typeMapping = typeMapping;
}
public TypeRemapper(@NotNull TypeRemapper remapper, @NotNull Map<String, String> newTypeMappings) {
this(createNewAndMerge(remapper, newTypeMappings));
}
public static TypeRemapper createEmpty() {
return new TypeRemapper(new HashMap<String, String>());
}
public static TypeRemapper createFrom(Map<String, String> mappings) {
return new TypeRemapper(mappings);
}
@NotNull
private static Map<String, String> createNewAndMerge(@NotNull TypeRemapper remapper, @NotNull Map<String, String> additionalTypeMappings) {
Map<String, String> map = new HashMap<String, String>(remapper.typeMapping);
map.putAll(additionalTypeMappings);
return map;
}
public void addMapping(String type, String newType) {
typeMapping.put(type, newType);
}
public boolean hasNoAdditionalMapping(String type) {
return typeMapping.containsKey(type);
}
@Override
public String map(String type) {
String newType = typeMapping.get(type);

View File

@@ -17,6 +17,7 @@
package org.jetbrains.kotlin.codegen.intrinsics;
import com.google.common.collect.ImmutableList;
import kotlin.StringsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
@@ -26,6 +27,7 @@ import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.resolve.CompileTimeConstantUtils;
import org.jetbrains.kotlin.resolve.jvm.JvmPrimitiveType;
import org.jetbrains.kotlin.types.expressions.OperatorConventions;
import org.jetbrains.kotlin.util.capitalizeDecapitalize.CapitalizeDecapitalizeKt;
import java.util.HashMap;
import java.util.Map;
@@ -63,11 +65,12 @@ public class IntrinsicMethods {
namedMethods.put("kotlin.javaClass.function", new JavaClassFunction());
namedMethods.put("kotlin.javaClass.property", new JavaClassProperty());
namedMethods.put("kotlin.KClass.java.property", new KClassJavaProperty());
namedMethods.put("kotlin.arrays.array", new JavaClassArray());
namedMethods.put("kotlin.jvm.internal.unsafe.monitorEnter", MonitorInstruction.MONITOR_ENTER);
namedMethods.put("kotlin.jvm.internal.unsafe.monitorExit", MonitorInstruction.MONITOR_EXIT);
namedMethods.put("kotlin.jvm.isArrayOf", new IsArrayOf());
intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME, null, "arrayOf", 1, new JavaClassArray());
ImmutableList<Name> primitiveCastMethods = OperatorConventions.NUMBER_CONVERSIONS.asList();
for (Name method : primitiveCastMethods) {
String methodName = method.asString();
@@ -94,6 +97,10 @@ public class IntrinsicMethods {
declareIntrinsicFunction(typeName, "equals", 1, EQUALS);
declareIntrinsicFunction(typeName, "hashCode", 0, HASH_CODE);
declareIntrinsicFunction(typeName, "toString", 0, TO_STRING);
intrinsicsMap.registerIntrinsic(
BUILT_INS_PACKAGE_FQ_NAME, null, StringsKt.decapitalize(type.getArrayTypeName().asString()) + "Of", 1, new JavaClassArray()
);
}
declareBinaryOp("plus", IADD);

View File

@@ -58,7 +58,7 @@ public class JavaClassProperty : IntrinsicPropertyGetter() {
}
override fun toCallable(fd: FunctionDescriptor, isSuper: Boolean, resolvedCall: ResolvedCall<*>, codegen: ExpressionCodegen): Callable {
val classType = codegen.getState().typeMapper.mapType(resolvedCall.getCall().getDispatchReceiver().getType())
val classType = codegen.getState().typeMapper.mapType(resolvedCall.getCall().getDispatchReceiver()!!.getType())
return object : IntrinsicCallable(getType(javaClass<Class<Any>>()), listOf(), classType, null) {
override fun invokeIntrinsic(v: InstructionAdapter) {
if (isPrimitive(classType)) {

View File

@@ -91,27 +91,28 @@ public class OptimizationBasicInterpreter extends BasicInterpreter {
public BasicValue merge(
@NotNull BasicValue v, @NotNull BasicValue w
) {
if (!v.equals(w)) {
if (v == BasicValue.UNINITIALIZED_VALUE || w == BasicValue.UNINITIALIZED_VALUE) {
return BasicValue.UNINITIALIZED_VALUE;
}
// if merge of two references then `lub` is java/lang/Object
// arrays also are BasicValues with reference type's
if (v.getType().getSort() == Type.OBJECT && w.getType().getSort() == Type.OBJECT) {
return BasicValue.REFERENCE_VALUE;
}
assert v.getType().getSort() != Type.ARRAY && w.getType().getSort() != Type.ARRAY : "There should not be arrays";
// if merge of something can be stored in int var (int, char, boolean, byte, character)
if (v.getType().getOpcode(Opcodes.ISTORE) == Opcodes.ISTORE &&
w.getType().getOpcode(Opcodes.ISTORE) == Opcodes.ISTORE) {
return BasicValue.INT_VALUE;
}
if (v == BasicValue.UNINITIALIZED_VALUE || w == BasicValue.UNINITIALIZED_VALUE) {
return BasicValue.UNINITIALIZED_VALUE;
}
return v;
// Objects must be equal, others can just have the same sort
if (v.getType().getSort() == w.getType().getSort() && (v.getType().getSort() != Type.OBJECT || v.equals(w))) {
return v;
}
// if merge of two references then `lub` is java/lang/Object
// arrays also are BasicValues with reference type's
if (v.getType().getSort() == Type.OBJECT && w.getType().getSort() == Type.OBJECT) {
return BasicValue.REFERENCE_VALUE;
}
assert v.getType().getSort() != Type.ARRAY && w.getType().getSort() != Type.ARRAY : "There should not be arrays";
// if merge of something can be stored in int var (int, char, boolean, byte, character)
if (v.getType().getOpcode(Opcodes.ISTORE) == Opcodes.ISTORE &&
w.getType().getOpcode(Opcodes.ISTORE) == Opcodes.ISTORE) {
return BasicValue.INT_VALUE;
}
return BasicValue.UNINITIALIZED_VALUE;
}
}

View File

@@ -33,7 +33,6 @@ import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.jvm.diagnostics.*
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.utils.addIfNotNull
import java.util.*
@@ -53,8 +52,18 @@ class BuilderFactoryForDuplicateSignatureDiagnostics(
// Avoid errors when some classes are not loaded for some reason
private val typeMapper = JetTypeMapper(bindingContext, ClassBuilderMode.LIGHT_CLASSES, fileClassesProvider, incrementalCache, moduleName)
private val reportDiagnosticsTasks = ArrayList<() -> Unit>()
fun reportDiagnostics() {
reportDiagnosticsTasks.forEach { it() }
reportDiagnosticsTasks.clear()
}
override fun handleClashingSignatures(data: ConflictingJvmDeclarationsData) {
reportDiagnosticsTasks.add { reportConflictingJvmSignatures(data) }
}
private fun reportConflictingJvmSignatures(data: ConflictingJvmDeclarationsData) {
val noOwnImplementations = data.signatureOrigins.all { it.originKind in EXTERNAL_SOURCES_KINDS }
val elements = LinkedHashSet<PsiElement>()
@@ -82,6 +91,14 @@ class BuilderFactoryForDuplicateSignatureDiagnostics(
classOrigin: JvmDeclarationOrigin,
classInternalName: String?,
signatures: MultiMap<RawSignature, JvmDeclarationOrigin>
) {
reportDiagnosticsTasks.add { reportClashingSignaturesInHierarchy(classOrigin, classInternalName, signatures) }
}
private fun reportClashingSignaturesInHierarchy(
classOrigin: JvmDeclarationOrigin,
classInternalName: String?,
signatures: MultiMap<RawSignature, JvmDeclarationOrigin>
) {
val descriptor = classOrigin.descriptor
if (descriptor !is ClassDescriptor) return
@@ -157,7 +174,7 @@ class BuilderFactoryForDuplicateSignatureDiagnostics(
descriptor.getParentJavaStaticClassScope()?.run {
getContributedDescriptors(DescriptorKindFilter.FUNCTIONS)
.filter {
it is FunctionDescriptor && Visibilities.isVisible(ReceiverValue.IRRELEVANT_RECEIVER, it, descriptor)
it is FunctionDescriptor && Visibilities.isVisibleWithIrrelevantReceiver(it, descriptor)
}
.forEach(::processMember)
}
@@ -165,7 +182,7 @@ class BuilderFactoryForDuplicateSignatureDiagnostics(
return groupedBySignature
}
public fun isOrOverridesSamAdapter(descriptor: CallableMemberDescriptor): Boolean {
private fun isOrOverridesSamAdapter(descriptor: CallableMemberDescriptor): Boolean {
if (descriptor is SamAdapterDescriptor<*>) return true
return descriptor.getKind() == CallableMemberDescriptor.Kind.FAKE_OVERRIDE

View File

@@ -17,6 +17,8 @@
package org.jetbrains.kotlin.codegen.state
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ModificationTracker
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.builtins.ReflectionTypes
import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.`when`.MappingsClassesForWhenByEnum
@@ -28,6 +30,7 @@ import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicMethods
import org.jetbrains.kotlin.codegen.optimization.OptimizationClassBuilderFactory
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.ScriptDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.load.kotlin.incremental.components.IncrementalCompilationComponents
import org.jetbrains.kotlin.modules.TargetId
@@ -63,19 +66,20 @@ public class GenerationState @JvmOverloads constructor(
// TODO: get rid of it with the proper module infrastructure
public val outDirectory: File? = null,
public val incrementalCompilationComponents: IncrementalCompilationComponents? = null,
public val generateOpenMultifileClasses: Boolean = false,
public val progress: Progress = Progress.DEAF
) {
public abstract class GenerateClassFilter {
public abstract fun shouldAnnotateClass(classOrObject: KtClassOrObject): Boolean
public abstract fun shouldGenerateClass(classOrObject: KtClassOrObject): Boolean
public abstract fun shouldAnnotateClass(processingClassOrObject: KtClassOrObject): Boolean
public abstract fun shouldGenerateClass(processingClassOrObject: KtClassOrObject): Boolean
public abstract fun shouldGeneratePackagePart(jetFile: KtFile): Boolean
public abstract fun shouldGenerateScript(script: KtScript): Boolean
companion object {
public val GENERATE_ALL: GenerateClassFilter = object : GenerateClassFilter() {
override fun shouldAnnotateClass(classOrObject: KtClassOrObject): Boolean = true
override fun shouldAnnotateClass(processingClassOrObject: KtClassOrObject): Boolean = true
override fun shouldGenerateClass(classOrObject: KtClassOrObject): Boolean = true
override fun shouldGenerateClass(processingClassOrObject: KtClassOrObject): Boolean = true
override fun shouldGenerateScript(script: KtScript): Boolean = true
@@ -96,7 +100,10 @@ public class GenerationState @JvmOverloads constructor(
private var used = false
public val diagnostics: DiagnosticSink get() = extraJvmDiagnosticsTrace
public val collectedExtraJvmDiagnostics: Diagnostics get() = extraJvmDiagnosticsTrace.bindingContext.diagnostics
public val collectedExtraJvmDiagnostics: Diagnostics = LazyJvmDiagnostics {
duplicateSignatureFactory.reportDiagnostics()
extraJvmDiagnosticsTrace.bindingContext.diagnostics
}
public val moduleName: String = moduleName ?: JvmCodegenUtil.getModuleName(module)
public val classBuilderMode: ClassBuilderMode = builderFactory.getClassBuilderMode()
@@ -110,6 +117,7 @@ public class GenerationState @JvmOverloads constructor(
public val reflectionTypes: ReflectionTypes = ReflectionTypes(module)
public val jvmRuntimeTypes: JvmRuntimeTypes = JvmRuntimeTypes()
public val factory: ClassFileFactory
private val duplicateSignatureFactory: BuilderFactoryForDuplicateSignatureDiagnostics
public val replSpecific = ForRepl()
@@ -135,12 +143,13 @@ public class GenerationState @JvmOverloads constructor(
init {
val optimizationClassBuilderFactory = OptimizationClassBuilderFactory(builderFactory, disableOptimization)
var interceptedBuilderFactory: ClassBuilderFactory = BuilderFactoryForDuplicateSignatureDiagnostics(
duplicateSignatureFactory = BuilderFactoryForDuplicateSignatureDiagnostics(
optimizationClassBuilderFactory, this.bindingContext, diagnostics, fileClassesProvider,
getIncrementalCacheForThisTarget(),
this.moduleName)
interceptedBuilderFactory = BuilderFactoryForDuplicateClassNameDiagnostics(interceptedBuilderFactory, diagnostics);
var interceptedBuilderFactory: ClassBuilderFactory
= BuilderFactoryForDuplicateClassNameDiagnostics(duplicateSignatureFactory, diagnostics)
val interceptExtensions = ClassBuilderInterceptorExtension.getInstances(project)
@@ -168,3 +177,20 @@ public class GenerationState @JvmOverloads constructor(
interceptedBuilderFactory.close()
}
}
private class LazyJvmDiagnostics(compute: () -> Diagnostics): Diagnostics {
private val delegate by lazy(LazyThreadSafetyMode.SYNCHRONIZED, compute)
override val modificationTracker: ModificationTracker
get() = delegate.modificationTracker
override fun all(): Collection<Diagnostic> = delegate.all()
override fun forElement(psiElement: PsiElement) = delegate.forElement(psiElement)
override fun isEmpty() = delegate.isEmpty()
override fun noSuppression() = delegate.noSuppression()
override fun iterator() = delegate.iterator()
}

View File

@@ -20,7 +20,6 @@ import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import kotlin.CollectionsKt;
import kotlin.Pair;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.BuiltinsPackageFragment;
@@ -50,7 +49,7 @@ import org.jetbrains.kotlin.platform.JavaToKotlinClassMap;
import org.jetbrains.kotlin.psi.KtExpression;
import org.jetbrains.kotlin.psi.KtFile;
import org.jetbrains.kotlin.psi.KtFunctionLiteral;
import org.jetbrains.kotlin.psi.KtFunctionLiteralExpression;
import org.jetbrains.kotlin.psi.KtLambdaExpression;
import org.jetbrains.kotlin.resolve.*;
import org.jetbrains.kotlin.resolve.annotations.AnnotationUtilKt;
import org.jetbrains.kotlin.resolve.calls.model.DefaultValueArgument;
@@ -405,10 +404,11 @@ public class JetTypeMapper {
}
TypeConstructor constructor = jetType.getConstructor();
DeclarationDescriptor descriptor = constructor.getDeclarationDescriptor();
if (constructor instanceof IntersectionTypeConstructor) {
jetType = CommonSupertypes.commonSupertype(new ArrayList<KotlinType>(constructor.getSupertypes()));
constructor = jetType.getConstructor();
}
DeclarationDescriptor descriptor = constructor.getDeclarationDescriptor();
if (descriptor == null) {
throw new UnsupportedOperationException("no descriptor for type constructor of " + jetType);
@@ -581,7 +581,14 @@ public class JetTypeMapper {
@NotNull TypeMappingMode mode
) {
if (signatureVisitor != null) {
if (hasNothingInArguments(type) || type.getArguments().isEmpty()) {
// Nothing mapping rules:
// Map<Nothing, Foo> -> Map
// Map<Foo, List<Nothing>> -> Map<Foo, List>
// In<Nothing, Foo> == In<*, Foo> -> In<?, Foo>
// In<Nothing, Nothing> -> In
// Inv<in Nothing, Foo> -> Inv
if (hasNothingInNonContravariantPosition(type) || type.getArguments().isEmpty()) {
signatureVisitor.writeAsmType(asmType);
return;
}
@@ -638,7 +645,11 @@ public class JetTypeMapper {
TypeParameterDescriptor parameter = item.getFirst();
TypeProjection argument = item.getSecond();
if (argument.isStarProjection()) {
if (
argument.isStarProjection() ||
// In<Nothing, Foo> == In<*, Foo> -> In<?, Foo>
KotlinBuiltIns.isNothing(argument.getType()) && parameter.getVariance() == Variance.IN_VARIANCE
) {
signatureVisitor.writeUnboundedWildcard();
}
else {
@@ -656,22 +667,22 @@ public class JetTypeMapper {
}
}
private static boolean hasNothingInArguments(KotlinType jetType) {
boolean hasNothingInArguments = CollectionsKt.any(jetType.getArguments(), new Function1<TypeProjection, Boolean>() {
@Override
public Boolean invoke(TypeProjection projection) {
return KotlinBuiltIns.isNothingOrNullableNothing(projection.getType());
}
});
private static boolean hasNothingInNonContravariantPosition(KotlinType kotlinType) {
List<TypeParameterDescriptor> parameters = kotlinType.getConstructor().getParameters();
List<TypeProjection> arguments = kotlinType.getArguments();
if (hasNothingInArguments) return true;
for (int i = 0; i < arguments.size(); i++) {
TypeProjection projection = arguments.get(i);
return CollectionsKt.any(jetType.getArguments(), new Function1<TypeProjection, Boolean>() {
@Override
public Boolean invoke(TypeProjection projection) {
return !projection.isStarProjection() && hasNothingInArguments(projection.getType());
}
});
if (projection.isStarProjection()) continue;
KotlinType type = projection.getType();
if (KotlinBuiltIns.isNullableNothing(type) ||
KotlinBuiltIns.isNothing(type) && parameters.get(i).getVariance() != Variance.IN_VARIANCE) return true;
}
return false;
}
@NotNull
@@ -748,7 +759,7 @@ public class JetTypeMapper {
ClassDescriptor ownerForDefault = (ClassDescriptor) baseMethodDescriptor.getContainingDeclaration();
ownerForDefaultImpl = isJvmInterface(ownerForDefault) ? mapDefaultImpls(ownerForDefault) : mapClass(ownerForDefault);
if (isInterface && (superCall || descriptor.getVisibility() == Visibilities.PRIVATE)) {
if (isInterface && (superCall || descriptor.getVisibility() == Visibilities.PRIVATE || isAccessor(descriptor))) {
thisClass = mapClass(currentOwner);
if (declarationOwner instanceof JavaClassDescriptor) {
invokeOpcode = INVOKESPECIAL;
@@ -778,7 +789,7 @@ public class JetTypeMapper {
}
FunctionDescriptor overriddenSpecialBuiltinFunction =
SpecialBuiltinMembers.<FunctionDescriptor>getOverriddenBuiltinWithDifferentJvmDescriptor(functionDescriptor.getOriginal());
SpecialBuiltinMembers.<FunctionDescriptor>getOverriddenBuiltinReflectingJvmDescriptor(functionDescriptor.getOriginal());
FunctionDescriptor functionToCall = overriddenSpecialBuiltinFunction != null && !superCall
? overriddenSpecialBuiltinFunction.getOriginal()
: functionDescriptor.getOriginal();
@@ -888,7 +899,7 @@ public class JetTypeMapper {
PsiElement element = DescriptorToSourceUtils.getSourceFromDescriptor(descriptor);
if (element instanceof KtFunctionLiteral) {
PsiElement expression = element.getParent();
if (expression instanceof KtFunctionLiteralExpression) {
if (expression instanceof KtLambdaExpression) {
SamType samType = bindingContext.get(SAM_VALUE, (KtExpression) expression);
if (samType != null) {
return samType.getAbstractMethod().getName().asString();
@@ -957,7 +968,7 @@ public class JetTypeMapper {
public JvmMethodSignature mapSignature(@NotNull FunctionDescriptor f, @NotNull OwnerKind kind) {
if (f.getInitialSignatureDescriptor() != null && f != f.getInitialSignatureDescriptor()) {
// Overrides of special builtin in Kotlin classes always have special signature
if (SpecialBuiltinMembers.getOverriddenBuiltinWithDifferentJvmDescriptor(f) == null ||
if (SpecialBuiltinMembers.getOverriddenBuiltinReflectingJvmDescriptor(f) == null ||
f.getContainingDeclaration().getOriginal() instanceof JavaClassDescriptor) {
return mapSignature(f.getInitialSignatureDescriptor(), kind);
}

View File

@@ -26,7 +26,8 @@ internal class TypeMappingMode private constructor(
val skipDeclarationSiteWildcards: Boolean = false,
val skipDeclarationSiteWildcardsIfPossible: Boolean = false,
private val genericArgumentMode: TypeMappingMode? = null,
private val genericContravariantArgumentMode: TypeMappingMode? = genericArgumentMode
private val genericContravariantArgumentMode: TypeMappingMode? = genericArgumentMode,
private val genericInvariantArgumentMode: TypeMappingMode? = genericArgumentMode
) {
companion object {
/**
@@ -86,11 +87,18 @@ internal class TypeMappingMode private constructor(
else
null
val invariantArgumentMode =
if (canBeUsedInSupertypePosition)
getOptimalModeForSignaturePart(type, isForAnnotationParameter, canBeUsedInSupertypePosition = false)
else
null
return TypeMappingMode(
isForAnnotationParameter = isForAnnotationParameter,
skipDeclarationSiteWildcards = !canBeUsedInSupertypePosition,
skipDeclarationSiteWildcardsIfPossible = true,
genericContravariantArgumentMode = contravariantArgumentMode)
genericContravariantArgumentMode = contravariantArgumentMode,
genericInvariantArgumentMode = invariantArgumentMode)
}
@JvmStatic
@@ -107,6 +115,7 @@ internal class TypeMappingMode private constructor(
fun toGenericArgumentMode(effectiveVariance: Variance): TypeMappingMode =
when (effectiveVariance) {
Variance.IN_VARIANCE -> genericContravariantArgumentMode ?: this
Variance.INVARIANT -> genericInvariantArgumentMode ?: this
else -> genericArgumentMode ?: this
}
}

View File

@@ -40,7 +40,7 @@ private fun KotlinType.canHaveSubtypesIgnoringNullability(): Boolean {
when (descriptor) {
is TypeParameterDescriptor -> return true
is ClassDescriptor -> if (descriptor.modality.isOverridable) return true
is ClassDescriptor -> if (!descriptor.isFinalClass) return true
}
for ((parameter, argument) in constructor.parameters.zip(arguments)) {

View File

@@ -30,10 +30,11 @@ public class EnumSwitchCodegen extends SwitchCodegen {
public EnumSwitchCodegen(
@NotNull KtWhenExpression expression,
boolean isStatement,
boolean isExhaustive,
@NotNull ExpressionCodegen codegen,
@NotNull WhenByEnumsMapping mapping
) {
super(expression, isStatement, codegen);
super(expression, isStatement, isExhaustive, codegen);
this.mapping = mapping;
}

View File

@@ -26,9 +26,10 @@ public class IntegralConstantsSwitchCodegen extends SwitchCodegen {
public IntegralConstantsSwitchCodegen(
@NotNull KtWhenExpression expression,
boolean isStatement,
boolean isExhaustive,
@NotNull ExpressionCodegen codegen
) {
super(expression, isStatement, codegen);
super(expression, isStatement, isExhaustive, codegen);
}
@Override

View File

@@ -47,7 +47,7 @@ public class MappingClassesForWhenByEnumCodegen {
cb.defineClass(
srcFile,
V1_6,
ACC_FINAL | ACC_SYNTHETIC | ACC_PUBLIC,
ACC_PUBLIC | ACC_FINAL | ACC_SUPER | ACC_SYNTHETIC,
mappingsClass.getInternalName(),
null,
OBJECT_TYPE.getInternalName(),

View File

@@ -40,9 +40,10 @@ public class StringSwitchCodegen extends SwitchCodegen {
public StringSwitchCodegen(
@NotNull KtWhenExpression expression,
boolean isStatement,
boolean isExhaustive,
@NotNull ExpressionCodegen codegen
) {
super(expression, isStatement, codegen);
super(expression, isStatement, isExhaustive, codegen);
}
@Override

View File

@@ -35,6 +35,7 @@ import java.util.*;
abstract public class SwitchCodegen {
protected final KtWhenExpression expression;
protected final boolean isStatement;
protected final boolean isExhaustive;
protected final ExpressionCodegen codegen;
protected final BindingContext bindingContext;
protected final Type subjectType;
@@ -49,10 +50,11 @@ abstract public class SwitchCodegen {
public SwitchCodegen(
@NotNull KtWhenExpression expression, boolean isStatement,
@NotNull ExpressionCodegen codegen
boolean isExhaustive, @NotNull ExpressionCodegen codegen
) {
this.expression = expression;
this.isStatement = isStatement;
this.isExhaustive = isExhaustive;
this.codegen = codegen;
this.bindingContext = codegen.getBindingContext();
@@ -70,7 +72,7 @@ abstract public class SwitchCodegen {
boolean hasElse = expression.getElseExpression() != null;
// if there is no else-entry and it's statement then default --- endLabel
defaultLabel = (hasElse || !isStatement) ? elseLabel : endLabel;
defaultLabel = (hasElse || !isStatement || isExhaustive) ? elseLabel : endLabel;
generateSubject();
@@ -79,9 +81,9 @@ abstract public class SwitchCodegen {
generateEntries();
// there is no else-entry but this is not statement, so we should return Unit
if (!hasElse && !isStatement) {
if (!hasElse && (!isStatement || isExhaustive)) {
v.visitLabel(elseLabel);
codegen.putUnitInstanceOntoStackForNonExhaustiveWhen(expression);
codegen.putUnitInstanceOntoStackForNonExhaustiveWhen(expression, isStatement);
}
codegen.markLineNumber(expression, isStatement);

View File

@@ -102,6 +102,7 @@ public class SwitchCodegenUtil {
public static SwitchCodegen buildAppropriateSwitchCodegenIfPossible(
@NotNull KtWhenExpression expression,
boolean isStatement,
boolean isExhaustive,
@NotNull ExpressionCodegen codegen
) {
BindingContext bindingContext = codegen.getBindingContext();
@@ -114,15 +115,15 @@ public class SwitchCodegenUtil {
WhenByEnumsMapping mapping = codegen.getBindingContext().get(CodegenBinding.MAPPING_FOR_WHEN_BY_ENUM, expression);
if (mapping != null) {
return new EnumSwitchCodegen(expression, isStatement, codegen, mapping);
return new EnumSwitchCodegen(expression, isStatement, isExhaustive, codegen, mapping);
}
if (isIntegralConstantsSwitch(expression, subjectType, bindingContext)) {
return new IntegralConstantsSwitchCodegen(expression, isStatement, codegen);
return new IntegralConstantsSwitchCodegen(expression, isStatement, isExhaustive, codegen);
}
if (isStringConstantsSwitch(expression, subjectType, bindingContext)) {
return new StringSwitchCodegen(expression, isStatement, codegen);
return new StringSwitchCodegen(expression, isStatement, isExhaustive, codegen);
}
return null;

View File

@@ -16,27 +16,20 @@
package org.jetbrains.kotlin.serialization.builtins
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.resolve.constants.NullValue
import org.jetbrains.kotlin.builtins.BuiltInSerializerProtocol
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.serialization.*
import org.jetbrains.kotlin.types.KotlinType
public class BuiltInsSerializerExtension : SerializerExtension() {
private val stringTable = StringTableImpl()
private val annotationSerializer = AnnotationSerializer(stringTable)
override fun getStringTable(): StringTable = stringTable
import org.jetbrains.kotlin.serialization.DescriptorSerializer
import org.jetbrains.kotlin.serialization.KotlinSerializerExtensionBase
import org.jetbrains.kotlin.serialization.ProtoBuf
public class BuiltInsSerializerExtension : KotlinSerializerExtensionBase(BuiltInSerializerProtocol) {
override fun shouldUseTypeTable(): Boolean = true
override fun serializeClass(descriptor: ClassDescriptor, proto: ProtoBuf.Class.Builder) {
for (annotation in descriptor.annotations) {
proto.addExtension(BuiltInsProtoBuf.classAnnotation, annotationSerializer.serializeAnnotation(annotation))
}
}
override fun serializePackage(packageFragments: Collection<PackageFragmentDescriptor>, proto: ProtoBuf.Package.Builder) {
if (packageFragments.isEmpty()) return
val classes = packageFragments.flatMap {
it.getMemberScope().getContributedDescriptors(DescriptorKindFilter.CLASSIFIERS).filterIsInstance<ClassDescriptor>()
}
@@ -44,40 +37,7 @@ public class BuiltInsSerializerExtension : SerializerExtension() {
for (descriptor in DescriptorSerializer.sort(classes)) {
proto.addExtension(BuiltInsProtoBuf.className, stringTable.getSimpleNameIndex(descriptor.name))
}
}
override fun serializeConstructor(descriptor: ConstructorDescriptor, proto: ProtoBuf.Constructor.Builder) {
for (annotation in descriptor.annotations) {
proto.addExtension(BuiltInsProtoBuf.constructorAnnotation, annotationSerializer.serializeAnnotation(annotation))
}
}
override fun serializeFunction(descriptor: FunctionDescriptor, proto: ProtoBuf.Function.Builder) {
for (annotation in descriptor.annotations) {
proto.addExtension(BuiltInsProtoBuf.functionAnnotation, annotationSerializer.serializeAnnotation(annotation))
}
}
override fun serializeProperty(descriptor: PropertyDescriptor, proto: ProtoBuf.Property.Builder) {
for (annotation in descriptor.annotations) {
proto.addExtension(BuiltInsProtoBuf.propertyAnnotation, annotationSerializer.serializeAnnotation(annotation))
}
val compileTimeConstant = descriptor.compileTimeInitializer ?: return
if (compileTimeConstant !is NullValue) {
val valueProto = annotationSerializer.valueProto(compileTimeConstant)
proto.setExtension(BuiltInsProtoBuf.compileTimeValue, valueProto.build())
}
}
override fun serializeValueParameter(descriptor: ValueParameterDescriptor, proto: ProtoBuf.ValueParameter.Builder) {
for (annotation in descriptor.annotations) {
proto.addExtension(BuiltInsProtoBuf.parameterAnnotation, annotationSerializer.serializeAnnotation(annotation))
}
}
override fun serializeType(type: KotlinType, proto: ProtoBuf.Type.Builder) {
for (annotation in type.annotations) {
proto.addExtension(BuiltInsProtoBuf.typeAnnotation, annotationSerializer.serializeAnnotation(annotation))
}
proto.setExtension(BuiltInsProtoBuf.packageFqName, stringTable.getPackageFqNameIndex(packageFragments.first().fqName))
}
}

View File

@@ -17,3 +17,11 @@
package org.jetbrains.kotlin.cli.common
public val KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY = "kotlin.environment.keepalive"
fun String?.toBooleanLenient(): Boolean? = when (this?.toLowerCase()) {
null -> false
in listOf("", "yes", "true", "on", "y") -> true
in listOf("no", "false", "off", "n") -> false
else -> null
}

View File

@@ -64,6 +64,9 @@ public class K2JVMCompilerArguments extends CommonCompilerArguments {
@Argument(value = "Xreport-perf", description = "Report detailed performance statistics")
public boolean reportPerf;
@Argument(value = "Xmultifile-facades-open", description = "Compile multifile facade classes as open")
public boolean multifileFacadesOpen;
// Paths to output directories for friend modules.
public String[] friendPaths;

View File

@@ -20,6 +20,8 @@ import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import org.jetbrains.annotations.NotNull;
import java.util.*;
public class GroupingMessageCollector implements MessageCollector {
private final MessageCollector delegate;
@@ -48,13 +50,14 @@ public class GroupingMessageCollector implements MessageCollector {
public void flush() {
boolean hasError = false;
for (String path : groupedMessages.keySet()) {
Collection<String> keys = sortedKeys();
for (String path : keys) {
for (Message message : groupedMessages.get(path)) {
hasError |= CompilerMessageSeverity.ERRORS.contains(message.severity);
}
}
for (String path : groupedMessages.keySet()) {
for (String path : keys) {
for (Message message : groupedMessages.get(path)) {
if (!hasError || CompilerMessageSeverity.ERRORS.contains(message.severity)) {
delegate.report(message.severity, message.message, message.location);
@@ -65,6 +68,22 @@ public class GroupingMessageCollector implements MessageCollector {
groupedMessages.clear();
}
@NotNull
private Collection<String> sortedKeys() {
List<String> sortedKeys = new ArrayList<String>(groupedMessages.keySet());
// ensure that messages with no location i.e. perf, incomplete hierarchy are always reported first
Collections.sort(sortedKeys, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1 == o2) return 0;
if (o1 == null) return -1;
if (o2 == null) return 1;
return o1.compareTo(o2);
}
});
return sortedKeys;
}
private static class Message {
private final CompilerMessageSeverity severity;
private final String message;

View File

@@ -275,6 +275,7 @@ public open class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
configuration.put(JVMConfigurationKeys.DISABLE_PARAM_ASSERTIONS, arguments.noParamAssertions)
configuration.put(JVMConfigurationKeys.DISABLE_INLINE, arguments.noInline)
configuration.put(JVMConfigurationKeys.DISABLE_OPTIMIZATION, arguments.noOptimize)
configuration.put(JVMConfigurationKeys.MULTIFILE_FACADES_OPEN, arguments.multifileFacadesOpen);
}
private fun getClasspath(paths: KotlinPaths, arguments: K2JVMCompilerArguments): List<File> {

View File

@@ -80,11 +80,13 @@ public class CliLightClassGenerationSupport(project: Project) : LightClassGenera
}
override fun getContextForPackage(files: Collection<KtFile>): LightClassConstructionContext {
return getContext()
return LightClassConstructionContext(bindingContext, module)
}
override fun getContextForClassOrObject(classOrObject: KtClassOrObject): LightClassConstructionContext {
return getContext()
//force resolve companion for light class generation
bindingContext.get(BindingContext.CLASS, classOrObject)?.companionObjectDescriptor
return LightClassConstructionContext(bindingContext, module)
}
private fun getContext(): LightClassConstructionContext {

View File

@@ -35,7 +35,9 @@ import com.intellij.openapi.fileTypes.PlainTextFileType
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.PersistentFSConstants
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.FileContextProvider
import com.intellij.psi.PsiElementFinder
@@ -60,6 +62,7 @@ import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.ERROR
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.WARNING
import org.jetbrains.kotlin.cli.common.toBooleanLenient
import org.jetbrains.kotlin.cli.jvm.config.JVMConfigurationKeys
import org.jetbrains.kotlin.cli.jvm.config.JavaSourceRoot
import org.jetbrains.kotlin.cli.jvm.config.JvmClasspathRoot
@@ -110,6 +113,10 @@ public class KotlinCoreEnvironment private constructor(
it
}
init {
PersistentFSConstants.setMaxIntellisenseFileSize(FileUtilRt.LARGE_FOR_CONTENT_LOADING)
}
init {
val project = projectEnvironment.getProject()
project.registerService(javaClass<DeclarationProviderFactoryService>(), CliDeclarationProviderFactoryService(sourceFiles))
@@ -258,7 +265,7 @@ public class KotlinCoreEnvironment private constructor(
val appEnv = getOrCreateApplicationEnvironmentForProduction(configuration, configFilePaths)
// Disposing of the environment is unsafe in production then parallel builds are enabled, but turning it off universally
// breaks a lot of tests, therefore it is disabled for production and enabled for tests
if (System.getProperty(KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY) == null) {
if (!(System.getProperty(KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY).toBooleanLenient() ?: false)) {
// JPS may run many instances of the compiler in parallel (there's an option for compiling independent modules in parallel in IntelliJ)
// All projects share the same ApplicationEnvironment, and when the last project is disposed, the ApplicationEnvironment is disposed as well
Disposer.register(parentDisposable, object : Disposable {
@@ -312,8 +319,7 @@ public class KotlinCoreEnvironment private constructor(
public fun disposeApplicationEnvironment() {
synchronized (APPLICATION_LOCK) {
if (ourApplicationEnvironment == null) return
val environment = ourApplicationEnvironment
val environment = ourApplicationEnvironment ?: return
ourApplicationEnvironment = null
Disposer.dispose(environment.getParentDisposable())
}

View File

@@ -438,7 +438,8 @@ public class KotlinToJVMBytecodeCompiler {
targetId,
moduleName,
outputDirectory,
incrementalCompilationComponents
incrementalCompilationComponents,
configuration.get(JVMConfigurationKeys.MULTIFILE_FACADES_OPEN, false)
);
ProgressIndicatorAndCompilationCanceledStatus.checkCanceled();

View File

@@ -35,6 +35,8 @@ public class JVMConfigurationKeys {
CompilerConfigurationKey.create("disable inline");
public static final CompilerConfigurationKey<Boolean> DISABLE_OPTIMIZATION =
CompilerConfigurationKey.create("disable optimization");
public static final CompilerConfigurationKey<Boolean> MULTIFILE_FACADES_OPEN =
CompilerConfigurationKey.create("compile multifile facade classes as open");
public static final CompilerConfigurationKey<IncrementalCompilationComponents> INCREMENTAL_COMPILATION_COMPONENTS =
CompilerConfigurationKey.create("incremental cache provider");

View File

@@ -65,7 +65,7 @@ import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo;
import org.jetbrains.kotlin.resolve.jvm.JvmClassName;
import org.jetbrains.kotlin.resolve.jvm.TopDownAnalyzerFacadeForJVM;
import org.jetbrains.kotlin.resolve.lazy.ResolveSession;
import org.jetbrains.kotlin.resolve.lazy.data.JetClassLikeInfo;
import org.jetbrains.kotlin.resolve.lazy.data.KtClassLikeInfo;
import org.jetbrains.kotlin.resolve.lazy.declarations.*;
import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyScriptDescriptor;
import org.jetbrains.kotlin.resolve.scopes.LexicalScope;
@@ -478,7 +478,7 @@ public class ReplInterpreter {
@NotNull
@Override
public ClassMemberDeclarationProvider getClassMemberDeclarationProvider(@NotNull JetClassLikeInfo classLikeInfo) {
public ClassMemberDeclarationProvider getClassMemberDeclarationProvider(@NotNull KtClassLikeInfo classLikeInfo) {
return delegateFactory.getClassMemberDeclarationProvider(classLikeInfo);
}
@@ -492,6 +492,11 @@ public class ReplInterpreter {
return this.delegateFactory.getPackageMemberDeclarationProvider(packageFqName);
}
@Override
public void diagnoseMissingPackageFragment(KtFile file) {
this.delegateFactory.diagnoseMissingPackageFragment(file);
}
public static class AdaptablePackageMemberDeclarationProvider extends DelegatePackageMemberDeclarationProvider {
@NotNull
private PackageMemberDeclarationProvider delegateProvider;

View File

@@ -35,7 +35,6 @@ import org.jetbrains.kotlin.resolve.QualifiedExpressionResolver
import org.jetbrains.kotlin.resolve.jvm.JavaClassFinderPostConstruct
import org.jetbrains.kotlin.resolve.jvm.JavaDescriptorResolver
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform
import org.jetbrains.kotlin.resolve.lazy.FileScopeProvider
import org.jetbrains.kotlin.resolve.lazy.FileScopeProviderImpl
import org.jetbrains.kotlin.resolve.lazy.ResolveSession
import org.jetbrains.kotlin.resolve.lazy.TopLevelDescriptorProvider
@@ -54,9 +53,8 @@ class ReplFileScopeProvider(
moduleDescriptor: ModuleDescriptor,
qualifiedExpressionResolver: QualifiedExpressionResolver,
bindingTrace: BindingTrace,
ktImportsFactory: KtImportsFactory,
additionalScopes: Iterable<FileScopeProvider.AdditionalScopes>
) : FileScopeProviderImpl(topLevelDescriptorProvider, storageManager, moduleDescriptor, qualifiedExpressionResolver, bindingTrace, ktImportsFactory, additionalScopes) {
ktImportsFactory: KtImportsFactory
) : FileScopeProviderImpl(topLevelDescriptorProvider, storageManager, moduleDescriptor, qualifiedExpressionResolver, bindingTrace, ktImportsFactory) {
override fun getFileResolutionScope(file: KtFile): LexicalScope
= lastLineScopeProvider.lastLineScope ?: super.getFileResolutionScope(file)

View File

@@ -13,5 +13,6 @@
<orderEntry type="library" name="intellij-core" level="project" />
<orderEntry type="library" scope="TEST" name="junit-4.12" level="project" />
<orderEntry type="library" exported="" name="javax.inject" level="project" />
<orderEntry type="library" scope="TEST" name="kotlin-test" level="project" />
</component>
</module>

View File

@@ -16,8 +16,10 @@
package org.jetbrains.kotlin.daemon.client
import com.intellij.openapi.progress.ProcessCanceledException
import org.jetbrains.kotlin.daemon.common.CompilerCallbackServicesFacade
import org.jetbrains.kotlin.daemon.common.LoopbackNetworkInterface
import org.jetbrains.kotlin.daemon.common.RmiFriendlyCompilationCancelledException
import org.jetbrains.kotlin.daemon.common.SOCKET_ANY_FREE_PORT
import org.jetbrains.kotlin.incremental.components.LookupInfo
import org.jetbrains.kotlin.incremental.components.LookupTracker
@@ -80,6 +82,13 @@ class CompilerCallbackServicesFacadeServer(
override fun lookupTracker_isDoNothing(): Boolean = lookupTracker_isDoNothing
override fun compilationCanceledStatus_checkCanceled() {
compilationCancelledStatus!!.checkCanceled()
try {
compilationCancelledStatus!!.checkCanceled()
}
catch (e: ProcessCanceledException) {
// avoid passing exceptions that may have different serialVersionUID on across rmi border
// TODO: doublecheck whether we need to distinguish different cancellation exceptions
throw RmiFriendlyCompilationCancelledException()
}
}
}

View File

@@ -19,6 +19,7 @@ package org.jetbrains.kotlin.daemon.common
import org.jetbrains.kotlin.incremental.components.LookupInfo
import org.jetbrains.kotlin.load.kotlin.incremental.components.JvmPackagePartProto
import org.jetbrains.kotlin.modules.TargetId
import java.io.Serializable
import java.rmi.Remote
import java.rmi.RemoteException
@@ -81,7 +82,13 @@ interface CompilerCallbackServicesFacade : Remote {
// ----------------------------------------------------
// CompilationCanceledStatus
@Throws(RemoteException::class)
@Throws(RemoteException::class, RmiFriendlyCompilationCancelledException::class)
fun compilationCanceledStatus_checkCanceled(): Unit
}
class RmiFriendlyCompilationCancelledException: Exception(), Serializable {
companion object {
private val serialVersionUID: Long = 8228357578L // just a random number, but should never be changed to avoid deserialization problems
}
}

View File

@@ -19,6 +19,7 @@ package org.jetbrains.kotlin.daemon
import com.intellij.openapi.vfs.impl.ZipHandler
import org.jetbrains.kotlin.cli.common.CLICompiler
import org.jetbrains.kotlin.cli.common.ExitCode
import org.jetbrains.kotlin.cli.common.KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.config.Services
import org.jetbrains.kotlin.daemon.common.*
@@ -75,6 +76,10 @@ class CompileServiceImpl(
val onShutdown: () -> Unit
) : CompileService {
init {
System.setProperty(KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY, "true")
}
// wrapped in a class to encapsulate alive check logic
private class ClientOrSessionProxy(val aliveFlagPath: String?) {
val registered = nowSeconds()

View File

@@ -61,7 +61,7 @@ class LazyClasspathWatcher(classpath: Iterable<String>,
fileIds = classpath
.map { File(it) }
.asSequence()
.flatMap { FileTreeWalk(it, filter = ::isClasspathFile) }
.flatMap { it.walk().filter(::isClasspathFile) }
.map { FileId(it, it.lastModified(), it.md5Digest()) }
.toArrayList()
val nowMs = TimeUnit.MILLISECONDS.toMillis(System.nanoTime())

View File

@@ -20,6 +20,8 @@ import org.jetbrains.kotlin.progress.CompilationCanceledStatus
import org.jetbrains.kotlin.daemon.common.CompilerCallbackServicesFacade
import org.jetbrains.kotlin.daemon.common.DummyProfiler
import org.jetbrains.kotlin.daemon.common.Profiler
import org.jetbrains.kotlin.daemon.common.RmiFriendlyCompilationCancelledException
import org.jetbrains.kotlin.progress.CompilationCanceledException
import java.util.concurrent.TimeUnit
val CANCELED_STATUS_CHECK_THRESHOLD_NS = TimeUnit.MILLISECONDS.toNanos(100)
@@ -30,7 +32,12 @@ class RemoteCompilationCanceledStatusClient(val facade: CompilerCallbackServices
val curNanos = System.nanoTime()
if (curNanos - lastChecked > CANCELED_STATUS_CHECK_THRESHOLD_NS) {
profiler.withMeasure(this) {
facade.compilationCanceledStatus_checkCanceled()
try {
facade.compilationCanceledStatus_checkCanceled()
}
catch (e: RmiFriendlyCompilationCancelledException) {
throw CompilationCanceledException()
}
}
lastChecked = curNanos
}

View File

@@ -21,13 +21,13 @@ import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.container.*
import org.jetbrains.kotlin.context.LazyResolveToken
import org.jetbrains.kotlin.context.ModuleContext
import org.jetbrains.kotlin.descriptors.PackagePartProvider
import org.jetbrains.kotlin.frontend.di.configureModule
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.load.java.JavaClassFinderImpl
import org.jetbrains.kotlin.load.java.JavaFlexibleTypeCapabilitiesProvider
import org.jetbrains.kotlin.load.java.components.*
import org.jetbrains.kotlin.load.java.lazy.ModuleClassResolver
import org.jetbrains.kotlin.descriptors.PackagePartProvider
import org.jetbrains.kotlin.load.java.lazy.SingleModuleClassResolver
import org.jetbrains.kotlin.load.java.sam.SamConversionResolverImpl
import org.jetbrains.kotlin.load.java.structure.impl.JavaPropertyInitializerEvaluatorImpl
@@ -41,7 +41,6 @@ import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform
import org.jetbrains.kotlin.resolve.lazy.FileScopeProviderImpl
import org.jetbrains.kotlin.resolve.lazy.ResolveSession
import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactory
import org.jetbrains.kotlin.synthetic.AdditionalScopesWithJavaSyntheticExtensions
public fun StorageComponentContainer.configureJavaTopDownAnalysis(moduleContentScope: GlobalSearchScope, project: Project, lookupTracker: LookupTracker) {
useInstance(moduleContentScope)
@@ -65,7 +64,6 @@ public fun StorageComponentContainer.configureJavaTopDownAnalysis(moduleContentS
useImpl<JavaSourceElementFactoryImpl>()
useImpl<JavaLazyAnalyzerPostConstruct>()
useImpl<JavaFlexibleTypeCapabilitiesProvider>()
useImpl<AdditionalScopesWithJavaSyntheticExtensions>()
}
public fun createContainerForLazyResolveWithJava(

View File

@@ -27,10 +27,8 @@ import org.jetbrains.kotlin.resolve.calls.context.CallResolutionContext
import org.jetbrains.kotlin.resolve.calls.context.ResolutionContext
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.types.upperIfFlexible
public class RuntimeAssertionInfo(public val needNotNullAssertion: Boolean, public val message: String) {
public interface DataFlowExtras {
@@ -53,7 +51,7 @@ public class RuntimeAssertionInfo(public val needNotNullAssertion: Boolean, publ
dataFlowExtras: DataFlowExtras
): RuntimeAssertionInfo? {
fun assertNotNull(): Boolean {
if (expectedType.isError() || expressionType.isError()) return false
if (expectedType.isError || expressionType.isError) return false
// T : Any, T! = T..T?
// Let T$ will be copy of T! with enhanced nullability.
@@ -94,7 +92,7 @@ public object RuntimeAssertionsTypeChecker : AdditionalTypeChecker {
override val canBeNull: Boolean
get() = c.dataFlowInfo.getPredictableNullability(dataFlowValue).canBeNull()
override val possibleTypes: Set<KotlinType>
get() = c.dataFlowInfo.getPossibleTypes(dataFlowValue)
get() = c.dataFlowInfo.getCollectedTypes(dataFlowValue)
override val presentableText: String
get() = StringUtil.trimMiddle(expression.getText(), 50)

View File

@@ -21,6 +21,7 @@ import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl;
import org.jetbrains.kotlin.resolve.ExternalOverridabilityCondition;
import org.jetbrains.kotlin.resolve.OverridingUtil;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.kotlin.types.TypeSubstitutor;
import org.jetbrains.kotlin.types.TypeUtils;
@@ -28,20 +29,30 @@ import org.jetbrains.kotlin.types.TypeUtils;
import java.util.List;
public class SamAdapterOverridabilityCondition implements ExternalOverridabilityCondition {
@NotNull
@Override
public boolean isOverridable(@NotNull CallableDescriptor superDescriptor, @NotNull CallableDescriptor subDescriptor) {
if (!(subDescriptor instanceof SimpleFunctionDescriptor)) {
return true;
public Result isOverridable(
@NotNull CallableDescriptor superDescriptor,
@NotNull CallableDescriptor subDescriptor,
@Nullable ClassDescriptor subClassDescriptor
) {
if (!(subDescriptor instanceof SimpleFunctionDescriptor) || !(superDescriptor instanceof SimpleFunctionDescriptor)) {
return Result.UNKNOWN;
}
SimpleFunctionDescriptor superOriginal = getOriginalOfSamAdapterFunction((SimpleFunctionDescriptor) superDescriptor);
SimpleFunctionDescriptor subOriginal = getOriginalOfSamAdapterFunction((SimpleFunctionDescriptor) subDescriptor);
if (superOriginal == null || subOriginal == null) { // super or sub is/overrides DECLARATION
return subOriginal == null; // DECLARATION can override anything
return subOriginal == null ? Result.UNKNOWN : Result.INCOMPATIBLE; // DECLARATION can override anything
}
OverridingUtil.OverrideCompatibilityInfo basicResult = OverridingUtil.DEFAULT
.isOverridableByWithoutExternalConditions(superDescriptor, subDescriptor, /* checkReturnType = */ false);
if (basicResult.getResult() != OverridingUtil.OverrideCompatibilityInfo.Result.OVERRIDABLE) return Result.UNKNOWN;
// inheritor if SYNTHESIZED can override inheritor of SYNTHESIZED if their originals have same erasure
return equalErasure(superOriginal, subOriginal);
return equalErasure(superOriginal, subOriginal) ? Result.UNKNOWN : Result.INCOMPATIBLE;
}
private static boolean equalErasure(@NotNull FunctionDescriptor fun1, @NotNull FunctionDescriptor fun2) {

View File

@@ -17,7 +17,6 @@
package org.jetbrains.kotlin.load.java.structure.impl;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.load.java.structure.*;
@@ -113,8 +112,8 @@ public class JavaClassifierTypeImpl extends JavaTypeImpl<PsiClassType> implement
// parameters including ones from outer class
Iterable<PsiTypeParameter> parameters = classifier instanceof JavaClassImpl
? getReversedTypeParameters((JavaClassImpl) classifier)
: Collections.<PsiTypeParameter>emptyList();
? getTypeParameters(((JavaClassImpl) classifier).getPsi())
: Collections.<PsiTypeParameter>emptyList();
JavaTypeSubstitutor substitutor = getSubstitutor();
@@ -126,16 +125,32 @@ public class JavaClassifierTypeImpl extends JavaTypeImpl<PsiClassType> implement
return result;
}
private static Collection<PsiTypeParameter> getReversedTypeParameters(@NotNull JavaClassImpl classifier) {
Iterable<PsiTypeParameter> parameters = PsiUtil.typeParametersIterable(classifier.getPsi());
List<PsiTypeParameter> result = new ArrayList<PsiTypeParameter>();
// Copy-pasted from PsiUtil.typeParametersIterable
// The only change is using `Collections.addAll(result, typeParameters)` instead of reversing type parameters of `currentOwner`
// Result differs in cases like:
// class Outer<H1> {
// class Inner<H2, H3> {}
// }
//
// PsiUtil.typeParametersIterable returns H3, H2, H1
// But we would like to have H2, H3, H1 as such order is consistent with our type representation
@NotNull
public static List<PsiTypeParameter> getTypeParameters(@NotNull PsiClass owner) {
List<PsiTypeParameter> result = null;
for (PsiTypeParameter parameter : parameters) {
result.add(parameter);
PsiTypeParameterListOwner currentOwner = owner;
while (currentOwner != null) {
PsiTypeParameter[] typeParameters = currentOwner.getTypeParameters();
if (typeParameters.length > 0) {
if (result == null) result = new ArrayList<PsiTypeParameter>(typeParameters.length);
Collections.addAll(result, typeParameters);
}
if (currentOwner.hasModifierProperty(PsiModifier.STATIC)) break;
currentOwner = currentOwner.getContainingClass();
}
Collections.reverse(result);
if (result == null) return Collections.emptyList();
return result;
}
}

View File

@@ -1,81 +0,0 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.load.kotlin;
import com.intellij.ide.highlighter.JavaClassFileType;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public final class KotlinBinaryClassCache implements Disposable {
private static class RequestCache {
VirtualFile virtualFile;
long modificationStamp;
VirtualFileKotlinClass virtualFileKotlinClass;
public VirtualFileKotlinClass cache(VirtualFile file, VirtualFileKotlinClass aClass) {
virtualFile = file;
virtualFileKotlinClass = aClass;
modificationStamp = file.getModificationStamp();
return aClass;
}
}
private final ThreadLocal<RequestCache> cache =
new ThreadLocal<RequestCache>() {
@Override
protected RequestCache initialValue() {
return new RequestCache();
}
};
@Nullable
public static KotlinJvmBinaryClass getKotlinBinaryClass(@NotNull final VirtualFile file) {
if (file.getFileType() != JavaClassFileType.INSTANCE) return null;
KotlinBinaryClassCache service = ServiceManager.getService(KotlinBinaryClassCache.class);
RequestCache requestCache = service.cache.get();
if (file.getModificationStamp() == requestCache.modificationStamp && file.equals(requestCache.virtualFile)) {
return requestCache.virtualFileKotlinClass;
}
else {
VirtualFileKotlinClass aClass = ApplicationManager.getApplication().runReadAction(new Computable<VirtualFileKotlinClass>() {
@Override
public VirtualFileKotlinClass compute() {
//noinspection deprecation
return VirtualFileKotlinClass.Factory.create(file);
}
});
return requestCache.cache(file, aClass);
}
}
@Override
public void dispose() {
// This is only relevant for tests. We create a new instance of Application for each test, and so a new instance of this service is
// also created for each test. However all tests share the same event dispatch thread, which would collect all instances of this
// thread-local if they're not removed properly. Each instance would transitively retain VFS resulting in OutOfMemoryError
cache.remove();
}
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.load.kotlin
import com.intellij.ide.highlighter.JavaClassFileType
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.util.Computable
import com.intellij.openapi.vfs.VirtualFile
class KotlinBinaryClassCache : Disposable {
private class RequestCache {
internal var virtualFile: VirtualFile? = null
internal var modificationStamp: Long = 0
internal var virtualFileKotlinClass: VirtualFileKotlinClass? = null
fun cache(file: VirtualFile, aClass: VirtualFileKotlinClass?): VirtualFileKotlinClass? {
virtualFile = file
virtualFileKotlinClass = aClass
modificationStamp = file.modificationStamp
return aClass
}
}
private val cache = object : ThreadLocal<RequestCache>() {
override fun initialValue(): RequestCache {
return RequestCache()
}
}
override fun dispose() {
// This is only relevant for tests. We create a new instance of Application for each test, and so a new instance of this service is
// also created for each test. However all tests share the same event dispatch thread, which would collect all instances of this
// thread-local if they're not removed properly. Each instance would transitively retain VFS resulting in OutOfMemoryError
cache.remove()
}
companion object {
fun getKotlinBinaryClass(file: VirtualFile, fileContent: ByteArray? = null): KotlinJvmBinaryClass? {
if (file.fileType !== JavaClassFileType.INSTANCE) return null
val service = ServiceManager.getService(KotlinBinaryClassCache::class.java)
val requestCache = service.cache.get()
if (file.modificationStamp == requestCache.modificationStamp && file == requestCache.virtualFile) {
return requestCache.virtualFileKotlinClass
}
else {
val aClass = ApplicationManager.getApplication().runReadAction(Computable {
//noinspection deprecation
VirtualFileKotlinClass.create(file, fileContent)
})
return requestCache.cache(file, aClass)
}
}
}
}

View File

@@ -54,12 +54,12 @@ public class VirtualFileKotlinClass private constructor(
private val perfCounter = PerformanceCounter.create("Binary class from Kotlin file")
@Deprecated("Use KotlinBinaryClassCache")
fun create(file: VirtualFile): VirtualFileKotlinClass? {
fun create(file: VirtualFile, fileContent: ByteArray?): VirtualFileKotlinClass? {
return perfCounter.time {
assert(file.getFileType() == JavaClassFileType.INSTANCE) { "Trying to read binary data from a non-class file $file" }
try {
val byteContent = file.contentsToByteArray(false)
val byteContent = fileContent ?: file.contentsToByteArray(false)
if (!byteContent.isEmpty()) {
return@time FileBasedKotlinClass.create(byteContent) {
name, header, innerClasses ->

View File

@@ -32,7 +32,7 @@ import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.resolve.scopes.ChainedScope
import org.jetbrains.kotlin.resolve.scopes.ChainedMemberScope
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.serialization.PackageData
import org.jetbrains.kotlin.serialization.ProtoBuf
@@ -130,7 +130,7 @@ public class IncrementalPackageFragmentProvider(
MemberScope.Empty
}
else {
ChainedScope("Member scope for incremental compilation: union of package parts data", *scopes.toTypedArray())
ChainedMemberScope("Member scope for incremental compilation: union of package parts data", scopes)
}
}
}
@@ -153,9 +153,9 @@ public class IncrementalPackageFragmentProvider(
MemberScope.Empty
else {
val scopes = partsData.map { IncrementalPackageScope(JvmProtoBufUtil.readPackageDataFrom(it.data, it.strings)) }
ChainedScope(
ChainedMemberScope(
"Member scope for incremental compilation: union of multifile class parts data for $multifileClassFqName",
*scopes.toTypedArray<MemberScope>())
scopes)
}
}

View File

@@ -34,7 +34,7 @@ public class JavaClassOnCompanionChecker : CallChecker {
if (descriptor !is PropertyDescriptor || descriptor.name.asString() != "javaClass") return
val container = descriptor.containingDeclaration
if (container !is PackageFragmentDescriptor || container.fqName.asString() != "kotlin") return
if (container !is PackageFragmentDescriptor || container.fqName.asString() != "kotlin.jvm") return
val actualType = descriptor.type

View File

@@ -16,10 +16,7 @@
package org.jetbrains.kotlin.resolve.jvm.checkers
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil
import org.jetbrains.kotlin.fileClasses.isInsideJvmMultifileClassFile
@@ -35,12 +32,10 @@ import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
class JvmFieldApplicabilityChecker : DeclarationChecker {
enum class Problem(val errorMessage: String) {
NOT_A_PROPERTY("JvmField can only be applied to a property"),
internal enum class Problem(val errorMessage: String) {
NOT_FINAL("JvmField can only be applied to final property"),
PRIVATE("JvmField has no effect on a private property"),
CUSTOM_ACCESSOR("JvmField cannot be applied to a property with a custom accessor"),
NO_BACKING_FIELD("JvmField can only be applied to a property with backing field"),
OVERRIDES("JvmField cannot be applied to a property that overrides some other property"),
LATEINIT("JvmField cannot be applied to lateinit property"),
CONST("JvmField cannot be applied to const property"),
@@ -57,10 +52,11 @@ class JvmFieldApplicabilityChecker : DeclarationChecker {
val annotation = descriptor.findJvmFieldAnnotation() ?: return
val problem = when {
descriptor !is PropertyDescriptor -> NOT_A_PROPERTY
descriptor.modality.isOverridable -> NOT_FINAL
// First two cases just prevent duplication of WRONG_ANNOTATION_TARGET
descriptor !is PropertyDescriptor -> return
!descriptor.hasBackingField(bindingContext) -> return
descriptor.isOverridable -> NOT_FINAL
Visibilities.isPrivate(descriptor.visibility) -> PRIVATE
!descriptor.hasBackingField(bindingContext) -> NO_BACKING_FIELD
descriptor.hasCustomAccessor() -> CUSTOM_ACCESSOR
descriptor.overriddenDescriptors.isNotEmpty() -> OVERRIDES
descriptor.isLateInit -> LATEINIT

View File

@@ -33,7 +33,7 @@ object JvmSimpleNameBacktickChecker : IdentifierChecker {
}
override fun checkDeclaration(declaration: KtDeclaration, diagnosticHolder: DiagnosticSink) {
if (declaration is KtMultiDeclaration) {
if (declaration is KtDestructuringDeclaration) {
declaration.entries.forEach { checkNamed(it, diagnosticHolder) }
}
if (declaration is KtCallableDeclaration) {

View File

@@ -1,59 +0,0 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.resolve.jvm.checkers;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.descriptors.CallableDescriptor;
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor;
import org.jetbrains.kotlin.descriptors.PropertyDescriptor;
import org.jetbrains.kotlin.descriptors.Visibilities;
import org.jetbrains.kotlin.resolve.calls.checkers.CallChecker;
import org.jetbrains.kotlin.resolve.calls.context.BasicCallResolutionContext;
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall;
import org.jetbrains.kotlin.resolve.scopes.LexicalScope;
import static org.jetbrains.kotlin.resolve.BindingContext.NEED_SYNTHETIC_ACCESSOR;
public class NeedSyntheticChecker implements CallChecker {
@Override
public <F extends CallableDescriptor> void check(
@NotNull ResolvedCall<F> resolvedCall,
@NotNull BasicCallResolutionContext context
) {
CallableDescriptor targetDescriptor = resolvedCall.getResultingDescriptor();
if (needSyntheticAccessor(context.scope, targetDescriptor)) {
context.trace.record(NEED_SYNTHETIC_ACCESSOR, (CallableMemberDescriptor) targetDescriptor.getOriginal(), Boolean.TRUE);
}
}
//Necessary synthetic accessors in outer classes generated via old logic: CodegenContext.getAccessor
//Generation of accessors in nested classes (to invoke from outer,
// e.g.: from class to companion object) controlled via NEED_SYNTHETIC_ACCESSOR slice
private static boolean needSyntheticAccessor(LexicalScope invokationScope, CallableDescriptor targetDescriptor) {
return targetDescriptor instanceof CallableMemberDescriptor &&
isPrivate(targetDescriptor) &&
targetDescriptor.getContainingDeclaration() != invokationScope.getOwnerDescriptor().getContainingDeclaration();
}
private static boolean isPrivate(@NotNull CallableDescriptor targetDescriptor) {
return Visibilities.isPrivate(targetDescriptor.getVisibility()) ||
(targetDescriptor instanceof PropertyDescriptor &&
((PropertyDescriptor) targetDescriptor).getSetter() != null &&
Visibilities.isPrivate(((PropertyDescriptor) targetDescriptor).getSetter().getVisibility()));
}
}

View File

@@ -0,0 +1,33 @@
/*
* 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.resolve.jvm.checkers
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.resolve.calls.callResolverUtil.getSuperCallExpression
import org.jetbrains.kotlin.resolve.calls.callUtil.usesDefaultArguments
import org.jetbrains.kotlin.resolve.calls.checkers.CallChecker
import org.jetbrains.kotlin.resolve.calls.context.BasicCallResolutionContext
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
class SuperCallWithDefaultArgumentsChecker : CallChecker {
override fun <F : CallableDescriptor> check(resolvedCall: ResolvedCall<F>, context: BasicCallResolutionContext) {
val superCallExpression = getSuperCallExpression(resolvedCall.call)
if (superCallExpression == null || !resolvedCall.usesDefaultArguments()) return
context.trace.report(ErrorsJvm.SUPER_CALL_WITH_DEFAULT_PARAMETERS.on(superCallExpression.parent, resolvedCall.resultingDescriptor.name.asString()))
}
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.resolve.jvm.checkers
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.diagnostics.Errors.UNSUPPORTED
import org.jetbrains.kotlin.psi.KtCallableReferenceExpression
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.resolve.calls.checkers.CallChecker
import org.jetbrains.kotlin.resolve.calls.context.BasicCallResolutionContext
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor
class UnsupportedSyntheticCallableReferenceChecker : CallChecker {
override fun <F : CallableDescriptor> check(resolvedCall: ResolvedCall<F>, context: BasicCallResolutionContext) {
val expression = context.call.callElement
if (expression !is KtNameReferenceExpression || expression.parent !is KtCallableReferenceExpression) return
// TODO: support references to synthetic Java extension properties (KT-8575)
if (resolvedCall.resultingDescriptor is SyntheticJavaPropertyDescriptor) {
context.trace.report(UNSUPPORTED.on(expression, "reference to the synthetic extension property for a Java get/set method"))
}
}
}

View File

@@ -28,7 +28,6 @@ import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DeclarationChecker
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.annotations.hasIntrinsicAnnotation
import org.jetbrains.kotlin.resolve.annotations.hasJvmStaticAnnotation
import org.jetbrains.kotlin.resolve.inline.InlineUtil
import org.jetbrains.kotlin.resolve.jvm.annotations.hasJvmOverloadsAnnotation
@@ -115,7 +114,7 @@ public class JvmNameAnnotationChecker : DeclarationChecker {
if (descriptor is CallableMemberDescriptor) {
val callableMemberDescriptor = descriptor
if (DescriptorUtils.isOverride(callableMemberDescriptor) || callableMemberDescriptor.modality.isOverridable) {
if (DescriptorUtils.isOverride(callableMemberDescriptor) || callableMemberDescriptor.isOverridable) {
diagnosticHolder.report(ErrorsJvm.INAPPLICABLE_JVM_NAME.on(annotationEntry))
}
}
@@ -215,8 +214,6 @@ public class ReifiedTypeParameterAnnotationChecker : DeclarationChecker {
diagnosticHolder: DiagnosticSink,
bindingContext: BindingContext
) {
if (descriptor.hasIntrinsicAnnotation()) return
if (descriptor is CallableDescriptor && !InlineUtil.isInline(descriptor)) {
checkTypeParameterDescriptorsAreNotReified(descriptor.getTypeParameters(), diagnosticHolder)
}

View File

@@ -50,7 +50,7 @@ public class DefaultErrorMessagesJvm implements DefaultErrorMessages.Extension {
}
};
public static final DiagnosticFactoryToRendererMap MAP = new DiagnosticFactoryToRendererMap();
public static final DiagnosticFactoryToRendererMap MAP = new DiagnosticFactoryToRendererMap("JVM");
static {
MAP.put(ErrorsJvm.CONFLICTING_JVM_DECLARATIONS, "Platform declaration clash: {0}", CONFLICTING_JVM_DECLARATIONS_DATA);
MAP.put(ErrorsJvm.ACCIDENTAL_OVERRIDE, "Accidental override: {0}", CONFLICTING_JVM_DECLARATIONS_DATA);
@@ -99,6 +99,8 @@ public class DefaultErrorMessagesJvm implements DefaultErrorMessages.Extension {
MAP.put(ErrorsJvm.UPPER_BOUND_CANNOT_BE_ARRAY, "Upper bound of a type parameter cannot be an array");
MAP.put(ErrorsJvm.INAPPLICABLE_JVM_FIELD, "{0}", Renderers.TO_STRING);
MAP.put(ErrorsJvm.SUPER_CALL_WITH_DEFAULT_PARAMETERS, "Super-calls with default arguments are not allowed. Please specify all arguments of ''super.{0}'' explicitly", Renderers.TO_STRING);
}
@NotNull

View File

@@ -79,6 +79,8 @@ public interface ErrorsJvm {
DiagnosticFactory0<PsiElement> UPPER_BOUND_CANNOT_BE_ARRAY = DiagnosticFactory0.create(ERROR);
DiagnosticFactory1<PsiElement, String> SUPER_CALL_WITH_DEFAULT_PARAMETERS = DiagnosticFactory1.create(ERROR);
enum NullabilityInformationSource {
KOTLIN {
@NotNull

View File

@@ -43,11 +43,15 @@ public object JvmPlatform : TargetPlatform("JVM") {
override val platformConfigurator: PlatformConfigurator = JvmPlatformConfigurator
}
private val DEFAULT_IMPORTS_FOR_JVM = ArrayList<ImportPath>().apply {
private val DEFAULT_IMPORTS_FOR_JVM: List<ImportPath> = ArrayList<ImportPath>().apply {
add(ImportPath("java.lang.*"))
add(ImportPath("kotlin.*"))
add(ImportPath("kotlin.annotation.*"))
add(ImportPath("kotlin.jvm.*"))
add(ImportPath("kotlin.collections.*"))
add(ImportPath("kotlin.ranges.*"))
add(ImportPath("kotlin.sequences.*"))
add(ImportPath("kotlin.text.*"))
add(ImportPath("kotlin.io.*"))
fun addAllClassifiersFromScope(scope: MemberScope) {

View File

@@ -22,8 +22,10 @@ import org.jetbrains.kotlin.jvm.RuntimeAssertionsTypeChecker
import org.jetbrains.kotlin.load.kotlin.JavaAnnotationCallChecker
import org.jetbrains.kotlin.load.kotlin.nativeDeclarations.NativeFunChecker
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.jvm.checkers.SuperCallWithDefaultArgumentsChecker
import org.jetbrains.kotlin.resolve.jvm.JvmOverloadFilter
import org.jetbrains.kotlin.resolve.jvm.checkers.*
import org.jetbrains.kotlin.synthetic.JavaSyntheticScopes
import org.jetbrains.kotlin.types.DynamicTypesSettings
@@ -43,11 +45,12 @@ public object JvmPlatformConfigurator : PlatformConfigurator(
),
additionalCallCheckers = listOf(
NeedSyntheticChecker(),
JavaAnnotationCallChecker(),
TraitDefaultMethodCallChecker(),
JavaClassOnCompanionChecker(),
ProtectedInSuperClassCompanionCallChecker()
ProtectedInSuperClassCompanionCallChecker(),
UnsupportedSyntheticCallableReferenceChecker(),
SuperCallWithDefaultArgumentsChecker()
),
additionalTypeCheckers = listOf(
@@ -72,5 +75,6 @@ public object JvmPlatformConfigurator : PlatformConfigurator(
super.configure(container)
container.useImpl<ReflectionAPICallChecker>()
container.useImpl<JavaSyntheticScopes>()
}
}

View File

@@ -29,17 +29,16 @@ import org.jetbrains.kotlin.incremental.record
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.scopes.BaseImportingScope
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.HierarchicalScope
import org.jetbrains.kotlin.resolve.scopes.utils.collectSyntheticExtensionProperties
import org.jetbrains.kotlin.resolve.scopes.SyntheticScope
import org.jetbrains.kotlin.resolve.scopes.SyntheticScopes
import org.jetbrains.kotlin.resolve.scopes.collectSyntheticExtensionProperties
import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.util.capitalizeDecapitalize.capitalizeAsciiOnly
import org.jetbrains.kotlin.util.capitalizeDecapitalize.capitalizeFirstWord
import org.jetbrains.kotlin.utils.Printer
import org.jetbrains.kotlin.utils.addIfNotNull
import java.util.*
import kotlin.properties.Delegates
@@ -49,7 +48,7 @@ interface SyntheticJavaPropertyDescriptor : PropertyDescriptor {
val setMethod: FunctionDescriptor?
companion object {
fun findByGetterOrSetter(getterOrSetter: FunctionDescriptor, resolutionScope: HierarchicalScope): SyntheticJavaPropertyDescriptor? {
fun findByGetterOrSetter(getterOrSetter: FunctionDescriptor, syntheticScopes: SyntheticScopes): SyntheticJavaPropertyDescriptor? {
val name = getterOrSetter.getName()
if (name.isSpecial()) return null
val identifier = name.getIdentifier()
@@ -58,11 +57,16 @@ interface SyntheticJavaPropertyDescriptor : PropertyDescriptor {
val owner = getterOrSetter.getContainingDeclaration() as? ClassDescriptor ?: return null
val originalGetterOrSetter = getterOrSetter.original
return resolutionScope.collectSyntheticExtensionProperties(listOf(owner.defaultType))
return syntheticScopes.collectSyntheticExtensionProperties(listOf(owner.defaultType))
.filterIsInstance<SyntheticJavaPropertyDescriptor>()
.firstOrNull { originalGetterOrSetter == it.getMethod || originalGetterOrSetter == it.setMethod }
}
fun findByGetterOrSetter(getterOrSetter: FunctionDescriptor, syntheticScope: SyntheticScope)
= findByGetterOrSetter(getterOrSetter, object : SyntheticScopes {
override val scopes: Collection<SyntheticScope> = listOf(syntheticScope)
})
fun propertyNameByGetMethodName(methodName: Name): Name?
= org.jetbrains.kotlin.load.java.propertyNameByGetMethodName(methodName)
@@ -71,7 +75,7 @@ interface SyntheticJavaPropertyDescriptor : PropertyDescriptor {
}
}
class JavaSyntheticPropertiesScope(storageManager: StorageManager, private val lookupTracker: LookupTracker) : BaseImportingScope(null) {
class JavaSyntheticPropertiesScope(storageManager: StorageManager, private val lookupTracker: LookupTracker) : SyntheticScope {
private val syntheticPropertyInClass = storageManager.createMemoizedFunction<Pair<ClassDescriptor, Name>, SyntheticPropertyHolder> { pair ->
syntheticPropertyInClassNotCached(pair.first, pair.second)
}
@@ -163,7 +167,7 @@ class JavaSyntheticPropertiesScope(storageManager: StorageManager, private val l
return null
}
override fun getContributedSyntheticExtensionProperties(receiverTypes: Collection<KotlinType>, name: Name, location: LookupLocation): Collection<PropertyDescriptor> {
override fun getSyntheticExtensionProperties(receiverTypes: Collection<KotlinType>, name: Name, location: LookupLocation): Collection<PropertyDescriptor> {
var result: SmartList<PropertyDescriptor>? = null
val processedTypes: MutableSet<TypeConstructor>? = if (receiverTypes.size() > 1) HashSet<TypeConstructor>() else null
for (type in receiverTypes) {
@@ -193,7 +197,7 @@ class JavaSyntheticPropertiesScope(storageManager: StorageManager, private val l
return result
}
override fun getContributedSyntheticExtensionProperties(receiverTypes: Collection<KotlinType>): Collection<PropertyDescriptor> {
override fun getSyntheticExtensionProperties(receiverTypes: Collection<KotlinType>): Collection<PropertyDescriptor> {
val result = ArrayList<PropertyDescriptor>()
val processedTypes = HashSet<TypeConstructor>()
receiverTypes.forEach { result.collectSyntheticProperties(it.constructor, processedTypes) }
@@ -255,9 +259,8 @@ class JavaSyntheticPropertiesScope(storageManager: StorageManager, private val l
return Name.identifier("set" + identifier.removePrefix(prefix))
}
override fun printStructure(p: Printer) {
p.println(javaClass.simpleName)
}
override fun getSyntheticExtensionFunctions(receiverTypes: Collection<KotlinType>, name: Name, location: LookupLocation): Collection<FunctionDescriptor> = emptyList()
override fun getSyntheticExtensionFunctions(receiverTypes: Collection<KotlinType>): Collection<FunctionDescriptor> = emptyList()
private data class SyntheticPropertyHolder(val descriptor: PropertyDescriptor?, val lookedNames: List<Name>) {
companion object {

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