Compare commits

...

239 Commits

Author SHA1 Message Date
Ilya Gorbunov
67758d8701 fixup! step 2: keep iterators in public, but deprecated with error 2021-03-26 20:16:09 +03:00
Ilya Gorbunov
6e723a25e9 Stabilize unsigned types, fix compiler tests
Drop unsignedLiteralsOn1_2 because apiversion 1.2 is no longer supported
Drop experimental unsigned literals diagnostic test
2021-03-23 12:11:42 +03:00
Ilya Gorbunov
7cd18707d5 Stabilize unsigned types: update JS API dump 2021-03-22 14:40:43 +03:00
Ilya Gorbunov
805c7a51b2 Stabilize unsigned types, step 2
Remove specialized iterators from public API
2021-03-22 14:05:14 +03:00
Ilya Gorbunov
ab86030769 Stabilize unsigned types, step 1 2021-03-22 14:05:13 +03:00
Svyatoslav Scherbina
8b3ff11a2b Provide CName annotation in common stdlib as optional 2021-03-22 09:20:05 +00:00
Svyatoslav Scherbina
552bd108a9 stdlib: rename NativeAnnotationsH.kt -> NativeConcurrentAnnotations.kt
Also move it from libraries/stdlib/common/src/kotlin
to libraries/stdlib/src/kotlin/annotations
2021-03-22 09:20:05 +00:00
Igor Yakovlev
25929b50d9 [FIR IDE] RawFirBuilder for lazy bodies 2021-03-21 10:42:29 +01:00
Nikolay Krasko
1558bd7373 Trust all module metadata till Gradle 6.8 update (KTI-493)
There's and issue with absent module files in the cache that leads to
"Artifact has been deleted from dependency cache" that can be resolved
by cleaning caches. It should be fixed in Gradle 6.8

https://github.com/gradle/gradle/issues/12713
2021-03-21 00:05:54 +03:00
Nikolay Krasko
73bc16896d Trust all poms till Gradle 6.8 update (KTI-493)
There's and issue with absent poms in the cache that leads to
"Artifact has been deleted from dependency cache" that can be resolved
by cleaning caches. It should be fixed in Gradle 6.8

https://github.com/gradle/gradle/issues/12713
2021-03-21 00:05:54 +03:00
Nikolay Krasko
efcb071f24 Trust javadoc and sources artifacts as the shouldn't be used in builds (KTI-493) 2021-03-21 00:05:53 +03:00
Nikolay Krasko
fd921f1dc0 Trust kotlin-native-prebuild-* (KTI-493)
Need more investigation for this artifact
2021-03-21 00:05:53 +03:00
Nikolay Krasko
fae1215881 Trust kotlin artifacts for bootstrapping (KTI-493)
Can't predict exact version after build
2021-03-21 00:05:53 +03:00
Nikolay Krasko
4bbba74360 Trust ivy xml files as they are constantly regenerated (KTI-493) 2021-03-21 00:05:52 +03:00
Nikolay Krasko
8240f5e459 Add dependencies lock with md5 and sha256 (KTI-493)
Initial commit without explicit check or cleanup.

Includes Kotlin Native dependencies.
2021-03-21 00:05:52 +03:00
Keegan Witt
a1ceaa9e44 Change pronoun in execption from "his" to "its" 2021-03-19 23:36:53 +01:00
Ilya Goncharov
f85ad41674 [IR] Check pureness in inlining lowering after transformation 2021-03-19 21:52:51 +03:00
Ilya Goncharov
8ac8dbdab8 [JS IR] Type operator call pureness 2021-03-19 21:52:51 +03:00
Ilya Goncharov
47d050c420 [JS IR] Correct pureness of expressions for arrayLiteral 2021-03-19 21:52:50 +03:00
Ilya Goncharov
f890156dde [JS IR] arrayConcat not use additional slice 2021-03-19 21:52:50 +03:00
Ilya Goncharov
76005813ff [JS IR] Fix for pureness of vararg 2021-03-19 21:52:50 +03:00
Ilya Goncharov
278a8c27fc [JS IR] Not create temporary variable for pure expressions on inline 2021-03-19 21:52:50 +03:00
Ilya Goncharov
ece0e200d5 [JS IR] Not nullize external varargs if it is not on the end of call 2021-03-19 21:52:50 +03:00
Ilya Goncharov
b8d5712bc0 [JS IR] Not use double slice for external varargs 2021-03-19 21:52:50 +03:00
Ilya Goncharov
120b5b9e05 [JS IR] Move isPure check to backend.common and add platform-specific check on calls with side effects 2021-03-19 21:52:50 +03:00
Ilya Goncharov
7bbb5b77db [JS IR] Concat varargs with non varargs on compile time for function w/o receiver 2021-03-19 21:52:50 +03:00
Ilya Goncharov
fc559ab0cd [JS IR] Unite varargs and non varargs before vararg 2021-03-19 21:52:49 +03:00
Dmitry Petrov
9e30ddd12e JVM_IR KT-45581 generate H_INVOKEINTERFACE for interface method handles 2021-03-19 18:57:21 +03:00
Dmitry Petrov
73d4fa65ea JVM_IR KT-45431 don't optimize out $$delegatedProperties in companion
Corresponding delegates are initialized in the host class, using
'$$delegatedProperties'.
TODO figure out proper code generation scheme for delegated properties
in companions (KT-45580)
2021-03-19 18:54:01 +03:00
Dmitry Petrov
f6baabd98e JVM_IR KT-45408 rewrite static calls recursively 2021-03-19 18:53:59 +03:00
Alexander Udalov
e5f218859b JVM IR: minor, improve error messages for inline classes
It will help in diagnosing problems like KT-44723.
2021-03-19 16:33:42 +01:00
Ivan Kylchik
65fcd72ce1 [VISUALIZER] Add handler for dot qualified expression in fir
For some reason source element of such expression in fir
was changed, so to get FirFunctionCall we should seek it
in KtDotQualifiedExpression
2021-03-19 18:30:35 +03:00
Ivan Kylchik
0160174c7a Extract VisualizerDirectives to separate file 2021-03-19 18:30:34 +03:00
Ivan Kylchik
de351d8bd3 Extract output handlers in visualiser's tests to separate files 2021-03-19 18:30:33 +03:00
Ivan Kylchik
6a439ad186 Add Test postfix to Abstract(Psi|Fir)Visualizer classes 2021-03-19 18:30:31 +03:00
Ivan Kylchik
5efa00821d Replace junit dependencies with single testApiJUnit5 call 2021-03-19 18:30:30 +03:00
Ivan Kylchik
6f639a39a7 Remove unnecessary dependencies on visualizer module 2021-03-19 18:30:28 +03:00
Ivan Kylchik
13ef126d4c [VISUALIZER] Remove ignore directive from correct test files 2021-03-19 18:30:27 +03:00
Ivan Kylchik
59416f447e [VISUALIZER] Change rendering of equals call 2021-03-19 18:30:26 +03:00
Ivan Kylchik
dd8a7010f0 [VISUALIZER] Forbid to render unary minus for integer literals 2021-03-19 18:30:25 +03:00
Ivan Kylchik
685f599c82 [VISUALIZER] Allow to render all calls at unary expresion in fir 2021-03-19 18:30:23 +03:00
Ivan Kylchik
84d4a0609f [VISUALIZER] Fix typealias rendering in fir 2021-03-19 18:30:22 +03:00
Ivan Kylchik
c94a4e7baf [VISUALIZER] Fix class literals rendering 2021-03-19 18:30:21 +03:00
Ivan Kylchik
fb654ce09b [VISUALIZER] Fix extension types rendering in fir 2021-03-19 18:30:20 +03:00
Ivan Kylchik
9e5645777d [VISUALIZER] Add annotation text for backing field in fir 2021-03-19 18:30:19 +03:00
Ivan Kylchik
813e48ffb4 [VISUALIZER] Replace rendering of class with no name to anonymous 2021-03-19 18:30:18 +03:00
Ivan Kylchik
ca424a94ef [VISUALIZER] Add local path to local declarations in fir 2021-03-19 18:30:16 +03:00
Ivan Kylchik
607c7b3e82 [VISUALIZER] Add implicit receiver rendering in fir 2021-03-19 18:30:15 +03:00
Ivan Kylchik
0ca0304865 [VISUALIZER] Fix render of null constant in fir 2021-03-19 18:30:14 +03:00
Ivan Kylchik
a497a2fa9b [VISUALIZER] Forbid to render type of single underscore variable 2021-03-19 18:30:13 +03:00
Ivan Kylchik
48ee4791b6 [VISUALIZER] Fix rendering of enum class and enum entry in fir 2021-03-19 18:30:12 +03:00
Ivan Kylchik
e2a7da25b0 [VISUALIZER] Rewrite fir symbol's rendering 2021-03-19 18:30:10 +03:00
Ivan Kylchik
4259ad2d84 [VISUALIZER] Change result of psi render according to new test data 2021-03-19 18:30:09 +03:00
Ivan Kylchik
3e66d12bef [FIR] Change some raw-fir test files to make them correct
"correct" means that these files can be compiled. This change is
necessary for visualizer. Don't want to ignore these test files,
so they must not produce errors.
2021-03-19 18:30:08 +03:00
Ivan Kylchik
951d607445 [VISUALIZER] Forbid to walk inside type reference children in psi 2021-03-19 18:30:07 +03:00
Ivan Kylchik
cc7d82ab7b [VISUALIZER] Change rendering of equality operator 2021-03-19 18:30:06 +03:00
Ivan Kylchik
c678ad9eb9 [VISUALIZER] Fix superTypes test 2021-03-19 18:30:05 +03:00
Ivan Kylchik
05efb8c129 [VISUALIZER] Add possibility to render callable reference in fir part 2021-03-19 18:30:04 +03:00
Ivan Kylchik
ce844a9bba [VISUALIZER] Disable rendering of value arguments in psi part
For now instead of arguments will be rendered parameters
2021-03-19 18:30:03 +03:00
Ivan Kylchik
f2cf86a3ae [VISUALIZER] Fix package rendering 2021-03-19 18:30:02 +03:00
Ivan Kylchik
c4be67b518 [VISUALIZER] Change rendering of constructors in fir part 2021-03-19 18:30:01 +03:00
Ivan Kylchik
945cc36ce3 [VISUALIZER] Add annotation at Array.set method 2021-03-19 18:30:00 +03:00
Ivan Kylchik
ca1b20c7f4 [VISUALIZER] Add some tests to ignore list 2021-03-19 18:29:58 +03:00
Ivan Kylchik
919591909e Update test data for compiler visualizer 2021-03-19 18:29:56 +03:00
Ivan Kylchik
4ac38e5f29 Rewrite compiler visualizer tests using new test infrastructure 2021-03-19 18:29:55 +03:00
Roman Golyshev
4c0cab4756 FIR IDE: Always insert additional spaces into lambda brackets
The customization of this with
`INSERT_WHITESPACES_IN_SIMPLE_ONE_LINE_METHOD` will be supported later
2021-03-19 17:44:15 +03:00
Alexander Udalov
415d52fe54 Deprecate KotlinJvmOptions.useIR
Starting from language version 1.5, JVM IR is enabled by default, so
this option has no effect. To rollback to the old JVM backend, the new
option useOldBackend can be used.

 #KT-45504 Fixed
2021-03-19 14:57:55 +01:00
Alexander Udalov
a10ebcea51 Minor, add -Xopt-in=kotlin.RequiresOptIn to kotlin-test-js
To prevent compilation warning on usages of OptIn in new
assertContentEquals functions.
2021-03-19 14:56:37 +01:00
Alexander Udalov
b33d245dfb Do not print stdlib version substitution message if nothing changed 2021-03-19 14:56:14 +01:00
Alexander Udalov
ec3799a696 Do not print total bytes written in :core:builtins:serialize
To reduce the amount of output on a clean build. Will have effect after
the next bootstrap update.
2021-03-19 14:56:14 +01:00
Anastasiya Shadrina
94c4d1c23e Specify when the range is empty in KDoc 2021-03-19 20:40:06 +07:00
Victor Petukhov
60f2f85be7 Process captured types with type variable inside properly, in the operations related with the type variables fixation 2021-03-19 16:16:11 +03:00
Victor Petukhov
a2b1aa753b Substitute captured types with type variables properly
^KT-44687 Fixed
2021-03-19 16:16:09 +03:00
Sergey Bogolepov
d276d583ba Keep host_os and host_arch methods for backward-compatibility
Because it is still used by IDE plugin
2021-03-19 15:24:45 +03:00
Sergey Bogolepov
af3ff6c4d6 Revert "Revert "Remove unused protobuf from backend.native""
This reverts commit c4182c82
2021-03-19 15:24:44 +03:00
Sergey Bogolepov
bba82c0d60 Revert "Revert "Remove obsolete bc.frontend module""
This reverts commit e7a385f9
2021-03-19 15:24:43 +03:00
Sergey Bogolepov
30e9c645f8 Revert "Revert "Cleanup TargetManager.kt a little bit""
This reverts commit 3dd25e49
2021-03-19 15:24:42 +03:00
Sergey Bogolepov
1d8d76eb7f Revert "Revert "Cleanup HostManager.kt a little bit""
This reverts commit 98b2c000
2021-03-19 15:24:41 +03:00
Roman Golyshev
184838ae35 FIR IDE: Fix import of properties; also fix bug in alreadyHasImport 2021-03-19 12:37:43 +03:00
Roman Golyshev
054d6ccdfb FIR IDE: Refactor KotlinFirLookupElementFactory 2021-03-19 12:37:43 +03:00
Roman Golyshev
9db8bd8d38 FIR IDE: Refactor variables insertion handlers 2021-03-19 12:37:43 +03:00
Roman Golyshev
84386237a6 FIR IDE: Refactor classifiers insertion handlers 2021-03-19 12:37:42 +03:00
Roman Golyshev
fe921b98ce FIR IDE: Refactor functions insertion handler 2021-03-19 12:37:42 +03:00
Roman Golyshev
43b829b1f0 Fix test data
We do not need to check the imports order in this particular test
2021-03-19 12:37:42 +03:00
Roman Golyshev
7b7ba717d0 FIR IDE: Add more correct importing of the callables
Now we use scopes to decide if the callable really needs to be inserted
2021-03-19 12:37:42 +03:00
Roman Golyshev
76ff106458 FIR: Add collecting top-level scopes of the file
It will be useful in the completion when we need to dicide if we
need to import FQN or not
2021-03-19 12:37:42 +03:00
Roman Golyshev
3427e0aebb FIR IDE: Add extensions function completion from indices
The insertion handling test is not correct, we need to check file
imports before adding new ones
2021-03-19 12:37:41 +03:00
Roman Golyshev
8396e17c52 Improve test data (to avoid clash with stdlib) 2021-03-19 12:37:41 +03:00
Roman Golyshev
83a9b4fb87 FIR IDE: Only insert FqNames for non-extension non-members properties
This is not completely correct, will be fixed later
2021-03-19 12:37:41 +03:00
Roman Golyshev
bf52417268 Add test for synthetic java property completion to multi-file tests 2021-03-19 12:37:41 +03:00
Roman Golyshev
d955f8e0d3 FIR IDE: Add simple shortening completion handler for properties 2021-03-19 12:37:41 +03:00
Roman Golyshev
8392b36964 FIR IDE: Add more accurate shortening for properties 2021-03-19 12:37:41 +03:00
Roman Golyshev
03a1c6fcca Add multi-file completion handler tests for FIR code completion
This is a temporary (and dirty) solution to start using those tests as
fast as possible. We certainly need to refactor them so they can be
generated from the testData
2021-03-19 12:37:40 +03:00
Roman Golyshev
73e623b5ac Generate multi-file completion tests for FIR completion
Also remove `MultiFilePrimitiveJvmBasicCompletionTestGenerated` tests
2021-03-19 12:37:40 +03:00
Roman Golyshev
abeff5d5c5 Enable passing tests 2021-03-19 12:37:40 +03:00
Roman Golyshev
d6d3d3a6ad FIR IDE: Add completion for top level functions and properties 2021-03-19 12:37:40 +03:00
Roman Golyshev
62389bad0b FIR IDE: Add more useful Lookup Objects
Main purpose of those lookup objects for now is to allow same lookup
elements to merge
2021-03-19 12:37:40 +03:00
Roman Golyshev
ab191925cb FIR IDE: Update test data for completion handlers test 2021-03-19 12:37:39 +03:00
Roman Golyshev
9896512eda FIR IDE: Collect scopes information in reanalyze
It is needed for the completion, so after the changes in method bodies
all contexts are correctly collected
2021-03-19 12:37:39 +03:00
Roman Golyshev
f641466f70 FIR IDE: Fix searching for the closest function to re-resolve
If the function is local, there would be errors related to its
unresolved body and receiver type
2021-03-19 12:37:39 +03:00
Roman Golyshev
1d64c0789f FIR IDE: Add implementation of classifiers completion from indices 2021-03-19 12:37:38 +03:00
Alexander Shabalin
5b1c30c198 Extract initializing singleton marker
* Extract kInitializingSingleton marker
* Extract isNullOrMarker helper function
2021-03-19 08:19:10 +00:00
Vasily Levchenko
b3ae30fdea [llvm][context util] make error more readable 2021-03-19 08:04:00 +00:00
Sergey Bogolepov
e320f7efc3 Add libffi buildscript for Apple Silicon 2021-03-19 07:21:39 +00:00
Svyatoslav Scherbina
a9d0409f2e Don't use Function.reflect() in kotlin-native/Interop on JVM
Use inline functions and typeOf<T>() instead
2021-03-19 06:53:09 +00:00
Alexander Likhachev
008e2636b7 [Gradle] Prevent early capturing of project build dir in KotlinCompile
#KT-45301 Fixed
2021-03-18 19:51:08 +00:00
Ilya Gorbunov
42648d55a0 kotlin-test: make assertIs<T> returning value cast to T KT-45296 2021-03-18 21:57:16 +03:00
Ilya Goncharov
2fd8620551 [Gradle, JS] Support custom display name in npm versions generator
^KT-42921 fixed
2021-03-18 21:32:15 +03:00
Ilya Goncharov
a291895ebe [Gradle, JS] Add compatibility with webpack 4
^KT-42921 fixed
2021-03-18 21:32:14 +03:00
Ilya Goncharov
a1a01a1428 [Gradle, JS] Use compatible node version
^KT-42921 fixed
2021-03-18 21:32:12 +03:00
Ilya Goncharov
b2a2616c10 [Gradle, JS] Fix of using format-util
^KT-42921 fixed
2021-03-18 21:32:11 +03:00
Ilya Goncharov
965426bbd9 [Gradle, JS] Webpack serve for webpack-dev-server
^KT-42921 fixed
2021-03-18 21:32:10 +03:00
Ilya Goncharov
5827ed3f05 [Gradle, JS] Update versions with karma-webpack 5.0.0
^KT-42921 fixed
2021-03-18 21:32:08 +03:00
Ilya Goncharov
1b8c74337e [Gradle, JS] Adopt Gradle plugin to webpack 5
^KT-42921 fixed
2021-03-18 21:32:07 +03:00
Ilya Goncharov
a06feaf819 Add possibility to hardcode version
^KT-42921 fixed
2021-03-18 21:32:05 +03:00
Ilya Goncharov
88abb3d6c9 [JS IR] Fix creating of classes extended from nested one
[JS IR] Extract getClassRef method

 ^KT-44950 fixed
2021-03-18 21:14:00 +03:00
Ilya Goncharov
a61312120b [Gradle, JS] WA for tests with multiple binaries 2021-03-18 20:07:48 +03:00
Ilya Goncharov
8ffe70cb4d [Gradle, JS] Use one folder for sync tasks 2021-03-18 20:07:47 +03:00
Dmitry Petrov
17da240910 JVM_IR KT-45195 generate non-static annotation members as ACC_ABSTRACT 2021-03-18 19:41:24 +03:00
Dmitry Petrov
2fd69a5718 Add bytecode listing tests for 'allopen' plugin with JVM_IR 2021-03-18 19:41:23 +03:00
Victor Turansky
e4d98d4e39 Gradle 7.0 support. com.gradle.plugin-publish 0.12.0 -> 0.13.0
[With Gradle 7+ support](https://plugins.gradle.org/plugin/com.gradle.plugin-publish/0.13.0)
2021-03-18 19:11:26 +03:00
Steven Schäfer
d0424465b8 JVM IR: Resolve fake overrides when calculating return types (KT-44867) 2021-03-18 16:02:35 +01:00
Pavel Punegov
cae95b1ba0 [native] Fix kotlin.native.home properties order. 2021-03-18 14:41:03 +00:00
Roman Artemev
44d03bc727 [Psi2Ir] Fix generation of property references for synthetic java props
- Declare it on use-site
 - Fix export checker for that case
 - Fix KT-45297
2021-03-18 16:50:31 +03:00
Roman Artemev
9632839253 [JVM IR] Add jvm box test for KT-45297 2021-03-18 16:50:27 +03:00
Roman Artemev
0a4f2bc39c [IR] Add irText test for KT-45297 2021-03-18 16:50:22 +03:00
Mikhail Zarechenskiy
78a0d7b5bb Disable check about unimplemented check for real defaults
Now we can generate proper defaults and there is no need in additional
 checks about unimplemented methods

 #KT-41130 Fixed
2021-03-18 16:38:55 +03:00
Mikhail Zarechenskiy
641f08d561 Use compiler arguments for Java against Kotlin highlighting tests
This is needed for the next commit to check jvm-default options

 #KT-41130 In Progress
2021-03-18 16:38:54 +03:00
Mikhail Zarechenskiy
111e54c8c1 Do not generate DefaultImpls for light classes if not needed
#KT-41130 In Progress
2021-03-18 16:38:52 +03:00
Dmitry Petrov
ac6232b4ba JVM_IR KT-36853 patch parents after tailrecPhase 2021-03-18 15:19:24 +03:00
Dmitriy Novozhilov
34f8c7a68b [TEST] Add ability to register compiler extensions in EnvironmentConfigurator 2021-03-18 14:00:38 +03:00
Ivan Gavrilovic
875ef73371 KT-45519: Get AGP version only once per classloader
Memoize AGP version per classloader, instead of computing
it once per project.

Fixes #KT-45519
2021-03-18 12:08:04 +03:00
Dmitriy Novozhilov
fc2d294b6c [FIR] Fix tower priorities for invoke resolve
#KT-45316 Fixed
2021-03-18 10:24:57 +03:00
Sergey Shanshin
cfca7183e5 Add inspections and quickfixes of redundant Json format instantiation
Resolves KT-45075
2021-03-18 05:44:03 +03:00
Alexander Udalov
27174de891 Add JVM target bytecode version 16
#KT-45515 Fixed
2021-03-17 21:31:08 +01:00
Andrei Klunnyi
09f9489619 [FIR]: sealed hierarchy processor for IDE
From now on sealed declarations get resolved with the help of
FirIdeSealedHierarchyProcessor. This change entails correct IDE side
check for sealed when exhaustiveness.
2021-03-17 19:43:49 +01:00
Nikolay Krasko
98b2c00083 Revert "Cleanup HostManager.kt a little bit"
This reverts commit 9d957f68
2021-03-17 20:40:48 +03:00
Nikolay Krasko
3dd25e4965 Revert "Cleanup TargetManager.kt a little bit"
This reverts commit a4010c7a
2021-03-17 20:40:29 +03:00
Nikolay Krasko
e7a385f9da Revert "Remove obsolete bc.frontend module"
This reverts commit b48a42a5
2021-03-17 20:40:00 +03:00
Nikolay Krasko
c4182c8269 Revert "Remove unused protobuf from backend.native"
This reverts commit 7a526a85
2021-03-17 20:39:35 +03:00
Ilya Gorbunov
85a0538f0a Compile and run common tests of kotlin-test in kotlin-test-js-ir build 2021-03-17 17:53:54 +03:00
Ilya Gorbunov
e66eeefe2a kotlin-test: assertIs and assertIsNot KT-45296
- Rename assertNotIs to assertIsNot
- Extract parts of implementation to helper internal PublishedApi
functions in order to inline minimum amount of code at use sites
- Remove PublishedApi from messagePrefix, no longer needed
2021-03-17 17:53:54 +03:00
Ben Asher
3a0219d84c kotlin-test: add assertIs and assertNotIs assertions KT-45296 2021-03-17 17:53:54 +03:00
Svyatoslav Scherbina
542518f290 Remove contents of kotlin-native/CHANGELOG.md
Keep only links to old and new changelogs.
2021-03-17 13:53:05 +00:00
Svyatoslav Scherbina
8a940fc075 Update kotlin-native/BUILDING_LLVM.md after build rework
Running `dependencies:update` task is no longer required.
2021-03-17 13:53:04 +00:00
Svyatoslav Scherbina
1f5830404c Native: remove documents that were migrated to kotlin-web-site
These documents were moved from kotlin-native repo to kotlin-web-site.
So copies that got merged into kotlin repo are unused.
2021-03-17 13:53:03 +00:00
Sergey Bogolepov
7a526a852f Remove unused protobuf from backend.native 2021-03-17 13:44:05 +00:00
Sergey Bogolepov
b48a42a5a6 Remove obsolete bc.frontend module 2021-03-17 13:44:04 +00:00
Sergey Bogolepov
a4010c7abe Cleanup TargetManager.kt a little bit 2021-03-17 13:44:03 +00:00
Sergey Bogolepov
9d957f686a Cleanup HostManager.kt a little bit 2021-03-17 13:44:03 +00:00
Sergey Bogolepov
d7bd3d671c Fix formatting of HostManager.kt 2021-03-17 13:44:02 +00:00
Dmitry Petrov
7fabc19326 JVM_IR KT-45446 don't erase captured var if it's dead code 2021-03-17 15:37:35 +03:00
Svyatoslav Kuzmich
6bd34db725 [JS IR] Fix kotlin.js.js with complex constant expressions
Use IR interpreter to evaluate complex constexprs
2021-03-17 15:12:18 +03:00
Jinseong Jeon
93289aa899 FIR checker: report VAL_REASSIGNMENT_VIA_BACKING_FIELD(_ERROR) 2021-03-17 15:04:44 +03:00
Mikhail Glukhikh
a6d11b8914 FirFunctionParameterChecker: use reportOnWithSuppression 2021-03-17 15:04:44 +03:00
Tianyu Geng
94de193993 FIR: introduce VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION check
Besides adding VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION,
we remove here NO_TYPE_FOR_TYPE_PARAMETER since it doesn't exist in FE1.0.
The name also doesn't make much sense.
From the usage it looks like it should have been
VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION instead.
2021-03-17 15:04:43 +03:00
sebastian.sellmair
f4b840467f CommonizerIT: Mark Windows as non-executable target 2021-03-17 10:55:46 +00:00
Dmitriy Dolovov
5a35018a88 [Commonizer] Move source code to the folder that corresponds package name 2021-03-17 13:34:14 +03:00
Dmitriy Dolovov
fc4f66b702 [Commonizer] Change the main package name
org.jetbrains.kotlin.descriptors.commonizer -> org.jetbrains.kotlin.commonizer
2021-03-17 13:34:06 +03:00
Alexander Dudinsky
28e4ce191b [Test] Add 'kotlin-stdlib-jdk7' to dependency for publishing KGP 2021-03-17 13:12:57 +03:00
Mark Punzalan
10d16d10d5 Raw FIR: Fix downward propagation of external and inline from
property to default accessors for light-tree.
2021-03-17 10:45:26 +01:00
Mark Punzalan
7d31ea3e8f FIR checker: Add utility functions for FirModifierList. 2021-03-17 10:45:26 +01:00
Mark Punzalan
315047b164 FIR checker: Make FirJvmExternalDeclarationChecker a
FirMemberDeclarationChecker.

Set isExternal in status for FirRegularClass. Invoke member declaration
checkers for FirRegularClass.
2021-03-17 10:45:26 +01:00
Mark Punzalan
cef26a043e FIR checker: Merge FirConstDeclarationChecker with
FirConstPropertyChecker.
2021-03-17 10:45:26 +01:00
Mark Punzalan
beaeb74a26 FIR checker: Separate FirExternalDeclarationChecker as it is
JVM-specific.
2021-03-17 10:45:26 +01:00
Mark Punzalan
c3d2ce0c1f FIR checker/IDE: Add checker and quickfix for WRONG_MODIFIER_TARGET.
There are only simple checks for `external` and `const` for now. The
rest of the checks (see ModifiersChecker in FE1.0) will be added later.
2021-03-17 10:45:26 +01:00
Mikhail Glukhikh
ebfc431733 FIR body resolve context: fix accessor scope handling 2021-03-17 12:13:23 +03:00
Mikhail Glukhikh
ca15df7815 FIR: introduce separate containingClass in BodyResolveContext 2021-03-17 12:13:23 +03:00
Mikhail Glukhikh
f9618db9e2 FIR: rearrange functions in BodyResolveContext 2021-03-17 12:13:23 +03:00
Mikhail Glukhikh
d30299c29e FIR: introduce BodyResolveContext.forBlock, withWhenExpression 2021-03-17 12:13:22 +03:00
Mikhail Glukhikh
6ae948b655 FirAbstractBodyResolveTransformer: drop some unused context functions 2021-03-17 12:13:22 +03:00
Mikhail Glukhikh
cbf38b119c FIR: introduce BodyResolveContext.storeCallableReferenceContext 2021-03-17 12:13:22 +03:00
Mikhail Glukhikh
8b7b15f02b FIR: refactor delegating constructors resolve 2021-03-17 12:13:22 +03:00
Mikhail Glukhikh
8a9be56d07 FIR: introduce BodyResolveContext.forFunctionBody 2021-03-17 12:13:22 +03:00
Mikhail Glukhikh
b4cec3fb5d FIR: introduce BodyResolveContext.forEnumEntry 2021-03-17 12:13:22 +03:00
Mikhail Glukhikh
2db413d535 FIR: enhance (using mode inside) BodyResolveContext.withAnonymousFunction 2021-03-17 12:13:21 +03:00
Mikhail Glukhikh
798d848a91 FirReturnsImpliesAnalyzer: find receiver/variable of accessor properly 2021-03-17 12:13:21 +03:00
Mikhail Glukhikh
a345b81f2a Use BodyResolveContext.with* functions in FirContractResolveTransformer 2021-03-17 12:13:21 +03:00
Mikhail Glukhikh
4d519f646e FIR: extract BodyResolveContext.withAnonymousInitializer, withParameter 2021-03-17 12:13:21 +03:00
Mikhail Glukhikh
4235075f35 FIR: extract BodyResolveContext.withAnonymousFunction 2021-03-17 12:13:21 +03:00
Mikhail Glukhikh
d7b2ab6b99 FIR: extract BodyResolveContext.withConstructor in variations 2021-03-17 12:13:21 +03:00
Mikhail Glukhikh
bd2cdf2ec9 FIR: extract BodyResolveContext.withField 2021-03-17 12:13:21 +03:00
Mikhail Glukhikh
64353f34e9 FIR: extract BodyResolveContext.withProperty 2021-03-17 12:13:20 +03:00
Mikhail Glukhikh
06b3a0d57b FIR: extract BodyResolveContext.withSimpleFunction 2021-03-17 12:13:20 +03:00
Mikhail Glukhikh
db2b6e92e5 FIR: extract BodyResolveContext.withAnonymousObject 2021-03-17 12:13:20 +03:00
Mikhail Glukhikh
e5325e70fc FIR: extract BodyResolveContext.withRegularClass 2021-03-17 12:13:20 +03:00
Mikhail Glukhikh
4cff6d93be Get rid of containingClass storage in FirDeclarationsResolveTransformer 2021-03-17 12:13:20 +03:00
Mikhail Glukhikh
91607044d0 FIR: extract BodyResolveContext.withFile 2021-03-17 12:13:20 +03:00
Andrey
b7dc1e64b1 [KAPT] Disable JPMS when running annotation processing
If sources contain module-info.java javac tries to validate modules existence/visibility during AP phase and fails, because we don't specify modules-path/patch-module. All these checks will be done in kotlin compiler and in javac for java classes. And it is not necessary to do it in AP too.
So we go for easiest path possible - disable jpms for AP. 

#KT-32202 Fixed
2021-03-17 11:10:27 +03:00
Ilmir Usmanov
a90a5f6dd4 Check for backend when checking for suspend in fun interfaces 2021-03-16 22:37:44 +01:00
Steven Schäfer
bf2942b5cc JVM IR: Add Object.clone to JvmSymbols
The `clone` function is not available in the builtin classes created
from fir.
2021-03-16 21:30:18 +01:00
Steven Schäfer
99a4779c6b JVM IR: Don't produce line numbers in synthetic Enum members 2021-03-16 21:30:18 +01:00
Steven Schäfer
5be00cfa04 JVM IR: Don't use null checks in Enum.valueOf 2021-03-16 21:30:18 +01:00
Steven Schäfer
bea1a8c422 JVM IR: Use Object.clone in Enum.values 2021-03-16 21:30:18 +01:00
Ilmir Usmanov
e47715f52b Minor. Add tests with returning inline class from SAM adapter 2021-03-16 20:57:05 +01:00
Nikolay Krasko
aff25b3666 Remove jcenter usages 2021-03-16 22:24:10 +03:00
Nikolay Krasko
74dd8726c0 Update repositories in kotlin/buildSrc 2021-03-16 22:24:08 +03:00
Mikhail Glukhikh
0e8f8362da FIR checkers: use isNullableType() instead of isSubtypeOfAny() 2021-03-16 21:56:11 +03:00
Mikhail Glukhikh
599a0d9c2b Minor fixes in FirTypeParameterInQualifiedAccessChecker 2021-03-16 21:56:10 +03:00
Mikhail Glukhikh
0b9598d880 Minor fixes around FirKClassWithIncorrectTypeArgumentChecker 2021-03-16 21:56:10 +03:00
Jinseong Jeon
4c08d10cce FIR checker: report expression of nullable type parameter as LHS of class literals 2021-03-16 21:56:10 +03:00
Jinseong Jeon
26441ed64f FIR IDEA: avoid unnecessary type casting 2021-03-16 21:56:10 +03:00
Jinseong Jeon
7fff4108b6 FIR checker: report KClass with incorrect type argument 2021-03-16 21:56:10 +03:00
Jinseong Jeon
bc2228d434 FIR checker: don't report errors on type parameter as LHS of class literals
If a type paramter is not reified or nullable, different errors will
be reported by FirGetClassCallChecker.

When determining whether type parameter wrapped in qualified access is a
standalone expression or not, we examine whether the checker context has
other qualified accesses in stack. Class literals (::class) is desugared
to FirGetClassCall, and thus not stacked as qualified access. Since
class literals are a special type of callable reference (a subtype of
qualified access), we should keep track of FirGetClassCall in a similar
way.
2021-03-16 21:56:09 +03:00
Jinseong Jeon
e29b40b07f FIR checker: report TYPE_PARAMETER_AS_REIFIED 2021-03-16 21:56:09 +03:00
Jinseong Jeon
5ba5b63dee FIR checker: report nullable expression as LHS of class literals 2021-03-16 21:56:09 +03:00
Jinseong Jeon
33c5b49632 FIR checker: report non-typed LHS of callable references 2021-03-16 21:56:08 +03:00
scaventz
329be4f906 Add a test to for the situation where pathname of destination does not name a parent. 2021-03-16 18:44:12 +01:00
Georgy Bronnikov
bff6e9b972 IR: document lock priority. 2021-03-16 19:49:31 +03:00
Georgy Bronnikov
60f38369f1 JVM_IR: synchronize binary class reloading 2021-03-16 19:49:30 +03:00
Georgy Bronnikov
42279c3b5b IR: introduce IrLock
Use a single lock object for synchronization to avoid deadlocks.
2021-03-16 19:49:30 +03:00
Georgy Bronnikov
215556511e JVM_IR: synchronization in InlineCodegen 2021-03-16 19:49:30 +03:00
Georgy Bronnikov
be67dacef1 JVM_IR: synchronized getOrPut for SLRUMap 2021-03-16 19:49:30 +03:00
Georgy Bronnikov
78d62dcb1e JVM_IR: use ConcurrentHashMap in codegen where appropriate 2021-03-16 19:49:30 +03:00
Georgy Bronnikov
c36bc9f312 JVM_IR: use synchronized map in ClassFileFactory 2021-03-16 19:49:30 +03:00
Georgy Bronnikov
3a10ea4f88 JVM_IR: synchronize code generation for inline functions 2021-03-16 19:49:29 +03:00
Georgy Bronnikov
c7feaee8ae IR: make copying optional in performByIrFile
For codegen phases, input files are readonly data. There is no need to
copy them.
2021-03-16 19:49:29 +03:00
Georgy Bronnikov
1383c31caf JVM_IR: use threadLocal in GlobalInlineContext 2021-03-16 19:49:29 +03:00
Georgy Bronnikov
fe4d33dcb1 JVM_IR: make codegen a phase 2021-03-16 19:49:29 +03:00
sebastian.sellmair
b68fee9cbc CliCommonizer: Guard input- and dependency- libraries 2021-03-16 15:47:29 +00:00
sebastian.sellmair
d03a85525d [Commonizer] DependencyLibrariesOptionType: Make option optional (default: empty) 2021-03-16 15:47:28 +00:00
sebastian.sellmair
73222fbc4f [Commonizer] Add more verbose debugging information when failing to parse a task 2021-03-16 15:47:28 +00:00
sebastian.sellmair
f6e8afcbcc Move Gradle property 'kotlin.commonizer.jvmArgs' to 'kotlin.mpp.commonizerJvmArgs' 2021-03-16 15:47:27 +00:00
sebastian.sellmair
56661068bd CommonizerIT: Reuse DISABLED_NATIVE_TARGETS_REPORTER_WARNING_PREFIX instead of hardcoded string 2021-03-16 15:47:26 +00:00
sebastian.sellmair
5a10cb6a3e CommonizerIT: Add integration tests for user defined c-interop commonization 2021-03-16 15:47:25 +00:00
sebastian.sellmair
80e964c166 [Commonizer] NativeKlibCommonize: Remove optimization for only loading dependencies from native distribution
This is removed for now, because of test failures on Windows.
It seems like the dependencies in the klib produced by Windows are not
correct.

See: https://youtrack.jetbrains.com/issue/KT-45471
^KT-45471
2021-03-16 15:47:25 +00:00
sebastian.sellmair
b777c89bc8 [Commonizer] NativeKlibCommonize: Only load dependencies from native distribution 2021-03-16 15:47:24 +00:00
sebastian.sellmair
97a57a7d93 Forward dependencies from CInteropCommonizerTask to commonizer 2021-03-16 15:47:23 +00:00
sebastian.sellmair
49cf386258 Limit CInteropCommonizerTask to only one level of commonization
See ^KT-39324
2021-03-16 15:47:23 +00:00
sebastian.sellmair
261934d881 Implement CopyCommonizeCInteropForIdeTask to survive build folder cleaning 2021-03-16 15:47:22 +00:00
sebastian.sellmair
a53df56781 Implement CInteropIdentifier.Scope 2021-03-16 15:47:21 +00:00
sebastian.sellmair
6efd04edc0 Implement CInteropCommonizerTask to support commonization of user-defined cinterops
^KT-40975 Verification Pending
2021-03-16 15:47:20 +00:00
sebastian.sellmair
7cf8e9ec58 CInteropProcess: Promote settings to constructor
This enforces that the specified c-interop settings cannot be re-set on
a CInteropProcess.
2021-03-16 15:47:20 +00:00
sebastian.sellmair
be84b7b419 Rename 'getSourceSetHierarchy' to 'withAllDependsOnSourceSets' and lift the previous Deprecation 2021-03-16 15:47:19 +00:00
sebastian.sellmair
7da7dd92d6 Deprecate KotlinSourceSet.getSourceSetHierarchy in favour of 'resolveAllDependsOnSourceSets' and general purpose 'transitiveClosure' 2021-03-16 15:47:18 +00:00
sebastian.sellmair
4e07dcf2d8 Minor: Add dictionaries/sebastiansellmair.xml 2021-03-16 15:47:17 +00:00
Ilya Matveev
6643119f08 [K/N][New MM] Move ThreadStateGuard to the main Memory.h
Integrating the stdlib with the thread states machinery requires
accessing to some parts of the new MM. This patch provides this
access by moving these parts to the main Memory.h header.
2021-03-16 17:04:26 +03:00
Ilya Matveev
482305cfb2 [K/N][New MM] Move RunInNewThread to the main ThreadSupport.hpp
Some of unit-tests for the C++ part of the stdlib will require
thread state switching. In the new MM, we already have a helper
function that allows us to scopely initialize the memory subsystem
for a separate thread. This patch makes this helper available
for tests in the main runtime module by moving it to the main
ThreadSupport.hpp.
2021-03-16 17:04:25 +03:00
Ilya Matveev
fc43fbf578 [K/N][New MM] Move MemoryState conversions to separate header 2021-03-16 17:04:23 +03:00
1071 changed files with 64395 additions and 5646 deletions

View File

@@ -0,0 +1,8 @@
<component name="ProjectDictionaryState">
<dictionary name="sebastiansellmair">
<words>
<w>cinterops</w>
<w>interops</w>
</words>
</dictionary>
</component>

View File

@@ -11,10 +11,8 @@ buildscript {
repositories {
if (cacheRedirectorEnabled) {
maven("https://cache-redirector.jetbrains.com/jcenter.bintray.com")
maven("https://cache-redirector.jetbrains.com/maven.pkg.jetbrains.space/kotlin/p/kotlin/kotlin-dependencies")
} else {
jcenter()
maven("https://maven.pkg.jetbrains.space/kotlin/p/kotlin/kotlin-dependencies")
}
@@ -84,10 +82,9 @@ extra["versions.androidDxSources"] = "5.0.0_r2"
extra["customDepsOrg"] = "kotlin.build"
repositories {
jcenter()
mavenCentral()
maven("https://jetbrains.bintray.com/intellij-third-party-dependencies/")
maven("https://maven.pkg.jetbrains.space/kotlin/p/kotlin/kotlin-dependencies")
maven("https://kotlin.bintray.com/kotlinx")
gradlePluginPortal()
extra["bootstrapKotlinRepo"]?.let {
@@ -148,7 +145,7 @@ dependencies {
implementation(kotlin("stdlib", embeddedKotlinVersion))
implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:${project.bootstrapKotlinVersion}")
implementation("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.26")
implementation("com.gradle.publish:plugin-publish-plugin:0.12.0")
implementation("com.gradle.publish:plugin-publish-plugin:0.13.0")
implementation("net.rubygrapefruit:native-platform:${property("versions.native-platform")}")
implementation("net.rubygrapefruit:native-platform-windows-amd64:${property("versions.native-platform")}")

View File

@@ -46,6 +46,7 @@ val kotlinGradlePluginAndItsRequired = arrayOf(
":kotlin-gradle-subplugin-example",
":kotlin-stdlib-common",
":kotlin-stdlib",
":kotlin-stdlib-jdk7",
":kotlin-stdlib-jdk8",
":kotlin-stdlib-js",
":examples:annotation-processor-example",

View File

@@ -52,13 +52,14 @@ import org.jetbrains.org.objectweb.asm.Type;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.getMappingFileName;
public class ClassFileFactory implements OutputFileCollection {
private final GenerationState state;
private final ClassBuilderFactory builderFactory;
private final Map<String, OutAndSourceFileList> generators = new LinkedHashMap<>();
private final Map<String, OutAndSourceFileList> generators = Collections.synchronizedMap(new LinkedHashMap<>());
private boolean isDone = false;
@@ -346,7 +347,9 @@ public class ClassFileFactory implements OutputFileCollection {
@Override
public byte[] asBytes(ClassBuilderFactory factory) {
return factory.asBytes(classBuilder);
synchronized(this) {
return factory.asBytes(classBuilder);
}
}
@Override

View File

@@ -9,15 +9,16 @@ import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.utils.threadLocal
import java.util.*
class GlobalInlineContext(private val diagnostics: DiagnosticSink) {
// Ordered set of declarations and inline calls being generated right now.
// No call in it should point to a declaration that's before it in the stack.
private val inlineCallsAndDeclarations = LinkedList<Any? /* CallableDescriptor | PsiElement? */>()
private val inlineDeclarationSet = mutableSetOf<CallableDescriptor>()
private val inlineCallsAndDeclarations by threadLocal { LinkedList<Any? /* CallableDescriptor | PsiElement? */>() }
private val inlineDeclarationSet by threadLocal { mutableSetOf<CallableDescriptor>() }
private val typesUsedInInlineFunctions = LinkedList<MutableSet<String>>()
private val typesUsedInInlineFunctions by threadLocal { LinkedList<MutableSet<String>>() }
fun enterDeclaration(descriptor: CallableDescriptor) {
assert(descriptor.original !in inlineDeclarationSet) { "entered inlining cycle on $descriptor" }

View File

@@ -28,12 +28,14 @@ class InlineCache {
}
inline fun <K, V : Any> SLRUMap<K, V>.getOrPut(key: K, defaultValue: () -> V): V {
val value = get(key)
return if (value == null) {
val answer = defaultValue()
put(key, answer)
answer
} else {
value
synchronized(this) {
val value = get(key)
return if (value == null) {
val answer = defaultValue()
put(key, answer)
answer
} else {
value
}
}
}

View File

@@ -6,7 +6,6 @@
package org.jetbrains.kotlin.codegen.inline
import com.intellij.psi.PsiElement
import com.intellij.util.ArrayUtil
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.AsmUtil.isPrimitive
@@ -599,14 +598,6 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
return (directMember as? ImportedFromObjectCallableDescriptor<*>)?.callableFromObject ?: directMember
}
private fun cloneMethodNode(methodNode: MethodNode): MethodNode {
methodNode.instructions.resetLabels()
return MethodNode(
Opcodes.API_VERSION, methodNode.access, methodNode.name, methodNode.desc, methodNode.signature,
ArrayUtil.toStringArray(methodNode.exceptions)
).also(methodNode::accept)
}
private fun doCreateMethodNodeFromCompiled(
callableDescriptor: CallableMemberDescriptor,
state: GenerationState,

View File

@@ -625,3 +625,13 @@ fun MethodNode.preprocessSuspendMarkers(forInline: Boolean, keepFakeContinuation
}
}
}
fun cloneMethodNode(methodNode: MethodNode): MethodNode {
synchronized(methodNode) {
methodNode.instructions.resetLabels()
return MethodNode(
Opcodes.API_VERSION, methodNode.access, methodNode.name, methodNode.desc, methodNode.signature,
methodNode.exceptions.toTypedArray()
).also(methodNode::accept)
}
}

View File

@@ -57,6 +57,8 @@ class CapturedVarsOptimizationMethodTransformer : MethodTransformer() {
override fun onUseAsTainted() {
hazard = true
}
fun canRewrite() = !hazard && initCallInsn != null
}
private class Transformer(private val internalClassName: String, private val methodNode: MethodNode) {
@@ -72,7 +74,7 @@ class CapturedVarsOptimizationMethodTransformer : MethodTransformer() {
assignLocalVars(frames)
for (refValue in refValues) {
if (!refValue.hazard) {
if (refValue.canRewrite()) {
rewriteRefValue(refValue)
}
}

View File

@@ -22,6 +22,7 @@ import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import java.util.concurrent.ConcurrentHashMap
class BuilderFactoryForDuplicateClassNameDiagnostics(
@@ -29,7 +30,7 @@ class BuilderFactoryForDuplicateClassNameDiagnostics(
private val diagnostics: DiagnosticSink
) : ClassNameCollectionClassBuilderFactory(builderFactory) {
private val className = hashMapOf<String, JvmDeclarationOrigin> ()
private val className = ConcurrentHashMap<String, JvmDeclarationOrigin>()
override fun handleClashingNames(internalName: String, origin: JvmDeclarationOrigin) {
val another = className.getOrPut(internalName, { origin })

View File

@@ -49,7 +49,6 @@ dependencies {
testCompile(projectTests(":compiler:fir:raw-fir:light-tree2fir"))
testCompile(projectTests(":compiler:fir:fir2ir"))
testCompile(projectTests(":compiler:fir:analysis-tests:legacy-fir-tests"))
testCompile(projectTests(":compiler:visualizer"))
testCompile(projectTests(":generators:test-generator"))
testCompile(project(":compiler:ir.ir2cfg"))
testCompile(project(":compiler:ir.tree")) // used for deepCopyWithSymbols call that is removed by proguard from the compiler TODO: make it more straightforward

View File

@@ -42,6 +42,8 @@ found top-level declarations to <destination dir> (*.kotlin_builtins files)"""
assert(missing.isEmpty()) { "These source directories are missing: $missing" }
BuiltInsSerializer(dependOnOldBuiltIns = false).serialize(destDir, srcDirs, listOf()) { totalSize, totalFiles ->
println("Total bytes written: $totalSize to $totalFiles files")
if (System.getProperty("kotlin.builtins.serializer.log") == "true") {
println("Total bytes written: $totalSize to $totalFiles files")
}
}
}

View File

@@ -74,7 +74,7 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
@Argument(
value = "-jvm-target",
valueDescription = "<version>",
description = "Target version of the generated JVM bytecode (1.6 (DEPRECATED), 1.8, 9, 10, 11, 12, 13, 14 or 15), default is 1.8"
description = "Target version of the generated JVM bytecode (1.6 (DEPRECATED), 1.8, 9, 10, 11, 12, 13, 14, 15 or 16), default is 1.8"
)
var jvmTarget: String? by NullableStringFreezableVar(JvmTarget.DEFAULT.description)
@@ -84,8 +84,12 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
// Advanced options
@DeprecatedOption(removeAfter = "1.5", level = DeprecationLevel.WARNING)
@GradleOption(DefaultValues.BooleanFalseDefault::class)
@Argument(value = "-Xuse-ir", description = "Use the IR backend")
@Argument(
value = "-Xuse-ir",
description = "Use the IR backend. This option has no effect unless the language version less than 1.5 is used"
)
var useIR: Boolean by FreezableVar(false)
@GradleOption(DefaultValues.BooleanFalseDefault::class)
@@ -489,6 +493,7 @@ default: `indy-with-constants` for JVM target 9 or greater, `inline` otherwise""
result[JvmAnalysisFlags.enableJvmPreview] = enableJvmPreview
result[AnalysisFlags.allowUnstableDependencies] = allowUnstableDependencies || useFir
result[JvmAnalysisFlags.disableUltraLightClasses] = disableUltraLightClasses
result[JvmAnalysisFlags.useIR] = useIR
return result
}

View File

@@ -13,6 +13,7 @@ import com.intellij.psi.search.PsiSearchScopeUtil
import com.intellij.util.SmartList
import org.jetbrains.kotlin.asJava.KotlinAsJavaSupport
import org.jetbrains.kotlin.asJava.classes.*
import org.jetbrains.kotlin.config.JvmAnalysisFlags
import org.jetbrains.kotlin.descriptors.PackageViewDescriptor
import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName
import org.jetbrains.kotlin.load.java.components.FilesByFacadeFqNameIndexer
@@ -109,7 +110,7 @@ class CliKotlinAsJavaSupport(
}
override fun getLightClass(classOrObject: KtClassOrObject): KtLightClass? =
KtLightClassForSourceDeclaration.create(classOrObject)
KtLightClassForSourceDeclaration.create(classOrObject, traceHolder.languageVersionSettings.getFlag(JvmAnalysisFlags.jvmDefaultMode))
override fun getLightClassForScript(script: KtScript): KtLightClassForScript? =
KtLightClassForScript.create(script)

View File

@@ -33,6 +33,9 @@ object JvmAnalysisFlags {
@JvmStatic
val enableJvmPreview by AnalysisFlag.Delegates.Boolean
@JvmStatic
val useIR by AnalysisFlag.Delegates.Boolean
private object Delegates {
object JavaTypeEnhancementStateWarnByDefault {
operator fun provideDelegate(instance: Any?, property: KProperty<*>): AnalysisFlag.Delegate<JavaTypeEnhancementState> =

View File

@@ -32,6 +32,7 @@ enum class JvmTarget(
JVM_13("13", Opcodes.V12 + 1),
JVM_14("14", Opcodes.V12 + 2),
JVM_15("15", Opcodes.V12 + 3),
JVM_16("16", Opcodes.V12 + 4),
;
companion object {

View File

@@ -750,6 +750,11 @@ public class LazyBodyIsNotTouchedTilContractsPhaseTestGenerated extends Abstract
runTest("compiler/fir/analysis-tests/testData/resolve/callResolution/syntheticPropertiesWrongImplicitReceiver.kt");
}
@TestMetadata("twoLocalLambdasWithSameName.kt")
public void testTwoLocalLambdasWithSameName() throws Exception {
runTest("compiler/fir/analysis-tests/testData/resolve/callResolution/twoLocalLambdasWithSameName.kt");
}
@TestMetadata("typeAliasWithNotNullBound.kt")
public void testTypeAliasWithNotNullBound() throws Exception {
runTest("compiler/fir/analysis-tests/testData/resolve/callResolution/typeAliasWithNotNullBound.kt");

View File

@@ -0,0 +1,19 @@
FILE: twoLocalLambdasWithSameName.kt
public abstract interface R : R|kotlin/Any| {
}
public final fun takeInt(x: R|kotlin/Int|): R|kotlin/Unit| {
}
public final fun test(fn: R|R.() -> kotlin/String|): R|kotlin/Unit| {
lval renderer: R|<anonymous>| = object : R|R| {
private constructor(): R|<anonymous>| {
super<R|kotlin/Any|>()
}
public final fun render(fn: R|R.() -> kotlin/Int|): R|kotlin/Unit| {
lval result: R|kotlin/Int| = R|<local>/fn|.R|SubstitutionOverride<kotlin/Function1.invoke: R|kotlin/Int|>|(this@R|/<anonymous>|)
R|/takeInt|(R|<local>/result|)
}
}
}

View File

@@ -0,0 +1,13 @@
// ISSUE: KT-45316
interface R
fun takeInt(x: Int) {}
fun test(fn: R.() -> String) { // (1)
val renderer = object : R {
fun render(fn: R.() -> Int) { // (2)
val result = fn()
takeInt(result)
}
}
}

View File

@@ -9,7 +9,7 @@ FILE: annotationArgumentKClassLiteralTypeError.kt
}
public final val <reified T> R|T|.test: R|kotlin/Any|
public get(): R|<anonymous><T>| {
public inline get(): R|<anonymous><T>| {
^ @R|Ann|(<implicitArrayOf>(<getClass>(R|T|), <getClass>(Q|kotlin/Array|))) object : R|kotlin/Any| {
private constructor(): R|<anonymous><T>| {
super<R|kotlin/Any|>()

View File

@@ -11,8 +11,8 @@ fun Any?.isNotNull(): Boolean {
@OptIn(ExperimentalContracts::class)
val Any?.isNotNull: Boolean
get() {
<!WRONG_IMPLIES_CONDITION!>contract {
contract {
returns(true) implies (this@isNotNull != null)
}<!>
}
return this@isNotNull != null
}

View File

@@ -6,16 +6,16 @@ interface A {
var Any?.isNotNull: Boolean
get() {
<!WRONG_IMPLIES_CONDITION!>contract {
contract {
returns(true) implies (this@isNotNull != null)
}<!>
}
return this != null
}
set(value) {
<!WRONG_IMPLIES_CONDITION!>contract {
contract {
returns() implies (this@isNotNull != null)
require(this != null)
}<!>
}
}
fun test_1(a: A?) {

View File

@@ -869,6 +869,12 @@ public class FirDiagnosticTestGenerated extends AbstractFirDiagnosticTest {
runTest("compiler/fir/analysis-tests/testData/resolve/callResolution/syntheticPropertiesWrongImplicitReceiver.kt");
}
@Test
@TestMetadata("twoLocalLambdasWithSameName.kt")
public void testTwoLocalLambdasWithSameName() throws Exception {
runTest("compiler/fir/analysis-tests/testData/resolve/callResolution/twoLocalLambdasWithSameName.kt");
}
@Test
@TestMetadata("typeAliasWithNotNullBound.kt")
public void testTypeAliasWithNotNullBound() throws Exception {

View File

@@ -876,6 +876,12 @@ public class FirDiagnosticsWithLightTreeTestGenerated extends AbstractFirDiagnos
runTest("compiler/fir/analysis-tests/testData/resolve/callResolution/syntheticPropertiesWrongImplicitReceiver.kt");
}
@Test
@TestMetadata("twoLocalLambdasWithSameName.kt")
public void testTwoLocalLambdasWithSameName() throws Exception {
runTest("compiler/fir/analysis-tests/testData/resolve/callResolution/twoLocalLambdasWithSameName.kt");
}
@Test
@TestMetadata("typeAliasWithNotNullBound.kt")
public void testTypeAliasWithNotNullBound() throws Exception {

View File

@@ -2091,6 +2091,12 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirDiagnosti
runTest("compiler/testData/diagnostics/tests/backingField/kt782packageLevel.kt");
}
@Test
@TestMetadata("LocalDeclarations.kt")
public void testLocalDeclarations() throws Exception {
runTest("compiler/testData/diagnostics/tests/backingField/LocalDeclarations.kt");
}
@Test
@TestMetadata("SetterWithExplicitType.kt")
public void testSetterWithExplicitType() throws Exception {
@@ -10078,28 +10084,6 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirDiagnosti
runTest("compiler/testData/diagnostics/tests/functionLiterals/return/unresolvedReferenceInReturnBlock.kt");
}
}
@Nested
@TestMetadata("compiler/testData/diagnostics/tests/functionLiterals/suspend")
@TestDataPath("$PROJECT_ROOT")
public class Suspend {
@Test
public void testAllFilesPresentInSuspend() throws Exception {
KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/diagnostics/tests/functionLiterals/suspend"), Pattern.compile("^(.+)\\.kt$"), Pattern.compile("^(.+)\\.fir\\.kts?$"), true);
}
@Test
@TestMetadata("disabled.kt")
public void testDisabled() throws Exception {
runTest("compiler/testData/diagnostics/tests/functionLiterals/suspend/disabled.kt");
}
@Test
@TestMetadata("enabled.kt")
public void testEnabled() throws Exception {
runTest("compiler/testData/diagnostics/tests/functionLiterals/suspend/enabled.kt");
}
}
}
@Nested
@@ -12574,6 +12558,12 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirDiagnosti
runTest("compiler/testData/diagnostics/tests/inference/capturedTypes/starProjectionRegression.kt");
}
@Test
@TestMetadata("substituteCapturedTypesWithTypeVariables.kt")
public void testSubstituteCapturedTypesWithTypeVariables() throws Exception {
runTest("compiler/testData/diagnostics/tests/inference/capturedTypes/substituteCapturedTypesWithTypeVariables.kt");
}
@Test
@TestMetadata("topLevelCapturingInsideReturnType.kt")
public void testTopLevelCapturingInsideReturnType() throws Exception {
@@ -29597,12 +29587,6 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirDiagnosti
runTest("compiler/testData/diagnostics/tests/unsignedTypes/unsignedLiteralsInsideConstVals.kt");
}
@Test
@TestMetadata("unsignedLiteralsOn1_2.kt")
public void testUnsignedLiteralsOn1_2() throws Exception {
runTest("compiler/testData/diagnostics/tests/unsignedTypes/unsignedLiteralsOn1_2.kt");
}
@Test
@TestMetadata("unsignedLiteralsOverflowSignedBorder.kt")
public void testUnsignedLiteralsOverflowSignedBorder() throws Exception {
@@ -33619,12 +33603,6 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirDiagnosti
runTest("compiler/testData/diagnostics/testsWithStdLib/experimental/experimentalOnWholeModule.kt");
}
@Test
@TestMetadata("experimentalUnsignedLiterals.kt")
public void testExperimentalUnsignedLiterals() throws Exception {
runTest("compiler/testData/diagnostics/testsWithStdLib/experimental/experimentalUnsignedLiterals.kt");
}
@Test
@TestMetadata("fullFqNameUsage.kt")
public void testFullFqNameUsage() throws Exception {

View File

@@ -160,6 +160,10 @@ object DIAGNOSTICS_LIST : DiagnosticList() {
parameter<KtModifierKeywordToken>("modifier2")
}
val REDUNDANT_OPEN_IN_INTERFACE by warning<FirSourceElement, KtModifierListOwner>(PositioningStrategy.OPEN_MODIFIER)
val WRONG_MODIFIER_TARGET by error<FirSourceElement, PsiElement> {
parameter<KtModifierKeywordToken>("modifier")
parameter<String>("target")
}
}
val INLINE_CLASSES by object : DiagnosticGroup("Inline classes") {
@@ -231,7 +235,6 @@ object DIAGNOSTICS_LIST : DiagnosticList() {
parameter<Int>("expectedCount")
parameter<FirClassLikeSymbol<*>>("classifier")
}
val NO_TYPE_FOR_TYPE_PARAMETER by error<FirSourceElement, PsiElement>()
val TYPE_PARAMETERS_IN_OBJECT by error<FirSourceElement, PsiElement>()
val ILLEGAL_PROJECTION_USAGE by error<FirSourceElement, PsiElement>()
val TYPE_PARAMETERS_IN_ENUM by error<FirSourceElement, PsiElement>()
@@ -245,11 +248,24 @@ object DIAGNOSTICS_LIST : DiagnosticList() {
val TYPE_PARAMETER_IN_CATCH_CLAUSE by error<FirSourceElement, PsiElement>()
val GENERIC_THROWABLE_SUBCLASS by error<FirSourceElement, KtTypeParameterList>()
val INNER_CLASS_OF_GENERIC_THROWABLE_SUBCLASS by error<FirSourceElement, KtClassOrObject>(PositioningStrategy.DECLARATION_NAME)
val KCLASS_WITH_NULLABLE_TYPE_PARAMETER_IN_SIGNATURE by error<FirSourceElement, KtNamedDeclaration>(PositioningStrategy.DECLARATION_NAME) {
parameter<FirTypeParameterSymbol>("typeParameter")
}
val TYPE_PARAMETER_AS_REIFIED by error<FirSourceElement, PsiElement> {
parameter<FirTypeParameterSymbol>("typeParameter")
}
}
val REFLECTION by object : DiagnosticGroup("Reflection") {
val CALLABLE_REFERENCE_LHS_NOT_A_CLASS by error<FirSourceElement, KtExpression>()
val CLASS_LITERAL_LHS_NOT_A_CLASS by error<FirSourceElement, KtExpression>()
val NULLABLE_TYPE_IN_CLASS_LITERAL_LHS by error<FirSourceElement, KtExpression>()
val EXPRESSION_OF_NULLABLE_TYPE_IN_CLASS_LITERAL_LHS by error<FirSourceElement, PsiElement> {
parameter<ConeKotlinType>("lhsType")
}
}
val OVERRIDES by object : DiagnosticGroup("overrides") {
@@ -341,6 +357,7 @@ object DIAGNOSTICS_LIST : DiagnosticList() {
val FORBIDDEN_VARARG_PARAMETER_TYPE by error<FirSourceElement, KtParameter>(PositioningStrategy.PARAMETER_VARARG_MODIFIER) {
parameter<ConeKotlinType>("varargParameterType")
}
val VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION by error<FirSourceElement, KtParameter>()
}
val PROPERTIES_AND_ACCESSORS by object : DiagnosticGroup("Properties & accessors") {
@@ -410,6 +427,12 @@ object DIAGNOSTICS_LIST : DiagnosticList() {
val VAL_REASSIGNMENT by error<FirSourceElement, KtExpression> {
parameter<FirPropertySymbol>("variable")
}
val VAL_REASSIGNMENT_VIA_BACKING_FIELD by warning<FirSourceElement, KtExpression> {
parameter<FirPropertySymbol>("variable")
}
val VAL_REASSIGNMENT_VIA_BACKING_FIELD_ERROR by error<FirSourceElement, KtExpression> {
parameter<FirPropertySymbol>("variable")
}
val WRONG_INVOCATION_KIND by warning<FirSourceElement, PsiElement> {
parameter<AbstractFirBasedSymbol<*>>("declaration")
parameter<EventOccurrencesRange>("requiredRange")
@@ -448,6 +471,15 @@ object DIAGNOSTICS_LIST : DiagnosticList() {
val INVALID_IF_AS_EXPRESSION by error<FirSourceElement, KtIfExpression>(PositioningStrategy.IF_EXPRESSION)
}
val CONTEXT_TRACKING by object : DiagnosticGroup("Context tracking") {
val TYPE_PARAMETER_IS_NOT_AN_EXPRESSION by error<FirSourceElement, KtSimpleNameExpression> {
parameter<FirTypeParameterSymbol>("typeParameter")
}
val TYPE_PARAMETER_ON_LHS_OF_DOT by error<FirSourceElement, KtSimpleNameExpression> {
parameter<FirTypeParameterSymbol>("typeParameter")
}
}
val FUNCTION_CONTRACTS by object : DiagnosticGroup("Function contracts") {
val ERROR_IN_CONTRACT_DESCRIPTION by error<FirSourceElement, KtElement>(PositioningStrategy.SELECTOR_BY_QUALIFIED) {
parameter<String>("reason")

View File

@@ -145,6 +145,7 @@ object FirErrors {
val DEPRECATED_MODIFIER_PAIR by error2<FirSourceElement, PsiElement, KtModifierKeywordToken, KtModifierKeywordToken>()
val INCOMPATIBLE_MODIFIERS by error2<FirSourceElement, PsiElement, KtModifierKeywordToken, KtModifierKeywordToken>()
val REDUNDANT_OPEN_IN_INTERFACE by warning0<FirSourceElement, KtModifierListOwner>(SourceElementPositioningStrategies.OPEN_MODIFIER)
val WRONG_MODIFIER_TARGET by error2<FirSourceElement, PsiElement, KtModifierKeywordToken, String>()
// Inline classes
val INLINE_CLASS_NOT_TOP_LEVEL by error0<FirSourceElement, KtDeclaration>(SourceElementPositioningStrategies.INLINE_OR_VALUE_MODIFIER)
@@ -182,7 +183,6 @@ object FirErrors {
val UPPER_BOUND_VIOLATED by error2<FirSourceElement, PsiElement, FirTypeParameterSymbol, ConeKotlinType>()
val TYPE_ARGUMENTS_NOT_ALLOWED by error0<FirSourceElement, PsiElement>()
val WRONG_NUMBER_OF_TYPE_ARGUMENTS by error2<FirSourceElement, PsiElement, Int, FirClassLikeSymbol<*>>()
val NO_TYPE_FOR_TYPE_PARAMETER by error0<FirSourceElement, PsiElement>()
val TYPE_PARAMETERS_IN_OBJECT by error0<FirSourceElement, PsiElement>()
val ILLEGAL_PROJECTION_USAGE by error0<FirSourceElement, PsiElement>()
val TYPE_PARAMETERS_IN_ENUM by error0<FirSourceElement, PsiElement>()
@@ -193,10 +193,14 @@ object FirErrors {
val TYPE_PARAMETER_IN_CATCH_CLAUSE by error0<FirSourceElement, PsiElement>()
val GENERIC_THROWABLE_SUBCLASS by error0<FirSourceElement, KtTypeParameterList>()
val INNER_CLASS_OF_GENERIC_THROWABLE_SUBCLASS by error0<FirSourceElement, KtClassOrObject>(SourceElementPositioningStrategies.DECLARATION_NAME)
val KCLASS_WITH_NULLABLE_TYPE_PARAMETER_IN_SIGNATURE by error1<FirSourceElement, KtNamedDeclaration, FirTypeParameterSymbol>(SourceElementPositioningStrategies.DECLARATION_NAME)
val TYPE_PARAMETER_AS_REIFIED by error1<FirSourceElement, PsiElement, FirTypeParameterSymbol>()
// Reflection
val CALLABLE_REFERENCE_LHS_NOT_A_CLASS by error0<FirSourceElement, KtExpression>()
val CLASS_LITERAL_LHS_NOT_A_CLASS by error0<FirSourceElement, KtExpression>()
val NULLABLE_TYPE_IN_CLASS_LITERAL_LHS by error0<FirSourceElement, KtExpression>()
val EXPRESSION_OF_NULLABLE_TYPE_IN_CLASS_LITERAL_LHS by error1<FirSourceElement, PsiElement, ConeKotlinType>()
// overrides
val NOTHING_TO_OVERRIDE by error1<FirSourceElement, KtModifierListOwner, FirMemberDeclaration>(SourceElementPositioningStrategies.OVERRIDE_MODIFIER)
@@ -231,6 +235,7 @@ object FirErrors {
val USELESS_VARARG_ON_PARAMETER by warning0<FirSourceElement, KtParameter>()
val MULTIPLE_VARARG_PARAMETERS by error0<FirSourceElement, KtParameter>(SourceElementPositioningStrategies.PARAMETER_VARARG_MODIFIER)
val FORBIDDEN_VARARG_PARAMETER_TYPE by error1<FirSourceElement, KtParameter, ConeKotlinType>(SourceElementPositioningStrategies.PARAMETER_VARARG_MODIFIER)
val VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION by error0<FirSourceElement, KtParameter>()
// Properties & accessors
val ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS by error2<FirSourceElement, KtModifierListOwner, FirMemberDeclaration, FirMemberDeclaration>(SourceElementPositioningStrategies.MODALITY_MODIFIER)
@@ -270,6 +275,8 @@ object FirErrors {
// Control flow diagnostics
val UNINITIALIZED_VARIABLE by error1<FirSourceElement, KtSimpleNameExpression, FirPropertySymbol>()
val VAL_REASSIGNMENT by error1<FirSourceElement, KtExpression, FirPropertySymbol>()
val VAL_REASSIGNMENT_VIA_BACKING_FIELD by warning1<FirSourceElement, KtExpression, FirPropertySymbol>()
val VAL_REASSIGNMENT_VIA_BACKING_FIELD_ERROR by error1<FirSourceElement, KtExpression, FirPropertySymbol>()
val WRONG_INVOCATION_KIND by warning3<FirSourceElement, PsiElement, AbstractFirBasedSymbol<*>, EventOccurrencesRange, EventOccurrencesRange>()
val LEAKED_IN_PLACE_LAMBDA by error1<FirSourceElement, PsiElement, AbstractFirBasedSymbol<*>>()
val WRONG_IMPLIES_CONDITION by warning0<FirSourceElement, PsiElement>()
@@ -284,6 +291,10 @@ object FirErrors {
val NO_ELSE_IN_WHEN by error1<FirSourceElement, KtWhenExpression, List<WhenMissingCase>>(SourceElementPositioningStrategies.WHEN_EXPRESSION)
val INVALID_IF_AS_EXPRESSION by error0<FirSourceElement, KtIfExpression>(SourceElementPositioningStrategies.IF_EXPRESSION)
// Context tracking
val TYPE_PARAMETER_IS_NOT_AN_EXPRESSION by error1<FirSourceElement, KtSimpleNameExpression, FirTypeParameterSymbol>()
val TYPE_PARAMETER_ON_LHS_OF_DOT by error1<FirSourceElement, KtSimpleNameExpression, FirTypeParameterSymbol>()
// Function contracts
val ERROR_IN_CONTRACT_DESCRIPTION by error1<FirSourceElement, KtElement, String>(SourceElementPositioningStrategies.SELECTOR_BY_QUALIFIED)

View File

@@ -16,6 +16,7 @@ import org.jetbrains.kotlin.fir.contracts.coneEffects
import org.jetbrains.kotlin.fir.contracts.description.*
import org.jetbrains.kotlin.fir.declarations.FirContractDescriptionOwner
import org.jetbrains.kotlin.fir.declarations.FirFunction
import org.jetbrains.kotlin.fir.declarations.FirProperty
import org.jetbrains.kotlin.fir.expressions.*
import org.jetbrains.kotlin.fir.resolve.dfa.*
import org.jetbrains.kotlin.fir.resolve.dfa.cfg.BlockExitNode
@@ -23,6 +24,7 @@ import org.jetbrains.kotlin.fir.resolve.dfa.cfg.CFGNode
import org.jetbrains.kotlin.fir.resolve.dfa.cfg.ControlFlowGraph
import org.jetbrains.kotlin.fir.resolve.dfa.cfg.JumpNode
import org.jetbrains.kotlin.fir.symbols.AbstractFirBasedSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirPropertyAccessorSymbol
import org.jetbrains.kotlin.fir.typeContext
import org.jetbrains.kotlin.fir.types.ConeKotlinType
import org.jetbrains.kotlin.fir.types.coneType
@@ -61,7 +63,7 @@ object FirReturnsImpliesAnalyzer : FirControlFlowChecker() {
effects.forEach { effect ->
val wrongCondition = graph.exitNode.previousCfgNodes.any {
isWrongConditionOnNode(it, effect as ConeConditionalEffectDeclaration, function, logicSystem, dataFlowInfo)
isWrongConditionOnNode(it, effect as ConeConditionalEffectDeclaration, function, logicSystem, dataFlowInfo, context)
}
if (wrongCondition) {
@@ -77,7 +79,8 @@ object FirReturnsImpliesAnalyzer : FirControlFlowChecker() {
effectDeclaration: ConeConditionalEffectDeclaration,
function: FirFunction<*>,
logicSystem: LogicSystem<PersistentFlow>,
dataFlowInfo: DataFlowInfo
dataFlowInfo: DataFlowInfo,
context: CheckerContext
): Boolean {
val effect = effectDeclaration.effect as ConeReturnsEffectDeclaration
val builtinTypes = function.session.builtinTypes
@@ -92,7 +95,7 @@ object FirReturnsImpliesAnalyzer : FirControlFlowChecker() {
if (isReturn && resultExpression is FirWhenExpression) {
return node.collectBranchExits().any {
isWrongConditionOnNode(it, effectDeclaration, function, logicSystem, dataFlowInfo)
isWrongConditionOnNode(it, effectDeclaration, function, logicSystem, dataFlowInfo, context)
}
}
@@ -110,15 +113,16 @@ object FirReturnsImpliesAnalyzer : FirControlFlowChecker() {
}
}
val conditionStatements =
effectDeclaration.condition.buildTypeStatements(function, logicSystem, dataFlowInfo.variableStorage, flow) ?: return false
val conditionStatements = effectDeclaration.condition.buildTypeStatements(
function, logicSystem, dataFlowInfo.variableStorage, flow, context
) ?: return false
for ((realVar, requiredTypeStatement) in conditionStatements) {
val fixedRealVar = typeStatements.keys.find { it.identifier == realVar.identifier } ?: realVar
val resultTypeStatement = typeStatements[fixedRealVar]
val resultType = mutableListOf<ConeKotlinType>().apply {
addIfNotNull(function.getParameterType(fixedRealVar.identifier.symbol))
addIfNotNull(function.getParameterType(fixedRealVar.identifier.symbol, context))
if (resultTypeStatement != null) addAll(resultTypeStatement.exactType)
}.let { typeContext.intersectTypesOrNull(it) }
@@ -154,11 +158,12 @@ object FirReturnsImpliesAnalyzer : FirControlFlowChecker() {
function: FirFunction<*>,
logicSystem: LogicSystem<*>,
variableStorage: VariableStorage,
flow: Flow
flow: Flow,
context: CheckerContext
): MutableTypeStatements? = when (this) {
is ConeBinaryLogicExpression -> {
val left = left.buildTypeStatements(function, logicSystem, variableStorage, flow)
val right = right.buildTypeStatements(function, logicSystem, variableStorage, flow)
val left = left.buildTypeStatements(function, logicSystem, variableStorage, flow, context)
val right = right.buildTypeStatements(function, logicSystem, variableStorage, flow, context)
if (left != null && right != null) {
if (kind == LogicOperationKind.AND) {
left.apply { mergeTypeStatements(right) }
@@ -166,16 +171,16 @@ object FirReturnsImpliesAnalyzer : FirControlFlowChecker() {
} else (left ?: right)
}
is ConeIsInstancePredicate -> {
val fir = function.getParameterSymbol(arg.parameterIndex).fir
val fir = function.getParameterSymbol(arg.parameterIndex, context).fir
val realVar = variableStorage.getOrCreateRealVariable(flow, fir.symbol, fir)
realVar?.to(simpleTypeStatement(realVar, !isNegated, type))?.let { mutableMapOf(it) }
}
is ConeIsNullPredicate -> {
val fir = function.getParameterSymbol(arg.parameterIndex).fir
val fir = function.getParameterSymbol(arg.parameterIndex, context).fir
val realVar = variableStorage.getOrCreateRealVariable(flow, fir.symbol, fir)
realVar?.to(simpleTypeStatement(realVar, isNegated, function.session.builtinTypes.anyType.type))?.let { mutableMapOf(it) }
}
is ConeLogicalNot -> arg.buildTypeStatements(function, logicSystem, variableStorage, flow)
is ConeLogicalNot -> arg.buildTypeStatements(function, logicSystem, variableStorage, flow, context)
?.mapValuesTo(mutableMapOf()) { (_, value) -> value.invert() }
else -> null
@@ -212,11 +217,31 @@ object FirReturnsImpliesAnalyzer : FirControlFlowChecker() {
return nodes
}
private fun FirFunction<*>.getParameterType(symbol: AbstractFirBasedSymbol<*>): ConeKotlinType? {
return (if (this.symbol == symbol) receiverTypeRef else valueParameters.find { it.symbol == symbol }?.returnTypeRef)?.coneType
private val CheckerContext.containingProperty: FirProperty?
get() = (containingDeclarations.asReversed().firstOrNull { it is FirProperty } as? FirProperty)
private fun FirFunction<*>.getParameterType(symbol: AbstractFirBasedSymbol<*>, context: CheckerContext): ConeKotlinType? {
val typeRef = if (this.symbol == symbol) {
if (symbol is FirPropertyAccessorSymbol) {
context.containingProperty?.receiverTypeRef
} else {
receiverTypeRef
}
} else {
valueParameters.find { it.symbol == symbol }?.returnTypeRef
}
return typeRef?.coneType
}
private fun FirFunction<*>.getParameterSymbol(index: Int): AbstractFirBasedSymbol<*> {
return if (index == -1) this.symbol else this.valueParameters[index].symbol
private fun FirFunction<*>.getParameterSymbol(index: Int, context: CheckerContext): AbstractFirBasedSymbol<*> {
return if (index == -1) {
if (symbol !is FirPropertyAccessorSymbol) {
symbol
} else {
context.containingProperty?.symbol ?: symbol
}
} else {
this.valueParameters[index].symbol
}
}
}

View File

@@ -127,7 +127,7 @@ fun ConeKotlinType.toRegularClass(session: FirSession): FirRegularClass? {
return safeAs<ConeClassLikeType>()?.fullyExpandedType(session)?.toRegularClass(session)
}
fun ConeKotlinType.isInline(session: FirSession) : Boolean = toRegularClass(session)?.isInline == true
fun ConeKotlinType.isInline(session: FirSession): Boolean = toRegularClass(session)?.isInline == true
/**
* Returns the FirRegularClass associated with this
@@ -143,7 +143,7 @@ fun FirTypeRef.toRegularClass(session: FirSession): FirRegularClass? {
inline fun <reified T : Any> FirQualifiedAccessExpression.getDeclaration(): T? {
return this.calleeReference.safeAs<FirResolvedNamedReference>()
?.resolvedSymbol
?.fir.safeAs<T>()
?.fir.safeAs()
}
/**
@@ -153,17 +153,6 @@ inline fun <reified T : Any> FirQualifiedAccessExpression.getDeclaration(): T? {
fun FirSymbolOwner<*>.getContainingClass(context: CheckerContext): FirClassLikeDeclaration<*>? =
this.safeAs<FirCallableMemberDeclaration<*>>()?.containingClass()?.toSymbol(context.session)?.fir
/**
* Returns the FirClassLikeDeclaration the type alias is pointing
* to provided `this` is a FirTypeAlias. Returns this otherwise.
*/
fun FirClassLikeDeclaration<*>.followAlias(session: FirSession): FirClassLikeDeclaration<*> {
return this.safeAs<FirTypeAlias>()
?.expandedTypeRef
?.firClassLike(session)
?: return this
}
/**
* Returns the FirClassLikeDeclaration that the
* sequence of FirTypeAlias'es points to starting

View File

@@ -11,6 +11,7 @@ import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.persistentSetOf
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.declarations.FirDeclaration
import org.jetbrains.kotlin.fir.expressions.FirGetClassCall
import org.jetbrains.kotlin.fir.expressions.FirQualifiedAccess
import org.jetbrains.kotlin.fir.resolve.ImplicitReceiverStack
import org.jetbrains.kotlin.fir.resolve.PersistentImplicitReceiverStack
@@ -23,6 +24,7 @@ abstract class CheckerContext {
abstract val implicitReceiverStack: ImplicitReceiverStack
abstract val containingDeclarations: List<FirDeclaration>
abstract val qualifiedAccesses: List<FirQualifiedAccess>
abstract val getClassCalls: List<FirGetClassCall>
abstract val sessionHolder: SessionHolder
abstract val returnTypeCalculator: ReturnTypeCalculator
abstract val suppressedDiagnostics: Set<String>
@@ -57,6 +59,7 @@ class PersistentCheckerContext private constructor(
override val implicitReceiverStack: PersistentImplicitReceiverStack,
override val containingDeclarations: PersistentList<FirDeclaration>,
override val qualifiedAccesses: PersistentList<FirQualifiedAccess>,
override val getClassCalls: PersistentList<FirGetClassCall>,
override val sessionHolder: SessionHolder,
override val returnTypeCalculator: ReturnTypeCalculator,
override val suppressedDiagnostics: PersistentSet<String>,
@@ -68,6 +71,7 @@ class PersistentCheckerContext private constructor(
PersistentImplicitReceiverStack(),
persistentListOf(),
persistentListOf(),
persistentListOf(),
sessionHolder,
returnTypeCalculator,
persistentSetOf(),
@@ -81,6 +85,7 @@ class PersistentCheckerContext private constructor(
implicitReceiverStack.add(name, value),
containingDeclarations,
qualifiedAccesses,
getClassCalls,
sessionHolder,
returnTypeCalculator,
suppressedDiagnostics,
@@ -95,6 +100,7 @@ class PersistentCheckerContext private constructor(
implicitReceiverStack,
containingDeclarations.add(declaration),
qualifiedAccesses,
getClassCalls,
sessionHolder,
returnTypeCalculator,
suppressedDiagnostics,
@@ -109,6 +115,22 @@ class PersistentCheckerContext private constructor(
implicitReceiverStack,
containingDeclarations,
qualifiedAccesses.add(qualifiedAccess),
getClassCalls,
sessionHolder,
returnTypeCalculator,
suppressedDiagnostics,
allInfosSuppressed,
allWarningsSuppressed,
allErrorsSuppressed
)
}
fun addGetClassCall(getClassCall: FirGetClassCall): PersistentCheckerContext {
return PersistentCheckerContext(
implicitReceiverStack,
containingDeclarations,
qualifiedAccesses,
getClassCalls.add(getClassCall),
sessionHolder,
returnTypeCalculator,
suppressedDiagnostics,
@@ -129,6 +151,7 @@ class PersistentCheckerContext private constructor(
implicitReceiverStack,
containingDeclarations,
qualifiedAccesses,
getClassCalls,
sessionHolder,
returnTypeCalculator,
suppressedDiagnostics.addAll(diagnosticNames),

View File

@@ -13,10 +13,19 @@ import org.jetbrains.kotlin.fir.analysis.diagnostics.reportOn
import org.jetbrains.kotlin.fir.declarations.FirProperty
import org.jetbrains.kotlin.fir.declarations.FirRegularClass
import org.jetbrains.kotlin.fir.declarations.isConst
import org.jetbrains.kotlin.lexer.KtTokens
object FirConstPropertyChecker : FirPropertyChecker() {
override fun check(declaration: FirProperty, context: CheckerContext, reporter: DiagnosticReporter) {
if (!declaration.isConst) return
if (declaration.isVar) {
val constModifier = declaration.getModifier(KtTokens.CONST_KEYWORD)
constModifier?.let {
reporter.reportOn(it.source, FirErrors.WRONG_MODIFIER_TARGET, it.token, "vars", context)
}
}
val classKind = (context.containingDeclarations.lastOrNull() as? FirRegularClass)?.classKind
if (classKind != ClassKind.OBJECT && context.containingDeclarations.size > 1) {
reporter.reportOn(declaration.source, FirErrors.CONST_VAL_NOT_TOP_LEVEL_OR_OBJECT, context)

View File

@@ -32,7 +32,7 @@ object FirConstructorAllowedChecker : FirConstructorChecker() {
reporter.reportOn(source, FirErrors.NON_PRIVATE_CONSTRUCTOR_IN_ENUM, context)
}
ClassKind.CLASS -> if (containingClass is FirRegularClass && containingClass.modality == Modality.SEALED) {
val modifierList = with(FirModifierList) { source.getModifierList() } ?: return
val modifierList = source.getModifierList() ?: return
val hasIllegalModifier = modifierList.modifiers.any {
it.token != KtTokens.PROTECTED_KEYWORD && it.token != KtTokens.PRIVATE_KEYWORD
}

View File

@@ -5,9 +5,11 @@
package org.jetbrains.kotlin.fir.analysis.checkers.declaration
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.fir.FirElement
import org.jetbrains.kotlin.fir.FirSourceElement
import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext
import org.jetbrains.kotlin.fir.analysis.checkers.modality
@@ -16,7 +18,11 @@ import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors
import org.jetbrains.kotlin.fir.analysis.diagnostics.reportOn
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.declarations.impl.FirDefaultPropertyAccessor
import org.jetbrains.kotlin.fir.expressions.FirVariableAssignment
import org.jetbrains.kotlin.fir.languageVersionSettings
import org.jetbrains.kotlin.fir.references.FirBackingFieldReference
import org.jetbrains.kotlin.fir.types.FirImplicitTypeRef
import org.jetbrains.kotlin.fir.visitors.FirVisitorVoid
import org.jetbrains.kotlin.lexer.KtTokens
internal fun isInsideExpectClass(containingClass: FirRegularClass, context: CheckerContext): Boolean {
@@ -85,7 +91,7 @@ internal fun checkPropertyInitializer(
context: CheckerContext
) {
val inInterface = containingClass?.isInterface == true
val hasAbstractModifier = modifierList?.modifiers?.any { it.token == KtTokens.ABSTRACT_KEYWORD } == true
val hasAbstractModifier = KtTokens.ABSTRACT_KEYWORD in modifierList
val isAbstract = property.isAbstract || hasAbstractModifier
if (isAbstract) {
if (property.initializer == null && property.delegate == null && property.returnTypeRef is FirImplicitTypeRef) {
@@ -168,8 +174,36 @@ internal fun checkPropertyAccessors(
reporter: DiagnosticReporter,
context: CheckerContext
) {
property.setter?.source?.let {
if (property.isVal) {
if (property.isVal) {
if (property.getter != null) {
var reassignment: FirBackingFieldReference? = null
// TODO: consider replacing this with normal VariableAssignmentChecker and reporting all 'field = ...' in getter (not just 1st)
// This way is a bit hacky and does not handle diagnostic suppression normally
val visitor = object : FirVisitorVoid() {
override fun visitElement(element: FirElement) {
element.acceptChildren(this)
}
override fun visitVariableAssignment(variableAssignment: FirVariableAssignment) {
// Report the first violation (to match FE 1.0 behavior)
if (reassignment != null) return
val backingFieldReference = variableAssignment.lValue as? FirBackingFieldReference
if (backingFieldReference?.resolvedSymbol?.fir == property) {
reassignment = backingFieldReference
}
}
}
property.getter?.body?.accept(visitor, null)
reassignment?.source?.let {
if (context.session.languageVersionSettings.supportsFeature(LanguageFeature.RestrictionOfValReassignmentViaBackingField)) {
reporter.reportOn(it, FirErrors.VAL_REASSIGNMENT_VIA_BACKING_FIELD_ERROR, property.symbol, context)
} else {
reporter.reportOn(it, FirErrors.VAL_REASSIGNMENT_VIA_BACKING_FIELD, property.symbol, context)
}
}
}
property.setter?.source?.let {
reporter.reportOn(it, FirErrors.VAL_WITH_SETTER, context)
}
}
@@ -184,6 +218,5 @@ internal val FirClass<*>.canHaveOpenMembers: Boolean get() = modality() != Modal
internal fun FirRegularClass.isInlineOrValueClass(): Boolean {
if (this.classKind != ClassKind.CLASS) return false
val modifierList = with(FirModifierList) { source.getModifierList() }
return isInline || modifierList?.modifiers?.any { it.token == KtTokens.VALUE_KEYWORD } == true
return isInline || hasModifier(KtTokens.VALUE_KEYWORD)
}

View File

@@ -5,13 +5,17 @@
package org.jetbrains.kotlin.fir.analysis.checkers.declaration
import org.jetbrains.kotlin.fir.FirRealSourceElementKind
import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext
import org.jetbrains.kotlin.fir.analysis.checkers.isInline
import org.jetbrains.kotlin.fir.analysis.diagnostics.DiagnosticReporter
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors
import org.jetbrains.kotlin.fir.analysis.diagnostics.reportOn
import org.jetbrains.kotlin.fir.analysis.diagnostics.reportOnWithSuppression
import org.jetbrains.kotlin.fir.declarations.FirFunction
import org.jetbrains.kotlin.fir.diagnostics.ConeSimpleDiagnostic
import org.jetbrains.kotlin.fir.diagnostics.DiagnosticKind
import org.jetbrains.kotlin.fir.typeContext
import org.jetbrains.kotlin.fir.types.FirErrorTypeRef
import org.jetbrains.kotlin.fir.types.arrayElementType
import org.jetbrains.kotlin.fir.types.coneType
import org.jetbrains.kotlin.fir.types.isUnsignedTypeOrNullableUnsignedType
@@ -20,13 +24,32 @@ import org.jetbrains.kotlin.types.AbstractTypeChecker
object FirFunctionParameterChecker : FirFunctionChecker() {
override fun check(declaration: FirFunction<*>, context: CheckerContext, reporter: DiagnosticReporter) {
checkVarargParameters(declaration, context, reporter)
checkParameterTypes(declaration, context, reporter)
}
private fun checkParameterTypes(declaration: FirFunction<*>, context: CheckerContext, reporter: DiagnosticReporter) {
for (valueParameter in declaration.valueParameters) {
val returnTypeRef = valueParameter.returnTypeRef
if (returnTypeRef !is FirErrorTypeRef) continue
// type problems on real source are already reported by ConeDiagnostic.toFirDiagnostics
if (returnTypeRef.source?.kind == FirRealSourceElementKind) continue
val diagnostic = returnTypeRef.diagnostic
if (diagnostic is ConeSimpleDiagnostic && diagnostic.kind == DiagnosticKind.ValueParameterWithNoTypeAnnotation) {
reporter.reportOnWithSuppression(
valueParameter,
FirErrors.VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION,
context
)
}
}
}
private fun checkVarargParameters(function: FirFunction<*>, context: CheckerContext, reporter: DiagnosticReporter) {
val varargParameters = function.valueParameters.filter { it.isVararg }
if (varargParameters.size > 1) {
for (parameter in varargParameters) {
reporter.reportOn(parameter.source ?: continue, FirErrors.MULTIPLE_VARARG_PARAMETERS, context)
reporter.reportOnWithSuppression(parameter, FirErrors.MULTIPLE_VARARG_PARAMETERS, context)
}
}
@@ -38,8 +61,8 @@ object FirFunctionParameterChecker : FirFunctionChecker() {
// Note: comparing with FE1.0, we skip checking if the type is not primitive because primitive types are not inline. That
// is any primitive values are already allowed by the inline check.
) {
reporter.reportOn(
varargParameter.source ?: continue,
reporter.reportOnWithSuppression(
varargParameter,
FirErrors.FORBIDDEN_VARARG_PARAMETER_TYPE,
varargParameterType,
context

View File

@@ -173,8 +173,7 @@ object FirInlineClassDeclarationChecker : FirRegularClassChecker() {
private fun FirValueParameter.isNotFinalReadOnly(primaryConstructorProperty: FirProperty?): Boolean {
if (primaryConstructorProperty == null) return true
val modifierList = with(FirModifierList) { source.getModifierList() }
val isOpen = modifierList?.modifiers?.any { it.token == KtTokens.OPEN_KEYWORD } == true
val isOpen = hasModifier(KtTokens.OPEN_KEYWORD)
return isVararg || !primaryConstructorProperty.isVal || isOpen
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.analysis.checkers.declaration
import org.jetbrains.kotlin.fir.FirFakeSourceElementKind
import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext
import org.jetbrains.kotlin.fir.analysis.diagnostics.DiagnosticReporter
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors
import org.jetbrains.kotlin.fir.analysis.diagnostics.reportOn
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.resolve.diagnostics.ConeTypeParameterInQualifiedAccess
import org.jetbrains.kotlin.fir.resolve.inference.inferenceComponents
import org.jetbrains.kotlin.fir.resolve.inference.isKClassType
import org.jetbrains.kotlin.fir.scopes.impl.toConeType
import org.jetbrains.kotlin.fir.types.*
// See FE1.0 [KClassWithIncorrectTypeArgumentChecker]
object FirKClassWithIncorrectTypeArgumentChecker : FirFileChecker() {
override fun check(declaration: FirFile, context: CheckerContext, reporter: DiagnosticReporter) {
for (topLevelDeclaration in declaration.declarations) {
if (topLevelDeclaration is FirCallableMemberDeclaration<*>) {
checkTopLevelDeclaration(topLevelDeclaration, context, reporter)
}
}
}
// When a type parameter is used as a type argument for KClass, it shouldn't be nullable.
// bad: fun <T> test1() = T::class
// okay: fun <T: Any> test2() = T::class
private fun checkTopLevelDeclaration(
declaration: FirCallableMemberDeclaration<*>,
context: CheckerContext,
reporter: DiagnosticReporter
) {
val source = declaration.source ?: return
if (source.kind is FirFakeSourceElementKind) return
val returnType = declaration.returnTypeRef.coneType
if (!returnType.isKClassTypeWithErrorOrNullableArgument(context.session.inferenceComponents.ctx)) return
val typeArgument = (returnType.typeArguments[0] as ConeKotlinTypeProjection).type
typeArgument.typeParameterFromError?.let {
reporter.reportOn(source, FirErrors.KCLASS_WITH_NULLABLE_TYPE_PARAMETER_IN_SIGNATURE, it.symbol, context)
}
}
private fun ConeKotlinType.isKClassTypeWithErrorOrNullableArgument(context: ConeInferenceContext): Boolean {
if (!this.isKClassType()) return false
val argumentType = typeArguments.toList().singleOrNull()?.let {
when (it) {
is ConeStarProjection -> null
is ConeKotlinTypeProjection -> it.type
}
} ?: return false
with(context) {
argumentType.typeParameterFromError?.let { typeParameter ->
return typeParameter.toConeType().isNullableType()
}
return argumentType is ConeKotlinErrorType || argumentType.isNullableType()
}
}
private val ConeKotlinType.typeParameterFromError: FirTypeParameter?
get() = ((this as? ConeKotlinErrorType)?.diagnostic as? ConeTypeParameterInQualifiedAccess)?.symbol?.fir
}

View File

@@ -34,8 +34,8 @@ object FirMemberFunctionsChecker : FirRegularClassChecker() {
if (source.kind is FirFakeSourceElementKind) return
// If multiple (potentially conflicting) modality modifiers are specified, not all modifiers are recorded at `status`.
// So, our source of truth should be the full modifier list retrieved from the source.
val modifierList = with(FirModifierList) { source.getModifierList() }
val hasAbstractModifier = modifierList?.modifiers?.any { it.token == KtTokens.ABSTRACT_KEYWORD } == true
val modifierList = source.getModifierList()
val hasAbstractModifier = KtTokens.ABSTRACT_KEYWORD in modifierList
val isAbstract = function.isAbstract || hasAbstractModifier
if (isAbstract) {
if (!containingDeclaration.canHaveAbstractDeclaration) {
@@ -49,7 +49,7 @@ object FirMemberFunctionsChecker : FirRegularClassChecker() {
}
}
val isInsideExpectClass = isInsideExpectClass(containingDeclaration, context)
val hasOpenModifier = modifierList?.modifiers?.any { it.token == KtTokens.OPEN_KEYWORD } == true
val hasOpenModifier = KtTokens.OPEN_KEYWORD in modifierList
if (!function.hasBody) {
if (containingDeclaration.isInterface) {
if (Visibilities.isPrivate(function.visibility)) {

View File

@@ -146,7 +146,7 @@ object FirMemberPropertiesChecker : FirRegularClassChecker() {
if (source.kind is FirFakeSourceElementKind) return
// If multiple (potentially conflicting) modality modifiers are specified, not all modifiers are recorded at `status`.
// So, our source of truth should be the full modifier list retrieved from the source.
val modifierList = with(FirModifierList) { property.source.getModifierList() }
val modifierList = property.source.getModifierList()
checkPropertyInitializer(
containingDeclaration,
@@ -159,7 +159,7 @@ object FirMemberPropertiesChecker : FirRegularClassChecker() {
checkPropertyAccessors(property, reporter, context)
checkExpectDeclarationVisibilityAndBody(property, source, reporter, context)
val hasAbstractModifier = modifierList?.modifiers?.any { it.token == KtTokens.ABSTRACT_KEYWORD } == true
val hasAbstractModifier = KtTokens.ABSTRACT_KEYWORD in modifierList
val isAbstract = property.isAbstract || hasAbstractModifier
if (containingDeclaration.isInterface &&
Visibilities.isPrivate(property.visibility) &&
@@ -203,7 +203,7 @@ object FirMemberPropertiesChecker : FirRegularClassChecker() {
}
}
val hasOpenModifier = modifierList?.modifiers?.any { it.token == KtTokens.OPEN_KEYWORD } == true
val hasOpenModifier = KtTokens.OPEN_KEYWORD in modifierList
if (hasOpenModifier &&
containingDeclaration.isInterface &&
!hasAbstractModifier &&

View File

@@ -169,7 +169,7 @@ object FirModifierChecker : FirBasicDeclarationChecker() {
if (!isDeclarationMappedToSourceCorrectly(declaration, source)) return
if (context.containingDeclarations.last() is FirDefaultPropertyAccessor) return
val modifierList = with(FirModifierList) { source.getModifierList() }
val modifierList = source.getModifierList()
modifierList?.let { checkModifiers(it, declaration, reporter, context) }
}

View File

@@ -12,6 +12,7 @@ import com.intellij.util.diff.FlyweightCapableTreeStructure
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.fir.*
import org.jetbrains.kotlin.fir.analysis.checkers.getChildren
import org.jetbrains.kotlin.fir.declarations.FirDeclaration
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtModifierList
@@ -44,19 +45,9 @@ internal sealed class FirModifierList {
}
}
companion object {
fun FirSourceElement?.getModifierList(): FirModifierList? {
return when (this) {
null -> null
is FirPsiSourceElement<*> -> (psi as? KtModifierListOwner)?.modifierList?.let { FirPsiModifierList(it) }
is FirLightSourceElement -> {
val modifierListNode = lighterASTNode.getChildren(treeStructure).find { it?.tokenType == KtNodeTypes.MODIFIER_LIST }
?: return null
FirLightModifierList(modifierListNode, treeStructure)
}
}
}
}
operator fun get(token: KtModifierKeywordToken): FirModifier<*>? = modifiers.firstOrNull { it.token == token }
operator fun contains(token: KtModifierKeywordToken): Boolean = modifiers.any { it.token == token }
}
private val MODIFIER_KEYWORD_SET = TokenSet.orSet(KtTokens.SOFT_KEYWORDS, TokenSet.create(KtTokens.IN_KEYWORD, KtTokens.FUN_KEYWORD))
@@ -82,3 +73,21 @@ internal sealed class FirModifier<Node : Any>(val node: Node, val token: KtModif
abstract val source: FirSourceElement
}
internal fun FirSourceElement?.getModifierList(): FirModifierList? {
return when (this) {
null -> null
is FirPsiSourceElement<*> -> (psi as? KtModifierListOwner)?.modifierList?.let { FirModifierList.FirPsiModifierList(it) }
is FirLightSourceElement -> {
val modifierListNode = lighterASTNode.getChildren(treeStructure).find { it?.tokenType == KtNodeTypes.MODIFIER_LIST }
?: return null
FirModifierList.FirLightModifierList(modifierListNode, treeStructure)
}
}
}
internal operator fun FirModifierList?.contains(token: KtModifierKeywordToken): Boolean = this?.contains(token) == true
internal fun FirDeclaration.getModifier(token: KtModifierKeywordToken): FirModifier<*>? = source.getModifierList()?.get(token)
internal fun FirDeclaration.hasModifier(token: KtModifierKeywordToken): Boolean = token in source.getModifierList()

View File

@@ -10,7 +10,6 @@ import org.jetbrains.kotlin.fir.FirFakeSourceElementKind
import org.jetbrains.kotlin.fir.FirRealSourceElementKind
import org.jetbrains.kotlin.fir.FirSourceElement
import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext
import org.jetbrains.kotlin.fir.analysis.checkers.declaration.FirModifierList.Companion.getModifierList
import org.jetbrains.kotlin.fir.analysis.diagnostics.DiagnosticReporter
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors
import org.jetbrains.kotlin.fir.analysis.diagnostics.reportOn
@@ -29,7 +28,7 @@ object FirOpenMemberChecker : FirClassChecker() {
memberDeclaration is FirConstructor
) continue
val source = memberDeclaration.source ?: continue
if (memberDeclaration.isOpen || (source.hasOpenModifierInSource && source.shouldReportOpenFromSource)) {
if (memberDeclaration.isOpen || memberDeclaration.hasModifier(KtTokens.OPEN_KEYWORD) && source.shouldReportOpenFromSource) {
if (declaration.classKind == ClassKind.OBJECT) {
reporter.reportOn(source, FirErrors.NON_FINAL_MEMBER_IN_OBJECT, context)
} else {
@@ -39,7 +38,6 @@ object FirOpenMemberChecker : FirClassChecker() {
}
}
private val FirSourceElement.hasOpenModifierInSource: Boolean get() = getModifierList()?.modifiers?.any { it.token == KtTokens.OPEN_KEYWORD } == true
private val FirSourceElement.shouldReportOpenFromSource: Boolean
get() = when (kind) {
FirRealSourceElementKind,

View File

@@ -28,8 +28,7 @@ object FirTopLevelFunctionsChecker : FirFileChecker() {
if (source.kind is FirFakeSourceElementKind) return
// If multiple (potentially conflicting) modality modifiers are specified, not all modifiers are recorded at `status`.
// So, our source of truth should be the full modifier list retrieved from the source.
val modifierList = with(FirModifierList) { source.getModifierList() }
if (modifierList?.modifiers?.any { it.token == KtTokens.ABSTRACT_KEYWORD } == true) return
if (function.hasModifier(KtTokens.ABSTRACT_KEYWORD)) return
if (function.isExternal) return
if (!function.hasBody && !function.isExpect) {
reporter.reportOn(source, FirErrors.NON_MEMBER_FUNCTION_NO_BODY, function, context)

View File

@@ -26,7 +26,7 @@ object FirTopLevelPropertiesChecker : FirFileChecker() {
if (source.kind is FirFakeSourceElementKind) return
// If multiple (potentially conflicting) modality modifiers are specified, not all modifiers are recorded at `status`.
// So, our source of truth should be the full modifier list retrieved from the source.
val modifierList = with(FirModifierList) { source.getModifierList() }
val modifierList = source.getModifierList()
checkPropertyInitializer(
containingClass = null,

View File

@@ -0,0 +1,46 @@
/*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.analysis.checkers.declaration.jvm
import org.jetbrains.kotlin.fir.FirFakeSourceElementKind
import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext
import org.jetbrains.kotlin.fir.analysis.checkers.declaration.FirMemberDeclarationChecker
import org.jetbrains.kotlin.fir.analysis.checkers.declaration.FirModifierList
import org.jetbrains.kotlin.fir.analysis.checkers.declaration.getModifier
import org.jetbrains.kotlin.fir.analysis.checkers.declaration.getModifierList
import org.jetbrains.kotlin.fir.analysis.diagnostics.DiagnosticReporter
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors
import org.jetbrains.kotlin.fir.analysis.diagnostics.reportOn
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.lexer.KtTokens
// TODO: Move this to different, JVM-specific module?
object FirJvmExternalDeclarationChecker : FirMemberDeclarationChecker() {
override fun check(declaration: FirMemberDeclaration, context: CheckerContext, reporter: DiagnosticReporter) {
if (!declaration.isExternal) return
val source = declaration.source ?: return
if (source.kind is FirFakeSourceElementKind) return
// WRONG_MODIFIER_TARGET on external constructor is intentionally NOT covered in this checker.
if (declaration !is FirFunction<*>) {
val target = when (declaration) {
is FirProperty -> "property"
is FirRegularClass -> "class"
else -> "non-function declaration"
}
val externalModifier = declaration.getModifier(KtTokens.EXTERNAL_KEYWORD)
externalModifier?.let {
reporter.reportOn(it.source, FirErrors.WRONG_MODIFIER_TARGET, it.token, target, context)
}
}
// TODO: Implement checkers for these JVM-specific errors (see ExternalFunChecker in FE1.0):
// - EXTERNAL_DECLARATION_IN_INTERFACE
// - EXTERNAL_DECLARATION_CANNOT_BE_ABSTRACT
// - EXTERNAL_DECLARATION_CANNOT_HAVE_BODY
// - EXTERNAL_DECLARATION_CANNOT_BE_INLINED
}
}

View File

@@ -13,9 +13,11 @@ import org.jetbrains.kotlin.fir.analysis.diagnostics.reportOn
import org.jetbrains.kotlin.fir.analysis.getChild
import org.jetbrains.kotlin.fir.declarations.FirTypeParameter
import org.jetbrains.kotlin.fir.declarations.FirTypeParameterRefsOwner
import org.jetbrains.kotlin.fir.expressions.FirGetClassCall
import org.jetbrains.kotlin.fir.expressions.FirResolvedQualifier
import org.jetbrains.kotlin.fir.expressions.FirStatement
import org.jetbrains.kotlin.fir.expressions.*
import org.jetbrains.kotlin.fir.references.FirResolvedNamedReference
import org.jetbrains.kotlin.fir.resolve.inference.inferenceComponents
import org.jetbrains.kotlin.fir.scopes.impl.toConeType
import org.jetbrains.kotlin.fir.symbols.impl.FirTypeParameterSymbol
import org.jetbrains.kotlin.fir.types.*
import org.jetbrains.kotlin.lexer.KtTokens.QUEST
@@ -25,7 +27,6 @@ object FirGetClassCallChecker : FirBasicExpressionChecker() {
val source = expression.source ?: return
if (source.kind is FirFakeSourceElementKind) return
val argument = expression.argument as? FirResolvedQualifier ?: return
// Note that raw FIR drops marked nullability "?" in, e.g., `A?::class`, `A<T?>::class`, or `A<T?>?::class`.
// That is, AST structures for those expressions have token type QUEST, whereas FIR element doesn't have any information about it.
//
@@ -36,10 +37,33 @@ object FirGetClassCallChecker : FirBasicExpressionChecker() {
//
// Only the 2nd example is valid, and we want to check if token type QUEST doesn't exist at the same level as COLONCOLON.
val markedNullable = source.getChild(QUEST, depth = 1) != null
if (argument.isNullableLHSForCallableReference || markedNullable) {
reporter.reportOn(source, FirErrors.NULLABLE_TYPE_IN_CLASS_LITERAL_LHS, context)
val argument = expression.argument
val isNullable = markedNullable ||
(argument as? FirResolvedQualifier)?.isNullableLHSForCallableReference == true ||
argument.typeRef.coneType.isMarkedNullable ||
argument.typeRef.coneType.isNullableTypeParameter(context.session.inferenceComponents.ctx)
if (isNullable) {
if (argument.canBeDoubleColonLHSAsType) {
reporter.reportOn(source, FirErrors.NULLABLE_TYPE_IN_CLASS_LITERAL_LHS, context)
} else {
reporter.reportOn(
argument.source,
FirErrors.EXPRESSION_OF_NULLABLE_TYPE_IN_CLASS_LITERAL_LHS,
argument.typeRef.coneType,
context
)
}
return
}
argument.safeAsTypeParameterSymbol?.let {
if (!it.fir.isReified) {
// E.g., fun <T: Any> foo(): Any = T::class
reporter.reportOn(source, FirErrors.TYPE_PARAMETER_AS_REIFIED, it, context)
}
}
if (argument !is FirResolvedQualifier) return
// TODO: differentiate RESERVED_SYNTAX_IN_CALLABLE_REFERENCE_LHS
if (argument.typeArguments.isNotEmpty() && !argument.typeRef.coneType.isAllowedInClassLiteral(context)) {
val typeParameters = (argument.symbol?.fir as? FirTypeParameterRefsOwner)?.typeParameters
@@ -53,6 +77,30 @@ object FirGetClassCallChecker : FirBasicExpressionChecker() {
}
}
private fun ConeKotlinType.isNullableTypeParameter(context: ConeInferenceContext): Boolean {
if (this !is ConeTypeParameterType) return false
val typeParameter = lookupTag.typeParameterSymbol.fir
with(context) {
return !typeParameter.isReified &&
// E.g., fun <T> f2(t: T): Any = t::class
typeParameter.toConeType().isNullableType()
}
}
private val FirExpression.canBeDoubleColonLHSAsType: Boolean
get() {
return this is FirResolvedQualifier ||
this is FirResolvedReifiedParameterReference ||
safeAsTypeParameterSymbol != null
}
private val FirExpression.safeAsTypeParameterSymbol: FirTypeParameterSymbol?
get() {
return ((this as? FirQualifiedAccessExpression)
?.calleeReference as? FirResolvedNamedReference)
?.resolvedSymbol as? FirTypeParameterSymbol
}
private fun ConeKotlinType.isAllowedInClassLiteral(context: CheckerContext): Boolean =
when (this) {
is ConeClassLikeType -> {

View File

@@ -0,0 +1,59 @@
/*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.analysis.checkers.expression
import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext
import org.jetbrains.kotlin.fir.analysis.diagnostics.DiagnosticReporter
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors
import org.jetbrains.kotlin.fir.analysis.diagnostics.reportOn
import org.jetbrains.kotlin.fir.expressions.FirCallableReferenceAccess
import org.jetbrains.kotlin.fir.expressions.FirQualifiedAccessExpression
import org.jetbrains.kotlin.fir.expressions.FirResolvedReifiedParameterReference
import org.jetbrains.kotlin.fir.resolve.diagnostics.ConeTypeParameterInQualifiedAccess
import org.jetbrains.kotlin.fir.types.FirErrorTypeRef
import org.jetbrains.kotlin.fir.types.FirTypeRef
object FirTypeParameterInQualifiedAccessChecker : FirQualifiedAccessChecker() {
override fun check(expression: FirQualifiedAccessExpression, context: CheckerContext, reporter: DiagnosticReporter) {
checkExplicitReceiver(expression, context, reporter)
checkExpressionItself(expression, context, reporter)
}
private fun checkExpressionItself(
expression: FirQualifiedAccessExpression,
context: CheckerContext,
reporter: DiagnosticReporter
) {
// Make sure the current qualified access is not part of another qualified access or class literals.
// E.g., for `T::toString`, which is a callable reference (a subtype of qualified access), type parameter T is checked once as an
// explicit receiver (or LHS). When we visit `T` (as a qualified access), we should not regard it as an expression here.
if (context.qualifiedAccesses.size > 1 || context.getClassCalls.isNotEmpty()) return
val diagnostic = expression.typeRef.coneTypeParameterInQualifiedAccess ?: return
val source = expression.source ?: return
reporter.reportOn(source, FirErrors.TYPE_PARAMETER_IS_NOT_AN_EXPRESSION, diagnostic.symbol, context)
}
private fun checkExplicitReceiver(
expression: FirQualifiedAccessExpression,
context: CheckerContext,
reporter: DiagnosticReporter
) {
val explicitReceiver = expression.explicitReceiver
val typeParameterSymbol =
(explicitReceiver as? FirResolvedReifiedParameterReference)?.symbol
?: explicitReceiver?.typeRef?.coneTypeParameterInQualifiedAccess?.symbol
?: return
if (expression is FirCallableReferenceAccess) {
reporter.reportOn(expression.source, FirErrors.CALLABLE_REFERENCE_LHS_NOT_A_CLASS, context)
} else {
reporter.reportOn(explicitReceiver?.source, FirErrors.TYPE_PARAMETER_ON_LHS_OF_DOT, typeParameterSymbol, context)
}
}
private val FirTypeRef.coneTypeParameterInQualifiedAccess: ConeTypeParameterInQualifiedAccess?
get() = (this as? FirErrorTypeRef)?.diagnostic as? ConeTypeParameterInQualifiedAccess
}

View File

@@ -214,6 +214,10 @@ abstract class AbstractDiagnosticCollector(
visitWithQualifiedAccess(qualifiedAccessExpression)
}
override fun visitGetClassCall(getClassCall: FirGetClassCall, data: Nothing?) {
visitWithGetClassCall(getClassCall)
}
private inline fun visitWithDeclaration(
declaration: FirDeclaration,
block: () -> Unit = { declaration.acceptChildren(this, null) }
@@ -252,6 +256,17 @@ abstract class AbstractDiagnosticCollector(
context = existingContext
}
}
private fun visitWithGetClassCall(getClassCall: FirGetClassCall) {
val existingContext = context
context = context.addGetClassCall(getClassCall)
try {
getClassCall.runComponents()
getClassCall.acceptChildren(this, null)
} finally {
context = existingContext
}
}
}
protected open fun getDeclarationActionOnDeclarationEnter(declaration: FirDeclaration): DiagnosticCollectorDeclarationAction =

View File

@@ -31,7 +31,7 @@ class DeclarationCheckersDiagnosticComponent(
}
override fun visitRegularClass(regularClass: FirRegularClass, data: CheckerContext) {
checkers.regularClassCheckers.check(regularClass, data, reporter)
(checkers.memberDeclarationCheckers + checkers.regularClassCheckers).check(regularClass, data, reporter)
}
override fun visitSimpleFunction(simpleFunction: FirSimpleFunction, data: CheckerContext) {

View File

@@ -39,6 +39,7 @@ import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.ASSIGNED_VALUE_IS
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.ASSIGN_OPERATOR_AMBIGUITY
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.BACKING_FIELD_IN_INTERFACE
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.BREAK_OR_CONTINUE_OUTSIDE_A_LOOP
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.CALLABLE_REFERENCE_LHS_NOT_A_CLASS
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.CANNOT_CHANGE_ACCESS_PRIVILEGE
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.CANNOT_WEAKEN_ACCESS_PRIVILEGE
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.CAN_BE_REPLACED_WITH_OPERATOR_ASSIGNMENT
@@ -54,10 +55,10 @@ import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.CONFLICTING_PROJE
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.CONSTRUCTOR_IN_INTERFACE
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.CONSTRUCTOR_IN_OBJECT
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.CYCLIC_CONSTRUCTOR_DELEGATION_CALL
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.DELEGATED_PROPERTY_INSIDE_INLINE_CLASS
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.DATA_CLASS_NOT_PROPERTY_PARAMETER
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.DATA_CLASS_VARARG_PARAMETER
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.DATA_CLASS_WITHOUT_PARAMETERS
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.DELEGATED_PROPERTY_INSIDE_INLINE_CLASS
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.DELEGATED_PROPERTY_IN_INTERFACE
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.DELEGATION_IN_INTERFACE
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.DELEGATION_SUPER_CALL_IN_ENUM_CONSTRUCTOR
@@ -81,6 +82,7 @@ import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.EXPOSED_SUPER_CLA
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.EXPOSED_SUPER_INTERFACE
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.EXPOSED_TYPEALIAS_EXPANDED_TYPE
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.EXPOSED_TYPE_PARAMETER_BOUND
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.EXPRESSION_OF_NULLABLE_TYPE_IN_CLASS_LITERAL_LHS
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.EXTENSION_PROPERTY_MUST_HAVE_ACCESSORS_OR_BE_ABSTRACT
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.EXTENSION_PROPERTY_WITH_BACKING_FIELD
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.FORBIDDEN_VARARG_PARAMETER_TYPE
@@ -109,17 +111,18 @@ import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.INSTANCE_ACCESS_B
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.INTERFACE_WITH_SUPERCLASS
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.INVALID_IF_AS_EXPRESSION
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.INVALID_TYPE_OF_ANNOTATION_MEMBER
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.KCLASS_WITH_NULLABLE_TYPE_PARAMETER_IN_SIGNATURE
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.LEAKED_IN_PLACE_LAMBDA
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.LOCAL_ANNOTATION_CLASS_ERROR
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.LOCAL_INTERFACE_NOT_ALLOWED
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.LOCAL_OBJECT_NOT_ALLOWED
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.MANY_COMPANION_OBJECTS
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.MISSING_VAL_ON_ANNOTATION_PARAMETER
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.NESTED_CLASS_NOT_ALLOWED
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.MULTIPLE_VARARG_PARAMETERS
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.MUST_BE_INITIALIZED
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.MUST_BE_INITIALIZED_OR_BE_ABSTRACT
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.NAMED_ARGUMENTS_NOT_ALLOWED
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.NESTED_CLASS_NOT_ALLOWED
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.NONE_APPLICABLE
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.NON_ABSTRACT_FUNCTION_WITH_NO_BODY
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.NON_FINAL_MEMBER_IN_FINAL_CLASS
@@ -133,7 +136,6 @@ import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.NOT_A_LOOP_LABEL
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.NOT_A_SUPERTYPE
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.NO_ELSE_IN_WHEN
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.NO_THIS
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.NO_TYPE_FOR_TYPE_PARAMETER
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.NULLABLE_TYPE_IN_CLASS_LITERAL_LHS
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.NULLABLE_TYPE_OF_ANNOTATION_MEMBER
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.OTHER_ERROR
@@ -183,8 +185,11 @@ import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.TYPE_ARGUMENTS_NO
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.TYPE_MISMATCH
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.TYPE_PARAMETERS_IN_ENUM
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.TYPE_PARAMETERS_IN_OBJECT
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.TYPE_PARAMETER_AS_REIFIED
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.TYPE_PARAMETER_AS_SUPERTYPE
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.TYPE_PARAMETER_IN_CATCH_CLAUSE
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.TYPE_PARAMETER_IS_NOT_AN_EXPRESSION
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.TYPE_PARAMETER_ON_LHS_OF_DOT
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.UNINITIALIZED_VARIABLE
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.UNNECESSARY_LATEINIT
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.UNRESOLVED_LABEL
@@ -196,9 +201,12 @@ import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.UNSAFE_OPERATOR_C
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.UNUSED_VARIABLE
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.UPPER_BOUND_VIOLATED
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.USELESS_VARARG_ON_PARAMETER
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.VAL_REASSIGNMENT
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.VAL_WITH_SETTER
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.VALUE_CLASS_CANNOT_BE_CLONEABLE
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.VAL_REASSIGNMENT
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.VAL_REASSIGNMENT_VIA_BACKING_FIELD
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.VAL_REASSIGNMENT_VIA_BACKING_FIELD_ERROR
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.VAL_WITH_SETTER
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.VARARG_OUTSIDE_PARENTHESES
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.VARIABLE_EXPECTED
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.VARIABLE_INITIALIZER_IS_REDUNDANT
@@ -208,6 +216,7 @@ import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.VAR_ANNOTATION_PA
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.VAR_OVERRIDDEN_BY_VAL
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.VAR_TYPE_MISMATCH_ON_OVERRIDE
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.WRONG_INVOCATION_KIND
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.WRONG_MODIFIER_TARGET
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.WRONG_NUMBER_OF_TYPE_ARGUMENTS
@Suppress("unused")
@@ -348,6 +357,7 @@ class FirDefaultErrorMessages : DefaultErrorMessages.Extension {
map.put(DEPRECATED_MODIFIER_PAIR, "Modifier ''{0}'' is deprecated in presence of ''{1}''", TO_STRING, TO_STRING)
map.put(INCOMPATIBLE_MODIFIERS, "Modifier ''{0}'' is incompatible with ''{1}''", TO_STRING, TO_STRING)
map.put(REDUNDANT_OPEN_IN_INTERFACE, "Modifier 'open' is redundant for abstract interface members")
map.put(WRONG_MODIFIER_TARGET, "Modifier ''{0}'' is not applicable to ''{1}''", TO_STRING, TO_STRING)
// Applicability
map.put(NONE_APPLICABLE, "None of the following functions are applicable: {0}", SYMBOLS)
@@ -373,7 +383,6 @@ class FirDefaultErrorMessages : DefaultErrorMessages.Extension {
null,
TO_STRING
)
map.put(NO_TYPE_FOR_TYPE_PARAMETER, "There're no types suitable for this type parameter") // &
map.put(TYPE_PARAMETERS_IN_OBJECT, "Type parameters are not allowed for objects")
// map.put(ILLEGAL_PROJECTION_USAGE, ...) // &
map.put(TYPE_PARAMETERS_IN_ENUM, "Enum class cannot have type parameters")
@@ -390,9 +399,25 @@ class FirDefaultErrorMessages : DefaultErrorMessages.Extension {
map.put(REIFIED_TYPE_IN_CATCH_CLAUSE, "Reified type is forbidden for catch parameter")
map.put(TYPE_PARAMETER_IN_CATCH_CLAUSE, "Type parameter is forbidden for catch parameter")
map.put(
KCLASS_WITH_NULLABLE_TYPE_PARAMETER_IN_SIGNATURE,
"Declaration has an inconsistent return type. " +
"Please add upper bound Any for type parameter ''{0}'' or specify return type explicitly",
SYMBOL
)
map.put(TYPE_PARAMETER_AS_REIFIED, "Cannot use ''{0}'' as reified type parameter. Use a class instead", SYMBOL)
// Reflection
map.put(CALLABLE_REFERENCE_LHS_NOT_A_CLASS, "Left-hand side of a callable reference cannot be a type parameter")
map.put(CLASS_LITERAL_LHS_NOT_A_CLASS, "Only classes are allowed on the left hand side of a class literal")
map.put(NULLABLE_TYPE_IN_CLASS_LITERAL_LHS, "Type in a class literal must not be nullable")
map.put(
EXPRESSION_OF_NULLABLE_TYPE_IN_CLASS_LITERAL_LHS,
"Expression in a class literal has a nullable type ''{0}'', use !! to make the type non-nullable",
RENDER_TYPE
)
// Inline and value classes
map.put(INLINE_CLASS_NOT_TOP_LEVEL, "Inline classes cannot be local or inner")
@@ -505,6 +530,7 @@ class FirDefaultErrorMessages : DefaultErrorMessages.Extension {
map.put(USELESS_VARARG_ON_PARAMETER, "Vararg on this parameter is useless")
map.put(MULTIPLE_VARARG_PARAMETERS, "Multiple vararg-parameters are prohibited")
map.put(FORBIDDEN_VARARG_PARAMETER_TYPE, "Forbidden vararg parameter type: {0}", RENDER_TYPE)
map.put(VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION, "A type annotation is required on a value parameter")
// Properties & accessors
map.put(
@@ -570,6 +596,8 @@ class FirDefaultErrorMessages : DefaultErrorMessages.Extension {
// Control flow diagnostics
map.put(UNINITIALIZED_VARIABLE, "{0} must be initialized before access", PROPERTY_NAME)
map.put(VAL_REASSIGNMENT, "Val cannot be reassigned", PROPERTY_NAME)
map.put(VAL_REASSIGNMENT_VIA_BACKING_FIELD, "Reassignment of read-only property via backing field is deprecated", PROPERTY_NAME)
map.put(VAL_REASSIGNMENT_VIA_BACKING_FIELD_ERROR, "Reassignment of read-only property via backing field", PROPERTY_NAME)
map.put(
WRONG_INVOCATION_KIND,
"{2} wrong invocation kind: given {3} case, but {4} case is possible",
@@ -611,6 +639,14 @@ class FirDefaultErrorMessages : DefaultErrorMessages.Extension {
map.put(NO_ELSE_IN_WHEN, "''when'' expression must be exhaustive, add necessary {0}", WHEN_MISSING_CASES)
map.put(INVALID_IF_AS_EXPRESSION, "'if' must have both main and 'else' branches if used as an expression")
// Context tracking
map.put(TYPE_PARAMETER_IS_NOT_AN_EXPRESSION, "Type parameter ''{0}'' is not an expression", SYMBOL)
map.put(
TYPE_PARAMETER_ON_LHS_OF_DOT,
"Type parameter ''{0}'' cannot have or inherit a companion object, so it cannot be on the left hand side of dot",
SYMBOL
)
// Function contracts
map.put(ERROR_IN_CONTRACT_DESCRIPTION, "Error in contract description", TO_STRING)

View File

@@ -17,6 +17,7 @@ import org.jetbrains.kotlin.fir.symbols.AbstractFirBasedSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirCallableSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirClassLikeSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirPropertySymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirTypeParameterSymbol
import org.jetbrains.kotlin.fir.types.ConeKotlinType
import org.jetbrains.kotlin.fir.types.render
@@ -27,6 +28,7 @@ object FirDiagnosticRenderers {
when (symbol) {
is FirClassLikeSymbol<*> -> symbol.classId.asString()
is FirCallableSymbol<*> -> symbol.callableId.toString()
is FirTypeParameterSymbol -> symbol.name.asString()
else -> "???"
}
}

View File

@@ -22,7 +22,6 @@ import org.jetbrains.kotlin.fir.types.*
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.resolve.calls.tower.isSuccess
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.kotlin.utils.ifEmpty
private fun ConeDiagnostic.toFirDiagnostic(source: FirSourceElement): FirDiagnostic<FirSourceElement>? = when (this) {
is ConeUnresolvedReferenceError -> FirErrors.UNRESOLVED_REFERENCE.on(source, this.name?.asString() ?: "<No name>")
@@ -51,6 +50,7 @@ private fun ConeDiagnostic.toFirDiagnostic(source: FirSourceElement): FirDiagnos
is ConeIntermediateDiagnostic -> null
is ConeContractDescriptionError -> FirErrors.ERROR_IN_CONTRACT_DESCRIPTION.on(source, this.reason)
is ConeTypeParameterSupertype -> FirErrors.SUPERTYPE_NOT_A_CLASS_OR_INTERFACE.on(source, this.reason)
is ConeTypeParameterInQualifiedAccess -> null // reported in various checkers instead
else -> throw IllegalArgumentException("Unsupported diagnostic type: ${this.javaClass}")
}
@@ -146,7 +146,7 @@ private fun ConeSimpleDiagnostic.getFactory(): FirDiagnosticFactory0<FirSourceEl
DiagnosticKind.JumpOutsideLoop -> FirErrors.BREAK_OR_CONTINUE_OUTSIDE_A_LOOP
DiagnosticKind.NotLoopLabel -> FirErrors.NOT_A_LOOP_LABEL
DiagnosticKind.VariableExpected -> FirErrors.VARIABLE_EXPECTED
DiagnosticKind.NoTypeForTypeParameter -> FirErrors.NO_TYPE_FOR_TYPE_PARAMETER
DiagnosticKind.ValueParameterWithNoTypeAnnotation -> FirErrors.VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION
DiagnosticKind.UnknownCallableKind -> FirErrors.UNKNOWN_CALLABLE_KIND
DiagnosticKind.IllegalProjectionUsage -> FirErrors.ILLEGAL_PROJECTION_USAGE
DiagnosticKind.MissingStdlibClass -> FirErrors.MISSING_STDLIB_CLASS

View File

@@ -16,3 +16,8 @@ fun FirSessionFactory.FirSessionConfigurator.registerExtendedCommonCheckers() {
useCheckers(ExtendedExpressionCheckers)
useCheckers(ExtendedDeclarationCheckers)
}
// TODO: Move this to different, JVM-specific module?
fun FirSessionFactory.FirSessionConfigurator.registerJvmCheckers() {
useCheckers(JvmDeclarationCheckers)
}

View File

@@ -70,6 +70,7 @@ object CommonDeclarationCheckers : DeclarationCheckers() {
)
override val fileCheckers: Set<FirFileChecker> = setOf(
FirKClassWithIncorrectTypeArgumentChecker,
FirTopLevelFunctionsChecker,
FirTopLevelPropertiesChecker,
)

View File

@@ -22,6 +22,7 @@ object CommonExpressionCheckers : ExpressionCheckers() {
FirProjectionsOnNonClassTypeArgumentChecker,
FirUpperBoundViolatedChecker,
FirTypeArgumentsNotAllowedExpressionChecker,
FirTypeParameterInQualifiedAccessChecker,
FirSealedClassConstructorCallChecker,
)
override val functionCallCheckers: Set<FirFunctionCallChecker> = setOf()

View File

@@ -0,0 +1,16 @@
/*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.checkers
import org.jetbrains.kotlin.fir.analysis.checkers.declaration.*
import org.jetbrains.kotlin.fir.analysis.checkers.declaration.jvm.FirJvmExternalDeclarationChecker
// TODO: Move this to different, JVM-specific module?
object JvmDeclarationCheckers : DeclarationCheckers() {
override val memberDeclarationCheckers: Set<FirMemberDeclarationChecker> = setOf(
FirJvmExternalDeclarationChecker,
)
}

View File

@@ -22,6 +22,7 @@ import org.jetbrains.kotlin.fir.analysis.extensions.additionalCheckers
import org.jetbrains.kotlin.fir.caches.FirCachesFactory
import org.jetbrains.kotlin.fir.caches.FirThreadUnsafeCachesFactory
import org.jetbrains.kotlin.fir.checkers.registerCommonCheckers
import org.jetbrains.kotlin.fir.checkers.registerJvmCheckers
import org.jetbrains.kotlin.fir.extensions.BunchOfRegisteredExtensions
import org.jetbrains.kotlin.fir.extensions.extensionService
import org.jetbrains.kotlin.fir.extensions.registerExtensions
@@ -94,6 +95,7 @@ object FirSessionFactory {
FirSessionConfigurator(this).apply {
registerCommonCheckers()
registerJvmCheckers()
init()
}.configure()

View File

@@ -10,6 +10,7 @@ import org.jetbrains.kotlin.fir.backend.generators.AnnotationGenerator
import org.jetbrains.kotlin.fir.backend.generators.CallAndReferenceGenerator
import org.jetbrains.kotlin.fir.backend.generators.FakeOverrideGenerator
import org.jetbrains.kotlin.fir.resolve.ScopeSession
import org.jetbrains.kotlin.ir.IrLock
import org.jetbrains.kotlin.ir.declarations.IrFactory
import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns
import org.jetbrains.kotlin.ir.util.SymbolTable
@@ -22,6 +23,7 @@ interface Fir2IrComponents {
val irBuiltIns: IrBuiltIns
val builtIns: Fir2IrBuiltIns
val irFactory: IrFactory
val lock: IrLock
val classifierStorage: Fir2IrClassifierStorage
val declarationStorage: Fir2IrDeclarationStorage

View File

@@ -12,6 +12,7 @@ import org.jetbrains.kotlin.fir.backend.generators.FakeOverrideGenerator
import org.jetbrains.kotlin.fir.resolve.ScopeSession
import org.jetbrains.kotlin.fir.signaturer.FirBasedSignatureComposer
import org.jetbrains.kotlin.fir.signaturer.FirMangler
import org.jetbrains.kotlin.ir.IrLock
import org.jetbrains.kotlin.ir.declarations.IrFactory
import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns
import org.jetbrains.kotlin.ir.util.SymbolTable
@@ -36,4 +37,7 @@ class Fir2IrComponentsStorage(
override lateinit var annotationGenerator: AnnotationGenerator
override lateinit var callGenerator: CallAndReferenceGenerator
override lateinit var fakeOverrideGenerator: FakeOverrideGenerator
override val lock: IrLock
get() = symbolTable.lock
}

View File

@@ -1145,40 +1145,42 @@ class Fir2IrDeclarationStorage(
val fir = firSymbol.fir as F
val irParent by lazy { findIrParent(fir) }
val signature by lazy { signatureComposer.composeSignature(fir) }
getCachedIrDeclaration(fir) {
// Parent calculation provokes declaration calculation for some members from IrBuiltIns
@Suppress("UNUSED_EXPRESSION") irParent
signature
}?.let { return it.symbol }
val parentOrigin = (irParent as? IrDeclaration)?.origin ?: IrDeclarationOrigin.DEFINED
val declarationOrigin = computeDeclarationOrigin(firSymbol, parentOrigin)
// TODO: package fragment members (?)
when (val parent = irParent) {
is Fir2IrLazyClass -> {
assert(parentOrigin != IrDeclarationOrigin.DEFINED) {
"Should not have reference to public API uncached property from source code"
synchronized(symbolTable.lock) {
getCachedIrDeclaration(fir) {
// Parent calculation provokes declaration calculation for some members from IrBuiltIns
@Suppress("UNUSED_EXPRESSION") irParent
signature
}?.let { return it.symbol }
val parentOrigin = (irParent as? IrDeclaration)?.origin ?: IrDeclarationOrigin.DEFINED
val declarationOrigin = computeDeclarationOrigin(firSymbol, parentOrigin)
// TODO: package fragment members (?)
when (val parent = irParent) {
is Fir2IrLazyClass -> {
assert(parentOrigin != IrDeclarationOrigin.DEFINED) {
"Should not have reference to public API uncached property from source code"
}
signature?.let {
return createIrLazyDeclaration(it, parent, declarationOrigin).symbol
}
}
signature?.let {
return createIrLazyDeclaration(it, parent, declarationOrigin).symbol
}
}
is IrLazyClass -> {
val unwrapped = fir.unwrapFakeOverrides()
if (unwrapped !== fir) {
when (unwrapped) {
is FirSimpleFunction -> {
return getIrFunctionSymbol(unwrapped.symbol)
}
is FirProperty -> {
return getIrPropertySymbol(unwrapped.symbol)
is IrLazyClass -> {
val unwrapped = fir.unwrapFakeOverrides()
if (unwrapped !== fir) {
when (unwrapped) {
is FirSimpleFunction -> {
return getIrFunctionSymbol(unwrapped.symbol)
}
is FirProperty -> {
return getIrPropertySymbol(unwrapped.symbol)
}
}
}
}
}
return createIrDeclaration(irParent, declarationOrigin).apply {
(this as IrDeclaration).setAndModifyParent(irParent)
}.symbol
}
return createIrDeclaration(irParent, declarationOrigin).apply {
(this as IrDeclaration).setAndModifyParent(irParent)
}.symbol
}
private fun computeDeclarationOrigin(
@@ -1224,7 +1226,9 @@ class Fir2IrDeclarationStorage(
private fun getIrVariableSymbol(firVariable: FirVariable<*>): IrVariableSymbol {
return localStorage.getVariable(firVariable)?.symbol
?: throw IllegalArgumentException("Cannot find variable ${firVariable.render()} in local storage")
?: run {
throw IllegalArgumentException("Cannot find variable ${firVariable.render()} in local storage")
}
}
fun getIrValueSymbol(firVariableSymbol: FirVariableSymbol<*>): IrSymbol {

View File

@@ -38,7 +38,7 @@ interface AbstractFir2IrLazyDeclaration<F : FirMemberDeclaration, D : IrDeclarat
}
}
fun createLazyAnnotations(): ReadWriteProperty<Any?, List<IrConstructorCall>> = lazyVar {
fun createLazyAnnotations(): ReadWriteProperty<Any?, List<IrConstructorCall>> = lazyVar(lock) {
fir.annotations.mapNotNull {
callGenerator.convertToIrConstructorCall(it) as? IrConstructorCall
}

View File

@@ -68,7 +68,7 @@ abstract class AbstractFir2IrLazyFunction<F : FirMemberDeclaration>(
get() = null
set(_) = error("We should never need to store body of external functions.")
override var visibility: DescriptorVisibility by lazyVar {
override var visibility: DescriptorVisibility by lazyVar(lock) {
components.visibilityConverter.convertToDescriptorVisibility(fir.visibility)
}

View File

@@ -96,11 +96,11 @@ class Fir2IrLazyClass(
override val isFun: Boolean
get() = fir.isFun
override var superTypes: List<IrType> by lazyVar {
override var superTypes: List<IrType> by lazyVar(lock) {
fir.superTypeRefs.map { it.toIrType(typeConverter) }
}
override var thisReceiver: IrValueParameter? by lazyVar {
override var thisReceiver: IrValueParameter? by lazyVar(lock) {
symbolTable.enterScope(this)
val typeArguments = fir.typeParameters.map {
IrSimpleTypeImpl(
@@ -124,7 +124,7 @@ class Fir2IrLazyClass(
.also(fakeOverrideGenerator::bindOverriddenSymbols)
}
override val declarations: MutableList<IrDeclaration> by lazyVar {
override val declarations: MutableList<IrDeclaration> by lazyVar(lock) {
val result = mutableListOf<IrDeclaration>()
val processedNames = mutableSetOf<Name>()
// NB: it's necessary to take all callables from scope,

View File

@@ -67,11 +67,11 @@ class Fir2IrLazyConstructor(
error("Mutating Fir2Ir lazy elements is not possible")
}
override var returnType: IrType by lazyVar {
override var returnType: IrType by lazyVar(lock) {
fir.returnTypeRef.toIrType(typeConverter)
}
override var dispatchReceiverParameter: IrValueParameter? by lazyVar {
override var dispatchReceiverParameter: IrValueParameter? by lazyVar(lock) {
val containingClass = parent as? IrClass
val outerClass = containingClass?.parentClassOrNull
if (containingClass?.isInner == true && outerClass != null) {
@@ -92,7 +92,7 @@ class Fir2IrLazyConstructor(
error("Mutating Fir2Ir lazy elements is not possible")
}
override var valueParameters: List<IrValueParameter> by lazyVar {
override var valueParameters: List<IrValueParameter> by lazyVar(lock) {
declarationStorage.enterScope(this)
fir.valueParameters.mapIndexed { index, valueParameter ->
declarationStorage.createIrParameter(

View File

@@ -86,7 +86,7 @@ class Fir2IrLazyProperty(
}
@OptIn(ObsoleteDescriptorBasedAPI::class)
override var backingField: IrField? by lazyVar {
override var backingField: IrField? by lazyVar(lock) {
// TODO: this checks are very preliminary, FIR resolve should determine backing field presence itself
val parent = parent
when {
@@ -126,7 +126,7 @@ class Fir2IrLazyProperty(
}
}
override var getter: IrSimpleFunction? by lazyVar {
override var getter: IrSimpleFunction? by lazyVar(lock) {
if (fir.isConst) return@lazyVar null
Fir2IrLazyPropertyAccessor(
components, startOffset, endOffset,
@@ -155,7 +155,7 @@ class Fir2IrLazyProperty(
}
}
override var setter: IrSimpleFunction? by lazyVar {
override var setter: IrSimpleFunction? by lazyVar(lock) {
if (!fir.isVar) null else Fir2IrLazyPropertyAccessor(
components, startOffset, endOffset,
when {

View File

@@ -45,11 +45,11 @@ class Fir2IrLazyPropertyAccessor(
override val name: Name
get() = Name.special("<${if (isSetter) "set" else "get"}-${firParentProperty.name}>")
override var returnType: IrType by lazyVar {
override var returnType: IrType by lazyVar(lock) {
if (isSetter) irBuiltIns.unitType else firParentProperty.returnTypeRef.toIrType(typeConverter, conversionTypeContext)
}
override var dispatchReceiverParameter: IrValueParameter? by lazyVar {
override var dispatchReceiverParameter: IrValueParameter? by lazyVar(lock) {
val containingClass = parent as? IrClass
if (containingClass != null && shouldHaveDispatchReceiver(containingClass, firParentProperty)
) {
@@ -57,13 +57,13 @@ class Fir2IrLazyPropertyAccessor(
} else null
}
override var extensionReceiverParameter: IrValueParameter? by lazyVar {
override var extensionReceiverParameter: IrValueParameter? by lazyVar(lock) {
firParentProperty.receiverTypeRef?.let {
createThisReceiverParameter(it.toIrType(typeConverter, conversionTypeContext))
}
}
override var valueParameters: List<IrValueParameter> by lazyVar {
override var valueParameters: List<IrValueParameter> by lazyVar(lock) {
if (!isSetter) emptyList()
else {
declarationStorage.enterScope(this)
@@ -81,7 +81,7 @@ class Fir2IrLazyPropertyAccessor(
}
}
override var overriddenSymbols: List<IrSimpleFunctionSymbol> by lazyVar {
override var overriddenSymbols: List<IrSimpleFunctionSymbol> by lazyVar(lock) {
firParentProperty.generateOverriddenAccessorSymbols(
firParentClass,
!isSetter,

View File

@@ -37,24 +37,24 @@ class Fir2IrLazySimpleFunction(
override val name: Name
get() = fir.name
override var returnType: IrType by lazyVar {
override var returnType: IrType by lazyVar(lock) {
fir.returnTypeRef.toIrType(typeConverter)
}
override var dispatchReceiverParameter: IrValueParameter? by lazyVar {
override var dispatchReceiverParameter: IrValueParameter? by lazyVar(lock) {
val containingClass = parent as? IrClass
if (containingClass != null && shouldHaveDispatchReceiver(containingClass, fir)) {
createThisReceiverParameter(thisType = containingClass.thisReceiver?.type ?: error("No this receiver for containing class"))
} else null
}
override var extensionReceiverParameter: IrValueParameter? by lazyVar {
override var extensionReceiverParameter: IrValueParameter? by lazyVar(lock) {
fir.receiverTypeRef?.let {
createThisReceiverParameter(it.toIrType(typeConverter))
}
}
override var valueParameters: List<IrValueParameter> by lazyVar {
override var valueParameters: List<IrValueParameter> by lazyVar(lock) {
declarationStorage.enterScope(this)
fir.valueParameters.mapIndexed { index, valueParameter ->
declarationStorage.createIrParameter(
@@ -67,7 +67,7 @@ class Fir2IrLazySimpleFunction(
}
}
override var overriddenSymbols: List<IrSimpleFunctionSymbol> by lazyVar {
override var overriddenSymbols: List<IrSimpleFunctionSymbol> by lazyVar(lock) {
val parent = parent
if (isFakeOverride && parent is Fir2IrLazyClass) {
fakeOverrideGenerator.calcBaseSymbolsForFakeOverrideFunction(

View File

@@ -5793,6 +5793,12 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/closures/capturedVarsOptimization/kt44347.kt");
}
@Test
@TestMetadata("kt45446.kt")
public void testKt45446() throws Exception {
runTest("compiler/testData/codegen/box/closures/capturedVarsOptimization/kt45446.kt");
}
@Test
@TestMetadata("sharedSlotsWithCapturedVars.kt")
public void testSharedSlotsWithCapturedVars() throws Exception {
@@ -12072,6 +12078,24 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/defaultArguments/inheritedFromInterfaceViaAbstractSuperclass.kt");
}
@Test
@TestMetadata("kt36853.kt")
public void testKt36853() throws Exception {
runTest("compiler/testData/codegen/box/defaultArguments/kt36853.kt");
}
@Test
@TestMetadata("kt36853_nestedObject.kt")
public void testKt36853_nestedObject() throws Exception {
runTest("compiler/testData/codegen/box/defaultArguments/kt36853_nestedObject.kt");
}
@Test
@TestMetadata("kt36853a.kt")
public void testKt36853a() throws Exception {
runTest("compiler/testData/codegen/box/defaultArguments/kt36853a.kt");
}
@Test
@TestMetadata("kt36972_companion.kt")
public void testKt36972_companion() throws Exception {
@@ -12726,6 +12750,12 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/delegatedProperty/insideInlinedObjectMultiModule.kt");
}
@Test
@TestMetadata("javaDelegateTopLevel.kt")
public void testJavaDelegateTopLevel() throws Exception {
runTest("compiler/testData/codegen/box/delegatedProperty/javaDelegateTopLevel.kt");
}
@Test
@TestMetadata("kt35707.kt")
public void testKt35707() throws Exception {
@@ -12744,6 +12774,12 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/delegatedProperty/kt4138.kt");
}
@Test
@TestMetadata("kt45431.kt")
public void testKt45431() throws Exception {
runTest("compiler/testData/codegen/box/delegatedProperty/kt45431.kt");
}
@Test
@TestMetadata("kt6722.kt")
public void testKt6722() throws Exception {
@@ -15612,6 +15648,12 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/functions/max.kt");
}
@Test
@TestMetadata("mutualInline.kt")
public void testMutualInline() throws Exception {
runTest("compiler/testData/codegen/box/functions/mutualInline.kt");
}
@Test
@TestMetadata("nothisnoclosure.kt")
public void testNothisnoclosure() throws Exception {
@@ -17740,6 +17782,12 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/inlineClasses/kt44141.kt");
}
@Test
@TestMetadata("kt44867.kt")
public void testKt44867() throws Exception {
runTest("compiler/testData/codegen/box/inlineClasses/kt44867.kt");
}
@Test
@TestMetadata("mangledDefaultParameterFunction.kt")
public void testMangledDefaultParameterFunction() throws Exception {
@@ -18684,6 +18732,24 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
public void testJavaSam() throws Exception {
runTest("compiler/testData/codegen/box/inlineClasses/funInterface/javaSam.kt");
}
@Test
@TestMetadata("javaSamReturnResult.kt")
public void testJavaSamReturnResult() throws Exception {
runTest("compiler/testData/codegen/box/inlineClasses/funInterface/javaSamReturnResult.kt");
}
@Test
@TestMetadata("returnIC.kt")
public void testReturnIC() throws Exception {
runTest("compiler/testData/codegen/box/inlineClasses/funInterface/returnIC.kt");
}
@Test
@TestMetadata("returnResult.kt")
public void testReturnResult() throws Exception {
runTest("compiler/testData/codegen/box/inlineClasses/funInterface/returnResult.kt");
}
}
@Nested
@@ -19452,6 +19518,12 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/innerNested/createdNestedInOuterMember.kt");
}
@Test
@TestMetadata("extenderNestedClass.kt")
public void testExtenderNestedClass() throws Exception {
runTest("compiler/testData/codegen/box/innerNested/extenderNestedClass.kt");
}
@Test
@TestMetadata("extensionFun.kt")
public void testExtensionFun() throws Exception {
@@ -20432,6 +20504,18 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/invokedynamic/sam/functionRefToJavaInterface/intReturnTypeAsNumber.kt");
}
@Test
@TestMetadata("interfaceMemberRef.kt")
public void testInterfaceMemberRef() throws Exception {
runTest("compiler/testData/codegen/box/invokedynamic/sam/functionRefToJavaInterface/interfaceMemberRef.kt");
}
@Test
@TestMetadata("kt45581.kt")
public void testKt45581() throws Exception {
runTest("compiler/testData/codegen/box/invokedynamic/sam/functionRefToJavaInterface/kt45581.kt");
}
@Test
@TestMetadata("localFunction1.kt")
public void testLocalFunction1() throws Exception {
@@ -23356,6 +23440,12 @@ public class FirBlackBoxCodegenTestGenerated extends AbstractFirBlackBoxCodegenT
runTest("compiler/testData/codegen/box/jvmStatic/kt35716.kt");
}
@Test
@TestMetadata("kt45408.kt")
public void testKt45408() throws Exception {
runTest("compiler/testData/codegen/box/jvmStatic/kt45408.kt");
}
@Test
@TestMetadata("kt9897_static.kt")
public void testKt9897_static() throws Exception {

View File

@@ -809,6 +809,12 @@ public class Fir2IrTextTestGenerated extends AbstractFir2IrTextTest {
runTest("compiler/testData/ir/irText/declarations/provideDelegate/differentReceivers.kt");
}
@Test
@TestMetadata("javaDelegate.kt")
public void testJavaDelegate() throws Exception {
runTest("compiler/testData/ir/irText/declarations/provideDelegate/javaDelegate.kt");
}
@Test
@TestMetadata("local.kt")
public void testLocal() throws Exception {
@@ -2110,6 +2116,12 @@ public class Fir2IrTextTestGenerated extends AbstractFir2IrTextTest {
runTest("compiler/testData/ir/irText/firProblems/AnnotationLoader.kt");
}
@Test
@TestMetadata("ArrayMap.kt")
public void testArrayMap() throws Exception {
runTest("compiler/testData/ir/irText/firProblems/ArrayMap.kt");
}
@Test
@TestMetadata("candidateSymbol.kt")
public void testCandidateSymbol() throws Exception {

View File

@@ -40,8 +40,6 @@ import org.jetbrains.kotlin.fir.lightTree.fir.modifier.TypeProjectionModifier
import org.jetbrains.kotlin.fir.references.builder.buildSimpleNamedReference
import org.jetbrains.kotlin.fir.references.impl.FirReferencePlaceholderForResolvedAnnotations
import org.jetbrains.kotlin.fir.scopes.FirScopeProvider
import org.jetbrains.kotlin.name.CallableId
import org.jetbrains.kotlin.name.LocalCallableIdConstructor
import org.jetbrains.kotlin.fir.symbols.impl.*
import org.jetbrains.kotlin.fir.types.*
import org.jetbrains.kotlin.fir.types.builder.*
@@ -50,10 +48,7 @@ import org.jetbrains.kotlin.fir.types.impl.FirQualifierPartImpl
import org.jetbrains.kotlin.fir.types.impl.FirTypeArgumentListImpl
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens.*
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.name.*
import org.jetbrains.kotlin.utils.addToStdlib.runIf
class DeclarationsConverter(
@@ -408,6 +403,7 @@ class DeclarationsConverter(
isData = modifiers.isDataClass()
isInline = modifiers.isInlineClass()
isFun = modifiers.isFunctionalInterface()
isExternal = modifiers.hasExternal()
}
buildRegularClass {
@@ -1008,11 +1004,19 @@ class DeclarationsConverter(
val propertyVisibility = modifiers.getVisibility()
fun defaultAccessorStatus() =
// Downward propagation of `inline` and `external` modifiers (from property to its accessors)
FirDeclarationStatusImpl(propertyVisibility, modifiers.getModality()).apply {
isInline = modifiers.hasInline()
isExternal = modifiers.hasExternal()
}
val convertedAccessors = accessors.map { convertGetterOrSetter(it, returnType, propertyVisibility, modifiers) }
this.getter = convertedAccessors.find { it.isGetter }
?: FirDefaultPropertyGetter(
null, session, FirDeclarationOrigin.Source, returnType, propertyVisibility
).also {
it.status = defaultAccessorStatus()
currentDispatchReceiverType()?.lookupTag?.let { lookupTag ->
it.containingClassAttr = lookupTag
}
@@ -1023,6 +1027,7 @@ class DeclarationsConverter(
FirDefaultPropertySetter(
null, session, FirDeclarationOrigin.Source, returnType, propertyVisibility
).also {
it.status = defaultAccessorStatus()
currentDispatchReceiverType()?.lookupTag?.let { lookupTag ->
it.containingClassAttr = lookupTag
}

View File

@@ -91,6 +91,11 @@ public class LightTree2FirConverterTestCaseGenerated extends AbstractLightTree2F
runTest("compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/expectActual.kt");
}
@TestMetadata("external.kt")
public void testExternal() throws Exception {
runTest("compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/external.kt");
}
@TestMetadata("F.kt")
public void testF() throws Exception {
runTest("compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/F.kt");
@@ -111,6 +116,11 @@ public class LightTree2FirConverterTestCaseGenerated extends AbstractLightTree2F
runTest("compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/genericProperty.kt");
}
@TestMetadata("initBlockWithDeclarations.kt")
public void testInitBlockWithDeclarations() throws Exception {
runTest("compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/initBlockWithDeclarations.kt");
}
@TestMetadata("nestedClass.kt")
public void testNestedClass() throws Exception {
runTest("compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/nestedClass.kt");

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.builder
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.containingClass
import org.jetbrains.kotlin.fir.containingClassAttr
import org.jetbrains.kotlin.fir.declarations.FirCallableMemberDeclaration
import org.jetbrains.kotlin.fir.declarations.FirDeclaration
import org.jetbrains.kotlin.fir.declarations.FirRegularClass
import org.jetbrains.kotlin.fir.declarations.isInner
import org.jetbrains.kotlin.fir.psi
import org.jetbrains.kotlin.fir.scopes.FirScopeProvider
import org.jetbrains.kotlin.fir.types.FirResolvedTypeRef
import org.jetbrains.kotlin.psi.*
class RawFirFragmentForLazyBodiesBuilder private constructor(
session: FirSession,
baseScopeProvider: FirScopeProvider,
private val declaration: KtDeclaration,
) : RawFirBuilder(session, baseScopeProvider, RawFirBuilderMode.NORMAL) {
companion object {
fun build(
session: FirSession,
baseScopeProvider: FirScopeProvider,
designation: List<FirDeclaration>,
declaration: KtDeclaration,
): FirDeclaration {
require(declaration is KtNamedFunction || declaration is KtProperty) { "Not implemented for ${declaration::class.qualifiedName}" }
val builder = RawFirFragmentForLazyBodiesBuilder(session, baseScopeProvider, declaration)
builder.context.packageFqName = declaration.containingKtFile.packageFqName
return builder.moveNext(designation.iterator())
}
}
private fun moveNext(iterator: Iterator<FirDeclaration>): FirDeclaration {
if (!iterator.hasNext()) {
return if (declaration is KtProperty) {
with(Visitor()) {
declaration.toFirProperty(null)
}
} else {
declaration.accept(Visitor(), Unit) as FirDeclaration
}
}
val parent = iterator.next()
if (parent !is FirRegularClass) return moveNext(iterator)
val classOrObject = parent.psi
check(classOrObject is KtClassOrObject)
withChildClassName(classOrObject.nameAsSafeName, false) {
withCapturedTypeParameters {
if (!parent.isInner) context.capturedTypeParameters = context.capturedTypeParameters.clear()
addCapturedTypeParameters(parent.typeParameters.take(classOrObject.typeParameters.size))
registerSelfType(classOrObject.toDelegatedSelfType(parent))
return moveNext(iterator)
}
}
}
private fun PsiElement?.toDelegatedSelfType(firClass: FirRegularClass): FirResolvedTypeRef =
toDelegatedSelfType(firClass.typeParameters, firClass.symbol)
}

View File

@@ -49,12 +49,25 @@ import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import org.jetbrains.kotlin.utils.addToStdlib.runIf
class RawFirBuilder(
session: FirSession, val baseScopeProvider: FirScopeProvider, val mode: RawFirBuilderMode = RawFirBuilderMode.NORMAL
open class RawFirBuilder(
session: FirSession, val baseScopeProvider: FirScopeProvider, builderMode: RawFirBuilderMode = RawFirBuilderMode.NORMAL
) : BaseFirBuilder<PsiElement>(session) {
private val stubMode get() = mode == RawFirBuilderMode.STUBS
var mode: RawFirBuilderMode = builderMode
private set
private inline fun <T> disabledLazyMode(body: () -> T): T {
if (mode != RawFirBuilderMode.LAZY_BODIES) return body()
return try {
mode = RawFirBuilderMode.NORMAL
body()
} finally {
mode = RawFirBuilderMode.LAZY_BODIES
}
}
fun buildFirFile(file: KtFile): FirFile {
return file.accept(Visitor(), Unit) as FirFile
}
@@ -63,49 +76,6 @@ class RawFirBuilder(
return reference.accept(Visitor(), Unit) as FirTypeRef
}
fun buildFunctionWithBody(function: KtNamedFunction, original: FirFunction<*>?): FirFunction<*> {
return buildDeclaration(function, original) as FirFunction<*>
}
fun buildSecondaryConstructor(secondaryConstructor: KtSecondaryConstructor, original: FirConstructor?): FirConstructor {
return buildDeclaration(secondaryConstructor, original) as FirConstructor
}
fun buildPropertyWithBody(property: KtProperty, original: FirProperty?): FirProperty {
require(!property.isLocal) { "Should not be used to build local properties (variables)" }
return buildDeclaration(property, original) as FirProperty
}
private fun buildDeclaration(declaration: KtDeclaration, original: FirDeclaration?): FirDeclaration {
assert(mode == RawFirBuilderMode.NORMAL) { "Building FIR declarations isn't supported in stub or lazy mode mode" }
setupContextForPosition(declaration,)
val firDeclaration = declaration.accept(Visitor(), Unit) as FirDeclaration
original?.let { firDeclaration.copyContainingClassAttrFrom(it) }
return firDeclaration
}
// TODO this is a (temporary) hack, instead we should properly initialize [context]
private fun FirDeclaration.copyContainingClassAttrFrom(from: FirDeclaration) {
(this as? FirCallableMemberDeclaration<*>)?.let {
it.containingClassAttr = (from as? FirCallableMemberDeclaration<*>)?.containingClass()
}
}
private fun setupContextForPosition(position: KtElement) {
val parentsUpToFile = position.parents
for (parent in parentsUpToFile.toList().asReversed()) {
when (parent) {
is KtFile -> {
context.packageFqName = parent.packageFqName
}
is KtClassOrObject -> {
context.className = context.className.child(parent.nameAsSafeName)
context.localBits.add(parent.isLocal || parent.getStrictParentOfType<KtEnumEntry>() != null)
}
}
}
}
override fun PsiElement.toFirSourceElement(kind: FirFakeSourceElementKind?): FirPsiSourceElement<*> {
val actualKind = kind ?: this@RawFirBuilder.context.forcedElementSourceKind ?: FirRealSourceElementKind
return this.toFirPsiSourceElement(actualKind)
@@ -178,7 +148,7 @@ class RawFirBuilder(
}
}
private inner class Visitor : KtVisitor<FirElement, Unit>() {
protected inner class Visitor : KtVisitor<FirElement, Unit>() {
private inline fun <reified R : FirElement> KtElement?.convertSafe(): R? =
this?.accept(this@Visitor, Unit) as? R
@@ -237,12 +207,14 @@ class RawFirBuilder(
): FirDeclaration {
return when (this) {
is KtSecondaryConstructor -> {
toFirConstructor(
delegatedSuperType,
delegatedSelfType,
owner,
ownerTypeParameters
)
disabledLazyMode {
toFirConstructor(
delegatedSuperType,
delegatedSelfType,
owner,
ownerTypeParameters
)
}
}
is KtEnumEntry -> {
val primaryConstructor = owner.primaryConstructor
@@ -250,7 +222,9 @@ class RawFirBuilder(
primaryConstructor?.valueParameters?.isEmpty() ?: owner.secondaryConstructors.let { constructors ->
constructors.isEmpty() || constructors.any { it.valueParameters.isEmpty() }
}
toFirEnumEntry(delegatedSelfType, ownerClassHasDefaultConstructor)
disabledLazyMode {
toFirEnumEntry(delegatedSelfType, ownerClassHasDefaultConstructor)
}
}
is KtProperty -> {
toFirProperty(ownerClassBuilder)
@@ -548,7 +522,7 @@ class RawFirBuilder(
container.argumentList = argumentList
}
private fun KtClassOrObject.extractSuperTypeListEntriesTo(
fun KtClassOrObject.extractSuperTypeListEntriesTo(
container: FirClassBuilder,
delegatedSelfTypeRef: FirTypeRef?,
delegatedEnumSuperTypeRef: FirTypeRef?,
@@ -790,6 +764,12 @@ class RawFirBuilder(
}
}
override fun visitClassInitializer(initializer: KtClassInitializer, data: Unit?): FirElement {
return disabledLazyMode {
super.visitClassInitializer(initializer, data)
}
}
override fun visitClassOrObject(classOrObject: KtClassOrObject, data: Unit): FirElement {
return withChildClassName(
classOrObject.nameAsSafeName,
@@ -817,6 +797,7 @@ class RawFirBuilder(
isData = classOrObject.hasModifier(DATA_KEYWORD)
isInline = classOrObject.hasModifier(INLINE_KEYWORD)
isFun = classOrObject.hasModifier(FUN_KEYWORD)
isExternal = classOrObject.hasModifier(EXTERNAL_KEYWORD)
}
withCapturedTypeParameters {
if (!status.isInner) context.capturedTypeParameters = context.capturedTypeParameters.clear()
@@ -873,7 +854,8 @@ class RawFirBuilder(
}
if (classOrObject.hasModifier(DATA_KEYWORD) && firPrimaryConstructor != null) {
val zippedParameters = classOrObject.primaryConstructorParameters.filter { it.hasValOrVar() } zip declarations.filterIsInstance<FirProperty>()
val zippedParameters =
classOrObject.primaryConstructorParameters.filter { it.hasValOrVar() } zip declarations.filterIsInstance<FirProperty>()
DataClassMembersGenerator(
baseSession,
classOrObject,
@@ -1214,7 +1196,7 @@ class RawFirBuilder(
}
}
private fun KtProperty.toFirProperty(ownerClassBuilder: FirClassBuilder?): FirProperty {
fun KtProperty.toFirProperty(ownerClassBuilder: FirClassBuilder?): FirProperty {
val propertyType = typeReference.toFirOrImplicitType()
val propertyName = nameAsSafeName
val isVar = isVar

View File

@@ -0,0 +1,10 @@
// FUNCTION: foo
package test.classes
class Outer<X> {
fun foo() {
val z = object { }
}
}

View File

@@ -0,0 +1,9 @@
public? final? fun test/classes/Outer.foo(): R|kotlin/Unit| {
lval <local>/z: <implicit> = object : R|kotlin/Any| {
private constructor(): R|<anonymous><X>| {
super<R|kotlin/Any|>()
}
}
}

View File

@@ -1,4 +1,12 @@
@Target(AnnotationTarget.ANNOTATION_CLASS) annotation class base
@Target(
AnnotationTarget.CLASS,
AnnotationTarget.PROPERTY,
AnnotationTarget.LOCAL_VARIABLE,
AnnotationTarget.VALUE_PARAMETER,
AnnotationTarget.CONSTRUCTOR,
AnnotationTarget.FUNCTION,
AnnotationTarget.TYPE
) annotation class base
@base annotation class derived

View File

@@ -1,5 +1,5 @@
FILE: annotation.kt
@Target(AnnotationTarget#.ANNOTATION_CLASS#) public? final? annotation class base : R|kotlin/Annotation| {
@Target(AnnotationTarget#.CLASS#, AnnotationTarget#.PROPERTY#, AnnotationTarget#.LOCAL_VARIABLE#, AnnotationTarget#.VALUE_PARAMETER#, AnnotationTarget#.CONSTRUCTOR#, AnnotationTarget#.FUNCTION#, AnnotationTarget#.TYPE#) public? final? annotation class base : R|kotlin/Annotation| {
public? constructor(): R|base| {
super<R|kotlin/Any|>()
}

View File

@@ -1,5 +1,5 @@
FILE: annotation.kt
@Target(AnnotationTarget#.ANNOTATION_CLASS#) public? final? annotation class base : R|kotlin/Annotation| {
@Target(AnnotationTarget#.CLASS#, AnnotationTarget#.PROPERTY#, AnnotationTarget#.LOCAL_VARIABLE#, AnnotationTarget#.VALUE_PARAMETER#, AnnotationTarget#.CONSTRUCTOR#, AnnotationTarget#.FUNCTION#, AnnotationTarget#.TYPE#) public? final? annotation class base : R|kotlin/Annotation| {
public? constructor(): R|base| {
super<R|kotlin/Any|>()
}

View File

@@ -30,7 +30,9 @@ FILE: enums.kt
super<R|Planet|>(Double(1.0), Double(2.0))
}
public? open? override fun sayHello(): R|kotlin/Unit| { LAZY_BLOCK }
public? open? override fun sayHello(): R|kotlin/Unit| {
println#(String(Hello!!!))
}
}
@@ -39,7 +41,9 @@ FILE: enums.kt
super<R|Planet|>(Double(3.0), Double(4.0))
}
public? open? override fun sayHello(): R|kotlin/Unit| { LAZY_BLOCK }
public? open? override fun sayHello(): R|kotlin/Unit| {
println#(String(Ola!!!))
}
}
@@ -48,7 +52,9 @@ FILE: enums.kt
super<R|Planet|>(Double(5.0), Double(6.0))
}
public? open? override fun sayHello(): R|kotlin/Unit| { LAZY_BLOCK }
public? open? override fun sayHello(): R|kotlin/Unit| {
println#(String(Privet!!!))
}
}

View File

@@ -26,7 +26,9 @@ FILE: enums2.kt
super<R|SomeEnum|>(O1#)
}
public? open? override fun check(y: Some): Boolean { LAZY_BLOCK }
public? open? override fun check(y: Some): Boolean {
^check Boolean(true)
}
}
@@ -35,7 +37,9 @@ FILE: enums2.kt
super<R|SomeEnum|>(O2#)
}
public? open? override fun check(y: Some): Boolean { LAZY_BLOCK }
public? open? override fun check(y: Some): Boolean {
^check ==(y#, O2#)
}
}

View File

@@ -0,0 +1,16 @@
external class External
external fun foo(): String
external val x: Int
class NotExternal {
external fun bar(): String
var y: Int
external get
set(value) {}
}
var z: Int
external get
external set

View File

@@ -0,0 +1,25 @@
FILE: external.kt
public? final? external class External : R|kotlin/Any| {
public? constructor(): R|External| {
super<R|kotlin/Any|>()
}
}
public? final? external fun foo(): String
public? final? external val x: Int
public? external get(): Int
public? final? class NotExternal : R|kotlin/Any| {
public? constructor(): R|NotExternal| {
super<R|kotlin/Any|>()
}
public? final? external fun bar(): String
public? final? var y: Int
public? external get(): Int
public? set(value: Int): R|kotlin/Unit| { LAZY_BLOCK }
}
public? final? external var z: Int
public? external get(): Int
public? external set(value: Int): R|kotlin/Unit|

View File

@@ -0,0 +1,26 @@
FILE: external.kt
public? final? external class External : R|kotlin/Any| {
public? constructor(): R|External| {
super<R|kotlin/Any|>()
}
}
public? final? external fun foo(): String
public? final? external val x: Int
public? external get(): Int
public? final? class NotExternal : R|kotlin/Any| {
public? constructor(): R|NotExternal| {
super<R|kotlin/Any|>()
}
public? final? external fun bar(): String
public? final? var y: Int
public? external get(): Int
public? set(value: Int): R|kotlin/Unit| {
}
}
public? final? external var z: Int
public? external get(): Int
public? external set(value: Int): R|kotlin/Unit|

View File

@@ -1,4 +1,4 @@
fun <T> simpleRun(f: (T) -> Unit): Unit = f()
fun <T> simpleRun(f: () -> T): T = f()
fun <T, R> List<T>.simpleMap(f: (T) -> R): R {

View File

@@ -1,4 +1,4 @@
FILE: functionTypes.kt
public? final? fun <T> simpleRun(f: ( (T) -> Unit )): Unit { LAZY_BLOCK }
public? final? fun <T> simpleRun(f: ( () -> T )): T { LAZY_BLOCK }
public? final? fun <T, R> List<T>.simpleMap(f: ( (T) -> R )): R { LAZY_BLOCK }
public? final? fun <T> simpleWith(t: T, f: ( T.() -> Unit )): Unit { LAZY_BLOCK }

View File

@@ -1,5 +1,5 @@
FILE: functionTypes.kt
public? final? fun <T> simpleRun(f: ( (T) -> Unit )): Unit {
public? final? fun <T> simpleRun(f: ( () -> T )): T {
^simpleRun f#()
}
public? final? fun <T, R> List<T>.simpleMap(f: ( (T) -> R )): R {

View File

@@ -0,0 +1,22 @@
class X {
init {
class classInInit {
fun funInClassInInit() {
}
}
fun funInInit() {
}
}
}
object {
init {
class classInInit {
fun funInClassInInit() {
}
}
fun funInInit() {
}
}
}

View File

@@ -0,0 +1,45 @@
FILE: initBlockWithDeclarations.kt
public? final? class X : R|kotlin/Any| {
public? constructor(): R|X| {
super<R|kotlin/Any|>()
}
init {
local final? class classInInit : R|kotlin/Any| {
public? constructor(): R|X.classInInit| {
super<R|kotlin/Any|>()
}
public? final? fun funInClassInInit(): R|kotlin/Unit| {
}
}
local final? fun funInInit(): R|kotlin/Unit| {
}
}
}
public? final? object <no name provided> : R|kotlin/Any| {
private constructor(): R|<no name provided>| {
super<R|kotlin/Any|>()
}
init {
local final? class classInInit : R|kotlin/Any| {
public? constructor(): R|<no name provided>.classInInit| {
super<R|kotlin/Any|>()
}
public? final? fun funInClassInInit(): R|kotlin/Unit| {
}
}
local final? fun funInInit(): R|kotlin/Unit| {
}
}
}

View File

@@ -0,0 +1,45 @@
FILE: initBlockWithDeclarations.kt
public? final? class X : R|kotlin/Any| {
public? constructor(): R|X| {
super<R|kotlin/Any|>()
}
init {
local final? class classInInit : R|kotlin/Any| {
public? constructor(): R|X.classInInit| {
super<R|kotlin/Any|>()
}
public? final? fun funInClassInInit(): R|kotlin/Unit| {
}
}
local final? fun funInInit(): R|kotlin/Unit| {
}
}
}
public? final? object <no name provided> : R|kotlin/Any| {
private constructor(): R|<no name provided>| {
super<R|kotlin/Any|>()
}
init {
local final? class classInInit : R|kotlin/Any| {
public? constructor(): R|<no name provided>.classInInit| {
super<R|kotlin/Any|>()
}
public? final? fun funInClassInInit(): R|kotlin/Unit| {
}
}
local final? fun funInInit(): R|kotlin/Unit| {
}
}
}

View File

@@ -3,7 +3,10 @@ FILE: noPrimaryConstructor.kt
public? final? val x: String
public? get(): String
public? constructor(x: String): R|NoPrimary| { LAZY_BLOCK }
public? constructor(x: String): R|NoPrimary| {
super<R|kotlin/Any|>()
this#.x# = x#
}
public? constructor(): R|NoPrimary| {
this<R|NoPrimary|>(String())

View File

@@ -1,4 +1,4 @@
@Target(AnnotationTarget.EXPRESSION)
@Target(AnnotationTarget.EXPRESSION, AnnotationTarget.LOCAL_VARIABLE)
@Retention(AnnotationRetention.SOURCE)
annotation class Ann
@@ -12,7 +12,7 @@ fun foo(arg: Int): Int {
return 42
}
data class Two(x: Int, y: Int)
data class Two(val x: Int, val y: Int)
fun bar(two: Two) {
val (@Ann x, @Ann y) = two

View File

@@ -1,5 +1,5 @@
FILE: annotated.kt
@Target(AnnotationTarget#.EXPRESSION#) @Retention(AnnotationRetention#.SOURCE#) public? final? annotation class Ann : R|kotlin/Annotation| {
@Target(AnnotationTarget#.EXPRESSION#, AnnotationTarget#.LOCAL_VARIABLE#) @Retention(AnnotationRetention#.SOURCE#) public? final? annotation class Ann : R|kotlin/Annotation| {
public? constructor(): R|Ann| {
super<R|kotlin/Any|>()
}
@@ -11,7 +11,17 @@ FILE: annotated.kt
super<R|kotlin/Any|>()
}
public final fun copy(): R|Two|
public? final? val x: Int = R|<local>/x|
public? get(): Int
public? final? val y: Int = R|<local>/y|
public? get(): Int
public final operator fun component1(): Int
public final operator fun component2(): Int
public final fun copy(x: Int = this@R|/Two|.R|/Two.x|, y: Int = this@R|/Two|.R|/Two.y|): R|Two|
}
public? final? fun bar(two: Two): R|kotlin/Unit| { LAZY_BLOCK }

View File

@@ -1,5 +1,5 @@
FILE: annotated.kt
@Target(AnnotationTarget#.EXPRESSION#) @Retention(AnnotationRetention#.SOURCE#) public? final? annotation class Ann : R|kotlin/Annotation| {
@Target(AnnotationTarget#.EXPRESSION#, AnnotationTarget#.LOCAL_VARIABLE#) @Retention(AnnotationRetention#.SOURCE#) public? final? annotation class Ann : R|kotlin/Annotation| {
public? constructor(): R|Ann| {
super<R|kotlin/Any|>()
}
@@ -25,7 +25,17 @@ FILE: annotated.kt
super<R|kotlin/Any|>()
}
public final fun copy(): R|Two|
public? final? val x: Int = R|<local>/x|
public? get(): Int
public? final? val y: Int = R|<local>/y|
public? get(): Int
public final operator fun component1(): Int
public final operator fun component2(): Int
public final fun copy(x: Int = this@R|/Two|.R|/Two.x|, y: Int = this@R|/Two|.R|/Two.y|): R|Two|
}
public? final? fun bar(two: Two): R|kotlin/Unit| {

View File

@@ -1,9 +1,9 @@
// WITH_RUNTIME
infix fun distance(x: Int, y: Int) = x + y
infix fun Int.distance(y: Int) = this + y
fun test(): Int = 3 distance 4
fun testRegular(): Int = distance(3, 4)
fun testRegular(): Int = 3.distance(4)
class My(var x: Int) {
operator fun invoke() = x

View File

@@ -1,5 +1,5 @@
FILE: calls.kt
public? final? infix fun distance(x: Int, y: Int): <implicit> { LAZY_BLOCK }
public? final? infix fun Int.distance(y: Int): <implicit> { LAZY_BLOCK }
public? final? fun test(): Int { LAZY_BLOCK }
public? final? fun testRegular(): Int { LAZY_BLOCK }
public? final? class My : R|kotlin/Any| {

View File

@@ -1,12 +1,12 @@
FILE: calls.kt
public? final? infix fun distance(x: Int, y: Int): <implicit> {
^distance x#.plus#(y#)
public? final? infix fun Int.distance(y: Int): <implicit> {
^distance this#.plus#(y#)
}
public? final? fun test(): Int {
^test IntegerLiteral(3).distance#(IntegerLiteral(4))
}
public? final? fun testRegular(): Int {
^testRegular distance#(IntegerLiteral(3), IntegerLiteral(4))
^testRegular IntegerLiteral(3).distance#(IntegerLiteral(4))
}
public? final? class My : R|kotlin/Any| {
public? constructor(x: Int): R|My| {

View File

@@ -6,7 +6,7 @@ fun withLocals(p: Int): Int {
val x = Local(42).diff()
fun sum(y: Int, z: Int, f: (Int, Int) -> Int): Int {
return x + f(y + z)
return x + f(y, z)
}
val code = (object : Any() {

View File

@@ -16,7 +16,7 @@ FILE: locals.kt
lval x: <implicit> = Local#(IntegerLiteral(42)).diff#()
local final? fun sum(y: Int, z: Int, f: ( (Int, Int) -> Int )): Int {
^sum x#.plus#(f#(y#.plus#(z#)))
^sum x#.plus#(f#(y#, z#))
}
lval code: <implicit> = object : Any {

View File

@@ -44,6 +44,11 @@ public class PartialRawFirBuilderTestCaseGenerated extends AbstractPartialRawFir
runTest("compiler/fir/raw-fir/psi2fir/testData/partialRawBuilder/memberProperty.kt");
}
@TestMetadata("paramemtersCatching.kt")
public void testParamemtersCatching() throws Exception {
runTest("compiler/fir/raw-fir/psi2fir/testData/partialRawBuilder/paramemtersCatching.kt");
}
@TestMetadata("simpleFunction.kt")
public void testSimpleFunction() throws Exception {
runTest("compiler/fir/raw-fir/psi2fir/testData/partialRawBuilder/simpleFunction.kt");

View File

@@ -91,6 +91,11 @@ public class RawFirBuilderLazyBodiesTestCaseGenerated extends AbstractRawFirBuil
runTest("compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/expectActual.kt");
}
@TestMetadata("external.kt")
public void testExternal() throws Exception {
runTest("compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/external.kt");
}
@TestMetadata("F.kt")
public void testF() throws Exception {
runTest("compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/F.kt");
@@ -111,6 +116,11 @@ public class RawFirBuilderLazyBodiesTestCaseGenerated extends AbstractRawFirBuil
runTest("compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/genericProperty.kt");
}
@TestMetadata("initBlockWithDeclarations.kt")
public void testInitBlockWithDeclarations() throws Exception {
runTest("compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/initBlockWithDeclarations.kt");
}
@TestMetadata("nestedClass.kt")
public void testNestedClass() throws Exception {
runTest("compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/nestedClass.kt");

View File

@@ -91,6 +91,11 @@ public class RawFirBuilderTestCaseGenerated extends AbstractRawFirBuilderTestCas
runTest("compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/expectActual.kt");
}
@TestMetadata("external.kt")
public void testExternal() throws Exception {
runTest("compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/external.kt");
}
@TestMetadata("F.kt")
public void testF() throws Exception {
runTest("compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/F.kt");
@@ -111,6 +116,11 @@ public class RawFirBuilderTestCaseGenerated extends AbstractRawFirBuilderTestCas
runTest("compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/genericProperty.kt");
}
@TestMetadata("initBlockWithDeclarations.kt")
public void testInitBlockWithDeclarations() throws Exception {
runTest("compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/initBlockWithDeclarations.kt");
}
@TestMetadata("nestedClass.kt")
public void testNestedClass() throws Exception {
runTest("compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/nestedClass.kt");

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