Compare commits

...

1078 Commits

Author SHA1 Message Date
Andrey Breslav
a11a846f9f bintray repo 2016-01-26 16:24:01 +03:00
Nikolay Krasko
311a074f28 Update test jar during runtime library update (KT-10773)
#KT-10773 Fixed
2016-01-25 11:48:56 +03:00
Ilya Gorbunov
a1d0ae6729 Insert required casts to make plus work again in compiler. 2016-01-24 16:15:41 +03:00
Ilya Gorbunov
4787ec24fe Constrain plus and minus operator's generic type parameter with @OnlyInputTypes.
LowPriority for list + element to enable concatenating List<Any> + List<Any> as list + list
#KT-9992 Fixed
2016-01-24 16:15:39 +03:00
Ilya Gorbunov
4a2c3aa31b Map.getOrPut: treat nulls as missing values. 2016-01-24 15:59:52 +03:00
Ilya Gorbunov
b08c903022 Map.getOrElse: treat nulls as missing values. 2016-01-24 15:59:51 +03:00
Ilya Gorbunov
8b96b0e071 Provide toMutableList as a replacement for toArrayList. 2016-01-24 15:59:49 +03:00
Ilya Gorbunov
7fcad4d534 Provide toMap with the destination mutable map to populate.
Tune type projections of map mutating operations.
2016-01-24 15:59:47 +03:00
Ilya Gorbunov
21ae0b47a4 Introduce associateTo and associateByTo with the destination MutableMap to fill. 2016-01-24 15:59:46 +03:00
Ilya Gorbunov
5fdc5e4fee Deprecate toLinkedMap 2016-01-24 15:59:44 +03:00
Ilya Gorbunov
c960d00b0a Rename toMap and toMapBy to associate and associateBy 2016-01-24 15:59:42 +03:00
Ilya Gorbunov
53561407b8 Breaking: Change File.copyTo contract to be similar to Files.copy from JDK8. 2016-01-24 15:59:41 +03:00
Ilya Gorbunov
284f8f985a Introduce overwrite parameter to File.copyRecursively.
#KT-8924 Fixed
2016-01-24 15:59:39 +03:00
Ilya Gorbunov
aa284c5ffd Deprecate assertFailsWith with java Class<T> parameter.
#KT-10377
2016-01-24 15:59:37 +03:00
Ilya Gorbunov
326df0456b Improve samples in tests for groupBy. 2016-01-24 15:57:23 +03:00
Ilya Gorbunov
4dc958e1bd Provide groupBy and groupByTo with keySelector and valueTransform.
Rename parameters of groupBy, add type parameter for MutableMap to groupByTo.
2016-01-24 15:57:22 +03:00
Ilya Gorbunov
add519e164 Use generic coerceIn for nullable primitives, provide specialization for non-nullable ones.
Fix docs for coerceAtMost.
2016-01-24 15:56:29 +03:00
Alexander Udalov
ad8247b806 Increase metadata version to 1.1, hardcode incompatibility with 1.0
Add a temporary option to suppress incompatibility errors when compiling Kotlin
against current IDEA libraries until they are migrated
2016-01-23 10:00:25 +03:00
Alexander Udalov
6c93e8de1d Add temporary compiler option to suppress incompatibility errors
To compile Kotlin against current IDEA libraries until they are migrated to 1.1
2016-01-22 23:54:15 +03:00
Dmitry Jemerov
3a1663febc use <default> branch 2016-01-22 16:58:23 +01:00
Dmitry Jemerov
5ef274b988 stop using non-default branch for downloading IDEA 2016-01-22 16:56:09 +01:00
Dmitry Jemerov
346fb74751 back to correct bootstrap for RC branch 2016-01-22 16:14:13 +01:00
Dmitry Jemerov
1b885818fe temp revert bootstrap changes 2016-01-22 15:16:13 +01:00
Dmitry Jemerov
61756aee19 don't use bootstrap tag for fetching bootstrap build, use latest build 2016-01-22 13:49:41 +01:00
Dmitry Jemerov
8ff4f75ead update_dependencies set up for RC branch 2016-01-22 13:41:27 +01:00
Dmitry Petrov
55b7e4bbf0 Ignore special resolved calls for 'when' in PSI unifier. 2016-01-22 10:41:56 +03:00
Dmitry Petrov
a33c840939 Fix Kotlin build after fixing when-related type checking issues.
Filed: KT-10752, KT-10755.
2016-01-22 10:41:55 +03:00
Dmitry Petrov
f371e67ce8 PatternMatchingTypingVisitor:
rewrite type inference for 'when' using special constructs.
This fixes several type inference issues for 'when':
KT-9929, KT-9972, KT-10439, KT-10463
along with some other diagnostics-related issues.
2016-01-22 10:41:55 +03:00
Dmitry Petrov
b49e08fe04 PatternMatchingTypingVisitor:
separate condition data flow info analysis and exhaustiveness check
from type inference for "incomplete" (statement-like) 'when'.
2016-01-22 10:41:55 +03:00
Michael Bogdanov
a76d16931c Temporary generate old default method 2016-01-22 10:10:32 +03:00
Michael Bogdanov
829978a37d Added additional parameter for default methods 2016-01-22 10:10:32 +03:00
Ilya Gorbunov
875287574f Update testData for LoadBuiltinsTest and BuiltInDecompilerTest 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
4d5ec9be3f Drop identityEquals from builtins, compiler and tests. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
f5f5a2dcc1 Move progression final element test to stdlib tests.
Less values are tested for iteration not to timeout in js tests.
2016-01-22 05:54:38 +03:00
Ilya Gorbunov
2a125ca92d Drop deprecated builtins: PropertyMetadata, progression internal utils, HiddenDeclaration and Extension annotations 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
31ec7bcbea Deprecate String.concat with error severity.
Fix concat j2k conversion.
Add expected deprecation errors for Java String constructors that must be converted to special Kotlin String methods.
2016-01-22 05:54:38 +03:00
Ilya Gorbunov
2257fa36ec Drop deprecations: text and system
Fix import in testData
Fix testData: replace removed method.
2016-01-22 05:54:38 +03:00
Ilya Gorbunov
8bf638c60f Drop deprecations: FileTreeWalk deprecated API elements. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
e9c14a02d3 Make FilePathComponents internal, temporary disable tests of internal API 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
c1ad82ff8c Harden charset-as-string taking function deprecations.
Fix usages in compiler.
2016-01-22 05:54:38 +03:00
Ilya Gorbunov
6d5a65cac6 Minor: remove File?.readTextOrEmpty() 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
d728a1a6c7 Replace File.relativePath from stdlib with File.descendantRelativeTo in fileUtils.
IO utils: cleanup java usages.
2016-01-22 05:54:38 +03:00
Ilya Gorbunov
b39b29dfea Drop deprecations: io and threading functions. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
25c4453dc5 Cleanup deprecated symbol usages in testData 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
eefbd72a64 Remove AddStarProjectionsFix for removed javaClass<T> function. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
cbc3a3b595 Make IndexingIterator and IndexingIterable internal. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
9142025df6 Drop deprecations: reflection utilites. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
69f884dcd3 Drop deprecations: preconditions with non-lazy message. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
768a23f7eb Drop deprecations: functions that were converted to properties. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
2813840769 Fix testData: diagnostics changed. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
ef0d998fbc Drop deprecations: *Raw functions. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
d1a5988bfc Drop deprecations: complicated map delegates and kotlin.support.AbstractIterator. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
4f1d2252f0 Make test for replacement, which requires adding import to the package with operator, independent from stdlib. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
d7f8754282 Drop deprecated classes inheriting multifile facade classes moved out of kotlin package. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
473773723b Drop deprecations in kotlin.test 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
85a02d40c6 Drop hidden declarations provided for binary compatibility 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
264c9a0fc9 Drop deprecated toGenerator and toLinkedList (again). 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
b97e436a50 Fix deprecated Range and Progression usages in testData 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
d48ec7e296 Update testData for LoadBuiltinsTest 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
91f4cf0ebc Drop Progression<T> and its deprecated properties: start, end, increment.
Drop deprecated range extensions.
Make progression constructors private.
2016-01-22 05:54:38 +03:00
Ilya Gorbunov
6dd8470835 Drop deprecated primitive ranges and progressions: for Byte and Short 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
e8621cb738 Drop Range<T> interface and its extensions. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
face6d449b Make values in Typography constant, add dollar sign. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
6eabd1d692 Move stdlib classes between packages. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
f4822cd757 Fix testData in compiler: add collections and ranges package to fq-names. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
98e2d27c77 Resolve types from all builtin default packages in TypeUnifierTest 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
c84cbfb36a Allow to specify fq-names in expected resolve testData 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
3262a4ddc2 LoadBuiltinsTest inspects three packages: kotlin, kotlin.collections and kotlin.ranges 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
db9e458cf9 Fix imports in maven kotlin from java usage example. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
46a59b7550 Fix imports in java: temporary replace with star imports. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
0213a129ce Increment STUB_VERSION due to changed fq-names in signatures. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
26a6147a56 Minor: array constructor names formatting. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
1129cee0ff Collect nested classes from all 4 builtin packages. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
e500e4bdf4 Obtain purely implemented interface class descriptor by its fq-name. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
e485bd4909 Fix mutability-flexible types rendering. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
83ef48d0ac Refer to builtin names in HeuristicSignatures and j2k TypeVisitor 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
346291af7b Use fq-names from KotlinBuiltins.FQ_NAMES instead of hardcoded ones. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
9c0f0cad70 Packages: move collections to kotlin.collections. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
9fbbc9db98 Packages: move Ranges, Progression, ProgressionIterators to kotlin.ranges and PrimitiveIterators to kotlin.collections. 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
a3efa1ea6c Temporary allow-kotlin-package for building compiler 2016-01-22 05:54:38 +03:00
Ilya Gorbunov
3176f7d06c Restore downloading IDEA from teamcity, build markdown every time (temporary) 2016-01-22 05:54:38 +03:00
Alexander Udalov
0b7d2e3a68 Do not write old callable proto flags, use only new ones 2016-01-22 05:51:14 +03:00
Ilya Gorbunov
300a4be060 Deprecate Map.minus and minusAssign operators.
Disable tests failing in JS.
2016-01-22 01:13:33 +03:00
Ilya Gorbunov
7896e58afc Rename sequence function to generateSequence 2016-01-22 01:13:31 +03:00
Ilya Gorbunov
63e8865123 Make Lazy an interface open to implementation.
#KT-9287 Fixed
2016-01-22 01:03:18 +03:00
Ilya Gorbunov
dbcad08a35 Regex: MatchResult.groupValues do not exclude zeroth group, use the same indices as in groups collection.
Provide destructured property for destructured assignment.
2016-01-22 00:59:13 +03:00
Ilya Gorbunov
3459a24b0a Regex: Introduce MatchResult.groupValues to get list of numbered group values exlcuding zeroth group with the entire match. 2016-01-22 00:56:08 +03:00
Pavel V. Talanov
1fe749c114 Refactor: get rid of LightClassUtil#getPsiClass() in favor of KtClassOrObject:toLightClass extension 2016-01-21 20:47:22 +03:00
Pavel V. Talanov
2972dbca00 Rename LightClassGenerationSupport.getPsiClass -> getLightClass and make it return KtLightClass 2016-01-21 20:47:21 +03:00
Pavel V. Talanov
06215ca932 Correctly avoid calculation of autogenerated parameter name in ClsParameterImpl.calcName() 2016-01-21 20:47:21 +03:00
Pavel V. Talanov
36d5798a2e Regression test for old issue
#KT-7656 Fixed
2016-01-21 20:47:20 +03:00
Zalim Bashorov
1e6b3c5ae1 Add own PathStringDescriptor to compare paths properly on case-insensitive filesystems 2016-01-21 19:47:10 +03:00
Ilya Chernikov
c585d91e79 Adding generation states destroying to module-based compilation, to fix kapt usage with this compilation path 2016-01-21 19:47:09 +03:00
Ilya Chernikov
3615ca5b02 build.xml: add kotlin-build target 2016-01-21 19:47:08 +03:00
Ilya Chernikov
a61e5a6736 build.xml: add manifest to kotlin-daemon-client.jar 2016-01-21 19:47:07 +03:00
Ilya Chernikov
6198d0abbc Move compiler running utils to common module 2016-01-21 19:47:06 +03:00
Ilya Chernikov
a36e6a2e07 J2K KotlinModuleXmlBuilder: convert 2016-01-21 19:47:05 +03:00
Ilya Chernikov
60892f2b9c J2K KotlinModuleXmlBuilder: rename file 2016-01-21 19:47:04 +03:00
Zalim Bashorov
cc1c5b7e10 Move back classes which used only in JPS 2016-01-21 19:47:04 +03:00
Zalim Bashorov
e2e0167880 Minor: don't override clean in SourceToClassesMap 2016-01-21 19:47:03 +03:00
Ilya Chernikov
5ead2edaa0 Creating shared module "build", copying lookup storage, tracker and incremental cache related files into it from jps plugin 2016-01-21 19:47:02 +03:00
Valentin Kipyatkov
84e530bc1a KT-6079 Show "parameter information" popup for type arguments
#KT-6079 Fixed
2016-01-21 19:07:39 +03:00
Michael Bogdanov
bf16783fb7 Fix for KT-9591: Exception on inlining
#KT-9591 Fixed
2016-01-21 18:44:05 +03:00
Valentin Kipyatkov
53fe1568c9 KT-8529 Code completion for parameter name and type together replaces wrong range on Tab
#KT-8529 Fixed
2016-01-21 18:30:09 +03:00
Valentin Kipyatkov
bc8095ce33 KT-9424 "Exclude from import and completion" with "Project" scope
#KT-9424 Fixed
2016-01-21 18:30:08 +03:00
Alexey Tsvetkov
9bb876e6da Test incremental facade to class conversion and vice versa 2016-01-21 18:16:01 +03:00
Alexey Tsvetkov
94d4dae1fe Recompile all class usages when constructor is changed 2016-01-21 18:14:56 +03:00
Nikolay Krasko
5fcb9ca2bd Add speed to perfomance output 2016-01-21 17:45:51 +03:00
Nikolay Krasko
10648f44ac Do not auto-import convention methods without 'operator' modifier (KT-10212)
#KT-10212 Fixed
2016-01-21 17:45:51 +03:00
Dmitry Jemerov
84d507b770 code review 2016-01-21 15:30:13 +01:00
Dmitry Jemerov
4910b06f2c show "kotlin not configured" editor notification 2016-01-21 15:30:11 +01:00
Dmitry Jemerov
170ba98b20 show unsupported ABI notification only when current module or its dependencies have libraries with bad ABI 2016-01-21 15:30:11 +01:00
Dmitry Jemerov
6f80f36f2e UnsupportedAbiVersionNotificationPanelProvider: fix compilation and cleanup after J2K 2016-01-21 15:30:10 +01:00
Dmitry Jemerov
b1c5d3644e UnsupportedAbiVersionNotificationPanelProvider: J2K 2016-01-21 15:30:10 +01:00
Dmitry Jemerov
e20fdac9df UnsupportedAbiVersionNotificationPanelProvider: rename to .kt 2016-01-21 15:30:09 +01:00
Dmitry Jemerov
2379fd80fc don't show "kotlin not configured" notification for modules where the runtime is outdated 2016-01-21 15:30:08 +01:00
Dmitry Jemerov
85ea295e92 OutdatedKotlinRuntimeNotification: J2K and cleanup 2016-01-21 15:30:08 +01:00
Dmitry Jemerov
ca9979f9fb OutdatedKotlinRuntimeNotification.java: rename to .kt 2016-01-21 15:30:07 +01:00
Dmitry Jemerov
2272516d09 KotlinRuntimeLibraryUtil: J2K 2016-01-21 15:30:07 +01:00
Dmitry Jemerov
f588ef2912 KotlinRuntimeLibraryUtil: rename to .kt 2016-01-21 15:30:06 +01:00
Dmitry Jemerov
6c2a2b91b4 offer "All modules" choice in "Configure Kotlin in project" dialog, allow to invoke the action when there are no Kotlin files in the project
#KT-7979 Fixed
2016-01-21 15:30:05 +01:00
Dmitry Jemerov
4ffac80710 ConfigureKotlinInProjectUtils: convert to Kotlin, cleanup 2016-01-21 15:30:05 +01:00
Dmitry Jemerov
cff06cccf7 ConfigureKotlinInProjectUtils.kt: rename 2016-01-21 15:30:04 +01:00
Dmitry Jemerov
3b4a6afe01 Kotlin-produced test run configurations replace Java-produced ones (to avoid duplicate run configuration suggestions appearing since KtFile.getClasses() was implemented) 2016-01-21 14:46:26 +01:00
Dmitry Jemerov
51799ef70e fix tests on Windows agents: report canonical paths to conflicting Kotlin runtimes 2016-01-21 11:33:32 +01:00
Denis Zharkov
ad24092fd1 Move InlineOnly to kotlin.internal package 2016-01-21 11:26:01 +03:00
Denis Zharkov
ba506170e9 Use 'mapToCallableMethod' for delegateTo signature calculation
#KT-9707 Fixed
2016-01-21 11:24:23 +03:00
Valentin Kipyatkov
3a7ed33de1 KT-10747 "Incompatible stack heights" when compiling call to Java setter with non-void return type using property syntax
#KT-10747 Fixed
2016-01-21 10:48:47 +03:00
Alexander Udalov
d2d0f399db Minor, save parameters to field in ValueArgumentsToParametersMapper 2016-01-21 00:36:35 +03:00
Alexander Udalov
8fe964f269 Resolve array access RHS always as the last argument of the call
Also do not attempt to match any of the arguments in the brackets with the last
parameter of the 'set' method

 #KT-10633 Fixed
2016-01-21 00:36:35 +03:00
Dmitry Jemerov
ccef1ad49e report presence of multiple different versions of kotlin-runtime on the classpath as compilation error if other compilation errors have occurred 2016-01-20 21:02:44 +01:00
Dmitry Jemerov
4f5b2ec4b4 AnalyzerWithCompilerReport: some more cleanup after J2K 2016-01-20 21:00:24 +01:00
Dmitry Jemerov
bf5cdcb6b4 AnalyzerWithCompilerReport: J2K 2016-01-20 21:00:24 +01:00
Dmitry Jemerov
ae1e680319 AnalyzerWithCompilerReport: rename to .kt 2016-01-20 21:00:23 +01:00
Pavel V. Talanov
b34a91eeaa Changes inside init blocks should be considered out of block modifications 2016-01-20 19:02:53 +03:00
Pavel V. Talanov
d72bc78550 Resolve annotations on parameters of function type 2016-01-20 18:06:23 +03:00
Pavel V. Talanov
7d72875227 Create descriptors for parameters inside parameter list of KtFunctionType
Do not throw when trying to resolveToDescriptor those parameters
2016-01-20 18:06:19 +03:00
Michael Bogdanov
23480a5698 Supported inline of array convention simple cases; Fix for KT-9211: M13 an extension function that is inline, and for get(v) causes an exception when called using brackets
#KT-9211 Fixed
2016-01-20 17:33:50 +03:00
Michael Bogdanov
84dbdf2ccb Get rid of ValueParameterDescriptor in 'afterParameterPut' fun 2016-01-20 17:33:49 +03:00
Dmitry Jemerov
aacf2ad68c proguard: keep all JNA methods (some of them are accessed from native code) 2016-01-20 14:34:50 +01:00
Dmitry Jemerov
f88f38f7d2 Android Studio adds Android-Gradle facet to all modules, so we need to check for Android facet and Gradle module instead
#KT-9600 Fixed
2016-01-20 14:32:10 +01:00
Dmitry Jemerov
4ab6436f93 avoid index access in KtFile.getClasses() when the file isn't part of a multi-file class (helps with KT-10684) 2016-01-20 13:45:42 +01:00
Denis Zharkov
ede4b61980 Add tests for obsolete issue
#KT-7412 Obsolete
2016-01-20 14:27:53 +03:00
Denis Zharkov
06fbc9bdd3 Support reification of arrays containing reified parameters
#KT-10555 Fixed
2016-01-20 14:27:53 +03:00
Valentin Kipyatkov
28331bca9f KT-9418 Suggest name for new declaration basing on unresolved names in code
#KT-9418 Fixed
2016-01-20 13:55:56 +03:00
Valentin Kipyatkov
83ca4b84f9 Minor optimization 2016-01-20 13:55:55 +03:00
Alexander Udalov
17e8eafe33 Pass -Xallow-kotlin-package to compiler in project
To compile the 'builtins' module
2016-01-20 00:55:43 +03:00
Valentin Kipyatkov
59fb90a5ee Dropped KtTypedef 2016-01-19 19:31:44 +03:00
Valentin Kipyatkov
808c7453a4 Added test for 'typealias' being keyword 2016-01-19 19:31:44 +03:00
Valentin Kipyatkov
68853fecc3 Removed support for "typealias" declarations from the parser
#KT-10683 Fixed
2016-01-19 19:31:44 +03:00
Valentin Kipyatkov
38d374d4b9 Added test for nested class 2016-01-19 19:30:19 +03:00
Valentin Kipyatkov
2791d99f9d Direct implementation of ImportingScope 2016-01-19 19:30:19 +03:00
Valentin Kipyatkov
d337dff5fa Minor 2016-01-19 19:30:18 +03:00
Valentin Kipyatkov
d749f85a60 Inaccessible classes from the current package to not conflict with visible classes from somewhere else 2016-01-19 19:30:18 +03:00
Valentin Kipyatkov
bfe728526a Alias imports to hide symbols by original name from the current package too 2016-01-19 19:30:18 +03:00
Valentin Kipyatkov
e83bd759e6 Minor 2016-01-19 19:30:18 +03:00
Alexander Udalov
e2f49536f5 Move OldPackageFacadeClassUtils to module light-classes 2016-01-19 18:54:08 +03:00
Alexander Udalov
c78bf6c807 Set bytecode version to 1.0.0
It was 1.0.2 only because it was introduced as a clone of the metadata version,
which is 1.0.2 at the moment
2016-01-19 18:43:07 +03:00
Alexander Udalov
27dbfc7aef Rethrow InvalidProtocolBufferException with class file location info 2016-01-19 18:39:59 +03:00
Alexander Udalov
4d93d18af7 J2K DeserializedDescriptorResolver: prettify 2016-01-19 18:39:59 +03:00
Alexander Udalov
3efa51af40 J2K DeserializedDescriptorResolver: convert 2016-01-19 18:39:59 +03:00
Alexander Udalov
432d458c02 J2K DeserializedDescriptorResolver: rename .java -> .kt 2016-01-19 18:39:59 +03:00
Alexander Udalov
b216ed99b4 Simplify UTF-8 decoding, just trivially convert bytes to 16-bit Unicode
ASM will do the rest (see ByteVector#encodeUTF8)
2016-01-19 18:39:59 +03:00
Alexander Udalov
9620893fa4 Drop synthetic class kind Function, drop Metadata#xi 2016-01-19 18:39:59 +03:00
Alexander Udalov
aef6d49b48 Drop isLocalClass, do not write KotlinLocalClass 2016-01-19 18:39:59 +03:00
Alexander Udalov
e17cd12c3c Report error on generating calls to binary incompatible classes 2016-01-19 18:39:59 +03:00
Alexander Udalov
4bd1d064bb Do not load built-ins in old format, drop class_name extension 2016-01-19 18:39:59 +03:00
Alexander Udalov
625c46d568 Delete obsolete and unused class_annotation JVM proto extension 2016-01-19 18:39:59 +03:00
Alexander Udalov
6dbd29e6a4 Support decoding of both old and new encoded metadata 2016-01-19 18:39:59 +03:00
Alexander Udalov
5585c7da7f Minor, simplify utfEncoding, add option to force using 8to7 encoding 2016-01-19 18:39:59 +03:00
Andrey Breslav
fe15984a59 Direct encoding into UTF-8 bytes, without the 8-to-7-bit conversion 2016-01-19 18:39:59 +03:00
Alexander Udalov
693a9c9453 Write new flags to proto messages for callables
This is needed to get rid of two unused bits: Flags.RESERVED_1 and
Flags.RESERVED_2. The old flags are still there temporarily because of the
bootstrap dependency on built-ins. Soon the old flags will be dropped and the
current flags will be transformed to the new format
2016-01-19 18:39:59 +03:00
Alexander Udalov
86bbc9f15b Read new Metadata annotation in check-library-abi-version.kts 2016-01-19 18:39:59 +03:00
Alexander Udalov
a4daa08e5c Write module name as proto extension instead of another annotation argument 2016-01-19 18:39:59 +03:00
Alexander Udalov
d4c4515944 Refactor BinaryVersion and subclasses, get rid of static factories 2016-01-19 18:39:59 +03:00
Alexander Udalov
e37bd4eba6 Do not write and read KotlinInterfaceDefaultImpls
This was only used in InlineTestUtil.kt and had no effect in the condition
2016-01-19 18:39:59 +03:00
Alexander Udalov
7906ac63b5 Read Metadata annotation, support option to ignore old annotations 2016-01-19 18:39:59 +03:00
Alexander Udalov
59dab0a558 Combine all metadata annotations into one kotlin/Metadata 2016-01-19 18:39:59 +03:00
Alexander Udalov
661af854fa Drop KotlinClassHeader#filePartClassNames, use 'data' instead 2016-01-19 18:39:59 +03:00
Alexander Udalov
b587d3a78d Use JvmMetadataVersion where appropriate instead of bytecode version 2016-01-19 18:39:59 +03:00
Alexander Udalov
bd47e9d47b Split JVM binary version into two: metadata and bytecode interface
Currently all code only uses the first one (JvmMetadataVersion), later the
bytecode interface version (JvmBytecodeBinaryVersion) will be used only in
codegen and reflection to avoid compiling against or calling methods with
unsupported conventions like default method naming and signature,
getters/setters naming etc.
2016-01-19 18:39:59 +03:00
Alexander Udalov
fc88a0186f Drop obsolete synthetic class kind in KotlinClassHeader 2016-01-19 18:39:59 +03:00
Alexander Udalov
9552accaec Introduce BinaryVersion.isCompatible()
To decrease the chance to mix up the receiver and the first argument when
checking version compatibility
2016-01-19 18:39:59 +03:00
Alexander Udalov
04d335db15 Move version constants to corresponding BinaryVersion subclasses 2016-01-19 18:39:59 +03:00
Alexander Udalov
2f64680b63 Add several subclasses of BinaryVersion
To simplify comparison of expected vs actual versions in the future
2016-01-19 18:39:59 +03:00
Yan Zhulanow
4cd2ff040d J2K: convert hex Java literal to hex Kotlin literal 2016-01-19 23:29:58 +09:00
Zalim Bashorov
bd9b2f9f06 Restore logging changes when process them using lookups and add assert to avoid getting parent from root FqName 2016-01-19 16:33:44 +03:00
Mikhail Glukhikh
9360bd49a6 Data flow info: correct disjunction of a type with Nothing: Type U Nothing = Type #KT-9578 Fixed 2016-01-19 16:01:10 +03:00
Mikhail Glukhikh
5d3186ac49 DelegatingDataFlowInfo: converted to Kotlin 2016-01-19 16:01:08 +03:00
Mikhail Glukhikh
4cc2450b37 DelegatingDataFlowInfo.java --> DelegatingDataFlowInfo.kt 2016-01-19 16:01:05 +03:00
Valentin Kipyatkov
a1d760fc36 KT-10631 Consider creating a synthetic property even when the setter returns 'this'
#KT-10631 Fixed
2016-01-19 15:57:20 +03:00
Dmitry Petrov
eef68e0a94 J2K: PatternMatchingTypingVisitor.kt: convert to Kotlin and cleanup 2016-01-19 15:02:45 +03:00
Dmitry Petrov
3e2d9a6a27 J2K: PatternMatchingTypingVisitor.java -> PatternMatchingTypingVisitor.kt 2016-01-19 14:24:09 +03:00
Pavel V. Talanov
ce42d47383 Resolve lambda argument types when failing to resolve call 2016-01-19 14:14:33 +03:00
Nikolay Krasko
adbf098166 Store information is file was compiled with Kotlin in attributes (KT-10312)
- Add boolean attribute for all binary files in the project
- Stop using JarUserDataManager for full file indexing
- Store full header of files compiled with Kotlin in file UserData
2016-01-19 13:33:51 +03:00
Nikolay Krasko
5431c6937f Allow to configure print accuracy and fetch temprory results from profiler 2016-01-19 13:33:51 +03:00
Nikolay Krasko
61bd0e7265 Refactoring: Remove unused class 2016-01-19 13:33:51 +03:00
Nikolay Krasko
803bd55f70 Minor: refactoring 2016-01-19 13:33:51 +03:00
Dmitry Jemerov
f85c4dd458 cleanup KotlinProjectViewProvider 2016-01-19 11:04:10 +01:00
Dmitry Jemerov
52acd34a61 fix Maven build 2016-01-19 10:54:04 +01:00
Dmitry Jemerov
b60621c428 tests fixed 2016-01-19 10:53:53 +01:00
Dmitry Jemerov
39c6e3712b add test to check that "Only the Kotlin standard library is allowed to use the 'kotlin' package" is reported in JPS builds 2016-01-19 10:53:49 +01:00
Dmitry Jemerov
39ad2b2378 return correct exit code when script execution fails 2016-01-19 10:53:48 +01:00
Dmitry Jemerov
f3faa10fcc forbid compiling code in packages with names starting with 'kotlin' unless the -Xallow-kotlin-package command line option is specified 2016-01-19 10:53:47 +01:00
Dmitry Jemerov
6b354748ba KotlinToJVMBytecodeCompiler: cleanup after J2K 2016-01-19 10:53:45 +01:00
Dmitry Jemerov
bccd64de19 KotlinToJVMBytecodeCompiler: J2K 2016-01-19 10:53:44 +01:00
Dmitry Jemerov
0d88595baf KotlinToJVMBytecodeCompiler: rename to .kt 2016-01-19 10:53:43 +01:00
Dmitry Jemerov
e4903c1a47 proguard: don't exclude native libraries when repackaging jna.jar (IDEA core code now accesses FileSystemUtil which uses JNA) 2016-01-19 10:51:21 +01:00
Mikhail Glukhikh
7f2624c9a1 Handling of annotations on delegated property in descriptor loader & stub builder 2016-01-19 11:38:58 +03:00
Mikhail Glukhikh
e4f7446bec JvmSynthetic forbidden for delegated properties (and searched for different use-site targets) 2016-01-19 11:38:53 +03:00
Mikhail Glukhikh
a2bba7c8f1 JvmField forbidden for delegated properties 2016-01-19 11:38:49 +03:00
Mikhail Glukhikh
ec909d0775 Volatile forbidden for delegated properties (and checked for other use-site targets) 2016-01-19 11:38:45 +03:00
Mikhail Glukhikh
b78d481bb1 delegate use-site targeted annotations: parser, front-end, codegen with some tests #KT-10502 Fixed 2016-01-19 11:38:41 +03:00
Mikhail Glukhikh
474076a550 Annotation use-site refactoring: field, property, getter 2016-01-19 11:38:36 +03:00
Denis Zharkov
e9693e987f Humanize type mismatch diagnostic caused by type projections
#KT-10581 Fixed
2016-01-19 11:05:41 +03:00
Dmitry Petrov
0c52960d7a KT-10706: do not report IMPLICIT_CAST_TO_ANY on expressions of type Nothing 2016-01-19 10:50:09 +03:00
Zalim Bashorov
5889ba4293 Minor: extract most of JPS (old IC) specific part from IncrementalCacheImpl 2016-01-18 22:13:29 +03:00
Dmitry Jemerov
f1b5e72b99 always add mavenCentral() as buildscript repository dependency (KT-10342)
#KT-10342 Fixed
2016-01-18 20:09:30 +01:00
Ilya Gorbunov
14f17e76e1 Deprecate dropWhileTo and takeWhileTo on CharSequences. 2016-01-18 21:46:33 +03:00
Ilya Gorbunov
5bbce7a1de Deprecate 'comparator { ... }' in favor of Comparator SAM-constructor. Provide SAM-like constructor for JS. 2016-01-18 21:46:32 +03:00
Ilya Gorbunov
67ef790abc Move comparison related functions to kotlin.comparisons, update imports in stdlib. 2016-01-18 21:46:31 +03:00
Ilya Gorbunov
c250921643 Deprecate getOrImplicitDefault to make it private later. 2016-01-18 21:46:30 +03:00
Ilya Gorbunov
aafd79078f Provide mutableSetOf and mutableMapOf
#KT-9663 Fixed
2016-01-18 21:46:29 +03:00
Ilya Gorbunov
fe8ba4d356 Provide mutableListOf.
Deprecate linkedListOf.
#KT-9663
2016-01-18 21:46:28 +03:00
Dmitry Jemerov
60ca1cbcf3 don't represent Kotlin project view nodes as light classes (KT-10703) 2016-01-18 19:07:51 +01:00
Dmitry Jemerov
8cca34a00e KotlinProjectViewProvider: J2K 2016-01-18 19:00:56 +01:00
Dmitry Jemerov
f4d4ab691b KotlinProjectViewProvider: rename to .kt 2016-01-18 18:58:52 +01:00
Stanislav Erokhin
206fecf872 Possible fix for KT-10603. 2016-01-18 19:45:34 +03:00
Valentin Kipyatkov
4c62304a1d KT-10337 Object marked as unused
#KT-10337 Fixed
2016-01-18 17:40:04 +03:00
Valentin Kipyatkov
4c2a14ff43 KT-9834 Optimizing imports with named import (kinda like static import)
#KT-9834 Fixed
2016-01-18 17:40:03 +03:00
Valentin Kipyatkov
bec16efbd7 Add/remove argument name intentions to work for super class constructor call 2016-01-18 17:40:03 +03:00
Valentin Kipyatkov
c44340a351 Corrections on code review 2016-01-18 15:34:20 +03:00
Valentin Kipyatkov
65f5dd1dd5 Got rid of special methods "applyTo" without editor parameter in intentions 2016-01-18 15:34:20 +03:00
Valentin Kipyatkov
552359ce03 KT-7443 Inspection + intention to replace assert (x != null) with "!!" or elvis
#KT-7443 Fixed
2016-01-18 15:34:20 +03:00
Mikhail Glukhikh
5ad4571ddf 'IMPLICIT_NOTHING_PROPERTY_TYPE' is now an error 2016-01-18 14:04:38 +03:00
Mikhail Glukhikh
380e2dd153 Diagnostic message fixed for 'PRIVATE_SETTER_FOR_OPEN_PROPERTY' 2016-01-18 14:04:34 +03:00
Mikhail Glukhikh
1c789f6862 minor 2016-01-18 14:04:25 +03:00
Dmitry Petrov
a073f29006 KT-10460: use unsubstituted descriptors
while comparing overloaded generic functions  for specificity.
2016-01-18 12:25:04 +03:00
Alexander Udalov
d21ce08548 Minor, remove pointless environment creation in LoadJava test 2016-01-17 22:55:55 +03:00
Alexander Udalov
f88abc5b1f Minor, cleanup InlineTestUtil.kt 2016-01-17 20:00:13 +03:00
Alexander Udalov
d50a531934 Slightly improve bytecode version check during inline
Add class name to the exception message and provide a system property to
disable the check
2016-01-17 16:28:22 +03:00
Alexander Udalov
cf7f2b762f Minor, refactor and simplify RuntimePackagePartProvider
Lazy was unnecessary because we effectively were immediately evaluating it
after creation anyway
2016-01-17 16:28:22 +03:00
Alexander Udalov
0f2befd327 Minor, fix typos in GenerateProtoBufCompare.kt 2016-01-17 16:28:22 +03:00
Alexander Udalov
f6b5c31e39 build.xml: build kotlin-test along with rest of runtime JARs 2016-01-17 16:28:22 +03:00
Alexander Udalov
8c3661c01c build.xml: add option to skip jarjar of reflect 2016-01-17 16:28:22 +03:00
Alexander Udalov
078a53e6a0 Minor, add regression test for KT-10444
#KT-10444 Obsolete
2016-01-17 16:28:22 +03:00
Alexander Udalov
4a31ad0d53 Make PropertyMetadata internal and deprecated with error
To make them inaccessible from Kotlin sources and drop them later. They're
still needed in runtime because Kotlin tests run old IDEA code (which depends
on PropertyMetadata) with our own runtime
2016-01-17 16:28:22 +03:00
Alexander Udalov
d1f2255d38 Extract JS-related LibraryUtils utilities to JsLibraryUtils 2016-01-17 16:28:22 +03:00
Alexander Udalov
f9085327e7 Minor, export kotlin-reflect in 'util'
To allow many modules which depend on 'util' not depend explicitly on
kotlin-reflect
2016-01-17 16:28:22 +03:00
Ilya Gorbunov
57dcbe0aea Cleanup in libraries and tools: use property access syntax. 2016-01-17 15:52:14 +03:00
Ilya Gorbunov
19a4f65fd1 Cleanup in libraries 2016-01-17 15:52:12 +03:00
Ilya Gorbunov
92c2d17910 Cleanup leftovers in compiler and IDE 2016-01-17 15:52:11 +03:00
Ilya Gorbunov
3d5e415c87 Annotate Iterable.forEach and Map.forEach with HidesMembers.
#KT-10538 Fixed
#KT-10479 Fixed
2016-01-16 15:33:12 +03:00
Stanislav Erokhin
133155f4cc Minor. Temporary import forEach as forEachStdLib to avoid problem with introducing HidesMembers annotation 2016-01-16 11:30:38 +03:00
Ilya Gorbunov
56ddd496c5 Hide listFiles as it's no more preferred by overload resolution over synthetic SAM invocations.
#KT-10652 Fixed
2016-01-15 23:53:44 +03:00
Stanislav Erokhin
b185316a6e Create new HidesMembers annotation 2016-01-15 23:32:34 +03:00
Dmitry Jemerov
0c995d0ae1 Merge pull request #808 from mcgee/KT-10196
KT-10196: Suggest to replace 'substring' calls by take/drop/dropLast calls when possible
2016-01-15 19:52:35 +01:00
Dmitry Jemerov
63dd0fc4ae streamlined plugin update logic 2016-01-15 19:18:26 +01:00
Dmitry Jemerov
765d58b8eb plugin autoupdate fixed: always provide plugin descriptor with new version number to plugin downloader 2016-01-15 19:18:26 +01:00
Michael Bogdanov
9cbde911ce Revert of 'Minor. workaround for KT-10679 Wrong outer after inline.' 2016-01-15 18:24:34 +03:00
Michael Bogdanov
7eec1d8e1d Skip inline lambdas in 'InlineCallSite' parameter calculation; Fix for KT-10679: Wrong outer after inline
#KT-10679 Fixed
2016-01-15 18:24:33 +03:00
Pavel V. Talanov
abf4a5cf43 Show kotlin builtIn classes in "go to symbol"
#KT-10474 Fixed
2016-01-15 18:04:59 +03:00
Pavel V. Talanov
af1e83422e Move KotlinGotoClassContributor and KotlinGotoSymbolContributor to a single Kotlin file (j2k on the fly)
Move the file to "goto" package
2016-01-15 18:04:58 +03:00
Pavel V. Talanov
db07d783a2 Member is considered deprecated if it overrides only deprecated members
Property accessor is considered deprecated when the property is
Provide IDE inspection to strikeout members overriding deprecated members (like in java)
2016-01-15 17:53:23 +03:00
Michael Bogdanov
9b3d97470f Prohibit super calls with default parameters 2016-01-15 17:50:48 +03:00
Mikhail Glukhikh
c48c3fc8ed Cleanup: DataFlowAnalyzer, ignore MethodMayBeStatic for SmartCastManager 2016-01-15 17:22:57 +03:00
Mikhail Glukhikh
6157ebe3b8 Separate UNSAFE_IMPLICIT_INVOKE_CALL diagnostics introduced (see KT-8252) 2016-01-15 17:22:54 +03:00
Mikhail Glukhikh
fe11b5a473 Minor 2016-01-15 17:22:50 +03:00
Mikhail Glukhikh
1049d4c53a Nullable function-like property call is prohibited now #KT-8252 Fixed 2016-01-15 17:22:46 +03:00
Mikhail Glukhikh
0f80df7b2e initialDataFlowInfoForArguments introduced in CallExpressionResolver methods #KT-10175 Fixed 2016-01-15 17:22:42 +03:00
Mikhail Glukhikh
16d97ab72c Get rid of MutableDataFlorInfoForArguments.setInitialDataFlowInfo 2016-01-15 17:22:38 +03:00
Mikhail Glukhikh
5ceb973ee9 Minor refactoring of getQualifiedExpressionTypeInfo 2016-01-15 17:22:35 +03:00
Alexander Udalov
bb68aacee4 Minor refactoring in TowerResolver 2016-01-15 17:15:00 +03:00
NataliaUkhorskaya
b73ce68dbd Debugger: quote package fqName properly. Fix muted tests 2016-01-15 15:57:35 +03:00
NataliaUkhorskaya
d4fcb59965 Gradle plugin: fix compatibility with android-gradle plugin 2.0.0-alpha5
#KT-10676 Fixed
2016-01-15 15:56:47 +03:00
Stanislav Erokhin
8f441a020e Minor. workaround for KT-10679 Wrong outer after inline. 2016-01-15 14:44:24 +03:00
Stanislav Erokhin
3a9ecf0bce 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-15 13:11:38 +03:00
Stanislav Erokhin
dee040a5b5 Minor. Extract tower data creation to separate function. 2016-01-15 13:11:37 +03:00
Stanislav Erokhin
dbd6982b3a Move levels to TowerResolver 2016-01-15 13:11:36 +03:00
Denis Zharkov
a2f8ad1396 Minor. Extract constant FQ names 2016-01-15 09:46:30 +03:00
Denis Zharkov
be2f857670 Introduce inline-only functions
They have private visibility in bytecode
2016-01-15 09:46:30 +03:00
Anton Sukhonosenko
b2e98e9353 Suggest to replace 'substring' calls by take/drop/dropLast calls when possible
Code review fixes
#KT-10196 Fixed
2016-01-14 22:40:50 +03:00
Valentin Kipyatkov
15930a42b8 Fixed containingDeclaration for descriptors inside init-blocks for the case of no primary constructor
KT-10226 Wrong Imports optimization ("Unresolved reference" is being added)

 #KT-10226 Fixed
2016-01-14 21:53:41 +03:00
Denis Zharkov
f4613b8db1 Support foreign nullability annotations
#KT-10418 Fixed
 #KT-10594 Fixed
2016-01-14 19:24:10 +03:00
Denis Zharkov
fd8a718797 Get rid of duplicating annotations FQ names usages
E.g. JETBRAINS_NOT_NULL_ANNOTATION were used both in NULLABLE_ANNOTATIONS
and for ANNOTATIONS_COPIED_TO_TYPES
2016-01-14 19:24:10 +03:00
Denis Zharkov
01fd3905be Minor. Fix typo in package name: typeEnhacement -> typeEnhancement 2016-01-14 19:24:10 +03:00
Valentin Kipyatkov
7c6a33a36c KT-10664 No code completion after variable initialized with elvis
#KT-10664 Fixed
2016-01-14 19:23:01 +03:00
Valentin Kipyatkov
b41f2dcda3 KT-10655 No "in" in code completion popup after "!"
#KT-10655 Fixed
2016-01-14 19:23:01 +03:00
Valentin Kipyatkov
2f1108421e Added container information when needed 2016-01-14 19:23:01 +03:00
Denis Zharkov
23d2b87a52 Ignore redundant projections for declaration-site variance 2016-01-14 19:20:00 +03:00
Pavel V. Talanov
06d0a7c17c Avoid throwing on trying to obtain module info by some unexpected light element 2016-01-14 18:35:05 +03:00
Ilya Gorbunov
7ddac1945e Unify functional parameter name for 'let', 'run', 'with', 'apply' scope function with 'use' and 'synchronize'. 2016-01-14 18:31:57 +03:00
Ilya Gorbunov
4eb3cff129 Unify functional parameter name for 'forEachLine', 'forEachBlock', 'repeat' methods with 'forEach' 2016-01-14 18:31:56 +03:00
Ilya Gorbunov
c9ddea6d03 Breaking: File.(buffered)reader/writer now returns less specific InputStreamReader/OutputStreamReader and use UTF-8 encoding by default, allowing to specify different encoding with optional parameter.
File.printWriter supports specifying Charset and uses UTF-8 by default.
#KT-10454 Fixed
2016-01-14 18:31:55 +03:00
Ilya Gorbunov
a64c1ff0f4 Rename defaultBufferSize to DEFAULT_BUFFER_SIZE. 2016-01-14 18:31:43 +03:00
Ilya Gorbunov
d64882e19b File.useLines and Reader.readLines. 2016-01-14 18:30:45 +03:00
Ilya Gorbunov
ddcafdd9b3 J2K: Avoid to convert to deprecated String methods, namely toByteArray. 2016-01-14 18:30:44 +03:00
Ilya Gorbunov
ac15807ba4 Deprecate functions taking charset name as string. 2016-01-14 18:30:42 +03:00
Ilya Gorbunov
68971e2162 Remove redundant JvmName annotations for Array.copyOf, copyOfRange 2016-01-14 18:30:41 +03:00
Ilya Gorbunov
b99e1111f6 Do not use out projection for Array where appropriate. 2016-01-14 18:30:40 +03:00
Ilya Gorbunov
eb5b5331fb Minor: reorder invariant arrays of objects in generated code 2016-01-14 18:30:39 +03:00
Ilya Gorbunov
362e463b26 Preserve type projection for Array.requireNoNulls.
#KT-10039 Fixed
2016-01-14 18:30:37 +03:00
Ilya Gorbunov
90a33fb19c Make return type more specific for File.inputStream and File.outputStream, for String.byteInputStream 2016-01-14 18:30:20 +03:00
Ilya Gorbunov
ea3a2eefe7 File.deleteRecursively returns true even if path specified by File does not exist.
False is returned only in case of incomplete deletion.
Distinguish situations when file was not deleted because it's vanished after listing and because of some other error.
2016-01-14 18:14:12 +03:00
Ilya Gorbunov
5e6489f1a2 Minor: refactor file utils test not to use 'assert' to make test assertions. Use assertTrue, assertFalse, assertEquals, assertFailsWith instead. 2016-01-14 18:14:11 +03:00
Ilya Gorbunov
3ee9c2b9d8 Introduce exitProcess(status) returning Nothing.
#KT-10441 Fixed
2016-01-14 18:14:10 +03:00
Valentin Kipyatkov
5a079defc7 "Rename on import" hides importing of the same symbol by other imports with the original name 2016-01-14 17:05:28 +03:00
Valentin Kipyatkov
47041885ca Do not use incorrect import 2016-01-14 17:05:13 +03:00
Valentin Kipyatkov
866f3f189f Minor 2016-01-14 17:05:13 +03:00
Valentin Kipyatkov
89843685c2 Renamed class 2016-01-14 17:05:13 +03:00
Dmitry Jemerov
af66af07a0 adapt move refactoring to new behavior of KtFile.getClasses() 2016-01-14 14:20:41 +01:00
Dmitry Jemerov
1bc4420734 implement KtFile.getClasses() in plugin (required to have coverage work, among other things) 2016-01-14 14:20:35 +01:00
Michael Bogdanov
607f32615f Type uncapturing 2016-01-14 15:32:50 +03:00
Michael Bogdanov
2228cb6a9a Rollback parameter descriptor propagation to CapturedTypeConstructor 2016-01-14 15:32:50 +03:00
Alexey Sedunov
6e5a2208c0 Misc: Partially revert cleanup (44138f499e) as accessing synthetic properties leads to IllegalAccessError
#KT-10653 Fixed
2016-01-14 13:55:11 +03:00
Alexey Sedunov
1d9bafe196 PSI Unifier: Fix matching of this-expressions
#KT-8293 Fixed
2016-01-14 13:55:10 +03:00
Alexey Sedunov
ed8674c0f9 Safe Delete: Skip usages inside of overriding to-be-deleted declarations
#KT-7253 Fixed
2016-01-14 13:55:09 +03:00
Alexey Sedunov
59bacd932a Minor: Add test for KT-8295 2016-01-14 13:55:08 +03:00
Alexey Sedunov
e7de6400e5 Create from Usage: Make 'Create annotation' low-priority action
#KT-9116 Fixed
2016-01-14 13:55:07 +03:00
Alexey Sedunov
70a851fe44 Move/Change Package Directive Intention: Skip callee references to inner class constructors
#KT-10554 Fixed
2016-01-14 13:55:05 +03:00
Alexey Sedunov
73233b2e90 Change Variable Mutability Quick-Fix: Forbid on non-primary-constructor parameters
#KT-10601 Fixed
2016-01-14 13:55:03 +03:00
Alexey Sedunov
5a108c5cde Generate equals/hashCode Action: Use Arrays.equals/Arrays.hashCode for properties of array types
#KT-10514 Fixed
2016-01-14 13:55:02 +03:00
Natalia Ukhorskaya
7b67eed3dd Qoute package name if needed
#KT-10649 Fixed
2016-01-14 13:42:19 +03:00
Natalia Ukhorskaya
128440b16f Use intention to simplify for in j2k
#KT-7157 Fixed
2016-01-14 13:41:54 +03:00
Natalia Ukhorskaya
ea3ba6f534 Intention to simplify for using destructing declaration 2016-01-14 13:41:45 +03:00
Natalia Ukhorskaya
5667a92472 Debugger: add breakpoint variant for line with lambda in init block
#KT-KT-1061 Fixed
2016-01-14 13:39:01 +03:00
Natalia Ukhorskaya
2b1d60397d Object to lambda intention is inapplicable when reference to this is used
#KT-10202 In Progress
2016-01-14 13:39:00 +03:00
Natalia Ukhorskaya
41e7c3d70b Debugger: generate package parts only for debug file
#KT-10126 Fixed
2016-01-14 13:38:59 +03:00
Mikhail Zarechenskiy
29af6586f2 Get rid of ContainerUtil usages in ide-common 2016-01-14 12:06:52 +03:00
Mikhail Zarechenskiy
dd11fa9320 Move logic related to expression occurrence searching to ide-common 2016-01-14 12:06:50 +03:00
Mikhail Zarechenskiy
bd57096b66 Move AnalyzerUtil to ide-common 2016-01-14 12:06:49 +03:00
Mikhail Zarechenskiy
bde556fc10 Move QuickFixUtil to ide-common 2016-01-14 12:06:47 +03:00
Mikhail Zarechenskiy
85b4f5d593 Move part of resolutionApi to ide-common 2016-01-14 12:06:45 +03:00
Mikhail Zarechenskiy
1523586717 Extract interface out from KotlinCacheService to provide separate implementation in Eclipse plugin 2016-01-14 12:06:44 +03:00
Dmitry Petrov
609ffc10a9 KT-10322, KT-10646, KT-10647:
- update diagnostic to (supposedly) more useful
- also report IMPLICIT_CAST_TO_ANY if expected type is DONT_CARE
 (effectively "no expected type" for lambda expression).
2016-01-14 10:08:20 +03:00
Dmitry Petrov
f54de08073 KT-10646, KT-10647:
Move IMPLICIT_CAST_TO_UNIT_OR_ANY to ControlFlowInformationProvider
(where checks for 'if' and 'when' used as expressions are performed).
2016-01-14 10:08:20 +03:00
Ilya Gorbunov
f91c01919b kotlin.test: 'fail' returns Nothing, 'assertFails' returns Throwable (not nullable).
Js tests now fail at the first failed assertion.
#KT-10289 Fixed
#KT-10369 Fixed
2016-01-14 06:03:40 +03:00
Dmitry Jemerov
8fdd8179b9 Workaround for KtEnumEntrySuperclassReferenceExpression which implements KtSimpleNameExpression in a weird way and can break Move refactoring (EA-75268 - assert: TextRange.<init>) 2016-01-13 20:28:39 +01:00
Zalim Bashorov
c1dbfee2a9 Don't fail when create IncrementalCacheImpl for target without output directory, and fail when try to use this info instead.
#KT-10505 Fixed
2016-01-13 21:37:36 +03:00
Zalim Bashorov
d9af9472f0 Don't fail when output directory not specified for "friend" build target
#KT-10505 Fixed
2016-01-13 21:09:06 +03:00
Zalim Bashorov
3df091e7cf Report error when output directory not specified for build target
#KT-10505 Fixed
2016-01-13 21:09:05 +03:00
Mikhail Glukhikh
6b09c5dfae Minor when missing cases renderer refactoring 2016-01-13 19:54:54 +03:00
Denis Zharkov
b8c79e689b Make all nested inlined closure classes public
#KT-6987 Fixed
2016-01-13 19:41:59 +03:00
Anton Sukhonosenko
ba0efda2f0 Suggest to replace 'substring' calls by take/drop/dropLast calls when possible
#KT-10196 Fixed
2016-01-13 19:05:50 +03:00
Alexey Tsvetkov
328169cd2e Minor: fix test data as exhaustive when error message was changed 2016-01-13 18:47:05 +03:00
Mikhail Glukhikh
e54471abbc Formatting rule: new line before when entry 2016-01-13 18:04:24 +03:00
Mikhail Glukhikh
b7790177e0 KotlinParserDefinition.kt: converted to Kotlin 2016-01-13 18:04:15 +03:00
Mikhail Glukhikh
6ae7309c54 KotlinParserDefinition.java --> KotlinParserDefinition.kt 2016-01-13 17:54:53 +03:00
Alexey Sedunov
2e18ad7160 Remove Right Part of Binary Expression Quick-Fix: Split to separate quick fixes for cast- and elvis-expressions 2016-01-13 17:47:23 +03:00
Alexey Sedunov
6be44f59da Remove Function Body Quick-Fix: Convert to Kotlin & refactor. Add tests with comments 2016-01-13 17:47:22 +03:00
Alexey Sedunov
de8a3c17a2 Remove Function Body Quick-Fix: Convert to Kotlin (rename to .kt) 2016-01-13 17:47:21 +03:00
Alexey Sedunov
ed679fef9d Remove Element Quick-Fixes: Convert to Kotlin & refactor 2016-01-13 17:47:20 +03:00
Alexey Sedunov
28a0e8ebe6 Remove Element Quick-Fixes: Convert to Kotlin (rename to .kt) 2016-01-13 17:47:19 +03:00
Alexey Sedunov
9a8aef6b6d Remove Right Part of Binary Expression Quick-Fix: Convert to Kotlin & refactor 2016-01-13 17:47:18 +03:00
Alexey Sedunov
0a4a486048 Remove Right Part of Binary Expression Quick-Fix: Convert to Kotlin (rename to .kt) 2016-01-13 17:47:17 +03:00
Alexey Sedunov
cac479102a Remove Supertype Quick-Fix: Convert to Kotlin & refactor 2016-01-13 17:47:16 +03:00
Alexey Sedunov
2fcce20c73 Remove Supertype Quick-Fix: Convert to Kotlin (rename to .kt) 2016-01-13 17:47:15 +03:00
Alexey Sedunov
0fea86c10a Remove 'val'/'var' from Parameter Quick-Fix: Convert to Kotlin & refactor 2016-01-13 17:47:14 +03:00
Alexey Sedunov
f2a6805f8b Remove 'val'/'var' from Parameter Quick-Fix: Convert to Kotlin (rename to .kt) 2016-01-13 17:47:13 +03:00
Alexey Sedunov
474ab531ea Rename Parameter to Match Overridden Method Quick-Fix: Convert to Kotlin & refactor 2016-01-13 17:47:12 +03:00
Alexey Sedunov
c3b3ad52a9 Rename Parameter to Match Overridden Method Quick-Fix: Convert to Kotlin (rename to .kt) 2016-01-13 17:47:11 +03:00
Alexey Sedunov
012a36d97c Remove Nullable Quick-Fix: Convert to Kotlin & refactor 2016-01-13 17:47:10 +03:00
Alexey Sedunov
f1c38f5f16 Remove Nullable Quick-Fix: Convert to Kotlin (rename to .kt) 2016-01-13 17:47:09 +03:00
Alexey Sedunov
111a670d66 Move 'else' Branch in 'when' Quick-Fix: Convert to Kotlin & refactor 2016-01-13 17:47:08 +03:00
Alexey Sedunov
212504bbd4 Move 'else' Branch in 'when' Quick-Fix: Convert to Kotlin (rename to .kt) 2016-01-13 17:47:07 +03:00
Alexey Sedunov
b8a8f1638f Change Visibility Modifier Quick-Fix: Convert to Kotlin & refactor 2016-01-13 17:47:06 +03:00
Alexey Sedunov
1e77caedbc Change Visibility Modifier Quick-Fix: Convert to Kotlin (rename to .kt) 2016-01-13 17:47:05 +03:00
Alexey Sedunov
c44d0ed619 Add 'override' to equals/hashCode/toString Quick-Fix: Convert to Kotlin & refactor 2016-01-13 17:47:04 +03:00
Alexey Sedunov
96e6319ee1 Add 'override' to equals/hashCode/toString Quick-Fix: Convert to Kotlin (rename to .kt) 2016-01-13 17:47:03 +03:00
Alexey Sedunov
64eeaf8b9d Make Class an Annotation Quick-Fix: Convert to Kotlin & refactor 2016-01-13 17:47:02 +03:00
Alexey Sedunov
04b8f16576 Make Class an Annotation Quick-Fix: Convert to Kotlin (rename to .kt) 2016-01-13 17:47:01 +03:00
Alexey Sedunov
6c44aa4d76 Change to Function Invocation Quick-Fix: Convert to Kotlin & refactor 2016-01-13 17:47:00 +03:00
Alexey Sedunov
584d3ad374 Change to Function Invocation Quick-Fix: Convert to Kotlin (rename to .kt) 2016-01-13 17:46:59 +03:00
Alexey Sedunov
a7a5619523 Change to Star-Projection Quick-Fix: Convert to Kotlin & refactor 2016-01-13 17:46:58 +03:00
Alexey Sedunov
625967fc15 Change to Star-Projection Quick-Fix: Convert to Kotlin (rename to .kt) 2016-01-13 17:46:57 +03:00
Alexey Sedunov
3153196343 Change Type Quick-Fix: Convert to Kotlin & refactor. Wrap in delegating quick fix to decrease memory footprint 2016-01-13 17:46:56 +03:00
Alexey Sedunov
11ef780adf Change Type Quick-Fix: Convert to Kotlin (rename to .kt) 2016-01-13 17:46:55 +03:00
Alexey Sedunov
05506a24d7 Add Star Projections Quick-Fix: Convert to Kotlin & refactor 2016-01-13 17:46:54 +03:00
Alexey Sedunov
2e25d2d885 Add Star Projections Quick-Fix: Convert to Kotlin (rename to .kt) 2016-01-13 17:46:53 +03:00
Alexey Sedunov
a696efc3ef Change Accessor Type Quick-Fix: Convert to Kotlin & refactor 2016-01-13 17:46:52 +03:00
Alexey Sedunov
54b149ce71 Change Accessor Type Quick-Fix: Convert to Kotlin (rename to .kt) 2016-01-13 17:46:51 +03:00
Alexey Sedunov
4e54cee693 Cast Expression Quick-Fix: Convert to Kotlin & refactor. Wrap in delegating quick fix to decrease memory footprint 2016-01-13 17:46:49 +03:00
Alexey Sedunov
63ab9df275 Cast Expression Quick-Fix: Convert to Kotlin (rename to .kt) 2016-01-13 17:46:48 +03:00
Alexey Sedunov
7cb5bc8902 Add Else Branch to When Quick-Fix: Convert to Kotlin & refactor 2016-01-13 17:46:47 +03:00
Alexey Sedunov
c0ca4e6b79 Add Else Branch to When Quick-Fix: Convert to Kotlin (rename to .kt) 2016-01-13 17:46:46 +03:00
Alexey Sedunov
f8be2f23a1 Add Function Body Quick-Fix: Convert to Kotlin & refactor 2016-01-13 17:46:45 +03:00
Alexey Sedunov
50497e8013 Add Function Body Quick-Fix: Convert to Kotlin (rename to .kt) 2016-01-13 17:46:43 +03:00
Alexey Sedunov
8264cef004 Quick Fixes: Pass original element to KotlinIntentionActionFactoryWithDelegate.createFix() 2016-01-13 17:46:42 +03:00
Michael Bogdanov
66ab1c484c StackOverflow fix on type remapping 2016-01-13 16:57:36 +03:00
Alexey Tsvetkov
94cea25e2e Recompile all sealed class usages when new derived class is added 2016-01-13 15:46:54 +03:00
Alexey Tsvetkov
0cf2928761 Recompile all enum usages when new entry is added 2016-01-13 15:46:54 +03:00
Alexey Tsvetkov
e7f8d7103f Recompile all class and member usages when flag and member are changed 2016-01-13 15:46:53 +03:00
Alexander Udalov
b0627b4ce6 Minor, add system property to suppress color output in CLI 2016-01-13 14:24:42 +03:00
Mikhail Glukhikh
c3cce53aa2 Quick fix "add when remaining branches" refactoring + enum / sealed generated name w/o package name 2016-01-13 12:32:14 +03:00
Valentin Kipyatkov
0a3631db6a Fixed KT-10602 Incorrect completion for class name
#KT-10602 Fixed
2016-01-12 22:09:12 +03:00
Nikolay Krasko
12b9002c0e Remove assert that isn't valid in UpSource (UP-5742) 2016-01-12 21:40:11 +03:00
Dmitry Jemerov
7390e0ac66 editor is nullable in SelfTargetingIntention.applyTo() 2016-01-12 19:23:51 +01:00
Pavel V. Talanov
9bfa90dc0e Analyze local variable declarations in expression position
Fixes exception on invalid code "val c = 1 < val Int.f: Int = 3"
2016-01-12 19:31:16 +03:00
Pavel V. Talanov
060864f7af Minor: prettify code after autoconversion 2016-01-12 16:47:38 +03:00
Pavel V. Talanov
94ce1d1193 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-12 16:47:31 +03:00
Pavel V. Talanov
9fea22885e AnnotationUtil: Do not throw on ErrorValue constant 2016-01-12 16:08:59 +03:00
Michael Bogdanov
657b9ff808 Write enclosing method info for transformed objects 2016-01-12 15:51:57 +03:00
Michael Bogdanov
8ab1190082 Don't try remap type parameter of inline lambda parent context 2016-01-12 15:51:57 +03:00
Michael Bogdanov
fee6d4f282 Type parameters mapping
#KT-10429 Fixed
2016-01-12 15:51:56 +03:00
Michael Bogdanov
5cdf170511 TypeRemapper.java -> TypeRemapper.kt 2016-01-12 15:51:56 +03:00
Michael Bogdanov
cb41f1cc2a Signature remapping moved to RemappingSignatureAdapter inside TypeRemapper 2016-01-12 15:51:55 +03:00
Michael Bogdanov
dd336a5581 ReifiedTypeParameterMappings renamed to TypeParameterMappings, add isReified property 2016-01-12 15:51:55 +03:00
Michael Bogdanov
833cdb0706 TypeParameterDescriptor propagation to CapturedTypeConstructor 2016-01-12 15:51:54 +03:00
Mikhail Glukhikh
0bcae4e0c0 Build fix: nullable exhaustiveness checker is now only a part of other exhaustiveness checkers 2016-01-12 15:44:55 +03:00
Alexey Tsvetkov
d928ac744e Make withSubtypesOf more efficent 2016-01-12 15:32:48 +03:00
Alexey Tsvetkov
756c78bfcc Append in a more safe way 2016-01-12 15:32:47 +03:00
Alexey Tsvetkov
f137910e63 Make doProcessChangesUsingLookups extension again 2016-01-12 15:32:47 +03:00
Alexey Tsvetkov
f20b39d02e Use one loop for changes processing 2016-01-12 15:32:47 +03:00
Alexey Tsvetkov
d36810ab42 Minor: rename getSubtypeOf->withSubtypes 2016-01-12 15:32:47 +03:00
Alexey Tsvetkov
9190029fcc Add tests for class hierarchy incremental recompilation 2016-01-12 15:32:47 +03:00
Alexey Tsvetkov
e2794cfa3f Do not write inline calls to cache when experimental incremental compilation is enabled 2016-01-12 15:32:47 +03:00
Alexey Tsvetkov
2286268929 Append to class map should use IOUtil.writeUTF 2016-01-12 15:32:47 +03:00
Alexey Tsvetkov
a9fb5647b8 Get caches for targets transitively for exported dependencies 2016-01-12 15:32:46 +03:00
Alexey Tsvetkov
dfc08b8f38 Process changed signatures of classes 2016-01-12 15:32:46 +03:00
Alexey Tsvetkov
ab13b2ddfc Minor: move processChanges 2016-01-12 15:32:46 +03:00
Mikhail Glukhikh
8b6156abd6 Quick fix "Add remaining when branches" with some tests 2016-01-12 14:33:20 +03:00
Mikhail Glukhikh
44b07d8dfa Refactoring: context instead of trace in WhenChecker and around 2016-01-12 14:19:29 +03:00
Mikhail Glukhikh
936fee0afa KT-10295: long enum (sealed) special case 2016-01-12 14:18:36 +03:00
Mikhail Glukhikh
c085eb650f Better diagnostics for non-exhaustive whens, relevant test #KT-10295 Fixed 2016-01-12 14:18:23 +03:00
Mikhail Glukhikh
61c2a88a32 Separate when exhaustiveness checkers with list of missing cases as result 2016-01-12 14:07:08 +03:00
Mikhail Glukhikh
a99b2a6799 J2K: WhenChecker converted to Kotlin 2016-01-12 11:17:09 +03:00
Mikhail Glukhikh
e59fed7d9b J2K: WhenChecker 2016-01-12 11:17:06 +03:00
Dmitry Jemerov
682a61ad26 use PARTIAL_FOR_COMPLETION resolve mode when checking whether reference will resolve to the property, otherwise we're going to miss local variables which shadow the property 2016-01-11 19:05:37 +01:00
Dmitry Jemerov
76c9bbc06d handle setter calls used as expression bodies in "Use property access syntax" intention
#KT-10587 Fixed
2016-01-11 18:53:07 +01:00
Dmitry Jemerov
36488d21da remove empty modifier list after removing visibility modifier 2016-01-11 18:46:04 +01:00
Dmitry Jemerov
d0a4e542af use StubIndex.getElements() with required class specified to diagnose CCE problems when using stub index 2016-01-11 16:29:41 +01:00
Pavel V. Talanov
8d22eafe3f Minor: prettify code 2016-01-11 16:33:20 +03:00
Pavel V. Talanov
41a8ded182 getting rid of ClsFileImpl.setPhysical
patch by Roman Shevchenko
2016-01-11 16:29:19 +03:00
Michael Bogdanov
0274ce4619 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
2016-01-11 09:55:56 +03:00
Dmitry Jemerov
b11acdfbea regenerate builtins (don't remove 'public' modifiers until we agree that we don't want them in stdlib) 2016-01-08 16:01:34 +01:00
Dmitry Jemerov
f885459a43 fix compilation after cleanup 2016-01-08 16:01:28 +01:00
Dmitry Jemerov
5d3ba1ad6c remove "public" from generated code template 2016-01-08 16:01:26 +01:00
Dmitry Jemerov
d5903c5374 workaround for KT-10590: ensure that the inherited getProject() method is public, not protected 2016-01-08 16:01:20 +01:00
Dmitry Jemerov
44138f499e plugins: cleanup 'public', property access syntax 2016-01-07 18:15:44 +01:00
Dmitry Jemerov
d6a11b839b js: cleanup 'public', property access syntax 2016-01-07 18:15:19 +01:00
Dmitry Jemerov
33ef7ad024 jps-plugin: cleanup 'public', property access syntax 2016-01-07 18:14:31 +01:00
Dmitry Jemerov
6684dff14b j2k: cleanup 'public', property access syntax 2016-01-07 18:13:10 +01:00
Dmitry Jemerov
43a6e13f4b idea: cleanup 'public', property access syntax 2016-01-07 18:12:36 +01:00
Dmitry Jemerov
4afbf02bdd generators: cleanup 'public', property access syntax 2016-01-07 18:07:13 +01:00
Dmitry Jemerov
951a313331 eval4j: cleanup 'public', property access syntax 2016-01-07 18:03:29 +01:00
Dmitry Jemerov
3870bd04b8 core: cleanup 'public', property access syntax 2016-01-07 18:03:09 +01:00
Dmitry Jemerov
117a0d8b7b compiler: cleanup 'public', property access syntax 2016-01-07 17:57:38 +01:00
Dmitry Jemerov
b72ea1ff07 ant: cleanup 'public', property access syntax 2016-01-07 17:53:32 +01:00
Dmitry Jemerov
e47e9f6763 inspection and code cleanup for redundant visibility modifiers 2016-01-05 13:31:43 +01:00
Dmitry Petrov
b736880787 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.
2015-12-31 11:07:56 +03:00
Nikolay Krasko
ffd1bcf72f Update icons (KT-10516)
#KT-10516 Fixed
2015-12-30 17:26:34 +03:00
Nikolay Krasko
f9a6da05df Add explicit type (local builds othen fail here) 2015-12-30 17:26:06 +03:00
Nikolay Krasko
0518c6f618 Set "No" as default button 2015-12-30 17:19:16 +03:00
Natalia Ukhorskaya
ad9303b97b Support breakpoints in anonymous objects with usages of cross inline argument 2015-12-30 14:49:30 +03:00
Natalia Ukhorskaya
754b02aa3c Fix EA-76946 - IOOBE: LineSet.checkLineIndex: do not try to get line start offset for line out off document 2015-12-30 14:49:29 +03:00
Natalia Ukhorskaya
0a6dbc91ae Fix EA-75128 - KNPE: IdentifierKt.declarationIdentifier 2015-12-30 14:49:29 +03:00
Natalia Ukhorskaya
5c83e2ac5b KotlinSyntheticTypeComponentProvider: catch UnsupportedOperationException
#KT-10526 Fixed
2015-12-30 14:49:28 +03:00
Natalia Ukhorskaya
36d154babf Support breakpoints for inline function with cross inline argument 2015-12-30 14:49:27 +03:00
Natalia Ukhorskaya
c351293394 KotlinPositionManager: drop PositionElement, classNameForPosition now returns collection of names 2015-12-30 14:49:26 +03:00
Natalia Ukhorskaya
e8aef7d29e Minor: move methods from companion object 2015-12-30 14:49:26 +03:00
Natalia Ukhorskaya
3678bda409 InlineUtil: extract method 2015-12-30 14:49:25 +03:00
Michael Bogdanov
1d70b58d17 Fixed test data 2015-12-30 14:42:12 +03:00
Michael Bogdanov
11268331a8 Added '@' for annotation names in diagnostic messages 2015-12-30 12:25:13 +03:00
Dmitry Petrov
74c13906ed 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.
2015-12-30 10:44:01 +03:00
Dmitry Petrov
4b3290dd8c Check specificity relation for generant types of the constraint system.
Otherwise we can't properly chose between 'dynamic' and generic type.
2015-12-30 10:44:00 +03:00
Dmitry Petrov
c97294a066 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).
2015-12-30 10:44:00 +03:00
Dmitry Petrov
02daeac41b Use constraint system for comparing for specificity against a generic signature.
Drop "discrimiate generics" mode where it's unneeded.
2015-12-30 10:44:00 +03:00
Alexey Sedunov
aeefdffaab Implement Abstract Member Intention: Support primary constructor parameters
#KT-8427 Fixed
2015-12-30 00:56:34 +03:00
Alexey Sedunov
2b4f03feef Implement Members Quick-Fix: Support primary constructor parameters
#KT-8427 In Progress
2015-12-30 00:56:34 +03:00
Alexey Sedunov
00cc9d4150 Specify Type Explicitly: Filter out types which can't be resolved in the target scope
#KT-10066 Fixed
2015-12-30 00:56:34 +03:00
Alexey Sedunov
21fd894d75 Create From Usage: Place caret at the end of initializer selection
#KT-10120 Fixed
2015-12-30 00:56:34 +03:00
Alexey Sedunov
c391882651 Minor: Fix NPE (EA-76742) 2015-12-30 00:56:34 +03:00
Alexey Sedunov
5b5e7fb9b7 'Change parameter type' Quick-Fix: Use Change Signature API
#KT-9812 Fixed
2015-12-30 00:56:34 +03:00
Alexey Sedunov
9180a99342 Convert to Kotlin: ChangeParameterTypeFix.java 2015-12-30 00:56:34 +03:00
Alexey Sedunov
3af7c7b57a Convert to Kotlin: ChangeParameterTypeFix.java (rename to .kt) 2015-12-30 00:56:34 +03:00
Pavel V. Talanov
004c266433 Minor: fix missed error marker in test data 2015-12-29 18:13:10 +03:00
Ilya Gorbunov
0aef321c73 Cleanup in idea plugin, src and tests 2015-12-29 18:04:24 +03:00
Ilya Gorbunov
145722b20d Cleanup in idea plugin modules, misc 2015-12-29 18:04:23 +03:00
Ilya Gorbunov
865fdd7962 Cleanup in idea plugin modules, idea-core 2015-12-29 18:04:22 +03:00
Ilya Gorbunov
6ffc407158 Cleanup in idea plugin modules, idea-completion 2015-12-29 18:04:21 +03:00
Ilya Gorbunov
be590312f7 Cleanup in idea plugin modules, idea-analysis 2015-12-29 18:04:20 +03:00
Ilya Gorbunov
bce9514739 Cleanup in idea plugin modules, ide-common 2015-12-29 18:04:19 +03:00
Ilya Gorbunov
fcfb063eca Cleanup in modules: j2k, jps, ant and generators. 2015-12-29 18:04:18 +03:00
Ilya Gorbunov
da4b1ae0fb Cleanup in js modules 2015-12-29 18:04:16 +03:00
Ilya Gorbunov
80916d5ed7 Cleanup in compiler modules 2015-12-29 18:04:15 +03:00
Ilya Gorbunov
911adfd04d Cleanup in core modules 2015-12-29 18:04:14 +03:00
Ilya Gorbunov
b71b336a69 Fix fq names of moved facade classes in imports and other code occurrences 2015-12-29 18:04:13 +03:00
Nikolay Krasko
f9944e28b0 Show full library panel. Add warning on attempt to create project without library. 2015-12-29 18:01:15 +03:00
Michael Bogdanov
d54c3f4fc7 Added '@' to annotation names in diagnostic messages 2015-12-29 17:20:16 +03:00
Michael Bogdanov
91f27ba176 Report error on 'JvmStatic' annotation on const or @JvmField property
#KT-10415 Fixed
2015-12-29 17:20:07 +03:00
Michael Bogdanov
ae4ca3b5bb Report JvmStatic diagnostic on primary constructor properties 2015-12-29 16:45:24 +03:00
Michael Bogdanov
bb63bcd520 Removed obsolete tests 2015-12-29 16:45:24 +03:00
Michael Bogdanov
e671d05105 Companion public val annotated with @JvmFIeld or const 2015-12-29 16:45:23 +03:00
Michael Bogdanov
e116cc3206 Private visibility for non-const, non-jvmField class companion property backing field 2015-12-29 16:45:22 +03:00
Michael Bogdanov
85ae0cb78e Restrict companion properties copying to interface by const 2015-12-29 16:45:22 +03:00
Pavel V. Talanov
6f0c2a0260 Project configuration: Add source directories for kotlin builtIns to KotlinRuntime 2015-12-29 15:57:02 +03:00
Pavel V. Talanov
9096a443ea 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
2015-12-29 15:57:01 +03:00
Pavel V. Talanov
b38fc7b3c1 Parse local interfaces in expression position 2015-12-29 15:57:00 +03:00
Pavel V. Talanov
1c4d4f3e36 Create class descriptors for local classes in illegal positions
Typecheck code in illegal selector position
Fixes exceptions on "val p = A.class" erroneous code
2015-12-29 15:56:44 +03:00
Pavel V. Talanov
06e829936e Fix codegen predictor for properties and property accessors 2015-12-29 12:32:14 +03:00
Pavel V. Talanov
4f5f56e4a5 Add and use KtPropertyAccessor#getProperty() 2015-12-29 12:32:12 +03:00
Denis Zharkov
d511059cfa Unify code generation of as/is operation
They should be the same for common and reified cases
2015-12-28 18:32:15 +03:00
Denis Zharkov
da53d8cbf4 Replace reified operations instanceof/checkcast with is/as
It's more consistent with how they effectively work
2015-12-28 18:31:40 +03:00
Denis Zharkov
87b6374351 Get rid of redundant intrinsic
Also drop 'safe' parameter from TypeIntrinsics.checkcast,
because it's supposed to work as JVM checkcast (i.e. accepting nulls)
2015-12-28 18:31:40 +03:00
Denis Zharkov
39bbd7c795 Rework reified markers format
Use integer operation identifier instead of method name to differentiate
reified operations
2015-12-28 18:31:40 +03:00
Alexander Udalov
890c961383 Fix reflection internal error on enum nested classes query
#KT-10520 Fixed
2015-12-28 16:40:34 +03:00
Denis Zharkov
688a1b6305 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
2015-12-28 11:13:39 +03:00
Denis Zharkov
722a152a74 Fix supertypes calculation for types with projections
Use captured types as replacement for non top-level entries

 #KT-7296 Fixed
2015-12-28 11:13:39 +03:00
Denis Zharkov
397d2ca312 Fix captured approximation for case of flexible types
#KT-9294 Fixed
2015-12-28 11:13:38 +03:00
Denis Zharkov
b6edddbe8b Make project compilable after member scope refinement 2015-12-28 11:13:38 +03:00
Denis Zharkov
ec0ec55ab5 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
2015-12-28 11:13:37 +03:00
Denis Zharkov
9773e98d8a 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)
2015-12-28 11:13:37 +03:00
Denis Zharkov
e2c02f825f 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
2015-12-28 11:13:37 +03:00
Denis Zharkov
365ff593f3 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
2015-12-28 07:44:56 +03:00
Denis Zharkov
58caff3411 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)
2015-12-28 07:44:56 +03:00
Denis Zharkov
7aaa6422b4 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
2015-12-28 07:44:55 +03:00
Denis Zharkov
8d0a90a838 Preserve type capabilities of captured type 2015-12-28 07:44:55 +03:00
Denis Zharkov
e7dbcfe21f Minor. Cleanup code 2015-12-28 07:44:54 +03:00
Denis Zharkov
555286849e Minor. Move declaration closer to usages and optimize imports 2015-12-28 07:44:54 +03:00
Denis Zharkov
48b89a5db7 Replace unchecked 'is' on local class with unchecked 'as'
It became unchecked after latest changes (see parent commit)
2015-12-28 07:44:54 +03:00
Denis Zharkov
3fd35636ad Fix type parameter list for local classes
Add captured parameters from enclosing functions

 #KT-9584 Fixed
2015-12-28 07:44:53 +03:00
Denis Zharkov
73b961e885 Clean project code after #KT-3996 fix
No overload resolution ambiguity in smart-casts
2015-12-28 07:44:53 +03:00
Mikhail Glukhikh
0cc09872b6 Implicit exhaustive when annotation / highlighting 2015-12-26 10:46:44 +03:00
Mikhail Glukhikh
7d6ccc40c2 Implicit exhaustive whens now have exception in else branch #KT-8700 Fixed 2015-12-26 10:46:39 +03:00
Mikhail Glukhikh
011a9f23b9 Implicit exhaustive when check for definite variable initialization (KT-8700) 2015-12-26 10:46:35 +03:00
Mikhail Glukhikh
52c3fb03a2 ControlFlowInfo introduced to store variable states, related refactoring 2015-12-26 10:46:30 +03:00
Mikhail Glukhikh
0f3997c6ca InitState / VariableUseState / VariableControlFlowState moved to a separate file 2015-12-26 10:46:25 +03:00
Mikhail Glukhikh
4c4456c808 PseudocodeVariablesData converted to Kotlin 2015-12-26 10:46:20 +03:00
Mikhail Glukhikh
7179b37d95 PseudocodeVariablesData.java --> PseudocodeVariablesData.kt 2015-12-26 10:46:16 +03:00
Mikhail Glukhikh
b93894953d Exhaustive whens without else and 'Nothing' as the result are considered 'implicit exhaustive' 2015-12-26 10:46:11 +03:00
Mikhail Glukhikh
d62d7dd84f Introduced binding context storage for implicit exhaustive when (KT-8700) 2015-12-26 10:46:06 +03:00
Mikhail Glukhikh
b805ce06c2 CFG exhaustive when else instruction for KT-8700 2015-12-26 10:46:01 +03:00
Alexander Udalov
697228eae0 Mark enum entry names as name ids for incremental compilation purposes 2015-12-25 20:16:18 +03:00
Alexander Udalov
3513a64351 Move utilities about companion property fields to JvmAbi
To reuse that logic in reflection
2015-12-25 20:16:18 +03:00
Alexander Udalov
0685f06200 Drop outdated stuff from metadata annotations
Make KotlinLocalClass and KotlinInterfaceDefaultImpls not retained at runtime,
to be maybe deleted in the future
2015-12-25 20:16:18 +03:00
Alexander Udalov
0ecf04dcc5 Drop KotlinDelegatedMethod, simplify related code in codegen 2015-12-25 20:16:18 +03:00
Alexander Udalov
39c10867a0 Drop 'index' JVM binary format extension
Compute the JVM parameer index manually instead
2015-12-25 20:16:18 +03:00
Alexander Udalov
8dc604ac8b Drop compatibility flag, suppressing optimized generation of callable references 2015-12-25 20:16:18 +03:00
Alexander Udalov
64b48f4458 Drop compatibility flag, suppressing optimized generation of delegated property metadata 2015-12-25 20:16:18 +03:00
Alexander Udalov
002dc92d89 Drop old antlib.xml in org/jetbrains/jet/buildtools/ant
Use the new one in org/jetbrains/kotlin/ant instead
2015-12-25 20:16:18 +03:00
Alexander Udalov
dc6a176282 Drop old JVM binary format extensions: static in outer, impl class name 2015-12-25 20:16:18 +03:00
Alexander Udalov
fc74759231 Drop old enum entries from binary format 2015-12-25 20:16:18 +03:00
Alexander Udalov
57b96f38a9 Minor, remove/simplify unnecessary utilities in util.runtime 2015-12-25 20:16:18 +03:00
Alexander Udalov
b4addd0567 Move builtins-related logic from DeserializedPackageFragment to BuiltinsPackageFragment 2015-12-25 20:16:18 +03:00
Alexander Udalov
e7da56baf4 Restructure code in BuiltInsSerializer 2015-12-25 20:16:18 +03:00
Alexander Udalov
ddcdc11099 Write and read built-ins binary version 2015-12-25 20:16:18 +03:00
Alexander Udalov
906d706961 Deserialize builtins from new message 2015-12-25 20:16:18 +03:00
Alexander Udalov
7592f31596 Serialize built-ins to separate file .kotlin_builtins 2015-12-25 20:16:18 +03:00
Alexander Udalov
07a23cab10 Minor, make SerializedResourcePaths an interface 2015-12-25 20:16:18 +03:00
Alexander Udalov
75f046fa81 Drop Throwable#printStackTrace, make it a JVM-specific extension 2015-12-25 20:16:18 +03:00
Stanislav Erokhin
3d44471659 KT-10483 Missing smart cast on variable in variable as function call
#KT-10483 Fixed
2015-12-25 20:13:08 +03:00
Alexey Sedunov
4de26bed93 Minor: Add test for now-obsolete KT-8035 "Extended class is not open" quickfix fails on nested classes " 2015-12-25 18:51:03 +03:00
Alexey Sedunov
c90d283ff5 Quick Fixes: Implement 'Add val/var to primary constructor parameter' quick-fix for data classes
#KT-4038 Fixed
2015-12-25 18:50:59 +03:00
Alexey Sedunov
6978d842fb Intentions: Implement 'Add val/var to primary constructor parameter' intention
#KT-4038 In Progress
2015-12-25 18:50:55 +03:00
Alexey Sedunov
5dcf531048 Formatter: Leave single space between val/var and value parameter 2015-12-25 18:50:52 +03:00
Alexey Sedunov
2895e2e86f Change Signature: Process implicit usages of data class 'componentN' functions
#KT-9393 Fixed
2015-12-25 18:50:48 +03:00
Alexey Sedunov
4fba251fba Intentions: 'Implement abstract member' (Kotlin -> Java)
#KT-8467 Fixed
2015-12-25 18:50:41 +03:00
Alexey Sedunov
03641ffbee Intentions: 'Implement abstract member' (Kotlin -> Kotlin)
#KT-8467 In Progress
2015-12-25 18:50:37 +03:00
Alexey Sedunov
123b813073 'Replace with infix call' Intention: Disable on calls without explicit receiver
#KT-6332 Fixed
2015-12-25 18:50:34 +03:00
Alexey Sedunov
ae636a0d32 Iterate Intention: Add support of destructuring declarations 2015-12-25 18:50:30 +03:00
Alexey Sedunov
1d3054e7a6 Iterate Intention: Filter out functions without 'operator' modifier 2015-12-25 18:50:27 +03:00
Alexey Sedunov
1c74bab1cc Iterate Intention: Fix detection of extension iterators
#KT-8616 Fixed
2015-12-25 18:50:23 +03:00
Alexey Sedunov
ee9389d089 Create from Usage: Strip first parameter of extension function when expected type is non-extension 2015-12-25 18:50:19 +03:00
Alexey Sedunov
da2806acde Minor: Fix IllegalAccessError on referencing synthetic property 2015-12-25 12:59:15 +03:00
Michael Bogdanov
f870e365fa Removed accessors for const properties 2015-12-25 11:28:10 +03:00
Michael Bogdanov
b4db23a7b3 Removed 'INSTANCE' field from companions 2015-12-24 13:59:45 +03:00
Michael Bogdanov
2e73559f33 Removed 'INSTANCE$' field generation 2015-12-24 13:59:44 +03:00
Michael Bogdanov
aeb6486473 Deprecated 'INSTANCE$' replaced with 'INSTANCE' 2015-12-24 13:59:43 +03:00
Denis Zharkov
80fd9e3cbb Fix wrong contract assumption
Currently SamAdapterOverridabilityCondition can be called
even for incompatible descriptors

 #KT-10486 Fixed
2015-12-24 12:25:31 +03:00
Ilya Gorbunov
f9ba35af64 Place Char constants into builtin Char companion object. 2015-12-24 06:18:51 +03:00
Ilya Gorbunov
de11ed4fc6 Primitive Companion objects do not longer implement IntegerConstants and FloatingPointConstants. All declarations moved inside companions.
IntegerConstants and FloatingPointConstants are dropped.
#KT-8897 Fixed
2015-12-24 06:17:03 +03:00
Mikhail Glukhikh
fc4250b02b EA-75872 / KT-10473 fix: both JVM- and JS-diagnostic factories are now used as extensions 2015-12-23 18:33:50 +03:00
Mikhail Glukhikh
99a32b93fb Implemented missed checks for local functions #KT-10449 Fixed
Relevant code/test fixes
2015-12-23 18:22:32 +03:00
Mikhail Glukhikh
15746cbf56 Implicit callable type check refactoring, additional check for property with explicit Nothing type 2015-12-23 18:04:25 +03:00
Mikhail Glukhikh
6b8b39a7bd Intersection types are no more allowed in signatures #KT-10244 Fixed 2015-12-23 18:04:21 +03:00
Mikhail Glukhikh
f56dc722d9 Lateinit property backing field now inherits visibility from the property setter 2015-12-23 18:02:20 +03:00
Mikhail Glukhikh
ebda21c68a Codegen tests for lateinit var with private setter 2015-12-23 18:02:07 +03:00
Mikhail Glukhikh
60521e20ff SETTER_VISIBILITY_DIFFERS_FROM_LATEINIT_VISIBILITY diagnostic removed 2015-12-23 17:48:28 +03:00
Pavel V. Talanov
cfacd5da1e Fix a problem caused by getting project using an invalid psi element 2015-12-23 17:07:51 +03:00
Alexander Udalov
a7324ebad2 Minor, additional constructor for JvmPackagePartSource 2015-12-23 16:45:26 +03:00
Alexander Udalov
12e921ab15 Minor, add test on annotation in enum companion 2015-12-23 16:45:26 +03:00
Alexander Udalov
7170d488bd Fix package part class name calculation
Package part name can contain dollars
2015-12-23 16:45:26 +03:00
Alexander Udalov
e67318e049 Minor, add DescriptorUtils.isClassOrEnumClass 2015-12-23 16:45:26 +03:00
Alexander Udalov
48a0a95e8f Fix nested class context in cls stub builder
Previously two contexts were created for a nested class stub: one with the
replaced NameResolver, another with everything else. Now only one is created
2015-12-23 16:45:26 +03:00
Alexander Udalov
cd435c4130 Do not load implClassName JVM proto extension
Use JvmPackagePartSource instead for functions/properties in package parts,
check containing class kind for properties in interfaces
2015-12-23 16:45:26 +03:00
Alexander Udalov
03606c13aa Introduce PackagePartSource to store part class name in deserialized descriptors
Not used at the moment, will be in the following commits
2015-12-23 16:45:26 +03:00
Alexander Udalov
f4c5289cfc Minor, fix typo in class name: jmv -> jvm 2015-12-23 16:45:26 +03:00
Alexander Udalov
51cdb981f4 Remove obsolete code in IncrementalPackageFragmentProvider 2015-12-23 16:45:26 +03:00
Alexander Udalov
f7969621d6 Don't read isStaticInOuter message for fields
It's only written for fields of properties of companion objects of classes;
handle that case manually in deserialization
2015-12-23 16:45:26 +03:00
Alexander Udalov
696dce68fb Move deserialized callable descriptors to single file, convert to Kotlin 2015-12-23 16:45:26 +03:00
Alexander Udalov
19372a7210 Minor, make ProtoContainer sealed with two subclasses 2015-12-23 16:45:26 +03:00
Alexander Udalov
745de229cc Minor, split IMPL_CLASS_NAME_FOR_CALLABLE to two slices 2015-12-23 16:45:26 +03:00
Yan Zhulanow
b3877b5f0b Always compile Android projects without JDK in classpath #KT-10479 2015-12-23 16:42:35 +03:00
Pavel V. Talanov
70dc5a5c4c IDELightClassGenerationSupport: fix a problem when marking source root as both source and library source led to SO
# KT-10413 Fixed
2015-12-23 16:08:34 +03:00
Pavel V. Talanov
a8c5e0cc95 Minor, ProjectRootsUtil: extract a couple of utils and use them 2015-12-23 16:08:34 +03:00
Pavel V. Talanov
f20aba63a6 Add better diagnostic for "could not create stub for nested class" failures 2015-12-23 15:13:13 +03:00
Pavel V. Talanov
6a1ca7b9c9 Fix an exception caused by objects literals in supertype list not considered local 2015-12-23 14:56:27 +03:00
Dmitry Petrov
00db7d150b Fix KT-10472: compare all overloads including varargs in a single pass. 2015-12-23 10:05:40 +03:00
Nikolay Krasko
f25d80c38b Make add test lib quick-fix applicable only when there is unresolved import 2015-12-22 19:44:15 +03:00
Nikolay Krasko
259397db9d Add library for Gradle 2015-12-22 19:44:15 +03:00
Nikolay Krasko
2fba6c361a Determine maven library version from kotlin-stdlib 2015-12-22 19:44:15 +03:00
Nikolay Krasko
5467671a21 Add libraries to maven 2015-12-22 19:44:15 +03:00
Nikolay Krasko
1b92fa94bc Add kotlin-test.jar to classpath quickfix 2015-12-22 19:44:14 +03:00
Pavel V. Talanov
99966c17da Go to (show) implementations: skip light methods that are generated with DELEGATION or DELEGATION_TO_DEFAULT_IMPLS JvmDeclarationOriginKind
Add some unrelated tests for fake overrides
2015-12-22 17:30:51 +03:00
Stanislav Erokhin
de6f52030c Hack for unavailable archive.apache.org: use bintray.com instead 2015-12-22 16:44:10 +03:00
Dmitry Petrov
142e85be04 Prohibit functions (and constructors) with multiple vararg parameters. 2015-12-22 10:40:41 +03:00
Alexander Udalov
ed2ad8e8e3 Minor, fix warnings related to OperatorNameConventions 2015-12-21 20:41:45 +03:00
Alexander Udalov
97ce61ac44 Throw exception on inlining bytecode of version > 1.6
To prevent ASM from failing with a meaningless exception in this case as soon
as we support target 1.8 and someone tries to compile some code with the
current compiler against the new (1.8) code.
2015-12-21 20:38:18 +03:00
Alexander Udalov
7449ad2763 Rename Extension annotation to ExtensionFunctionType
The old one is kept temporarily and will be removed later
2015-12-21 20:33:32 +03:00
Alexander Udalov
6d40d94127 Minor, use String instead of DeprecationLevel
Using classes from runtime in the compiler is confusing and doesn't allow to
incompatibly change them
2015-12-21 20:28:40 +03:00
Alexander Udalov
c10cc30f40 Drop kotlin.jvm.internal.Intrinsic, use only one mechanism for intrinsics 2015-12-21 20:28:40 +03:00
Alexander Udalov
6048ebf871 Fix terminology: internal name instead of FQ name 2015-12-21 20:27:41 +03:00
Alexander Udalov
2ccd6d54b7 Add kotlin-reflect as a separate library
Exclude in core modules, since they do not have kotlin-reflect.jar in
dependencies when are built in build.xml
2015-12-21 18:46:08 +03:00
Alexander Udalov
a9476dfe37 Replace 'kotlin-runtime' in module dependencies with 'util' 2015-12-21 18:46:08 +03:00
Alexander Udalov
fa8c1f1a37 Delete obsolete tests on metadata annotations 2015-12-21 18:46:08 +03:00
Alexander Udalov
12922c3abd Minor, delete kunit source root from StdlibTest 2015-12-21 18:46:08 +03:00
Sergey Mashkov
c5e43a1327 kotlin-test: fix manifest description caused by copy-paste 2015-12-21 18:43:54 +03:00
Sergey Mashkov
2b6ae3127b kotlin-test: exclude OnlyInpuType from dist kotlin-test as well 2015-12-21 15:39:44 +03:00
Sergey Mashkov
8139070754 kotlin-test: exclude OnlyInputTypes annotation from jar 2015-12-21 15:14:55 +03:00
Sergey Mashkov
5ad0a84039 rename kotlin.test to kotlin-test 2015-12-21 15:10:24 +03:00
Andrey Breslav
a7e7d53e2b Reserve "async* {}", extend the quick-fix 2015-12-21 07:15:37 +03:00
Andrey Breslav
45074841a4 Minor. Additional test for "async {}" 2015-12-21 07:15:37 +03:00
Stanislav Erokhin
318f0c89b2 Completion fix for reserved 'async' syntax 2015-12-21 07:15:37 +03:00
Nikolay Krasko
afc1e24571 Quick fix for deprecated async syntax 2015-12-21 07:15:37 +03:00
Nikolay Krasko
01095bc652 More usages for getTestRoots method 2015-12-19 14:32:40 +03:00
Nikolay Krasko
2c1bf4dbd9 Remove filenameStartsLowerCase flag and clean warnings 2015-12-19 14:32:39 +03:00
Nikolay Krasko
aee36c40cd Request resolve only for modifier list for suppression check 2015-12-19 14:32:39 +03:00
Nikolay Krasko
b79aa686bb Avoid analyze in suppression check if there are no suppression annotations 2015-12-19 14:32:38 +03:00
Nikolay Krasko
697132561f Allow to override suppression key for inspections 2015-12-19 14:32:38 +03:00
Nikolay Krasko
8196621be5 Add test for inspections suppression 2015-12-19 14:32:38 +03:00
Nikolay Krasko
aff83087a3 Allow to suppress warnings at file level 2015-12-19 14:32:37 +03:00
Nikolay Krasko
712d2bdec0 Enable suppression actions for Kotlin inspections 2015-12-19 14:32:37 +03:00
Nikolay Krasko
94c0ccf2bf Fix test with dummy diagnostic 2015-12-19 14:32:36 +03:00
Nikolay Krasko
36210f0a27 Allow to suppress kotlin inspections with Suppress() annotation 2015-12-19 14:32:36 +03:00
Nikolay Krasko
ef265e23f8 Refactoring: SuppressionManager -> KotlinSuppressCache 2015-12-19 14:32:35 +03:00
Nikolay Krasko
b61b4e1c90 Allow to check suppression by string keys 2015-12-19 14:32:35 +03:00
Nikolay Krasko
20379028e8 Refactoring: extract separate class that can store suppressions 2015-12-19 14:32:34 +03:00
Nikolay Krasko
e562b73eff Refactoring: extract method for check test is AllFilesPresent test 2015-12-19 14:32:33 +03:00
Nikolay Krasko
5cd23daf4e Allow to run additional resolve from KtFileAnnotationList 2015-12-19 14:32:33 +03:00
Nikolay Krasko
0aa8d89b16 Minor: regenerate, optimize imports 2015-12-19 14:32:32 +03:00
Ilya Gorbunov
0a1f4d6088 Deprecate IndexingIterable and IndexingIterator and provide Iterator.withIndex() instead of the latter. 2015-12-19 09:56:52 +03:00
Ilya Gorbunov
fbfeb98ecf Deprecate some top-level constants to make 'em private later. 2015-12-19 09:56:46 +03:00
Ilya Chernikov
6ba68da811 Working around cancellation-related exception in case of different versions of daemon and client 2015-12-18 22:17:15 +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
7725 changed files with 97728 additions and 54948 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

@@ -24,6 +24,7 @@
<element id="module-output" name="deserialization" />
<element id="extracted-dir" path="$PROJECT_DIR$/dependencies/native-platform-uberjar.jar" path-in-jar="/" />
<element id="module-output" name="android-jps-plugin" />
<element id="module-output" name="build" />
</root>
</artifact>
</component>

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>

8
.idea/dictionaries/dzharkov.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<component name="ProjectDictionaryState">
<dictionary name="dzharkov">
<words>
<w>checkcast</w>
<w>insn</w>
</words>
</dictionary>
</component>

BIN
.idea/icon.png generated Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

6
.idea/kotlinc.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="KotlinCompilerSettings">
<option name="additionalArguments" value="-version -Xallow-kotlin-package -Xskip-metadata-version-check" />
</component>
</project>

9
.idea/libraries/kotlin_reflect.xml generated Normal file
View File

@@ -0,0 +1,9 @@
<component name="libraryTable">
<library name="kotlin-reflect">
<CLASSES>
<root url="jar://$KOTLIN_BUNDLED$/lib/kotlin-reflect.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</component>

View File

@@ -2,11 +2,12 @@
<library name="kotlin-runtime">
<CLASSES>
<root url="jar://$KOTLIN_BUNDLED$/lib/kotlin-runtime.jar!/" />
<root url="jar://$KOTLIN_BUNDLED$/lib/kotlin-reflect.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="file://$PROJECT_DIR$/libraries/stdlib/src" />
<root url="file://$PROJECT_DIR$/core/builtins/native" />
<root url="file://$PROJECT_DIR$/core/builtins/src" />
</SOURCES>
</library>
</component>

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>

4
.idea/modules.xml generated
View File

@@ -13,6 +13,7 @@
<module fileurl="file://$PROJECT_DIR$/compiler/backend/backend.iml" filepath="$PROJECT_DIR$/compiler/backend/backend.iml" group="compiler/java" />
<module fileurl="file://$PROJECT_DIR$/compiler/backend-common/backend-common.iml" filepath="$PROJECT_DIR$/compiler/backend-common/backend-common.iml" group="compiler" />
<module fileurl="file://$PROJECT_DIR$/jps-plugin/bare-plugin/bare-plugin.iml" filepath="$PROJECT_DIR$/jps-plugin/bare-plugin/bare-plugin.iml" group="ide/jps" />
<module fileurl="file://$PROJECT_DIR$/build/build.iml" filepath="$PROJECT_DIR$/build/build.iml" />
<module fileurl="file://$PROJECT_DIR$/core/builtins/builtins.iml" filepath="$PROJECT_DIR$/core/builtins/builtins.iml" group="core" />
<module fileurl="file://$PROJECT_DIR$/compiler/builtins-serializer/builtins-serializer.iml" filepath="$PROJECT_DIR$/compiler/builtins-serializer/builtins-serializer.iml" group="compiler/cli" />
<module fileurl="file://$PROJECT_DIR$/compiler/cli/cli.iml" filepath="$PROJECT_DIR$/compiler/cli/cli.iml" group="compiler/cli" />
@@ -40,7 +41,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 +63,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

@@ -9,6 +9,7 @@
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="ant" level="project" />
<orderEntry type="library" name="kotlin-runtime" level="project" />
<orderEntry type="library" name="kotlin-reflect" level="project" />
<orderEntry type="module" module-name="preloader" />
</component>
</module>

View File

@@ -1,7 +0,0 @@
<!-- NOTE: this Antlib is deprecated. Use org/jetbrains/kotlin/ant/antlib.xml instead -->
<!-- TODO: delete this file -->
<antlib>
<taskdef name="kotlinc" classname="org.jetbrains.kotlin.ant.Kotlin2JvmTask"/>
<taskdef name="kotlin2js" classname="org.jetbrains.kotlin.ant.Kotlin2JsTask"/>
<typedef name="withKotlin" classname="org.jetbrains.kotlin.ant.KotlinCompilerAdapter"/>
</antlib>

View File

@@ -19,22 +19,22 @@ package org.jetbrains.kotlin.ant
import org.apache.tools.ant.types.Path
import java.io.File
public class Kotlin2JsTask : KotlinCompilerBaseTask() {
class Kotlin2JsTask : KotlinCompilerBaseTask() {
override val compilerFqName = "org.jetbrains.kotlin.cli.js.K2JSCompiler"
public var library: Path? = null
public var outputPrefix: File? = null
public var outputPostfix: File? = null
public var sourceMap: Boolean = false
public var metaInfo: Boolean = false
var library: Path? = null
var outputPrefix: File? = null
var outputPostfix: File? = null
var sourceMap: Boolean = false
var metaInfo: Boolean = false
/**
* {@link K2JsArgumentConstants.CALL} (default) if need generate a main function call (main function will be auto detected)
* {@link K2JsArgumentConstants.NO_CALL} otherwise.
*/
public var main: String? = null
var main: String? = null
public fun createLibrary(): Path {
fun createLibrary(): Path {
val libraryPath = library
if (libraryPath == null) {
val t = Path(getProject())

View File

@@ -20,15 +20,15 @@ import org.apache.tools.ant.types.Path
import org.apache.tools.ant.types.Reference
import java.io.File.pathSeparator
public class Kotlin2JvmTask : KotlinCompilerBaseTask() {
class Kotlin2JvmTask : KotlinCompilerBaseTask() {
override val compilerFqName = "org.jetbrains.kotlin.cli.jvm.K2JVMCompiler"
public var includeRuntime: Boolean = true
public var moduleName: String? = null
var includeRuntime: Boolean = true
var moduleName: String? = null
private var compileClasspath: Path? = null
public fun setClasspath(classpath: Path) {
fun setClasspath(classpath: Path) {
if (compileClasspath == null) {
compileClasspath = classpath
}
@@ -37,14 +37,14 @@ public class Kotlin2JvmTask : KotlinCompilerBaseTask() {
}
}
public fun setClasspathRef(ref: Reference) {
fun setClasspathRef(ref: Reference) {
if (compileClasspath == null) {
compileClasspath = Path(getProject())
}
compileClasspath!!.createPath().setRefid(ref)
compileClasspath!!.createPath().refid = ref
}
public fun addConfiguredClasspath(classpath: Path) {
fun addConfiguredClasspath(classpath: Path) {
setClasspath(classpath)
}

View File

@@ -29,12 +29,12 @@ object KotlinAntTaskUtil {
private val libPath: File by lazy {
// Find path of kotlin-ant.jar in the filesystem and find kotlin-compiler.jar in the same directory
val resourcePath = "/" + javaClass.getName().replace('.', '/') + ".class"
val resourcePath = "/" + javaClass.name.replace('.', '/') + ".class"
val jarConnection = javaClass.getResource(resourcePath).openConnection() as? JarURLConnection
?: throw UnsupportedOperationException("Kotlin compiler Ant task should be loaded from the JAR file")
val antTaskJarPath = File(jarConnection.getJarFileURL().toURI())
val antTaskJarPath = File(jarConnection.jarFileURL.toURI())
antTaskJarPath.getParentFile()
antTaskJarPath.parentFile
}
val compilerJar: File by lazy {
@@ -47,7 +47,7 @@ object KotlinAntTaskUtil {
private fun File.assertExists(): File {
if (!this.exists()) {
throw IllegalStateException("${getName()} is not found in the directory of Kotlin Ant task")
throw IllegalStateException("${name} is not found in the directory of Kotlin Ant task")
}
return this
}
@@ -68,5 +68,5 @@ object KotlinAntTaskUtil {
}
public val Task.defaultModuleName: String?
val Task.defaultModuleName: String?
get() = owningTarget?.name ?: project?.name

View File

@@ -70,7 +70,7 @@ class KotlinCompilerAdapter : Javac13() {
// Javac13#execute passes everything in compileList to javac, which doesn't recognize .kt files
val compileListForJavac = filterOutKotlinSources(compileList)
val hasKotlinFilesInSources = compileListForJavac.size() < compileList.size()
val hasKotlinFilesInSources = compileListForJavac.size < compileList.size
if (hasKotlinFilesInSources) {
kotlinc.execute()

View File

@@ -24,25 +24,25 @@ import org.apache.tools.ant.types.Reference
import java.io.File
import java.io.PrintStream
public abstract class KotlinCompilerBaseTask : Task() {
abstract class KotlinCompilerBaseTask : Task() {
protected abstract val compilerFqName: String
public val args: MutableList<String> = arrayListOf()
val args: MutableList<String> = arrayListOf()
public var src: Path? = null
public var output: File? = null
public var nowarn: Boolean = false
public var verbose: Boolean = false
public var printVersion: Boolean = false
public var failOnError: Boolean = true
var src: Path? = null
var output: File? = null
var nowarn: Boolean = false
var verbose: Boolean = false
var printVersion: Boolean = false
var failOnError: Boolean = true
public var noStdlib: Boolean = false
var noStdlib: Boolean = false
public val additionalArguments: MutableList<Commandline.Argument> = arrayListOf()
val additionalArguments: MutableList<Commandline.Argument> = arrayListOf()
public var exitCode: Int? = null
var exitCode: Int? = null
public fun createSrc(): Path {
fun createSrc(): Path {
val srcPath = src
if (srcPath == null) {
val t = Path(getProject())
@@ -53,11 +53,11 @@ public abstract class KotlinCompilerBaseTask : Task() {
return srcPath.createPath()
}
public fun setSrcRef(ref: Reference) {
createSrc().setRefid(ref)
fun setSrcRef(ref: Reference) {
createSrc().refid = ref
}
public fun createCompilerArg(): Commandline.Argument {
fun createCompilerArg(): Commandline.Argument {
val argument = Commandline.Argument()
additionalArguments.add(argument)
return argument
@@ -65,7 +65,7 @@ public abstract class KotlinCompilerBaseTask : Task() {
abstract fun fillSpecificArguments()
public fun fillArguments() {
fun fillArguments() {
val sourcePaths = src ?: throw BuildException("\"src\" should be specified")
args.addAll(sourcePaths.list().map { File(it).canonicalPath })
@@ -75,7 +75,7 @@ public abstract class KotlinCompilerBaseTask : Task() {
if (verbose) args.add("-verbose")
if (printVersion) args.add("-version")
args.addAll(additionalArguments.flatMap { it.getParts().toList() })
args.addAll(additionalArguments.flatMap { it.parts.toList() })
fillSpecificArguments()
}
@@ -85,12 +85,12 @@ public abstract class KotlinCompilerBaseTask : Task() {
val compilerClass = KotlinAntTaskUtil.getOrCreateClassLoader().loadClass(compilerFqName)
val compiler = compilerClass.newInstance()
val exec = compilerClass.getMethod("execFullPathsInMessages", javaClass<PrintStream>(), javaClass<Array<String>>())
val exec = compilerClass.getMethod("execFullPathsInMessages", PrintStream::class.java, Array<String>::class.java)
log("Compiling ${src!!.list().toList()} => [${output!!.canonicalPath}]");
val result = exec(compiler, System.err, args.toTypedArray())
exitCode = (result as Enum<*>).ordinal()
exitCode = (result as Enum<*>).ordinal
if (failOnError && exitCode != 0) {
throw BuildException("Compile failed; see the compiler error output for details.")

185
build.xml
View File

@@ -6,14 +6,19 @@
<!-- Set to false to disable compiler's javadoc generation. Speeds up the build -->
<property name="generate.javadoc" value="true"/>
<!-- Set to false to prevent jarjar and metadata stripping on kotlin-reflect.jar and reflection sources. Use to debug reflection -->
<property name="obfuscate.reflect" value="true"/>
<property name="max.heap.size.for.forked.jvm" value="1024m"/>
<property name="bootstrap.home" value="${basedir}/dependencies/bootstrap-compiler"/>
<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 +60,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 +183,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 +328,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 +354,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 +363,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 +382,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/**"/>
@@ -531,8 +551,12 @@
<javac2 destdir="${output}/classes/compiler" debug="true" debuglevel="lines,vars,source" includeAntRuntime="false"
source="${java.target}" target="${java.target}">
<withKotlin modulename="kotlin-compiler"/>
<withKotlin modulename="kotlin-compiler">
<!-- remove after bootstrapping packages -->
<compilerarg value="-Xallow-kotlin-package"/>
</withKotlin>
<skip pattern="kotlin/jvm/internal/.*"/>
<skip pattern="kotlin/Metadata"/>
<src refid="compilerSources.path"/>
<classpath refid="classpath"/>
</javac2>
@@ -583,6 +607,51 @@
</jar>
</target>
<target name="kotlin-build">
<cleandir dir="${output}/classes/kotlin-build"/>
<javac2 destdir="${output}/classes/kotlin-build" debug="true" debuglevel="lines,vars,source" includeAntRuntime="false"
source="${java.target}" target="${java.target}">
<withKotlin modulename="kotlin-build"/>
<skip pattern="kotlin/jvm/internal/.*"/>
<src>
<pathelement path="build/src"/>
</src>
<classpath>
<pathelement path="${bootstrap.runtime}"/>
<pathelement path="${bootstrap.reflect}"/>
<pathelement path="${idea.sdk}/lib/util.jar"/>
<pathelement path="${kotlin-home}/lib/kotlin-compiler.jar"/>
</classpath>
</javac2>
<jar destfile="${kotlin-home}/lib/kotlin-build.jar">
<fileset dir="${output}/classes/kotlin-build"/>
<zipfileset file="${kotlin-home}/build.txt" prefix="META-INF"/>
<manifest>
<attribute name="Built-By" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Vendor" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Title" value="${manifest.impl.title.kotlin.build}"/>
<attribute name="Implementation-Version" value="${build.number}"/>
</manifest>
</jar>
<jar jarfile="${output}/kotlin-build-sources.jar">
<fileset dir="build/src"/>
<zipfileset file="${kotlin-home}/build.txt" prefix="META-INF"/>
<manifest>
<attribute name="Built-By" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Vendor" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Title" value="${manifest.impl.title.kotlin.build.sources}"/>
<attribute name="Implementation-Version" value="${build.number}"/>
</manifest>
</jar>
</target>
<target name="daemon-client">
<cleandir dir="${output}/classes/daemon-client"/>
@@ -602,6 +671,14 @@
<fileset dir="${output}/classes/daemon-client"/>
<zipfileset src="${dependencies.dir}/native-platform-uberjar.jar" includes="**" />
<zipfileset file="${kotlin-home}/build.txt" prefix="META-INF"/>
<manifest>
<attribute name="Built-By" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Vendor" value="${manifest.impl.vendor}"/>
<attribute name="Implementation-Title" value="${manifest.impl.title.kotlin.daemon-client}"/>
<attribute name="Implementation-Version" value="${build.number}"/>
</manifest>
</jar>
</target>
@@ -610,6 +687,7 @@
<javac2 destdir="${output}/classes/android-compiler-plugin" debug="true" debuglevel="lines,vars,source" includeAntRuntime="false">
<withKotlin modulename="kotlin-android-compiler-plugin"/>
<skip pattern="kotlin/jvm/internal/.*"/>
<skip pattern="kotlin/Metadata"/>
<src>
<pathelement path="plugins/android-compiler-plugin/src"/>
</src>
@@ -634,6 +712,7 @@
source="${java.target}" target="${java.target}">
<withKotlin modulename="kotlin-ant-tools"/>
<skip pattern="kotlin/jvm/internal/.*"/>
<skip pattern="kotlin/Metadata"/>
<src>
<dirset dir="${basedir}/ant">
<include name="src"/>
@@ -730,11 +809,13 @@
<arg value="${toString:classpath.path}"/>
<arg value="-module-name"/>
<arg value="@{moduleName}"/>
<arg value="-Xallow-kotlin-package"/>
</java>
<javac2 srcdir="${toString:src.dirset}" destdir="@{output}" debug="true" debuglevel="lines,vars,source"
includeAntRuntime="false" source="${java.target}" target="${java.target}">
<skip pattern="kotlin/jvm/internal/.*"/>
<skip pattern="kotlin/Metadata"/>
<classpath>
<path refid="classpath.path"/>
<!-- Include @{output} here for Java compiler to resolve symbols from Kotlin sources -->
@@ -791,6 +872,26 @@
</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>
<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="core">
<new-kotlinc output="${output}/classes/core" moduleName="kotlin-core">
<src>
@@ -877,31 +978,46 @@
</jar>
<delete file="${output}/kotlin-reflect-jarjar.jar" failonerror="false"/>
<taskdef name="jarjar" classname="com.tonicsystems.jarjar.JarJarTask" classpath="dependencies/jarjar.jar"/>
<jarjar jarfile="${output}/kotlin-reflect-jarjar.jar" filesonly="true" filesetmanifest="merge">
<zipfileset src="${output}/kotlin-reflect-before-jarjar.jar"/>
<rule pattern="org.jetbrains.kotlin.**" result="kotlin.reflect.jvm.internal.impl.@1"/>
<rule pattern="com.google.protobuf.**" result="kotlin.reflect.jvm.internal.impl.com.google.protobuf.@1"/>
<rule pattern="javax.inject.**" result="kotlin.reflect.jvm.internal.impl.javax.inject.@1"/>
</jarjar>
<kotlinc src="${basedir}/generators/infrastructure/strip-kotlin-annotations.kts" output="">
<compilerarg value="-script"/>
<compilerarg value="kotlin/jvm/internal/.*"/> <!-- Annotations to strip -->
<compilerarg value="kotlin/reflect/jvm/internal/impl/.*"/> <!-- Classes to strip from -->
<compilerarg value="${output}/kotlin-reflect-jarjar.jar"/>
<compilerarg value="${kotlin-home}/lib/kotlin-reflect.jar"/>
<classpath>
<pathelement location="${idea.sdk}/lib/asm-all.jar"/>
</classpath>
</kotlinc>
<sequential if:true="${obfuscate.reflect}">
<taskdef name="jarjar" classname="com.tonicsystems.jarjar.JarJarTask" classpath="dependencies/jarjar.jar"/>
<jarjar jarfile="${output}/kotlin-reflect-jarjar.jar" filesonly="true" filesetmanifest="merge">
<zipfileset src="${output}/kotlin-reflect-before-jarjar.jar"/>
<rule pattern="org.jetbrains.kotlin.**" result="kotlin.reflect.jvm.internal.impl.@1"/>
<rule pattern="com.google.protobuf.**" result="kotlin.reflect.jvm.internal.impl.com.google.protobuf.@1"/>
<rule pattern="javax.inject.**" result="kotlin.reflect.jvm.internal.impl.javax.inject.@1"/>
</jarjar>
<kotlinc src="${basedir}/generators/infrastructure/strip-kotlin-annotations.kts" output="">
<compilerarg value="-script"/>
<compilerarg value="kotlin/jvm/internal/.*|kotlin/Metadata"/> <!-- Annotations to strip -->
<compilerarg value="kotlin/reflect/jvm/internal/impl/.*"/> <!-- Classes to strip from -->
<compilerarg value="${output}/kotlin-reflect-jarjar.jar"/>
<compilerarg value="${kotlin-home}/lib/kotlin-reflect.jar"/>
<classpath>
<pathelement location="${idea.sdk}/lib/asm-all.jar"/>
</classpath>
</kotlinc>
</sequential>
<sequential unless:true="${obfuscate.reflect}">
<echo message="Obfuscation of kotlin-reflect is disabled"/>
<copy file="${output}/kotlin-reflect-before-jarjar.jar" tofile="${output}/kotlin-reflect-jarjar.jar" overwrite="true"/>
<copy file="${output}/kotlin-reflect-before-jarjar.jar" tofile="${kotlin-home}/lib/kotlin-reflect.jar" overwrite="true"/>
</sequential>
</target>
<target name="pack-runtime-sources">
<!-- Rename packages in the sources of reflection impl (core) -->
<delete dir="${output}/core.src" failonerror="false"/>
<copy todir="${output}/core.src/kotlin/reflect/jvm/internal/impl">
<local name="runtime.sources.base.dir"/>
<condition property="runtime.sources.base.dir"
value="${output}/core.src/kotlin/reflect/jvm/internal/impl"
else="${output}/core.src/org/jetbrains/kotlin">
<istrue value="${obfuscate.reflect}"/>
</condition>
<copy todir="${runtime.sources.base.dir}">
<fileset dir="core">
<include name="descriptor.loader.java/src/**"/>
<include name="descriptors/src/**"/>
@@ -911,9 +1027,13 @@
</fileset>
<cutdirsmapper dirs="5"/> <!-- module/src/org/jetbrains/kotlin -->
</copy>
<replaceregexp match="org\.jetbrains\.kotlin" replace="kotlin.reflect.jvm.internal.impl" flags="g">
<fileset dir="${output}/core.src"/>
</replaceregexp>
<sequential if:true="${obfuscate.reflect}">
<!-- Rename packages in the sources of reflection impl (core) -->
<replaceregexp match="org\.jetbrains\.kotlin" replace="kotlin.reflect.jvm.internal.impl" flags="g">
<fileset dir="${output}/core.src"/>
</replaceregexp>
</sequential>
<pack-runtime-jar jar-name="kotlin-runtime-sources.jar" implementation-title="${manifest.impl.title.kotlin.jvm.runtime.sources}">
<jar-content>
@@ -936,10 +1056,10 @@
</target>
<target name="runtime"
depends="builtins,stdlib,core,reflection,pack-runtime,pack-runtime-sources"/>
depends="builtins,stdlib,kotlin-test,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,kotlin-build,ant-tools,jdk-annotations,android-sdk-annotations,runtime,kotlin-js-stdlib,android-compiler-plugin,daemon-client"
description="Builds redistributables from sources"/>
<target name="dist-quick"
@@ -965,6 +1085,7 @@
source="${java.target}" target="${java.target}">
<withKotlin modulename="kotlin-for-upsource"/>
<skip pattern="kotlin/jvm/internal/.*"/>
<skip pattern="kotlin/Metadata"/>
<src>
<dirset dir="${basedir}/idea/ide-common" includes="src"/>
<dirset dir="${basedir}/idea/idea-analysis" includes="src"/>

19
build/build.iml Normal file
View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/testData" type="java-test-resource" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module" module-name="frontend.java" />
<orderEntry type="module" module-name="util.runtime" />
<orderEntry type="module" module-name="cli-common" />
<orderEntry type="module" module-name="util" />
<orderEntry type="module" module-name="compiler-tests" scope="TEST" />
<orderEntry type="library" scope="TEST" name="idea-full" level="project" />
</component>
</module>

View File

@@ -14,7 +14,7 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.jps.build
package org.jetbrains.kotlin.build
import java.io.File

View File

@@ -0,0 +1,40 @@
/*
* 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.build
import org.jetbrains.kotlin.incremental.LocalFileKotlinClass
import org.jetbrains.kotlin.load.kotlin.ModuleMapping
import org.jetbrains.kotlin.utils.sure
import java.io.File
open class GeneratedFile<Target>(
val target: Target,
val sourceFiles: Collection<File>,
val outputFile: File
)
class GeneratedJvmClass<Target> (
target: Target,
sourceFiles: Collection<File>,
outputFile: File
) : GeneratedFile<Target>(target, sourceFiles, outputFile) {
val outputClass = LocalFileKotlinClass.create(outputFile).sure {
"Couldn't load KotlinClass from $outputFile; it may happen because class doesn't have valid Kotlin annotations"
}
}
fun File.isModuleMappingFile() = extension == ModuleMapping.MAPPING_FILE_EXT && parentFile.name == "META-INF"

View File

@@ -0,0 +1,126 @@
/*
* 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.incremental
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.config.IncrementalCompilation
import org.jetbrains.kotlin.load.java.JvmBytecodeBinaryVersion
import org.jetbrains.kotlin.load.kotlin.JvmMetadataVersion
import java.io.File
private val NORMAL_VERSION = 8
private val EXPERIMENTAL_VERSION = 2
private val DATA_CONTAINER_VERSION = 1
private val NORMAL_VERSION_FILE_NAME = "format-version.txt"
private val EXPERIMENTAL_VERSION_FILE_NAME = "experimental-format-version.txt"
private val DATA_CONTAINER_VERSION_FILE_NAME = "data-container-format-version.txt"
class CacheVersion(
private val ownVersion: Int,
private val versionFile: File,
private val whenVersionChanged: CacheVersion.Action,
private val whenTurnedOn: CacheVersion.Action,
private val whenTurnedOff: CacheVersion.Action,
isEnabled: ()->Boolean
) {
private val isEnabled by lazy(isEnabled)
private val actualVersion: Int
get() = versionFile.readText().toInt()
private val expectedVersion: Int
get() {
val metadata = JvmMetadataVersion.INSTANCE
val bytecode = JvmBytecodeBinaryVersion.INSTANCE
return ownVersion * 1000000 +
bytecode.major * 10000 + bytecode.minor * 100 +
metadata.major * 1000 + metadata.minor
}
fun checkVersion(): Action =
when (versionFile.exists() to isEnabled) {
true to true -> if (actualVersion != expectedVersion) whenVersionChanged else Action.DO_NOTHING
false to true -> whenTurnedOn
true to false -> whenTurnedOff
else -> Action.DO_NOTHING
}
fun saveIfNeeded() {
if (!isEnabled) return
if (!versionFile.parentFile.exists()) {
versionFile.parentFile.mkdirs()
}
versionFile.writeText(expectedVersion.toString())
}
fun clean() {
versionFile.delete()
}
@get:TestOnly
val formatVersionFile: File
get() = versionFile
// Order of entries is important, because actions are sorted in KotlinBuilder::checkVersions
enum class Action {
REBUILD_ALL_KOTLIN,
REBUILD_CHUNK,
CLEAN_NORMAL_CACHES,
CLEAN_EXPERIMENTAL_CACHES,
CLEAN_DATA_CONTAINER,
DO_NOTHING
}
}
fun normalCacheVersion(dataRoot: File): CacheVersion =
CacheVersion(ownVersion = NORMAL_VERSION,
versionFile = File(dataRoot, NORMAL_VERSION_FILE_NAME),
whenVersionChanged = CacheVersion.Action.REBUILD_CHUNK,
whenTurnedOn = CacheVersion.Action.REBUILD_CHUNK,
whenTurnedOff = CacheVersion.Action.CLEAN_NORMAL_CACHES,
isEnabled = { IncrementalCompilation.isEnabled() })
fun experimentalCacheVersion(dataRoot: File): CacheVersion =
CacheVersion(ownVersion = EXPERIMENTAL_VERSION,
versionFile = File(dataRoot, EXPERIMENTAL_VERSION_FILE_NAME),
whenVersionChanged = CacheVersion.Action.REBUILD_CHUNK,
whenTurnedOn = CacheVersion.Action.REBUILD_CHUNK,
whenTurnedOff = CacheVersion.Action.CLEAN_EXPERIMENTAL_CACHES,
isEnabled = { IncrementalCompilation.isExperimental() })
fun dataContainerCacheVersion(dataRoot: File): CacheVersion =
CacheVersion(ownVersion = DATA_CONTAINER_VERSION,
versionFile = File(dataRoot, DATA_CONTAINER_VERSION_FILE_NAME),
whenVersionChanged = CacheVersion.Action.REBUILD_ALL_KOTLIN,
whenTurnedOn = CacheVersion.Action.REBUILD_ALL_KOTLIN,
whenTurnedOff = CacheVersion.Action.CLEAN_DATA_CONTAINER,
isEnabled = { IncrementalCompilation.isExperimental() })
fun allCachesVersions(containerDataRoot: File, dataRoots: Iterable<File>): Iterable<CacheVersion> {
val versions = arrayListOf<CacheVersion>()
versions.add(dataContainerCacheVersion(containerDataRoot))
for (dataRoot in dataRoots) {
versions.add(normalCacheVersion(dataRoot))
versions.add(experimentalCacheVersion(dataRoot))
}
return versions
}

View File

@@ -14,99 +14,99 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.jps.incremental
package org.jetbrains.kotlin.incremental
import com.google.protobuf.MessageLite
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtil.toSystemIndependentName
import com.intellij.util.SmartList
import com.intellij.util.io.BooleanDataDescriptor
import com.intellij.util.io.EnumeratorStringDescriptor
import com.intellij.util.io.IOUtil
import gnu.trove.THashSet
import org.jetbrains.annotations.TestOnly
import org.jetbrains.jps.builders.BuildTarget
import org.jetbrains.jps.builders.storage.BuildDataPaths
import org.jetbrains.jps.builders.storage.StorageProvider
import org.jetbrains.jps.incremental.ModuleBuildTarget
import org.jetbrains.jps.incremental.storage.BuildDataManager
import org.jetbrains.jps.incremental.storage.PathStringDescriptor
import org.jetbrains.kotlin.build.GeneratedJvmClass
import org.jetbrains.kotlin.config.IncrementalCompilation
import org.jetbrains.kotlin.inline.inlineFunctionsJvmNames
import org.jetbrains.kotlin.jps.build.GeneratedJvmClass
import org.jetbrains.kotlin.jps.build.KotlinBuilder
import org.jetbrains.kotlin.jps.incremental.storage.*
import org.jetbrains.kotlin.incremental.storage.*
import org.jetbrains.kotlin.load.kotlin.ModuleMapping
import org.jetbrains.kotlin.load.kotlin.header.isCompatibleClassKind
import org.jetbrains.kotlin.load.kotlin.header.isCompatibleFileFacadeKind
import org.jetbrains.kotlin.load.kotlin.header.isCompatibleMultifileClassKind
import org.jetbrains.kotlin.load.kotlin.header.isCompatibleMultifileClassPartKind
import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader
import org.jetbrains.kotlin.load.kotlin.incremental.components.IncrementalCache
import org.jetbrains.kotlin.load.kotlin.incremental.components.JvmPackagePartProto
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.serialization.ProtoBuf
import org.jetbrains.kotlin.serialization.deserialization.NameResolver
import org.jetbrains.kotlin.serialization.deserialization.TypeTable
import org.jetbrains.kotlin.serialization.deserialization.supertypes
import org.jetbrains.kotlin.serialization.jvm.BitEncoding
import org.jetbrains.kotlin.serialization.jvm.JvmProtoBufUtil
import org.jetbrains.org.objectweb.asm.*
import org.jetbrains.org.objectweb.asm.ClassReader
import org.jetbrains.org.objectweb.asm.ClassVisitor
import org.jetbrains.org.objectweb.asm.FieldVisitor
import org.jetbrains.org.objectweb.asm.Opcodes
import java.io.File
import java.security.MessageDigest
import java.util.*
internal val CACHE_DIRECTORY_NAME = "kotlin"
val KOTLIN_CACHE_DIRECTORY_NAME = "kotlin"
@TestOnly
public fun getCacheDirectoryName(): String =
CACHE_DIRECTORY_NAME
public class IncrementalCacheImpl(
targetDataRoot: File,
private val target: ModuleBuildTarget
open class IncrementalCacheImpl<Target>(
private val targetDataRoot: File,
targetOutputDir: File?,
target: Target
) : BasicMapsOwner(), IncrementalCache {
companion object {
val PROTO_MAP = "proto"
val CONSTANTS_MAP = "constants"
val INLINE_FUNCTIONS = "inline-functions"
val PACKAGE_PARTS = "package-parts"
val MULTIFILE_CLASS_FACADES = "multifile-class-facades"
val MULTIFILE_CLASS_PARTS = "multifile-class-parts"
val SOURCE_TO_CLASSES = "source-to-classes"
val DIRTY_OUTPUT_CLASSES = "dirty-output-classes"
val DIRTY_INLINE_FUNCTIONS = "dirty-inline-functions"
val INLINED_TO = "inlined-to"
private val PROTO_MAP = "proto"
private val CONSTANTS_MAP = "constants"
private val PACKAGE_PARTS = "package-parts"
private val MULTIFILE_CLASS_FACADES = "multifile-class-facades"
private val MULTIFILE_CLASS_PARTS = "multifile-class-parts"
private val SOURCE_TO_CLASSES = "source-to-classes"
private val DIRTY_OUTPUT_CLASSES = "dirty-output-classes"
private val SUBTYPES = "subtypes"
private val SUPERTYPES = "supertypes"
private val MODULE_MAPPING_FILE_NAME = "." + ModuleMapping.MAPPING_FILE_EXT
}
private val baseDir = File(targetDataRoot, CACHE_DIRECTORY_NAME)
private val baseDir = File(targetDataRoot, KOTLIN_CACHE_DIRECTORY_NAME)
private val experimentalMaps = arrayListOf<BasicMap<*, *>>()
private val String.storageFile: File
private fun <K, V, M : BasicMap<K, V>> registerExperimentalMap(map: M): M {
experimentalMaps.add(map)
return registerMap(map)
}
protected val String.storageFile: File
get() = File(baseDir, this + "." + CACHE_EXTENSION)
private val protoMap = registerMap(ProtoMap(PROTO_MAP.storageFile))
private val constantsMap = registerMap(ConstantsMap(CONSTANTS_MAP.storageFile))
private val inlineFunctionsMap = registerMap(InlineFunctionsMap(INLINE_FUNCTIONS.storageFile))
private val packagePartMap = registerMap(PackagePartMap(PACKAGE_PARTS.storageFile))
private val multifileClassFacadeMap = registerMap(MultifileClassFacadeMap(MULTIFILE_CLASS_FACADES.storageFile))
private val multifileClassPartMap = registerMap(MultifileClassPartMap(MULTIFILE_CLASS_PARTS.storageFile))
private val multifileFacadeToParts = registerMap(MultifileClassFacadeMap(MULTIFILE_CLASS_FACADES.storageFile))
private val partToMultifileFacade = registerMap(MultifileClassPartMap(MULTIFILE_CLASS_PARTS.storageFile))
private val sourceToClassesMap = registerMap(SourceToClassesMap(SOURCE_TO_CLASSES.storageFile))
private val dirtyOutputClassesMap = registerMap(DirtyOutputClassesMap(DIRTY_OUTPUT_CLASSES.storageFile))
private val dirtyInlineFunctionsMap = registerMap(DirtyInlineFunctionsMap(DIRTY_INLINE_FUNCTIONS.storageFile))
private val inlinedTo = registerMap(InlineFunctionsFilesMap(INLINED_TO.storageFile))
private val subtypesMap = registerExperimentalMap(SubtypesMap(SUBTYPES.storageFile))
private val supertypesMap = registerExperimentalMap(SupertypesMap(SUPERTYPES.storageFile))
private val cacheFormatVersion = CacheFormatVersion(targetDataRoot)
private val dependents = arrayListOf<IncrementalCacheImpl>()
private val outputDir = requireNotNull(target.outputDir) { "Target is expected to have output directory: $target" }
private val dependents = arrayListOf<IncrementalCacheImpl<Target>>()
private val outputDir by lazy(LazyThreadSafetyMode.NONE) { requireNotNull(targetOutputDir) { "Target is expected to have output directory: $target" } }
// TODO: review
val dependentsWithThis: Sequence<IncrementalCacheImpl<Target>>
get() = sequenceOf(this).plus(dependents.asSequence())
internal val dependentCaches: Iterable<IncrementalCacheImpl<Target>>
get() = dependents
override fun registerInline(fromPath: String, jvmSignature: String, toPath: String) {
inlinedTo.add(fromPath, jvmSignature, toPath)
}
public fun addDependentCache(cache: IncrementalCacheImpl) {
protected open fun debugLog(message: String) {}
fun addDependentCache(cache: IncrementalCacheImpl<Target>) {
dependents.add(cache)
}
public fun markOutputClassesDirty(removedAndCompiledSources: List<File>) {
fun markOutputClassesDirty(removedAndCompiledSources: List<File>) {
for (sourceFile in removedAndCompiledSources) {
val classes = sourceToClassesMap[sourceFile]
classes.forEach {
@@ -117,38 +117,14 @@ public class IncrementalCacheImpl(
}
}
public fun getFilesToReinline(): Collection<File> {
val result = THashSet(FileUtil.PATH_HASHING_STRATEGY)
for ((className, functions) in dirtyInlineFunctionsMap.getEntries()) {
val classFilePath = getClassFilePath(className.internalName)
fun addFilesAffectedByChangedInlineFuns(cache: IncrementalCacheImpl) {
val targetFiles = functions.flatMap { cache.inlinedTo[classFilePath, it] }
result.addAll(targetFiles)
}
addFilesAffectedByChangedInlineFuns(this)
dependents.forEach(::addFilesAffectedByChangedInlineFuns)
}
cleanDirtyInlineFunctions()
return result.map { File(it) }
}
public fun cleanDirtyInlineFunctions() {
dirtyInlineFunctionsMap.clean()
}
fun getSubtypesOf(className: FqName): Sequence<FqName> =
subtypesMap[className].asSequence()
override fun getClassFilePath(internalClassName: String): String {
return toSystemIndependentName(File(outputDir, "$internalClassName.class").canonicalPath)
}
public fun saveCacheFormatVersion() {
cacheFormatVersion.saveIfNeeded()
}
public fun saveModuleMappingToCache(sourceFiles: Collection<File>, file: File): CompilationResult {
fun saveModuleMappingToCache(sourceFiles: Collection<File>, file: File): CompilationResult {
val jvmClassName = JvmClassName.byInternalName(MODULE_MAPPING_FILE_NAME)
protoMap.process(jvmClassName, file.readBytes(), emptyArray<String>(), isPackage = false, checkChangesIsOpenPart = false)
dirtyOutputClassesMap.notDirty(MODULE_MAPPING_FILE_NAME)
@@ -156,48 +132,59 @@ public class IncrementalCacheImpl(
return CompilationResult.NO_CHANGES
}
public fun saveFileToCache(generatedClass: GeneratedJvmClass): CompilationResult {
fun saveFileToCache(generatedClass: GeneratedJvmClass<Target>): CompilationResult {
val sourceFiles: Collection<File> = generatedClass.sourceFiles
val kotlinClass: LocalFileKotlinClass = generatedClass.outputClass
val className = JvmClassName.byClassId(kotlinClass.classId)
val className = kotlinClass.className
dirtyOutputClassesMap.notDirty(className.internalName)
sourceFiles.forEach {
sourceToClassesMap.add(it, className)
}
if (kotlinClass.classId.isLocal) {
return CompilationResult.NO_CHANGES
}
val header = kotlinClass.classHeader
val changesInfo = when {
header.isCompatibleFileFacadeKind() -> {
assert(sourceFiles.size() == 1) { "Package part from several source files: $sourceFiles" }
val changesInfo = when (header.kind) {
KotlinClassHeader.Kind.FILE_FACADE -> {
assert(sourceFiles.size == 1) { "Package part from several source files: $sourceFiles" }
packagePartMap.addPackagePart(className)
protoMap.process(kotlinClass, isPackage = true) +
constantsMap.process(kotlinClass) +
inlineFunctionsMap.process(kotlinClass, isPackage = true)
additionalProcessChangedClass(kotlinClass, isPackage = true)
}
header.isCompatibleMultifileClassKind() -> {
val partNames = kotlinClass.classHeader.filePartClassNames?.toList()
KotlinClassHeader.Kind.MULTIFILE_CLASS -> {
val partNames = kotlinClass.classHeader.data?.toList()
?: throw AssertionError("Multifile class has no parts: ${kotlinClass.className}")
multifileClassFacadeMap.add(className, partNames)
multifileFacadeToParts[className] = partNames
// When a class is replaced with a facade with the same name,
// the class' proto wouldn't ever be deleted,
// because we don't write proto for multifile facades.
// As a workaround we can remove proto values for multifile facades.
protoMap.remove(className)
// TODO NO_CHANGES? (delegates only)
constantsMap.process(kotlinClass) +
inlineFunctionsMap.process(kotlinClass, isPackage = true)
additionalProcessChangedClass(kotlinClass, isPackage = true)
}
header.isCompatibleMultifileClassPartKind() -> {
assert(sourceFiles.size() == 1) { "Multifile class part from several source files: $sourceFiles" }
KotlinClassHeader.Kind.MULTIFILE_CLASS_PART -> {
assert(sourceFiles.size == 1) { "Multifile class part from several source files: $sourceFiles" }
packagePartMap.addPackagePart(className)
multifileClassPartMap.add(className.internalName, header.multifileClassName!!)
partToMultifileFacade.set(className.internalName, header.multifileClassName!!)
protoMap.process(kotlinClass, isPackage = true) +
constantsMap.process(kotlinClass) +
inlineFunctionsMap.process(kotlinClass, isPackage = true)
additionalProcessChangedClass(kotlinClass, isPackage = true)
}
header.isCompatibleClassKind() && !header.isLocalClass -> {
KotlinClassHeader.Kind.CLASS -> {
addToClassStorage(kotlinClass)
protoMap.process(kotlinClass, isPackage = false) +
constantsMap.process(kotlinClass) +
inlineFunctionsMap.process(kotlinClass, isPackage = false)
additionalProcessChangedClass(kotlinClass, isPackage = false)
}
else -> CompilationResult.NO_CHANGES
}
@@ -206,15 +193,17 @@ public class IncrementalCacheImpl(
return changesInfo
}
protected open fun additionalProcessChangedClass(kotlinClass: LocalFileKotlinClass, isPackage: Boolean) = CompilationResult.NO_CHANGES
private fun CompilationResult.logIfSomethingChanged(className: JvmClassName) {
if (this == CompilationResult.NO_CHANGES) return
KotlinBuilder.LOG.debug("$className is changed: $this")
debugLog("$className is changed: $this")
}
public fun clearCacheForRemovedClasses(): CompilationResult {
fun clearCacheForRemovedClasses(): CompilationResult {
fun <T> T.getNonPrivateNames(nameResolver: NameResolver, vararg members: T.() -> List<MessageLite>) =
fun <T> T.getNonPrivateNames(nameResolver: NameResolver, vararg members: T.() -> List<MessageLite>): Set<String> =
members.flatMap { this.it().filterNot { it.isPrivate }.names(nameResolver) }.toSet()
fun createChangeInfo(className: JvmClassName): ChangeInfo? {
@@ -244,8 +233,7 @@ public class IncrementalCacheImpl(
ProtoBuf.Class::getConstructorList,
ProtoBuf.Class::getFunctionList,
ProtoBuf.Class::getPropertyList
) +
classData.classProto.enumEntryList.map { classData.nameResolver.getString(it) }.toSet()
) + classData.classProto.enumEntryList.map { classData.nameResolver.getString(it.name) }
ChangeInfo.Removed(className.fqNameForClassNameWithoutDollars, memberNames)
}
@@ -270,27 +258,54 @@ public class IncrementalCacheImpl(
info + newInfo
}
val facadesWithRemovedParts = hashMapOf<JvmClassName, MutableSet<String>>()
for (dirtyClass in dirtyClasses) {
val facade = partToMultifileFacade.get(dirtyClass.internalName) ?: continue
val facadeClassName = JvmClassName.byInternalName(facade)
val removedParts = facadesWithRemovedParts.getOrPut(facadeClassName) { hashSetOf() }
removedParts.add(dirtyClass.internalName)
}
for ((facade, removedParts) in facadesWithRemovedParts.entries) {
val allParts = multifileFacadeToParts[facade.internalName] ?: continue
val notRemovedParts = allParts.filter { it !in removedParts }
if (notRemovedParts.isEmpty()) {
multifileFacadeToParts.remove(facade)
}
else {
multifileFacadeToParts[facade] = notRemovedParts
}
}
dirtyClasses.forEach {
protoMap.remove(it)
packagePartMap.remove(it)
multifileClassFacadeMap.remove(it)
multifileClassPartMap.remove(it)
multifileFacadeToParts.remove(it)
partToMultifileFacade.remove(it)
constantsMap.remove(it)
inlineFunctionsMap.remove(it)
}
additionalProcessRemovedClasses(dirtyClasses)
removeAllFromClassStorage(dirtyClasses)
dirtyOutputClassesMap.clean()
return changesInfo
}
protected open fun additionalProcessRemovedClasses(dirtyClasses: List<JvmClassName>) {
}
override fun getObsoletePackageParts(): Collection<String> {
val obsoletePackageParts =
dirtyOutputClassesMap.getDirtyOutputClasses().filter { packagePartMap.isPackagePart(JvmClassName.byInternalName(it)) }
KotlinBuilder.LOG.debug("Obsolete package parts: ${obsoletePackageParts}")
debugLog("Obsolete package parts: ${obsoletePackageParts}")
return obsoletePackageParts
}
override fun getPackagePartData(fqName: String): JvmPackagePartProto? {
return protoMap[JvmClassName.byInternalName(fqName)]?.let { value ->
override fun getPackagePartData(partInternalName: String): JvmPackagePartProto? {
return protoMap[JvmClassName.byInternalName(partInternalName)]?.let { value ->
JvmPackagePartProto(value.bytes, value.strings)
}
}
@@ -298,40 +313,46 @@ public class IncrementalCacheImpl(
override fun getObsoleteMultifileClasses(): Collection<String> {
val obsoleteMultifileClasses = linkedSetOf<String>()
for (dirtyClass in dirtyOutputClassesMap.getDirtyOutputClasses()) {
val dirtyFacade = multifileClassPartMap.getFacadeName(dirtyClass) ?: continue
val dirtyFacade = partToMultifileFacade.get(dirtyClass) ?: continue
obsoleteMultifileClasses.add(dirtyFacade)
}
KotlinBuilder.LOG.debug("Obsolete multifile class facades: $obsoleteMultifileClasses")
debugLog("Obsolete multifile class facades: $obsoleteMultifileClasses")
return obsoleteMultifileClasses
}
override fun getStableMultifileFacadeParts(facadeInternalName: String): Collection<String>? {
val partNames = multifileClassFacadeMap.getMultifileClassParts(facadeInternalName) ?: return null
val partNames = multifileFacadeToParts.get(facadeInternalName) ?: return null
return partNames.filter { !dirtyOutputClassesMap.isDirty(it) }
}
override fun getMultifileFacade(partInternalName: String): String? {
return multifileClassPartMap.getFacadeName(partInternalName)
return partToMultifileFacade.get(partInternalName)
}
override fun getModuleMappingData(): ByteArray? {
return protoMap[JvmClassName.byInternalName(MODULE_MAPPING_FILE_NAME)]?.bytes
}
public override fun clean() {
override fun clean() {
super.clean()
cacheFormatVersion.clean()
normalCacheVersion(targetDataRoot).clean()
experimentalCacheVersion(targetDataRoot).clean()
}
fun cleanExperimental() {
experimentalCacheVersion(targetDataRoot).clean()
experimentalMaps.forEach { it.clean() }
}
private inner class ProtoMap(storageFile: File) : BasicStringMap<ProtoMapValue>(storageFile, ProtoMapValueExternalizer) {
public fun process(kotlinClass: LocalFileKotlinClass, isPackage: Boolean): CompilationResult {
fun process(kotlinClass: LocalFileKotlinClass, isPackage: Boolean): CompilationResult {
val header = kotlinClass.classHeader
val bytes = BitEncoding.decodeBytes(header.annotationData!!)
val bytes = BitEncoding.decodeBytes(header.data!!)
return put(kotlinClass.className, bytes, header.strings!!, isPackage, checkChangesIsOpenPart = true)
}
public fun process(className: JvmClassName, data: ByteArray, strings: Array<String>, isPackage: Boolean, checkChangesIsOpenPart: Boolean): CompilationResult {
fun process(className: JvmClassName, data: ByteArray, strings: Array<String>, isPackage: Boolean, checkChangesIsOpenPart: Boolean): CompilationResult {
return put(className, data, strings, isPackage, checkChangesIsOpenPart)
}
@@ -352,20 +373,19 @@ public class IncrementalCacheImpl(
if (oldData == null || !checkChangesIsOpenPart) return CompilationResult(protoChanged = true)
val diff = difference(oldData, data)
if (!IncrementalCompilation.isExperimental()) return CompilationResult(protoChanged = diff != DifferenceKind.NONE)
val difference = difference(oldData, data)
val fqName = if (isPackage) className.packageFqName else className.fqNameForClassNameWithoutDollars
val changeList = SmartList<ChangeInfo>()
val changes =
when (diff) {
is DifferenceKind.NONE -> emptySequence<ChangeInfo>()
is DifferenceKind.CLASS_SIGNATURE -> sequenceOf(ChangeInfo.SignatureChanged(fqName))
is DifferenceKind.MEMBERS -> sequenceOf(ChangeInfo.MembersChanged(fqName, diff.names))
}
if (difference.isClassAffected) {
changeList.add(ChangeInfo.SignatureChanged(fqName, difference.areSubclassesAffected))
}
return CompilationResult(protoChanged = diff != DifferenceKind.NONE, changes = changes)
if (difference.changedMembersNames.isNotEmpty()) {
changeList.add(ChangeInfo.MembersChanged(fqName, difference.changedMembersNames))
}
return CompilationResult(protoChanged = changeList.isNotEmpty(), changes = changeList.asSequence())
}
operator fun contains(className: JvmClassName): Boolean =
@@ -374,7 +394,7 @@ public class IncrementalCacheImpl(
operator fun get(className: JvmClassName): ProtoMapValue? =
storage[className.internalName]
public fun remove(className: JvmClassName) {
fun remove(className: JvmClassName) {
storage.remove(className.internalName)
}
@@ -403,12 +423,12 @@ public class IncrementalCacheImpl(
operator fun contains(className: JvmClassName): Boolean =
className.internalName in storage
public fun process(kotlinClass: LocalFileKotlinClass): CompilationResult {
fun process(kotlinClass: LocalFileKotlinClass): CompilationResult {
return put(kotlinClass.className, getConstantsMap(kotlinClass.fileContents))
}
private fun put(className: JvmClassName, constantsMap: Map<String, Any>?): CompilationResult {
val key = className.getInternalName()
val key = className.internalName
val oldMap = storage[key]
if (oldMap == constantsMap) return CompilationResult.NO_CHANGES
@@ -423,7 +443,7 @@ public class IncrementalCacheImpl(
return CompilationResult(constantsChanged = true)
}
public fun remove(className: JvmClassName) {
fun remove(className: JvmClassName) {
put(className, null)
}
@@ -431,214 +451,132 @@ public class IncrementalCacheImpl(
value.dumpMap(Any::toString)
}
private inner class InlineFunctionsMap(storageFile: File) : BasicStringMap<Map<String, Long>>(storageFile, StringToLongMapExternalizer) {
private fun getInlineFunctionsMap(bytes: ByteArray): Map<String, Long> {
val result = HashMap<String, Long>()
val inlineFunctions = inlineFunctionsJvmNames(bytes)
if (inlineFunctions.isEmpty()) return emptyMap()
ClassReader(bytes).accept(object : ClassVisitor(Opcodes.ASM5) {
override fun visitMethod(access: Int, name: String, desc: String, signature: String?, exceptions: Array<out String>?): MethodVisitor? {
val dummyClassWriter = ClassWriter(Opcodes.ASM5)
return object : MethodVisitor(Opcodes.ASM5, dummyClassWriter.visitMethod(0, name, desc, null, exceptions)) {
override fun visitEnd() {
val jvmName = name + desc
if (jvmName !in inlineFunctions) return
val dummyBytes = dummyClassWriter.toByteArray()!!
val hash = dummyBytes.md5()
result[jvmName] = hash
}
}
}
}, 0)
return result
}
public fun process(kotlinClass: LocalFileKotlinClass, isPackage: Boolean): CompilationResult {
return put(kotlinClass.className, getInlineFunctionsMap(kotlinClass.fileContents), isPackage)
}
private fun put(className: JvmClassName, newMap: Map<String, Long>, isPackage: Boolean): CompilationResult {
val internalName = className.internalName
val oldMap = storage[internalName] ?: emptyMap()
val added = hashSetOf<String>()
val changed = hashSetOf<String>()
val allFunctions = oldMap.keySet() + newMap.keySet()
for (fn in allFunctions) {
val oldHash = oldMap[fn]
val newHash = newMap[fn]
when {
oldHash == null -> added.add(fn)
oldHash != newHash -> changed.add(fn)
}
}
when {
newMap.isNotEmpty() -> storage[internalName] = newMap
else -> storage.remove(internalName)
}
if (changed.isNotEmpty()) {
dirtyInlineFunctionsMap.put(className, changed.toList())
}
val changes =
if (IncrementalCompilation.isExperimental()) {
val fqName = if (isPackage) className.packageFqName else className.fqNameForClassNameWithoutDollars
// TODO get name in better way instead of using substringBefore
(added.asSequence() + changed.asSequence()).map { ChangeInfo.MembersChanged(fqName, listOf(it.substringBefore("("))) }
}
else {
emptySequence<ChangeInfo>()
}
return CompilationResult(inlineChanged = changed.isNotEmpty(),
inlineAdded = added.isNotEmpty(),
changes = changes)
}
public fun remove(className: JvmClassName) {
storage.remove(className.internalName)
}
override fun dumpValue(value: Map<String, Long>): String =
value.dumpMap { java.lang.Long.toHexString(it) }
}
private inner class PackagePartMap(storageFile: File) : BasicStringMap<Boolean>(storageFile, BooleanDataDescriptor.INSTANCE) {
public fun addPackagePart(className: JvmClassName) {
fun addPackagePart(className: JvmClassName) {
storage[className.internalName] = true
}
public fun remove(className: JvmClassName) {
fun remove(className: JvmClassName) {
storage.remove(className.internalName)
}
public fun isPackagePart(className: JvmClassName): Boolean =
fun isPackagePart(className: JvmClassName): Boolean =
className.internalName in storage
override fun dumpValue(value: Boolean) = ""
}
private inner class MultifileClassFacadeMap(storageFile: File) : BasicStringMap<List<String>>(storageFile, StringListExternalizer) {
public fun add(facadeName: JvmClassName, partNames: List<String>) {
private inner class MultifileClassFacadeMap(storageFile: File) : BasicStringMap<Collection<String>>(storageFile, StringCollectionExternalizer) {
operator fun set(facadeName: JvmClassName, partNames: Collection<String>) {
storage[facadeName.internalName] = partNames
}
public fun getMultifileClassParts(facadeName: String): List<String>? = storage[facadeName]
operator fun get(facadeName: String): Collection<String>? = storage[facadeName]
public fun remove(className: JvmClassName) {
fun remove(className: JvmClassName) {
storage.remove(className.internalName)
}
override fun dumpValue(value: List<String>): String = value.toString()
override fun dumpValue(value: Collection<String>): String = value.dumpCollection()
}
private inner class MultifileClassPartMap(storageFile: File) : BasicStringMap<String>(storageFile, EnumeratorStringDescriptor.INSTANCE) {
public fun add(partName: String, facadeName: String) {
fun set(partName: String, facadeName: String) {
storage[partName] = facadeName
}
public fun getFacadeName(partName: String): String? {
fun get(partName: String): String? {
return storage.get(partName)
}
public fun remove(className: JvmClassName) {
fun remove(className: JvmClassName) {
storage.remove(className.internalName)
}
override fun dumpValue(value: String): String = value
}
private inner class SourceToClassesMap(storageFile: File) : BasicStringMap<List<String>>(storageFile, PathStringDescriptor.INSTANCE, StringListExternalizer) {
public fun clearOutputsForSource(sourceFile: File) {
inner class SourceToClassesMap(storageFile: File) : BasicStringMap<Collection<String>>(storageFile, PathStringDescriptor, StringCollectionExternalizer) {
fun clearOutputsForSource(sourceFile: File) {
remove(sourceFile.absolutePath)
}
public fun add(sourceFile: File, className: JvmClassName) {
storage.append(sourceFile.absolutePath, { out -> IOUtil.writeUTF(out, className.internalName) })
fun add(sourceFile: File, className: JvmClassName) {
storage.append(sourceFile.absolutePath, className.internalName)
}
public operator fun get(sourceFile: File): Collection<JvmClassName> =
operator fun get(sourceFile: File): Collection<JvmClassName> =
storage[sourceFile.absolutePath].orEmpty().map { JvmClassName.byInternalName(it) }
override fun dumpValue(value: List<String>) = value.toString()
override fun clean() {
storage.keys.forEach { remove(it) }
}
override fun dumpValue(value: Collection<String>) = value.dumpCollection()
private fun remove(path: String) {
storage.remove(path)
}
}
private fun addToClassStorage(kotlinClass: LocalFileKotlinClass) {
if (!IncrementalCompilation.isExperimental()) return
val classData = JvmProtoBufUtil.readClassDataFrom(kotlinClass.classHeader.data!!, kotlinClass.classHeader.strings!!)
val supertypes = classData.classProto.supertypes(TypeTable(classData.classProto.typeTable))
val parents = supertypes.map { classData.nameResolver.getClassId(it.className).asSingleFqName() }
.filter { it.asString() != "kotlin.Any" }
.toSet()
val child = kotlinClass.classId.asSingleFqName()
parents.forEach { subtypesMap.add(it, child) }
val removedSupertypes = supertypesMap[child].filter { it !in parents }
removedSupertypes.forEach { subtypesMap.removeValues(it, setOf(child)) }
supertypesMap[child] = parents
}
private fun removeAllFromClassStorage(removedClasses: Collection<JvmClassName>) {
if (!IncrementalCompilation.isExperimental() || removedClasses.isEmpty()) return
val removedFqNames = removedClasses.map { it.fqNameForClassNameWithoutDollars }.toSet()
for (cache in dependentsWithThis) {
val parentsFqNames = hashSetOf<FqName>()
val childrenFqNames = hashSetOf<FqName>()
for (removedFqName in removedFqNames) {
parentsFqNames.addAll(cache.supertypesMap[removedFqName])
childrenFqNames.addAll(cache.subtypesMap[removedFqName])
cache.supertypesMap.remove(removedFqName)
cache.subtypesMap.remove(removedFqName)
}
for (child in childrenFqNames) {
cache.supertypesMap.removeValues(child, removedFqNames)
}
for (parent in parentsFqNames) {
cache.subtypesMap.removeValues(parent, removedFqNames)
}
}
}
private inner class DirtyOutputClassesMap(storageFile: File) : BasicStringMap<Boolean>(storageFile, BooleanDataDescriptor.INSTANCE) {
public fun markDirty(className: String) {
fun markDirty(className: String) {
storage[className] = true
}
public fun notDirty(className: String) {
fun notDirty(className: String) {
storage.remove(className)
}
public fun getDirtyOutputClasses(): Collection<String> =
fun getDirtyOutputClasses(): Collection<String> =
storage.keys
public fun isDirty(className: String): Boolean =
fun isDirty(className: String): Boolean =
storage.contains(className)
override fun dumpValue(value: Boolean) = ""
}
private inner class DirtyInlineFunctionsMap(storageFile: File) : BasicStringMap<List<String>>(storageFile, StringListExternalizer) {
public fun getEntries(): Map<JvmClassName, List<String>> =
storage.keys.toMap(JvmClassName::byInternalName) { storage[it]!! }
public fun put(className: JvmClassName, changedFunctions: List<String>) {
storage[className.internalName] = changedFunctions
}
override fun dumpValue(value: List<String>) =
value.dumpCollection()
}
/**
* Mapping: (sourceFile+inlineFunction)->(targetFiles)
*
* Where:
* * sourceFile - path to some kotlin source
* * inlineFunction - jvmSignature of some inline function in source file
* * target files - collection of files inlineFunction has been inlined to
*/
private inner class InlineFunctionsFilesMap(storageFile: File) : BasicMap<PathFunctionPair, Collection<String>>(storageFile, PathFunctionPairKeyDescriptor, PathCollectionExternalizer) {
public fun add(sourcePath: String, jvmSignature: String, targetPath: String) {
val key = PathFunctionPair(sourcePath, jvmSignature)
storage.append(key) { out ->
IOUtil.writeUTF(out, targetPath)
}
}
public operator fun get(sourcePath: String, jvmSignature: String): Collection<String> {
val key = PathFunctionPair(sourcePath, jvmSignature)
return storage[key] ?: emptySet()
}
override fun dumpKey(key: PathFunctionPair): String =
"(${key.path}, ${key.function})"
override fun dumpValue(value: Collection<String>) =
value.dumpCollection()
}
}
sealed class ChangeInfo(val fqName: FqName) {
@@ -648,7 +586,7 @@ sealed class ChangeInfo(val fqName: FqName) {
class Removed(fqName: FqName, names: Collection<String>) : MembersChanged(fqName, names)
class SignatureChanged(fqName: FqName) : ChangeInfo(fqName)
class SignatureChanged(fqName: FqName, val areSubclassesAffected: Boolean) : ChangeInfo(fqName)
protected open fun toStringProperties(): String = "fqName = $fqName"
@@ -666,36 +604,18 @@ data class CompilationResult(
val changes: Sequence<ChangeInfo> = emptySequence()
) {
companion object {
public val NO_CHANGES: CompilationResult = CompilationResult()
val NO_CHANGES: CompilationResult = CompilationResult()
}
operator fun plus(other: CompilationResult): CompilationResult =
CompilationResult(protoChanged || other.protoChanged,
constantsChanged || other.constantsChanged,
inlineChanged || other.inlineChanged,
inlineAdded || other.inlineAdded,
changes + other.changes)
constantsChanged || other.constantsChanged,
inlineChanged || other.inlineChanged,
inlineAdded || other.inlineAdded,
changes + other.changes)
}
public fun BuildDataPaths.getKotlinCacheVersion(target: BuildTarget<*>): CacheFormatVersion = CacheFormatVersion(getTargetDataRoot(target))
private class KotlinIncrementalStorageProvider(
private val target: ModuleBuildTarget
) : StorageProvider<IncrementalCacheImpl>() {
override fun equals(other: Any?) = other is KotlinIncrementalStorageProvider && target == other.target
override fun hashCode() = target.hashCode()
override fun createStorage(targetDataDir: File): IncrementalCacheImpl =
IncrementalCacheImpl(targetDataDir, target)
}
public fun BuildDataManager.getKotlinCache(target: ModuleBuildTarget): IncrementalCacheImpl =
getStorage(target, KotlinIncrementalStorageProvider(target))
private fun ByteArray.md5(): Long {
fun ByteArray.md5(): Long {
val d = MessageDigest.getInstance("MD5").digest(this)!!
return ((d[0].toLong() and 0xFFL)
or ((d[1].toLong() and 0xFFL) shl 8)
@@ -709,11 +629,11 @@ private fun ByteArray.md5(): Long {
}
@TestOnly
private fun <K : Comparable<K>, V> Map<K, V>.dumpMap(dumpValue: (V)->String): String =
StringBuilder {
fun <K : Comparable<K>, V> Map<K, V>.dumpMap(dumpValue: (V)->String): String =
buildString {
append("{")
for (key in keySet().sorted()) {
if (length() != 1) {
for (key in keys.sorted()) {
if (length != 1) {
append(", ")
}
@@ -721,8 +641,7 @@ private fun <K : Comparable<K>, V> Map<K, V>.dumpMap(dumpValue: (V)->String): St
append("$key -> $value")
}
append("}")
}.toString()
}
@TestOnly
public fun <T : Comparable<T>> Collection<T>.dumpCollection(): String =
@TestOnly fun <T : Comparable<T>> Collection<T>.dumpCollection(): String =
"[${sorted().joinToString(", ", transform = Any::toString)}]"

View File

@@ -14,22 +14,19 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.jps.incremental
package org.jetbrains.kotlin.incremental
import org.jetbrains.jps.incremental.ModuleBuildTarget
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.load.kotlin.incremental.components.IncrementalCache
import org.jetbrains.kotlin.load.kotlin.incremental.components.IncrementalCompilationComponents
import org.jetbrains.kotlin.modules.TargetId
public class IncrementalCompilationComponentsImpl(
caches: Map<ModuleBuildTarget, IncrementalCache>,
class IncrementalCompilationComponentsImpl(
private val caches: Map<TargetId, IncrementalCache>,
private val lookupTracker: LookupTracker
): IncrementalCompilationComponents {
private val caches = caches.mapKeys { TargetId(it.key) }
override fun getIncrementalCache(target: TargetId): IncrementalCache =
caches[target]!!
caches[target] ?: throw Exception("Incremental cache for target ${target.name} not found")
override fun getLookupTracker(): LookupTracker = lookupTracker
}

View File

@@ -14,7 +14,7 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.jps.incremental
package org.jetbrains.kotlin.incremental
import org.jetbrains.kotlin.load.kotlin.FileBasedKotlinClass
import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader
@@ -40,7 +40,7 @@ class LocalFileKotlinClass private constructor(
}
}
public val className: JvmClassName by lazy { JvmClassName.byClassId(classId) }
val className: JvmClassName by lazy { JvmClassName.byClassId(classId) }
override fun getLocation(): String = file.absolutePath

View File

@@ -14,24 +14,20 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.jps.incremental
package org.jetbrains.kotlin.incremental
import com.intellij.util.containers.MultiMap
import org.jetbrains.annotations.TestOnly
import org.jetbrains.jps.builders.storage.StorageProvider
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.incremental.components.Position
import org.jetbrains.kotlin.incremental.components.ScopeKind
import org.jetbrains.kotlin.jps.incremental.storage.*
import org.jetbrains.kotlin.incremental.storage.*
import org.jetbrains.kotlin.utils.Printer
import java.io.File
import java.util.*
object LookupStorageProvider : StorageProvider<LookupStorage>() {
override fun createStorage(targetDataDir: File): LookupStorage = LookupStorage(targetDataDir)
}
class LookupStorage(private val targetDataDir: File) : BasicMapsOwner() {
open class LookupStorage(private val targetDataDir: File) : BasicMapsOwner() {
companion object {
private val DELETED_TO_SIZE_TRESHOLD = 0.5
private val MINIMUM_GARBAGE_COLLECTIBLE_SIZE = 10000
@@ -65,14 +61,14 @@ class LookupStorage(private val targetDataDir: File) : BasicMapsOwner() {
}
}
public fun add(lookupSymbol: LookupSymbol, containingPaths: Collection<String>) {
fun add(lookupSymbol: LookupSymbol, containingPaths: Collection<String>) {
val key = LookupSymbolKey(lookupSymbol.name, lookupSymbol.scope)
val fileIds = containingPaths.map { addFileIfNeeded(File(it)) }.toHashSet()
fileIds.addAll(lookupMap[key] ?: emptySet())
lookupMap[key] = fileIds
}
public fun removeLookupsFrom(file: File) {
fun removeLookupsFrom(file: File) {
val id = fileToId[file] ?: return
idToFile.remove(id)
fileToId.remove(file)
@@ -149,14 +145,12 @@ class LookupStorage(private val targetDataDir: File) : BasicMapsOwner() {
}
}
@TestOnly
public fun forceGC() {
@TestOnly fun forceGC() {
removeGarbageIfNeeded(force = true)
flush(false)
}
@TestOnly
public fun dump(lookupSymbols: Set<LookupSymbol>): String {
@TestOnly fun dump(lookupSymbols: Set<LookupSymbol>): String {
flush(false)
val sb = StringBuilder()

View File

@@ -14,7 +14,7 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.jps.incremental
package org.jetbrains.kotlin.incremental
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.serialization.ProtoBuf
@@ -25,12 +25,12 @@ import java.util.*
/** This file is generated by org.jetbrains.kotlin.generators.protobuf.GenerateProtoBufCompare. DO NOT MODIFY MANUALLY */
open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, public val newNameResolver: NameResolver) {
open class ProtoCompareGenerated(val oldNameResolver: NameResolver, val newNameResolver: NameResolver) {
private val strings = Interner<String>()
public val oldStringIndexesMap: MutableMap<Int, Int> = hashMapOf()
public val newStringIndexesMap: MutableMap<Int, Int> = hashMapOf()
public val oldClassIdIndexesMap: MutableMap<Int, Int> = hashMapOf()
public val newClassIdIndexesMap: MutableMap<Int, Int> = hashMapOf()
val oldStringIndexesMap: MutableMap<Int, Int> = hashMapOf()
val newStringIndexesMap: MutableMap<Int, Int> = hashMapOf()
val oldClassIdIndexesMap: MutableMap<Int, Int> = hashMapOf()
val newClassIdIndexesMap: MutableMap<Int, Int> = hashMapOf()
private val classIds = Interner<ClassId>()
@@ -44,15 +44,21 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi
if (!checkEquals(old.typeTable, new.typeTable)) return false
}
if (old.hasExtension(JvmProtoBuf.packageModuleName) != new.hasExtension(JvmProtoBuf.packageModuleName)) return false
if (old.hasExtension(JvmProtoBuf.packageModuleName)) {
if (!checkStringEquals(old.getExtension(JvmProtoBuf.packageModuleName), new.getExtension(JvmProtoBuf.packageModuleName))) return false
}
return true
}
public enum class ProtoBufPackageKind {
enum class ProtoBufPackageKind {
FUNCTION_LIST,
PROPERTY_LIST,
TYPE_TABLE
TYPE_TABLE,
PACKAGE_MODULE_NAME
}
public fun difference(old: ProtoBuf.Package, new: ProtoBuf.Package): EnumSet<ProtoBufPackageKind> {
fun difference(old: ProtoBuf.Package, new: ProtoBuf.Package): EnumSet<ProtoBufPackageKind> {
val result = EnumSet.noneOf(ProtoBufPackageKind::class.java)
if (!checkEqualsPackageFunction(old, new)) result.add(ProtoBufPackageKind.FUNCTION_LIST)
@@ -64,6 +70,11 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi
if (!checkEquals(old.typeTable, new.typeTable)) result.add(ProtoBufPackageKind.TYPE_TABLE)
}
if (old.hasExtension(JvmProtoBuf.packageModuleName) != new.hasExtension(JvmProtoBuf.packageModuleName)) result.add(ProtoBufPackageKind.PACKAGE_MODULE_NAME)
if (old.hasExtension(JvmProtoBuf.packageModuleName)) {
if (!checkStringEquals(old.getExtension(JvmProtoBuf.packageModuleName), new.getExtension(JvmProtoBuf.packageModuleName))) result.add(ProtoBufPackageKind.PACKAGE_MODULE_NAME)
}
return result
}
@@ -101,15 +112,14 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi
if (!checkEquals(old.typeTable, new.typeTable)) return false
}
if (old.getExtensionCount(JvmProtoBuf.classAnnotation) != new.getExtensionCount(JvmProtoBuf.classAnnotation)) return false
for(i in 0..old.getExtensionCount(JvmProtoBuf.classAnnotation) - 1) {
if (!checkEquals(old.getExtension(JvmProtoBuf.classAnnotation, i), new.getExtension(JvmProtoBuf.classAnnotation, i))) return false
if (old.hasExtension(JvmProtoBuf.classModuleName) != new.hasExtension(JvmProtoBuf.classModuleName)) return false
if (old.hasExtension(JvmProtoBuf.classModuleName)) {
if (!checkStringEquals(old.getExtension(JvmProtoBuf.classModuleName), new.getExtension(JvmProtoBuf.classModuleName))) return false
}
return true
}
public enum class ProtoBufClassKind {
enum class ProtoBufClassKind {
FLAGS,
FQ_NAME,
COMPANION_OBJECT_NAME,
@@ -122,10 +132,10 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi
PROPERTY_LIST,
ENUM_ENTRY_LIST,
TYPE_TABLE,
CLASS_ANNOTATION_LIST
CLASS_MODULE_NAME
}
public fun difference(old: ProtoBuf.Class, new: ProtoBuf.Class): EnumSet<ProtoBufClassKind> {
fun difference(old: ProtoBuf.Class, new: ProtoBuf.Class): EnumSet<ProtoBufClassKind> {
val result = EnumSet.noneOf(ProtoBufClassKind::class.java)
if (old.hasFlags() != new.hasFlags()) result.add(ProtoBufClassKind.FLAGS)
@@ -161,10 +171,9 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi
if (!checkEquals(old.typeTable, new.typeTable)) result.add(ProtoBufClassKind.TYPE_TABLE)
}
if (old.getExtensionCount(JvmProtoBuf.classAnnotation) != new.getExtensionCount(JvmProtoBuf.classAnnotation)) result.add(ProtoBufClassKind.CLASS_ANNOTATION_LIST)
for(i in 0..old.getExtensionCount(JvmProtoBuf.classAnnotation) - 1) {
if (!checkEquals(old.getExtension(JvmProtoBuf.classAnnotation, i), new.getExtension(JvmProtoBuf.classAnnotation, i))) result.add(ProtoBufClassKind.CLASS_ANNOTATION_LIST)
if (old.hasExtension(JvmProtoBuf.classModuleName) != new.hasExtension(JvmProtoBuf.classModuleName)) result.add(ProtoBufClassKind.CLASS_MODULE_NAME)
if (old.hasExtension(JvmProtoBuf.classModuleName)) {
if (!checkStringEquals(old.getExtension(JvmProtoBuf.classModuleName), new.getExtension(JvmProtoBuf.classModuleName))) result.add(ProtoBufClassKind.CLASS_MODULE_NAME)
}
return result
@@ -176,6 +185,11 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi
if (old.flags != new.flags) return false
}
if (old.hasOldFlags() != new.hasOldFlags()) return false
if (old.hasOldFlags()) {
if (old.oldFlags != new.oldFlags) return false
}
if (!checkStringEquals(old.name, new.name)) return false
if (old.hasReturnType() != new.hasReturnType()) return false
@@ -212,11 +226,6 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi
if (!checkEquals(old.getExtension(JvmProtoBuf.methodSignature), new.getExtension(JvmProtoBuf.methodSignature))) return false
}
if (old.hasExtension(JvmProtoBuf.methodImplClassName) != new.hasExtension(JvmProtoBuf.methodImplClassName)) return false
if (old.hasExtension(JvmProtoBuf.methodImplClassName)) {
if (!checkStringEquals(old.getExtension(JvmProtoBuf.methodImplClassName), new.getExtension(JvmProtoBuf.methodImplClassName))) return false
}
return true
}
@@ -226,6 +235,11 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi
if (old.flags != new.flags) return false
}
if (old.hasOldFlags() != new.hasOldFlags()) return false
if (old.hasOldFlags()) {
if (old.oldFlags != new.oldFlags) return false
}
if (!checkStringEquals(old.name, new.name)) return false
if (old.hasReturnType() != new.hasReturnType()) return false
@@ -270,11 +284,6 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi
if (!checkEquals(old.getExtension(JvmProtoBuf.propertySignature), new.getExtension(JvmProtoBuf.propertySignature))) return false
}
if (old.hasExtension(JvmProtoBuf.propertyImplClassName) != new.hasExtension(JvmProtoBuf.propertyImplClassName)) return false
if (old.hasExtension(JvmProtoBuf.propertyImplClassName)) {
if (!checkStringEquals(old.getExtension(JvmProtoBuf.propertyImplClassName), new.getExtension(JvmProtoBuf.propertyImplClassName))) return false
}
return true
}
@@ -395,10 +404,11 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi
return true
}
open fun checkEquals(old: ProtoBuf.Annotation, new: ProtoBuf.Annotation): Boolean {
if (!checkClassIdEquals(old.id, new.id)) return false
if (!checkEqualsAnnotationArgument(old, new)) return false
open fun checkEquals(old: ProtoBuf.EnumEntry, new: ProtoBuf.EnumEntry): Boolean {
if (old.hasName() != new.hasName()) return false
if (old.hasName()) {
if (!checkStringEquals(old.name, new.name)) return false
}
return true
}
@@ -431,11 +441,6 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi
if (old.varargElementTypeId != new.varargElementTypeId) return false
}
if (old.hasExtension(JvmProtoBuf.index) != new.hasExtension(JvmProtoBuf.index)) return false
if (old.hasExtension(JvmProtoBuf.index)) {
if (old.getExtension(JvmProtoBuf.index) != new.getExtension(JvmProtoBuf.index)) return false
}
return true
}
@@ -477,6 +482,14 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi
return true
}
open fun checkEquals(old: ProtoBuf.Annotation, new: ProtoBuf.Annotation): Boolean {
if (!checkClassIdEquals(old.id, new.id)) return false
if (!checkEqualsAnnotationArgument(old, new)) return false
return true
}
open fun checkEquals(old: ProtoBuf.Type.Argument, new: ProtoBuf.Type.Argument): Boolean {
if (old.hasProjection() != new.hasProjection()) return false
if (old.hasProjection()) {
@@ -496,14 +509,6 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi
return true
}
open fun checkEquals(old: ProtoBuf.Annotation.Argument, new: ProtoBuf.Annotation.Argument): Boolean {
if (!checkStringEquals(old.nameId, new.nameId)) return false
if (!checkEquals(old.value, new.value)) return false
return true
}
open fun checkEquals(old: JvmProtoBuf.JvmFieldSignature, new: JvmProtoBuf.JvmFieldSignature): Boolean {
if (old.hasName() != new.hasName()) return false
if (old.hasName()) {
@@ -515,10 +520,13 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi
if (!checkStringEquals(old.desc, new.desc)) return false
}
if (old.hasIsStaticInOuter() != new.hasIsStaticInOuter()) return false
if (old.hasIsStaticInOuter()) {
if (old.isStaticInOuter != new.isStaticInOuter) return false
}
return true
}
open fun checkEquals(old: ProtoBuf.Annotation.Argument, new: ProtoBuf.Annotation.Argument): Boolean {
if (!checkStringEquals(old.nameId, new.nameId)) return false
if (!checkEquals(old.value, new.value)) return false
return true
}
@@ -663,7 +671,7 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi
if (old.enumEntryCount != new.enumEntryCount) return false
for(i in 0..old.enumEntryCount - 1) {
if (!checkStringEquals(old.getEnumEntry(i), new.getEnumEntry(i))) return false
if (!checkEquals(old.getEnumEntry(i), new.getEnumEntry(i))) return false
}
return true
@@ -769,10 +777,10 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi
return true
}
public fun oldGetIndexOfString(index: Int): Int = getIndexOfString(index, oldStringIndexesMap, oldNameResolver)
public fun newGetIndexOfString(index: Int): Int = getIndexOfString(index, newStringIndexesMap, newNameResolver)
fun oldGetIndexOfString(index: Int): Int = getIndexOfString(index, oldStringIndexesMap, oldNameResolver)
fun newGetIndexOfString(index: Int): Int = getIndexOfString(index, newStringIndexesMap, newNameResolver)
public fun getIndexOfString(index: Int, map: MutableMap<Int, Int>, nameResolver: NameResolver): Int {
fun getIndexOfString(index: Int, map: MutableMap<Int, Int>, nameResolver: NameResolver): Int {
map[index]?.let { return it }
val result = strings.intern(nameResolver.getString(index))
@@ -780,10 +788,10 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi
return result
}
public fun oldGetIndexOfClassId(index: Int): Int = getIndexOfClassId(index, oldClassIdIndexesMap, oldNameResolver)
public fun newGetIndexOfClassId(index: Int): Int = getIndexOfClassId(index, newClassIdIndexesMap, newNameResolver)
fun oldGetIndexOfClassId(index: Int): Int = getIndexOfClassId(index, oldClassIdIndexesMap, oldNameResolver)
fun newGetIndexOfClassId(index: Int): Int = getIndexOfClassId(index, newClassIdIndexesMap, newNameResolver)
public fun getIndexOfClassId(index: Int, map: MutableMap<Int, Int>, nameResolver: NameResolver): Int {
fun getIndexOfClassId(index: Int, map: MutableMap<Int, Int>, nameResolver: NameResolver): Int {
map[index]?.let { return it }
val result = classIds.intern(nameResolver.getClassId(index))
@@ -800,7 +808,7 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi
}
}
public fun ProtoBuf.Package.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
fun ProtoBuf.Package.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
var hashCode = 1
for(i in 0..functionCount - 1) {
@@ -815,10 +823,14 @@ public fun ProtoBuf.Package.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes:
hashCode = 31 * hashCode + typeTable.hashCode(stringIndexes, fqNameIndexes)
}
if (hasExtension(JvmProtoBuf.packageModuleName)) {
hashCode = 31 * hashCode + stringIndexes(getExtension(JvmProtoBuf.packageModuleName))
}
return hashCode
}
public fun ProtoBuf.Class.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
fun ProtoBuf.Class.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
var hashCode = 1
if (hasFlags()) {
@@ -860,27 +872,31 @@ public fun ProtoBuf.Class.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (
}
for(i in 0..enumEntryCount - 1) {
hashCode = 31 * hashCode + stringIndexes(getEnumEntry(i))
hashCode = 31 * hashCode + getEnumEntry(i).hashCode(stringIndexes, fqNameIndexes)
}
if (hasTypeTable()) {
hashCode = 31 * hashCode + typeTable.hashCode(stringIndexes, fqNameIndexes)
}
for(i in 0..getExtensionCount(JvmProtoBuf.classAnnotation) - 1) {
hashCode = 31 * hashCode + getExtension(JvmProtoBuf.classAnnotation, i).hashCode(stringIndexes, fqNameIndexes)
if (hasExtension(JvmProtoBuf.classModuleName)) {
hashCode = 31 * hashCode + stringIndexes(getExtension(JvmProtoBuf.classModuleName))
}
return hashCode
}
public fun ProtoBuf.Function.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
fun ProtoBuf.Function.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
var hashCode = 1
if (hasFlags()) {
hashCode = 31 * hashCode + flags
}
if (hasOldFlags()) {
hashCode = 31 * hashCode + oldFlags
}
hashCode = 31 * hashCode + stringIndexes(name)
if (hasReturnType()) {
@@ -915,20 +931,20 @@ public fun ProtoBuf.Function.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes
hashCode = 31 * hashCode + getExtension(JvmProtoBuf.methodSignature).hashCode(stringIndexes, fqNameIndexes)
}
if (hasExtension(JvmProtoBuf.methodImplClassName)) {
hashCode = 31 * hashCode + stringIndexes(getExtension(JvmProtoBuf.methodImplClassName))
}
return hashCode
}
public fun ProtoBuf.Property.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
fun ProtoBuf.Property.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
var hashCode = 1
if (hasFlags()) {
hashCode = 31 * hashCode + flags
}
if (hasOldFlags()) {
hashCode = 31 * hashCode + oldFlags
}
hashCode = 31 * hashCode + stringIndexes(name)
if (hasReturnType()) {
@@ -967,14 +983,10 @@ public fun ProtoBuf.Property.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes
hashCode = 31 * hashCode + getExtension(JvmProtoBuf.propertySignature).hashCode(stringIndexes, fqNameIndexes)
}
if (hasExtension(JvmProtoBuf.propertyImplClassName)) {
hashCode = 31 * hashCode + stringIndexes(getExtension(JvmProtoBuf.propertyImplClassName))
}
return hashCode
}
public fun ProtoBuf.TypeTable.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
fun ProtoBuf.TypeTable.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
var hashCode = 1
for(i in 0..typeCount - 1) {
@@ -988,7 +1000,7 @@ public fun ProtoBuf.TypeTable.hashCode(stringIndexes: (Int) -> Int, fqNameIndexe
return hashCode
}
public fun ProtoBuf.TypeParameter.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
fun ProtoBuf.TypeParameter.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
var hashCode = 1
hashCode = 31 * hashCode + id
@@ -1018,7 +1030,7 @@ public fun ProtoBuf.TypeParameter.hashCode(stringIndexes: (Int) -> Int, fqNameIn
return hashCode
}
public fun ProtoBuf.Type.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
fun ProtoBuf.Type.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
var hashCode = 1
for(i in 0..argumentCount - 1) {
@@ -1072,7 +1084,7 @@ public fun ProtoBuf.Type.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (I
return hashCode
}
public fun ProtoBuf.Constructor.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
fun ProtoBuf.Constructor.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
var hashCode = 1
if (hasFlags()) {
@@ -1090,19 +1102,17 @@ public fun ProtoBuf.Constructor.hashCode(stringIndexes: (Int) -> Int, fqNameInde
return hashCode
}
public fun ProtoBuf.Annotation.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
fun ProtoBuf.EnumEntry.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
var hashCode = 1
hashCode = 31 * hashCode + fqNameIndexes(id)
for(i in 0..argumentCount - 1) {
hashCode = 31 * hashCode + getArgument(i).hashCode(stringIndexes, fqNameIndexes)
if (hasName()) {
hashCode = 31 * hashCode + stringIndexes(name)
}
return hashCode
}
public fun ProtoBuf.ValueParameter.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
fun ProtoBuf.ValueParameter.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
var hashCode = 1
if (hasFlags()) {
@@ -1127,14 +1137,10 @@ public fun ProtoBuf.ValueParameter.hashCode(stringIndexes: (Int) -> Int, fqNameI
hashCode = 31 * hashCode + varargElementTypeId
}
if (hasExtension(JvmProtoBuf.index)) {
hashCode = 31 * hashCode + getExtension(JvmProtoBuf.index)
}
return hashCode
}
public fun JvmProtoBuf.JvmMethodSignature.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
fun JvmProtoBuf.JvmMethodSignature.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
var hashCode = 1
if (hasName()) {
@@ -1148,7 +1154,7 @@ public fun JvmProtoBuf.JvmMethodSignature.hashCode(stringIndexes: (Int) -> Int,
return hashCode
}
public fun JvmProtoBuf.JvmPropertySignature.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
fun JvmProtoBuf.JvmPropertySignature.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
var hashCode = 1
if (hasField()) {
@@ -1170,7 +1176,19 @@ public fun JvmProtoBuf.JvmPropertySignature.hashCode(stringIndexes: (Int) -> Int
return hashCode
}
public fun ProtoBuf.Type.Argument.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
fun ProtoBuf.Annotation.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
var hashCode = 1
hashCode = 31 * hashCode + fqNameIndexes(id)
for(i in 0..argumentCount - 1) {
hashCode = 31 * hashCode + getArgument(i).hashCode(stringIndexes, fqNameIndexes)
}
return hashCode
}
fun ProtoBuf.Type.Argument.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
var hashCode = 1
if (hasProjection()) {
@@ -1188,17 +1206,7 @@ public fun ProtoBuf.Type.Argument.hashCode(stringIndexes: (Int) -> Int, fqNameIn
return hashCode
}
public fun ProtoBuf.Annotation.Argument.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
var hashCode = 1
hashCode = 31 * hashCode + stringIndexes(nameId)
hashCode = 31 * hashCode + value.hashCode(stringIndexes, fqNameIndexes)
return hashCode
}
public fun JvmProtoBuf.JvmFieldSignature.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
fun JvmProtoBuf.JvmFieldSignature.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
var hashCode = 1
if (hasName()) {
@@ -1209,14 +1217,20 @@ public fun JvmProtoBuf.JvmFieldSignature.hashCode(stringIndexes: (Int) -> Int, f
hashCode = 31 * hashCode + stringIndexes(desc)
}
if (hasIsStaticInOuter()) {
hashCode = 31 * hashCode + isStaticInOuter.hashCode()
}
return hashCode
}
fun ProtoBuf.Annotation.Argument.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
var hashCode = 1
hashCode = 31 * hashCode + stringIndexes(nameId)
hashCode = 31 * hashCode + value.hashCode(stringIndexes, fqNameIndexes)
return hashCode
}
public fun ProtoBuf.Annotation.Argument.Value.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
fun ProtoBuf.Annotation.Argument.Value.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int {
var hashCode = 1
if (hasType()) {

View File

@@ -14,13 +14,13 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.jps.incremental
package org.jetbrains.kotlin.incremental
import com.google.protobuf.MessageLite
import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.jps.incremental.ProtoCompareGenerated.ProtoBufClassKind
import org.jetbrains.kotlin.jps.incremental.ProtoCompareGenerated.ProtoBufPackageKind
import org.jetbrains.kotlin.jps.incremental.storage.ProtoMapValue
import org.jetbrains.kotlin.incremental.ProtoCompareGenerated.ProtoBufClassKind
import org.jetbrains.kotlin.incremental.ProtoCompareGenerated.ProtoBufPackageKind
import org.jetbrains.kotlin.incremental.storage.ProtoMapValue
import org.jetbrains.kotlin.serialization.Flags
import org.jetbrains.kotlin.serialization.ProtoBuf
import org.jetbrains.kotlin.serialization.deserialization.Deserialization
@@ -29,17 +29,24 @@ import org.jetbrains.kotlin.serialization.jvm.JvmProtoBufUtil
import org.jetbrains.kotlin.utils.HashSetUtil
import java.util.*
public sealed class DifferenceKind() {
public object NONE: DifferenceKind()
public object CLASS_SIGNATURE: DifferenceKind()
public class MEMBERS(val names: Collection<String>): DifferenceKind()
}
data class Difference(
val isClassAffected: Boolean = false,
val areSubclassesAffected: Boolean = false,
val changedMembersNames: Set<String> = emptySet()
)
public fun difference(oldData: ProtoMapValue, newData: ProtoMapValue): DifferenceKind {
if (oldData.isPackageFacade != newData.isPackageFacade) return DifferenceKind.CLASS_SIGNATURE
fun difference(oldData: ProtoMapValue, newData: ProtoMapValue): Difference {
if (!oldData.isPackageFacade && newData.isPackageFacade) return Difference(isClassAffected = true, areSubclassesAffected = true)
if (oldData.isPackageFacade && !newData.isPackageFacade) return Difference(isClassAffected = true)
val differenceObject =
if (oldData.isPackageFacade) DifferenceCalculatorForPackageFacade(oldData, newData) else DifferenceCalculatorForClass(oldData, newData)
if (oldData.isPackageFacade) {
DifferenceCalculatorForPackageFacade(oldData, newData)
}
else {
DifferenceCalculatorForClass(oldData, newData)
}
return differenceObject.difference()
}
@@ -70,9 +77,7 @@ private abstract class DifferenceCalculator() {
protected val compareObject by lazy { ProtoCompareGenerated(oldNameResolver, newNameResolver) }
abstract fun difference(): DifferenceKind
protected fun membersOrNone(names: Collection<String>): DifferenceKind = if (names.isEmpty()) DifferenceKind.NONE else DifferenceKind.MEMBERS(names)
abstract fun difference(): Difference
protected fun calcDifferenceForMembers(oldList: List<MessageLite>, newList: List<MessageLite>): Collection<String> {
val result = hashSetOf<String>()
@@ -82,7 +87,7 @@ private abstract class DifferenceCalculator() {
val newMap =
newList.groupBy { it.getHashCode({ compareObject.newGetIndexOfString(it) }, { compareObject.newGetIndexOfClassId(it) }) }
val hashes = oldMap.keySet() + newMap.keySet()
val hashes = oldMap.keys + newMap.keys
for (hash in hashes) {
val oldMembers = oldMap[hash]
val newMembers = newMap[hash]
@@ -156,8 +161,7 @@ private class DifferenceCalculatorForClass(oldData: ProtoMapValue, newData: Prot
ProtoBufClassKind.FLAGS,
ProtoBufClassKind.FQ_NAME,
ProtoBufClassKind.TYPE_PARAMETER_LIST,
ProtoBufClassKind.SUPERTYPE_LIST,
ProtoBufClassKind.CLASS_ANNOTATION_LIST
ProtoBufClassKind.SUPERTYPE_LIST
)
}
@@ -172,16 +176,11 @@ private class DifferenceCalculatorForClass(oldData: ProtoMapValue, newData: Prot
val diff = compareObject.difference(oldProto, newProto)
override fun difference(): DifferenceKind {
if (diff.isEmpty()) return DifferenceKind.NONE
CLASS_SIGNATURE_ENUMS.forEach { if (it in diff) return DifferenceKind.CLASS_SIGNATURE }
return membersOrNone(getChangedMembersNames())
}
private fun getChangedMembersNames(): Set<String> {
override fun difference(): Difference {
var isClassAffected = false
var areSubclassesAffected = false
val names = hashSetOf<String>()
val classIsSealed = newProto.isSealed && oldProto.isSealed
fun Int.oldToNames() = names.add(oldNameResolver.getString(this))
fun Int.newToNames() = names.add(newNameResolver.getString(this))
@@ -198,30 +197,41 @@ private class DifferenceCalculatorForClass(oldData: ProtoMapValue, newData: Prot
if (oldProto.hasCompanionObjectName()) oldProto.companionObjectName.oldToNames()
if (newProto.hasCompanionObjectName()) newProto.companionObjectName.newToNames()
}
ProtoBufClassKind.NESTED_CLASS_NAME_LIST ->
ProtoBufClassKind.NESTED_CLASS_NAME_LIST -> {
if (classIsSealed) {
// when class is sealed, adding an implementation can break exhaustive when expressions
// the workaround is to recompile all class usages
isClassAffected = true
}
names.addAll(calcDifferenceForNames(oldProto.nestedClassNameList, newProto.nestedClassNameList))
ProtoBufClassKind.CONSTRUCTOR_LIST ->
names.addAll(calcDifferenceForNonPrivateMembers(ProtoBuf.Class::getConstructorList))
}
ProtoBufClassKind.CONSTRUCTOR_LIST -> {
val differentNonPrivateConstructors = calcDifferenceForNonPrivateMembers(ProtoBuf.Class::getConstructorList)
if (differentNonPrivateConstructors.isNotEmpty()) {
isClassAffected = true
}
}
ProtoBufClassKind.FUNCTION_LIST ->
names.addAll(calcDifferenceForNonPrivateMembers(ProtoBuf.Class::getFunctionList))
ProtoBufClassKind.PROPERTY_LIST ->
names.addAll(calcDifferenceForNonPrivateMembers(ProtoBuf.Class::getPropertyList))
ProtoBufClassKind.ENUM_ENTRY_LIST ->
names.addAll(calcDifferenceForNames(oldProto.enumEntryList, newProto.enumEntryList))
ProtoBufClassKind.ENUM_ENTRY_LIST -> {
isClassAffected = true
}
ProtoBufClassKind.TYPE_TABLE -> {
// TODO
}
ProtoBufClassKind.FLAGS,
ProtoBufClassKind.FQ_NAME,
ProtoBufClassKind.TYPE_PARAMETER_LIST,
ProtoBufClassKind.SUPERTYPE_LIST,
ProtoBufClassKind.CLASS_ANNOTATION_LIST ->
throw IllegalArgumentException("Unexpected kind: $kind")
else ->
throw IllegalArgumentException("Unsupported kind: $kind")
in CLASS_SIGNATURE_ENUMS -> {
isClassAffected = true
areSubclassesAffected = true
}
else -> throw IllegalArgumentException("Unsupported kind: $kind")
}
}
return names
return Difference(isClassAffected, areSubclassesAffected, names)
}
}
@@ -237,13 +247,7 @@ private class DifferenceCalculatorForPackageFacade(oldData: ProtoMapValue, newDa
val diff = compareObject.difference(oldProto, newProto)
override fun difference(): DifferenceKind {
if (diff.isEmpty()) return DifferenceKind.NONE
return membersOrNone(getChangedMembersNames())
}
private fun getChangedMembersNames(): Set<String> {
override fun difference(): Difference {
val names = hashSetOf<String>()
fun calcDifferenceForNonPrivateMembers(members: (ProtoBuf.Package) -> List<MessageLite>): Collection<String> {
@@ -261,11 +265,13 @@ private class DifferenceCalculatorForPackageFacade(oldData: ProtoMapValue, newDa
ProtoBufPackageKind.TYPE_TABLE -> {
// TODO
}
else ->
throw IllegalArgumentException("Unsupported kind: $kind")
else -> throw IllegalArgumentException("Unsupported kind: $kind")
}
}
return names
return Difference(changedMembersNames = names)
}
}
private val ProtoBuf.Class.isSealed: Boolean
get() = ProtoBuf.Modality.SEALED == Flags.MODALITY.get(flags)

View File

@@ -14,7 +14,7 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.jps.incremental.storage
package org.jetbrains.kotlin.incremental.storage
import com.intellij.util.io.DataExternalizer
import com.intellij.util.io.EnumeratorStringDescriptor
@@ -23,14 +23,14 @@ import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.utils.Printer
import java.io.File
internal abstract class BasicMap<K : Comparable<K>, V>(
abstract class BasicMap<K : Comparable<K>, V>(
storageFile: File,
keyDescriptor: KeyDescriptor<K>,
valueExternalizer: DataExternalizer<V>
) {
protected val storage = LazyStorage(storageFile, keyDescriptor, valueExternalizer)
open fun clean() {
fun clean() {
storage.clean()
}
@@ -60,19 +60,22 @@ internal abstract class BasicMap<K : Comparable<K>, V>(
}.toString()
}
@TestOnly
protected abstract fun dumpKey(key: K): String
@TestOnly
protected abstract fun dumpValue(value: V): String
}
internal abstract class BasicStringMap<V>(
abstract class BasicStringMap<V>(
storageFile: File,
keyDescriptor: KeyDescriptor<String>,
valueExternalizer: DataExternalizer<V>
) : BasicMap<String, V>(storageFile, keyDescriptor, valueExternalizer) {
public constructor(
constructor(
storageFile: File,
valueExternalizer: DataExternalizer<V>
) : this(storageFile, EnumeratorStringDescriptor.INSTANCE, valueExternalizer)
override fun dumpKey(key: String): String = key
}
}

View File

@@ -14,12 +14,11 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.jps.incremental.storage
package org.jetbrains.kotlin.incremental.storage
import org.jetbrains.annotations.TestOnly
import org.jetbrains.jps.incremental.storage.StorageOwner
open class BasicMapsOwner : StorageOwner {
open class BasicMapsOwner {
private val maps = arrayListOf<BasicMap<*, *>>()
companion object {
@@ -31,18 +30,17 @@ open class BasicMapsOwner : StorageOwner {
return map
}
override fun clean() {
open fun clean() {
maps.forEach { it.clean() }
}
override fun close() {
open fun close() {
maps.forEach { it.close() }
}
override fun flush(memoryCachesOnly: Boolean) {
open fun flush(memoryCachesOnly: Boolean) {
maps.forEach { it.flush(memoryCachesOnly) }
}
@TestOnly
public fun dump(): String = maps.map { it.dump() }.joinToString("\n\n")
@TestOnly fun dump(): String = maps.map { it.dump() }.joinToString("\n\n")
}

View File

@@ -0,0 +1,55 @@
/*
* 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.incremental.storage
import org.jetbrains.kotlin.incremental.dumpCollection
import org.jetbrains.kotlin.name.FqName
import java.io.File
internal open class ClassOneToManyMap(
storageFile: File
) : BasicStringMap<Collection<String>>(storageFile, StringCollectionExternalizer) {
override fun dumpValue(value: Collection<String>): String = value.dumpCollection()
fun add(key: FqName, value: FqName) {
storage.append(key.asString(), value.asString())
}
operator fun get(key: FqName): Collection<FqName> =
storage[key.asString()]?.map(::FqName) ?: setOf()
operator fun set(key: FqName, values: Collection<FqName>) {
if (values.isEmpty()) {
remove(key)
return
}
storage[key.asString()] = values.map(FqName::asString)
}
fun remove(key: FqName) {
storage.remove(key.asString())
}
fun removeValues(key: FqName, removed: Set<FqName>) {
val notRemoved = this[key].filter { it !in removed }
this[key] = notRemoved
}
}
internal class SubtypesMap(storageFile: File) : ClassOneToManyMap(storageFile)
internal class SupertypesMap(storageFile: File) : ClassOneToManyMap(storageFile)

View File

@@ -14,7 +14,7 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.jps.incremental.storage
package org.jetbrains.kotlin.incremental.storage
import org.jetbrains.kotlin.utils.keysToMap
import java.io.File
@@ -24,15 +24,15 @@ internal class FileToIdMap(file: File) : BasicMap<File, Int>(file, FileKeyDescri
override fun dumpValue(value: Int): String = value.toString()
public operator fun get(file: File): Int? = storage[file]
operator fun get(file: File): Int? = storage[file]
public operator fun set(file: File, id: Int) {
operator fun set(file: File, id: Int) {
storage[file] = id
}
public fun remove(file: File) {
fun remove(file: File) {
storage.remove(file)
}
public fun toMap(): Map<File, Int> = storage.keys.keysToMap { storage[it]!! }
fun toMap(): Map<File, Int> = storage.keys.keysToMap { storage[it]!! }
}

View File

@@ -14,7 +14,7 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.jps.incremental.storage
package org.jetbrains.kotlin.incremental.storage
import com.intellij.util.io.ExternalIntegerKeyDescriptor
import java.io.File
@@ -24,15 +24,15 @@ internal class IdToFileMap(file: File) : BasicMap<Int, File>(file, ExternalInteg
override fun dumpValue(value: File): String = value.toString()
public operator fun get(id: Int): File? = storage[id]
operator fun get(id: Int): File? = storage[id]
public operator fun contains(id: Int): Boolean = id in storage
operator fun contains(id: Int): Boolean = id in storage
public operator fun set(id: Int, file: File) {
operator fun set(id: Int, file: File) {
storage[id] = file
}
public fun remove(id: Int) {
fun remove(id: Int) {
storage.remove(id)
}
}

View File

@@ -14,9 +14,10 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.jps.incremental.storage
package org.jetbrains.kotlin.incremental.storage
import com.intellij.util.io.DataExternalizer
import com.intellij.util.io.IOUtil
import com.intellij.util.io.KeyDescriptor
import com.intellij.util.io.PersistentHashMap
import java.io.DataOutput
@@ -27,7 +28,7 @@ import java.io.IOException
/**
* It's lazy in a sense that PersistentHashMap is created only on write
*/
internal class LazyStorage<K, V>(
class LazyStorage<K, V>(
private val storageFile: File,
private val keyDescriptor: KeyDescriptor<K>,
private val valueExternalizer: DataExternalizer<V>
@@ -73,8 +74,12 @@ internal class LazyStorage<K, V>(
getStorageIfExists()?.remove(key)
}
fun append(key: K, append: (DataOutput)->Unit) {
getStorageOrCreateNew().appendData(key, append)
fun append(key: K, value: String) {
append(key) { out -> IOUtil.writeUTF(out, value) }
}
fun append(key: K, value: Int) {
append(key) { out -> out.writeInt(value) }
}
@Synchronized
@@ -110,4 +115,8 @@ internal class LazyStorage<K, V>(
private fun createMap(): PersistentHashMap<K, V> =
PersistentHashMap(storageFile, keyDescriptor, valueExternalizer)
private fun append(key: K, append: (DataOutput)->Unit) {
getStorageOrCreateNew().appendData(key, append)
}
}

View File

@@ -14,29 +14,29 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.jps.incremental.storage
package org.jetbrains.kotlin.incremental.storage
import java.io.File
internal class LookupMap(storage: File) : BasicMap<LookupSymbolKey, Set<Int>>(storage, LookupSymbolKeyDescriptor, IntSetExternalizer) {
internal class LookupMap(storage: File) : BasicMap<LookupSymbolKey, Collection<Int>>(storage, LookupSymbolKeyDescriptor, IntCollectionExternalizer) {
override fun dumpKey(key: LookupSymbolKey): String = key.toString()
override fun dumpValue(value: Set<Int>): String = value.toString()
override fun dumpValue(value: Collection<Int>): String = value.toString()
public fun add(name: String, scope: String, fileId: Int) {
storage.append(LookupSymbolKey(name, scope)) { out -> out.writeInt(fileId) }
fun add(name: String, scope: String, fileId: Int) {
storage.append(LookupSymbolKey(name, scope), fileId)
}
public operator fun get(key: LookupSymbolKey): Set<Int>? = storage[key]
operator fun get(key: LookupSymbolKey): Collection<Int>? = storage[key]
public operator fun set(key: LookupSymbolKey, fileIds: Set<Int>) {
operator fun set(key: LookupSymbolKey, fileIds: Set<Int>) {
storage[key] = fileIds
}
public fun remove(key: LookupSymbolKey) {
fun remove(key: LookupSymbolKey) {
storage.remove(key)
}
public val keys: Collection<LookupSymbolKey>
val keys: Collection<LookupSymbolKey>
get() = storage.keys
}

View File

@@ -14,15 +14,13 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.jps.incremental.storage
package org.jetbrains.kotlin.incremental.storage
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.io.DataExternalizer
import com.intellij.util.io.EnumeratorStringDescriptor
import com.intellij.util.io.IOUtil
import com.intellij.util.io.KeyDescriptor
import gnu.trove.THashSet
import gnu.trove.TIntHashSet
import gnu.trove.decorator.TIntHashSetDecorator
import java.io.DataInput
import java.io.DataInputStream
import java.io.DataOutput
@@ -47,31 +45,12 @@ object LookupSymbolKeyDescriptor : KeyDescriptor<LookupSymbolKey> {
override fun isEqual(val1: LookupSymbolKey, val2: LookupSymbolKey): Boolean = val1 == val2
}
object PathFunctionPairKeyDescriptor : KeyDescriptor<PathFunctionPair> {
override fun read(input: DataInput): PathFunctionPair {
val path = IOUtil.readUTF(input)
val function = IOUtil.readUTF(input)
return PathFunctionPair(path, function)
}
override fun save(output: DataOutput, value: PathFunctionPair) {
IOUtil.writeUTF(output, value.path)
IOUtil.writeUTF(output, value.function)
}
override fun getHashCode(value: PathFunctionPair): Int = value.hashCode()
override fun isEqual(val1: PathFunctionPair, val2: PathFunctionPair): Boolean = val1 == val2
}
object ProtoMapValueExternalizer : DataExternalizer<ProtoMapValue> {
override fun save(output: DataOutput, value: ProtoMapValue) {
output.writeBoolean(value.isPackageFacade)
output.writeInt(value.bytes.size())
output.writeInt(value.bytes.size)
output.write(value.bytes)
output.writeInt(value.strings.size())
output.writeInt(value.strings.size)
for (string in value.strings) {
output.writeUTF(string)
@@ -92,9 +71,9 @@ object ProtoMapValueExternalizer : DataExternalizer<ProtoMapValue> {
abstract class StringMapExternalizer<T> : DataExternalizer<Map<String, T>> {
override fun save(output: DataOutput, map: Map<String, T>?) {
output.writeInt(map!!.size())
output.writeInt(map!!.size)
for ((key, value) in map.entrySet()) {
for ((key, value) in map.entries) {
IOUtil.writeString(key, output)
writeValue(output, value)
}
@@ -125,69 +104,31 @@ object StringToLongMapExternalizer : StringMapExternalizer<Long>() {
}
}
object StringListExternalizer : DataExternalizer<List<String>> {
override fun save(output: DataOutput, value: List<String>) {
value.forEach { IOUtil.writeUTF(output, it) }
}
override fun read(input: DataInput): List<String> {
val result = ArrayList<String>()
while ((input as DataInputStream).available() > 0) {
result.add(IOUtil.readUTF(input))
}
return result
}
}
object PathCollectionExternalizer : DataExternalizer<Collection<String>> {
override fun save(output: DataOutput, value: Collection<String>) {
for (str in value) {
IOUtil.writeUTF(output, str)
}
}
override fun read(input: DataInput): Collection<String> {
val result = THashSet(FileUtil.PATH_HASHING_STRATEGY)
val stream = input as DataInputStream
while (stream.available() > 0) {
val str = IOUtil.readUTF(stream)
result.add(str)
}
return result
}
}
object ConstantsMapExternalizer : DataExternalizer<Map<String, Any>> {
override fun save(output: DataOutput, map: Map<String, Any>?) {
output.writeInt(map!!.size())
for (name in map.keySet().sorted()) {
output.writeInt(map!!.size)
for (name in map.keys.sorted()) {
IOUtil.writeString(name, output)
val value = map[name]!!
when (value) {
is Int -> {
output.writeByte(Kind.INT.ordinal())
output.writeByte(Kind.INT.ordinal)
output.writeInt(value)
}
is Float -> {
output.writeByte(Kind.FLOAT.ordinal())
output.writeByte(Kind.FLOAT.ordinal)
output.writeFloat(value)
}
is Long -> {
output.writeByte(Kind.LONG.ordinal())
output.writeByte(Kind.LONG.ordinal)
output.writeLong(value)
}
is Double -> {
output.writeByte(Kind.DOUBLE.ordinal())
output.writeByte(Kind.DOUBLE.ordinal)
output.writeDouble(value)
}
is String -> {
output.writeByte(Kind.STRING.ordinal())
output.writeByte(Kind.STRING.ordinal)
IOUtil.writeString(value, output)
}
else -> throw IllegalStateException("Unexpected constant class: ${value.javaClass}")
@@ -222,25 +163,6 @@ object ConstantsMapExternalizer : DataExternalizer<Map<String, Any>> {
}
}
object IntSetExternalizer : DataExternalizer<Set<Int>> {
override fun save(output: DataOutput, value: Set<Int>) {
value.forEach { output.writeInt(it) }
}
override fun read(input: DataInput): Set<Int> {
val result = TIntHashSet()
val stream = input as DataInputStream
while (stream.available() > 0) {
val str = stream.readInt()
result.add(str)
}
return TIntHashSetDecorator(result)
}
}
object IntExternalizer : DataExternalizer<Int> {
override fun read(input: DataInput): Int = input.readInt()
@@ -249,6 +171,12 @@ object IntExternalizer : DataExternalizer<Int> {
}
}
object PathStringDescriptor : EnumeratorStringDescriptor() {
override fun getHashCode(value: String) = FileUtil.pathHashCode(value)
override fun isEqual(val1: String, val2: String?) = FileUtil.pathsEqual(val1, val2)
}
object FileKeyDescriptor : KeyDescriptor<File> {
override fun read(input: DataInput): File = File(input.readUTF())
@@ -261,4 +189,28 @@ object FileKeyDescriptor : KeyDescriptor<File> {
override fun isEqual(val1: File?, val2: File?): Boolean =
FileUtil.FILE_HASHING_STRATEGY.equals(val1, val2)
}
}
open class CollectionExternalizer<T>(
private val elementExternalizer: DataExternalizer<T>,
private val newCollection: () -> MutableCollection<T>
) : DataExternalizer<Collection<T>> {
override fun read(input: DataInput): Collection<T> {
val result = newCollection()
val stream = input as DataInputStream
while (stream.available() > 0) {
result.add(elementExternalizer.read(stream))
}
return result
}
override fun save(output: DataOutput, value: Collection<T>) {
value.forEach { elementExternalizer.save(output, it) }
}
}
object StringCollectionExternalizer : CollectionExternalizer<String>(EnumeratorStringDescriptor(), { HashSet() })
object IntCollectionExternalizer : CollectionExternalizer<Int>(IntExternalizer, { HashSet() })

View File

@@ -0,0 +1,31 @@
/*
* 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.incremental.storage
data class LookupSymbolKey(val nameHash: Int, val scopeHash: Int) : Comparable<LookupSymbolKey> {
constructor(name: String, scope: String) : this(name.hashCode(), scope.hashCode())
override fun compareTo(other: LookupSymbolKey): Int {
val nameCmp = nameHash.compareTo(other.nameHash)
if (nameCmp != 0) return nameCmp
return scopeHash.compareTo(other.scopeHash)
}
}
data class ProtoMapValue(val isPackageFacade: Boolean, val bytes: ByteArray, val strings: Array<String>)

View File

@@ -0,0 +1,131 @@
/*
* 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.modules
import com.intellij.openapi.util.io.FileUtil.toSystemIndependentName
import com.intellij.openapi.util.text.StringUtil.escapeXml
import org.jetbrains.kotlin.build.JvmSourceRoot
import org.jetbrains.kotlin.cli.common.modules.ModuleXmlParser.*
import org.jetbrains.kotlin.config.IncrementalCompilation
import org.jetbrains.kotlin.utils.Printer
import java.io.File
class KotlinModuleXmlBuilder {
private val xml = StringBuilder()
private val p = Printer(xml)
private var done = false
init {
openTag(p, MODULES)
}
fun addModule(
moduleName: String,
outputDir: String,
sourceFiles: Iterable<File>,
javaSourceRoots: Iterable<JvmSourceRoot>,
classpathRoots: Iterable<File>,
targetTypeId: String,
isTests: Boolean,
directoriesToFilterOut: Set<File>,
friendDirs: Iterable<File>): KotlinModuleXmlBuilder {
assert(!done) { "Already done" }
p.println("<!-- Module script for ${if (isTests) "tests" else "production"} -->")
p.println("<", MODULE, " ",
NAME, "=\"", escapeXml(moduleName), "\" ",
TYPE, "=\"", escapeXml(targetTypeId), "\" ",
OUTPUT_DIR, "=\"", getEscapedPath(File(outputDir)), "\">")
p.pushIndent()
for (friendDir in friendDirs) {
p.println("<", FRIEND_DIR, " ", PATH, "=\"", getEscapedPath(friendDir), "\"/>")
}
for (sourceFile in sourceFiles) {
p.println("<", SOURCES, " ", PATH, "=\"", getEscapedPath(sourceFile), "\"/>")
}
processJavaSourceRoots(javaSourceRoots)
processClasspath(classpathRoots, directoriesToFilterOut)
closeTag(p, MODULE)
return this
}
private fun processClasspath(
files: Iterable<File>,
directoriesToFilterOut: Set<File>) {
p.println("<!-- Classpath -->")
for (file in files) {
val isOutput = directoriesToFilterOut.contains(file) && !IncrementalCompilation.isEnabled()
if (isOutput) {
// For IDEA's make (incremental compilation) purposes, output directories of the current module and its dependencies
// appear on the class path, so we are at risk of seeing the results of the previous build, i.e. if some class was
// removed in the sources, it may still be there in binaries. Thus, we delete these entries from the classpath.
p.println("<!-- Output directory, commented out -->")
p.println("<!-- ")
p.pushIndent()
}
p.println("<", CLASSPATH, " ", PATH, "=\"", getEscapedPath(file), "\"/>")
if (isOutput) {
p.popIndent()
p.println("-->")
}
}
}
private fun processJavaSourceRoots(roots: Iterable<JvmSourceRoot>) {
p.println("<!-- Java source roots -->")
for (root in roots) {
p.print("<")
p.printWithNoIndent(JAVA_SOURCE_ROOTS, " ", PATH, "=\"", getEscapedPath(root.file), "\"")
if (root.packagePrefix != null) {
p.printWithNoIndent(" ", JAVA_SOURCE_PACKAGE_PREFIX, "=\"", root.packagePrefix, "\"")
}
p.printWithNoIndent("/>")
p.println()
}
}
fun asText(): CharSequence {
if (!done) {
closeTag(p, MODULES)
done = true
}
return xml
}
private fun openTag(p: Printer, tag: String) {
p.println("<$tag>")
p.pushIndent()
}
private fun closeTag(p: Printer, tag: String) {
p.popIndent()
p.println("</$tag>")
}
private fun getEscapedPath(sourceFile: File): String {
return escapeXml(toSystemIndependentName(sourceFile.path))
}
}

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

@@ -27,43 +27,47 @@ import org.jetbrains.kotlin.types.isDynamic
import org.jetbrains.kotlin.utils.keysToMapExceptNulls
import java.util.Comparator
public object CodegenUtilKt {
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(
@JvmStatic 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) as Collection<CallableMemberDescriptor> +
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" }
assert(actualDelegates.size <= 1) { "Many delegates found for $delegatingMember: $actualDelegates" }
actualDelegates.firstOrNull()
}

View File

@@ -19,22 +19,22 @@ package org.jetbrains.kotlin.backend.common.bridges
import org.jetbrains.kotlin.utils.DFS
import java.util.HashSet
public interface FunctionHandle {
public val isDeclaration: Boolean
public val isAbstract: Boolean
interface FunctionHandle {
val isDeclaration: Boolean
val isAbstract: Boolean
public fun getOverridden(): Iterable<FunctionHandle>
fun getOverridden(): Iterable<FunctionHandle>
}
public data class Bridge<Signature>(
public val from: Signature,
public val to: Signature
data class Bridge<Signature>(
val from: Signature,
val to: Signature
) {
override fun toString() = "$from -> $to"
}
public fun <Function : FunctionHandle, Signature> generateBridges(
fun <Function : FunctionHandle, Signature> generateBridges(
function: Function,
signature: (Function) -> Signature
): Set<Bridge<Signature>> {
@@ -69,7 +69,7 @@ public fun <Function : FunctionHandle, Signature> generateBridges(
return bridgesToGenerate.map { Bridge(it, method) }.toSet()
}
public fun <Function : FunctionHandle> findAllReachableDeclarations(function: Function): MutableSet<Function> {
fun <Function : FunctionHandle> findAllReachableDeclarations(function: Function): MutableSet<Function> {
val collector = object : DFS.NodeHandlerWithListResult<Function, Function>() {
override fun afterChildren(current: Function) {
if (current.isDeclaration) {
@@ -86,7 +86,7 @@ public fun <Function : FunctionHandle> findAllReachableDeclarations(function: Fu
* Given a concrete function, finds an implementation (a concrete declaration) of this function in the supertypes.
* The implementation is guaranteed to exist because if it wouldn't, the given function would've been abstract
*/
public fun <Function : FunctionHandle> findConcreteSuperDeclaration(function: Function): Function {
fun <Function : FunctionHandle> findConcreteSuperDeclaration(function: Function): Function {
require(!function.isAbstract, { "Only concrete functions have implementations: $function" })
if (function.isDeclaration) return function
@@ -109,7 +109,7 @@ public fun <Function : FunctionHandle> findConcreteSuperDeclaration(function: Fu
result.removeAll(toRemove)
val concreteRelevantDeclarations = result.filter { !it.isAbstract }
if (concreteRelevantDeclarations.size() != 1) {
if (concreteRelevantDeclarations.size != 1) {
error("Concrete fake override $function should have exactly one concrete super-declaration: $concreteRelevantDeclarations")
}

View File

@@ -23,7 +23,7 @@ import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.OverrideResolver
import org.jetbrains.kotlin.resolve.calls.callResolverUtil.isOrOverridesSynthesized
public fun <Signature> generateBridgesForFunctionDescriptor(
fun <Signature> generateBridgesForFunctionDescriptor(
descriptor: FunctionDescriptor,
signature: (FunctionDescriptor) -> Signature
): Set<Bridge<Signature>> {
@@ -47,16 +47,16 @@ public fun <Signature> generateBridgesForFunctionDescriptor(
* can generate a bridge near an implementation (of course, in case it has a super-declaration with a different signature). Ultimately this
* eases the process of determining what bridges are already generated in our supertypes and need to be inherited, not regenerated.
*/
public data class DescriptorBasedFunctionHandle(val descriptor: FunctionDescriptor) : FunctionHandle {
private val overridden = descriptor.getOverriddenDescriptors().map { DescriptorBasedFunctionHandle(it.getOriginal()) }
data class DescriptorBasedFunctionHandle(val descriptor: FunctionDescriptor) : FunctionHandle {
private val overridden = descriptor.overriddenDescriptors.map { DescriptorBasedFunctionHandle(it.original) }
override val isDeclaration: Boolean =
descriptor.getKind().isReal() ||
descriptor.kind.isReal ||
findTraitImplementation(descriptor) != null
override val isAbstract: Boolean =
descriptor.getModality() == Modality.ABSTRACT ||
DescriptorUtils.isInterface(descriptor.getContainingDeclaration())
descriptor.modality == Modality.ABSTRACT ||
DescriptorUtils.isInterface(descriptor.containingDeclaration)
override fun getOverridden() = overridden
}
@@ -67,14 +67,14 @@ public data class DescriptorBasedFunctionHandle(val descriptor: FunctionDescript
* trait implementation should be generated into the class containing the fake override; or null if the given function is not a fake
* override of any trait implementation or such method was already generated into the superclass or is a method from Any.
*/
public fun findTraitImplementation(descriptor: CallableMemberDescriptor): CallableMemberDescriptor? {
if (descriptor.getKind().isReal()) return null
fun findTraitImplementation(descriptor: CallableMemberDescriptor): CallableMemberDescriptor? {
if (descriptor.kind.isReal) return null
if (isOrOverridesSynthesized(descriptor)) return null
val implementation = findImplementationFromInterface(descriptor) ?: return null
val immediateConcreteSuper = firstSuperMethodFromKotlin(descriptor, implementation) ?: return null
if (!DescriptorUtils.isInterface(immediateConcreteSuper.getContainingDeclaration())) {
if (!DescriptorUtils.isInterface(immediateConcreteSuper.containingDeclaration)) {
// If this implementation is already generated into the superclass, we need not generate it again, it'll be inherited
return null
}
@@ -86,14 +86,13 @@ public fun findTraitImplementation(descriptor: CallableMemberDescriptor): Callab
* Given a fake override, returns an overridden non-abstract function from an interface which is the actual implementation of this function
* that should be called when the given fake override is called.
*/
public fun findImplementationFromInterface(descriptor: CallableMemberDescriptor): CallableMemberDescriptor? {
fun findImplementationFromInterface(descriptor: CallableMemberDescriptor): CallableMemberDescriptor? {
val overridden = OverrideResolver.getOverriddenDeclarations(descriptor)
val filtered = OverrideResolver.filterOutOverridden(overridden)
val result = filtered.firstOrNull { it.getModality() != Modality.ABSTRACT } ?: return null
val result = filtered.firstOrNull { it.modality != Modality.ABSTRACT } ?: return null
val container = result.getContainingDeclaration()
if (DescriptorUtils.isClass(container) || DescriptorUtils.isEnumClass(container)) return null
if (DescriptorUtils.isClassOrEnumClass(result.containingDeclaration)) return null
return result
}
@@ -103,12 +102,12 @@ public fun findImplementationFromInterface(descriptor: CallableMemberDescriptor)
* returns the first immediate super function of the given fake override which overrides that implementation.
* The returned function should be called from TImpl-bridges generated for the given fake override.
*/
public fun firstSuperMethodFromKotlin(
fun firstSuperMethodFromKotlin(
descriptor: CallableMemberDescriptor,
implementation: CallableMemberDescriptor
): CallableMemberDescriptor? {
return descriptor.getOverriddenDescriptors().firstOrNull { overridden ->
overridden.getModality() != Modality.ABSTRACT &&
return descriptor.overriddenDescriptors.firstOrNull { overridden ->
overridden.modality != Modality.ABSTRACT &&
(overridden == implementation || OverrideResolver.overrides(overridden, implementation))
}
}

View File

@@ -18,24 +18,24 @@ package org.jetbrains.kotlin.backend.common.output
import java.io.File
public interface OutputFileCollection {
public fun get(relativePath: String): OutputFile?
public fun asList(): List<OutputFile>
interface OutputFileCollection {
fun get(relativePath: String): OutputFile?
fun asList(): List<OutputFile>
}
public class SimpleOutputFileCollection(private val outputFiles: List<OutputFile>) : OutputFileCollection {
class SimpleOutputFileCollection(private val outputFiles: List<OutputFile>) : OutputFileCollection {
override fun get(relativePath: String): OutputFile? = outputFiles.firstOrNull { it.relativePath == relativePath }
override fun asList(): List<OutputFile> = outputFiles
}
public interface OutputFile {
public val relativePath: String
public val sourceFiles: List<File>
public fun asByteArray(): ByteArray
public fun asText(): String
interface OutputFile {
val relativePath: String
val sourceFiles: List<File>
fun asByteArray(): ByteArray
fun asText(): String
}
public class SimpleOutputFile(
class SimpleOutputFile(
override val sourceFiles: List<File>,
override val relativePath: String,
private val content: String
@@ -46,7 +46,7 @@ public class SimpleOutputFile(
override fun toString() = "$relativePath (compiled from $sourceFiles)"
}
public class SimpleOutputBinaryFile(
class SimpleOutputBinaryFile(
override val sourceFiles: List<File>,
override val relativePath: String,
private val content: ByteArray

View File

@@ -24,18 +24,18 @@ import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.DescriptorUtils
import java.util.*
open public class AbstractAccessorForFunctionDescriptor(
open class AbstractAccessorForFunctionDescriptor(
containingDeclaration: DeclarationDescriptor,
name: Name
) : SimpleFunctionDescriptorImpl(containingDeclaration, null, Annotations.EMPTY,
name, CallableMemberDescriptor.Kind.DECLARATION, SourceElement.NO_SOURCE) {
protected fun copyTypeParameters(descriptor: FunctionDescriptor): List<TypeParameterDescriptor> = descriptor.getTypeParameters().map {
protected fun copyTypeParameters(descriptor: FunctionDescriptor): List<TypeParameterDescriptor> = descriptor.typeParameters.map {
val copy = TypeParameterDescriptorImpl.createForFurtherModification(
this, it.getAnnotations(), it.isReified(),
it.getVariance(), it.getName(),
it.getIndex(), SourceElement.NO_SOURCE)
for (upperBound in it.getUpperBounds()) {
this, it.annotations, it.isReified,
it.variance, it.name,
it.index, SourceElement.NO_SOURCE)
for (upperBound in it.upperBounds) {
copy.addUpperBound(upperBound)
}
copy.setInitialized()
@@ -43,5 +43,5 @@ open public class AbstractAccessorForFunctionDescriptor(
}
protected fun copyValueParameters(descriptor: FunctionDescriptor): List<ValueParameterDescriptor> =
descriptor.getValueParameters().map { it.copy(this, it.getName()) }
descriptor.valueParameters.map { it.copy(this, it.name) }
}

View File

@@ -22,7 +22,7 @@ import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeSubstitutor
public class AccessorForConstructorDescriptor(
class AccessorForConstructorDescriptor(
private val calleeDescriptor: ConstructorDescriptor,
containingDeclaration: DeclarationDescriptor,
private val superCallTarget: ClassDescriptor?
@@ -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

@@ -31,9 +31,9 @@ abstract class ArgumentGenerator {
*
* @see kotlin.reflect.jvm.internal.KCallableImpl.callBy
*/
open fun generate(valueArgumentsByIndex: List<ResolvedValueArgument>, actualArgs: List<ResolvedValueArgument>): DefaultCallMask {
assert(valueArgumentsByIndex.size() == actualArgs.size()) {
"Value arguments collection should have same size, but ${valueArgumentsByIndex.size()} != ${actualArgs.size()}"
open fun generate(valueArgumentsByIndex: List<ResolvedValueArgument>, actualArgs: List<ResolvedValueArgument>): DefaultCallArgs {
assert(valueArgumentsByIndex.size == actualArgs.size) {
"Value arguments collection should have same size, but ${valueArgumentsByIndex.size} != ${actualArgs.size}"
}
val arg2Index = valueArgumentsByIndex.mapToIndex()
@@ -48,7 +48,7 @@ abstract class ArgumentGenerator {
}
}
val masks = DefaultCallMask(valueArgumentsByIndex.size())
val defaultArgs = DefaultCallArgs(valueArgumentsByIndex.size)
for (argumentWithDeclIndex in actualArgsWithDeclIndex) {
val argument = argumentWithDeclIndex.arg
@@ -59,7 +59,7 @@ abstract class ArgumentGenerator {
generateExpression(declIndex, argument)
}
is DefaultValueArgument -> {
masks.mark(declIndex)
defaultArgs.mark(declIndex)
generateDefault(declIndex, argument)
}
is VarargValueArgument -> {
@@ -73,7 +73,7 @@ abstract class ArgumentGenerator {
reorderArgumentsIfNeeded(actualArgsWithDeclIndex)
return masks
return defaultArgs
}
protected open fun generateExpression(i: Int, argument: ExpressionValueArgument) {

View File

@@ -61,11 +61,11 @@ import java.util.Set;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isBoolean;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isPrimitiveClass;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isConstOrHasJvmFieldAnnotation;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isJvmInterface;
import static org.jetbrains.kotlin.load.java.JvmAnnotationNames.KOTLIN_SYNTHETIC_CLASS;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.*;
import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.*;
import static org.jetbrains.kotlin.resolve.jvm.annotations.AnnotationUtilKt.hasJvmFieldAnnotation;
import static org.jetbrains.kotlin.types.TypeUtils.isNullableType;
import static org.jetbrains.org.objectweb.asm.Opcodes.*;
@@ -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;
@@ -268,7 +268,7 @@ public class AsmUtil {
}
public static int getVisibilityAccessFlagForAnonymous(@NotNull ClassDescriptor descriptor) {
return InlineUtil.isInline(descriptor.getContainingDeclaration()) ? ACC_PUBLIC : NO_FLAG_PACKAGE_PRIVATE;
return InlineUtil.isInlineOrContainingInline(descriptor.getContainingDeclaration()) ? ACC_PUBLIC : NO_FLAG_PACKAGE_PRIVATE;
}
public static int calculateInnerClassAccessFlags(@NotNull ClassDescriptor innerClass) {
@@ -299,9 +299,6 @@ public class AsmUtil {
public static int getDeprecatedAccessFlag(@NotNull MemberDescriptor descriptor) {
if (descriptor instanceof PropertyAccessorDescriptor) {
if (((PropertyAccessorDescriptor) descriptor).getCorrespondingProperty().isConst()) {
return ACC_DEPRECATED;
}
return KotlinBuiltIns.isDeprecated(descriptor)
? ACC_DEPRECATED
: getDeprecatedAccessFlag(((PropertyAccessorDescriptor) descriptor).getCorrespondingProperty());
@@ -325,9 +322,8 @@ 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 (AnnotationUtilKt.isInlineOnly(memberDescriptor)) return ACC_PRIVATE;
if (memberVisibility == Visibilities.LOCAL && memberDescriptor instanceof CallableMemberDescriptor) {
return ACC_PUBLIC;
@@ -379,11 +375,6 @@ public class AsmUtil {
}
}
if (memberDescriptor instanceof PropertyDescriptor &&
((PropertyDescriptor) memberDescriptor).isConst() || hasJvmFieldAnnotation(memberDescriptor)) {
return null;
}
return null;
}
@@ -550,7 +541,7 @@ public class AsmUtil {
if (opToken == KtTokens.EXCLEQ || opToken == KtTokens.EXCLEQEQEQ) {
genInvertBoolean(v);
}
return Unit.INSTANCE$;
return Unit.INSTANCE;
}
});
}
@@ -689,28 +680,17 @@ public class AsmUtil {
}
public static boolean isInstancePropertyWithStaticBackingField(@NotNull PropertyDescriptor propertyDescriptor) {
if (propertyDescriptor.getKind() == CallableMemberDescriptor.Kind.FAKE_OVERRIDE) {
return false;
}
DeclarationDescriptor container = propertyDescriptor.getContainingDeclaration();
return isNonCompanionObject(container) ||
isPropertyWithBackingFieldInOuterClass(propertyDescriptor) ||
(isCompanionObject(container) && isInterface(container.getContainingDeclaration()));
}
public static boolean isPropertyWithBackingFieldInOuterClass(@NotNull PropertyDescriptor propertyDescriptor) {
return propertyDescriptor.getKind() != CallableMemberDescriptor.Kind.FAKE_OVERRIDE &&
isCompanionObjectWithBackingFieldsInOuter(propertyDescriptor.getContainingDeclaration());
isObject(propertyDescriptor.getContainingDeclaration());
}
public static int getVisibilityForSpecialPropertyBackingField(@NotNull PropertyDescriptor propertyDescriptor, boolean isDelegate) {
public static int getVisibilityForBackingField(@NotNull PropertyDescriptor propertyDescriptor, boolean isDelegate) {
boolean isExtensionProperty = propertyDescriptor.getExtensionReceiverParameter() != null;
if (isDelegate || isExtensionProperty) {
return ACC_PRIVATE;
}
else {
return areBothAccessorDefault(propertyDescriptor)
return propertyDescriptor.isLateInit() || isConstOrHasJvmFieldAnnotation(propertyDescriptor)
? getVisibilityAccessFlag(descriptorForVisibility(propertyDescriptor))
: ACC_PRIVATE;
}
@@ -726,27 +706,10 @@ public class AsmUtil {
}
public static boolean isPropertyWithBackingFieldCopyInOuterClass(@NotNull PropertyDescriptor propertyDescriptor) {
boolean isExtensionProperty = propertyDescriptor.getExtensionReceiverParameter() != null;
DeclarationDescriptor propertyContainer = propertyDescriptor.getContainingDeclaration();
return !propertyDescriptor.isVar()
&& !isExtensionProperty
return propertyDescriptor.isConst()
&& isCompanionObject(propertyContainer) && isInterface(propertyContainer.getContainingDeclaration())
&& areBothAccessorDefault(propertyDescriptor)
&& getVisibilityForSpecialPropertyBackingField(propertyDescriptor, false) == ACC_PUBLIC;
}
public static boolean isCompanionObjectWithBackingFieldsInOuter(@NotNull DeclarationDescriptor companionObject) {
DeclarationDescriptor containingClass = companionObject.getContainingDeclaration();
return isCompanionObject(companionObject) && (isClass(containingClass) || isEnumClass(containingClass));
}
private static boolean areBothAccessorDefault(@NotNull PropertyDescriptor propertyDescriptor) {
return isAccessorWithEmptyBody(propertyDescriptor.getGetter())
&& (!propertyDescriptor.isVar() || isAccessorWithEmptyBody(propertyDescriptor.getSetter()));
}
private static boolean isAccessorWithEmptyBody(@Nullable PropertyAccessorDescriptor accessorDescriptor) {
return accessorDescriptor == null || !accessorDescriptor.hasBody();
&& getVisibilityForBackingField(propertyDescriptor, false) == ACC_PUBLIC;
}
public static Type comparisonOperandType(Type left, Type right) {
@@ -822,24 +785,25 @@ public class AsmUtil {
public static void writeKotlinSyntheticClassAnnotation(@NotNull ClassBuilder v, @NotNull GenerationState state) {
AnnotationVisitor av = v.newAnnotation(asmDescByFqNameWithoutInnerClasses(KOTLIN_SYNTHETIC_CLASS), true);
JvmCodegenUtil.writeAbiVersion(av);
JvmCodegenUtil.writeModuleName(av, state);
av.visitEnd();
}
public static void writeAnnotationData(
@NotNull AnnotationVisitor av,
@NotNull DescriptorSerializer serializer,
@NotNull MessageLite message
@NotNull MessageLite message,
boolean old
) {
byte[] bytes = serializer.serialize(message);
JvmCodegenUtil.writeAbiVersion(av);
AnnotationVisitor data = av.visitArray(JvmAnnotationNames.DATA_FIELD_NAME);
AnnotationVisitor data = av.visitArray(old ? JvmAnnotationNames.DATA_FIELD_NAME : JvmAnnotationNames.METADATA_DATA_FIELD_NAME);
for (String string : BitEncoding.encodeBytes(bytes)) {
data.visit(null, string);
}
data.visitEnd();
AnnotationVisitor strings = av.visitArray(JvmAnnotationNames.STRINGS_FIELD_NAME);
AnnotationVisitor strings = av.visitArray(
old ? JvmAnnotationNames.STRINGS_FIELD_NAME : JvmAnnotationNames.METADATA_STRINGS_FIELD_NAME
);
for (String string : ((JvmStringTable) serializer.getStringTable()).getStrings()) {
strings.visit(null, string);
}
@@ -851,13 +815,6 @@ public class AsmUtil {
return asmTypeByFqNameWithoutInnerClasses(fqName).getDescriptor();
}
@NotNull
public static String shortNameByAsmType(@NotNull Type type) {
String internalName = type.getInternalName();
int lastSlash = internalName.lastIndexOf('/');
return lastSlash < 0 ? internalName : internalName.substring(lastSlash + 1);
}
@NotNull
public static Type asmTypeByFqNameWithoutInnerClasses(@NotNull FqName fqName) {
return Type.getObjectType(internalNameByFqNameWithoutInnerClasses(fqName));

View File

@@ -147,8 +147,8 @@ open class BranchedValue(
}, IFEQ)
}
public fun cmp(opToken: IElementType, operandType: Type, left: StackValue, right: StackValue): StackValue =
if (operandType.getSort() == Type.OBJECT)
fun cmp(opToken: IElementType, operandType: Type, left: StackValue, right: StackValue): StackValue =
if (operandType.sort == Type.OBJECT)
ObjectCompare(opToken, operandType, left, right)
else
NumberCompare(opToken, operandType, left, right)

View File

@@ -51,15 +51,15 @@ public class CallBasedArgumentGenerator extends ArgumentGenerator {
@NotNull
@Override
public DefaultCallMask generate(
public DefaultCallArgs generate(
@NotNull List<? extends ResolvedValueArgument> valueArgumentsByIndex,
@NotNull List<? extends ResolvedValueArgument> valueArgs
) {
boolean shouldMarkLineNumbers = this.codegen.isShouldMarkLineNumbers();
this.codegen.setShouldMarkLineNumbers(false);
DefaultCallMask masks = super.generate(valueArgumentsByIndex, valueArgs);
DefaultCallArgs defaultArgs = super.generate(valueArgumentsByIndex, valueArgs);
this.codegen.setShouldMarkLineNumbers(shouldMarkLineNumbers);
return masks;
return defaultArgs;
}
@Override
@@ -75,10 +75,9 @@ public class CallBasedArgumentGenerator extends ArgumentGenerator {
@Override
protected void generateDefault(int i, @NotNull DefaultValueArgument argument) {
ValueParameterDescriptor parameter = valueParameters.get(i);
Type type = valueParameterTypes.get(i);
pushDefaultValueOnStack(type, codegen.v);
callGenerator.afterParameterPut(type, null, parameter, i);
callGenerator.afterParameterPut(type, null, i);
}
@Override
@@ -86,11 +85,11 @@ public class CallBasedArgumentGenerator extends ArgumentGenerator {
ValueParameterDescriptor parameter = valueParameters.get(i);
Type type = valueParameterTypes.get(i);
codegen.genVarargs(argument, parameter.getType());
callGenerator.afterParameterPut(type, null, parameter, i);
callGenerator.afterParameterPut(type, null, i);
}
@Override
protected void reorderArgumentsIfNeeded(@NotNull List actualArgsWithDeclIndex) {
protected void reorderArgumentsIfNeeded(@NotNull List<ArgumentAndDeclIndex> actualArgsWithDeclIndex) {
callGenerator.reorderArgumentsIfNeeded(actualArgsWithDeclIndex, valueParameterTypes);
}
}

View File

@@ -46,7 +46,6 @@ abstract class CallGenerator {
override fun afterParameterPut(
type: Type,
stackValue: StackValue?,
valueParameterDescriptor: ValueParameterDescriptor,
parameterIndex: Int) {
}
@@ -70,7 +69,7 @@ abstract class CallGenerator {
}
override fun putValueIfNeeded(
valueParameterDescriptor: ValueParameterDescriptor?, parameterType: Type, value: StackValue) {
parameterType: Type, value: StackValue) {
value.put(value.type, codegen.v)
}
@@ -113,7 +112,6 @@ abstract class CallGenerator {
abstract fun afterParameterPut(
type: Type,
stackValue: StackValue?,
valueParameterDescriptor: ValueParameterDescriptor,
parameterIndex: Int)
abstract fun genValueAndPut(
@@ -123,7 +121,6 @@ abstract class CallGenerator {
parameterIndex: Int)
abstract fun putValueIfNeeded(
valueParameterDescriptor: ValueParameterDescriptor?,
parameterType: Type,
value: StackValue)

View File

@@ -20,32 +20,32 @@ import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
public interface Callable {
public val owner: Type
interface Callable {
val owner: Type
public val dispatchReceiverType: Type?
val dispatchReceiverType: Type?
public val extensionReceiverType: Type?
val extensionReceiverType: Type?
public val generateCalleeType: Type?
val generateCalleeType: Type?
public val valueParameterTypes: List<Type>
val valueParameterTypes: List<Type>
public val parameterTypes: Array<Type>
val parameterTypes: Array<Type>
public val returnType: Type
val returnType: Type
public fun genInvokeInstruction(v: InstructionAdapter)
fun genInvokeInstruction(v: InstructionAdapter)
public fun isStaticCall(): Boolean
fun isStaticCall(): Boolean
public fun invokeMethodWithArguments(resolvedCall: ResolvedCall<*>, receiver: StackValue, codegen: ExpressionCodegen): StackValue {
fun invokeMethodWithArguments(resolvedCall: ResolvedCall<*>, receiver: StackValue, codegen: ExpressionCodegen): StackValue {
return StackValue.functionCall(returnType) {
codegen.invokeMethodWithArguments(this, resolvedCall, receiver)
}
}
public fun afterReceiverGeneration(v: InstructionAdapter) {
fun afterReceiverGeneration(v: InstructionAdapter) {
}
}

View File

@@ -27,7 +27,7 @@ import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
import org.jetbrains.org.objectweb.asm.commons.Method
import org.jetbrains.org.objectweb.asm.util.Printer
public class CallableMethod(
class CallableMethod(
override val owner: Type,
private val defaultImplOwner: Type?,
private val defaultMethodDesc: String,
@@ -37,48 +37,47 @@ public class CallableMethod(
override val extensionReceiverType: Type?,
override val generateCalleeType: Type?
) : Callable {
public fun getValueParameters(): List<JvmMethodParameterSignature> =
signature.getValueParameters()
fun getValueParameters(): List<JvmMethodParameterSignature> =
signature.valueParameters
override val valueParameterTypes: List<Type>
get() = signature.getValueParameters().filter { it.getKind() == JvmMethodParameterKind.VALUE }.map { it.getAsmType() }
get() = signature.valueParameters.filter { it.kind == JvmMethodParameterKind.VALUE }.map { it.asmType }
public fun getAsmMethod(): Method =
signature.getAsmMethod()
fun getAsmMethod(): Method =
signature.asmMethod
override val parameterTypes: Array<Type>
get() = getAsmMethod().getArgumentTypes()
get() = getAsmMethod().argumentTypes
public override fun genInvokeInstruction(v: InstructionAdapter) {
v.visitMethodInsn(invokeOpcode, owner.getInternalName(), getAsmMethod().getName(), getAsmMethod().getDescriptor())
override fun genInvokeInstruction(v: InstructionAdapter) {
v.visitMethodInsn(invokeOpcode, owner.internalName, getAsmMethod().name, getAsmMethod().descriptor)
}
public fun genInvokeDefaultInstruction(v: InstructionAdapter) {
fun genInvokeDefaultInstruction(v: InstructionAdapter) {
if (defaultImplOwner == null) {
throw IllegalStateException()
}
val method = getAsmMethod()
if ("<init>".equals(method.getName())) {
v.aconst(null)
v.visitMethodInsn(INVOKESPECIAL, defaultImplOwner.getInternalName(), "<init>", defaultMethodDesc, false)
if ("<init>".equals(method.name)) {
v.visitMethodInsn(INVOKESPECIAL, defaultImplOwner.internalName, "<init>", defaultMethodDesc, false)
}
else {
v.visitMethodInsn(INVOKESTATIC, defaultImplOwner.getInternalName(),
method.getName() + JvmAbi.DEFAULT_PARAMS_IMPL_SUFFIX, defaultMethodDesc, false)
v.visitMethodInsn(INVOKESTATIC, defaultImplOwner.internalName,
method.name + JvmAbi.DEFAULT_PARAMS_IMPL_SUFFIX, defaultMethodDesc, false)
StackValue.coerce(Type.getReturnType(defaultMethodDesc), Type.getReturnType(signature.asmMethod.descriptor), v)
}
}
override val returnType: Type
get() = signature.getReturnType()
get() = signature.returnType
override fun isStaticCall(): Boolean =
invokeOpcode == INVOKESTATIC
override fun toString(): String =
"${Printer.OPCODES[invokeOpcode]} ${owner.getInternalName()}.$signature"
"${Printer.OPCODES[invokeOpcode]} ${owner.internalName}.$signature"
}

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

@@ -22,14 +22,14 @@ import com.intellij.psi.PsiFile;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.DataOutputStream;
import kotlin.CollectionsKt;
import kotlin.collections.CollectionsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.kotlin.backend.common.output.OutputFile;
import org.jetbrains.kotlin.backend.common.output.OutputFileCollection;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.load.java.JvmAbi;
import org.jetbrains.kotlin.load.kotlin.JvmMetadataVersion;
import org.jetbrains.kotlin.load.kotlin.PackagePartClassUtils;
import org.jetbrains.kotlin.load.kotlin.PackageParts;
import org.jetbrains.kotlin.name.FqName;
@@ -123,7 +123,7 @@ public class ClassFileFactory implements OutputFileCollection {
try {
ByteArrayOutputStream moduleMapping = new ByteArrayOutputStream(4096);
DataOutputStream dataOutStream = new DataOutputStream(moduleMapping);
int[] version = JvmAbi.VERSION.toArray();
int[] version = JvmMetadataVersion.INSTANCE.toArray();
dataOutStream.writeInt(version.length);
for (int number : version) {
dataOutStream.writeInt(number);

View File

@@ -25,7 +25,7 @@ import org.jetbrains.kotlin.resolve.jvm.diagnostics.RawSignature
import org.jetbrains.org.objectweb.asm.FieldVisitor
import org.jetbrains.org.objectweb.asm.MethodVisitor
public abstract class ClassNameCollectionClassBuilderFactory(
abstract class ClassNameCollectionClassBuilderFactory(
delegate: ClassBuilderFactory
) : DelegatingClassBuilderFactory(delegate) {

View File

@@ -18,8 +18,8 @@ package org.jetbrains.kotlin.codegen;
import com.google.common.collect.Lists;
import com.intellij.util.ArrayUtil;
import kotlin.CollectionsKt;
import kotlin.Unit;
import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -35,6 +35,7 @@ import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl;
import org.jetbrains.kotlin.incremental.components.NoLookupLocation;
import org.jetbrains.kotlin.load.java.JvmAbi;
import org.jetbrains.kotlin.load.java.JvmAnnotationNames;
import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader;
import org.jetbrains.kotlin.psi.KtElement;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.DescriptorUtils;
@@ -46,7 +47,6 @@ import org.jetbrains.kotlin.serialization.ProtoBuf;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils;
import org.jetbrains.kotlin.util.OperatorNameConventions;
import org.jetbrains.kotlin.utils.FunctionsKt;
import org.jetbrains.org.objectweb.asm.AnnotationVisitor;
import org.jetbrains.org.objectweb.asm.MethodVisitor;
import org.jetbrains.org.objectweb.asm.Type;
@@ -60,7 +60,7 @@ import java.util.List;
import static org.jetbrains.kotlin.codegen.AsmUtil.*;
import static org.jetbrains.kotlin.codegen.ExpressionCodegen.generateClassLiteralReference;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isConst;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.writeModuleName;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.writeAbiVersion;
import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.CLOSURE;
import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.asmTypeForAnonymousClass;
import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.*;
@@ -212,7 +212,7 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
this.constructor = generateConstructor();
if (isConst(closure)) {
generateConstInstance(asmType, asmType, FunctionsKt.<InstructionAdapter>doNothing());
generateConstInstance(asmType, asmType);
}
genClosureFields(closure, v, typeMapper);
@@ -222,16 +222,22 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
protected void generateKotlinAnnotation() {
writeKotlinSyntheticClassAnnotation(v, state);
DescriptorSerializer serializer =
DescriptorSerializer.createForLambda(
new JvmSerializerExtension(v.getSerializationBindings(), typeMapper, state.getUseTypeTableInSerializer())
);
final DescriptorSerializer serializer =
DescriptorSerializer.createForLambda(new JvmSerializerExtension(v.getSerializationBindings(), state));
ProtoBuf.Function functionProto = serializer.functionProto(funDescriptor).build();
final ProtoBuf.Function functionProto = serializer.functionProto(funDescriptor).build();
WriteAnnotationUtilKt.writeKotlinMetadata(v, KotlinClassHeader.Kind.SYNTHETIC_CLASS, new Function1<AnnotationVisitor, Unit>() {
@Override
public Unit invoke(AnnotationVisitor av) {
writeAnnotationData(av, serializer, functionProto, false);
return Unit.INSTANCE;
}
});
AnnotationVisitor av = v.getVisitor().visitAnnotation(asmDescByFqNameWithoutInnerClasses(JvmAnnotationNames.KOTLIN_FUNCTION), true);
writeAnnotationData(av, serializer, functionProto);
writeModuleName(av, state);
writeAbiVersion(av);
writeAnnotationData(av, serializer, functionProto, true);
av.visitEnd();
}
@@ -259,13 +265,7 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
v.invokespecial(asmType.getInternalName(), "<init>", constructor.getDescriptor(), false);
}
if (functionReferenceTarget != null) {
if (!"true".equalsIgnoreCase(System.getProperty("kotlin.jvm.optimize.callable.references"))) {
v.invokestatic(REFLECTION, "function", Type.getMethodDescriptor(K_FUNCTION, FUNCTION_REFERENCE), false);
}
}
return Unit.INSTANCE$;
return Unit.INSTANCE;
}
}
);

View File

@@ -21,7 +21,7 @@ import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil
import org.jetbrains.kotlin.fileClasses.JvmFileClassesProvider
import org.jetbrains.kotlin.psi.KtFile
public class CodegenFileClassesProvider : JvmFileClassesProvider {
override public fun getFileClassInfo(file: KtFile): JvmFileClassInfo =
class CodegenFileClassesProvider : JvmFileClassesProvider {
override fun getFileClassInfo(file: KtFile): JvmFileClassInfo =
JvmFileClassUtil.getFileClassInfoNoResolve(file)
}

View File

@@ -65,14 +65,14 @@ class CollectionStubMethodGenerator(
val (child, typeParameters) = createSyntheticSubclass()
// If the original class has any type parameters, we copied them and now we need to substitute types of the newly created type
// parameters as arguments for the type parameters of the original class
val parentType = newType(descriptor, typeParameters.map { TypeProjectionImpl(it.getDefaultType()) })
val parentType = newType(descriptor, typeParameters.map { TypeProjectionImpl(it.defaultType) })
// Now we need to determine the arguments which should be substituted for the MutableCollection super class. To do that,
// we look for type arguments which were substituted in the inheritance of the original class from Collection and use them
// to construct the needed MutableCollection type. Since getAllSupertypes() may return several types which correspond to the
// Collection class descriptor, we find the most specific one (which is guaranteed to exist by front-end)
val readOnlyCollectionType = TypeUtils.getAllSupertypes(parentType).findMostSpecificTypeForClass(readOnlyClass)
val mutableCollectionType = newType(mutableClass, readOnlyCollectionType.getArguments())
val mutableCollectionType = newType(mutableClass, readOnlyCollectionType.arguments)
child.addSupertype(parentType)
child.addSupertype(mutableCollectionType)
@@ -81,10 +81,10 @@ class CollectionStubMethodGenerator(
// Bind fake overrides and for each fake override originated from the MutableCollection, save its signature to generate a stub
// or save its descriptor to generate all the needed bridges
for (method in findFakeOverridesForMethodsFromMutableCollection(child, mutableClass)) {
if (method.getModality() == Modality.ABSTRACT) {
if (method.modality == Modality.ABSTRACT) {
// If the fake override is abstract and it's _declared_ as abstract in the class, skip it because the method is already
// present in the bytecode (abstract) and we don't want a duplicate signature error
if (method.findOverriddenFromDirectSuperClass(descriptor)?.getKind() == DECLARATION) continue
if (method.findOverriddenFromDirectSuperClass(descriptor)?.kind == DECLARATION) continue
// Otherwise we can safely generate the stub with the substituted signature
val signature = method.signature()
@@ -160,18 +160,18 @@ class CollectionStubMethodGenerator(
val collectionClasses = with(descriptor.builtIns) {
listOf(
pair(getCollection(), getMutableCollection()),
pair(getSet(), getMutableSet()),
pair(getList(), getMutableList()),
pair(getMap(), getMutableMap()),
pair(getMapEntry(), getMutableMapEntry()),
pair(getIterable(), getMutableIterable()),
pair(getIterator(), getMutableIterator()),
pair(getListIterator(), getMutableListIterator())
pair(collection, mutableCollection),
pair(set, mutableSet),
pair(list, mutableList),
pair(map, mutableMap),
pair(mapEntry, mutableMapEntry),
pair(iterable, mutableIterable),
pair(iterator, mutableIterator),
pair(listIterator, mutableListIterator)
)
}
val allSuperClasses = TypeUtils.getAllSupertypes(descriptor.getDefaultType()).classes().toHashSet()
val allSuperClasses = TypeUtils.getAllSupertypes(descriptor.defaultType).classes().toHashSet()
val ourSuperCollectionClasses = collectionClasses.filter { pair ->
pair.readOnlyClass in allSuperClasses && pair.mutableClass !in allSuperClasses
@@ -180,13 +180,13 @@ class CollectionStubMethodGenerator(
// Filter out built-in classes which are overridden by other built-in classes in the list, to avoid duplicating methods.
val redundantClasses = ourSuperCollectionClasses.flatMapTo(HashSet<ClassDescriptor>()) { pair ->
pair.readOnlyClass.getTypeConstructor().getSupertypes().classes()
pair.readOnlyClass.typeConstructor.supertypes.classes()
}
return ourSuperCollectionClasses.filter { klass -> klass.readOnlyClass !in redundantClasses }
}
private fun Collection<KotlinType>.classes(): Collection<ClassDescriptor> =
this.map { it.getConstructor().getDeclarationDescriptor() as ClassDescriptor }
this.map { it.constructor.declarationDescriptor as ClassDescriptor }
private fun findFakeOverridesForMethodsFromMutableCollection(
klass: ClassDescriptor,
@@ -212,9 +212,9 @@ class CollectionStubMethodGenerator(
}
private fun Collection<KotlinType>.findMostSpecificTypeForClass(klass: ClassDescriptor): KotlinType {
val types = this.filter { it.getConstructor().getDeclarationDescriptor() == klass }
val types = this.filter { it.constructor.declarationDescriptor == klass }
if (types.isEmpty()) error("No supertype of $klass in $this")
if (types.size() == 1) return types.first()
if (types.size == 1) return types.first()
// Find the first type in the list such that it's a subtype of every other type in that list
return types.first { type ->
types.all { other -> KotlinTypeChecker.DEFAULT.isSubtypeOf(type, other) }
@@ -222,19 +222,19 @@ class CollectionStubMethodGenerator(
}
private fun createSyntheticSubclass(): Pair<MutableClassDescriptor, List<TypeParameterDescriptor>> {
val child = MutableClassDescriptor(descriptor.getContainingDeclaration(), ClassKind.CLASS, false,
Name.special("<synthetic inheritor of ${descriptor.getName()}>"), descriptor.getSource())
child.setModality(Modality.FINAL)
child.setVisibility(Visibilities.PUBLIC)
val typeParameters = descriptor.getTypeConstructor().getParameters()
val newTypeParameters = ArrayList<TypeParameterDescriptor>(typeParameters.size())
val child = MutableClassDescriptor(descriptor.containingDeclaration, ClassKind.CLASS, false,
Name.special("<synthetic inheritor of ${descriptor.name}>"), descriptor.source)
child.modality = Modality.FINAL
child.visibility = Visibilities.PUBLIC
val typeParameters = descriptor.typeConstructor.parameters
val newTypeParameters = ArrayList<TypeParameterDescriptor>(typeParameters.size)
DescriptorSubstitutor.substituteTypeParameters(typeParameters, TypeSubstitution.EMPTY, child, newTypeParameters)
child.setTypeParameterDescriptors(typeParameters)
return Pair(child, newTypeParameters)
}
private fun FunctionDescriptor.findOverriddenFromDirectSuperClass(classDescriptor: ClassDescriptor): FunctionDescriptor? {
return this.getOverriddenDescriptors().firstOrNull { it.getContainingDeclaration() == classDescriptor }
return this.overriddenDescriptors.firstOrNull { it.containingDeclaration == classDescriptor }
}
private fun newType(classDescriptor: ClassDescriptor, typeArguments: List<TypeProjection>): KotlinType {
@@ -246,13 +246,13 @@ class CollectionStubMethodGenerator(
private fun generateMethodStub(signature: JvmMethodSignature, synthetic: Boolean) {
// TODO: investigate if it makes sense to generate abstract stubs in traits
var access = ACC_PUBLIC
if (descriptor.getKind() == ClassKind.INTERFACE) access = access or ACC_ABSTRACT
if (descriptor.kind == ClassKind.INTERFACE) access = access or ACC_ABSTRACT
if (synthetic) access = access or ACC_SYNTHETIC
val asmMethod = signature.getAsmMethod()
val genericSignature = if (synthetic) null else signature.getGenericsSignature()
val mv = v.newMethod(JvmDeclarationOrigin.NO_ORIGIN, access, asmMethod.getName(), asmMethod.getDescriptor(), genericSignature, null)
if (descriptor.getKind() != ClassKind.INTERFACE) {
val asmMethod = signature.asmMethod
val genericSignature = if (synthetic) null else signature.genericsSignature
val mv = v.newMethod(JvmDeclarationOrigin.NO_ORIGIN, access, asmMethod.name, asmMethod.descriptor, genericSignature, null)
if (descriptor.kind != ClassKind.INTERFACE) {
mv.visitCode()
AsmUtil.genThrow(InstructionAdapter(mv), "java/lang/UnsupportedOperationException", "Mutating immutable collection")
FunctionCodegen.endVisit(mv, "built-in stub for $signature", null)

View File

@@ -16,10 +16,11 @@
package org.jetbrains.kotlin.codegen
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.org.objectweb.asm.Type
import java.util.*
class DefaultCallMask(val size: Int) {
class DefaultCallArgs(val size: Int) {
val bits: BitSet = BitSet(size)
@@ -50,10 +51,15 @@ class DefaultCallMask(val size: Int) {
return masks
}
public fun generateOnStackIfNeeded(callGenerator: CallGenerator): Boolean {
fun generateOnStackIfNeeded(callGenerator: CallGenerator, isConstructor: Boolean): Boolean {
val toInts = toInts()
for (mask in toInts) {
callGenerator.putValueIfNeeded(null, Type.INT_TYPE, StackValue.constant(mask, Type.INT_TYPE))
if (!toInts.isEmpty()) {
for (mask in toInts) {
callGenerator.putValueIfNeeded(Type.INT_TYPE, StackValue.constant(mask, Type.INT_TYPE))
}
val parameterType = if (isConstructor) AsmTypes.DEFAULT_CONSTRUCTOR_MARKER else AsmTypes.OBJECT_TYPE
callGenerator.putValueIfNeeded(parameterType, StackValue.constant(null, parameterType))
}
return toInts.isNotEmpty();
}

View File

@@ -33,7 +33,7 @@ import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
* Generates Java overloads for functions and constructors that have the default
* parameter values substituted.
*/
public class DefaultParameterValueSubstitutor(val state: GenerationState) {
class DefaultParameterValueSubstitutor(val state: GenerationState) {
/**
* If all of the parameters of the specified constructor declare default values,
* generates a no-argument constructor that passes default values for all arguments.
@@ -118,19 +118,19 @@ public class DefaultParameterValueSubstitutor(val state: GenerationState) {
val typeMapper = state.typeMapper
val isStatic = AsmUtil.isStaticMethod(contextKind, functionDescriptor)
val flags = AsmUtil.getVisibilityAccessFlag(functionDescriptor) or (if (isStatic) Opcodes.ACC_STATIC else 0)
val remainingParameters = getRemainingParameters(functionDescriptor.getOriginal(), substituteCount)
val remainingParameters = getRemainingParameters(functionDescriptor.original, substituteCount)
val signature = typeMapper.mapSignature(functionDescriptor, contextKind, remainingParameters)
val mv = classBuilder.newMethod(OtherOrigin(methodElement, functionDescriptor), flags,
signature.getAsmMethod().getName(),
signature.getAsmMethod().getDescriptor(),
signature.getGenericsSignature(),
signature.asmMethod.name,
signature.asmMethod.descriptor,
signature.genericsSignature,
FunctionCodegen.getThrownExceptions(functionDescriptor, typeMapper))
AnnotationCodegen.forMethod(mv, typeMapper).genAnnotations(functionDescriptor, signature.getReturnType())
AnnotationCodegen.forMethod(mv, typeMapper).genAnnotations(functionDescriptor, signature.returnType)
remainingParameters.withIndex().forEach {
val annotationCodegen = AnnotationCodegen.forParameter(it.index, mv, typeMapper)
annotationCodegen.genAnnotations(it.value, signature.getValueParameters()[it.index].getAsmType())
annotationCodegen.genAnnotations(it.value, signature.valueParameters[it.index].asmType)
}
if (state.classBuilderMode == ClassBuilderMode.LIGHT_CLASSES) {
@@ -148,14 +148,14 @@ public class DefaultParameterValueSubstitutor(val state: GenerationState) {
v.load(thisIndex, methodOwner) // Load this on stack
}
else {
val delegateOwner = delegateFunctionDescriptor.getContainingDeclaration()
if (delegateOwner is ClassDescriptor && delegateOwner.isCompanionObject()) {
val delegateOwner = delegateFunctionDescriptor.containingDeclaration
if (delegateOwner is ClassDescriptor && delegateOwner.isCompanionObject) {
val singletonValue = StackValue.singleton(delegateOwner, typeMapper)
singletonValue.put(singletonValue.type, v);
}
}
val receiver = functionDescriptor.getExtensionReceiverParameter()
val receiver = functionDescriptor.extensionReceiverParameter
if (receiver != null) {
val receiverType = typeMapper.mapType(receiver)
val receiverIndex = frameMap.enter(receiver, receiverType)
@@ -167,8 +167,8 @@ public class DefaultParameterValueSubstitutor(val state: GenerationState) {
var mask = 0
val masks = arrayListOf<Int>()
for (parameterDescriptor in functionDescriptor.getValueParameters()) {
val paramType = typeMapper.mapType(parameterDescriptor.getType())
for (parameterDescriptor in functionDescriptor.valueParameters) {
val paramType = typeMapper.mapType(parameterDescriptor.type)
if (parameterDescriptor in remainingParameters) {
val index = frameMap.getIndex(parameterDescriptor)
StackValue.local(index, paramType).put(paramType, v)
@@ -184,50 +184,50 @@ public class DefaultParameterValueSubstitutor(val state: GenerationState) {
}
}
masks.add(mask)
for (m in masks) {
v.iconst(m)
}
// constructors with default arguments has last synthetic argument of specific type
if (functionDescriptor is ConstructorDescriptor) {
v.aconst(null)
}
// for default constructors: just marks default constructor (see DEFAULT_CONSTRUCTOR_MARKER)
// for default methods: contains MethodHandle for super calls ('null' cause not super call)
v.aconst(null)
val defaultMethod = typeMapper.mapDefaultMethod(delegateFunctionDescriptor, contextKind)
if (functionDescriptor is ConstructorDescriptor) {
v.invokespecial(methodOwner.getInternalName(), defaultMethod.getName(), defaultMethod.getDescriptor(), false)
v.invokespecial(methodOwner.internalName, defaultMethod.name, defaultMethod.descriptor, false)
}
else {
v.invokestatic(methodOwner.getInternalName(), defaultMethod.getName(), defaultMethod.getDescriptor(), false)
v.invokestatic(methodOwner.internalName, defaultMethod.name, defaultMethod.descriptor, false)
}
v.areturn(signature.getReturnType())
v.areturn(signature.returnType)
FunctionCodegen.endVisit(mv, null, methodElement)
}
private fun getRemainingParameters(functionDescriptor: FunctionDescriptor,
substituteCount: Int): List<ValueParameterDescriptor> {
var remainingCount = functionDescriptor.countDefaultParameters() - substituteCount
return functionDescriptor.getValueParameters().filter { !it.declaresDefaultValue() || --remainingCount >= 0 }
return functionDescriptor.valueParameters.filter { !it.declaresDefaultValue() || --remainingCount >= 0 }
}
private fun isEmptyConstructorNeeded(constructorDescriptor: ConstructorDescriptor, classOrObject: KtClassOrObject): Boolean {
val classDescriptor = constructorDescriptor.getContainingDeclaration()
if (classDescriptor.getKind() != ClassKind.CLASS) return false
val classDescriptor = constructorDescriptor.containingDeclaration
if (classDescriptor.kind != ClassKind.CLASS) return false
if (classOrObject.isLocal()) return false
if (CodegenBinding.canHaveOuter(state.bindingContext, classDescriptor)) return false
if (Visibilities.isPrivate(classDescriptor.getVisibility()) || Visibilities.isPrivate(constructorDescriptor.getVisibility()))
if (Visibilities.isPrivate(classDescriptor.visibility) || Visibilities.isPrivate(constructorDescriptor.visibility))
return false
if (constructorDescriptor.getValueParameters().isEmpty()) return false
if (constructorDescriptor.valueParameters.isEmpty()) return false
if (classOrObject is KtClass && hasSecondaryConstructorsWithNoParameters(classOrObject)) return false
return constructorDescriptor.getValueParameters().all { it.declaresDefaultValue() }
return constructorDescriptor.valueParameters.all { it.declaresDefaultValue() }
}
private fun hasSecondaryConstructorsWithNoParameters(klass: KtClass) =
klass.getSecondaryConstructors().any { it.getValueParameters().isEmpty() }
klass.getSecondaryConstructors().any { it.valueParameters.isEmpty() }
}

View File

@@ -25,18 +25,18 @@ import org.jetbrains.kotlin.resolve.jvm.diagnostics.RawSignature
import org.jetbrains.org.objectweb.asm.FieldVisitor
import org.jetbrains.org.objectweb.asm.MethodVisitor
public abstract class DelegatingClassBuilderFactory(
abstract class DelegatingClassBuilderFactory(
protected val delegate: ClassBuilderFactory
) : ClassBuilderFactory by delegate {
abstract override fun newClassBuilder(origin: JvmDeclarationOrigin): DelegatingClassBuilder
public override fun asBytes(builder: ClassBuilder?): ByteArray? {
override fun asBytes(builder: ClassBuilder?): ByteArray? {
return delegate.asBytes((builder as DelegatingClassBuilder).getDelegate())
}
public override fun asText(builder: ClassBuilder?): String? {
override fun asText(builder: ClassBuilder?): String? {
return delegate.asText((builder as DelegatingClassBuilder).getDelegate())
}
}

View File

@@ -24,7 +24,8 @@ import com.intellij.psi.tree.IElementType;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.Stack;
import kotlin.CollectionsKt;
import kotlin.Pair;
import kotlin.collections.CollectionsKt;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull;
@@ -39,7 +40,6 @@ import org.jetbrains.kotlin.codegen.inline.*;
import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicMethod;
import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicMethods;
import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicPropertyGetter;
import org.jetbrains.kotlin.codegen.intrinsics.TypeIntrinsics;
import org.jetbrains.kotlin.codegen.pseudoInsns.PseudoInsnsKt;
import org.jetbrains.kotlin.codegen.signature.BothSignatureWriter;
import org.jetbrains.kotlin.codegen.state.GenerationState;
@@ -54,10 +54,10 @@ import org.jetbrains.kotlin.incremental.components.NoLookupLocation;
import org.jetbrains.kotlin.jvm.RuntimeAssertionInfo;
import org.jetbrains.kotlin.jvm.bindingContextSlices.BindingContextSlicesKt;
import org.jetbrains.kotlin.lexer.KtTokens;
import org.jetbrains.kotlin.load.java.JvmAbi;
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;
@@ -93,15 +93,13 @@ import java.util.*;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isInt;
import static org.jetbrains.kotlin.codegen.AsmUtil.*;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.couldUseDirectAccessToProperty;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isJvmInterface;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.*;
import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.*;
import static org.jetbrains.kotlin.resolve.BindingContext.*;
import static org.jetbrains.kotlin.resolve.BindingContextUtils.*;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.isEnumEntry;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.isObject;
import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.*;
import static org.jetbrains.kotlin.resolve.jvm.annotations.AnnotationUtilKt.hasJvmFieldAnnotation;
import static org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils.isFunctionExpression;
import static org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils.isFunctionLiteral;
import static org.jetbrains.org.objectweb.asm.Opcodes.*;
@@ -481,7 +479,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
markLineNumber(expression, isStatement);
v.mark(end);
return Unit.INSTANCE$;
return Unit.INSTANCE;
}
});
}
@@ -669,7 +667,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 +685,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());
@@ -1067,7 +1065,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
Type asmLoopRangeType = asmType(loopRangeType);
Collection<PropertyDescriptor> incrementProp =
loopRangeType.getMemberScope().getContributedVariables(Name.identifier("increment"), NoLookupLocation.FROM_BACKEND);
loopRangeType.getMemberScope().getContributedVariables(Name.identifier("step"), NoLookupLocation.FROM_BACKEND);
assert incrementProp.size() == 1 : loopRangeType + " " + incrementProp.size();
incrementType = asmType(incrementProp.iterator().next().getType());
@@ -1295,7 +1293,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
}
v.invokevirtual("java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false);
return Unit.INSTANCE$;
return Unit.INSTANCE;
}
});
}
@@ -1332,7 +1330,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());
}
@@ -1434,7 +1432,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
JvmMethodSignature constructor = typeMapper.mapSignature(SamCodegenUtil.resolveSamAdapter(constructorDescriptor));
v.invokespecial(type.getInternalName(), "<init>", constructor.getAsmMethod().getDescriptor(), false);
return Unit.INSTANCE$;
return Unit.INSTANCE;
}
});
}
@@ -1552,7 +1550,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
for (Function<StackValue, Void> task : Lists.reverse(leaveTasks)) {
task.fun(value);
}
return Unit.INSTANCE$;
return Unit.INSTANCE;
}
});
}
@@ -1569,9 +1567,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 +1607,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 +2070,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;
}
@@ -2116,11 +2117,11 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
DeclarationDescriptor containingDeclaration = propertyDescriptor.getContainingDeclaration();
FieldAccessorKind fieldAccessorKind = FieldAccessorKind.NORMAL;
boolean isBackingFieldInClassCompanion = AsmUtil.isPropertyWithBackingFieldInOuterClass(propertyDescriptor);
boolean isBackingFieldInClassCompanion = JvmAbi.isPropertyWithBackingFieldInOuterClass(propertyDescriptor);
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) ||
@@ -2140,7 +2141,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
PropertyDescriptor originalPropertyDescriptor = DescriptorUtils.unwrapFakeOverride(propertyDescriptor);
if (fieldAccessorKind != FieldAccessorKind.NORMAL) {
int flags = AsmUtil.getVisibilityForSpecialPropertyBackingField(propertyDescriptor, isDelegatedProperty);
int flags = AsmUtil.getVisibilityForBackingField(propertyDescriptor, isDelegatedProperty);
skipPropertyAccessors = (flags & ACC_PRIVATE) == 0 || skipAccessorsForPrivateFieldInOuterClass;
if (!skipPropertyAccessors) {
//noinspection ConstantConditions
@@ -2161,18 +2162,12 @@ 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);
PropertyGetterDescriptor getter = propertyDescriptor.getGetter();
if (getter != null && !hasJvmFieldAnnotation(propertyDescriptor)) {
if (getter != null && !isConstOrHasJvmFieldAnnotation(propertyDescriptor)) {
callableGetter = typeMapper.mapToCallableMethod(getter, isSuper);
}
}
@@ -2181,7 +2176,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
PropertySetterDescriptor setter = propertyDescriptor.getSetter();
if (setter != null &&
!couldUseDirectAccessToProperty(propertyDescriptor, false, isDelegatedProperty, context) &&
!hasJvmFieldAnnotation(propertyDescriptor)) {
!isConstOrHasJvmFieldAnnotation(propertyDescriptor)) {
callableSetter = typeMapper.mapToCallableMethod(setter, isSuper);
}
}
@@ -2251,8 +2246,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 +2295,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 +2309,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 +2321,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);
}
@@ -2401,7 +2378,8 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@NotNull CallGenerator callGenerator,
@NotNull ArgumentGenerator argumentGenerator
) {
if (!(resolvedCall.getResultingDescriptor() instanceof ConstructorDescriptor)) { // otherwise already
boolean isConstructor = resolvedCall.getResultingDescriptor() instanceof ConstructorDescriptor;
if (!isConstructor) { // otherwise already
receiver = StackValue.receiver(resolvedCall, receiver, this, callableMethod);
receiver.put(receiver.type, v);
callableMethod.afterReceiverGeneration(v);
@@ -2412,7 +2390,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
List<ResolvedValueArgument> valueArguments = resolvedCall.getValueArgumentsByIndex();
assert valueArguments != null : "Failed to arrange value arguments by index: " + resolvedCall.getResultingDescriptor();
DefaultCallMask masks =
DefaultCallArgs defaultArgs =
argumentGenerator.generate(valueArguments, new ArrayList<ResolvedValueArgument>(resolvedCall.getValueArguments().values()));
if (tailRecursionCodegen.isTailRecursion(resolvedCall)) {
@@ -2420,26 +2398,32 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
return;
}
boolean defaultMaskWasGenerated = masks.generateOnStackIfNeeded(callGenerator);
boolean defaultMaskWasGenerated = defaultArgs.generateOnStackIfNeeded(callGenerator, isConstructor);
// Extra constructor marker argument
if (callableMethod instanceof CallableMethod) {
List<JvmMethodParameterSignature> callableParameters = ((CallableMethod) callableMethod).getValueParameters();
for (JvmMethodParameterSignature parameter: callableParameters) {
if (parameter.getKind() == JvmMethodParameterKind.CONSTRUCTOR_MARKER) {
callGenerator.putValueIfNeeded(null, parameter.getAsmType(), StackValue.constant(null, parameter.getAsmType()));
callGenerator.putValueIfNeeded(parameter.getAsmType(), StackValue.constant(null, parameter.getAsmType()));
}
}
}
callGenerator.genCall(callableMethod, resolvedCall, defaultMaskWasGenerated, this);
KotlinType returnType = resolvedCall.getResultingDescriptor().getReturnType();
if (returnType != null && KotlinBuiltIns.isNothing(returnType)) {
v.aconst(null);
v.athrow();
}
}
@NotNull
protected CallGenerator getOrCreateCallGenerator(
private CallGenerator getOrCreateCallGenerator(
@NotNull CallableDescriptor descriptor,
@Nullable KtElement callElement,
@Nullable ReifiedTypeParameterMappings reifiedTypeParameterMappings
@Nullable TypeParameterMappings typeParameterMappings
) {
if (callElement == null) return defaultCallGenerator;
@@ -2451,25 +2435,25 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
if (!isInline) return defaultCallGenerator;
SimpleFunctionDescriptor original = DescriptorUtils.unwrapFakeOverride((SimpleFunctionDescriptor) descriptor.getOriginal());
return new InlineCodegen(this, state, original, callElement, reifiedTypeParameterMappings);
return new InlineCodegen(this, state, original, callElement, typeParameterMappings);
}
@NotNull
public CallGenerator getOrCreateCallGenerator(@NotNull FunctionDescriptor descriptor, @Nullable KtNamedFunction function) {
protected CallGenerator getOrCreateCallGeneratorForDefaultImplBody(@NotNull FunctionDescriptor descriptor, @Nullable KtNamedFunction function) {
return getOrCreateCallGenerator(descriptor, function, null);
}
@NotNull
private CallGenerator getOrCreateCallGenerator(@NotNull ResolvedCall<?> resolvedCall) {
CallGenerator getOrCreateCallGenerator(@NotNull ResolvedCall<?> resolvedCall) {
Map<TypeParameterDescriptor, KotlinType> typeArguments = resolvedCall.getTypeArguments();
ReifiedTypeParameterMappings mappings = new ReifiedTypeParameterMappings();
TypeParameterMappings mappings = new TypeParameterMappings();
for (Map.Entry<TypeParameterDescriptor, KotlinType> entry : typeArguments.entrySet()) {
TypeParameterDescriptor key = entry.getKey();
if (!key.isReified()) continue;
KotlinType type = entry.getValue();
TypeParameterDescriptor parameterDescriptor = TypeUtils.getTypeParameterDescriptorOrNull(type);
if (parameterDescriptor == null) {
KotlinType type = TypeUtils.uncaptureTypeForInlineMapping(entry.getValue());
Pair<TypeParameterDescriptor, ReificationArgument> typeParameterAndReificationArgument = extractReificationArgument(type);
if (typeParameterAndReificationArgument == null) {
// type is not generic
BothSignatureWriter signatureWriter = new BothSignatureWriter(BothSignatureWriter.Mode.TYPE);
Type asmType = typeMapper.mapTypeParameter(type, signatureWriter);
@@ -2478,14 +2462,13 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
key.getName().getIdentifier(),
type,
asmType,
signatureWriter.toString()
);
signatureWriter.toString(),
key.isReified());
}
else {
mappings.addParameterMappingToNewParameter(
key.getName().getIdentifier(),
parameterDescriptor.getName().getIdentifier()
);
mappings.addParameterMappingForFurtherReification(
key.getName().getIdentifier(), type,
typeParameterAndReificationArgument.getSecond(), key.isReified());
}
}
return getOrCreateCallGenerator(
@@ -2493,8 +2476,26 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
);
}
@Nullable
private static Pair<TypeParameterDescriptor, ReificationArgument> extractReificationArgument(@NotNull KotlinType type) {
int arrayDepth = 0;
boolean isNullable = type.isMarkedNullable();
while (KotlinBuiltIns.isArray(type)) {
arrayDepth++;
type = type.getArguments().get(0).getType();
}
TypeParameterDescriptor parameterDescriptor = TypeUtils.getTypeParameterDescriptorOrNull(type);
if (parameterDescriptor == null) return null;
return new Pair<TypeParameterDescriptor, ReificationArgument>(
parameterDescriptor,
new ReificationArgument(parameterDescriptor.getName().asString(), isNullable, arrayDepth));
}
@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)) {
@@ -2746,19 +2747,17 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
VariableDescriptor variableDescriptor = bindingContext.get(VARIABLE, expression);
if (variableDescriptor != null) {
return generatePropertyReference(expression, variableDescriptor, (VariableDescriptor) resolvedCall.getResultingDescriptor(),
resolvedCall.getDispatchReceiver());
return generatePropertyReference(expression, variableDescriptor, resolvedCall);
}
throw new UnsupportedOperationException("Unsupported callable reference expression: " + expression.getText());
}
@NotNull
public StackValue generatePropertyReference(
private StackValue generatePropertyReference(
@NotNull KtElement element,
@NotNull VariableDescriptor variableDescriptor,
@NotNull VariableDescriptor target,
@NotNull ReceiverValue dispatchReceiver
@NotNull ResolvedCall<?> resolvedCall
) {
ClassDescriptor classDescriptor = CodegenBinding.anonymousClassForCallable(bindingContext, variableDescriptor);
@@ -2770,7 +2769,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
PropertyReferenceCodegen codegen = new PropertyReferenceCodegen(
state, parentCodegen, context.intoAnonymousClass(classDescriptor, this, OwnerKind.IMPLEMENTATION),
element, classBuilder, classDescriptor, target, dispatchReceiver
element, classBuilder, resolvedCall
);
codegen.generate();
@@ -2795,13 +2794,13 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
"Non-reified type parameter under ::class should be rejected by type checker: " + typeParameterDescriptor;
assert codegen != null :
"Reference to member of reified type should be rejected by type checker " + typeParameterDescriptor;
codegen.putReifierMarkerIfTypeIsReifiedParameter(type, ReifiedTypeInliner.JAVA_CLASS_MARKER_METHOD_NAME);
codegen.putReifiedOperationMarkerIfTypeIsReifiedParameter(type, ReifiedTypeInliner.OperationKind.JAVA_CLASS);
}
putJavaLangClassInstance(v, classAsmType);
wrapJavaClassIntoKClass(v);
return Unit.INSTANCE$;
return Unit.INSTANCE;
}
});
}
@@ -3260,7 +3259,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
value.store(StackValue.onStack(storeType), v, true);
return Unit.INSTANCE$;
return Unit.INSTANCE;
}
});
}
@@ -3276,7 +3275,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 +3292,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);
@@ -3385,7 +3384,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
CallableMethod method = typeMapper.mapToCallableMethod(constructor, false);
invokeMethodWithArguments(method, resolvedCall, StackValue.none());
return Unit.INSTANCE$;
return Unit.INSTANCE;
}
});
}
@@ -3401,7 +3400,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
public Unit invoke(InstructionAdapter v) {
gen(sizeExpression, Type.INT_TYPE);
newArrayInstruction(arrayType);
return Unit.INSTANCE$;
return Unit.INSTANCE;
}
});
}
@@ -3409,9 +3408,9 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
public void newArrayInstruction(@NotNull KotlinType arrayType) {
if (KotlinBuiltIns.isArray(arrayType)) {
KotlinType elementJetType = arrayType.getArguments().get(0).getType();
putReifierMarkerIfTypeIsReifiedParameter(
putReifiedOperationMarkerIfTypeIsReifiedParameter(
elementJetType,
ReifiedTypeInliner.NEW_ARRAY_MARKER_METHOD_NAME
ReifiedTypeInliner.OperationKind.NEW_ARRAY
);
v.newarray(boxType(asmType(elementJetType)));
}
@@ -3478,10 +3477,6 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
ResolvedCall<FunctionDescriptor> resolvedCall = isGetter ? resolvedGetCall : resolvedSetCall;
assert resolvedCall != null : "couldn't find resolved call: " + expression.getText();
ArgumentGenerator argumentGenerator = new CallBasedArgumentGenerator(
this, defaultCallGenerator, resolvedCall.getResultingDescriptor().getValueParameters(), callable.getValueParameterTypes()
);
List<ResolvedValueArgument> valueArguments = resolvedCall.getValueArgumentsByIndex();
assert valueArguments != null : "Failed to arrange value arguments by index: " + operationDescriptor;
@@ -3492,7 +3487,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}
return new StackValue.CollectionElementReceiver(
callable, receiver, resolvedGetCall, resolvedSetCall, isGetter, this, argumentGenerator, valueArguments
callable, receiver, resolvedGetCall, resolvedSetCall, isGetter, this, valueArguments
);
}
@@ -3640,7 +3635,7 @@ The "returned" value of try expression with no finally is either the last expres
if (finallyBlock != null) {
blockStackElements.pop();
}
return Unit.INSTANCE$;
return Unit.INSTANCE;
}
});
}
@@ -3688,28 +3683,19 @@ The "returned" value of try expression with no finally is either the last expres
StackValue.putUnitInstance(v);
}
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);
}
}
else {
v.dup();
generateInstanceOfInstruction(rightType);
Label ok = new Label();
v.ifne(ok);
v.pop();
v.aconst(null);
v.mark(ok);
boolean safeAs = opToken == KtTokens.AS_SAFE;
Type type = boxType(asmType(rightType));
if (TypeUtils.isReifiedTypeParameter(rightType)) {
putReifiedOperationMarkerIfTypeIsReifiedParameter(rightType,
safeAs ? ReifiedTypeInliner.OperationKind.SAFE_AS
: ReifiedTypeInliner.OperationKind.AS);
v.checkcast(type);
return Unit.INSTANCE;
}
generateCheckCastInstruction(rightType, opToken == KtTokens.AS_SAFE);
return Unit.INSTANCE$;
CodegenUtilKt.generateAsCast(v, rightType, type, safeAs);
return Unit.INSTANCE;
}
});
}
@@ -3747,11 +3733,11 @@ The "returned" value of try expression with no finally is either the last expres
private StackValue generateIsCheck(StackValue expressionToMatch, KtTypeReference typeReference, boolean negated) {
KotlinType jetType = bindingContext.get(TYPE, typeReference);
markStartLineNumber(typeReference);
StackValue value = generateInstanceOf(expressionToMatch, jetType, false);
StackValue value = generateIsCheck(expressionToMatch, jetType, false);
return negated ? StackValue.not(value) : value;
}
private StackValue generateInstanceOf(final StackValue expressionToGen, final KotlinType kotlinType, final boolean leaveExpressionOnStack) {
private StackValue generateIsCheck(final StackValue expressionToGen, final KotlinType kotlinType, final boolean leaveExpressionOnStack) {
return StackValue.operation(Type.BOOLEAN_TYPE, new Function1<InstructionAdapter, Unit>() {
@Override
public Unit invoke(InstructionAdapter v) {
@@ -3759,46 +3745,35 @@ 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>() {
@Override
public Unit invoke(InstructionAdapter adapter) {
generateInstanceOfInstruction(kotlinType);
return Unit.INSTANCE;
}
});
Type type = boxType(asmType(kotlinType));
if (TypeUtils.isReifiedTypeParameter(kotlinType)) {
putReifiedOperationMarkerIfTypeIsReifiedParameter(kotlinType, ReifiedTypeInliner.OperationKind.IS);
v.instanceOf(type);
return null;
}
CodegenUtilKt.generateIsCheck(v, kotlinType, type);
return null;
}
});
}
private void generateInstanceOfInstruction(@NotNull KotlinType jetType) {
Type type = boxType(asmType(jetType));
putReifierMarkerIfTypeIsReifiedParameter(jetType, ReifiedTypeInliner.INSTANCEOF_MARKER_METHOD_NAME);
TypeIntrinsics.instanceOf(v, jetType, type);
}
@NotNull
private StackValue generateCheckCastInstruction(@NotNull KotlinType jetType, boolean safeAs) {
Type type = boxType(asmType(jetType));
putReifierMarkerIfTypeIsReifiedParameter(jetType,
safeAs ? ReifiedTypeInliner.SAFE_CHECKCAST_MARKER_METHOD_NAME
: ReifiedTypeInliner.CHECKCAST_MARKER_METHOD_NAME);
TypeIntrinsics.checkcast(v, jetType, type, safeAs);
return StackValue.onStack(type);
}
public void putReifierMarkerIfTypeIsReifiedParameter(@NotNull KotlinType type, @NotNull String markerMethodName) {
TypeParameterDescriptor typeParameterDescriptor = TypeUtils.getTypeParameterDescriptorOrNull(type);
if (typeParameterDescriptor != null && typeParameterDescriptor.isReified()) {
public void putReifiedOperationMarkerIfTypeIsReifiedParameter(
@NotNull KotlinType type, @NotNull ReifiedTypeInliner.OperationKind operationKind
) {
Pair<TypeParameterDescriptor, ReificationArgument> typeParameterAndReificationArgument = extractReificationArgument(type);
if (typeParameterAndReificationArgument != null && typeParameterAndReificationArgument.getFirst().isReified()) {
TypeParameterDescriptor typeParameterDescriptor = typeParameterAndReificationArgument.getFirst();
if (typeParameterDescriptor.getContainingDeclaration() != context.getContextDescriptor()) {
parentCodegen.getReifiedTypeParametersUsages().
addUsedReifiedParameter(typeParameterDescriptor.getName().asString());
}
v.visitLdcInsn(typeParameterDescriptor.getName().asString());
v.iconst(operationKind.getId());
v.visitLdcInsn(typeParameterAndReificationArgument.getSecond().asString());
v.invokestatic(
IntrinsicMethods.INTRINSICS_CLASS_NAME, markerMethodName,
Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class)), false
IntrinsicMethods.INTRINSICS_CLASS_NAME, ReifiedTypeInliner.REIFIED_OPERATION_MARKER_METHOD_NAME,
Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE, Type.getType(String.class)), false
);
}
}
@@ -3821,11 +3796,12 @@ 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$;
return Unit.INSTANCE;
}
int subjectLocal = expr != null ? myFrameMap.enterTemp(subjectType) : -1;
@@ -3868,9 +3844,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 +3857,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

@@ -33,17 +33,12 @@ public class FieldInfo {
@NotNull
public static FieldInfo createForSingleton(@NotNull ClassDescriptor classDescriptor, @NotNull JetTypeMapper typeMapper) {
return createForSingleton(classDescriptor, typeMapper, false);
}
@NotNull
public static FieldInfo createForSingleton(@NotNull ClassDescriptor classDescriptor, @NotNull JetTypeMapper typeMapper, boolean oldSingleton) {
if (!classDescriptor.getKind().isSingleton() || DescriptorUtils.isEnumEntry(classDescriptor)) {
throw new UnsupportedOperationException("Can't create singleton field for class: " + classDescriptor);
}
if (isNonCompanionObject(classDescriptor) || COMPANION_OBJECT_MAPPING.hasMappingToObject(classDescriptor)) {
return createSingletonViaInstance(classDescriptor, typeMapper, oldSingleton);
return createSingletonViaInstance(classDescriptor, typeMapper);
}
else {
ClassDescriptor ownerDescriptor = DescriptorUtils.getParentOfType(classDescriptor, ClassDescriptor.class);
@@ -56,11 +51,10 @@ public class FieldInfo {
@NotNull
public static FieldInfo createSingletonViaInstance(
@NotNull ClassDescriptor classDescriptor,
@NotNull JetTypeMapper typeMapper,
boolean oldSingleton
@NotNull JetTypeMapper typeMapper
) {
Type type = typeMapper.mapType(classDescriptor);
return new FieldInfo(type, type, oldSingleton ? JvmAbi.DEPRECATED_INSTANCE_FIELD : JvmAbi.INSTANCE_FIELD, true);
return new FieldInfo(type, type, JvmAbi.INSTANCE_FIELD, true);
}
@NotNull

View File

@@ -47,7 +47,7 @@ public class FrameMap {
myVarSizes.remove(descriptor);
int oldIndex = myVarIndex.remove(descriptor);
if (oldIndex != myMaxIndex) {
throw new IllegalStateException("descriptor can be left only if it is last");
throw new IllegalStateException("Descriptor can be left only if it is last: " + descriptor);
}
return oldIndex;
}

View File

@@ -21,7 +21,6 @@ import com.intellij.psi.PsiElement;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -29,7 +28,6 @@ import org.jetbrains.kotlin.backend.common.bridges.Bridge;
import org.jetbrains.kotlin.backend.common.bridges.ImplKt;
import org.jetbrains.kotlin.codegen.annotation.AnnotatedWithOnlyTargetedAnnotations;
import org.jetbrains.kotlin.codegen.context.*;
import org.jetbrains.kotlin.codegen.intrinsics.TypeIntrinsics;
import org.jetbrains.kotlin.codegen.optimization.OptimizationMethodVisitor;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.codegen.state.JetTypeMapper;
@@ -40,7 +38,6 @@ import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget;
import org.jetbrains.kotlin.jvm.RuntimeAssertionInfo;
import org.jetbrains.kotlin.load.java.BuiltinMethodsWithSpecialGenericSignature;
import org.jetbrains.kotlin.load.java.JvmAbi;
import org.jetbrains.kotlin.load.java.JvmAnnotationNames;
import org.jetbrains.kotlin.load.java.SpecialBuiltinMembers;
import org.jetbrains.kotlin.load.kotlin.nativeDeclarations.NativeKt;
import org.jetbrains.kotlin.name.FqName;
@@ -60,10 +57,7 @@ import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodParameterSignature
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.kotlin.types.TypeUtils;
import org.jetbrains.org.objectweb.asm.AnnotationVisitor;
import org.jetbrains.org.objectweb.asm.Label;
import org.jetbrains.org.objectweb.asm.MethodVisitor;
import org.jetbrains.org.objectweb.asm.Type;
import org.jetbrains.org.objectweb.asm.*;
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
import org.jetbrains.org.objectweb.asm.commons.Method;
import org.jetbrains.org.objectweb.asm.util.TraceMethodVisitor;
@@ -77,11 +71,12 @@ import java.util.Set;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isNullableAny;
import static org.jetbrains.kotlin.codegen.AsmUtil.*;
import static org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings.*;
import static org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings.METHOD_FOR_FUNCTION;
import static org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.DECLARATION;
import static org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget.*;
import static org.jetbrains.kotlin.resolve.DescriptorToSourceUtils.getSourceFromDescriptor;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.*;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.getSuperClassDescriptor;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.isInterface;
import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.OBJECT_TYPE;
import static org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils.*;
import static org.jetbrains.org.objectweb.asm.Opcodes.*;
@@ -161,7 +156,7 @@ public class FunctionCodegen {
int flags = getMethodAsmFlags(functionDescriptor, contextKind);
boolean isNative = NativeKt.hasNativeAnnotation(functionDescriptor);
if (isNative && owner instanceof DelegatingFacadeContext) {
if (isNative && owner instanceof MultifileClassFacadeContext) {
// Native methods are only defined in facades and do not need package part implementations
return;
}
@@ -172,10 +167,6 @@ public class FunctionCodegen {
jvmSignature.getGenericsSignature(),
getThrownExceptions(functionDescriptor, typeMapper));
String implClassName = CodegenContextUtil.getImplementationClassShortName(owner);
if (implClassName != null) {
v.getSerializationBindings().put(IMPL_CLASS_NAME_FOR_CALLABLE, functionDescriptor, implClassName);
}
if (CodegenContextUtil.isImplClassOwner(owner)) {
v.getSerializationBindings().put(METHOD_FOR_FUNCTION, functionDescriptor, asmMethod);
}
@@ -221,8 +212,6 @@ public class FunctionCodegen {
}
endVisit(mv, null, origin.getElement());
methodContext.recordSyntheticAccessorIfNeeded(functionDescriptor, bindingContext);
}
private void generateMethodAnnotations(
@@ -239,22 +228,6 @@ public class FunctionCodegen {
else {
annotationCodegen.genAnnotations(functionDescriptor, asmMethod.getReturnType());
}
writePackageFacadeMethodAnnotationsIfNeeded(mv);
}
private void writePackageFacadeMethodAnnotationsIfNeeded(MethodVisitor mv) {
if (owner instanceof PackageFacadeContext) {
PackageFacadeContext packageFacadeContext = (PackageFacadeContext) owner;
Type delegateToClassType = packageFacadeContext.getPublicFacadeType();
if (delegateToClassType != null) {
String className = delegateToClassType.getClassName();
AnnotationVisitor
av = mv.visitAnnotation(AsmUtil.asmDescByFqNameWithoutInnerClasses(JvmAnnotationNames.KOTLIN_DELEGATED_METHOD), true);
av.visit(JvmAnnotationNames.IMPLEMENTATION_CLASS_NAME_FIELD_NAME, className);
av.visitEnd();
}
}
}
private void generateParameterAnnotations(
@@ -275,9 +248,6 @@ public class FunctionCodegen {
if (kind == JvmMethodParameterKind.VALUE) {
ValueParameterDescriptor parameter = iterator.next();
if (parameter.getIndex() != i) {
v.getSerializationBindings().put(INDEX_FOR_VALUE_PARAMETER, parameter, i);
}
AnnotationCodegen annotationCodegen = AnnotationCodegen.forParameter(i, mv, typeMapper);
if (functionDescriptor instanceof PropertySetterDescriptor) {
@@ -366,18 +336,18 @@ public class FunctionCodegen {
int functionFakeIndex = -1;
int lambdaFakeIndex = -1;
if (context.getParentContext() instanceof DelegatingFacadeContext) {
generateFacadeDelegateMethodBody(mv, signature.getAsmMethod(), (DelegatingFacadeContext) context.getParentContext());
if (context.getParentContext() instanceof MultifileClassFacadeContext) {
generateFacadeDelegateMethodBody(mv, signature.getAsmMethod(), (MultifileClassFacadeContext) context.getParentContext());
methodEnd = new Label();
}
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 +368,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 +376,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) {
@@ -470,9 +440,9 @@ public class FunctionCodegen {
private static void generateFacadeDelegateMethodBody(
@NotNull MethodVisitor mv,
@NotNull Method asmMethod,
@NotNull DelegatingFacadeContext context
@NotNull MultifileClassFacadeContext context
) {
generateDelegateToMethodBody(true, mv, asmMethod, context.getDelegateToClassType().getInternalName());
generateDelegateToMethodBody(true, mv, asmMethod, context.getFilePartType().getInternalName());
}
private static void generateDelegateToMethodBody(
@@ -555,7 +525,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 +559,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();
@@ -695,9 +665,9 @@ public class FunctionCodegen {
AnnotationCodegen.forMethod(mv, typeMapper).genAnnotations(functionDescriptor, defaultMethod.getReturnType());
if (state.getClassBuilderMode() == ClassBuilderMode.FULL) {
if (this.owner instanceof DelegatingFacadeContext) {
if (this.owner instanceof MultifileClassFacadeContext) {
mv.visitCode();
generateFacadeDelegateMethodBody(mv, defaultMethod, (DelegatingFacadeContext) this.owner);
generateFacadeDelegateMethodBody(mv, defaultMethod, (MultifileClassFacadeContext) this.owner);
endVisit(mv, "default method delegation", getSourceFromDescriptor(functionDescriptor));
}
else {
@@ -705,6 +675,15 @@ public class FunctionCodegen {
generateDefaultImplBody(owner, functionDescriptor, mv, loadStrategy, function, memberCodegen);
endVisit(mv, "default method", getSourceFromDescriptor(functionDescriptor));
}
generateOldDefaultForFun(defaultMethod,
JvmDeclarationOriginKt.Synthetic(function, functionDescriptor),
flags,
getThrownExceptions(functionDescriptor, typeMapper),
(owner.getContextKind() == OwnerKind.DEFAULT_IMPLS ?
typeMapper.mapDefaultImpls((ClassDescriptor) functionDescriptor.getContainingDeclaration()) :
typeMapper.mapImplementationOwner(functionDescriptor)).getInternalName()
);
}
}
@@ -724,7 +703,7 @@ public class FunctionCodegen {
ExpressionCodegen codegen = new ExpressionCodegen(mv, frameMap, signature.getReturnType(), methodContext, state, parentCodegen);
CallGenerator generator = codegen.getOrCreateCallGenerator(functionDescriptor, function);
CallGenerator generator = codegen.getOrCreateCallGeneratorForDefaultImplBody(functionDescriptor, function);
loadExplicitArgumentsOnStack(OBJECT_TYPE, isStatic, signature, generator);
@@ -759,7 +738,7 @@ public class FunctionCodegen {
iv.mark(loadArg);
}
generator.putValueIfNeeded(parameterDescriptor, type, StackValue.local(parameterIndex, type));
generator.putValueIfNeeded(type, StackValue.local(parameterIndex, type));
}
CallableMethod method = state.getTypeMapper().mapToCallableMethod(functionDescriptor, false);
@@ -769,6 +748,38 @@ public class FunctionCodegen {
iv.areturn(signature.getReturnType());
}
private void generateOldDefaultForFun(
Method newDefaultMethod,
JvmDeclarationOrigin origin,
int flags,
String[] exceptions,
String owner
) {
if ("<init>".equals(newDefaultMethod.getName())) {
return;
}
String oldSignature = newDefaultMethod.getDescriptor().replaceFirst("Ljava/lang/Object;\\)", ")");
MethodVisitor mv = v.newMethod(
origin,
flags,
newDefaultMethod.getName(),
oldSignature,
null,
exceptions
);
mv.visitCode();
int index = 0;
InstructionAdapter iv = new InstructionAdapter(mv);
for (Type type: Type.getArgumentTypes(oldSignature)) {
iv.load(index, type);
index += type.getSize();
}
iv.aconst(null);
iv.visitMethodInsn(Opcodes.INVOKESTATIC, owner, newDefaultMethod.getName(), newDefaultMethod.getDescriptor(), false);
iv.areturn(newDefaultMethod.getReturnType());
mv.visitEnd();
}
@NotNull
private static FrameMap createFrameMap(
@NotNull GenerationState state,
@@ -808,14 +819,14 @@ public class FunctionCodegen {
) {
int var = 0;
if (!isStatic) {
callGenerator.putValueIfNeeded(null, ownerType, StackValue.local(var, ownerType));
callGenerator.putValueIfNeeded(ownerType, StackValue.local(var, ownerType));
var += ownerType.getSize();
}
for (JvmMethodParameterSignature parameterSignature : signature.getValueParameters()) {
if (parameterSignature.getKind() != JvmMethodParameterKind.VALUE) {
Type type = parameterSignature.getAsmType();
callGenerator.putValueIfNeeded(null, type, StackValue.local(var, type));
callGenerator.putValueIfNeeded(type, StackValue.local(var, type));
var += type.getSize();
}
}
@@ -911,13 +922,7 @@ public class FunctionCodegen {
iv.ifnonnull(afterBarrier);
}
else {
CodegenUtilKt.generateIsCheck(iv, kotlinType, new Function1<InstructionAdapter, Unit>() {
@Override
public Unit invoke(InstructionAdapter adapter) {
TypeIntrinsics.instanceOf(adapter, kotlinType, boxType(delegateParameterType));
return Unit.INSTANCE;
}
});
CodegenUtilKt.generateIsCheck(iv, kotlinType, boxType(delegateParameterType));
iv.ifne(afterBarrier);
}
@@ -949,7 +954,7 @@ public class FunctionCodegen {
@NotNull MethodContext context,
@NotNull MemberCodegen<?> parentCodegen
) {
Method delegateToMethod = typeMapper.mapSignature(delegatedTo).getAsmMethod();
Method delegateToMethod = typeMapper.mapToCallableMethod(delegatedTo, /* superCall = */ false).getAsmMethod();
Method delegateMethod = typeMapper.mapSignature(delegateFunction).getAsmMethod();
Type[] argTypes = delegateMethod.getArgumentTypes();

View File

@@ -16,7 +16,7 @@
package org.jetbrains.kotlin.codegen;
import kotlin.CollectionsKt;
import kotlin.collections.CollectionsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.codegen.state.GenerationState;
@@ -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

@@ -19,8 +19,8 @@ package org.jetbrains.kotlin.codegen;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.psi.PsiElement;
import com.intellij.util.ArrayUtil;
import kotlin.CollectionsKt;
import kotlin.Unit;
import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.functions.Function2;
@@ -43,6 +43,8 @@ import org.jetbrains.kotlin.lexer.KtTokens;
import org.jetbrains.kotlin.load.java.JvmAbi;
import org.jetbrains.kotlin.load.java.JvmAnnotationNames;
import org.jetbrains.kotlin.load.java.descriptors.JavaCallableMemberDescriptor;
import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader;
import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.resolve.BindingContext;
@@ -62,8 +64,8 @@ import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodParameterKind;
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodParameterSignature;
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature;
import org.jetbrains.kotlin.resolve.scopes.receivers.ExtensionReceiver;
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue;
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver;
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue;
import org.jetbrains.kotlin.serialization.DescriptorSerializer;
import org.jetbrains.kotlin.serialization.ProtoBuf;
import org.jetbrains.kotlin.types.KotlinType;
@@ -74,6 +76,7 @@ import org.jetbrains.org.objectweb.asm.commons.Method;
import java.util.*;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.FQ_NAMES;
import static org.jetbrains.kotlin.codegen.AsmUtil.*;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.*;
import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.enumEntryNeedSubclass;
@@ -98,6 +101,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 +117,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 +233,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,31 +242,29 @@ 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();
}
}
@Override
protected void generateKotlinAnnotation() {
if (!isTopLevelOrInnerClass(descriptor)) {
AnnotationVisitor av = v.getVisitor().visitAnnotation(
asmDescByFqNameWithoutInnerClasses(JvmAnnotationNames.KOTLIN_LOCAL_CLASS), true
);
av.visit(JvmAnnotationNames.VERSION_FIELD_NAME, JvmAbi.VERSION.toArray());
av.visitEnd();
}
final DescriptorSerializer serializer =
DescriptorSerializer.create(descriptor, new JvmSerializerExtension(v.getSerializationBindings(), state));
DescriptorSerializer serializer =
DescriptorSerializer.create(descriptor, new JvmSerializerExtension(
v.getSerializationBindings(), typeMapper, state.getUseTypeTableInSerializer()
));
final ProtoBuf.Class classProto = serializer.classProto(descriptor).build();
ProtoBuf.Class classProto = serializer.classProto(descriptor).build();
WriteAnnotationUtilKt.writeKotlinMetadata(v, KotlinClassHeader.Kind.CLASS, new Function1<AnnotationVisitor, Unit>() {
@Override
public Unit invoke(AnnotationVisitor av) {
writeAnnotationData(av, serializer, classProto, false);
return Unit.INSTANCE;
}
});
AnnotationVisitor av = v.getVisitor().visitAnnotation(asmDescByFqNameWithoutInnerClasses(JvmAnnotationNames.KOTLIN_CLASS), true);
writeAnnotationData(av, serializer, classProto);
writeModuleName(av, state);
writeAbiVersion(av);
writeAnnotationData(av, serializer, classProto, true);
av.visitEnd();
}
@@ -277,25 +280,25 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
}
private static final Map<String, String> KOTLIN_MARKER_INTERFACES = new HashMap<String, String>();
private static final Map<FqName, String> KOTLIN_MARKER_INTERFACES = new HashMap<FqName, String>();
static {
KOTLIN_MARKER_INTERFACES.put("kotlin.Iterator", "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put("kotlin.Iterable", "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put("kotlin.Collection", "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put("kotlin.List", "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put("kotlin.ListIterator", "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put("kotlin.Set", "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put("kotlin.Map", "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put("kotlin.Map.Entry", "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.iterator, "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.iterable, "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.collection, "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.list, "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.listIterator, "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.set, "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.map, "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.mapEntry, "kotlin/jvm/internal/markers/KMappedMarker");
KOTLIN_MARKER_INTERFACES.put("kotlin.MutableIterator", "kotlin/jvm/internal/markers/KMutableIterator");
KOTLIN_MARKER_INTERFACES.put("kotlin.MutableIterable", "kotlin/jvm/internal/markers/KMutableIterable");
KOTLIN_MARKER_INTERFACES.put("kotlin.MutableCollection", "kotlin/jvm/internal/markers/KMutableCollection");
KOTLIN_MARKER_INTERFACES.put("kotlin.MutableList", "kotlin/jvm/internal/markers/KMutableList");
KOTLIN_MARKER_INTERFACES.put("kotlin.MutableListIterator", "kotlin/jvm/internal/markers/KMutableListIterator");
KOTLIN_MARKER_INTERFACES.put("kotlin.MutableSet", "kotlin/jvm/internal/markers/KMutableSet");
KOTLIN_MARKER_INTERFACES.put("kotlin.MutableMap", "kotlin/jvm/internal/markers/KMutableMap");
KOTLIN_MARKER_INTERFACES.put("kotlin.MutableMap.MutableEntry", "kotlin/jvm/internal/markers/KMutableMap$Entry");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.mutableIterator, "kotlin/jvm/internal/markers/KMutableIterator");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.mutableIterable, "kotlin/jvm/internal/markers/KMutableIterable");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.mutableCollection, "kotlin/jvm/internal/markers/KMutableCollection");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.mutableList, "kotlin/jvm/internal/markers/KMutableList");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.mutableListIterator, "kotlin/jvm/internal/markers/KMutableListIterator");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.mutableSet, "kotlin/jvm/internal/markers/KMutableSet");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.mutableMap, "kotlin/jvm/internal/markers/KMutableMap");
KOTLIN_MARKER_INTERFACES.put(FQ_NAMES.mutableMapEntry, "kotlin/jvm/internal/markers/KMutableMap$Entry");
}
@NotNull
@@ -325,7 +328,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
String jvmInterfaceInternalName = jvmInterfaceType.getInternalName();
superInterfaces.add(jvmInterfaceInternalName);
String kotlinInterfaceName = DescriptorUtils.getFqName(supertype.getConstructor().getDeclarationDescriptor()).asString();
FqName kotlinInterfaceName = DescriptorUtils.getFqName(supertype.getConstructor().getDeclarationDescriptor()).toSafe();
String kotlinMarkerInterfaceInternalName = KOTLIN_MARKER_INTERFACES.get(kotlinInterfaceName);
if (kotlinMarkerInterfaceInternalName != null) {
kotlinMarkerInterfaces.add(kotlinMarkerInterfaceInternalName);
@@ -371,7 +374,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 +415,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() {
@@ -834,22 +841,16 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
private void generateFieldForSingleton() {
if (isEnumEntry(descriptor)) return;
if (isEnumEntry(descriptor) || isCompanionObject(descriptor)) return;
boolean isCompanionObject = isCompanionObject(descriptor);
if (isNonCompanionObject(descriptor) || isCompanionObject) {
if (isNonCompanionObject(descriptor)) {
StackValue.Field field = StackValue.singletonViaInstance(descriptor, typeMapper);
v.newField(JvmDeclarationOriginKt.OtherOrigin(myClass),
ACC_PUBLIC | ACC_STATIC | ACC_FINAL | (isCompanionObject ? ACC_DEPRECATED : 0),
ACC_PUBLIC | ACC_STATIC | ACC_FINAL,
field.name, field.type.getDescriptor(), null, null);
if (isNonCompanionObject(descriptor)) {
StackValue.Field oldField = StackValue.oldSingleton(descriptor, typeMapper);
v.newField(JvmDeclarationOriginKt.OtherOrigin(myClass), ACC_PUBLIC | ACC_STATIC | ACC_FINAL | ACC_DEPRECATED, oldField.name, oldField.type.getDescriptor(), null, null);
}
if (state.getClassBuilderMode() != ClassBuilderMode.FULL) return;
// Invoke the object constructor but ignore the result because INSTANCE$ will be initialized in the first line of <init>
// Invoke the object constructor but ignore the result because INSTANCE will be initialized in the first line of <init>
InstructionAdapter v = createOrGetClInitCodegen().v;
markLineNumberForElement(element, v);
v.anew(classAsmType);
@@ -868,12 +869,6 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
StackValue.Field field = StackValue.singleton(companionObjectDescriptor, typeMapper);
v.newField(JvmDeclarationOriginKt.OtherOrigin(companionObject), ACC_PUBLIC | ACC_STATIC | ACC_FINAL, field.name, field.type.getDescriptor(), null, null);
if (state.getClassBuilderMode() != ClassBuilderMode.FULL) return;
if (!isCompanionObjectWithBackingFieldsInOuter(companionObjectDescriptor)) {
generateCompanionObjectInitializer(companionObjectDescriptor);
}
}
private void generateCompanionObjectBackingFieldCopies() {
@@ -883,7 +878,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
PropertyDescriptor property = info.descriptor;
Type type = typeMapper.mapType(property);
int modifiers = ACC_STATIC | ACC_FINAL | ACC_PUBLIC | (property.isConst() ? 0 : ACC_DEPRECATED);
int modifiers = ACC_STATIC | ACC_FINAL | ACC_PUBLIC;
FieldVisitor fv = v.newField(JvmDeclarationOriginKt.Synthetic(DescriptorToSourceUtils.descriptorToDeclaration(property), property),
modifiers, context.getFieldName(property, false),
type.getDescriptor(), typeMapper.mapFieldSignature(property.getType(), property),
@@ -925,13 +920,13 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
private void generateCompanionObjectInitializer(@NotNull ClassDescriptor companionObject) {
ExpressionCodegen codegen = createOrGetClInitCodegen();
//TODO: uncomment when DEPRECATED INSTANCE is removed
//FunctionDescriptor constructor = (FunctionDescriptor) context.accessibleDescriptor(
// CollectionsKt.single(companionObject.getConstructors()), /* superCallExpression = */ null
//);
//generateMethodCallTo(constructor, null, codegen.v);
//StackValue instance = StackValue.onStack(typeMapper.mapClass(companionObject));
StackValue.singleton(companionObject, typeMapper).store(StackValue.singletonViaInstance(companionObject, typeMapper), codegen.v, true);
FunctionDescriptor constructor = (FunctionDescriptor) context.accessibleDescriptor(
CollectionsKt.single(companionObject.getConstructors()), /* superCallExpression = */ null
);
generateMethodCallTo(constructor, null, codegen.v);
StackValue instance = StackValue.onStack(typeMapper.mapClass(companionObject));
StackValue.singleton(companionObject, typeMapper).store(instance, codegen.v, true);
}
private void generatePrimaryConstructor(final DelegationFieldsInfo delegationFieldsInfo) {
@@ -958,10 +953,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) {
@@ -1005,16 +996,13 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
generateDelegatorToConstructorCall(iv, codegen, constructorDescriptor,
getDelegationConstructorCall(bindingContext, constructorDescriptor));
if (isObject(descriptor)) {
if (isNonCompanionObject(descriptor)) {
StackValue.singletonViaInstance(descriptor, typeMapper).store(StackValue.LOCAL_0, iv);
if (isNonCompanionObject(descriptor)) {
StackValue.oldSingleton(descriptor, typeMapper).store(StackValue.LOCAL_0, iv);
}
}
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);
}
}
@@ -1033,9 +1021,13 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
curParam++;
}
if (isCompanionObjectWithBackingFieldsInOuter(descriptor)) {
final ImplementationBodyCodegen parentCodegen = (ImplementationBodyCodegen) getParentCodegen();
if (isCompanionObject(descriptor)) {
ImplementationBodyCodegen parentCodegen = (ImplementationBodyCodegen) getParentCodegen();
parentCodegen.generateCompanionObjectInitializer(descriptor);
}
if (JvmAbi.isCompanionObjectWithBackingFieldsInOuter(descriptor)) {
final ImplementationBodyCodegen parentCodegen = (ImplementationBodyCodegen) getParentCodegen();
generateInitializers(new Function0<ExpressionCodegen>() {
@Override
public ExpressionCodegen invoke() {
@@ -1153,41 +1145,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 +1188,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 +1240,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 +1295,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 +1323,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 +1551,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
@Override
protected void reorderArgumentsIfNeeded(@NotNull List args) {
protected void reorderArgumentsIfNeeded(@NotNull List<ArgumentAndDeclIndex> args) {
}
}
@@ -1571,7 +1563,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 +1612,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 +1630,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

@@ -23,29 +23,29 @@ import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
public class InlineCycleReporter(val diagnostics: DiagnosticSink) {
class InlineCycleReporter(val diagnostics: DiagnosticSink) {
val processingFunctions = linkedMapOf<PsiElement, CallableDescriptor>()
public fun enterIntoInlining(call: ResolvedCall<*>?): Boolean {
fun enterIntoInlining(call: ResolvedCall<*>?): Boolean {
//null call for default method inlining
if (call != null) {
val callElement = call.getCall().getCallElement()
val callElement = call.call.callElement
if (processingFunctions.contains(callElement)) {
val cycle = processingFunctions.asSequence().dropWhile { it.getKey() != callElement }
val cycle = processingFunctions.asSequence().dropWhile { it.key != callElement }
cycle.forEach {
diagnostics.report(Errors.INLINE_CALL_CYCLE.on(it.getKey(), it.getValue()))
diagnostics.report(Errors.INLINE_CALL_CYCLE.on(it.key, it.value))
}
return false
}
processingFunctions.put(callElement, call.getResultingDescriptor().getOriginal())
processingFunctions.put(callElement, call.resultingDescriptor.original)
}
return true
}
public fun exitFromInliningOf(call: ResolvedCall<*>?) {
fun exitFromInliningOf(call: ResolvedCall<*>?) {
if (call != null) {
val callElement = call.getCall().getCallElement()
val callElement = call.call.callElement
processingFunctions.remove(callElement)
}
}

View File

@@ -24,8 +24,6 @@ import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.impl.ClassDescriptorImpl
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.load.java.JvmAnnotationNames
import org.jetbrains.kotlin.load.java.JvmAnnotationNames.KOTLIN_INTERFACE_DEFAULT_IMPLS
import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtClassOrObject
@@ -39,7 +37,7 @@ import org.jetbrains.org.objectweb.asm.MethodVisitor
import org.jetbrains.org.objectweb.asm.Opcodes.*
import java.util.*
public class InterfaceImplBodyCodegen(
class InterfaceImplBodyCodegen(
aClass: KtClassOrObject,
context: ClassContext,
v: ClassBuilder,
@@ -51,11 +49,11 @@ 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
)
v.visitSource(myClass.getContainingFile().getName(), null)
v.visitSource(myClass.containingFile.name, null)
}
override fun classForInnerClassRecord(): ClassDescriptor? {
@@ -63,19 +61,19 @@ 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
}
override fun generateSyntheticParts() {
for (memberDescriptor in descriptor.getDefaultType().getMemberScope().getContributedDescriptors()) {
for (memberDescriptor in descriptor.defaultType.memberScope.getContributedDescriptors()) {
if (memberDescriptor !is CallableMemberDescriptor) continue
if (memberDescriptor.getKind().isReal()) continue
if (memberDescriptor.getVisibility() == Visibilities.INVISIBLE_FAKE) continue
if (memberDescriptor.getModality() == Modality.ABSTRACT) continue
if (memberDescriptor.kind.isReal) continue
if (memberDescriptor.visibility == Visibilities.INVISIBLE_FAKE) continue
if (memberDescriptor.modality == Modality.ABSTRACT) continue
val implementation = findImplementationFromInterface(memberDescriptor) ?: continue
@@ -83,7 +81,7 @@ public class InterfaceImplBodyCodegen(
if (implementation is JavaMethodDescriptor) continue
// We create a copy of the function with kind = DECLARATION so that FunctionCodegen will generate its body
val copy = memberDescriptor.copy(memberDescriptor.getContainingDeclaration(), Modality.OPEN, memberDescriptor.getVisibility(),
val copy = memberDescriptor.copy(memberDescriptor.containingDeclaration, Modality.OPEN, memberDescriptor.visibility,
CallableMemberDescriptor.Kind.DECLARATION, true)
if (memberDescriptor is FunctionDescriptor) {
@@ -91,18 +89,20 @@ public class InterfaceImplBodyCodegen(
}
else if (memberDescriptor is PropertyDescriptor) {
implementation as PropertyDescriptor
val getter = (copy as PropertyDescriptor).getGetter()
val implGetter = implementation.getGetter()
val getter = (copy as PropertyDescriptor).getter
val implGetter = implementation.getter
if (getter != null && implGetter != null) {
generateDelegationToSuperTraitImpl(getter, implGetter)
}
val setter = copy.getSetter()
val implSetter = implementation.getSetter()
val setter = copy.setter
val implSetter = implementation.setter
if (setter != null && implSetter != null) {
generateDelegationToSuperTraitImpl(setter, implSetter)
}
}
}
generateSyntheticAccessors()
}
private fun generateDelegationToSuperTraitImpl(descriptor: FunctionDescriptor, implementation: FunctionDescriptor) {
@@ -119,10 +119,10 @@ public class InterfaceImplBodyCodegen(
val iv = codegen.v
val method = typeMapper.mapToCallableMethod(delegateTo, true)
val myParameters = signature.getValueParameters()
val myParameters = signature.valueParameters
val calleeParameters = method.getValueParameters()
if (myParameters.size() != calleeParameters.size()) {
if (myParameters.size != calleeParameters.size) {
throw AssertionError(
"Method from super interface has a different signature.\n" +
"This method:\n%s\n%s\n%s\nSuper method:\n%s\n%s\n%s".format(
@@ -134,14 +134,14 @@ public class InterfaceImplBodyCodegen(
var k = 0
val it = calleeParameters.iterator()
for (parameter in myParameters) {
val type = parameter.getAsmType()
StackValue.local(k, type).put(it.next().getAsmType(), iv)
k += type.getSize()
val type = parameter.asmType
StackValue.local(k, type).put(it.next().asmType, iv)
k += type.size
}
method.genInvokeInstruction(iv)
StackValue.coerce(method.returnType, signature.getReturnType(), iv)
iv.areturn(signature.getReturnType())
StackValue.coerce(method.returnType, signature.returnType, iv)
iv.areturn(signature.returnType)
}
})
}
@@ -149,10 +149,9 @@ public class InterfaceImplBodyCodegen(
override fun generateKotlinAnnotation() {
(v as InterfaceImplClassBuilder).stopCounting()
val av = v.newAnnotation(AsmUtil.asmDescByFqNameWithoutInnerClasses(KOTLIN_INTERFACE_DEFAULT_IMPLS), true)
av.visit(JvmAnnotationNames.VERSION_FIELD_NAME, JvmAbi.VERSION.toArray())
av.visitEnd()
AsmUtil.writeKotlinSyntheticClassAnnotation(v, state)
writeSyntheticClassMetadata(v);
}
override fun done() {

View File

@@ -18,9 +18,9 @@ package org.jetbrains.kotlin.codegen;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import kotlin.CollectionsKt;
import kotlin.StringsKt;
import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
import kotlin.text.StringsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.codegen.binding.CalculatedClosure;
@@ -28,11 +28,10 @@ import org.jetbrains.kotlin.codegen.context.CodegenContext;
import org.jetbrains.kotlin.codegen.context.FacadePartWithSourceFile;
import org.jetbrains.kotlin.codegen.context.MethodContext;
import org.jetbrains.kotlin.codegen.context.RootContext;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.codegen.state.JetTypeMapper;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.load.java.JvmAbi;
import org.jetbrains.kotlin.load.java.JvmAnnotationNames;
import org.jetbrains.kotlin.load.kotlin.JvmMetadataVersion;
import org.jetbrains.kotlin.load.kotlin.ModuleMapping;
import org.jetbrains.kotlin.load.kotlin.ModuleVisibilityUtilsKt;
import org.jetbrains.kotlin.psi.KtFile;
@@ -50,6 +49,7 @@ import java.io.File;
import static org.jetbrains.kotlin.descriptors.Modality.ABSTRACT;
import static org.jetbrains.kotlin.descriptors.Modality.FINAL;
import static org.jetbrains.kotlin.resolve.jvm.annotations.AnnotationUtilKt.hasJvmFieldAnnotation;
public class JvmCodegenUtil {
@@ -130,16 +130,21 @@ public class JvmCodegenUtil {
);
}
public static boolean isConstOrHasJvmFieldAnnotation(@NotNull PropertyDescriptor propertyDescriptor) {
return propertyDescriptor.isConst() || hasJvmFieldAnnotation(propertyDescriptor);
}
public static boolean couldUseDirectAccessToProperty(
@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 +169,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);
}
@@ -217,16 +222,6 @@ public class JvmCodegenUtil {
}
public static void writeAbiVersion(@NotNull AnnotationVisitor av) {
av.visit(JvmAnnotationNames.VERSION_FIELD_NAME, JvmAbi.VERSION.toArray());
// TODO: drop after some time
av.visit(JvmAnnotationNames.OLD_ABI_VERSION_FIELD_NAME, 32);
}
public static void writeModuleName(@NotNull AnnotationVisitor av, @NotNull GenerationState state) {
String name = state.getModuleName();
if (!name.equals(JvmAbi.DEFAULT_MODULE_NAME)) {
av.visit(JvmAnnotationNames.MODULE_NAME_FIELD_NAME, name);
}
av.visit(JvmAnnotationNames.VERSION_FIELD_NAME, JvmMetadataVersion.INSTANCE.toArray());
}
}

View File

@@ -40,7 +40,7 @@ public class JvmRuntimeTypes {
public JvmRuntimeTypes() {
ModuleDescriptorImpl module = TargetPlatformKt.createModule(
JvmPlatform.INSTANCE$,
JvmPlatform.INSTANCE,
Name.special("<jvm functions impl>"),
LockBasedStorageManager.NO_LOCKS
);

View File

@@ -79,15 +79,14 @@ class JvmStaticGenerator(
}
companion object {
@JvmStatic
public fun createStaticFunctionDescriptor(descriptor: FunctionDescriptor): FunctionDescriptor {
val memberDescriptor = if (descriptor is PropertyAccessorDescriptor) descriptor.getCorrespondingProperty() else descriptor
@JvmStatic fun createStaticFunctionDescriptor(descriptor: FunctionDescriptor): FunctionDescriptor {
val memberDescriptor = if (descriptor is PropertyAccessorDescriptor) descriptor.correspondingProperty else descriptor
val copies = CodegenUtil.copyFunctions(
memberDescriptor,
memberDescriptor,
descriptor.getContainingDeclaration().getContainingDeclaration(),
descriptor.getModality(),
descriptor.getVisibility(),
descriptor.containingDeclaration.containingDeclaration,
descriptor.modality,
descriptor.visibility,
CallableMemberDescriptor.Kind.SYNTHESIZED,
false
)

View File

@@ -18,9 +18,7 @@ package org.jetbrains.kotlin.codegen;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.psi.PsiElement;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.backend.common.CodegenUtil;
@@ -46,8 +44,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;
import org.jetbrains.kotlin.storage.NotNullLazyValue;
@@ -65,8 +61,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 +276,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();
@@ -306,7 +302,7 @@ public abstract class MemberCodegen<T extends KtElement/* TODO: & JetDeclaration
if (outermost instanceof ClassContext) {
return typeMapper.mapType(((ClassContext) outermost).getContextDescriptor());
}
else if (outermost instanceof DelegatingFacadeContext || outermost instanceof DelegatingToPartContext) {
else if (outermost instanceof MultifileClassFacadeContext || outermost instanceof DelegatingToPartContext) {
Type implementationOwnerType = CodegenContextUtil.getImplementationOwnerClassType(outermost);
if (implementationOwnerType != null) {
return implementationOwnerType;
@@ -499,37 +495,23 @@ public abstract class MemberCodegen<T extends KtElement/* TODO: & JetDeclaration
iv.dup();
iv.iconst(i);
StackValue value;
// TODO: remove this option and always generate PropertyReferenceNImpl creation
if ("true".equalsIgnoreCase(System.getProperty("kotlin.jvm.optimize.delegated.properties"))) {
int receiverCount = (property.getDispatchReceiverParameter() != null ? 1 : 0) +
(property.getExtensionReceiverParameter() != null ? 1 : 0);
Type implType = property.isVar() ? MUTABLE_PROPERTY_REFERENCE_IMPL[receiverCount] : PROPERTY_REFERENCE_IMPL[receiverCount];
iv.anew(implType);
iv.dup();
// TODO: generate the container once and save to a local field instead
ClosureCodegen.generateCallableReferenceDeclarationContainer(iv, property, state);
iv.aconst(property.getName().asString());
iv.aconst(PropertyReferenceCodegen.getPropertyReferenceSignature(property, state));
iv.invokespecial(
implType.getInternalName(), "<init>",
Type.getMethodDescriptor(Type.VOID_TYPE, K_DECLARATION_CONTAINER_TYPE, JAVA_STRING_TYPE, JAVA_STRING_TYPE), false
);
value = StackValue.onStack(implType);
Method wrapper = PropertyReferenceCodegen.getWrapperMethodForPropertyReference(property, receiverCount);
iv.invokestatic(REFLECTION, wrapper.getName(), wrapper.getDescriptor(), false);
}
else {
ReceiverParameterDescriptor dispatchReceiver = property.getDispatchReceiverParameter();
int receiverCount = (property.getDispatchReceiverParameter() != null ? 1 : 0) +
(property.getExtensionReceiverParameter() != null ? 1 : 0);
Type implType = property.isVar() ? MUTABLE_PROPERTY_REFERENCE_IMPL[receiverCount] : PROPERTY_REFERENCE_IMPL[receiverCount];
iv.anew(implType);
iv.dup();
// TODO: generate the container once and save to a local field instead (KT-10495)
ClosureCodegen.generateCallableReferenceDeclarationContainer(iv, property, state);
iv.aconst(property.getName().asString());
iv.aconst(PropertyReferenceCodegen.getPropertyReferenceSignature(property, state));
iv.invokespecial(
implType.getInternalName(), "<init>",
Type.getMethodDescriptor(Type.VOID_TYPE, K_DECLARATION_CONTAINER_TYPE, JAVA_STRING_TYPE, JAVA_STRING_TYPE), false
);
Method wrapper = PropertyReferenceCodegen.getWrapperMethodForPropertyReference(property, receiverCount);
iv.invokestatic(REFLECTION, wrapper.getName(), wrapper.getDescriptor(), false);
//noinspection ConstantConditions
value = createOrGetClInitCodegen().generatePropertyReference(
delegatedProperties.get(i).getDelegate(), property, property,
dispatchReceiver != null ? new TransientReceiver(dispatchReceiver.getType()) : ReceiverValue.NO_RECEIVER
);
}
value.put(K_PROPERTY_TYPE, iv);
StackValue.onStack(implType).put(K_PROPERTY_TYPE, iv);
iv.astore(K_PROPERTY_TYPE);
}
@@ -568,20 +550,17 @@ public abstract class MemberCodegen<T extends KtElement/* TODO: & JetDeclaration
return sourceMapper;
}
protected void generateConstInstance(
@NotNull Type thisAsmType,
@NotNull Type fieldAsmType,
@NotNull Function1<InstructionAdapter, Unit> initialization
) {
v.newField(JvmDeclarationOriginKt.OtherOrigin(element), ACC_STATIC | ACC_FINAL | ACC_PUBLIC, JvmAbi.INSTANCE_FIELD, fieldAsmType.getDescriptor(),
null, null);
protected void generateConstInstance(@NotNull Type thisAsmType, @NotNull Type fieldAsmType) {
v.newField(
JvmDeclarationOriginKt.OtherOrigin(element), ACC_STATIC | ACC_FINAL | ACC_PUBLIC, JvmAbi.INSTANCE_FIELD,
fieldAsmType.getDescriptor(), null, null
);
if (state.getClassBuilderMode() == ClassBuilderMode.FULL) {
InstructionAdapter iv = createOrGetClInitCodegen().v;
iv.anew(thisAsmType);
iv.dup();
iv.invokespecial(thisAsmType.getInternalName(), "<init>", "()V", false);
initialization.invoke(iv);
iv.putstatic(thisAsmType.getInternalName(), JvmAbi.INSTANCE_FIELD, fieldAsmType.getDescriptor());
}
}
@@ -622,7 +601,7 @@ public abstract class MemberCodegen<T extends KtElement/* TODO: & JetDeclaration
@Override
public void doGenerateBody(@NotNull ExpressionCodegen codegen, @NotNull JvmMethodSignature signature) {
boolean syntheticBackingField = accessor instanceof AccessorForPropertyBackingFieldFromLocal;
boolean forceField = (AsmUtil.isPropertyWithBackingFieldInOuterClass(original) &&
boolean forceField = (JvmAbi.isPropertyWithBackingFieldInOuterClass(original) &&
!isCompanionObject(accessor.getContainingDeclaration())) ||
syntheticBackingField ||
original.getVisibility() == JavaVisibilities.PROTECTED_STATIC_VISIBILITY;
@@ -673,7 +652,7 @@ public abstract class MemberCodegen<T extends KtElement/* TODO: & JetDeclaration
}
}
private StackValue generateMethodCallTo(
protected StackValue generateMethodCallTo(
@NotNull FunctionDescriptor functionDescriptor,
@Nullable FunctionDescriptor accessorDescriptor,
@NotNull InstructionAdapter iv
@@ -684,7 +663,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

@@ -31,6 +31,7 @@ import org.jetbrains.kotlin.diagnostics.DiagnosticUtils
import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil
import org.jetbrains.kotlin.load.java.JvmAnnotationNames
import org.jetbrains.kotlin.load.kotlin.PackageParts
import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader
import org.jetbrains.kotlin.load.kotlin.incremental.IncrementalPackageFragmentProvider
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.progress.ProgressIndicatorAndCompilationCanceledStatus
@@ -38,6 +39,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
@@ -47,14 +49,16 @@ import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedCallableMemberDescriptor
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedPropertyDescriptor
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedSimpleFunctionDescriptor
import org.jetbrains.org.objectweb.asm.AnnotationVisitor
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(
class MultifileClassCodegen(
private val state: GenerationState,
public val files: Collection<KtFile>,
val files: Collection<KtFile>,
private val facadeFqName: FqName
) {
private val facadeClassType = AsmUtil.asmTypeByFqNameWithoutInnerClasses(facadeFqName)
@@ -72,7 +76,7 @@ public class MultifileClassCodegen(
private fun getDeserializedCallables(compiledPackageFragment: PackageFragmentDescriptor) =
compiledPackageFragment.getMemberScope().getContributedDescriptors(DescriptorKindFilter.CALLABLES, MemberScope.ALL_NAME_FILTER).filterIsInstance<DeserializedCallableMemberDescriptor>()
public val packageParts = PackageParts(facadeFqName.parent().asString())
val packageParts = PackageParts(facadeFqName.parent().asString())
private val classBuilder = ClassBuilderOnDemand {
val originFile = files.firstOrNull()
@@ -86,16 +90,22 @@ 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
}
public fun generate(errorHandler: CompilationErrorHandler) {
fun generate(errorHandler: CompilationErrorHandler) {
val generateCallableMemberTasks = HashMap<CallableMemberDescriptor, () -> Unit>()
val partFqNames = arrayListOf<FqName>()
@@ -144,10 +154,20 @@ public class MultifileClassCodegen(
writeKotlinMultifileFacadeAnnotationIfNeeded(partFqNames)
}
public fun generateClassOrObject(classOrObject: KtClassOrObject, packagePartContext: FieldOwnerContext<PackageFragmentDescriptor>) {
fun generateClassOrObject(classOrObject: KtClassOrObject, packagePartContext: FieldOwnerContext<PackageFragmentDescriptor>) {
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>,
@@ -253,17 +273,23 @@ public class MultifileClassCodegen(
if (state.classBuilderMode != ClassBuilderMode.FULL) return
if (files.any { it.isScript }) return
val partInternalNames = partFqNames.map(AsmUtil::internalNameByFqNameWithoutInnerClasses).sorted()
fun writePartNames(av: AnnotationVisitor, fieldName: String) {
val arv = av.visitArray(fieldName)
for (internalName in partInternalNames) {
arv.visit(null, internalName)
}
arv.visitEnd()
}
writeKotlinMetadata(classBuilder, KotlinClassHeader.Kind.MULTIFILE_CLASS) { av ->
writePartNames(av, JvmAnnotationNames.METADATA_DATA_FIELD_NAME)
}
val av = classBuilder.newAnnotation(AsmUtil.asmDescByFqNameWithoutInnerClasses(JvmAnnotationNames.KOTLIN_MULTIFILE_CLASS), true)
JvmCodegenUtil.writeAbiVersion(av)
JvmCodegenUtil.writeModuleName(av, state)
val partInternalNames = partFqNames.map { JvmClassName.byFqNameWithoutInnerClasses(it).internalName }.sorted()
val arv = av.visitArray(JvmAnnotationNames.FILE_PART_CLASS_NAMES_FIELD_NAME)
for (internalName in partInternalNames) {
arv.visit(null, internalName)
}
arv.visitEnd()
writePartNames(av, JvmAnnotationNames.FILE_PART_CLASS_NAMES_FIELD_NAME)
av.visitEnd()
}
@@ -274,12 +300,13 @@ public class MultifileClassCodegen(
override fun generateKotlinAnnotation() = throw UnsupportedOperationException()
}
public fun done() {
fun done() {
classBuilder.done()
}
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>()
@@ -293,7 +320,7 @@ public class MultifileClassCodegen(
fragments.add(fragment)
}
}
if (fragments.size() > 1) {
if (fragments.size > 1) {
throw IllegalStateException("More than one package fragment, files: $files | fragments: $fragments")
}
return fragments.firstOrNull()

View File

@@ -22,6 +22,7 @@ import org.jetbrains.kotlin.codegen.serialization.JvmSerializerExtension
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.load.java.JvmAnnotationNames
import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtProperty
@@ -31,7 +32,7 @@ import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.Type
import java.util.*
public class MultifileClassPartCodegen(
class MultifileClassPartCodegen(
v: ClassBuilder,
file: KtFile,
private val filePartType: Type,
@@ -46,7 +47,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",
@@ -83,15 +84,17 @@ public class MultifileClassPartCodegen(
}
}
val bindings = v.serializationBindings
val serializer = DescriptorSerializer.createTopLevel(
JvmSerializerExtension(bindings, state.typeMapper, state.useTypeTableInSerializer)
)
val serializer = DescriptorSerializer.createTopLevel(JvmSerializerExtension(v.serializationBindings, state))
val packageProto = serializer.packagePartProto(members).build()
writeKotlinMetadata(v, KotlinClassHeader.Kind.MULTIFILE_CLASS_PART) { av ->
AsmUtil.writeAnnotationData(av, serializer, packageProto, false)
av.visit(JvmAnnotationNames.METADATA_MULTIFILE_CLASS_NAME_FIELD_NAME, multifileClassType.internalName)
}
val av = v.newAnnotation(AsmUtil.asmDescByFqNameWithoutInnerClasses(JvmAnnotationNames.KOTLIN_MULTIFILE_CLASS_PART), true)
AsmUtil.writeAnnotationData(av, serializer, packageProto)
JvmCodegenUtil.writeAbiVersion(av)
AsmUtil.writeAnnotationData(av, serializer, packageProto, true)
av.visit(JvmAnnotationNames.MULTIFILE_CLASS_NAME_FIELD_NAME, multifileClassType.internalName)
av.visitEnd()
}

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

@@ -17,11 +17,12 @@
package org.jetbrains.kotlin.codegen;
import com.intellij.util.ArrayUtil;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.codegen.annotation.AnnotatedSimple;
import org.jetbrains.kotlin.codegen.context.FieldOwnerContext;
import org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings;
import org.jetbrains.kotlin.codegen.serialization.JvmSerializerExtension;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor;
@@ -31,6 +32,7 @@ import org.jetbrains.kotlin.descriptors.annotations.Annotated;
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor;
import org.jetbrains.kotlin.descriptors.annotations.AnnotationsImpl;
import org.jetbrains.kotlin.load.java.JvmAnnotationNames;
import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader;
import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.serialization.DescriptorSerializer;
@@ -43,7 +45,7 @@ import java.util.List;
import static org.jetbrains.kotlin.codegen.AsmUtil.asmDescByFqNameWithoutInnerClasses;
import static org.jetbrains.kotlin.codegen.AsmUtil.writeAnnotationData;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.writeModuleName;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.writeAbiVersion;
import static org.jetbrains.org.objectweb.asm.Opcodes.*;
public class PackagePartCodegen extends MemberCodegen<KtFile> {
@@ -63,7 +65,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",
@@ -119,16 +121,21 @@ public class PackagePartCodegen extends MemberCodegen<KtFile> {
}
}
JvmSerializationBindings bindings = v.getSerializationBindings();
final DescriptorSerializer serializer =
DescriptorSerializer.createTopLevel(new JvmSerializerExtension(v.getSerializationBindings(), state));
final ProtoBuf.Package packageProto = serializer.packagePartProto(members).build();
DescriptorSerializer serializer = DescriptorSerializer.createTopLevel(new JvmSerializerExtension(
bindings, state.getTypeMapper(), state.getUseTypeTableInSerializer()
));
ProtoBuf.Package packageProto = serializer.packagePartProto(members).build();
WriteAnnotationUtilKt.writeKotlinMetadata(v, KotlinClassHeader.Kind.FILE_FACADE, new Function1<AnnotationVisitor, Unit>() {
@Override
public Unit invoke(AnnotationVisitor av) {
writeAnnotationData(av, serializer, packageProto, false);
return Unit.INSTANCE;
}
});
AnnotationVisitor av = v.newAnnotation(asmDescByFqNameWithoutInnerClasses(JvmAnnotationNames.KOTLIN_FILE_FACADE), true);
writeAnnotationData(av, serializer, packageProto);
writeModuleName(av, state);
writeAbiVersion(av);
writeAnnotationData(av, serializer, packageProto, true);
av.visitEnd();
}

View File

@@ -54,10 +54,14 @@ import org.jetbrains.org.objectweb.asm.commons.Method;
import java.util.List;
import static org.jetbrains.kotlin.codegen.AsmUtil.*;
import static org.jetbrains.kotlin.codegen.AsmUtil.getDeprecatedAccessFlag;
import static org.jetbrains.kotlin.codegen.AsmUtil.getVisibilityForBackingField;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isConstOrHasJvmFieldAnnotation;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isJvmInterface;
import static org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings.*;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.*;
import static org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings.FIELD_FOR_PROPERTY;
import static org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings.SYNTHETIC_METHOD_FOR_PROPERTY;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.isCompanionObject;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.isInterface;
import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.K_PROPERTY_TYPE;
import static org.jetbrains.kotlin.resolve.jvm.annotations.AnnotationUtilKt.hasJvmFieldAnnotation;
import static org.jetbrains.org.objectweb.asm.Opcodes.*;
@@ -97,7 +101,7 @@ public class PropertyCodegen {
}
public void generateInPackageFacade(@NotNull DeserializedPropertyDescriptor deserializedProperty) {
assert context instanceof DelegatingFacadeContext : "should be called only for generating facade: " + context;
assert context instanceof MultifileClassFacadeContext : "should be called only for generating facade: " + context;
gen(null, deserializedProperty, null, null);
}
@@ -110,11 +114,6 @@ public class PropertyCodegen {
assert kind == OwnerKind.PACKAGE || kind == OwnerKind.IMPLEMENTATION || kind == OwnerKind.DEFAULT_IMPLS
: "Generating property with a wrong kind (" + kind + "): " + descriptor;
String implClassName = CodegenContextUtil.getImplementationClassShortName(context);
if (implClassName != null) {
v.getSerializationBindings().put(IMPL_CLASS_NAME_FOR_CALLABLE, descriptor, implClassName);
}
if (CodegenContextUtil.isImplClassOwner(context)) {
assert declaration != null : "Declaration is null for different context: " + context;
@@ -127,22 +126,22 @@ 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) {
boolean hasBackingField = hasBackingField(declaration, descriptor);
boolean hasDelegate = declaration instanceof KtProperty && ((KtProperty) declaration).hasDelegate();
AnnotationSplitter annotationSplitter =
AnnotationSplitter.create(LockBasedStorageManager.NO_LOCKS,
descriptor.getAnnotations(),
AnnotationSplitter.getTargetSet(isParameter, descriptor.isVar(), hasBackingField));
AnnotationSplitter.getTargetSet(isParameter, descriptor.isVar(), hasBackingField, hasDelegate));
Annotations fieldAnnotations = annotationSplitter.getAnnotationsForTarget(AnnotationUseSiteTarget.FIELD);
Annotations delegateAnnotations = annotationSplitter.getAnnotationsForTarget(AnnotationUseSiteTarget.PROPERTY_DELEGATE_FIELD);
Annotations propertyAnnotations = annotationSplitter.getAnnotationsForTarget(AnnotationUseSiteTarget.PROPERTY);
generateBackingField(declaration, descriptor, fieldAnnotations);
generateBackingField(declaration, descriptor, fieldAnnotations, delegateAnnotations);
generateSyntheticMethodIfNeeded(descriptor, propertyAnnotations);
}
@@ -157,7 +156,7 @@ public class PropertyCodegen {
@NotNull PropertyDescriptor descriptor,
@Nullable KtPropertyAccessor accessor
) {
if (hasJvmFieldAnnotation(descriptor)) return false;
if (isConstOrHasJvmFieldAnnotation(descriptor)) return false;
boolean isDefaultAccessor = accessor == null || !accessor.hasBody();
@@ -231,17 +230,18 @@ public class PropertyCodegen {
private boolean generateBackingField(
@NotNull KtNamedDeclaration p,
@NotNull PropertyDescriptor descriptor,
@NotNull Annotations annotations
@NotNull Annotations backingFieldAnnotations,
@NotNull Annotations delegateAnnotations
) {
if (isJvmInterface(descriptor.getContainingDeclaration()) || kind == OwnerKind.DEFAULT_IMPLS) {
return false;
}
if (p instanceof KtProperty && ((KtProperty) p).hasDelegate()) {
generatePropertyDelegateAccess((KtProperty) p, descriptor, annotations);
generatePropertyDelegateAccess((KtProperty) p, descriptor, delegateAnnotations);
}
else if (Boolean.TRUE.equals(bindingContext.get(BindingContext.BACKING_FIELD_REQUIRED, descriptor))) {
generateBackingFieldAccess(p, descriptor, annotations);
generateBackingFieldAccess(p, descriptor, backingFieldAnnotations);
}
else {
return false;
@@ -267,10 +267,6 @@ public class PropertyCodegen {
mv.visitInsn(Opcodes.RETURN);
mv.visitEnd();
}
else {
Type tImplType = typeMapper.mapDefaultImpls((ClassDescriptor) context.getContextDescriptor());
v.getSerializationBindings().put(IMPL_CLASS_NAME_FOR_CALLABLE, descriptor, shortNameByAsmType(tImplType));
}
if (kind != OwnerKind.DEFAULT_IMPLS) {
v.getSerializationBindings().put(SYNTHETIC_METHOD_FOR_PROPERTY, descriptor, new Method(name, desc));
@@ -309,46 +305,17 @@ public class PropertyCodegen {
ClassBuilder builder = v;
boolean hasJvmFieldAnnotation = hasJvmFieldAnnotation(propertyDescriptor);
FieldOwnerContext backingFieldContext = context;
boolean takeVisibilityFromDescriptor = propertyDescriptor.isLateInit() || propertyDescriptor.isConst();
if (AsmUtil.isInstancePropertyWithStaticBackingField(propertyDescriptor) ) {
modifiers |= ACC_STATIC;
if (takeVisibilityFromDescriptor) {
modifiers |= getVisibilityAccessFlag(propertyDescriptor);
}
else if (hasJvmFieldAnnotation && !isDelegate) {
modifiers |= getDefaultVisibilityFlag(propertyDescriptor.getVisibility());
}
else {
modifiers |= getVisibilityForSpecialPropertyBackingField(propertyDescriptor, isDelegate);
}
if (AsmUtil.isPropertyWithBackingFieldInOuterClass(propertyDescriptor)) {
if (JvmAbi.isPropertyWithBackingFieldInOuterClass(propertyDescriptor)) {
ImplementationBodyCodegen codegen = (ImplementationBodyCodegen) memberCodegen.getParentCodegen();
builder = codegen.v;
backingFieldContext = codegen.context;
v.getSerializationBindings().put(STATIC_FIELD_IN_OUTER_CLASS, propertyDescriptor);
}
if (isObject(propertyDescriptor.getContainingDeclaration()) &&
!hasJvmFieldAnnotation &&
!propertyDescriptor.isConst() &&
(modifiers & ACC_PRIVATE) == 0) {
modifiers |= ACC_DEPRECATED;
}
}
else if (takeVisibilityFromDescriptor) {
modifiers |= getVisibilityAccessFlag(propertyDescriptor);
}
else if (!isDelegate && hasJvmFieldAnnotation) {
modifiers |= getDefaultVisibilityFlag(propertyDescriptor.getVisibility());
}
else {
modifiers |= ACC_PRIVATE;
}
modifiers |= getVisibilityForBackingField(propertyDescriptor, isDelegate);
if (AsmUtil.isPropertyWithBackingFieldCopyInOuterClass(propertyDescriptor)) {
ImplementationBodyCodegen parentBodyCodegen = (ImplementationBodyCodegen) memberCodegen.getParentCodegen();
@@ -363,7 +330,8 @@ public class PropertyCodegen {
typeMapper.mapFieldSignature(jetType, propertyDescriptor), defaultValue);
Annotated fieldAnnotated = new AnnotatedWithFakeAnnotations(propertyDescriptor, annotations);
AnnotationCodegen.forField(fv, typeMapper).genAnnotations(fieldAnnotated, type, AnnotationUseSiteTarget.FIELD);
AnnotationCodegen.forField(fv, typeMapper).genAnnotations(
fieldAnnotated, type, isDelegate ? AnnotationUseSiteTarget.PROPERTY_DELEGATE_FIELD : AnnotationUseSiteTarget.FIELD);
}
private void generatePropertyDelegateAccess(KtProperty p, PropertyDescriptor propertyDescriptor, Annotations annotations) {

View File

@@ -28,31 +28,30 @@ import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.resolve.DescriptorFactory
import org.jetbrains.kotlin.resolve.PropertyImportedFromObject
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny
import org.jetbrains.kotlin.resolve.jvm.AsmTypes.*
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.utils.sure
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.commons.Method
public class PropertyReferenceCodegen(
class PropertyReferenceCodegen(
state: GenerationState,
parentCodegen: MemberCodegen<*>,
context: ClassContext,
expression: KtElement,
classBuilder: ClassBuilder,
private val classDescriptor: ClassDescriptor,
private val target: VariableDescriptor,
dispatchReceiver: ReceiverValue
resolvedCall: ResolvedCall<*>
) : MemberCodegen<KtElement>(state, parentCodegen, context, expression, classBuilder) {
private val classDescriptor = context.contextDescriptor
private val asmType = typeMapper.mapClass(classDescriptor)
private val dispatchReceiverType = if (dispatchReceiver.exists()) dispatchReceiver.type else null
private val target = resolvedCall.resultingDescriptor as VariableDescriptor
private val dispatchReceiverType = resolvedCall.dispatchReceiver?.type
private val extensionReceiverType = target.extensionReceiverParameter?.type
private val receiverCount =
@@ -69,26 +68,22 @@ public class PropertyReferenceCodegen(
element,
V1_6,
ACC_FINAL or ACC_SUPER or AsmUtil.getVisibilityAccessFlagForAnonymous(classDescriptor),
asmType.getInternalName(),
asmType.internalName,
null,
superAsmType.getInternalName(),
superAsmType.internalName,
emptyArray()
)
v.visitSource(element.getContainingFile().getName(), null)
v.visitSource(element.containingFile.name, null)
}
// TODO: ImplementationBodyCodegen.markLineNumberForSyntheticFunction?
override fun generateBody() {
generateConstInstance(asmType, wrapperMethod.getReturnType()) { iv ->
if (!"true".equals(System.getProperty("kotlin.jvm.optimize.callable.references"), ignoreCase = true)) {
iv.invokestatic(REFLECTION, wrapperMethod.getName(), wrapperMethod.getDescriptor(), false)
}
}
generateConstInstance(asmType, wrapperMethod.returnType)
generateMethod("property reference init", 0, method("<init>", Type.VOID_TYPE)) {
load(0, OBJECT_TYPE)
invokespecial(superAsmType.getInternalName(), "<init>", "()V", false)
invokespecial(superAsmType.internalName, "<init>", "()V", false)
}
generateMethod("property reference getOwner", ACC_PUBLIC, method("getOwner", K_DECLARATION_CONTAINER_TYPE)) {
@@ -96,7 +91,7 @@ public class PropertyReferenceCodegen(
}
generateMethod("property reference getName", ACC_PUBLIC, method("getName", JAVA_STRING_TYPE)) {
aconst(target.getName().asString())
aconst(target.name.asString())
}
generateMethod("property reference getSignature", ACC_PUBLIC, method("getSignature", JAVA_STRING_TYPE)) {
@@ -113,11 +108,11 @@ public class PropertyReferenceCodegen(
// return type and value parameter types. However, it's created only to be able to use
// ExpressionCodegen#intermediateValueForProperty, which is poorly coupled with everything else.
val fakeDescriptor = SimpleFunctionDescriptorImpl.create(
classDescriptor, Annotations.EMPTY, Name.identifier(method.getName()), CallableMemberDescriptor.Kind.DECLARATION,
classDescriptor, Annotations.EMPTY, Name.identifier(method.name), CallableMemberDescriptor.Kind.DECLARATION,
SourceElement.NO_SOURCE
)
fakeDescriptor.initialize(null, classDescriptor.getThisAsReceiverParameter(), emptyList(), emptyList(),
classDescriptor.builtIns.getAnyType(), Modality.OPEN, Visibilities.PUBLIC)
fakeDescriptor.initialize(null, classDescriptor.thisAsReceiverParameter, emptyList(), emptyList(),
classDescriptor.builtIns.anyType, Modality.OPEN, Visibilities.PUBLIC)
val fakeCodegen = ExpressionCodegen(
this, FrameMap(), OBJECT_TYPE, context.intoFunction(fakeDescriptor), state, this@PropertyReferenceCodegen
@@ -152,24 +147,26 @@ public class PropertyReferenceCodegen(
}
private fun generateMethod(debugString: String, access: Int, method: Method, generate: InstructionAdapter.() -> Unit) {
val mv = v.newMethod(JvmDeclarationOrigin.NO_ORIGIN, access, method.getName(), method.getDescriptor(), null, null)
val mv = v.newMethod(JvmDeclarationOrigin.NO_ORIGIN, access, method.name, method.descriptor, null, null)
if (state.classBuilderMode == ClassBuilderMode.FULL) {
val iv = InstructionAdapter(mv)
iv.visitCode()
iv.generate()
iv.areturn(method.getReturnType())
iv.areturn(method.returnType)
FunctionCodegen.endVisit(mv, debugString, element)
}
}
override fun generateKotlinAnnotation() {
writeKotlinSyntheticClassAnnotation(v, state)
writeSyntheticClassMetadata(v)
}
public fun putInstanceOnStack(): StackValue =
StackValue.operation(wrapperMethod.getReturnType()) { iv ->
iv.getstatic(asmType.getInternalName(), JvmAbi.INSTANCE_FIELD, wrapperMethod.getReturnType().getDescriptor())
fun putInstanceOnStack(): StackValue =
StackValue.operation(wrapperMethod.returnType) { iv ->
iv.getstatic(asmType.internalName, JvmAbi.INSTANCE_FIELD, wrapperMethod.returnType.descriptor)
}
companion object {

View File

@@ -31,7 +31,7 @@ import org.jetbrains.kotlin.types.KotlinType;
import java.util.List;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.BUILT_INS_PACKAGE_FQ_NAME;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.RANGES_PACKAGE_FQ_NAME;
import static org.jetbrains.kotlin.codegen.AsmUtil.isPrimitiveNumberClassDescriptor;
public class RangeCodegenUtil {
@@ -53,8 +53,8 @@ public class RangeCodegenUtil {
ImmutableMap.Builder<FqName, PrimitiveType> rangeBuilder = ImmutableMap.builder();
ImmutableMap.Builder<FqName, PrimitiveType> progressionBuilder = ImmutableMap.builder();
for (PrimitiveType primitiveType : supportedRangeTypes()) {
FqName rangeClassFqName = BUILT_INS_PACKAGE_FQ_NAME.child(Name.identifier(primitiveType.getTypeName() + "Range"));
FqName progressionClassFqName = BUILT_INS_PACKAGE_FQ_NAME.child(Name.identifier(primitiveType.getTypeName() + "Progression"));
FqName rangeClassFqName = RANGES_PACKAGE_FQ_NAME.child(Name.identifier(primitiveType.getTypeName() + "Range"));
FqName progressionClassFqName = RANGES_PACKAGE_FQ_NAME.child(Name.identifier(primitiveType.getTypeName() + "Progression"));
rangeBuilder.put(rangeClassFqName, primitiveType);
progressionBuilder.put(progressionClassFqName, primitiveType);
}

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(),
@@ -95,6 +96,8 @@ public class SamWrapperCodegen {
writeKotlinSyntheticClassAnnotation(cv, state);
WriteAnnotationUtilKt.writeSyntheticClassMetadata(cv);
// e.g. ASM type for Function2
Type functionAsmType = typeMapper.mapType(functionType);

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

@@ -26,7 +26,7 @@ import org.jetbrains.kotlin.resolve.jvm.diagnostics.RawSignature
import org.jetbrains.org.objectweb.asm.FieldVisitor
import org.jetbrains.org.objectweb.asm.MethodVisitor
public abstract class SignatureCollectingClassBuilderFactory(
abstract class SignatureCollectingClassBuilderFactory(
delegate: ClassBuilderFactory
) : DelegatingClassBuilderFactory(delegate) {
@@ -67,7 +67,7 @@ public abstract class SignatureCollectingClassBuilderFactory(
override fun done() {
for ((signature, elementsAndDescriptors) in signatures.entrySet()) {
if (elementsAndDescriptors.size() == 1) continue // no clash
if (elementsAndDescriptors.size == 1) continue // no clash
handleClashingSignatures(ConflictingJvmDeclarationsData(
classInternalName,
classCreatedFor,

View File

@@ -22,19 +22,19 @@ import org.jetbrains.kotlin.backend.common.CodegenUtil
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedFunction
data public class SourceInfo(val source: String, val pathOrCleanFQN: String, val linesInFile: Int) {
data class SourceInfo(val source: String, val pathOrCleanFQN: String, val linesInFile: Int) {
companion object {
fun createInfo(element: KtElement?, internalClassName: String): SourceInfo {
assert(element != null) { "Couldn't create source mapper for null element " + internalClassName }
val lineNumbers = CodegenUtil.getLineNumberForElement(element!!.getContainingFile(), true)
assert(lineNumbers != null) { "Couldn't extract line count in " + element.getContainingFile() }
val lineNumbers = CodegenUtil.getLineNumberForElement(element!!.containingFile, true)
assert(lineNumbers != null) { "Couldn't extract line count in " + element.containingFile }
//TODO hack condition for package parts cleaning
val isTopLevel = element is KtFile || (element is KtNamedFunction && element.getParent() is KtFile)
val cleanedClassFqName = if (!isTopLevel) internalClassName else internalClassName.substringBefore('$')
return SourceInfo(element.getContainingKtFile().getName(), cleanedClassFqName, lineNumbers!!)
return SourceInfo(element.getContainingKtFile().name, cleanedClassFqName, lineNumbers!!)
}
}

View File

@@ -17,12 +17,14 @@
package org.jetbrains.kotlin.codegen;
import com.intellij.psi.tree.IElementType;
import kotlin.ArraysKt;
import kotlin.Unit;
import kotlin.collections.ArraysKt;
import kotlin.collections.CollectionsKt;
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 +47,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 +505,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 +535,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 +551,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();
@@ -597,11 +600,7 @@ public abstract class StackValue {
}
public static Field singletonViaInstance(ClassDescriptor classDescriptor, JetTypeMapper typeMapper) {
return field(FieldInfo.createSingletonViaInstance(classDescriptor, typeMapper, false), none());
}
public static Field oldSingleton(ClassDescriptor classDescriptor, JetTypeMapper typeMapper) {
return field(FieldInfo.createForSingleton(classDescriptor, typeMapper, true), none());
return field(FieldInfo.createSingletonViaInstance(classDescriptor, typeMapper), none());
}
public static StackValue operation(Type type, Function1<InstructionAdapter, Unit> lambda) {
@@ -770,13 +769,14 @@ public abstract class StackValue {
private final Callable callable;
private final boolean isGetter;
private final ExpressionCodegen codegen;
private final ArgumentGenerator argumentGenerator;
private final List<ResolvedValueArgument> valueArguments;
private final FrameMap frame;
private final StackValue receiver;
private final ResolvedCall<FunctionDescriptor> resolvedGetCall;
private final ResolvedCall<FunctionDescriptor> resolvedSetCall;
private DefaultCallMask mask;
private DefaultCallArgs defaultArgs;
private CallGenerator callGenerator;
boolean isComplexOperationWithDup;
public CollectionElementReceiver(
@NotNull Callable callable,
@@ -785,7 +785,6 @@ public abstract class StackValue {
ResolvedCall<FunctionDescriptor> resolvedSetCall,
boolean isGetter,
@NotNull ExpressionCodegen codegen,
ArgumentGenerator argumentGenerator,
List<ResolvedValueArgument> valueArguments
) {
super(OBJECT_TYPE);
@@ -795,7 +794,6 @@ public abstract class StackValue {
this.receiver = receiver;
this.resolvedGetCall = resolvedGetCall;
this.resolvedSetCall = resolvedSetCall;
this.argumentGenerator = argumentGenerator;
this.valueArguments = valueArguments;
this.codegen = codegen;
this.frame = codegen.myFrameMap;
@@ -805,8 +803,25 @@ public abstract class StackValue {
public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
ResolvedCall<?> call = isGetter ? resolvedGetCall : resolvedSetCall;
StackValue newReceiver = StackValue.receiver(call, receiver, codegen, callable);
ArgumentGenerator generator = createArgumentGenerator();
newReceiver.put(newReceiver.type, v);
mask = argumentGenerator.generate(valueArguments, valueArguments);
callGenerator.putHiddenParams();
defaultArgs = generator.generate(valueArguments, valueArguments);
}
private ArgumentGenerator createArgumentGenerator() {
assert callGenerator == null :
"'putSelector' and 'createArgumentGenerator' methods should be called once for CollectionElementReceiver: " + callable;
ResolvedCall<FunctionDescriptor> resolvedCall = isGetter ? resolvedGetCall : resolvedSetCall;
assert resolvedCall != null : "Resolved call should be non-null: " + callable;
callGenerator =
!isComplexOperationWithDup ? codegen.getOrCreateCallGenerator(resolvedCall) : codegen.defaultCallGenerator;
return new CallBasedArgumentGenerator(
codegen,
callGenerator,
resolvedCall.getResultingDescriptor().getValueParameters(), callable.getValueParameterTypes()
);
}
@Override
@@ -834,7 +849,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 +857,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 +878,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 {
@@ -934,14 +949,22 @@ public abstract class StackValue {
if (getter == null) {
throw new UnsupportedOperationException("no getter specified");
}
CallGenerator callGenerator = codegen.defaultCallGenerator;
CallGenerator callGenerator = getCallGenerator();
callGenerator.genCall(getter, resolvedGetCall, genDefaultMaskIfPresent(callGenerator), codegen);
coerceTo(type, v);
}
private boolean genDefaultMaskIfPresent(CallGenerator callGenerator) {
DefaultCallMask mask = ((CollectionElementReceiver) receiver).mask;
return mask.generateOnStackIfNeeded(callGenerator);
DefaultCallArgs defaultArgs = ((CollectionElementReceiver) receiver).defaultArgs;
return defaultArgs.generateOnStackIfNeeded(callGenerator, true);
}
private CallGenerator getCallGenerator() {
CallGenerator generator = ((CollectionElementReceiver) receiver).callGenerator;
assert generator != null :
"CollectionElementReceiver should be putted on stack before CollectionElement:" +
" getCall = " + resolvedGetCall + ", setCall = " + resolvedSetCall;
return generator;
}
@Override
@@ -970,8 +993,8 @@ public abstract class StackValue {
}
}
if (call.getDispatchReceiver().exists()) {
if (call.getExtensionReceiver().exists()) {
if (call.getDispatchReceiver() != null) {
if (call.getExtensionReceiver() != null) {
return false;
}
}
@@ -993,8 +1016,13 @@ public abstract class StackValue {
Type lastParameterType = ArraysKt.last(setter.getParameterTypes());
coerce(topOfStackType, lastParameterType, v);
//*Convention setter couldn't have default parameters, just getter can have it at last positions
getCallGenerator().afterParameterPut(lastParameterType, StackValue.onStack(lastParameterType),
CollectionsKt.getLastIndex(setter.getValueParameterTypes()));
//Convention setter couldn't have default parameters, just getter can have it at last positions
//We should remove default parameters of getter from stack*/
//Note that it works only for non-inline case
CollectionElementReceiver collectionElementReceiver = (CollectionElementReceiver) receiver;
if (collectionElementReceiver.isGetter) {
List<ResolvedValueArgument> arguments = collectionElementReceiver.valueArguments;
@@ -1009,7 +1037,7 @@ public abstract class StackValue {
}
}
codegen.defaultCallGenerator.genCall(setter, resolvedSetCall, false, codegen);
getCallGenerator().genCall(setter, resolvedSetCall, false, codegen);
Type returnType = setter.getReturnType();
if (returnType != Type.VOID_TYPE) {
pop(v, returnType);
@@ -1090,6 +1118,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();
}
}
}
@@ -1134,6 +1168,11 @@ public abstract class StackValue {
else {
coerce(topOfStackType, ArraysKt.last(setter.getParameterTypes()), v);
setter.genInvokeInstruction(v);
Type returnType = setter.getReturnType();
if (returnType != Type.VOID_TYPE) {
pop(v, returnType);
}
}
}
@@ -1525,6 +1564,11 @@ public abstract class StackValue {
super(value.type, value.receiver.canHaveSideEffects());
this.originalValueWithReceiver = value;
this.isReadOperations = isReadOperations;
if (value instanceof CollectionElement) {
if (value.receiver instanceof CollectionElementReceiver) {
((CollectionElementReceiver) value.receiver).isComplexOperationWithDup = true;
}
}
}
@Override

View File

@@ -44,7 +44,7 @@ class CoercionValue(
}
public class StackValueWithLeaveTask(
class StackValueWithLeaveTask(
val stackValue: StackValue,
val leaveTasks: (StackValue) -> Unit
) : StackValue(stackValue.type) {

View File

@@ -22,15 +22,15 @@ import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.name.FqName
public interface WrappedAnnotated : Annotated {
public val originalAnnotated: Annotated
interface WrappedAnnotated : Annotated {
val originalAnnotated: Annotated
}
public class AnnotatedWithFakeAnnotations(override val originalAnnotated: Annotated, private val actual: Annotations) : WrappedAnnotated {
class AnnotatedWithFakeAnnotations(override val originalAnnotated: Annotated, private val actual: Annotations) : WrappedAnnotated {
override fun getAnnotations() = actual
}
public class AnnotatedWithOnlyTargetedAnnotations(private val original: Annotated) : Annotated {
class AnnotatedWithOnlyTargetedAnnotations(private val original: Annotated) : Annotated {
private val annotations: Annotations = UseSiteTargetedAnnotations(original.annotations)
override fun getAnnotations() = annotations
@@ -52,4 +52,4 @@ public class AnnotatedWithOnlyTargetedAnnotations(private val original: Annotate
}
}
public class AnnotatedSimple(annotations: Annotations) : AnnotatedImpl(annotations)
class AnnotatedSimple(annotations: Annotations) : AnnotatedImpl(annotations)

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
@@ -43,15 +43,14 @@ class BridgeForBuiltinSpecial<Signature>(
)
object BuiltinSpecialBridgesUtil {
@JvmStatic
public fun <Signature> generateBridgesForBuiltinSpecial(
@JvmStatic fun <Signature> generateBridgesForBuiltinSpecial(
function: FunctionDescriptor,
signatureByDescriptor: (FunctionDescriptor) -> Signature
): Set<BridgeForBuiltinSpecial<Signature>> {
val functionHandle = DescriptorBasedFunctionHandle(function)
val fake = !functionHandle.isDeclaration
val overriddenBuiltin = function.getOverriddenBuiltinWithDifferentJvmDescriptor()!!
val overriddenBuiltin = function.getOverriddenBuiltinReflectingJvmDescriptor()!!
val reachableDeclarations = findAllReachableDeclarations(function)
@@ -93,13 +92,12 @@ object BuiltinSpecialBridgesUtil {
return bridges
}
@JvmStatic
public fun <Signature> FunctionDescriptor.shouldHaveTypeSafeBarrier(
@JvmStatic fun <Signature> FunctionDescriptor.shouldHaveTypeSafeBarrier(
signatureByDescriptor: (FunctionDescriptor) -> Signature
): Boolean {
if (BuiltinMethodsWithSpecialGenericSignature.getDefaultValueForOverriddenBuiltinFunction(this) == null) return false
val builtin = getOverriddenBuiltinWithDifferentJvmDescriptor()!!
val builtin = getOverriddenBuiltinReflectingJvmDescriptor()!!
return signatureByDescriptor(this) == signatureByDescriptor(builtin)
}
}
@@ -134,7 +132,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
@@ -143,7 +141,7 @@ private fun <Signature> needGenerateSpecialBridge(
&& signatureByDescriptor(it) == overriddenBuiltinSignature }
}
public fun isValueArgumentForCallToMethodWithTypeCheckBarrier(
fun isValueArgumentForCallToMethodWithTypeCheckBarrier(
element: KtElement,
bindingContext: BindingContext
): Boolean {

View File

@@ -47,7 +47,7 @@ private fun List<PackageParts>.addCompiledParts(state: GenerationState): List<Pa
mapping.findPackageParts(qualifier)?.run { parts.remove(name) }
}
return (this + mapping.packageFqName2Parts.values())
return (this + mapping.packageFqName2Parts.values)
.groupBy { it.packageFqName }
.map {
val (packageFqName, packageParts) = it

View File

@@ -17,17 +17,29 @@
package org.jetbrains.kotlin.codegen
import org.jetbrains.kotlin.codegen.context.FieldOwnerContext
import org.jetbrains.kotlin.codegen.intrinsics.TypeIntrinsics
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.load.java.JvmAbi
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.kotlin.types.TypeUtils
import org.jetbrains.org.objectweb.asm.Label
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
fun generateIsCheck(
v: InstructionAdapter,
type: KotlinType,
generateInstanceOfInstruction: (InstructionAdapter) -> Unit
kotlinType: KotlinType,
asmType: Type
) {
if (type.isMarkedNullable) {
if (TypeUtils.isNullableType(kotlinType)) {
val nope = Label()
val end = Label()
@@ -36,7 +48,8 @@ fun generateIsCheck(
ifnull(nope)
generateInstanceOfInstruction(this)
TypeIntrinsics.instanceOf(this, kotlinType, asmType)
goTo(end)
mark(nope)
@@ -47,10 +60,69 @@ fun generateIsCheck(
}
}
else {
generateInstanceOfInstruction(v)
TypeIntrinsics.instanceOf(v, kotlinType, asmType)
}
}
fun generateAsCast(
v: InstructionAdapter,
kotlinType: KotlinType,
asmType: Type,
isSafe: Boolean
) {
if (!isSafe) {
if (!TypeUtils.isNullableType(kotlinType)) {
generateNullCheckForNonSafeAs(v, kotlinType)
}
}
else {
with(v) {
dup()
TypeIntrinsics.instanceOf(v, kotlinType, asmType)
val ok = Label()
ifne(ok)
pop()
aconst(null)
mark(ok)
}
}
public fun SpecialSignatureInfo.replaceValueParametersIn(sourceSignature: String?): String?
TypeIntrinsics.checkcast(v, kotlinType, asmType, isSafe)
}
private 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)
}
}
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 (!JvmAbi.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,8 +28,8 @@ 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.resolve.annotations.AnnotationUtilKt;
import org.jetbrains.kotlin.storage.LockBasedStorageManager;
import org.jetbrains.kotlin.storage.NullableLazyValue;
import org.jetbrains.kotlin.types.KotlinType;
@@ -37,7 +38,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 +268,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 +284,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 +299,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 +366,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 +516,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")
@@ -601,6 +610,8 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
boolean withinInline,
boolean isSuperCall
) {
if (AnnotationUtilKt.isInlineOnly(unwrappedDescriptor)) return false;
return isSuperCall && withinInline ||
(accessFlag & ACC_PRIVATE) != 0 ||
((accessFlag & ACC_PROTECTED) != 0 &&
@@ -632,7 +643,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 +651,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

@@ -16,24 +16,16 @@
package org.jetbrains.kotlin.codegen.context
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.org.objectweb.asm.Type
public object CodegenContextUtil {
@JvmStatic
public fun getImplementationOwnerClassType(owner: CodegenContext<*>): Type? =
object CodegenContextUtil {
@JvmStatic fun getImplementationOwnerClassType(owner: CodegenContext<*>): Type? =
when (owner) {
is DelegatingFacadeContext -> owner.delegateToClassType
is MultifileClassFacadeContext -> owner.filePartType
is DelegatingToPartContext -> owner.implementationOwnerClassType
else -> null
}
@JvmStatic
public fun getImplementationClassShortName(owner: CodegenContext<*>): String? =
getImplementationOwnerClassType(owner)?.let { AsmUtil.shortNameByAsmType(it) }
@JvmStatic
public fun isImplClassOwner(owner: CodegenContext<*>): Boolean =
owner !is DelegatingFacadeContext
}
@JvmStatic fun isImplClassOwner(owner: CodegenContext<*>): Boolean =
owner !is MultifileClassFacadeContext
}

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

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