From c1464c7cbc6e20229861dbf5918571ff2233d060 Mon Sep 17 00:00:00 2001 From: Juan Pedro Moreno <4879373+juanpedromoreno@users.noreply.github.com> Date: Wed, 18 Sep 2019 10:27:27 +0200 Subject: [PATCH] Merges arrow-meta-prototype (#1606) * first commit * First sample * Add resources to README.MD * Sample check for purity that illustrate the ClassBuilder phase * Update README.md * Update README.md * added intro info's about IR * removed unness. parts in IR * removed unness. parts in IR * added further resources on IR * walk function subexpressions and check for purity * fix compiler addition * WIP * finding all callable expressions and type checking them against purity * Add Jetpack Compose to list of plugin examples * Update README.md * Add note on Google having forked Kotlin and not having public sources * evaluating order of compiler phases based and extensions delegation * Add extensions invocation order * Meta DSL progress * Subscribing to newMethod, newField and newAnnotation on class builder generation * Update README.md * more progress * remove .DS_STORE from git * progress checkpoint * progress checkpoint * progress checkpoint * progress checkpoint * Mutate the compiler context with main services discovered in earlier analysis phase * moar progress * small cleanup before sharing with JB * clean up * clean up * Clean up * Clean up * toward automatic type alias generation * automatic type alias generation * update kotlin version and more progress attempting to intercept calls and type resolution * get a sample of gradle and idea plugin compiling * minor improvements and fixes * BOOM! implicit kinded conversions work! * clean up * clean up * merge Adrians work * Finding datatype, type class and instance based on @extension * progress prototyping type class resolution * Port of the most interesting parts of KEEP 87 over to the compiler plugin * enable the ExtensionResolutionCallChecker * Progress on the callchecker resolution * reflection utilities to intercept compiler services * Functions can now resolve `@with` arguments in their lexical scope * Suppress `NO_VALUE_FOR_PARAMETER` when an extension is properly resolved. * Ability to suppress any diagnostic given a CallCheckerContext ```kotlin fun CallCheckerContext.suppressDiagnostic(f: (Diagnostic) -> Boolean): Unit ``` * approach to match and unapply tree based on code snippets * quasiquote DSL progress * intercepting class generation with quotes, only matching on name for now * Initial Draft of the Higher Kind plugin based on quotes * Added modality in visibility * remove bogus import * move trim margins up to processing * support for kinds of N arity up to 22 * rename type parameters identifier * class matching DSL cleanup and simplification of the model for codegen * injection prototype working with type class package instances * auto insert with scopes * Support for `fun`, `val`, `object` and `class` providers of type class extensions * utils clean up * findExtension cleanup * IR transformations as meta functions * IR transformations as meta functions * Error reporting for ambiguous extensions * `with` injection supported in class members * clean up and more todos * support for internal orphan extensions * progress with comprehensions rewrites * progress with comprehensions rewrites * extracting flatMap calls from bindings presence * binding comprehensions as tree rewrites, working but lacking type checking * failing comprehensions rewrite example due to binding variables and order * failing comprehensions rewrite example due to binding variables and order * clean up * clean up * First steps into Idea support (#21) * some tries * gradle is the right one * revert to regular jar * init * init * autofold plugin with innerSealedSubclass * stash invest. * improvements in autofold * formating cleanUp * fix gradle plugin * merged with rr-typeclass * cleanUp * working HKplugin & Autofold init * safe * Move to kotlin-compiler package This change updates the compiler plugin to use the unshaded `kotlin-compiler` package instead of the `kotlin-compiler-embeddable` package, as to prevent it from clashing in IntelliJ. * added autofold plugin * working runIde task * added report message * added license and fixed comments * cleanUp * Revert "First steps into Idea support (#21)" (#23) This reverts commit 83ca62586ebd35f9d126b40984e69e40ca762b0e. * clean Up (#26) * fix type class resolution and plugin publishing, still need to autoinject compiler free args * gradle plugin jar cleanUp & fix (#27) * . * 1 try * further fix * further fix * progress with IDEA discovery shadowing and running the plugin in IDEA. Analysys not yet working * synth resolution progress * synth resolution progress on file save * synthetic methods and names working! * more synthetic resolver methods * getSyntheticNestedClassNames * synthetic package fragment provider * automatic synth resolution working based on local build output * progress on type class resolution on the IDE * IDE body resolution accounting type class injected symbols * Initialize IDE component registration earlier * Merge master and some debug output for next iteration * package organization * package organization (:compiler-plugin) * remove core and consumer modules * idea reorg * Update README.md * Moving arrow-meta-prototype into its own subdirectory * Moves arrow-meta-prototype into the proper subdirectory --- modules/meta/arrow-meta-prototype/.gitignore | 134 ++++ modules/meta/arrow-meta-prototype/README.md | 7 + .../meta/arrow-meta-prototype/build.gradle | 21 + .../compiler-plugin/build.gradle | 132 ++++ .../kotlin/arrow/meta/MetaCliProcessor.kt | 13 + .../arrow/meta/MetaCommandLineProcessor.kt | 12 + .../arrow/meta/MetaComponentRegistrar.kt | 18 + .../src/main/kotlin/arrow/meta/MetaPlugin.kt | 11 + .../kotlin/arrow/meta/dsl/MetaPluginSyntax.kt | 14 + .../arrow/meta/dsl/analysis/AnalysisSyntax.kt | 77 ++ .../arrow/meta/dsl/codegen/CodegenSyntax.kt | 6 + .../arrow/meta/dsl/codegen/asm/AsmSyntax.kt | 34 + .../arrow/meta/dsl/codegen/ir/IrSyntax.kt | 692 ++++++++++++++++++ .../arrow/meta/dsl/config/ConfigSyntax.kt | 48 ++ .../arrow/meta/dsl/platform/Platform.kt | 13 + .../arrow/meta/dsl/resolve/ResolveSyntax.kt | 203 +++++ .../main/kotlin/arrow/meta/internal/Noop.kt | 22 + .../internal/registry/InternalRegistry.kt | 618 ++++++++++++++++ .../arrow/meta/phases/CompilerContext.kt | 34 + .../kotlin/arrow/meta/phases/Composite.kt | 8 + .../kotlin/arrow/meta/phases/Extension.kt | 6 + .../meta/phases/analysis/AnalysisHandler.kt | 29 + .../analysis/CollectAdditionalSources.kt | 15 + .../meta/phases/analysis/ExtraImports.kt | 10 + .../arrow/meta/phases/analysis/KtUtils.kt | 55 ++ .../meta/phases/analysis/MetaAnalyzer.kt | 56 ++ .../phases/analysis/MetaFileViewProvider.kt | 14 + .../PreprocessedVirtualFileFactory.kt | 12 + .../meta/phases/codegen/asm/ClassBuilder.kt | 15 + .../arrow/meta/phases/codegen/asm/Codegen.kt | 24 + .../meta/phases/codegen/ir/IRGeneration.kt | 17 + .../arrow/meta/phases/codegen/ir/IrUtils.kt | 136 ++++ .../kotlin/arrow/meta/phases/config/Config.kt | 9 + .../config/StorageComponentContainer.kt | 21 + .../resolve/DeclarationAttributeAlterer.kt | 19 + .../meta/phases/resolve/PackageProvider.kt | 22 + .../diagnostics/DiagnosticsSuppressor.kt | 9 + .../resolve/synthetics/SyntheticResolver.kt | 60 ++ .../synthetics/SyntheticScopeProvider.kt | 23 + .../comprehensions/ComprehensionsPlugin.kt | 57 ++ .../arrow/meta/plugins/dummy/DummyPlugin.kt | 37 + .../plugins/higherkind/HigherKindPlugin.kt | 77 ++ .../higherkind/KindAwareTypeChecker.kt | 41 ++ .../plugins/typeclasses/TypeClassesPlugin.kt | 297 ++++++++ .../kotlin/arrow/meta/quotes/ClassOrObject.kt | 62 ++ .../src/main/kotlin/arrow/meta/quotes/Func.kt | 68 ++ .../arrow/meta/quotes/MetaTreeVisitor.kt | 5 + .../arrow/meta/quotes/QuasiQuoteContext.kt | 18 + .../main/kotlin/arrow/meta/quotes/Quote.kt | 622 ++++++++++++++++ .../arrow/meta/quotes/QuoteTransformation.kt | 11 + ...otlin.compiler.plugin.CommandLineProcessor | 1 + ....kotlin.compiler.plugin.ComponentRegistrar | 1 + .../gradle-plugin/build.gradle | 69 ++ .../meta/plugin/gradle/ArrowExtension.kt | 29 + .../gradle/ArrowKotlinGradleSubplugin.kt | 37 + .../meta/plugin/gradle/ArrowSubplugin.kt | 23 + ...kotlin.gradle.plugin.KotlinGradleSubplugin | 1 + .../gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 52928 bytes .../gradle/wrapper/gradle-wrapper.properties | 6 + modules/meta/arrow-meta-prototype/gradlew | 169 +++++ modules/meta/arrow-meta-prototype/gradlew.bat | 84 +++ .../idea-plugin/build.gradle | 39 + .../kotlin/arrow/meta/dsl/ide/IdeSyntax.kt | 6 + .../meta/dsl/ide/feature1/Feature1Syntax.kt | 5 + .../arrow/meta/plugin/idea/IdeMetaPlugin.kt | 6 + .../idea/gradle/ArrowGradleImportHandler.kt | 23 + .../idea/gradle/MetaClasspathContributor.kt | 73 ++ .../internal/registry/IdeInternalRegistry.kt | 24 + .../idea/phases/analysis/MetaIdeAnalyzer.kt | 336 +++++++++ .../analysis/SyntheticDescriptorCache.kt | 69 ++ .../meta/plugin/idea/phases/config/utils.kt | 20 + .../phases/resolve/MetaRecursiveVisitor.kt | 128 ++++ .../MetaSyntheticPackageFragmentProvider.kt | 217 ++++++ .../src/main/resources/META-INF/plugin.xml | 26 + .../meta/arrow-meta-prototype/settings.gradle | 3 + 75 files changed, 5359 insertions(+) create mode 100644 modules/meta/arrow-meta-prototype/.gitignore create mode 100644 modules/meta/arrow-meta-prototype/README.md create mode 100644 modules/meta/arrow-meta-prototype/build.gradle create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/build.gradle create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/MetaCliProcessor.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/MetaCommandLineProcessor.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/MetaComponentRegistrar.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/MetaPlugin.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/MetaPluginSyntax.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/analysis/AnalysisSyntax.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/codegen/CodegenSyntax.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/codegen/asm/AsmSyntax.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/codegen/ir/IrSyntax.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/config/ConfigSyntax.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/platform/Platform.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/resolve/ResolveSyntax.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/internal/Noop.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/internal/registry/InternalRegistry.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/CompilerContext.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/Composite.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/Extension.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/AnalysisHandler.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/CollectAdditionalSources.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/ExtraImports.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/KtUtils.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/MetaAnalyzer.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/MetaFileViewProvider.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/PreprocessedVirtualFileFactory.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/codegen/asm/ClassBuilder.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/codegen/asm/Codegen.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/codegen/ir/IRGeneration.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/codegen/ir/IrUtils.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/config/Config.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/config/StorageComponentContainer.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/resolve/DeclarationAttributeAlterer.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/resolve/PackageProvider.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/resolve/diagnostics/DiagnosticsSuppressor.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/resolve/synthetics/SyntheticResolver.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/resolve/synthetics/SyntheticScopeProvider.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/plugins/comprehensions/ComprehensionsPlugin.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/plugins/dummy/DummyPlugin.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/plugins/higherkind/HigherKindPlugin.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/plugins/higherkind/KindAwareTypeChecker.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/plugins/typeclasses/TypeClassesPlugin.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/ClassOrObject.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/Func.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/MetaTreeVisitor.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/QuasiQuoteContext.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/Quote.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/QuoteTransformation.kt create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor create mode 100644 modules/meta/arrow-meta-prototype/compiler-plugin/src/main/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.ComponentRegistrar create mode 100644 modules/meta/arrow-meta-prototype/gradle-plugin/build.gradle create mode 100644 modules/meta/arrow-meta-prototype/gradle-plugin/src/main/kotlin/arrow/meta/plugin/gradle/ArrowExtension.kt create mode 100644 modules/meta/arrow-meta-prototype/gradle-plugin/src/main/kotlin/arrow/meta/plugin/gradle/ArrowKotlinGradleSubplugin.kt create mode 100644 modules/meta/arrow-meta-prototype/gradle-plugin/src/main/kotlin/arrow/meta/plugin/gradle/ArrowSubplugin.kt create mode 100644 modules/meta/arrow-meta-prototype/gradle-plugin/src/main/resources/META-INF/services/org.jetbrains.kotlin.gradle.plugin.KotlinGradleSubplugin create mode 100644 modules/meta/arrow-meta-prototype/gradle/wrapper/gradle-wrapper.jar create mode 100644 modules/meta/arrow-meta-prototype/gradle/wrapper/gradle-wrapper.properties create mode 100755 modules/meta/arrow-meta-prototype/gradlew create mode 100644 modules/meta/arrow-meta-prototype/gradlew.bat create mode 100644 modules/meta/arrow-meta-prototype/idea-plugin/build.gradle create mode 100644 modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/dsl/ide/IdeSyntax.kt create mode 100644 modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/dsl/ide/feature1/Feature1Syntax.kt create mode 100644 modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/IdeMetaPlugin.kt create mode 100644 modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/gradle/ArrowGradleImportHandler.kt create mode 100644 modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/gradle/MetaClasspathContributor.kt create mode 100644 modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/internal/registry/IdeInternalRegistry.kt create mode 100644 modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/phases/analysis/MetaIdeAnalyzer.kt create mode 100644 modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/phases/analysis/SyntheticDescriptorCache.kt create mode 100644 modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/phases/config/utils.kt create mode 100644 modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/phases/resolve/MetaRecursiveVisitor.kt create mode 100644 modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/phases/resolve/MetaSyntheticPackageFragmentProvider.kt create mode 100644 modules/meta/arrow-meta-prototype/idea-plugin/src/main/resources/META-INF/plugin.xml create mode 100644 modules/meta/arrow-meta-prototype/settings.gradle diff --git a/modules/meta/arrow-meta-prototype/.gitignore b/modules/meta/arrow-meta-prototype/.gitignore new file mode 100644 index 00000000000..c7939211edb --- /dev/null +++ b/modules/meta/arrow-meta-prototype/.gitignore @@ -0,0 +1,134 @@ +# Created by https://www.gitignore.io/api/android,intellij + +### Android ### +# Built application files +*.apk +*.ap_ + +# Files for the ART/Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ + +# Gradle files +.gradle/ +build/ + +# dokka + ank apidocs merge to sources +apidocs/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# Intellij +*.iml +.idea/workspace.xml +.idea/tasks.xml +.idea/gradle.xml +.idea/libraries +.idea/markdown-navigator +.idea/ + +# Keystore files +*.jks + +# External native build folder generated in Android Studio 2.2 and later +.externalNativeBuild + +# Google Services (e.g. APIs or Firebase) +google-services.json + +# Freeline +freeline.py +freeline/ +freeline_project_description.json + +### Android Patch ### +gen-external-apklibs + +### Intellij ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: +.idea/**/workspace.xml +.idea/**/tasks.xml + +# Sensitive or high-churn files: +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.xml +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml + +# Gradle: +.idea/**/gradle.xml +.idea/**/libraries + +# Mongo Explorer plugin: +.idea/**/mongoSettings.xml + +## File-based project format: +*.iws + +## Plugin-specific files: + +# IntelliJ +/out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Jekyll +_site +.sass-cache + +### Intellij Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +###################### + +reports/ + +# End of https://www.gitignore.io/api/android,intellij +/.idea/misc.xml + +.DS_Store + +target/ + +.bash_profile \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/README.md b/modules/meta/arrow-meta-prototype/README.md new file mode 100644 index 00000000000..9c2186b2df4 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/README.md @@ -0,0 +1,7 @@ +# arrow-meta-prototype + +**Build and run in the IDE** + +``` +./gradlew clean gradle-plugin:publishArrowPluginMarkerMavenPublicationToMavenLocal gradle-plugin:publishPluginMavenPublicationToMavenLocal idea-plugin:runIde -Dorg.gradle.debug=true -Dkotlin.compiler.execution.strategy="in-process" +``` diff --git a/modules/meta/arrow-meta-prototype/build.gradle b/modules/meta/arrow-meta-prototype/build.gradle new file mode 100644 index 00000000000..c046b3af3ef --- /dev/null +++ b/modules/meta/arrow-meta-prototype/build.gradle @@ -0,0 +1,21 @@ +buildscript { + ext.kotlin_version = '1.3.50' + + repositories { + mavenCentral() + } +} + +plugins { + id 'org.jetbrains.kotlin.jvm' version '1.3.50' + id 'org.jetbrains.kotlin.kapt' version '1.3.50' + id 'com.github.johnrengelman.shadow' version '5.0.0' +} + +allprojects { + repositories { + maven { url "https://kotlin.bintray.com/kotlinx" } + mavenCentral() + jcenter() + } +} diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/build.gradle b/modules/meta/arrow-meta-prototype/compiler-plugin/build.gradle new file mode 100644 index 00000000000..93df49b9f27 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/build.gradle @@ -0,0 +1,132 @@ +apply plugin: 'kotlin' +apply plugin: 'kotlin-kapt' +apply plugin: 'com.github.johnrengelman.shadow' + + +//compileKotlin.kotlinOptions.freeCompilerArgs = ['-Xskip-runtime-version-check', 'true'] + +dependencies { + compileOnly "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + compileOnly "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + compileOnly "org.jetbrains.kotlin:kotlin-compiler-embeddable:$kotlin_version" + compileOnly "com.intellij:openapi:7.0.3" +} + +compileKotlin { + kotlinOptions.jvmTarget = "1.8" +} +compileTestKotlin { + kotlinOptions.jvmTarget = "1.8" +} +jar { + manifest { + attributes["Specification-Title"] = project.name + attributes["Specification-Version"] = project.version + attributes["Implementation-Title"] = "arrow.meta.plugin.compiler" + attributes["Implementation-Version"] = project.version + } +} + +shadowJar { + configurations = [project.configurations.compile] + relocate 'org.jetbrains.kotlin.com.intellij', 'com.intellij' + //relocate 'org.jetbrains.kotlin.load', 'kotlin.reflect.jvm.internal.impl.load' +} +// +//com.intellij.findUsagesHandlerFactory +//org.jetbrains.kotlin.scriptDefinitionsProvider +//com.intellij.runConfigurationTemplateProvider +//com.intellij.compiler.task +//org.jetbrains.kotlin.syntheticResolveExtension +//com.intellij.handleTypeFactory +//org.jetbrains.kotlin.expressionCodegenExtension +//org.jetbrains.kotlin.gradleProjectImportHandler +//com.intellij.projectExtension +//com.intellij.java.elementFinder +//org.jetbrains.kotlin.extraImportsProviderExtension +//com.intellij.compilerFactory +//com.intellij.fileContextProvider +//com.intellij.vcs +//org.jetbrains.kotlin.scriptDefinitionContributor +//com.intellij.prePushHandler +//com.intellij.projectViewNodeDecorator +//org.jetbrains.kotlin.classBuilderFactoryInterceptorExtension +//org.jetbrains.kotlin.scriptAdditionalIdeaDependenciesProvider +//org.jetbrains.kotlin.irGenerationExtension +//com.intellij.nonProjectFileWritingAccessExtension +//org.jetbrains.kotlin.jsSyntheticTranslateExtension +//com.intellij.changesViewContent +//com.intellij.vcsRepositoryCreator +//com.intellij.highlightErrorFilter +//com.intellij.projectViewPane +//com.intellij.hectorComponentProvider +//com.intellij.cachedValuesFactory +//com.intellij.vcs.baseContentProvider +//com.intellij.analyzeStacktraceFilter +//org.jetbrains.kotlin.mavenProjectImportHandler +//com.intellij.stepsBeforeRunProvider +//com.intellij.previewPanelProvider +//com.intellij.vcsIgnoreChecker +//com.intellij.checkinHandlerFactory +//com.intellij.compiler.inspectionValidator +//com.intellij.java-i18n.resourceBundleManager +//com.intellij.openapi.extensions.epAvailabilityListener +//com.intellij.editorNotificationProvider +//com.intellij.ignoredFileContentProvider +//com.intellij.highlightVisitor +//org.jetbrains.kotlin.androidDexer +//com.intellij.java.shortNamesCache +//com.intellij.logHighlighterFactory +//com.intellij.vcs.ignoredFilesHolder +//com.intellij.debugger.positionManagerFactory +//com.intellij.paletteItemProvider +//com.intellij.jvm.elementProvider +//com.intellij.favoriteNodeProvider +//org.jetbrains.android.uipreview.viewLoaderExtension +//org.jetbrains.kotlin.declarationAttributeAltererExtension +//com.intellij.vcs.taskHandler +//com.intellij.ideRootPaneNorth +//com.intellij.writingAccessProvider +//com.intellij.logProvider +//com.intellij.scopeTreeExpander +//com.intellij.coverageOptions +//com.intellij.lang.inferredAnnotationProvider +//com.intellij.java.compiler +//com.intellij.directoryIndexExcludePolicy +//org.jetbrains.kotlin.packageFragmentProviderExtension +//com.intellij.runConfigurationsSettings +//com.intellij.selectInTarget +//com.intellij.customScopesProvider +//org.jetbrains.kotlin.scriptTemplatesProvider +//com.intellij.fileBreadcrumbsCollector +//com.intellij.vcs.fileStatusProvider +//com.intellij.vcs.changes.changesViewModifier +//com.intellij.customFileDropHandler +//org.jetbrains.kotlin.kotlinIndicesHelperExtension +//com.intellij.javadocTagInfo +//com.intellij.problemFileHighlightFilter +//com.intellij.patch.extension +//com.intellij.streamProviderFactory +//com.intellij.multiHostInjector +//com.intellij.treeStructureProvider +//com.intellij.projectModelModifier +//com.intellij.psi.treeChangePreprocessor +//com.intellij.projectUndoProvider +//com.intellij.cherryPicker +//com.intellij.compiler +//com.intellij.autoImportOptionsProvider +//com.intellij.buildProcess.parametersProvider +//com.intellij.editChangelistSupport +//com.intellij.favoritesListProvider +//com.intellij.pushSupport +//com.intellij.roots.watchedRootsProvider +//com.intellij.compilerSettingsFactory +//org.jetbrains.kotlin.simpleNameReferenceExtension +//com.intellij.vcsChangesViewRefresher +//com.intellij.vcs.branchStateProvider +//org.jetbrains.kotlin.storageComponentContainerContributor +//com.intellij.refactoring.elementListenerProvider +//com.intellij.usageContextPanelProvider +//com.intellij.projectConfigurable +//org.jetbrains.kotlin.syntheticScopeProviderExtension +//com.android.project.projectsystem \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/MetaCliProcessor.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/MetaCliProcessor.kt new file mode 100644 index 00000000000..758379af79b --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/MetaCliProcessor.kt @@ -0,0 +1,13 @@ +package arrow.meta + +import org.jetbrains.kotlin.compiler.plugin.CliOption +import org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor + +//@AutoService(CommandLineProcessor::class) +class MetaCliProcessor : CommandLineProcessor { + + override val pluginId: String = "arrow.meta.plugin.compiler" + + override val pluginOptions: Collection = emptyList() + +} diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/MetaCommandLineProcessor.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/MetaCommandLineProcessor.kt new file mode 100644 index 00000000000..908ac8518f3 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/MetaCommandLineProcessor.kt @@ -0,0 +1,12 @@ +package arrow.meta + +import org.jetbrains.kotlin.compiler.plugin.CliOption +import org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor + +class MetaCommandLineProcessor : CommandLineProcessor { + + override val pluginId: String = "arrow.meta.plugin.compiler" + + override val pluginOptions: Collection = emptyList() + +} diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/MetaComponentRegistrar.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/MetaComponentRegistrar.kt new file mode 100644 index 00000000000..f722b546d4f --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/MetaComponentRegistrar.kt @@ -0,0 +1,18 @@ +package arrow.meta + +import arrow.meta.dsl.MetaPluginSyntax +import arrow.meta.internal.registry.InternalRegistry +import arrow.meta.phases.ExtensionPhase +import org.jetbrains.kotlin.com.intellij.mock.MockProject +import org.jetbrains.kotlin.compiler.plugin.ComponentRegistrar +import org.jetbrains.kotlin.config.CompilerConfiguration +import org.jetbrains.kotlin.name.Name + +interface MetaComponentRegistrar : ComponentRegistrar, MetaPluginSyntax, InternalRegistry { + + override fun intercept(): List>> + + override fun registerProjectComponents(project: MockProject, configuration: CompilerConfiguration) = + super.registerProjectComponents(project, configuration) + +} diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/MetaPlugin.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/MetaPlugin.kt new file mode 100644 index 00000000000..a53afd4368b --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/MetaPlugin.kt @@ -0,0 +1,11 @@ +package arrow.meta + +import arrow.meta.phases.ExtensionPhase +import arrow.meta.plugins.higherkind.higherKindedTypes +import arrow.meta.plugins.typeclasses.typeClasses +import org.jetbrains.kotlin.name.Name + +open class MetaPlugin : MetaComponentRegistrar { + override fun intercept(): List>> = + listOf(higherKindedTypes, typeClasses) //, higherKindedTypes, typeClasses, comprehensions) +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/MetaPluginSyntax.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/MetaPluginSyntax.kt new file mode 100644 index 00000000000..dc0b7a1b8ac --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/MetaPluginSyntax.kt @@ -0,0 +1,14 @@ +package arrow.meta.dsl + +import arrow.meta.dsl.analysis.AnalysisSyntax +import arrow.meta.dsl.codegen.CodegenSyntax +import arrow.meta.dsl.config.ConfigSyntax +import arrow.meta.dsl.resolve.ResolveSyntax +import arrow.meta.phases.ExtensionPhase + +interface MetaPluginSyntax : ConfigSyntax, AnalysisSyntax, ResolveSyntax, CodegenSyntax { + + fun meta(vararg phases: ExtensionPhase): List = + phases.toList() + +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/analysis/AnalysisSyntax.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/analysis/AnalysisSyntax.kt new file mode 100644 index 00000000000..339dec9f7f2 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/analysis/AnalysisSyntax.kt @@ -0,0 +1,77 @@ +package arrow.meta.dsl.analysis + +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.analysis.AnalysisHandler +import arrow.meta.phases.analysis.CollectAdditionalSources +import arrow.meta.phases.analysis.ExtraImports +import arrow.meta.phases.analysis.PreprocessedVirtualFileFactory +import arrow.meta.internal.Noop +import org.jetbrains.kotlin.analyzer.AnalysisResult +import org.jetbrains.kotlin.com.intellij.openapi.project.Project +import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFile +import org.jetbrains.kotlin.com.intellij.testFramework.LightVirtualFile +import org.jetbrains.kotlin.config.CompilerConfiguration +import org.jetbrains.kotlin.container.ComponentProvider +import org.jetbrains.kotlin.context.ProjectContext +import org.jetbrains.kotlin.descriptors.ModuleDescriptor +import org.jetbrains.kotlin.psi.KtFile +import org.jetbrains.kotlin.psi.KtImportInfo +import org.jetbrains.kotlin.resolve.BindingTrace + +interface AnalysisSyntax { + fun additionalSources( + collectAdditionalSourcesAndUpdateConfiguration: CompilerContext.(knownSources: Collection, configuration: CompilerConfiguration, project: Project) -> Collection + ): CollectAdditionalSources = + object : CollectAdditionalSources { + override fun CompilerContext.collectAdditionalSourcesAndUpdateConfiguration(knownSources: Collection, configuration: CompilerConfiguration, project: Project): Collection = + collectAdditionalSourcesAndUpdateConfiguration(knownSources, configuration, project) + } + + fun analysys( + doAnalysis: CompilerContext.(project: Project, module: ModuleDescriptor, projectContext: ProjectContext, files: Collection, bindingTrace: BindingTrace, componentProvider: ComponentProvider) -> AnalysisResult?, + analysisCompleted: CompilerContext.(project: Project, module: ModuleDescriptor, bindingTrace: BindingTrace, files: Collection) -> AnalysisResult? + ): AnalysisHandler = + object : AnalysisHandler { + override fun CompilerContext.doAnalysis( + project: Project, + module: ModuleDescriptor, + projectContext: ProjectContext, + files: Collection, + bindingTrace: BindingTrace, + componentProvider: ComponentProvider + ): AnalysisResult? { + ctx.module = module + ctx.files = files + ctx.componentProvider = componentProvider + return doAnalysis(project, module, projectContext, files, bindingTrace, componentProvider) + } + + override fun CompilerContext.analysisCompleted( + project: Project, + module: ModuleDescriptor, + bindingTrace: BindingTrace, + files: Collection + ): AnalysisResult? = + analysisCompleted(project, module, bindingTrace, files) + } + + fun preprocessedVirtualFileFactory( + createPreprocessedFile: CompilerContext.(file: VirtualFile?) -> VirtualFile?, + createPreprocessedLightFile: CompilerContext.(file: LightVirtualFile?) -> LightVirtualFile? = Noop.nullable2() + ): PreprocessedVirtualFileFactory = + object : PreprocessedVirtualFileFactory { + override fun CompilerContext.isPassThrough(): Boolean = false + + override fun CompilerContext.createPreprocessedFile(file: VirtualFile?): VirtualFile? = + createPreprocessedFile(file) + + override fun CompilerContext.createPreprocessedLightFile(file: LightVirtualFile?): LightVirtualFile? = + createPreprocessedLightFile(file) + } + + fun extraImports(extraImports: (ktFile: KtFile) -> Collection): ExtraImports = + object : ExtraImports { + override fun CompilerContext.extraImports(ktFile: KtFile): Collection = + extraImports(ktFile) + } +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/codegen/CodegenSyntax.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/codegen/CodegenSyntax.kt new file mode 100644 index 00000000000..61362750a9c --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/codegen/CodegenSyntax.kt @@ -0,0 +1,6 @@ +package arrow.meta.dsl.codegen + +import arrow.meta.dsl.codegen.asm.AsmSyntax +import arrow.meta.dsl.codegen.ir.IrSyntax + +interface CodegenSyntax: AsmSyntax, IrSyntax \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/codegen/asm/AsmSyntax.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/codegen/asm/AsmSyntax.kt new file mode 100644 index 00000000000..180e6b5226f --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/codegen/asm/AsmSyntax.kt @@ -0,0 +1,34 @@ +package arrow.meta.dsl.codegen.asm + +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.codegen.asm.Codegen +import org.jetbrains.kotlin.codegen.ImplementationBodyCodegen +import org.jetbrains.kotlin.codegen.StackValue +import org.jetbrains.kotlin.codegen.extensions.ExpressionCodegenExtension +import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall + +interface AsmSyntax { + fun codegen( + applyFunction: CompilerContext.(receiver: StackValue, resolvedCall: ResolvedCall<*>, c: ExpressionCodegenExtension.Context) -> StackValue?, + applyProperty: CompilerContext.(receiver: StackValue, resolvedCall: ResolvedCall<*>, c: ExpressionCodegenExtension.Context) -> StackValue?, + generateClassSyntheticParts: CompilerContext.(codegen: ImplementationBodyCodegen) -> Unit + ): Codegen = + object : Codegen { + override fun CompilerContext.applyFunction( + receiver: StackValue, + resolvedCall: ResolvedCall<*>, + c: ExpressionCodegenExtension.Context + ): StackValue? = + applyFunction(receiver, resolvedCall, c) + + override fun CompilerContext.applyProperty( + receiver: StackValue, + resolvedCall: ResolvedCall<*>, + c: ExpressionCodegenExtension.Context + ): StackValue? = + applyProperty(receiver, resolvedCall, c) + + override fun CompilerContext.generateClassSyntheticParts(codegen: ImplementationBodyCodegen) = + generateClassSyntheticParts(codegen) + } +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/codegen/ir/IrSyntax.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/codegen/ir/IrSyntax.kt new file mode 100644 index 00000000000..fb31d7fb7fc --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/codegen/ir/IrSyntax.kt @@ -0,0 +1,692 @@ +package arrow.meta.dsl.codegen.ir + +import arrow.meta.MetaComponentRegistrar +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.codegen.ir.IRGeneration +import arrow.meta.phases.codegen.ir.IrUtils +import org.jetbrains.kotlin.backend.common.BackendContext +import org.jetbrains.kotlin.ir.IrElement +import org.jetbrains.kotlin.ir.IrStatement +import org.jetbrains.kotlin.ir.declarations.IrAnonymousInitializer +import org.jetbrains.kotlin.ir.declarations.IrClass +import org.jetbrains.kotlin.ir.declarations.IrConstructor +import org.jetbrains.kotlin.ir.declarations.IrDeclaration +import org.jetbrains.kotlin.ir.declarations.IrEnumEntry +import org.jetbrains.kotlin.ir.declarations.IrErrorDeclaration +import org.jetbrains.kotlin.ir.declarations.IrExternalPackageFragment +import org.jetbrains.kotlin.ir.declarations.IrField +import org.jetbrains.kotlin.ir.declarations.IrFile +import org.jetbrains.kotlin.ir.declarations.IrFunction +import org.jetbrains.kotlin.ir.declarations.IrLocalDelegatedProperty +import org.jetbrains.kotlin.ir.declarations.IrModuleFragment +import org.jetbrains.kotlin.ir.declarations.IrProperty +import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction +import org.jetbrains.kotlin.ir.declarations.IrTypeParameter +import org.jetbrains.kotlin.ir.declarations.IrValueParameter +import org.jetbrains.kotlin.ir.declarations.IrVariable +import org.jetbrains.kotlin.ir.expressions.IrBlock +import org.jetbrains.kotlin.ir.expressions.IrBlockBody +import org.jetbrains.kotlin.ir.expressions.IrBody +import org.jetbrains.kotlin.ir.expressions.IrBranch +import org.jetbrains.kotlin.ir.expressions.IrBreak +import org.jetbrains.kotlin.ir.expressions.IrBreakContinue +import org.jetbrains.kotlin.ir.expressions.IrCall +import org.jetbrains.kotlin.ir.expressions.IrCallableReference +import org.jetbrains.kotlin.ir.expressions.IrCatch +import org.jetbrains.kotlin.ir.expressions.IrClassReference +import org.jetbrains.kotlin.ir.expressions.IrComposite +import org.jetbrains.kotlin.ir.expressions.IrConst +import org.jetbrains.kotlin.ir.expressions.IrConstructorCall +import org.jetbrains.kotlin.ir.expressions.IrContainerExpression +import org.jetbrains.kotlin.ir.expressions.IrContinue +import org.jetbrains.kotlin.ir.expressions.IrDeclarationReference +import org.jetbrains.kotlin.ir.expressions.IrDelegatingConstructorCall +import org.jetbrains.kotlin.ir.expressions.IrDoWhileLoop +import org.jetbrains.kotlin.ir.expressions.IrDynamicExpression +import org.jetbrains.kotlin.ir.expressions.IrDynamicMemberExpression +import org.jetbrains.kotlin.ir.expressions.IrDynamicOperatorExpression +import org.jetbrains.kotlin.ir.expressions.IrElseBranch +import org.jetbrains.kotlin.ir.expressions.IrEnumConstructorCall +import org.jetbrains.kotlin.ir.expressions.IrErrorCallExpression +import org.jetbrains.kotlin.ir.expressions.IrErrorExpression +import org.jetbrains.kotlin.ir.expressions.IrExpression +import org.jetbrains.kotlin.ir.expressions.IrExpressionBody +import org.jetbrains.kotlin.ir.expressions.IrFieldAccessExpression +import org.jetbrains.kotlin.ir.expressions.IrFunctionAccessExpression +import org.jetbrains.kotlin.ir.expressions.IrFunctionReference +import org.jetbrains.kotlin.ir.expressions.IrGetClass +import org.jetbrains.kotlin.ir.expressions.IrGetEnumValue +import org.jetbrains.kotlin.ir.expressions.IrGetField +import org.jetbrains.kotlin.ir.expressions.IrGetObjectValue +import org.jetbrains.kotlin.ir.expressions.IrGetSingletonValue +import org.jetbrains.kotlin.ir.expressions.IrGetValue +import org.jetbrains.kotlin.ir.expressions.IrInstanceInitializerCall +import org.jetbrains.kotlin.ir.expressions.IrLocalDelegatedPropertyReference +import org.jetbrains.kotlin.ir.expressions.IrLoop +import org.jetbrains.kotlin.ir.expressions.IrMemberAccessExpression +import org.jetbrains.kotlin.ir.expressions.IrPropertyReference +import org.jetbrains.kotlin.ir.expressions.IrReturn +import org.jetbrains.kotlin.ir.expressions.IrSetField +import org.jetbrains.kotlin.ir.expressions.IrSetVariable +import org.jetbrains.kotlin.ir.expressions.IrSpreadElement +import org.jetbrains.kotlin.ir.expressions.IrStringConcatenation +import org.jetbrains.kotlin.ir.expressions.IrSuspendableExpression +import org.jetbrains.kotlin.ir.expressions.IrSuspensionPoint +import org.jetbrains.kotlin.ir.expressions.IrSyntheticBody +import org.jetbrains.kotlin.ir.expressions.IrThrow +import org.jetbrains.kotlin.ir.expressions.IrTry +import org.jetbrains.kotlin.ir.expressions.IrTypeOperatorCall +import org.jetbrains.kotlin.ir.expressions.IrValueAccessExpression +import org.jetbrains.kotlin.ir.expressions.IrVararg +import org.jetbrains.kotlin.ir.expressions.IrWhen +import org.jetbrains.kotlin.ir.expressions.IrWhileLoop +import org.jetbrains.kotlin.ir.visitors.IrElementTransformer +import org.jetbrains.kotlin.resolve.BindingContext + +interface IrSyntax { + fun IrGeneration(generate: (compilerContext: CompilerContext, file: IrFile, backendContext: BackendContext, bindingContext: BindingContext) -> Unit): IRGeneration = + object : IRGeneration { + override fun CompilerContext.generate( + file: IrFile, + backendContext: BackendContext, + bindingContext: BindingContext + ) { + generate(this, file, backendContext, bindingContext) + } + } + + fun irElement(f: IrUtils.(IrElement) -> IrElement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitElement(expression: IrElement, data: Unit): IrElement = + f(IrUtils(backendContext, compilerContext), expression)?.let { super.visitElement(it, data) } ?: super.visitElement(expression, data) + }, Unit) + } + + fun irModuleFragment(f: IrUtils.(IrModuleFragment) -> IrModuleFragment?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitModuleFragment(expression: IrModuleFragment, data: Unit): IrModuleFragment = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitModuleFragment(expression, data) + }, Unit) + } + + fun irFile(f: IrUtils.(IrFile) -> IrFile?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitFile(expression: IrFile, data: Unit): IrFile = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitFile(expression, data) + }, Unit) + } + + fun irExternalPackageFragment(f: IrUtils.(IrExternalPackageFragment) -> IrExternalPackageFragment?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitExternalPackageFragment(expression: IrExternalPackageFragment, data: Unit): IrExternalPackageFragment = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitExternalPackageFragment(expression, data) + }, Unit) + } + + fun irDeclaration(f: IrUtils.(IrDeclaration) -> IrStatement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitDeclaration(expression: IrDeclaration, data: Unit): IrStatement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitDeclaration(expression, data) + }, Unit) + } + + fun irClass(f: IrUtils.(IrClass) -> IrStatement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitClass(expression: IrClass, data: Unit): IrStatement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitClass(expression, data) + }, Unit) + } + + fun irFunction(f: IrUtils.(IrFunction) -> IrStatement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitFunction(expression: IrFunction, data: Unit): IrStatement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitFunction(expression, data) + }, Unit) + } + + fun irSimpleFunction(f: IrUtils.(IrSimpleFunction) -> IrStatement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitSimpleFunction(expression: IrSimpleFunction, data: Unit): IrStatement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitSimpleFunction(expression, data) + }, Unit) + } + + fun irConstructor(f: IrUtils.(IrConstructor) -> IrStatement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitConstructor(expression: IrConstructor, data: Unit): IrStatement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitConstructor(expression, data) + }, Unit) + } + + fun irProperty(f: IrUtils.(IrProperty) -> IrStatement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitProperty(expression: IrProperty, data: Unit): IrStatement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitProperty(expression, data) + }, Unit) + } + + fun irField(f: IrUtils.(IrField) -> IrStatement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitField(expression: IrField, data: Unit): IrStatement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitField(expression, data) + }, Unit) + } + + fun irLocalDelegatedProperty(f: IrUtils.(IrLocalDelegatedProperty) -> IrStatement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitLocalDelegatedProperty(expression: IrLocalDelegatedProperty, data: Unit): IrStatement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitLocalDelegatedProperty(expression, data) + }, Unit) + } + + fun irEnumEntry(f: IrUtils.(IrEnumEntry) -> IrStatement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitEnumEntry(expression: IrEnumEntry, data: Unit): IrStatement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitEnumEntry(expression, data) + }, Unit) + } + + fun irAnonymousInitializer(f: IrUtils.(IrAnonymousInitializer) -> IrStatement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitAnonymousInitializer(expression: IrAnonymousInitializer, data: Unit): IrStatement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitAnonymousInitializer(expression, data) + }, Unit) + } + + fun irVariable(f: IrUtils.(IrVariable) -> IrStatement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitVariable(expression: IrVariable, data: Unit): IrStatement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitVariable(expression, data) + }, Unit) + } + + fun irTypeParameter(f: IrUtils.(IrTypeParameter) -> IrStatement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitTypeParameter(expression: IrTypeParameter, data: Unit): IrStatement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitTypeParameter(expression, data) + }, Unit) + } + + fun irValueParameter(f: IrUtils.(IrValueParameter) -> IrStatement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitValueParameter(expression: IrValueParameter, data: Unit): IrStatement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitValueParameter(expression, data) + }, Unit) + } + + fun irBody(f: IrUtils.(IrBody) -> IrBody?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitBody(body: IrBody, data: Unit): IrBody = + f(IrUtils(backendContext, compilerContext), body) ?: super.visitBody(body, data) + }, Unit) + } + + fun irExpressionBody(f: IrUtils.(IrExpressionBody) -> IrBody?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitExpressionBody(expression: IrExpressionBody, data: Unit): IrBody = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitExpressionBody(expression, data) + }, Unit) + } + + fun irBlockBody(f: IrUtils.(IrBlockBody) -> IrBody?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitBlockBody(expression: IrBlockBody, data: Unit): IrBody = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitBlockBody(expression, data) + }, Unit) + } + + fun irSyntheticBody(f: IrUtils.(IrSyntheticBody) -> IrBody?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitSyntheticBody(expression: IrSyntheticBody, data: Unit): IrBody = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitSyntheticBody(expression, data) + }, Unit) + } + + fun irSuspendableExpression(f: IrUtils.(IrSuspendableExpression) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitSuspendableExpression(expression: IrSuspendableExpression, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitSuspendableExpression(expression, data) + }, Unit) + } + + fun irSuspensionPoint(f: IrUtils.(IrSuspensionPoint) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitSuspensionPoint(expression: IrSuspensionPoint, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitSuspensionPoint(expression, data) + }, Unit) + } + + fun irExpression(f: IrUtils.(IrExpression) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitExpression(expression: IrExpression, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitExpression(expression, data) + }, Unit) + } + + fun MetaComponentRegistrar.irConst(f: IrUtils.(IrConst) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitConst(expression: IrConst, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression as IrConst) ?: super.visitConst(expression, data) + }, Unit) + } + + fun irVararg(f: IrUtils.(IrVararg) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitVararg(expression: IrVararg, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitVararg(expression, data) + }, Unit) + } + + fun irSpreadElement(f: IrUtils.(IrSpreadElement) -> IrSpreadElement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitSpreadElement(expression: IrSpreadElement, data: Unit): IrSpreadElement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitSpreadElement(expression, data) + }, Unit) + } + + fun irContainerExpression(f: IrUtils.(IrContainerExpression) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitContainerExpression(expression: IrContainerExpression, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitContainerExpression(expression, data) + }, Unit) + } + + fun irBlock(f: IrUtils.(IrBlock) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitBlock(expression: IrBlock, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitBlock(expression, data) + }, Unit) + } + + fun irComposite(f: IrUtils.(IrComposite) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitComposite(expression: IrComposite, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitComposite(expression, data) + }, Unit) + } + + fun irStringConcatenation(f: IrUtils.(IrStringConcatenation) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitStringConcatenation(expression: IrStringConcatenation, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitStringConcatenation(expression, data) + }, Unit) + } + + fun irDeclarationReference(f: IrUtils.(IrDeclarationReference) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitDeclarationReference(expression: IrDeclarationReference, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitDeclarationReference(expression, data) + }, Unit) + } + + fun irSingletonReference(f: IrUtils.(IrGetSingletonValue) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitSingletonReference(expression: IrGetSingletonValue, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitSingletonReference(expression, data) + }, Unit) + } + + fun irGetObjectValue(f: IrUtils.(IrGetObjectValue) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitGetObjectValue(expression: IrGetObjectValue, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitGetObjectValue(expression, data) + }, Unit) + } + + fun irGetEnumValue(f: IrUtils.(IrGetEnumValue) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitGetEnumValue(expression: IrGetEnumValue, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitGetEnumValue(expression, data) + }, Unit) + } + + fun irValueAccess(f: IrUtils.(IrValueAccessExpression) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitValueAccess(expression: IrValueAccessExpression, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitValueAccess(expression, data) + }, Unit) + } + + fun irGetValue(f: IrUtils.(IrGetValue) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitGetValue(expression: IrGetValue, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitGetValue(expression, data) + }, Unit) + } + + fun irSetVariable(f: IrUtils.(IrSetVariable) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitSetVariable(expression: IrSetVariable, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitSetVariable(expression, data) + }, Unit) + } + + fun irFieldAccess(f: IrUtils.(IrFieldAccessExpression) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitFieldAccess(expression: IrFieldAccessExpression, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitFieldAccess(expression, data) + }, Unit) + } + + fun irGetField(f: IrUtils.(IrGetField) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitGetField(expression: IrGetField, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitGetField(expression, data) + }, Unit) + } + + fun irSetField(f: IrUtils.(IrSetField) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitSetField(expression: IrSetField, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitSetField(expression, data) + }, Unit) + } + + fun irMemberAccess(f: IrUtils.(IrMemberAccessExpression) -> IrElement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitMemberAccess(expression: IrMemberAccessExpression, data: Unit): IrElement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitMemberAccess(expression, data) + }, Unit) + } + + fun irFunctionAccess(f: IrUtils.(IrFunctionAccessExpression) -> IrElement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitFunctionAccess(expression: IrFunctionAccessExpression, data: Unit): IrElement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitFunctionAccess(expression, data) + }, Unit) + } + + fun irCall(f: IrUtils.(IrCall) -> IrElement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitCall(expression: IrCall, data: Unit): IrElement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitCall(expression, data) + }, Unit) + } + + fun irConstructorCall(f: IrUtils.(IrConstructorCall) -> IrElement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitConstructorCall(expression: IrConstructorCall, data: Unit): IrElement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitConstructorCall(expression, data) + }, Unit) + } + + fun irDelegatingConstructorCall(f: IrUtils.(IrDelegatingConstructorCall) -> IrElement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitDelegatingConstructorCall(expression: IrDelegatingConstructorCall, data: Unit): IrElement = + f(IrUtils(backendContext, compilerContext), expression) + ?: super.visitDelegatingConstructorCall(expression, data) + }, Unit) + } + + fun irEnumConstructorCall(f: IrUtils.(IrEnumConstructorCall) -> IrElement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitEnumConstructorCall(expression: IrEnumConstructorCall, data: Unit): IrElement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitEnumConstructorCall(expression, data) + }, Unit) + } + + fun irGetClass(f: IrUtils.(IrGetClass) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitGetClass(expression: IrGetClass, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitGetClass(expression, data) + }, Unit) + } + + fun irCallableReference(f: IrUtils.(IrCallableReference) -> IrElement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitCallableReference(expression: IrCallableReference, data: Unit): IrElement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitCallableReference(expression, data) + }, Unit) + } + + fun irFunctionReference(f: IrUtils.(IrFunctionReference) -> IrElement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitFunctionReference(expression: IrFunctionReference, data: Unit): IrElement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitFunctionReference(expression, data) + }, Unit) + } + + fun irPropertyReference(f: IrUtils.(IrPropertyReference) -> IrElement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitPropertyReference(expression: IrPropertyReference, data: Unit): IrElement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitPropertyReference(expression, data) + }, Unit) + } + + fun irLocalDelegatedPropertyReference(f: IrUtils.(IrLocalDelegatedPropertyReference) -> IrElement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitLocalDelegatedPropertyReference(expression: IrLocalDelegatedPropertyReference, data: Unit): IrElement = + f(IrUtils(backendContext, compilerContext), expression) + ?: super.visitLocalDelegatedPropertyReference(expression, data) + }, Unit) + } + + fun irClassReference(f: IrUtils.(IrClassReference) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitClassReference(expression: IrClassReference, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitClassReference(expression, data) + }, Unit) + } + + fun irInstanceInitializerCall(f: IrUtils.(IrInstanceInitializerCall) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitInstanceInitializerCall(expression: IrInstanceInitializerCall, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitInstanceInitializerCall(expression, data) + }, Unit) + } + + fun irTypeOperator(f: IrUtils.(IrTypeOperatorCall) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitTypeOperator(expression: IrTypeOperatorCall, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitTypeOperator(expression, data) + }, Unit) + } + + fun irWhen(f: IrUtils.(IrWhen) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitWhen(expression: IrWhen, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitWhen(expression, data) + }, Unit) + } + + fun irBranch(f: IrUtils.(IrBranch) -> IrBranch?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitBranch(expression: IrBranch, data: Unit): IrBranch = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitBranch(expression, data) + }, Unit) + } + + fun irElseBranch(f: IrUtils.(IrElseBranch) -> IrElseBranch?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitElseBranch(expression: IrElseBranch, data: Unit): IrElseBranch = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitElseBranch(expression, data) + }, Unit) + } + + fun irLoop(f: IrUtils.(IrLoop) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitLoop(expression: IrLoop, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitLoop(expression, data) + }, Unit) + } + + fun irWhileLoop(f: IrUtils.(IrWhileLoop) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitWhileLoop(expression: IrWhileLoop, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitWhileLoop(expression, data) + }, Unit) + } + + fun irDoWhileLoop(f: IrUtils.(IrDoWhileLoop) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitDoWhileLoop(expression: IrDoWhileLoop, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitDoWhileLoop(expression, data) + }, Unit) + } + + fun irTry(f: IrUtils.(IrTry) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitTry(expression: IrTry, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitTry(expression, data) + }, Unit) + } + + fun irCatch(f: IrUtils.(IrCatch) -> IrCatch?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitCatch(expression: IrCatch, data: Unit): IrCatch = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitCatch(expression, data) + }, Unit) + } + + fun irBreakContinue(f: IrUtils.(IrBreakContinue) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitBreakContinue(expression: IrBreakContinue, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitBreakContinue(expression, data) + }, Unit) + } + + fun irBreak(f: IrUtils.(IrBreak) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitBreak(expression: IrBreak, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitBreak(expression, data) + }, Unit) + } + + fun irContinue(f: IrUtils.(IrContinue) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitContinue(expression: IrContinue, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitContinue(expression, data) + }, Unit) + } + + fun irReturn(f: IrUtils.(IrReturn) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitReturn(expression: IrReturn, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitReturn(expression, data) + }, Unit) + } + + fun irThrow(f: IrUtils.(IrThrow) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitThrow(expression: IrThrow, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitThrow(expression, data) + }, Unit) + } + + fun irDynamicExpression(f: IrUtils.(IrDynamicExpression) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitDynamicExpression(expression: IrDynamicExpression, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitDynamicExpression(expression, data) + }, Unit) + } + + fun irDynamicOperatorExpression(f: IrUtils.(IrDynamicOperatorExpression) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitDynamicOperatorExpression(expression: IrDynamicOperatorExpression, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) + ?: super.visitDynamicOperatorExpression(expression, data) + }, Unit) + } + + fun irDynamicMemberExpression(f: IrUtils.(IrDynamicMemberExpression) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitDynamicMemberExpression(expression: IrDynamicMemberExpression, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitDynamicMemberExpression(expression, data) + }, Unit) + } + + fun irErrorDeclaration(f: IrUtils.(IrErrorDeclaration) -> IrStatement?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitErrorDeclaration(expression: IrErrorDeclaration, data: Unit): IrStatement = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitErrorDeclaration(expression, data) + }, Unit) + } + + fun irErrorExpression(f: IrUtils.(IrErrorExpression) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitErrorExpression(expression: IrErrorExpression, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitErrorExpression(expression, data) + }, Unit) + } + + fun irErrorCallExpression(f: IrUtils.(IrErrorCallExpression) -> IrExpression?): IRGeneration = + IrGeneration { compilerContext, file, backendContext, bindingContext -> + file.transformChildren(object : IrElementTransformer { + override fun visitErrorCallExpression(expression: IrErrorCallExpression, data: Unit): IrExpression = + f(IrUtils(backendContext, compilerContext), expression) ?: super.visitErrorCallExpression(expression, data) + }, Unit) + } +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/config/ConfigSyntax.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/config/ConfigSyntax.kt new file mode 100644 index 00000000000..87f34343abd --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/config/ConfigSyntax.kt @@ -0,0 +1,48 @@ +package arrow.meta.dsl.config + +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.ExtensionPhase +import arrow.meta.phases.config.Config +import arrow.meta.dsl.platform.cli +import org.jetbrains.kotlin.config.CompilerConfiguration +import org.jetbrains.kotlin.config.JVMConfigurationKeys +import org.jetbrains.kotlin.container.StorageComponentContainer +import org.jetbrains.kotlin.descriptors.DeclarationDescriptor +import org.jetbrains.kotlin.descriptors.ModuleDescriptor +import org.jetbrains.kotlin.psi.KtDeclaration +import org.jetbrains.kotlin.resolve.checkers.DeclarationCheckerContext + +interface ConfigSyntax { + fun updateConfig(updateConfiguration: CompilerContext.(configuration: CompilerConfiguration) -> Unit): Config = + object : Config { + override fun CompilerContext.updateConfiguration(configuration: CompilerConfiguration) { + updateConfiguration(configuration) + } + } + + fun storageComponent( + registerModuleComponents: CompilerContext.(container: StorageComponentContainer, moduleDescriptor: ModuleDescriptor) -> Unit, + check: CompilerContext.(declaration: KtDeclaration, descriptor: DeclarationDescriptor, context: DeclarationCheckerContext) -> Unit + ): arrow.meta.phases.config.StorageComponentContainer = + object : arrow.meta.phases.config.StorageComponentContainer { + override fun CompilerContext.check( + declaration: KtDeclaration, + descriptor: DeclarationDescriptor, + context: DeclarationCheckerContext + ) { + check(declaration, descriptor, context) + } + + override fun CompilerContext.registerModuleComponents(container: StorageComponentContainer, moduleDescriptor: ModuleDescriptor) { + registerModuleComponents(container, moduleDescriptor) + } + } + + fun enableIr(): ExtensionPhase = + cli { + updateConfig { configuration -> + configuration.put(JVMConfigurationKeys.IR, true) + } + } ?: ExtensionPhase.Empty + +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/platform/Platform.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/platform/Platform.kt new file mode 100644 index 00000000000..67244b5a972 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/platform/Platform.kt @@ -0,0 +1,13 @@ +package arrow.meta.dsl.platform + +import org.jetbrains.kotlin.com.intellij.openapi.project.Project + +private val isIde: Boolean = Project::class.java.name == "com.intellij.openapi.project.Project" + +private val isCli: Boolean = !isIde && Project::class.java.name == "org.jetbrains.kotlin.com.intellij.openapi.project.Project" + +fun cli(f: () -> A) : A? = + if (isCli) f() else null + +fun ide(f: () -> A) : A? = + if (isIde) f() else null \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/resolve/ResolveSyntax.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/resolve/ResolveSyntax.kt new file mode 100644 index 00000000000..26ff8b9b0f7 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/dsl/resolve/ResolveSyntax.kt @@ -0,0 +1,203 @@ +package arrow.meta.dsl.resolve + +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.ExtensionPhase +import arrow.meta.phases.resolve.DeclarationAttributeAlterer +import arrow.meta.phases.resolve.PackageProvider +import arrow.meta.phases.resolve.diagnostics.DiagnosticsSuppressor +import arrow.meta.phases.resolve.synthetics.SyntheticResolver +import arrow.meta.phases.resolve.synthetics.SyntheticScopeProvider +import arrow.meta.internal.Noop +import arrow.meta.dsl.platform.ide +import org.jetbrains.kotlin.analyzer.ModuleInfo +import org.jetbrains.kotlin.com.intellij.openapi.project.Project +import org.jetbrains.kotlin.descriptors.ClassDescriptor +import org.jetbrains.kotlin.descriptors.ConstructorDescriptor +import org.jetbrains.kotlin.descriptors.DeclarationDescriptor +import org.jetbrains.kotlin.descriptors.FunctionDescriptor +import org.jetbrains.kotlin.descriptors.Modality +import org.jetbrains.kotlin.descriptors.ModuleDescriptor +import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor +import org.jetbrains.kotlin.descriptors.PackageFragmentProvider +import org.jetbrains.kotlin.descriptors.PropertyDescriptor +import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor +import org.jetbrains.kotlin.diagnostics.Diagnostic +import org.jetbrains.kotlin.incremental.components.LookupLocation +import org.jetbrains.kotlin.incremental.components.LookupTracker +import org.jetbrains.kotlin.name.Name +import org.jetbrains.kotlin.psi.KtModifierListOwner +import org.jetbrains.kotlin.resolve.BindingContext +import org.jetbrains.kotlin.resolve.BindingTrace +import org.jetbrains.kotlin.resolve.lazy.LazyClassContext +import org.jetbrains.kotlin.resolve.lazy.declarations.ClassMemberDeclarationProvider +import org.jetbrains.kotlin.resolve.lazy.declarations.PackageMemberDeclarationProvider +import org.jetbrains.kotlin.resolve.scopes.ResolutionScope +import org.jetbrains.kotlin.storage.StorageManager +import org.jetbrains.kotlin.types.KotlinType +import java.util.ArrayList + +interface ResolveSyntax { + fun declarationAttributeAlterer( + refineDeclarationModality: CompilerContext.(modifierListOwner: KtModifierListOwner, declaration: DeclarationDescriptor?, containingDeclaration: DeclarationDescriptor?, currentModality: Modality, bindingContext: BindingContext, isImplicitModality: Boolean) -> Modality? + ): DeclarationAttributeAlterer = + object : DeclarationAttributeAlterer { + override fun CompilerContext.refineDeclarationModality( + modifierListOwner: KtModifierListOwner, + declaration: DeclarationDescriptor?, + containingDeclaration: DeclarationDescriptor?, + currentModality: Modality, + bindingContext: BindingContext, + isImplicitModality: Boolean + ): Modality? = + refineDeclarationModality( + modifierListOwner, + declaration, + containingDeclaration, + currentModality, + bindingContext, + isImplicitModality + ) + } + + fun packageFragmentProvider(getPackageFragmentProvider: CompilerContext.(project: Project, module: ModuleDescriptor, storageManager: StorageManager, trace: BindingTrace, moduleInfo: ModuleInfo?, lookupTracker: LookupTracker) -> PackageFragmentProvider?): PackageProvider = + object : PackageProvider { + override fun CompilerContext.getPackageFragmentProvider( + project: Project, + module: ModuleDescriptor, + storageManager: StorageManager, + trace: BindingTrace, + moduleInfo: ModuleInfo?, + lookupTracker: LookupTracker + ): PackageFragmentProvider? = + getPackageFragmentProvider( + project, + module, + storageManager, + trace, + moduleInfo, + lookupTracker + ) + } + + fun syntheticScopes( + syntheticConstructor: CompilerContext.(constructor: ConstructorDescriptor) -> ConstructorDescriptor? = Noop.nullable2(), + syntheticConstructors: CompilerContext.(scope: ResolutionScope) -> Collection = Noop.emptyCollection2(), + syntheticConstructorsForName: CompilerContext.(scope: ResolutionScope, name: Name, location: LookupLocation) -> Collection = Noop.emptyCollection4(), + syntheticExtensionProperties: CompilerContext.(receiverTypes: Collection, location: LookupLocation) -> Collection = Noop.emptyCollection3(), + syntheticExtensionPropertiesForName: CompilerContext.(receiverTypes: Collection, name: Name, location: LookupLocation) -> Collection = Noop.emptyCollection4(), + syntheticMemberFunctions: CompilerContext.(receiverTypes: Collection) -> Collection = Noop.emptyCollection2(), + syntheticMemberFunctionsForName: CompilerContext.(receiverTypes: Collection, name: Name, location: LookupLocation) -> Collection = Noop.emptyCollection4(), + syntheticStaticFunctions: CompilerContext.(scope: ResolutionScope) -> Collection = Noop.emptyCollection2(), + syntheticStaticFunctionsForName: CompilerContext.(scope: ResolutionScope, name: Name, location: LookupLocation) -> Collection = Noop.emptyCollection4() + ): ExtensionPhase = + ide { + object : SyntheticScopeProvider { + override fun CompilerContext.syntheticConstructor(constructor: ConstructorDescriptor): ConstructorDescriptor? = + syntheticConstructor(constructor) + + override fun CompilerContext.syntheticConstructors(scope: ResolutionScope): Collection = + syntheticConstructors(scope) + + override fun CompilerContext.syntheticConstructors(scope: ResolutionScope, name: Name, location: LookupLocation): Collection = + syntheticConstructorsForName(scope, name, location) + + override fun CompilerContext.syntheticExtensionProperties(receiverTypes: Collection, location: LookupLocation): Collection = + syntheticExtensionProperties(receiverTypes, location) + + override fun CompilerContext.syntheticExtensionProperties(receiverTypes: Collection, name: Name, location: LookupLocation): Collection = + syntheticExtensionPropertiesForName(receiverTypes, name, location) + + override fun CompilerContext.syntheticMemberFunctions(receiverTypes: Collection): Collection = + syntheticMemberFunctions(receiverTypes) + + override fun CompilerContext.syntheticMemberFunctions(receiverTypes: Collection, name: Name, location: LookupLocation): Collection = + syntheticMemberFunctionsForName(receiverTypes, name, location) + + override fun CompilerContext.syntheticStaticFunctions(scope: ResolutionScope): Collection = + syntheticStaticFunctions(scope) + + override fun CompilerContext.syntheticStaticFunctions(scope: ResolutionScope, name: Name, location: LookupLocation): Collection = + syntheticStaticFunctionsForName(scope, name, location) + } + } ?: ExtensionPhase.Empty + + fun diagnosticsSuppressor(isSuppressed: CompilerContext.(diagnostic: Diagnostic) -> Boolean): DiagnosticsSuppressor = + object : DiagnosticsSuppressor { + override fun CompilerContext.isSuppressed(diagnostic: Diagnostic): Boolean = + isSuppressed(diagnostic) + } + + fun syntheticResolver( + addSyntheticSupertypes: CompilerContext.(thisDescriptor: ClassDescriptor, supertypes: MutableList) -> Unit = Noop.effect3, + /** + * For a given package fragment it iterates over all the package declaration + * allowing the user to contribute new synthetic declarations. + * The result mutable set includes the descriptors as seen from the Kotlin compiler + * initial analysis and allows us to mutate it to add new descriptor or change the existing ones + */ + generatePackageSyntheticClasses: CompilerContext.(thisDescriptor: PackageFragmentDescriptor, name: Name, ctx: LazyClassContext, declarationProvider: PackageMemberDeclarationProvider, result: MutableSet) -> Unit = Noop.effect6, + generateSyntheticClasses: CompilerContext.(thisDescriptor: ClassDescriptor, name: Name, ctx: LazyClassContext, declarationProvider: ClassMemberDeclarationProvider, result: MutableSet) -> Unit = Noop.effect6, + generateSyntheticMethods: CompilerContext.(thisDescriptor: ClassDescriptor, name: Name, bindingContext: BindingContext, fromSupertypes: List, result: MutableCollection) -> Unit = Noop.effect6, + generateSyntheticProperties: CompilerContext.(thisDescriptor: ClassDescriptor, name: Name, bindingContext: BindingContext, fromSupertypes: ArrayList, result: MutableSet) -> Unit = Noop.effect6, + getSyntheticCompanionObjectNameIfNeeded: CompilerContext.(thisDescriptor: ClassDescriptor) -> Name? = Noop.nullable2(), + getSyntheticFunctionNames: CompilerContext.(thisDescriptor: ClassDescriptor) -> List? = Noop.nullable2(), + getSyntheticNestedClassNames: CompilerContext.(thisDescriptor: ClassDescriptor) -> List? = Noop.nullable2() + ): SyntheticResolver = + object : SyntheticResolver { + override fun CompilerContext.addSyntheticSupertypes( + thisDescriptor: ClassDescriptor, + supertypes: MutableList + ) { + addSyntheticSupertypes(thisDescriptor, supertypes) + } + + override fun CompilerContext.generateSyntheticClasses( + thisDescriptor: ClassDescriptor, + name: Name, + ctx: LazyClassContext, + declarationProvider: ClassMemberDeclarationProvider, + result: MutableSet + ) { + generateSyntheticClasses(thisDescriptor, name, ctx, declarationProvider, result) + } + + override fun CompilerContext.generatePackageSyntheticClasses( + thisDescriptor: PackageFragmentDescriptor, + name: Name, + ctx: LazyClassContext, + declarationProvider: PackageMemberDeclarationProvider, + result: MutableSet + ) { + generatePackageSyntheticClasses(thisDescriptor, name, ctx, declarationProvider, result) + } + + override fun CompilerContext.generateSyntheticMethods( + thisDescriptor: ClassDescriptor, + name: Name, + bindingContext: BindingContext, + fromSupertypes: List, + result: MutableCollection + ) { + generateSyntheticMethods(thisDescriptor, name, bindingContext, fromSupertypes, result) + } + + override fun CompilerContext.generateSyntheticProperties( + thisDescriptor: ClassDescriptor, + name: Name, + bindingContext: BindingContext, + fromSupertypes: ArrayList, + result: MutableSet + ) { + generateSyntheticProperties(thisDescriptor, name, bindingContext, fromSupertypes, result) + } + + override fun CompilerContext.getSyntheticCompanionObjectNameIfNeeded(thisDescriptor: ClassDescriptor): Name? = + getSyntheticCompanionObjectNameIfNeeded(thisDescriptor) + + override fun CompilerContext.getSyntheticFunctionNames(thisDescriptor: ClassDescriptor): List = + getSyntheticFunctionNames(thisDescriptor) ?: emptyList() + + override fun CompilerContext.getSyntheticNestedClassNames(thisDescriptor: ClassDescriptor): List = + getSyntheticNestedClassNames(thisDescriptor) ?: emptyList() + } +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/internal/Noop.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/internal/Noop.kt new file mode 100644 index 00000000000..b243fc49f6b --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/internal/Noop.kt @@ -0,0 +1,22 @@ +package arrow.meta.internal + +object Noop { + val effect1: (Any?) -> Unit = { _ -> Unit } + val effect2: (Any?, Any?) -> Unit = { _, _ -> Unit } + val effect3: (Any?, Any?, Any?) -> Unit = { _, _, _ -> Unit } + val effect4: (Any?, Any?, Any?, Any?) -> Unit = { _, _, _, _ -> Unit } + val effect5: (Any?, Any?, Any?, Any?, Any?) -> Unit = { _, _, _, _, _ -> Unit } + val effect6: (Any?, Any?, Any?, Any?, Any?, Any?) -> Unit = { _, _, _, _, _, _ -> Unit } + fun nullable1(): (Any?) -> A? = { null } + fun nullable2(): (Any?, Any?) -> A? = { _, _ -> null } + fun nullable3(): (Any?, Any?, Any?) -> A? = { _, _, _ -> null } + fun nullable4(): (Any?, Any?, Any?, Any?) -> A? = { _, _, _, _ -> null } + fun nullable5(): (Any?, Any?, Any?, Any?, Any?) -> A? = { _, _, _, _, _ -> null } + fun emptyCollection1(): (Any?) -> Collection = { emptyList() } + fun emptyCollection2(): (Any?, Any?) -> Collection = { _, _ -> emptyList() } + fun emptyCollection3(): (Any?, Any?, Any?) -> Collection = { _, _, _ -> emptyList() } + fun emptyCollection4(): (Any?, Any?, Any?, Any?) -> Collection = { _, _, _, _ -> emptyList() } + fun emptyCollection5(): (Any?, Any?, Any?, Any?, Any?) -> Collection = { _, _, _, _, _ -> emptyList() } + val boolean1True: (Any?) -> Boolean = { _ -> true } + val boolean2True: (Any?, Any?) -> Boolean = { _, _ -> true } +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/internal/registry/InternalRegistry.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/internal/registry/InternalRegistry.kt new file mode 100644 index 00000000000..dd281efba34 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/internal/registry/InternalRegistry.kt @@ -0,0 +1,618 @@ +package arrow.meta.internal.registry + +import arrow.meta.dsl.config.ConfigSyntax +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.Composite +import arrow.meta.phases.ExtensionPhase +import arrow.meta.phases.analysis.AnalysisHandler +import arrow.meta.phases.analysis.CollectAdditionalSources +import arrow.meta.phases.analysis.ExtraImports +import arrow.meta.phases.analysis.PreprocessedVirtualFileFactory +import arrow.meta.phases.codegen.asm.ClassBuilder +import arrow.meta.phases.codegen.asm.Codegen +import arrow.meta.phases.codegen.ir.IRGeneration +import arrow.meta.phases.config.Config +import arrow.meta.phases.config.StorageComponentContainer +import arrow.meta.phases.resolve.DeclarationAttributeAlterer +import arrow.meta.phases.resolve.PackageProvider +import arrow.meta.phases.resolve.diagnostics.DiagnosticsSuppressor +import arrow.meta.phases.resolve.synthetics.SyntheticResolver +import arrow.meta.phases.resolve.synthetics.SyntheticScopeProvider +import arrow.meta.plugins.higherkind.KindAwareTypeChecker +import arrow.meta.dsl.platform.cli +import arrow.meta.dsl.platform.ide +import org.jetbrains.kotlin.analyzer.AnalysisResult +import org.jetbrains.kotlin.analyzer.ModuleInfo +import org.jetbrains.kotlin.backend.common.BackendContext +import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension +import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys +import org.jetbrains.kotlin.cli.common.messages.MessageCollector +import org.jetbrains.kotlin.codegen.ClassBuilderFactory +import org.jetbrains.kotlin.codegen.ImplementationBodyCodegen +import org.jetbrains.kotlin.codegen.StackValue +import org.jetbrains.kotlin.codegen.extensions.ClassBuilderInterceptorExtension +import org.jetbrains.kotlin.codegen.extensions.ExpressionCodegenExtension +import org.jetbrains.kotlin.com.intellij.mock.MockProject +import org.jetbrains.kotlin.com.intellij.openapi.extensions.Extensions +import org.jetbrains.kotlin.com.intellij.openapi.project.Project +import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFile +import org.jetbrains.kotlin.com.intellij.testFramework.LightVirtualFile +import org.jetbrains.kotlin.config.CompilerConfiguration +import org.jetbrains.kotlin.container.ComponentProvider +import org.jetbrains.kotlin.container.useInstance +import org.jetbrains.kotlin.context.ProjectContext +import org.jetbrains.kotlin.descriptors.ClassDescriptor +import org.jetbrains.kotlin.descriptors.ConstructorDescriptor +import org.jetbrains.kotlin.descriptors.DeclarationDescriptor +import org.jetbrains.kotlin.descriptors.FunctionDescriptor +import org.jetbrains.kotlin.descriptors.Modality +import org.jetbrains.kotlin.descriptors.ModuleDescriptor +import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor +import org.jetbrains.kotlin.descriptors.PackageFragmentProvider +import org.jetbrains.kotlin.descriptors.PropertyDescriptor +import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor +import org.jetbrains.kotlin.diagnostics.Diagnostic +import org.jetbrains.kotlin.diagnostics.DiagnosticSink +import org.jetbrains.kotlin.extensions.CollectAdditionalSourcesExtension +import org.jetbrains.kotlin.extensions.CompilerConfigurationExtension +import org.jetbrains.kotlin.extensions.DeclarationAttributeAltererExtension +import org.jetbrains.kotlin.extensions.PreprocessedVirtualFileFactoryExtension +import org.jetbrains.kotlin.extensions.StorageComponentContainerContributor +import org.jetbrains.kotlin.incremental.components.LookupLocation +import org.jetbrains.kotlin.incremental.components.LookupTracker +import org.jetbrains.kotlin.ir.declarations.IrFile +import org.jetbrains.kotlin.name.Name +import org.jetbrains.kotlin.platform.TargetPlatform +import org.jetbrains.kotlin.psi.KtDeclaration +import org.jetbrains.kotlin.psi.KtFile +import org.jetbrains.kotlin.psi.KtImportInfo +import org.jetbrains.kotlin.psi.KtModifierListOwner +import org.jetbrains.kotlin.resolve.BindingContext +import org.jetbrains.kotlin.resolve.BindingTrace +import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall +import org.jetbrains.kotlin.resolve.checkers.DeclarationChecker +import org.jetbrains.kotlin.resolve.checkers.DeclarationCheckerContext +import org.jetbrains.kotlin.resolve.diagnostics.DiagnosticSuppressor +import org.jetbrains.kotlin.resolve.extensions.ExtraImportsProviderExtension +import org.jetbrains.kotlin.resolve.extensions.SyntheticResolveExtension +import org.jetbrains.kotlin.resolve.jvm.extensions.AnalysisHandlerExtension +import org.jetbrains.kotlin.resolve.jvm.extensions.PackageFragmentProviderExtension +import org.jetbrains.kotlin.resolve.lazy.LazyClassContext +import org.jetbrains.kotlin.resolve.lazy.declarations.ClassMemberDeclarationProvider +import org.jetbrains.kotlin.resolve.lazy.declarations.PackageMemberDeclarationProvider +import org.jetbrains.kotlin.resolve.scopes.ResolutionScope +import org.jetbrains.kotlin.resolve.scopes.SyntheticScope +import org.jetbrains.kotlin.storage.StorageManager +import org.jetbrains.kotlin.synthetic.JavaSyntheticPropertiesScope +import org.jetbrains.kotlin.synthetic.SyntheticScopeProviderExtension +import org.jetbrains.kotlin.types.KotlinType +import org.jetbrains.kotlin.types.checker.KotlinTypeChecker +import java.lang.reflect.Field +import java.lang.reflect.Modifier +import java.util.ArrayList + +interface InternalRegistry: ConfigSyntax { + + fun intercept(): List>> + + private fun registerPostAnalysisContextEnrichment(project: Project, ctx: CompilerContext) { + cli { + AnalysisHandlerExtension.registerExtension(project, object : AnalysisHandlerExtension { + override fun doAnalysis( + project: Project, + module: ModuleDescriptor, + projectContext: ProjectContext, + files: Collection, + bindingTrace: BindingTrace, + componentProvider: ComponentProvider + ): AnalysisResult? { + ctx.module = module + ctx.files = files + ctx.componentProvider = componentProvider + return null + } + }) + } + ide { + PackageFragmentProviderExtension.registerExtension(project, object : PackageFragmentProviderExtension { + override fun getPackageFragmentProvider(project: Project, module: ModuleDescriptor, storageManager: StorageManager, trace: BindingTrace, moduleInfo: ModuleInfo?, lookupTracker: LookupTracker): PackageFragmentProvider? { + println("getPackageFragmentProvider") + return null + } + }) + StorageComponentContainerContributor.registerExtension( + project, + object : StorageComponentContainerContributor { + override fun registerModuleComponents( + container: org.jetbrains.kotlin.container.StorageComponentContainer, + platform: TargetPlatform, + moduleDescriptor: ModuleDescriptor + ) { + ctx.module = moduleDescriptor + ctx.componentProvider = container + super.registerModuleComponents(container, platform, moduleDescriptor) + } + } + ) + } + } + + fun registerProjectComponents( + project: MockProject, + configuration: CompilerConfiguration + ) { + ide { + println("registerProjectComponents!!!! CALLED in IDEA!!!! something is wrong.") + } + registerMetaComponents(project, configuration) + } + + fun registerMetaComponents( + project: Project, + configuration: CompilerConfiguration + ) { + println("Project allowed extensions: ${Extensions.getArea(project).extensionPoints.toList().joinToString("\n")}") + cli { + println("it's the CLI plugin") + } + ide { + println("it's the IDEA plugin") + } + val messageCollector: MessageCollector? = + cli { configuration.get(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY, MessageCollector.NONE) } + + val ctx = CompilerContext(project, messageCollector) + registerPostAnalysisContextEnrichment(project, ctx) + + val initialPhases = listOf(Name.identifier("Initial setup") to listOf( + enableIr(), + compilerContextService(), + registerKindAwareTypeChecker(), + registerMetaAnalyzer() + )) + (initialPhases + intercept()).forEach { (plugin, phases) -> + println("Registering plugin: $plugin extensions: $phases") + phases.forEach { currentPhase -> + fun registerPhase(phase: ExtensionPhase): Unit { + if (phase is ExtraImports) registerExtraImports(project, phase, ctx) + if (phase is PreprocessedVirtualFileFactory) registerPreprocessedVirtualFileFactory(project, phase, ctx) + if (phase is Config) registerCompilerConfiguration(project, phase, ctx) + if (phase is StorageComponentContainer) registerStorageComponentContainer(project, phase, ctx) + if (phase is CollectAdditionalSources) registerCollectAdditionalSources(project, phase, ctx) + if (phase is AnalysisHandler) registerAnalysisHandler(project, phase, ctx) + if (phase is ClassBuilder) registerClassBuilder(project, phase, ctx) + if (phase is Codegen) registerCodegen(project, phase, ctx) + if (phase is DeclarationAttributeAlterer) registerDeclarationAttributeAlterer(project, phase, ctx) + if (phase is PackageProvider) packageFragmentProvider(project, phase, ctx) + if (phase is SyntheticResolver) registerSyntheticResolver(project, phase, ctx) + if (phase is IRGeneration) registerIRGeneration(project, phase, ctx) + if (phase is SyntheticScopeProvider) registerSyntheticScopeProvider(project, phase, ctx) + if (phase is DiagnosticsSuppressor) registerDiagnosticSuppressor(project, phase, ctx) + if (phase is Composite) phase.phases.map(::registerPhase) + } + registerPhase(currentPhase) + ctx.registerIdeExclusivePhase(currentPhase) + } + } + } + + fun registerMetaAnalyzer(): ExtensionPhase = ExtensionPhase.Empty + fun registerDiagnosticSuppressor( + project: Project, + phase: DiagnosticsSuppressor, + ctx: CompilerContext + ) { + Extensions.getArea(project).getExtensionPoint(DiagnosticSuppressor.EP_NAME) + .registerExtension(object : DiagnosticSuppressor { + override fun isSuppressed(diagnostic: Diagnostic): Boolean = + phase.run { ctx.isSuppressed(diagnostic) } + }) + } + + fun registerExtraImports(project: Project, phase: ExtraImports, ctx: CompilerContext) { + ExtraImportsProviderExtension.registerExtension(project, object : ExtraImportsProviderExtension { + override fun getExtraImports(ktFile: KtFile): Collection = + phase.run { ctx.extraImports(ktFile) } + + }) + } + + fun registerPreprocessedVirtualFileFactory(project: Project, phase: PreprocessedVirtualFileFactory, ctx: CompilerContext) { + PreprocessedVirtualFileFactoryExtension.registerExtension(project, object : PreprocessedVirtualFileFactoryExtension { + override fun createPreprocessedFile(file: VirtualFile?): VirtualFile? = + phase.run { ctx.createPreprocessedFile(file) } + + override fun createPreprocessedLightFile(file: LightVirtualFile?): LightVirtualFile? = + phase.run { ctx.createPreprocessedLightFile(file) } + + override fun isPassThrough(): Boolean = + phase.run { ctx.isPassThrough() } + }) + } + + fun registerSyntheticScopeProvider(project: Project, phase: SyntheticScopeProvider, ctx: CompilerContext) { + SyntheticScopeProviderExtension.registerExtension(project, object : SyntheticScopeProviderExtension { + override fun getScopes(moduleDescriptor: ModuleDescriptor, javaSyntheticPropertiesScope: JavaSyntheticPropertiesScope): List = + phase.run { + listOf( + object : SyntheticScope.Default() { + override fun getSyntheticConstructor(constructor: ConstructorDescriptor): ConstructorDescriptor? = + phase.run { ctx.syntheticConstructor(constructor) } + + override fun getSyntheticConstructors(scope: ResolutionScope): Collection = + phase.run { ctx.syntheticConstructors(scope) } + + override fun getSyntheticConstructors(scope: ResolutionScope, name: Name, location: LookupLocation): Collection = + phase.run { ctx.syntheticConstructors(scope, name, location) } + + override fun getSyntheticExtensionProperties(receiverTypes: Collection, location: LookupLocation): Collection = + phase.run { ctx.syntheticExtensionProperties(receiverTypes, location) } + + override fun getSyntheticExtensionProperties(receiverTypes: Collection, name: Name, location: LookupLocation): Collection = + phase.run { ctx.syntheticExtensionProperties(receiverTypes, name, location) } + + override fun getSyntheticMemberFunctions(receiverTypes: Collection): Collection = + phase.run { ctx.syntheticMemberFunctions(receiverTypes) } + + override fun getSyntheticMemberFunctions(receiverTypes: Collection, name: Name, location: LookupLocation): Collection = + phase.run { ctx.syntheticMemberFunctions(receiverTypes, name, location) } + + override fun getSyntheticStaticFunctions(scope: ResolutionScope): Collection = + phase.run { ctx.syntheticStaticFunctions(scope) } + + override fun getSyntheticStaticFunctions(scope: ResolutionScope, name: Name, location: LookupLocation): Collection = + phase.run { ctx.syntheticStaticFunctions(scope, name, location) } + } + ) + } + }) + } + + fun registerIRGeneration( + project: Project, + phase: IRGeneration, + compilerContext: CompilerContext + ) { + IrGenerationExtension.registerExtension(project, object : IrGenerationExtension { + override fun generate( + file: IrFile, + backendContext: BackendContext, + bindingContext: BindingContext + ) { + phase.run { compilerContext.generate(file, backendContext, bindingContext) } + } + }) + } + + fun registerSyntheticResolver( + project: Project, + phase: SyntheticResolver, + compilerContext: CompilerContext + ) { + SyntheticResolveExtension.registerExtension(project, object : SyntheticResolveExtension { + override fun addSyntheticSupertypes(thisDescriptor: ClassDescriptor, supertypes: MutableList) { + phase.run { compilerContext.addSyntheticSupertypes(thisDescriptor, supertypes) } + } + + override fun generateSyntheticClasses( + thisDescriptor: ClassDescriptor, + name: Name, + ctx: LazyClassContext, + declarationProvider: ClassMemberDeclarationProvider, + result: MutableSet + ) { + phase.run { + compilerContext.generateSyntheticClasses( + thisDescriptor, + name, + ctx, + declarationProvider, + result + ) + } + } + + override fun generateSyntheticClasses( + thisDescriptor: PackageFragmentDescriptor, + name: Name, + ctx: LazyClassContext, + declarationProvider: PackageMemberDeclarationProvider, + result: MutableSet + ) { + phase.run { + compilerContext.generatePackageSyntheticClasses( + thisDescriptor, + name, + ctx, + declarationProvider, + result + ) + } + } + + override fun generateSyntheticMethods( + thisDescriptor: ClassDescriptor, + name: Name, + bindingContext: BindingContext, + fromSupertypes: List, + result: MutableCollection + ) { + phase.run { + compilerContext.generateSyntheticMethods( + thisDescriptor, + name, + bindingContext, + fromSupertypes, + result + ) + } + } + + override fun generateSyntheticProperties( + thisDescriptor: ClassDescriptor, + name: Name, + bindingContext: BindingContext, + fromSupertypes: ArrayList, + result: MutableSet + ) { + phase.run { + compilerContext.generateSyntheticProperties( + thisDescriptor, + name, + bindingContext, + fromSupertypes, + result + ) + } + } + + override fun getSyntheticCompanionObjectNameIfNeeded(thisDescriptor: ClassDescriptor): Name? { + return phase.run { compilerContext.getSyntheticCompanionObjectNameIfNeeded(thisDescriptor) } + } + + override fun getSyntheticFunctionNames(thisDescriptor: ClassDescriptor): List { + return phase.run { compilerContext.getSyntheticFunctionNames(thisDescriptor) } + } + + override fun getSyntheticNestedClassNames(thisDescriptor: ClassDescriptor): List { + return phase.run { compilerContext.getSyntheticNestedClassNames(thisDescriptor) } + } + }) + } + + fun packageFragmentProvider( + project: Project, + phase: PackageProvider, + ctx: CompilerContext + ) { + PackageFragmentProviderExtension.registerExtension( + project, + object : PackageFragmentProviderExtension { + override fun getPackageFragmentProvider( + project: Project, + module: ModuleDescriptor, + storageManager: StorageManager, + trace: BindingTrace, + moduleInfo: ModuleInfo?, + lookupTracker: LookupTracker + ): PackageFragmentProvider? { + return phase.run { + ctx.getPackageFragmentProvider( + project, + module, + storageManager, + trace, + moduleInfo, + lookupTracker + ) + } + } + }) + } + + fun registerDeclarationAttributeAlterer( + project: Project, + phase: DeclarationAttributeAlterer, + ctx: CompilerContext + ) { + DeclarationAttributeAltererExtension.registerExtension( + project, + object : DeclarationAttributeAltererExtension { + override fun refineDeclarationModality( + modifierListOwner: KtModifierListOwner, + declaration: DeclarationDescriptor?, + containingDeclaration: DeclarationDescriptor?, + currentModality: Modality, + bindingContext: BindingContext, + isImplicitModality: Boolean + ): Modality? { + return phase.run { + ctx.refineDeclarationModality( + modifierListOwner, + declaration, + containingDeclaration, + currentModality, + bindingContext, + isImplicitModality + ) + } + } + }) + } + + fun registerCodegen(project: Project, phase: Codegen, ctx: CompilerContext) { + ExpressionCodegenExtension.registerExtension(project, object : ExpressionCodegenExtension { + override fun applyFunction( + receiver: StackValue, + resolvedCall: ResolvedCall<*>, + c: ExpressionCodegenExtension.Context + ): StackValue? { + return phase.run { ctx.applyFunction(receiver, resolvedCall, c) } + } + + override fun applyProperty( + receiver: StackValue, + resolvedCall: ResolvedCall<*>, + c: ExpressionCodegenExtension.Context + ): StackValue? { + return phase.run { ctx.applyProperty(receiver, resolvedCall, c) } + } + + override fun generateClassSyntheticParts(codegen: ImplementationBodyCodegen) { + phase.run { ctx.generateClassSyntheticParts(codegen) } + } + }) + } + + fun registerStorageComponentContainer( + project: Project, + phase: StorageComponentContainer, + ctx: CompilerContext + ) { + StorageComponentContainerContributor.registerExtension( + project, + DelegatingContributorChecker(phase, ctx) + ) + } + + fun registerCollectAdditionalSources( + project: Project, + phase: CollectAdditionalSources, + ctx: CompilerContext + ) { + cli { + CollectAdditionalSourcesExtension.registerExtension( + project, + object : CollectAdditionalSourcesExtension { + override fun collectAdditionalSourcesAndUpdateConfiguration( + knownSources: Collection, + configuration: CompilerConfiguration, + project: Project + ): Collection = phase.run { + ctx.collectAdditionalSourcesAndUpdateConfiguration(knownSources, configuration, project) + } + } + ) + } + } + + fun registerAnalysisHandler( + project: Project, + phase: AnalysisHandler, + ctx: CompilerContext + ) { + cli { + AnalysisHandlerExtension.registerExtension(project, object : AnalysisHandlerExtension { + override fun analysisCompleted( + project: Project, + module: ModuleDescriptor, + bindingTrace: BindingTrace, + files: Collection + ): AnalysisResult? = phase.run { ctx.analysisCompleted(project, module, bindingTrace, files) } + + override fun doAnalysis( + project: Project, + module: ModuleDescriptor, + projectContext: ProjectContext, + files: Collection, + bindingTrace: BindingTrace, + componentProvider: ComponentProvider + ): AnalysisResult? { + return phase.run { + ctx.doAnalysis( + project, + module, + projectContext, + files, + bindingTrace, + componentProvider + ) + } + } + }) + } + } + + fun registerClassBuilder( + project: Project, + phase: ClassBuilder, + ctx: CompilerContext + ) { + ClassBuilderInterceptorExtension.registerExtension( + project, + object : ClassBuilderInterceptorExtension { + override fun interceptClassBuilderFactory( + interceptedFactory: ClassBuilderFactory, + bindingContext: BindingContext, + diagnostics: DiagnosticSink + ): ClassBuilderFactory = + phase.run { + ctx.interceptClassBuilder(interceptedFactory, bindingContext, diagnostics) + } + }) + } + + fun registerCompilerConfiguration( + project: Project, + phase: Config, + ctx: CompilerContext + ) { + CompilerConfigurationExtension.registerExtension( + project, + object : CompilerConfigurationExtension { + override fun updateConfiguration(configuration: CompilerConfiguration) { + phase.run { ctx.updateConfiguration(configuration) } + } + }) + } + + class DelegatingContributorChecker(val phase: StorageComponentContainer, val ctx: CompilerContext) : StorageComponentContainerContributor, DeclarationChecker { + + override fun registerModuleComponents(container: org.jetbrains.kotlin.container.StorageComponentContainer, platform: TargetPlatform, moduleDescriptor: ModuleDescriptor) { + phase.run { ctx.registerModuleComponents(container, moduleDescriptor) } + } + + override fun check(declaration: KtDeclaration, descriptor: DeclarationDescriptor, context: DeclarationCheckerContext) { + phase.run { ctx.check(declaration, descriptor, context) } + } + } + + fun registerKindAwareTypeChecker(): StorageComponentContainer = + storageComponent( + registerModuleComponents = { container, moduleDescriptor -> + val defaultTypeChecker = KotlinTypeChecker.DEFAULT + if (defaultTypeChecker !is KindAwareTypeChecker) { //nasty hack ahead to circumvent the ability to replace the Kotlin type checker + val defaultTypeCheckerField = KotlinTypeChecker::class.java.getDeclaredField("DEFAULT") + setFinalStatic(defaultTypeCheckerField, KindAwareTypeChecker(defaultTypeChecker)) + } + }, + check = { _, _, _ -> + } + ) + + /** + * The nastier bits + */ + @Throws(Exception::class) + private fun setFinalStatic(field: Field, newValue: Any) { + field.isAccessible = true + + val modifiersField = Field::class.java.getDeclaredField("modifiers") + modifiersField.isAccessible = true + modifiersField.setInt(field, field.modifiers and Modifier.FINAL.inv()) + + field.set(null, newValue) + } + + + fun compilerContextService(): StorageComponentContainer = + storageComponent( + registerModuleComponents = { container, moduleDescriptor -> + container.useInstance(this) + }, + check = { declaration, descriptor, context -> + } + ) + + fun CompilerContext.registerIdeExclusivePhase(currentPhase: ExtensionPhase): Unit {} +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/CompilerContext.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/CompilerContext.kt new file mode 100644 index 00000000000..6ed82e522d1 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/CompilerContext.kt @@ -0,0 +1,34 @@ +package arrow.meta.phases + +import arrow.meta.phases.analysis.MetaAnalyzer +import org.jetbrains.kotlin.cli.common.messages.MessageCollector +import org.jetbrains.kotlin.com.intellij.openapi.project.Project +import org.jetbrains.kotlin.container.ComponentProvider +import org.jetbrains.kotlin.container.get +import org.jetbrains.kotlin.descriptors.ModuleDescriptor +import org.jetbrains.kotlin.psi.KtFile +import org.jetbrains.kotlin.psi.KtPsiFactory + +class CompilerContext( + val project: Project, + val messageCollector: MessageCollector? +) { + + val ktPsiElementFactory: KtPsiFactory = KtPsiFactory(project, false) + val ctx: CompilerContext = this + lateinit var module: ModuleDescriptor + lateinit var files: Collection + lateinit var componentProvider: ComponentProvider + private lateinit var metaAnalyzerField: MetaAnalyzer + + val analyzer: MetaAnalyzer? + get() = when { + ::metaAnalyzerField.isInitialized -> metaAnalyzerField + ::componentProvider.isInitialized -> { + //TODO sometimes we get in here before the DI container has finished composing and it blows up + metaAnalyzerField = componentProvider.get() + metaAnalyzerField + } + else -> null + } +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/Composite.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/Composite.kt new file mode 100644 index 00000000000..ec70e9155a6 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/Composite.kt @@ -0,0 +1,8 @@ +package arrow.meta.phases + +data class Composite(val phases: List): ExtensionPhase { + companion object { + operator fun invoke(vararg phases: ExtensionPhase): ExtensionPhase = + Composite(phases.toList()) + } +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/Extension.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/Extension.kt new file mode 100644 index 00000000000..fb2c623fb31 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/Extension.kt @@ -0,0 +1,6 @@ +package arrow.meta.phases + +interface ExtensionPhase { + object Empty : ExtensionPhase +} + diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/AnalysisHandler.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/AnalysisHandler.kt new file mode 100644 index 00000000000..ce654c044ed --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/AnalysisHandler.kt @@ -0,0 +1,29 @@ +package arrow.meta.phases.analysis + +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.ExtensionPhase +import org.jetbrains.kotlin.analyzer.AnalysisResult +import org.jetbrains.kotlin.com.intellij.openapi.project.Project +import org.jetbrains.kotlin.container.ComponentProvider +import org.jetbrains.kotlin.context.ProjectContext +import org.jetbrains.kotlin.descriptors.ModuleDescriptor +import org.jetbrains.kotlin.psi.KtFile +import org.jetbrains.kotlin.resolve.BindingTrace + +interface AnalysisHandler : ExtensionPhase { + fun CompilerContext.doAnalysis( + project: Project, + module: ModuleDescriptor, + projectContext: ProjectContext, + files: Collection, + bindingTrace: BindingTrace, + componentProvider: ComponentProvider + ): AnalysisResult? + + fun CompilerContext.analysisCompleted( + project: Project, + module: ModuleDescriptor, + bindingTrace: BindingTrace, + files: Collection + ): AnalysisResult? +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/CollectAdditionalSources.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/CollectAdditionalSources.kt new file mode 100644 index 00000000000..4c6906a1e21 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/CollectAdditionalSources.kt @@ -0,0 +1,15 @@ +package arrow.meta.phases.analysis + +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.ExtensionPhase +import org.jetbrains.kotlin.com.intellij.openapi.project.Project +import org.jetbrains.kotlin.config.CompilerConfiguration +import org.jetbrains.kotlin.psi.KtFile + +interface CollectAdditionalSources : ExtensionPhase { + fun CompilerContext.collectAdditionalSourcesAndUpdateConfiguration( + knownSources: Collection, + configuration: CompilerConfiguration, + project: Project + ): Collection +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/ExtraImports.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/ExtraImports.kt new file mode 100644 index 00000000000..29d0cae0061 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/ExtraImports.kt @@ -0,0 +1,10 @@ +package arrow.meta.phases.analysis + +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.ExtensionPhase +import org.jetbrains.kotlin.psi.KtFile +import org.jetbrains.kotlin.psi.KtImportInfo + +interface ExtraImports : ExtensionPhase { + fun CompilerContext.extraImports(ktFile: KtFile): Collection +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/KtUtils.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/KtUtils.kt new file mode 100644 index 00000000000..36e0d70ba06 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/KtUtils.kt @@ -0,0 +1,55 @@ +package arrow.meta.phases.analysis + +import org.jetbrains.kotlin.psi.KtClass +import org.jetbrains.kotlin.psi.KtElement +import org.jetbrains.kotlin.psi.KtExpression +import org.jetbrains.kotlin.psi.KtFunction +import org.jetbrains.kotlin.psi.KtNamedFunction +import org.jetbrains.kotlin.psi.KtTreeVisitorVoid +import org.jetbrains.kotlin.psi.psiUtil.blockExpressionsOrSingle +import org.jetbrains.kotlin.psi.psiUtil.getValueParameters +import org.jetbrains.kotlin.psi2ir.deparenthesize + +fun KtClass.renderValueParameters(): String = + if (getValueParameters().isEmpty()) "" + else getValueParameters().joinToString(separator = ", ") { it.text } + +fun KtClass.renderSuperTypes(): String = + superTypeListEntries.joinToString(", ") { it.name.orEmpty() } + +fun KtClass.renderTypeParametersWithVariance(): String = + typeParameters.joinToString(separator = ", ") { it.text } + +fun KtNamedFunction.renderTypeParametersWithVariance(): String? = + if (typeParameters.isNotEmpty()) typeParameters.joinToString(separator = ", ") { it.text } + else null + +fun KtNamedFunction.renderValueParameters(): String? = + if (valueParameters.isEmpty()) null + else valueParameters.joinToString(separator = ", ") { it.text } + + +fun KtFunction.body(): KtExpression? = + bodyExpression ?: bodyBlockExpression + +fun KtFunction.bodyExpressionText(): String = + bodyBlockExpression?.blockExpressionsOrSingle() + ?.joinToString("\n") { it.deparenthesize().text } + ?.trim() + ?: bodyExpression?.text + ?: "" + +fun KtElement.dfs(f: (KtElement) -> Boolean): List { + val found = arrayListOf() + accept(object : KtTreeVisitorVoid() { + override fun visitKtElement(element: KtElement) { + val result = f(element) + if (result) found.add(element) + super.visitKtElement(element) + } + }) + return found +} + +fun String.removeReturn(): String = + replace("return ", "") \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/MetaAnalyzer.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/MetaAnalyzer.kt new file mode 100644 index 00000000000..2e22cf83446 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/MetaAnalyzer.kt @@ -0,0 +1,56 @@ +package arrow.meta.phases.analysis + +import arrow.meta.phases.CompilerContext +import arrow.meta.quotes.Quote +import org.jetbrains.kotlin.analyzer.AnalysisResult +import org.jetbrains.kotlin.analyzer.ModuleInfo +import org.jetbrains.kotlin.com.intellij.openapi.editor.Document +import org.jetbrains.kotlin.com.intellij.openapi.project.Project +import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFile +import org.jetbrains.kotlin.descriptors.ClassDescriptor +import org.jetbrains.kotlin.descriptors.ModuleDescriptor +import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor +import org.jetbrains.kotlin.descriptors.PropertyDescriptor +import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor +import org.jetbrains.kotlin.name.FqName +import org.jetbrains.kotlin.name.Name +import org.jetbrains.kotlin.psi.KtElement +import org.jetbrains.kotlin.psi.KtFile +import org.jetbrains.kotlin.resolve.BindingTrace +import org.jetbrains.kotlin.resolve.BodyResolver +import org.jetbrains.kotlin.resolve.StatementFilter +import org.jetbrains.kotlin.resolve.lazy.ResolveSession +import org.jetbrains.kotlin.resolve.lazy.declarations.ClassMemberDeclarationProvider +import org.jetbrains.kotlin.resolve.lazy.declarations.PackageMemberDeclarationProvider +import org.jetbrains.kotlin.types.KotlinType + +interface MetaAnalyzer { + + fun

CompilerContext.subscribeToEditorHooks( + project: Project, + quoteFactory: Quote.Factory, + match: K.() -> Boolean, + map: S.(K) -> List, + transformation: (VirtualFile, Document) -> Pair? + ) + + fun createBodyResolver( + resolveSession: ResolveSession, + trace: BindingTrace, + file: KtFile, + statementFilter: StatementFilter + ): BodyResolver + + fun KtFile.metaAnalysys(moduleInfo: ModuleInfo? = null): AnalysisResult + fun metaPackageFragments(module: ModuleDescriptor, fqName: FqName): List + fun metaSubPackagesOf(module: ModuleDescriptor, fqName: FqName, nameFilter: (Name) -> Boolean): Collection + fun metaSyntheticFunctionNames(thisDescriptor: ClassDescriptor): List + fun metaSyntheticNestedClassNames(thisDescriptor: ClassDescriptor): List + fun metaSyntheticMethods(name: Name, thisDescriptor: ClassDescriptor): List + fun metaSyntheticProperties(name: Name, thisDescriptor: ClassDescriptor): List + fun metaSyntheticPackageClasses(name: Name, packageDescriptor: PackageFragmentDescriptor, declarationProvider: PackageMemberDeclarationProvider): List + fun metaCompanionObjectNameIfNeeded(classDescriptor: ClassDescriptor): Name? + fun metaSyntheticSupertypes(classDescriptor: ClassDescriptor): List + fun metaSyntheticClasses(name: Name, classDescriptor: ClassDescriptor, declarationProvider: ClassMemberDeclarationProvider): List + fun populateSyntheticCache(document: com.intellij.openapi.editor.Document, transformation: (com.intellij.openapi.vfs.VirtualFile, com.intellij.openapi.editor.Document) -> Pair?) +} diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/MetaFileViewProvider.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/MetaFileViewProvider.kt new file mode 100644 index 00000000000..aac0a16e337 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/MetaFileViewProvider.kt @@ -0,0 +1,14 @@ +package arrow.meta.phases.analysis + +import org.jetbrains.kotlin.com.intellij.openapi.editor.Document +import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFile +import org.jetbrains.kotlin.com.intellij.psi.PsiManager +import org.jetbrains.kotlin.com.intellij.psi.SingleRootFileViewProvider + +class MetaFileViewProvider( + psiManager: PsiManager, + virtualFile: VirtualFile, + val transformation: (Document?) -> Document? +) : SingleRootFileViewProvider(psiManager, virtualFile) { + override fun getDocument(): Document? = transformation(super.getDocument()) +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/PreprocessedVirtualFileFactory.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/PreprocessedVirtualFileFactory.kt new file mode 100644 index 00000000000..2ce30625fb2 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/analysis/PreprocessedVirtualFileFactory.kt @@ -0,0 +1,12 @@ +package arrow.meta.phases.analysis + +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.ExtensionPhase +import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFile +import org.jetbrains.kotlin.com.intellij.testFramework.LightVirtualFile + +interface PreprocessedVirtualFileFactory : ExtensionPhase { + fun CompilerContext.isPassThrough(): Boolean + fun CompilerContext.createPreprocessedFile(file: VirtualFile?): VirtualFile? + fun CompilerContext.createPreprocessedLightFile(file: LightVirtualFile?): LightVirtualFile? +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/codegen/asm/ClassBuilder.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/codegen/asm/ClassBuilder.kt new file mode 100644 index 00000000000..116af8ad9ad --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/codegen/asm/ClassBuilder.kt @@ -0,0 +1,15 @@ +package arrow.meta.phases.codegen.asm + +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.ExtensionPhase +import org.jetbrains.kotlin.codegen.ClassBuilderFactory +import org.jetbrains.kotlin.diagnostics.DiagnosticSink +import org.jetbrains.kotlin.resolve.BindingContext + +interface ClassBuilder : ExtensionPhase { + fun CompilerContext.interceptClassBuilder( + interceptedFactory: ClassBuilderFactory, + bindingContext: BindingContext, + diagnostics: DiagnosticSink + ): ClassBuilderFactory +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/codegen/asm/Codegen.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/codegen/asm/Codegen.kt new file mode 100644 index 00000000000..8805c6d2262 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/codegen/asm/Codegen.kt @@ -0,0 +1,24 @@ +package arrow.meta.phases.codegen.asm + +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.ExtensionPhase +import org.jetbrains.kotlin.codegen.ImplementationBodyCodegen +import org.jetbrains.kotlin.codegen.StackValue +import org.jetbrains.kotlin.codegen.extensions.ExpressionCodegenExtension +import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall + +interface Codegen : ExtensionPhase { + fun CompilerContext.applyFunction( + receiver: StackValue, + resolvedCall: ResolvedCall<*>, + c: ExpressionCodegenExtension.Context + ): StackValue? + + fun CompilerContext.applyProperty( + receiver: StackValue, + resolvedCall: ResolvedCall<*>, + c: ExpressionCodegenExtension.Context + ): StackValue? + + fun CompilerContext.generateClassSyntheticParts(codegen: ImplementationBodyCodegen): Unit +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/codegen/ir/IRGeneration.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/codegen/ir/IRGeneration.kt new file mode 100644 index 00000000000..398ca110c28 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/codegen/ir/IRGeneration.kt @@ -0,0 +1,17 @@ +package arrow.meta.phases.codegen.ir + +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.ExtensionPhase +import org.jetbrains.kotlin.backend.common.BackendContext +import org.jetbrains.kotlin.ir.declarations.IrFile +import org.jetbrains.kotlin.resolve.BindingContext + +interface IRGeneration : ExtensionPhase { + + fun CompilerContext.generate( + file: IrFile, + backendContext: BackendContext, + bindingContext: BindingContext + ) + +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/codegen/ir/IrUtils.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/codegen/ir/IrUtils.kt new file mode 100644 index 00000000000..45c9bff2234 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/codegen/ir/IrUtils.kt @@ -0,0 +1,136 @@ +package arrow.meta.phases.codegen.ir + +import arrow.meta.phases.CompilerContext +import org.jetbrains.kotlin.backend.common.BackendContext +import org.jetbrains.kotlin.com.intellij.psi.PsiElement +import org.jetbrains.kotlin.config.LanguageVersionSettingsImpl +import org.jetbrains.kotlin.container.get +import org.jetbrains.kotlin.descriptors.ClassDescriptor +import org.jetbrains.kotlin.descriptors.FunctionDescriptor +import org.jetbrains.kotlin.descriptors.PackageViewDescriptor +import org.jetbrains.kotlin.descriptors.PropertyDescriptor +import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET +import org.jetbrains.kotlin.ir.expressions.IrBody +import org.jetbrains.kotlin.ir.expressions.IrCall +import org.jetbrains.kotlin.ir.expressions.IrConstructorCall +import org.jetbrains.kotlin.ir.expressions.IrFunctionAccessExpression +import org.jetbrains.kotlin.ir.expressions.impl.IrCallImpl +import org.jetbrains.kotlin.ir.expressions.impl.IrConstructorCallImpl +import org.jetbrains.kotlin.ir.symbols.IrSymbol +import org.jetbrains.kotlin.ir.util.constructors +import org.jetbrains.kotlin.ir.util.referenceFunction +import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi +import org.jetbrains.kotlin.psi.KtClassBody +import org.jetbrains.kotlin.psi.KtDeclaration +import org.jetbrains.kotlin.psi.KtElement +import org.jetbrains.kotlin.psi.KtFile +import org.jetbrains.kotlin.psi.KtModifierList +import org.jetbrains.kotlin.psi.KtObjectDeclaration +import org.jetbrains.kotlin.psi.KtParameter +import org.jetbrains.kotlin.psi.KtPrimaryConstructor +import org.jetbrains.kotlin.psi.KtPureClassOrObject +import org.jetbrains.kotlin.psi.KtSecondaryConstructor +import org.jetbrains.kotlin.psi.KtSuperTypeListEntry +import org.jetbrains.kotlin.psi2ir.Psi2IrConfiguration +import org.jetbrains.kotlin.psi2ir.Psi2IrTranslator +import org.jetbrains.kotlin.psi2ir.generators.DeclarationGenerator +import org.jetbrains.kotlin.psi2ir.generators.GeneratorContext +import org.jetbrains.kotlin.psi2ir.generators.createBodyGenerator +import org.jetbrains.kotlin.resolve.descriptorUtil.parents +import org.jetbrains.kotlin.resolve.lazy.LazyClassContext + +class IrUtils( + val backendContext: BackendContext, + val compilerContext: CompilerContext +) { + + private val psi2IrTranslator: Psi2IrTranslator = Psi2IrTranslator(LanguageVersionSettingsImpl.DEFAULT, Psi2IrConfiguration(ignoreErrors = true)) + private val generatorContext: GeneratorContext = + psi2IrTranslator.createGeneratorContext(compilerContext.module, compilerContext.componentProvider.get().trace.bindingContext) + private val declarationGenerator: DeclarationGenerator = + DeclarationGenerator(generatorContext) + + fun irBody(ownerSymbol: IrSymbol, code: String): IrBody = + declarationGenerator.createBodyGenerator(ownerSymbol).generateExpressionBody( + compilerContext.ktPsiElementFactory.createExpression(code) + ) + + private fun packageSyntheticDeclaration( + packageDescriptor: PackageViewDescriptor + ): KtPureClassOrObject = + object : KtPureClassOrObject { + override fun getName(): String? = packageDescriptor.name.asString() + override fun isLocal(): Boolean = false + + override fun getDeclarations(): List = emptyList() + override fun getSuperTypeListEntries(): List = emptyList() + override fun getCompanionObjects(): List = emptyList() + + override fun hasExplicitPrimaryConstructor(): Boolean = false + override fun hasPrimaryConstructor(): Boolean = false + override fun getPrimaryConstructor(): KtPrimaryConstructor? = null + override fun getPrimaryConstructorModifierList(): KtModifierList? = null + override fun getPrimaryConstructorParameters(): List = emptyList() + override fun getSecondaryConstructors(): List = emptyList() + + override fun getPsiOrParent(): KtElement = (packageDescriptor.findPsi() ?: parent!!) as KtElement + override fun getParent(): PsiElement? = packageDescriptor.parents.first().findPsi() + @Suppress("USELESS_ELVIS") + override fun getContainingKtFile(): KtFile = + // in theory `containingKtFile` is `@NotNull` but in practice EA-114080 + psiOrParent.containingKtFile + ?: throw IllegalStateException("containingKtFile was null for $parent of ${parent?.javaClass}") + + override fun getBody(): KtClassBody? = null + } + + fun IrFunctionAccessExpression.defaultValues(): List = + symbol.descriptor.valueParameters + .mapNotNull { it.findPsi() as? KtParameter } + .mapNotNull { it.defaultValue?.text } + + fun FunctionDescriptor.irCall(): IrCall { + val irFunctionSymbol = backendContext.ir.symbols.externalSymbolTable.referenceFunction(this) + return IrCallImpl( + startOffset = UNDEFINED_OFFSET, + endOffset = UNDEFINED_OFFSET, + type = irFunctionSymbol.owner.returnType, + symbol = irFunctionSymbol, + descriptor = irFunctionSymbol.owner.descriptor, + typeArgumentsCount = irFunctionSymbol.owner.descriptor.typeParameters.size, + valueArgumentsCount = irFunctionSymbol.owner.descriptor.valueParameters.size + ) + } + + fun PropertyDescriptor.irGetterCall(): IrCall? { + val irField = backendContext.ir.symbols.externalSymbolTable.referenceField(this) + return irField.owner.correspondingPropertySymbol?.owner?.getter?.symbol?.let { irSimpleFunctionSymbol -> + IrCallImpl( + startOffset = UNDEFINED_OFFSET, + endOffset = UNDEFINED_OFFSET, + type = irSimpleFunctionSymbol.owner.returnType, + symbol = irSimpleFunctionSymbol, + descriptor = irSimpleFunctionSymbol.owner.descriptor, + typeArgumentsCount = irSimpleFunctionSymbol.owner.descriptor.typeParameters.size, + valueArgumentsCount = irSimpleFunctionSymbol.owner.descriptor.valueParameters.size + ) + } + } + + fun ClassDescriptor.irConstructorCall(): IrConstructorCall? { + val irClass = backendContext.ir.symbols.externalSymbolTable.referenceClass(this) + return irClass.constructors.firstOrNull()?.let { irConstructorSymbol -> + IrConstructorCallImpl( + startOffset = UNDEFINED_OFFSET, + endOffset = UNDEFINED_OFFSET, + type = irConstructorSymbol.owner.returnType, + symbol = irConstructorSymbol, + descriptor = irConstructorSymbol.owner.descriptor, + typeArgumentsCount = irConstructorSymbol.owner.descriptor.typeParameters.size, + valueArgumentsCount = irConstructorSymbol.owner.descriptor.valueParameters.size, + constructorTypeArgumentsCount = declaredTypeParameters.size + ) + } + } + +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/config/Config.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/config/Config.kt new file mode 100644 index 00000000000..f23917f6eda --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/config/Config.kt @@ -0,0 +1,9 @@ +package arrow.meta.phases.config + +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.ExtensionPhase +import org.jetbrains.kotlin.config.CompilerConfiguration + +interface Config : ExtensionPhase { + fun CompilerContext.updateConfiguration(configuration: CompilerConfiguration): Unit +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/config/StorageComponentContainer.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/config/StorageComponentContainer.kt new file mode 100644 index 00000000000..bf51dbdecfc --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/config/StorageComponentContainer.kt @@ -0,0 +1,21 @@ +package arrow.meta.phases.config + +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.ExtensionPhase +import org.jetbrains.kotlin.descriptors.DeclarationDescriptor +import org.jetbrains.kotlin.descriptors.ModuleDescriptor +import org.jetbrains.kotlin.psi.KtDeclaration +import org.jetbrains.kotlin.resolve.checkers.DeclarationCheckerContext + +interface StorageComponentContainer : ExtensionPhase { + fun CompilerContext.registerModuleComponents( + container: org.jetbrains.kotlin.container.StorageComponentContainer, + moduleDescriptor: ModuleDescriptor + ): Unit + + fun CompilerContext.check( + declaration: KtDeclaration, + descriptor: DeclarationDescriptor, + context: DeclarationCheckerContext + ): Unit +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/resolve/DeclarationAttributeAlterer.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/resolve/DeclarationAttributeAlterer.kt new file mode 100644 index 00000000000..e9723088a1d --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/resolve/DeclarationAttributeAlterer.kt @@ -0,0 +1,19 @@ +package arrow.meta.phases.resolve + +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.ExtensionPhase +import org.jetbrains.kotlin.descriptors.DeclarationDescriptor +import org.jetbrains.kotlin.descriptors.Modality +import org.jetbrains.kotlin.psi.KtModifierListOwner +import org.jetbrains.kotlin.resolve.BindingContext + +interface DeclarationAttributeAlterer : ExtensionPhase { + fun CompilerContext.refineDeclarationModality( + modifierListOwner: KtModifierListOwner, + declaration: DeclarationDescriptor?, + containingDeclaration: DeclarationDescriptor?, + currentModality: Modality, + bindingContext: BindingContext, + isImplicitModality: Boolean + ): Modality? +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/resolve/PackageProvider.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/resolve/PackageProvider.kt new file mode 100644 index 00000000000..82ec9bd665c --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/resolve/PackageProvider.kt @@ -0,0 +1,22 @@ +package arrow.meta.phases.resolve + +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.ExtensionPhase +import org.jetbrains.kotlin.analyzer.ModuleInfo +import org.jetbrains.kotlin.com.intellij.openapi.project.Project +import org.jetbrains.kotlin.descriptors.ModuleDescriptor +import org.jetbrains.kotlin.descriptors.PackageFragmentProvider +import org.jetbrains.kotlin.incremental.components.LookupTracker +import org.jetbrains.kotlin.resolve.BindingTrace +import org.jetbrains.kotlin.storage.StorageManager + +interface PackageProvider : ExtensionPhase { + fun CompilerContext.getPackageFragmentProvider( + project: Project, + module: ModuleDescriptor, + storageManager: StorageManager, + trace: BindingTrace, + moduleInfo: ModuleInfo?, + lookupTracker: LookupTracker + ): PackageFragmentProvider? +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/resolve/diagnostics/DiagnosticsSuppressor.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/resolve/diagnostics/DiagnosticsSuppressor.kt new file mode 100644 index 00000000000..affaea0a8c2 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/resolve/diagnostics/DiagnosticsSuppressor.kt @@ -0,0 +1,9 @@ +package arrow.meta.phases.resolve.diagnostics + +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.ExtensionPhase +import org.jetbrains.kotlin.diagnostics.Diagnostic + +interface DiagnosticsSuppressor : ExtensionPhase { + fun CompilerContext.isSuppressed(diagnostic: Diagnostic): Boolean +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/resolve/synthetics/SyntheticResolver.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/resolve/synthetics/SyntheticResolver.kt new file mode 100644 index 00000000000..07c655a63f4 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/resolve/synthetics/SyntheticResolver.kt @@ -0,0 +1,60 @@ +package arrow.meta.phases.resolve.synthetics + +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.ExtensionPhase +import org.jetbrains.kotlin.descriptors.ClassDescriptor +import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor +import org.jetbrains.kotlin.descriptors.PropertyDescriptor +import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor +import org.jetbrains.kotlin.name.Name +import org.jetbrains.kotlin.resolve.BindingContext +import org.jetbrains.kotlin.resolve.lazy.LazyClassContext +import org.jetbrains.kotlin.resolve.lazy.declarations.ClassMemberDeclarationProvider +import org.jetbrains.kotlin.resolve.lazy.declarations.PackageMemberDeclarationProvider +import org.jetbrains.kotlin.types.KotlinType +import java.util.ArrayList + +interface SyntheticResolver : ExtensionPhase { + fun CompilerContext.addSyntheticSupertypes( + thisDescriptor: ClassDescriptor, + supertypes: MutableList + ): Unit + + fun CompilerContext.generateSyntheticClasses( + thisDescriptor: ClassDescriptor, + name: Name, + ctx: LazyClassContext, + declarationProvider: ClassMemberDeclarationProvider, + result: MutableSet + ): Unit + + fun CompilerContext.generatePackageSyntheticClasses( + thisDescriptor: PackageFragmentDescriptor, + name: Name, + ctx: LazyClassContext, + declarationProvider: PackageMemberDeclarationProvider, + result: MutableSet + ): Unit + + fun CompilerContext.generateSyntheticMethods( + thisDescriptor: ClassDescriptor, + name: Name, + bindingContext: BindingContext, + fromSupertypes: List, + result: MutableCollection + ): Unit + + fun CompilerContext.generateSyntheticProperties( + thisDescriptor: ClassDescriptor, + name: Name, + bindingContext: BindingContext, + fromSupertypes: ArrayList, + result: MutableSet + ): Unit + + fun CompilerContext.getSyntheticCompanionObjectNameIfNeeded(thisDescriptor: ClassDescriptor): Name? + + fun CompilerContext.getSyntheticFunctionNames(thisDescriptor: ClassDescriptor): List + + fun CompilerContext.getSyntheticNestedClassNames(thisDescriptor: ClassDescriptor): List +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/resolve/synthetics/SyntheticScopeProvider.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/resolve/synthetics/SyntheticScopeProvider.kt new file mode 100644 index 00000000000..bda0ebc469b --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/phases/resolve/synthetics/SyntheticScopeProvider.kt @@ -0,0 +1,23 @@ +package arrow.meta.phases.resolve.synthetics + +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.ExtensionPhase +import org.jetbrains.kotlin.descriptors.ConstructorDescriptor +import org.jetbrains.kotlin.descriptors.FunctionDescriptor +import org.jetbrains.kotlin.descriptors.PropertyDescriptor +import org.jetbrains.kotlin.incremental.components.LookupLocation +import org.jetbrains.kotlin.name.Name +import org.jetbrains.kotlin.resolve.scopes.ResolutionScope +import org.jetbrains.kotlin.types.KotlinType + +interface SyntheticScopeProvider : ExtensionPhase { + fun CompilerContext.syntheticConstructor(constructor: ConstructorDescriptor): ConstructorDescriptor? + fun CompilerContext.syntheticConstructors(scope: ResolutionScope): Collection + fun CompilerContext.syntheticConstructors(scope: ResolutionScope, name: Name, location: LookupLocation): Collection + fun CompilerContext.syntheticExtensionProperties(receiverTypes: Collection, location: LookupLocation): Collection + fun CompilerContext.syntheticExtensionProperties(receiverTypes: Collection, name: Name, location: LookupLocation): Collection + fun CompilerContext.syntheticMemberFunctions(receiverTypes: Collection): Collection + fun CompilerContext.syntheticMemberFunctions(receiverTypes: Collection, name: Name, location: LookupLocation): Collection + fun CompilerContext.syntheticStaticFunctions(scope: ResolutionScope): Collection + fun CompilerContext.syntheticStaticFunctions(scope: ResolutionScope, name: Name, location: LookupLocation): Collection +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/plugins/comprehensions/ComprehensionsPlugin.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/plugins/comprehensions/ComprehensionsPlugin.kt new file mode 100644 index 00000000000..fd6d91fff72 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/plugins/comprehensions/ComprehensionsPlugin.kt @@ -0,0 +1,57 @@ +package arrow.meta.plugins.comprehensions + +import arrow.meta.phases.ExtensionPhase +import arrow.meta.MetaComponentRegistrar +import arrow.meta.phases.analysis.body +import arrow.meta.phases.analysis.bodyExpressionText +import arrow.meta.phases.analysis.dfs +import arrow.meta.phases.analysis.removeReturn +import arrow.meta.quotes.func +import org.jetbrains.kotlin.name.Name +import org.jetbrains.kotlin.psi.KtElement +import org.jetbrains.kotlin.psi.KtExpression +import org.jetbrains.kotlin.psi.KtFunction +import org.jetbrains.kotlin.psi.KtUnaryExpression + +/** + * 1. replace all instances of bind application with flatMap: + * - Anonymous application using a generated flatMapArg0, flatMapArg1 etc name for each binding found + * 2. flatMap replacements takes care scoping all bodies with as many nested flatMap as bindings are found within a body by folding inside out all binds + */ +val MetaComponentRegistrar.comprehensions: Pair> + get() = + Name.identifier("comprehensions") to + meta( + func(KtFunction::hasBindings) { + listOf( + """ + |$modality $visibility fun <$typeParameters> $receiver.$name($valueParameters): $returnType = + | ${it.replaceBindingsWithFlatMap(it.bindings())} + |""" + ) + } + ) + +private fun KtFunction.replaceBindingsWithFlatMap(bindings: List): String = + bindings.foldRightIndexed(bodyExpressionText()) { n, binding, currentBody -> + val (replacedBody, receiver) = flatMapBodyAndReceiver(binding, currentBody, n) + "$receiver.flatMap { flatMapArg$n -> $replacedBody }" + }.removeReturn() + +private fun flatMapBodyAndReceiver(binding: KtElement, currentBody: String, n: Int): Pair = + when { + binding.isBindingCall() && binding is KtUnaryExpression -> binding.text.let { + currentBody.replaceFirst(it, "flatMapArg$n") to + binding.baseExpression?.text + } + else -> null to null + } + +private fun KtElement.isBindingCall(): Boolean = + this is KtUnaryExpression && operationReference.getReferencedName() == "!" // TODO enhance with type checks and validation + +private fun KtFunction.hasBindings(): Boolean = + body()?.bindings()?.isNotEmpty() == true + +private fun KtExpression.bindings(): List = + dfs { it.isBindingCall() }.reversed() \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/plugins/dummy/DummyPlugin.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/plugins/dummy/DummyPlugin.kt new file mode 100644 index 00000000000..295e9542728 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/plugins/dummy/DummyPlugin.kt @@ -0,0 +1,37 @@ +package arrow.meta.plugins.dummy + +import arrow.meta.phases.ExtensionPhase +import arrow.meta.MetaComponentRegistrar +import arrow.meta.quotes.classOrObject +import org.jetbrains.kotlin.name.Name + +val MetaComponentRegistrar.dummy: Pair> + get() = + Name.identifier("Dummy") to + meta( + classOrObject({ name == "TestClass" }) { c -> + println("Processing Dummy: ${c.name}") + listOfNotNull( + """ + |interface SynthSuperType { + | fun fromSynthSuperType(): Unit = println("fromSynthSuperType") + |} + """, + """ + |$modality $visibility $kind $name<$typeParameters>($valueParameters): SynthSuperType { + | $body + | fun test2(): String = "Boom!" + | fun test(): Unit = println(test2()) + | + | val xx: Int = 1 + | val yy: Double = 0.0 + | + | class ZZ + | class XX + | + | companion object Factory + |} + |""" + ) + } + ) diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/plugins/higherkind/HigherKindPlugin.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/plugins/higherkind/HigherKindPlugin.kt new file mode 100644 index 00000000000..e3cd2ef3668 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/plugins/higherkind/HigherKindPlugin.kt @@ -0,0 +1,77 @@ +package arrow.meta.plugins.higherkind + +import arrow.meta.phases.ExtensionPhase +import arrow.meta.MetaComponentRegistrar +import arrow.meta.quotes.classOrObject +import org.jetbrains.kotlin.name.FqName +import org.jetbrains.kotlin.name.Name +import org.jetbrains.kotlin.psi.KtClass +import org.jetbrains.kotlin.psi.KtFile + + +val MetaComponentRegistrar.higherKindedTypes: Pair> + get() = + Name.identifier("higherKindedTypes") to + meta( + additionalSources( + collectAdditionalSourcesAndUpdateConfiguration = { knownSources, configuration, project -> + println("additionalSources.collectAdditionalSourcesAndUpdateConfiguration: $knownSources") + knownSources + } + ), + classOrObject(::isHigherKindedType) { c -> + println("Processing Higher Kind: ${c.name}") + listOfNotNull( + /** Kind Marker **/ + "class For$name private constructor() { companion object }", + /** Single arg type alias **/ + "typealias ${name}Of<${typeParameters.invariant}> = arrow.Kind${c.kindAritySuffix}", + /** generate partial aliases if this kind has > 1 type parameters **/ + if (c.arity > 1) + "typealias ${name}PartialOf<${c.partialTypeParameters}> = arrow.Kind${c.partialKindAritySuffix}" + else null, + /** Class redefinition with kinded super type **/ + """ + |$modality $visibility $kind $name<$typeParameters>($valueParameters) : ${name}Of<${typeParameters.invariant}> { + | $body + |} + |""" + ) + } + ) + +private val Name.invariant: String + get() = identifier + .replace("out ", "") + .replace("in ", "") + +private val KtClass.partialTypeParameters: String + get() = typeParameters + .dropLast(1) + .joinToString(separator = ", ") { + it.nameAsSafeName.identifier + } + +private val KtClass.arity: Int + get() = typeParameters.size + +private val KtClass.kindAritySuffix: String + get() = arity.let { if (it > 1) "$it" else "" } + +private val KtClass.partialKindAritySuffix: String + get() = (arity - 1).let { if (it > 1) "$it" else "" } + +fun isHigherKindedType(ktClass: KtClass): Boolean = + ktClass.fqName?.asString()?.startsWith("arrow.Kind") != true && + !ktClass.isAnnotation() && + ktClass.typeParameters.isNotEmpty() && + ktClass.parent is KtFile + +val kindName: FqName = FqName("arrow.Kind") + +val FqName.kindTypeAliasName: Name + get() { + val segments = pathSegments() + val simpleName = segments.lastOrNull() ?: Name.special("index not ready") + return Name.identifier("${simpleName}Of") + } diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/plugins/higherkind/KindAwareTypeChecker.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/plugins/higherkind/KindAwareTypeChecker.kt new file mode 100644 index 00000000000..c92ce7dbda2 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/plugins/higherkind/KindAwareTypeChecker.kt @@ -0,0 +1,41 @@ +package arrow.meta.plugins.higherkind + +import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe +import org.jetbrains.kotlin.types.KotlinType +import org.jetbrains.kotlin.types.checker.KotlinTypeChecker +import org.jetbrains.kotlin.types.getAbbreviation +import org.jetbrains.kotlin.types.typeUtil.getImmediateSuperclassNotAny +import java.lang.IllegalStateException + +class KindAwareTypeChecker(val typeChecker: KotlinTypeChecker) : KotlinTypeChecker by typeChecker { + override fun isSubtypeOf(p0: KotlinType, p1: KotlinType): Boolean { + val subType = p0 + val superType = p1 + val isKind: Boolean = + (subType.isKind() || superType.isKind()) && (subType.typeAliasMatch(superType) || superType.typeAliasMatch(subType)) + val result = isKind || typeChecker.isSubtypeOf(p0, p1) + println("KindAwareTypeChecker.isSubtypeOf: $p0 <-> $p1 = $result") + return result + } + + override fun equalTypes(p0: KotlinType, p1: KotlinType): Boolean { + //println("KindAwareTypeChecker.equalTypes: $p0 <-> $p1") + val result = typeChecker.equalTypes(p0, p1) + println("KindAwareTypeChecker.equalTypes: $p0 <-> $p1 = $result") + return result + } + + private fun KotlinType.isKind(): Boolean = + constructor.declarationDescriptor?.fqNameSafe == kindName + + private fun KotlinType.typeAliasMatch(other: KotlinType): Boolean = + try { + val a = getAbbreviation()?.constructor?.declarationDescriptor?.fqNameSafe?.shortName() + val b = other.constructor.declarationDescriptor?.fqNameSafe?.shortName() + ?: other.getImmediateSuperclassNotAny()?.constructor?.declarationDescriptor?.fqNameSafe?.kindTypeAliasName + a == b || a == other.getImmediateSuperclassNotAny()?.constructor?.declarationDescriptor?.fqNameSafe?.kindTypeAliasName + } catch (e: IllegalStateException) { //rarely shortName throws + false + } + +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/plugins/typeclasses/TypeClassesPlugin.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/plugins/typeclasses/TypeClassesPlugin.kt new file mode 100644 index 00000000000..bd9c357607a --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/plugins/typeclasses/TypeClassesPlugin.kt @@ -0,0 +1,297 @@ +package arrow.meta.plugins.typeclasses + +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.ExtensionPhase +import arrow.meta.MetaComponentRegistrar +import arrow.meta.phases.codegen.ir.IrUtils +import arrow.meta.quotes.func +import arrow.meta.quotes.get +import arrow.meta.quotes.ktFile +import arrow.meta.dsl.platform.ide +import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation +import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity +import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor +import org.jetbrains.kotlin.descriptors.ClassDescriptor +import org.jetbrains.kotlin.descriptors.ClassifierDescriptor +import org.jetbrains.kotlin.descriptors.DeclarationDescriptor +import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithVisibility +import org.jetbrains.kotlin.descriptors.FunctionDescriptor +import org.jetbrains.kotlin.descriptors.Modality +import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor +import org.jetbrains.kotlin.descriptors.PropertyDescriptor +import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor +import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor +import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor +import org.jetbrains.kotlin.descriptors.Visibilities +import org.jetbrains.kotlin.descriptors.annotations.Annotations +import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor +import org.jetbrains.kotlin.descriptors.impl.ReceiverParameterDescriptorImpl +import org.jetbrains.kotlin.ir.expressions.IrFunctionAccessExpression +import org.jetbrains.kotlin.ir.expressions.mapValueParameters +import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi +import org.jetbrains.kotlin.name.FqName +import org.jetbrains.kotlin.name.Name +import org.jetbrains.kotlin.psi.KtCallableDeclaration +import org.jetbrains.kotlin.psi.KtDeclarationWithBody +import org.jetbrains.kotlin.psi.KtExpression +import org.jetbrains.kotlin.psi.KtParameter +import org.jetbrains.kotlin.psi.psiUtil.blockExpressionsOrSingle +import org.jetbrains.kotlin.resolve.BindingContext +import org.jetbrains.kotlin.resolve.FunctionDescriptorUtil +import org.jetbrains.kotlin.resolve.OverloadChecker +import org.jetbrains.kotlin.resolve.StatementFilter +import org.jetbrains.kotlin.resolve.calls.results.TypeSpecificityComparator +import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo +import org.jetbrains.kotlin.resolve.calls.smartcasts.ImplicitSmartCasts +import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe +import org.jetbrains.kotlin.resolve.descriptorUtil.module +import org.jetbrains.kotlin.resolve.lazy.ResolveSession +import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor +import org.jetbrains.kotlin.resolve.lazy.descriptors.findPackageFragmentForFile +import org.jetbrains.kotlin.resolve.scopes.LexicalScope +import org.jetbrains.kotlin.resolve.scopes.LexicalScopeImpl +import org.jetbrains.kotlin.resolve.scopes.LexicalScopeKind +import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver +import org.jetbrains.kotlin.resolve.scopes.receivers.ExtensionReceiver +import org.jetbrains.kotlin.types.IntersectionTypeConstructor +import org.jetbrains.kotlin.types.KotlinType +import org.jetbrains.kotlin.types.KotlinTypeFactory +import org.jetbrains.kotlin.types.SimpleType +import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf +import org.jetbrains.kotlin.utils.addToStdlib.safeAs + +const val WithMarker = "`*`" +val ExtensionAnnotation = FqName("arrow.extension") + +val MetaComponentRegistrar.typeClasses: Pair> + get() = + Name.identifier("typeClasses") to + meta( + func( + match = { hasExtensionValueParameters() }, + map = { func -> + listOf( + """ + |$modality $visibility fun <$typeParameters> $receiver.$name($valueParameters): $returnType = + | ${func.extensionValueParamNames().run(body)} + |""" + ) + } + ), + ideSyntheticBodyResolution(), + irFunctionAccess { mapValueParameterExtensions(it) } + ) + +private fun MetaComponentRegistrar.ideSyntheticBodyResolution(): ExtensionPhase = ide { + syntheticResolver( + generateSyntheticMethods = { thisDescriptor, name, bindingContext, fromSupertypes, result -> + thisDescriptor.safeAs()?.let { lazyDescriptor -> + val lazyClassContext: Any = lazyDescriptor["c"] + lazyClassContext.safeAs()?.let { session -> + result.firstOrNull { it.name == name }?.let { function -> + resolveBodyWithExtensionsScope(session, function) + } + println("typeclasses.syntheticResolver.generateSyntheticMethods: $thisDescriptor, $name, $fromSupertypes, $result") + } + } + } + ) +} ?: ExtensionPhase.Empty + + +private fun CompilerContext.resolveBodyWithExtensionsScope(session: ResolveSession, function: SimpleFunctionDescriptor): Unit { + function.findPsi().safeAs()?.let { ktCallable -> + val functionScope = session.declarationScopeProvider.getResolutionScopeForDeclaration(ktCallable) + val innerScope = FunctionDescriptorUtil.getFunctionInnerScope(functionScope, function, session.trace, OverloadChecker(TypeSpecificityComparator.NONE)) + val bodyResolver = analyzer?.createBodyResolver( + session, session.trace, ktCallable.containingKtFile, StatementFilter.NONE + ) + function.extensionReceiverParameter?.let { originalReceiver -> + val intersectedTypes = function.valueParameters.filter { it.shouldEnhanceScope() }.map { it.type } + val modifiedScope = function.valueParameters.scopeForExtensionParameters(innerScope) + val typeIntersection = + if (intersectedTypes.isNotEmpty()) { + val constructor = IntersectionTypeConstructor(intersectedTypes) + KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope( + Annotations.EMPTY, + constructor, + emptyList(), + false, + constructor.createScopeForKotlinType() + ) + } else null + typeIntersection?.let { uberExtendedType -> + //function.applySmartCast(originalReceiver, uberExtendedType, ktCallable, session) + bodyResolver?.resolveFunctionBody(DataFlowInfo.EMPTY, session.trace, ktCallable, function, modifiedScope) + } + } + } +} + +private fun SimpleFunctionDescriptor.applySmartCast( + originalReceiver: ReceiverParameterDescriptor, + uberExtendedType: SimpleType, + ktCallable: KtDeclarationWithBody, + session: ResolveSession +) { + val extensionReceiver = ExtensionReceiver(this, originalReceiver.type, null) + val smartCast = ImplicitSmartCasts(extensionReceiver, uberExtendedType) + ktCallable.blockExpressionsOrSingle().filterIsInstance().firstOrNull()?.let { expression -> + session.trace.record(BindingContext.IMPLICIT_RECEIVER_SMARTCAST, expression, smartCast) + ExpressionReceiver.create(expression, uberExtendedType, session.trace.bindingContext) + } +} + +private fun List.scopeForExtensionParameters(innerScope: LexicalScope): LexicalScope = + fold(innerScope) { currentScope, valueParameterDescriptor -> + val ownerDescriptor = AnonymousFunctionDescriptor(valueParameterDescriptor, valueParameterDescriptor.annotations, CallableMemberDescriptor.Kind.DECLARATION, valueParameterDescriptor.source, false) + val extensionReceiver = ExtensionReceiver(ownerDescriptor, valueParameterDescriptor.type, null) + val extensionReceiverParamDescriptor = ReceiverParameterDescriptorImpl(ownerDescriptor, extensionReceiver, ownerDescriptor.annotations) + ownerDescriptor.initialize(extensionReceiverParamDescriptor, null, valueParameterDescriptor.typeParameters, valueParameterDescriptor.valueParameters, valueParameterDescriptor.returnType, Modality.FINAL, valueParameterDescriptor.visibility) + LexicalScopeImpl(currentScope, ownerDescriptor, true, extensionReceiverParamDescriptor, LexicalScopeKind.FUNCTION_INNER_SCOPE) + } + +private fun ValueParameterDescriptor.shouldEnhanceScope(): Boolean { + val ktParameter = findPsi().safeAs() + return ktParameter?.hasExtensionDefaultValue() == true +} + +private fun List.run(body: Name): String = + fold(body.asString()) { acc, scope -> "$scope.run { $acc }" } + +private fun KtCallableDeclaration.extensionValueParamNames() = + valueParameters.filter { it.defaultValue?.text == WithMarker }.map { it.name } + +private fun KtCallableDeclaration.hasExtensionValueParameters(): Boolean = + valueParameters.any { it.hasExtensionDefaultValue() } + +fun KtParameter.hasExtensionDefaultValue(): Boolean = defaultValue?.text == WithMarker + +private fun IrUtils.mapValueParameterExtensions(expression: IrFunctionAccessExpression): IrFunctionAccessExpression? = + if (expression.defaultValues().contains(WithMarker)) { + expression.mapValueParameters { extensionCall(it) } + } else null + +private fun IrUtils.extensionCall(valueParameterDescriptor: ValueParameterDescriptor): IrFunctionAccessExpression? = + when (val extension = compilerContext.findExtension(valueParameterDescriptor)) { + is FunctionDescriptor -> extension.irCall() + is ClassDescriptor -> extension.irConstructorCall() + is PropertyDescriptor -> extension.irGetterCall() + else -> null + } + +private fun CompilerContext.findExtension(valueParameterDescriptor: ValueParameterDescriptor): DeclarationDescriptor? { + val extensionType = valueParameterDescriptor.type + val typeClass = extensionType.typeClassDescriptor() + val dataType = extensionType.dataTypeDescriptor() + val typeClassPackage = typeClass.packageFragmentDescriptor() + val dataTypePackage = dataType.packageFragmentDescriptor() + val internalPackages = modulePackages() + val internalExtensions = internalPackages.extensions(extensionType) + return if (dataTypePackage != null && + typeClassPackage != null) { + if ( + internalPackages.extensionsAreInternal(typeClassPackage, dataTypePackage, internalExtensions)) { + reportNonInternalOrphanExtension(extensionType, internalExtensions[0]) + } + val extensions = extensionType.resolveExtensions(internalExtensions, typeClassPackage, dataTypePackage) + when { + extensions.isEmpty() -> { + reportExtensionNotFound(extensionType) + null + } + extensions.size > 1 -> { + reportAmbiguousExtensions(extensionType, extensions) + null + } + else -> extensions[0] + } + } else null +} + +private fun List.extensions(extensionType: KotlinType): List = + flatMap { + it.findExtensionProof(extensionType) + }.distinctBy { it.name } + +private fun CompilerContext.modulePackages(): List = + files.toSet().flatMap { module.getPackage(it.packageFqName).fragments } + +private fun KotlinType.resolveExtensions( + internalExtensions: List, + typeClassPackage: PackageFragmentDescriptor, + dataTypePackage: PackageFragmentDescriptor +): List = + if (internalExtensions.isNotEmpty()) internalExtensions else { + val typeClassExtensions = typeClassPackage.findExtensionProof(this) + if (typeClassExtensions.isNotEmpty()) typeClassExtensions + else dataTypePackage.findExtensionProof(this) + } + +private fun List.extensionsAreInternal( + typeClassPackage: PackageFragmentDescriptor, + dataTypePackage: PackageFragmentDescriptor, + internalExtensions: List +): Boolean = (all { it != typeClassPackage && it != dataTypePackage } && //not the type class or data type module + internalExtensions.isNotEmpty() + && !internalExtensions.markedInternal()) + +private fun List.markedInternal(): Boolean = + isNotEmpty() && when (val extension = this[0]) { + is DeclarationDescriptorWithVisibility -> extension.visibility == Visibilities.INTERNAL + else -> false + } + +private fun CompilerContext.reportNonInternalOrphanExtension( + extensionType: KotlinType, + extension: DeclarationDescriptor +) { + messageCollector?.report( + CompilerMessageSeverity.ERROR, + """Orphan Extension $extension for $extensionType must be `internal`: + |```kotlin + |${extension.findPsi()?.text?.replaceFirst("@extension", "@extension internal")} + |``` + """.trimMargin(), + CompilerMessageLocation.create(null) + ) +} + +private fun CompilerContext.reportExtensionNotFound(extensionType: KotlinType): Unit { + messageCollector?.report( + CompilerMessageSeverity.ERROR, + "extension not found for $extensionType", + CompilerMessageLocation.create(null) + ) +} + +private fun CompilerContext.reportAmbiguousExtensions( + extensionType: KotlinType, + descriptors: List +): Unit { + messageCollector?.report( + CompilerMessageSeverity.ERROR, + """Expected a single @extension for [$extensionType] but found the following conflicting extensions: ${descriptors.joinToString() { it.fqNameSafe.asString() }}""".trimMargin(), + CompilerMessageLocation.create(null) + ) +} + +private fun PackageFragmentDescriptor.findExtensionProof(extensionType: KotlinType): List = + getMemberScope() + .getContributedDescriptors() + .filter { + it.annotations.findAnnotation(ExtensionAnnotation) != null && + it is FunctionDescriptor && it.returnType != module.builtIns.nothingType && it.returnType?.isSubtypeOf(extensionType) == true || + it is ClassDescriptor && it.typeConstructor.supertypes.contains(extensionType) || + it is PropertyDescriptor && it.type != module.builtIns.nothingType && it.type.isSubtypeOf(extensionType) + } + +private fun ClassifierDescriptor?.packageFragmentDescriptor(): PackageFragmentDescriptor? = + this?.ktFile()?.let { file -> this.module.findPackageFragmentForFile(file) } + +private fun KotlinType.dataTypeDescriptor(): ClassifierDescriptor? = + arguments[0].type.constructor.declarationDescriptor + +private fun KotlinType.typeClassDescriptor(): ClassifierDescriptor? = + constructor.declarationDescriptor + diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/ClassOrObject.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/ClassOrObject.kt new file mode 100644 index 00000000000..61f3b6b5e47 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/ClassOrObject.kt @@ -0,0 +1,62 @@ +package arrow.meta.quotes + +import arrow.meta.phases.analysis.renderSuperTypes +import arrow.meta.phases.analysis.renderTypeParametersWithVariance +import arrow.meta.phases.analysis.renderValueParameters +import org.jetbrains.kotlin.name.Name +import org.jetbrains.kotlin.psi.KtClass +import org.jetbrains.kotlin.psi.KtElement +import org.jetbrains.kotlin.psi.psiUtil.modalityModifierType +import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierType + +interface ClassOrObject : Quote { + + class ClassScope( + val modality: Name, + val visibility: Name, + val kind: Name, + val name: Name, + val typeParameters: Name, + val valueParameters: Name, + val supertypes: Name, + val body: Name + ) + + override fun transform(ktElement: KtClass): ClassScope = + ClassScope( + modality = Name.identifier(ktElement.modalityModifierType()?.value.orEmpty()), + visibility = Name.identifier(ktElement.visibilityModifierType()?.value.orEmpty()), + kind = Name.identifier(ktElement.getClassOrInterfaceKeyword()?.text.orEmpty()), + name = Name.identifier(ktElement.name ?: ""), + typeParameters = Name.identifier(ktElement.renderTypeParametersWithVariance()), + valueParameters = if (ktElement.isInterface()) Name.identifier("") + else Name.identifier(ktElement.renderValueParameters()), + supertypes = Name.identifier(ktElement.renderSuperTypes()), + body = Name.identifier(ktElement.body?.text?.drop(1)?.dropLast(1).orEmpty()) + ) + + override fun KtClass.cleanUserQuote(quoteDeclaration: String): String = + quoteDeclaration.trimMargin().let { + if (isInterface()) it.replace("interface (.*?)\\(\\)".toRegex(), "interface $1") + else it + }.replace("<>", "") + + override fun parse(template: String): KtClass = + quasiQuoteContext.compilerContext.ktPsiElementFactory.createClass(template) + + companion object : Quote.Factory { + override operator fun invoke( + quasiQuoteContext: QuasiQuoteContext, + containingDeclaration: KtElement, + match: KtClass.() -> Boolean, + map: ClassScope.(quotedTemplate: KtClass) -> List + ): ClassOrObject = + object : ClassOrObject { + override val quasiQuoteContext: QuasiQuoteContext = quasiQuoteContext + override fun KtClass.match(): Boolean = match(this) + override fun ClassScope.map(quotedTemplate: KtClass): List = map(quotedTemplate) + override val containingDeclaration: KtElement = containingDeclaration + } + } + +} diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/Func.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/Func.kt new file mode 100644 index 00000000000..5a1fa6655f6 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/Func.kt @@ -0,0 +1,68 @@ +package arrow.meta.quotes + +import arrow.meta.phases.analysis.renderTypeParametersWithVariance +import arrow.meta.phases.analysis.renderValueParameters +import org.jetbrains.kotlin.name.Name +import org.jetbrains.kotlin.psi.KtElement +import org.jetbrains.kotlin.psi.KtNamedFunction +import org.jetbrains.kotlin.psi.psiUtil.modalityModifierType +import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierType + +internal val EmptyElement: Name = Name.identifier("_EMPTY_ELEMENT_") + +interface Func : Quote { + + class FuncScope( + val modality: Name, + val visibility: Name, + val typeParameters: Name, + val receiver: Name, + val name: Name, + val valueParameters: Name, + val returnType: Name, + val body: Name + ) + + override fun transform(ktElement: KtNamedFunction): FuncScope = + FuncScope( + modality = ktElement.modalityModifierType()?.value?.let(Name::identifier) ?: EmptyElement, + visibility = ktElement.visibilityModifierType()?.value?.let(Name::identifier) ?: EmptyElement, + name = ktElement.nameAsName ?: EmptyElement, + typeParameters = ktElement.renderTypeParametersWithVariance()?.let(Name::identifier) + ?: EmptyElement, + receiver = ktElement.receiverTypeReference?.text?.let(Name::identifier) ?: EmptyElement, + valueParameters = ktElement.renderValueParameters()?.let(Name::identifier) ?: EmptyElement, + returnType = ktElement.typeReference?.text?.let(Name::identifier) ?: EmptyElement, + body = (ktElement.bodyExpression?.text + ?: ktElement.bodyBlockExpression?.text?.drop(1)?.dropLast(1) + )?.let(Name::identifier) ?: EmptyElement + ) + + override fun KtNamedFunction.cleanUserQuote(quoteDeclaration: String): String = + quoteDeclaration.trimMargin().removeEmptyTypeArgs() + + private fun String.removeEmptyTypeArgs(): String = + replace("<$EmptyElement>", "") + .replace("$EmptyElement.", "") + .replace("$EmptyElement", "") + + override fun parse(template: String): KtNamedFunction = + quasiQuoteContext.compilerContext.ktPsiElementFactory.createFunction(template) + + companion object : Quote.Factory { + override operator fun invoke( + quasiQuoteContext: QuasiQuoteContext, + containingDeclaration: KtElement, + match: KtNamedFunction.() -> Boolean, + map: FuncScope.(quotedTemplate: KtNamedFunction) -> List + ): Func = + object : Func { + override val quasiQuoteContext: QuasiQuoteContext = quasiQuoteContext + override fun KtNamedFunction.match(): Boolean = match(this) + override fun FuncScope.map(quotedTemplate: KtNamedFunction): List = map(quotedTemplate) + override val containingDeclaration: KtElement = containingDeclaration + } + } + +} + diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/MetaTreeVisitor.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/MetaTreeVisitor.kt new file mode 100644 index 00000000000..c8147d20eb6 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/MetaTreeVisitor.kt @@ -0,0 +1,5 @@ +package arrow.meta.quotes + +import org.jetbrains.kotlin.psi.KtTreeVisitorVoid + +abstract class MetaTreeVisitor : KtTreeVisitorVoid() \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/QuasiQuoteContext.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/QuasiQuoteContext.kt new file mode 100644 index 00000000000..6038950c445 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/QuasiQuoteContext.kt @@ -0,0 +1,18 @@ +package arrow.meta.quotes + +import arrow.meta.phases.CompilerContext +import org.jetbrains.kotlin.container.get +import org.jetbrains.kotlin.resolve.BindingContext +import org.jetbrains.kotlin.resolve.BindingTrace +import org.jetbrains.kotlin.resolve.lazy.LazyDeclarationResolver + +interface QuasiQuoteContext { + val compilerContext: CompilerContext + + companion object { + operator fun invoke(compilerContext: CompilerContext) = + object : QuasiQuoteContext { + override val compilerContext: CompilerContext = compilerContext + } + } +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/Quote.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/Quote.kt new file mode 100644 index 00000000000..0f950d77dba --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/Quote.kt @@ -0,0 +1,622 @@ +package arrow.meta.quotes + +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.ExtensionPhase +import arrow.meta.MetaComponentRegistrar +import arrow.meta.phases.analysis.MetaAnalyzer +import arrow.meta.phases.analysis.MetaFileViewProvider +import arrow.meta.dsl.platform.cli +import arrow.meta.dsl.platform.ide +import org.jetbrains.kotlin.analyzer.AnalysisResult +import org.jetbrains.kotlin.analyzer.ModuleInfo +import org.jetbrains.kotlin.com.intellij.openapi.editor.Document +import org.jetbrains.kotlin.com.intellij.openapi.project.Project +import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFile +import org.jetbrains.kotlin.com.intellij.psi.PsiElement +import org.jetbrains.kotlin.com.intellij.psi.PsiManager +import org.jetbrains.kotlin.com.intellij.psi.SingleRootFileViewProvider +import org.jetbrains.kotlin.descriptors.ClassDescriptor +import org.jetbrains.kotlin.descriptors.ClassKind +import org.jetbrains.kotlin.descriptors.DeclarationDescriptor +import org.jetbrains.kotlin.descriptors.FunctionDescriptor +import org.jetbrains.kotlin.descriptors.Modality +import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor +import org.jetbrains.kotlin.descriptors.PackageViewDescriptor +import org.jetbrains.kotlin.descriptors.SourceElement +import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor +import org.jetbrains.kotlin.descriptors.Visibilities +import org.jetbrains.kotlin.descriptors.annotations.Annotations +import org.jetbrains.kotlin.descriptors.impl.TypeParameterDescriptorImpl +import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi +import org.jetbrains.kotlin.name.Name +import org.jetbrains.kotlin.psi.KtClass +import org.jetbrains.kotlin.psi.KtClassOrObject +import org.jetbrains.kotlin.psi.KtDeclaration +import org.jetbrains.kotlin.psi.KtElement +import org.jetbrains.kotlin.psi.KtFile +import org.jetbrains.kotlin.psi.KtFunction +import org.jetbrains.kotlin.psi.KtNamedFunction +import org.jetbrains.kotlin.psi.KtObjectDeclaration +import org.jetbrains.kotlin.psi.KtTypeReference +import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType +import org.jetbrains.kotlin.psi.synthetics.SyntheticClassOrObjectDescriptor +import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe +import org.jetbrains.kotlin.resolve.lazy.LazyClassContext +import org.jetbrains.kotlin.resolve.lazy.declarations.ClassMemberDeclarationProvider +import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProvider +import org.jetbrains.kotlin.resolve.lazy.declarations.PackageMemberDeclarationProvider +import org.jetbrains.kotlin.types.KotlinType +import org.jetbrains.kotlin.types.KotlinTypeFactory +import org.jetbrains.kotlin.types.TypeProjectionImpl +import org.jetbrains.kotlin.types.Variance +import org.jetbrains.kotlin.utils.addToStdlib.safeAs + +/** + * A declaration quasi quote matches tree in the synthetic resolution and gives + * users the chance to transform them before they are processed by the Kotlin compiler. + */ +interface Quote

{ + + val containingDeclaration: P + + /** + * Provides access to compiler context services and factories including the binding trace + */ + val quasiQuoteContext: QuasiQuoteContext + + /** + * Turn a string template into a [KtElement] + */ + fun parse(template: String): K + + /** + * Returns a String representation of what a match for a tree may look like. For example: + * ``` + * "fun <$typeArgs> $name($params): $returnType = $body" + * ``` + */ + fun K.match(): Boolean + + /** + * Given real matches of a [quotedTemplate] the user is then given a chance to transform it into a new tree + * where also uses code as a template + */ + fun S.map(quotedTemplate: K): List + + interface Factory

{ + operator fun invoke( + quasiQuoteContext: QuasiQuoteContext, + containingDeclaration: P, + match: K.() -> Boolean, + map: S.(quotedTemplate: K) -> List + ): Quote + } + + fun transform(ktElement: K): S + + fun K.cleanUserQuote(quoteDeclaration: String): String = quoteDeclaration + + fun process(ktElement: K): QuoteTransformation? { + return if (ktElement.match()) { + // a new scope is transformed + val transformedScope = transform(ktElement) + // the user transforms the expression into a new list of declarations + val declarations = transformedScope.map(ktElement).map { quoteDeclaration -> + val declaration = + quasiQuoteContext.compilerContext.ktPsiElementFactory + .createDeclaration(ktElement.cleanUserQuote(quoteDeclaration)) + declaration + } + if (declarations.isEmpty()) null + else QuoteTransformation(ktElement, declarations) + } else null + } + +} + +fun MetaComponentRegistrar.func( + match: KtFunction.() -> Boolean, + map: Func.FuncScope.(KtFunction) -> List +): ExtensionPhase = + quote(Func, match, map) + +fun MetaComponentRegistrar.classOrObject( + match: KtClass.() -> Boolean, + map: ClassOrObject.ClassScope.(KtClass) -> List +): ExtensionPhase = + quote(ClassOrObject, match, map) + +inline fun

> MetaAnalyzer.runMetaCompilation( + compilerContext: CompilerContext, + project: Project, + virtualFile: VirtualFile, + document: Document, + moduleInfo: ModuleInfo, + quoteFactory: Quote.Factory, + noinline match: K.() -> Boolean, + noinline map: S.(K) -> List +): Pair = compilerContext.run { + val originFakeFile = KtFile(SingleRootFileViewProvider( + project.getComponent(PsiManager::class.java), + virtualFile, + false + ), true) + val analyzableFile = ktPsiElementFactory.createAnalyzableFile(virtualFile.name, document.text, originFakeFile) + val (file, transformations) = processKtFile(analyzableFile, quoteFactory, match, map) + val transformedFile = transformFile(file, transformations) + transformedFile to transformedFile.metaAnalysys(moduleInfo) +} + + +@Suppress("UNCHECKED_CAST") +inline fun

> MetaComponentRegistrar.quote( + quoteFactory: Quote.Factory, + noinline match: K.() -> Boolean, + noinline map: S.(K) -> List +): ExtensionPhase = + cli { + analysys( + doAnalysis = { _, _, _, files, _, _ -> + files as ArrayList + //files.clear() + val fileMutations = processFiles(files, quoteFactory, match, map) + updateFiles(files, fileMutations) + null + }, + analysisCompleted = { project, module, bindingTrace, files -> + null + } + ) + } ?: ExtensionPhase.Empty +// +// ide { +// println("Register SYNTH RESOLVER IN IDEA") +// ExtensionPhase.CompositePhase( +// packageFragmentProvider { project, module, storageManager, trace, moduleInfo, lookupTracker -> +// analyzer?.run { +// moduleInfo?.let { info -> +// subscribeToEditorHooks(project, quoteFactory, match, map) { virtualFile, document -> +// runMetaCompilation(this@packageFragmentProvider, project, virtualFile, document, info, quoteFactory, match, map) +// } +//// +//// val (file, analysysResult) = runMetaCompilation(this@packageFragmentProvider, project, virtualFile, document, info, quoteFactory, match, map) +//// populateSyntheticCache(doc) +// } +// } +// object : PackageFragmentProvider { +// override fun getPackageFragments(fqName: FqName): List { +// val result = analyzer?.run { +// storageManager.createRecursionTolerantLazyValue({ +// metaPackageFragments(module, fqName) +// }, emptyList()).invoke() +// } ?: emptyList() +// println("PackageFragmentProvider.getPackageFragments: $fqName $result") +// return result +// } +// +// override fun getSubPackagesOf(fqName: FqName, nameFilter: (Name) -> Boolean): Collection { +// val result = analyzer?.run { +// storageManager.createRecursionTolerantLazyValue({ +// metaSubPackagesOf(module, fqName, nameFilter) +// }, emptyList()).invoke() +// } ?: emptyList() +// println("PackageFragmentProvider.metaSubPackagesOf: $fqName $result") +// return result +// } +// +// +// } +// }, +// syntheticResolver( +// addSyntheticSupertypes = { thisDescriptor, supertypes -> +// analyzer?.run { +// val synthetic: List = metaSyntheticSupertypes(thisDescriptor) +// println("MetaSyntheticResolverExtension.addSyntheticSupertypes for $thisDescriptor name: [$synthetic]") +// supertypes.addAll(synthetic) +// } +// }, +// getSyntheticCompanionObjectNameIfNeeded = { thisDescriptor -> +// analyzer?.run { +// val companionName: Name? = metaCompanionObjectNameIfNeeded(thisDescriptor) +// println("MetaSyntheticResolverExtension.getSyntheticCompanionObjectNameIfNeeded for $thisDescriptor name: [$companionName]") +// companionName +// } +// }, +// generateSyntheticClasses = { thisDescriptor, name, ctx, declarationProvider, result -> +// analyzer?.run { +// val syntheticClasses: List = metaSyntheticClasses(name, thisDescriptor, declarationProvider) +// result.addAll(syntheticClasses) +// println("MetaSyntheticResolverExtension.generateSyntheticClasses for $thisDescriptor [$name]: $result") +// result +// } +// }, +// generatePackageSyntheticClasses = { thisDescriptor, name, ctx, declarationProvider, result -> +// analyzer?.run { +// val synthetic: List = metaSyntheticPackageClasses(name, thisDescriptor, declarationProvider) +// result.addAll(synthetic) +// println("MetaSyntheticResolverExtension.generatePackageSyntheticClasses for $thisDescriptor [$name]: $result") +// result +// } +// }, +// generateSyntheticMethods = { thisDescriptor, name, bindingContext, fromSupertypes, result -> +// analyzer?.run { +// val synthetic: List = metaSyntheticMethods(name, thisDescriptor) +// result.addAll(synthetic) +// println("MetaSyntheticResolverExtension.generateSyntheticMethods for $thisDescriptor [$name]: $result") +// result +// } +// }, +// generateSyntheticProperties = { thisDescriptor, name, bindingContext, fromSupertypes, result -> +// analyzer?.run { +// val synthetic: List = metaSyntheticProperties(name, thisDescriptor) +// result.addAll(synthetic) +// println("MetaSyntheticResolverExtension.generateSyntheticMethods for $thisDescriptor [$name]: $result") +// result +// } +// }, +// getSyntheticFunctionNames = { thisDescriptor -> +// analyzer?.run { +// val result = metaSyntheticFunctionNames(thisDescriptor) +// println("MetaSyntheticResolverExtension.getSyntheticFunctionNames: $thisDescriptor $result") +// result +// } ?: emptyList() +// }, +// getSyntheticNestedClassNames = { thisDescriptor -> +// analyzer?.run { +// val result = metaSyntheticNestedClassNames(thisDescriptor) +// println("MetaSyntheticResolverExtension.getSyntheticNestedClassNames: $thisDescriptor $result") +// result +// } ?: emptyList() +// } +// ) +// ) + +fun PackageViewDescriptor.declarations(): Collection = + memberScope.getContributedDescriptors { true } + +fun KtFile.declaredClassWithName(name: Name): KtClass? = + findDescendantOfType { it.name == name.asString() } + +fun KtClassOrObject.functions(): List = declarations.filterIsInstance() + +fun DeclarationDescriptor.ktFile(): KtFile? = + findPsi()?.containingFile.safeAs() + +fun KtFile.classes(): List = declarations.filterIsInstance() + +fun KtClassOrObject.nestedClasses(): List = declarations.filterIsInstance() + +fun companionName(ktClass: KtClass): String? = + ktClass.companionObjects.firstOrNull()?.name + +fun PackageFragmentDescriptor.packageFiles(declarationProvider: PackageMemberDeclarationProvider) = + declarationProvider.getPackageFiles().filter { it.packageFqName == fqName } + +fun ClassDescriptor.ktClassOrObject(): KtClassOrObject? = + findPsi() as? KtClassOrObject + +fun KtClassOrObject.nestedClassNames(): List = + declarations.filterIsInstance().mapNotNull { it.name } + +fun PsiElement.ktFile(): KtFile? = + containingFile.safeAs() + +inline fun CompilerContext.processSources( + ktFile: KtFile, + quoteFactory: Quote.Factory, + noinline match: K.() -> Boolean, + noinline map: S.(K) -> List +): KtFile { + val (file, transformations) = processKtFile(ktFile, quoteFactory, match, map) + return transformFile(file, transformations) +} + +fun KtFile.ktClassNamed(name: String?): KtClass? = + name?.let { + findDescendantOfType { d -> d.name == it } + } + +fun KtClassOrObject.functionNames() = + declarations.filterIsInstance().mapNotNull { it.name }.map(Name::identifier) + +//fun CompilerContext.syntheticFunctionDescriptor2( +// containingDeclaration: ClassDescriptorWithResolutionScopes, +// ktNamedFunction: KtNamedFunction +//): SimpleFunctionDescriptor? { +// containingDeclaration as LazyClassDescriptor +// return synthFunctionResolver.resolveFunctionDescriptor( +// containingDeclaration, +// containingDeclaration.scopeForMemberDeclarationResolution, +// ktNamedFunction, +// bindingTrace, +// DataFlowInfo.EMPTY +// ).run { +// copy(containingDeclaration, modality, visibility, CallableMemberDescriptor.Kind.SYNTHESIZED, true) +// } +//} + +fun ArrayList.contributeNames(syntheticDescriptors: List): Unit { + val newDescriptors = this + syntheticDescriptors + clear() + addAll(newDescriptors.distinct()) +} + +fun MutableCollection.contribute(syntheticDescriptors: List): Unit { + val newDescriptors = this + syntheticDescriptors + clear() + addAll(newDescriptors.distinctBy { + when (it) { + is ClassDescriptor -> it.fqNameSafe.asString() + is FunctionDescriptor -> it.findPsi()?.text + else -> it.name.asString() + } + }) +} + +// +//fun CompilerContext.syntheticFunctionDescriptor( +// container: ClassDescriptorWithResolutionScopes, +// ktNamedFunction: KtNamedFunction, +// bindingContext: BindingContext, +// descriptorResolver: DescriptorResolver, +// typeResolver : TypeResolver +//): SimpleFunctionDescriptor { +// val functionDescriptor = SimpleFunctionDescriptorImpl.create( +// container, +// Annotations.EMPTY, +// ktNamedFunction.nameAsSafeName, +// CallableMemberDescriptor.Kind.SYNTHESIZED, +// container.toSourceElement +// ) +// val headerScope = LexicalWritableScope( +// container.scopeForMemberDeclarationResolution, functionDescriptor, true, +// TraceBasedLocalRedeclarationChecker(bindingTrace, OverloadChecker(TypeSpecificityComparator.NONE)), LexicalScopeKind.FUNCTION_HEADER +// ) +// val typeParameterDescriptors = +// descriptorResolver.resolveTypeParametersForDescriptor(functionDescriptor, headerScope, headerScope, ktNamedFunction.typeParameters, bindingTrace) +// descriptorResolver.resolveGenericBounds(ktNamedFunction, functionDescriptor, headerScope, typeParameterDescriptors, bindingTrace) +// +// val receiverTypeRef = ktNamedFunction.receiverTypeReference +// val receiverType = +// if (receiverTypeRef != null) { +// typeResolver.resolveType(headerScope, receiverTypeRef, bindingTrace, true) +// } else { +// if (ktNamedFunction is KtFunctionLiteral) expectedFunctionType.getReceiverType() else null +// } +// +// +// val valueParameterDescriptors = +// createValueParameterDescriptors(function, functionDescriptor, headerScope, trace, expectedFunctionType) +// +// headerScope.freeze() +// +// val returnType = ktNamedFunction.typeReference?.let { typeResolver.resolveType(headerScope, it, trace, true) } +// +// val visibility = ModifiersChecker.resolveVisibilityFromModifiers(ktNamedFunction, DescriptorResolver.getDefaultVisibility(ktNamedFunction, container)) +// val modality = ModifiersChecker.resolveMemberModalityFromModifiers( +// ktNamedFunction, DescriptorResolver.getDefaultModality(container, visibility, ktNamedFunction.hasBody()), +// bindingContext, container +// ) +// +// val contractProvider = getContractProvider(functionDescriptor, trace, scope, dataFlowInfo, function) +// val userData = mutableMapOf, Any>().apply { +// if (contractProvider != null) { +// put(ContractProviderKey, contractProvider) +// } +// +// if (receiverType != null && expectedFunctionType.functionTypeExpected() && !expectedFunctionType.annotations.isEmpty()) { +// put(DslMarkerUtils.FunctionTypeAnnotationsKey, expectedFunctionType.annotations) +// } +// } +// +// val extensionReceiver = receiverType?.let { +// val splitter = AnnotationSplitter(storageManager, receiverType.annotations, EnumSet.of(AnnotationUseSiteTarget.RECEIVER)) +// DescriptorFactory.createExtensionReceiverParameterForCallable( +// functionDescriptor, it, splitter.getAnnotationsForTarget(AnnotationUseSiteTarget.RECEIVER) +// ) +// } +// +// functionDescriptor.initialize( +// extensionReceiver, +// DescriptorUtils.getDispatchReceiverParameterIfNeeded(container), +// typeParameterDescriptors, +// valueParameterDescriptors, +// returnType, +// modality, +// visibility, +// userData.takeIf { it.isNotEmpty() } +// ) +// +// functionDescriptor.isOperator = ktNamedFunction.hasModifier(KtTokens.OPERATOR_KEYWORD) +// functionDescriptor.isInfix = ktNamedFunction.hasModifier(KtTokens.INFIX_KEYWORD) +// functionDescriptor.isExternal = ktNamedFunction.hasModifier(KtTokens.EXTERNAL_KEYWORD) +// functionDescriptor.isInline = ktNamedFunction.hasModifier(KtTokens.INLINE_KEYWORD) +// functionDescriptor.isTailrec = ktNamedFunction.hasModifier(KtTokens.TAILREC_KEYWORD) +// functionDescriptor.isSuspend = ktNamedFunction.hasModifier(KtTokens.SUSPEND_KEYWORD) +// functionDescriptor.isExpect = container is PackageFragmentDescriptor && ktNamedFunction.hasExpectModifier() || +// container is ClassDescriptor && container.isExpect +// functionDescriptor.isActual = ktNamedFunction.hasActualModifier() +// +// receiverType?.let { ForceResolveUtil.forceResolveAllContents(it.annotations) } +// for (valueParameterDescriptor in valueParameterDescriptors) { +// ForceResolveUtil.forceResolveAllContents(valueParameterDescriptor.type.annotations) +// } +// return functionDescriptor +//} + +fun LazyClassContext.syntheticDescriptor( + containingDeclaration: DeclarationDescriptor, + declarationProvider: DeclarationProvider, + ktClassOrObject: KtClassOrObject, + isCompanionObject: Boolean +): SyntheticClassOrObjectDescriptor = + SyntheticClassOrObjectDescriptor( + this, + /* parentClassOrObject= */ ktClassOrObject, + containingDeclaration, + ktClassOrObject.nameAsSafeName, + SourceElement.NO_SOURCE, + if (declarationProvider is ClassMemberDeclarationProvider) { + /* outerScope= */ declarationScopeProvider.getResolutionScopeForDeclaration(declarationProvider.ownerInfo!!.scopeAnchor) + } else declarationScopeProvider.getResolutionScopeForDeclaration(ktClassOrObject), + Modality.FINAL, + Visibilities.PUBLIC, + Annotations.EMPTY, + Visibilities.PRIVATE, + if (ktClassOrObject is KtObjectDeclaration) ClassKind.OBJECT + else if (ktClassOrObject is KtClass && ktClassOrObject.isInterface()) ClassKind.INTERFACE + else ClassKind.CLASS, + isCompanionObject + ).also { + val typeParameters: List = + ktClassOrObject.typeParameters.mapIndexed { index, param -> + TypeParameterDescriptorImpl.createWithDefaultBound( + it, + Annotations.EMPTY, + false, + Variance.INVARIANT, + param.nameAsSafeName, + index + ) + } + it.initialize(typeParameters) + } + + +fun ClassDescriptor.createType(reference: KtTypeReference): KotlinType { + val projectionType = Variance.INVARIANT + val types = reference.typeElement?.typeArgumentsAsTypes?.map { argReference -> + TypeProjectionImpl(projectionType, createType(argReference)) + } ?: emptyList() + return KotlinTypeFactory.simpleNotNullType(Annotations.EMPTY, this, types) +} + + +@Suppress("UNCHECKED_CAST") +inline fun CompilerContext.processFiles( + files: Collection, + quoteFactory: Quote.Factory, + noinline match: K.() -> Boolean, + noinline map: S.(K) -> List +): List>>> { + return files.map { file -> + processKtFile(file, quoteFactory, match, map) + } +} + +@Suppress("UNCHECKED_CAST") +inline fun CompilerContext.processKtFile( + file: KtFile, + quoteFactory: Quote.Factory, + noinline match: K.() -> Boolean, + noinline map: S.(K) -> List +): Pair>> { + val mutatingDocument = file.viewProvider.document + val mutations = arrayListOf>() + if (mutatingDocument != null) { + file.accept(object : MetaTreeVisitor() { + override fun visitKtElement(element: KtElement) { + if (element.javaClass == K::class.java) { + val transformation = quoteFactory( + quasiQuoteContext = QuasiQuoteContext(this@processKtFile), + containingDeclaration = element.psiOrParent as P, + match = match, + map = map + ).process(element as K) + transformation?.let { mutations.add(it) } + } + return super.visitKtElement(element) + } + }) + } + return file to mutations +} + +inline fun CompilerContext.updateFiles( + result: java.util.ArrayList, + fileMutations: List>>> +) { + fileMutations.forEach { (file, mutations) -> + val newFile = updateFile(mutations, file) + result.replaceFiles(file, newFile) + } +} + +inline fun CompilerContext.updateFile( + mutations: java.util.ArrayList>, + file: KtFile +): KtFile = + if (mutations.isNotEmpty()) { + transformFile(file, mutations) + } else file + +inline fun CompilerContext.transformFile( + ktFile: KtFile, + mutations: java.util.ArrayList> +): KtFile { + val newSource = ktFile.sourceWithTransformations(mutations) + val newFile = changeSource(ktFile, newSource) + //ktFile.printDiff(newSource) + println("Transformed file: $ktFile. New contents: \n$newSource") + return newFile +} + +fun KtFile.sourceWithTransformations(mutations: ArrayList>): String = + mutations.fold(text) { acc, transformation -> + val originalSource = transformation.oldDescriptor.text + val newSource = transformation.newDeclarations.joinToString("\n\n") { it.text } + acc.replace(originalSource, newSource) + } + +fun KtFile.printDiff(newSource: String) { + println(""" + | + |---------------------------------- + |*Tree Mutation* + |---------------------------------- + |Old + |--- + |$text + |--- + |New + |--- + |$newSource + |--- + |---------------------------------- + | + |""".trimMargin()) +} + +fun java.util.ArrayList.replaceFiles(file: KtFile, newFile: KtFile) { + val fileIndex = indexOf(file) + removeAt(fileIndex) + add(fileIndex, newFile) +} + +fun CompilerContext.changeSource(file: KtFile, newSource: String): KtFile = + cli { + KtFile( + viewProvider = MetaFileViewProvider(file.manager, file.virtualFile) { + it?.also { + it.setText(newSource) + } + }, + isCompiled = false + ) + } ?: ide { + ktPsiElementFactory.createAnalyzableFile("_meta_${file.name}", newSource, file) + }!! + +@Suppress("UNCHECKED_CAST") +inline operator fun A.get(field: String): B { + val clazz = A::class.java + return try { + clazz.getDeclaredField(field).also { it.isAccessible = true }.get(this) as B + } catch (e: Exception) { + clazz.getField(field).also { it.isAccessible = true }.get(this) as B + } +} + + +fun KtFile.isMetaFile(): Boolean = + name.startsWith("_meta_") \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/QuoteTransformation.kt b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/QuoteTransformation.kt new file mode 100644 index 00000000000..bf88094a6b2 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/quotes/QuoteTransformation.kt @@ -0,0 +1,11 @@ +package arrow.meta.quotes + +import org.jetbrains.kotlin.psi.KtDeclaration + +/** + * A tree transformation given an existing ktElement + */ +data class QuoteTransformation( + val oldDescriptor: K, + val newDeclarations: List +) \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor new file mode 100644 index 00000000000..02002f4ecf7 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor @@ -0,0 +1 @@ +arrow.meta.MetaCliProcessor \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.ComponentRegistrar b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.ComponentRegistrar new file mode 100644 index 00000000000..a05618251d0 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/compiler-plugin/src/main/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.ComponentRegistrar @@ -0,0 +1 @@ +arrow.meta.MetaPlugin \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/gradle-plugin/build.gradle b/modules/meta/arrow-meta-prototype/gradle-plugin/build.gradle new file mode 100644 index 00000000000..d571501db0e --- /dev/null +++ b/modules/meta/arrow-meta-prototype/gradle-plugin/build.gradle @@ -0,0 +1,69 @@ +plugins { + id 'java-gradle-plugin' + id 'maven-publish' + id 'com.gradle.plugin-publish' version "0.10.1" + id 'com.jfrog.bintray' version "1.8.4" +} +apply plugin: 'kotlin' + +project.group = 'io.arrow-kt' +project.version = '0.0.1' +def pluginId = "arrow.meta.plugin.gradle" + +dependencies { + implementation gradleApi() + implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-gradle-plugin-api:$kotlin_version" + compileOnly project(":compiler-plugin") { "embeddable" } +} + +compileKotlin { + kotlinOptions.jvmTarget = "1.8" +} +compileTestKotlin { + kotlinOptions.jvmTarget = "1.8" +} + +jar { + // Embed compiler plugin in jar + configurations.named("compileClasspath").get().find { it.name.startsWith("compiler-plugin") } + + manifest { + attributes["Specification-Title"] = project.name + attributes["Specification-Version"] = project.version + attributes["Implementation-Title"] = pluginId + attributes["Implementation-Version"] = project.version + } +} + +// Required to put the Kotlin plugin on the classpath for the functional test suite +tasks.withType(PluginUnderTestMetadata).configureEach { + pluginClasspath.from(configurations.compileOnly) +} + +gradlePlugin { + plugins { + arrow { + id = pluginId + implementationClass = "arrow.meta.plugin.gradle.ArrowGradlePlugin" + } + } +} + +pluginBundle { + website = "http://arrow-kt.io/" + vcsUrl = "https://github.com/47deg/arrow-meta-prototype.git" + description = "The Arrow compiler plugin." + tags = ["kotlin", "compiler", "arrow", "plugin", "meta"] + + plugins { + arrow { + id = pluginId + displayName = "Arrow compiler plugin" + } + } + + mavenCoordinates { + groupId = pluginId + } +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/gradle-plugin/src/main/kotlin/arrow/meta/plugin/gradle/ArrowExtension.kt b/modules/meta/arrow-meta-prototype/gradle-plugin/src/main/kotlin/arrow/meta/plugin/gradle/ArrowExtension.kt new file mode 100644 index 00000000000..919f37716b8 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/gradle-plugin/src/main/kotlin/arrow/meta/plugin/gradle/ArrowExtension.kt @@ -0,0 +1,29 @@ +/* + * Copyright 2018 Fabian Mastenbroek. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package arrow.meta.plugin.gradle + +/** + * The available Gradle configuration for this plugin. + */ +open class ArrowExtension { + + var pureCheck: Boolean = false + + open fun pureCheck(pureCheck: Boolean) { + this.pureCheck = pureCheck + } +} diff --git a/modules/meta/arrow-meta-prototype/gradle-plugin/src/main/kotlin/arrow/meta/plugin/gradle/ArrowKotlinGradleSubplugin.kt b/modules/meta/arrow-meta-prototype/gradle-plugin/src/main/kotlin/arrow/meta/plugin/gradle/ArrowKotlinGradleSubplugin.kt new file mode 100644 index 00000000000..53d08f5e1f5 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/gradle-plugin/src/main/kotlin/arrow/meta/plugin/gradle/ArrowKotlinGradleSubplugin.kt @@ -0,0 +1,37 @@ +package arrow.meta.plugin.gradle + +import org.gradle.api.Project +import org.gradle.api.tasks.compile.AbstractCompile +import org.jetbrains.kotlin.gradle.dsl.KotlinCommonOptions +import org.jetbrains.kotlin.gradle.plugin.KotlinCompilation +import org.jetbrains.kotlin.gradle.plugin.KotlinGradleSubplugin +import org.jetbrains.kotlin.gradle.plugin.SubpluginArtifact +import org.jetbrains.kotlin.gradle.plugin.SubpluginOption + +/** + * The compilation-level Gradle plugin for applying the compiler plugin to the Kotlin compiler configuration. + */ +class ArrowKotlinGradleSubplugin : KotlinGradleSubplugin { + companion object { + private const val GENERATED_ARTIFACT_NAME = "gradle-plugin" + private const val GENERATED_GROUP_ID = "io.arrow-kt" + private const val GENERATED_VERSION = "0.0.1" + private const val GENERATED_COMPILER_PLUGIN_ID = "arrow.meta.plugin.compiler" + } + + override fun isApplicable(project: Project, task: AbstractCompile) = ArrowGradlePlugin.isEnabled(project) + + override fun apply( + project: Project, + kotlinCompile: AbstractCompile, + javaCompile: AbstractCompile?, + variantData: Any?, + androidProjectHandler: Any?, + kotlinCompilation: KotlinCompilation? + ): List = emptyList() + + override fun getPluginArtifact(): SubpluginArtifact = + SubpluginArtifact(GENERATED_GROUP_ID, GENERATED_ARTIFACT_NAME, GENERATED_VERSION) + + override fun getCompilerPluginId() = GENERATED_COMPILER_PLUGIN_ID +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/gradle-plugin/src/main/kotlin/arrow/meta/plugin/gradle/ArrowSubplugin.kt b/modules/meta/arrow-meta-prototype/gradle-plugin/src/main/kotlin/arrow/meta/plugin/gradle/ArrowSubplugin.kt new file mode 100644 index 00000000000..fd67c15bf17 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/gradle-plugin/src/main/kotlin/arrow/meta/plugin/gradle/ArrowSubplugin.kt @@ -0,0 +1,23 @@ +package arrow.meta.plugin.gradle + +import org.gradle.api.Plugin +import org.gradle.api.Project + +/** + * The project-level Gradle plugin behavior that is used specifying the plugin's configuration through the + * [ArrowExtension] class. + */ +class ArrowGradlePlugin : Plugin { + companion object { + fun isEnabled(project: Project) = project.plugins.findPlugin(ArrowGradlePlugin::class.java) != null + + fun getArrowExtension(project: Project): ArrowExtension { + return project.extensions.getByType(ArrowExtension::class.java) + } + } + + override fun apply(project: Project) { + project.extensions.create("arrow", ArrowExtension::class.java) + } +} + diff --git a/modules/meta/arrow-meta-prototype/gradle-plugin/src/main/resources/META-INF/services/org.jetbrains.kotlin.gradle.plugin.KotlinGradleSubplugin b/modules/meta/arrow-meta-prototype/gradle-plugin/src/main/resources/META-INF/services/org.jetbrains.kotlin.gradle.plugin.KotlinGradleSubplugin new file mode 100644 index 00000000000..2bb1c4f34ff --- /dev/null +++ b/modules/meta/arrow-meta-prototype/gradle-plugin/src/main/resources/META-INF/services/org.jetbrains.kotlin.gradle.plugin.KotlinGradleSubplugin @@ -0,0 +1 @@ +arrow.meta.plugin.gradle.ArrowKotlinGradleSubplugin \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/gradle/wrapper/gradle-wrapper.jar b/modules/meta/arrow-meta-prototype/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..6ffa237849ef3607e39c3b334a92a65367962071 GIT binary patch literal 52928 zcmagGb95)swk{ew9kXNGwr$(C^NZ85ZQHifv2EM7)3?vv`<-+5e*3;xW6Y}hW3I6< zCcd@iSEV2g3I+oN1O)|jZN@AK^!Eb!uiM`X`me}}stD3b%8Ai~0xA59VoR-HEdO5x zmA``ee=5of%1MfeDyz`Riap3qPRK~p(#^q3(^5@O&NM19EHdvN-A~evN>0g6QA^SQ z!<>hhq#PD$QMO@_mK+utjrKQVUtrxk-8ljOA06)g+sMHFc4+Tp{x5_2cOBS&>X1WSG!pV|VNad#DJM1TXs(`9L%opN1UGD9Zg1&fIj6|1q{So)3U-a4CWoQ*xDe5m z9`W<5i~8J4RP+_u%df<<9!9wKqF2xU;C4v(Y!-T*OjUIq^ zrN#C6w^bh64qit6YXA;^mssTgXO7Aq&Mv053QqQa7t6)c)cNllz(dg0#lqCi#nRZ& z#op;3i%_g=YmY35=!;GfIx@FkZcv@PzU--T6k$JSfDIiT4$UZAAuGdgYY1vy<8ERf ze_#6;Y0Gj4`C1s&D3DA5jB+zDea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ac?(Ir{r~=ksmv_n&0a{4(Mq z!tx3)q(y#4Sbstcn7h6|h(KTYQviQ|6F2&&6o5_8Pbu2Ir}!?1^iK%^0;E4B-2XM< z_ZSAhF&q2p8|DK3>kQ!c{Co0muNog*z-sCzA*R0p{tm44w{H5=9QCXQ%%TEjZEHZu zg?<72))@Z;_;ig1Sgkp`@H^NW1C(q{^nS=RKV{rKQn4!nFf9Ro#J?~)0`l+&M)AMP z@Yj~{DIRE{>xu>-uX2FYw7=kK11!IPz!SCA(Kk0x1c=FtSy>oJSy`DmSpONi99HIv z9$+}D1vK)vKKwg4C|3{8w20AknxVfa7iUEg(hEf!EE+<X!PXU!V1E|bj+erh^FaCfgU}a_hEr^D-w2p}-z=HZCbjH&zK;BOm)C=fMQGm>T z3xM$VQ{$5Wh?@5Y=&2NeSKJ@=-@%_Y<`V{_Yn2#Uuu{yuO{{;Je ztH|(sZ~RtoPXlWFK=su97pVUbUgK&0p9U`Y!Q^f5FPMII`vH{B`sXkPPpO{j#{Zx) zH~uH8|Dq!Q6#l6I`VV+u(|>~h-V*;LhyIl6sgmjsDiYg&LG@Rq{jchJDn|K(LxzEkDJ4svPwLQ_b_AFuym*U(kR3so%zrPI@RaB2mHi()AfdnU{NBX>>H_~$&Zifz ze{fcY|8LGe4_8k;WPf04Wd3i=KlsZ&&Gb`u#2*B&a{dLu&!g0zOYqbg><0l;-fskd z&l3N}jQg}CPn|b@5FHi%M)X^E{io0E>4EqU \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [[ "$(uname)" == "Darwin" ]] && [[ "$HOME" == "$PWD" ]]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/modules/meta/arrow-meta-prototype/gradlew.bat b/modules/meta/arrow-meta-prototype/gradlew.bat new file mode 100644 index 00000000000..e95643d6a2c --- /dev/null +++ b/modules/meta/arrow-meta-prototype/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/modules/meta/arrow-meta-prototype/idea-plugin/build.gradle b/modules/meta/arrow-meta-prototype/idea-plugin/build.gradle new file mode 100644 index 00000000000..d0c070b5a57 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/idea-plugin/build.gradle @@ -0,0 +1,39 @@ +plugins { + id 'org.jetbrains.intellij' version '0.4.10' +} + +apply plugin: 'java' +apply plugin: 'kotlin' +apply plugin: 'org.jetbrains.intellij' + +dependencies { + implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + compile project(path: ':compiler-plugin', configuration: 'shadow') +} + +compileKotlin { + kotlinOptions.jvmTarget = "1.8" +} +compileTestKotlin { + kotlinOptions.jvmTarget = "1.8" +} +jar { + manifest { + attributes["Specification-Title"] = project.name + attributes["Specification-Version"] = project.version + attributes["Implementation-Title"] = "arrow.meta.plugin.idea" + attributes["Implementation-Version"] = project.version + } +} + +intellij { + version = "2019.2.1" + pluginName = "Arrow plugin" + setPlugins("gradle", "java", "org.jetbrains.kotlin:$kotlin_version-release-IJ2019.2-1") +} + +patchPluginXml { + changeNotes """ + Add change notes here.
+ most HTML tags may be used""" +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/dsl/ide/IdeSyntax.kt b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/dsl/ide/IdeSyntax.kt new file mode 100644 index 00000000000..4c5edda01e0 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/dsl/ide/IdeSyntax.kt @@ -0,0 +1,6 @@ +package arrow.meta.dsl.ide + +import arrow.meta.dsl.ide.feature1.Feature1Syntax + +interface IdeSyntax : Feature1Syntax { +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/dsl/ide/feature1/Feature1Syntax.kt b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/dsl/ide/feature1/Feature1Syntax.kt new file mode 100644 index 00000000000..578b98018ed --- /dev/null +++ b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/dsl/ide/feature1/Feature1Syntax.kt @@ -0,0 +1,5 @@ +package arrow.meta.dsl.ide.feature1 + +interface Feature1Syntax { + //extension phases combinators for this feature that is IDE only goes here. +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/IdeMetaPlugin.kt b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/IdeMetaPlugin.kt new file mode 100644 index 00000000000..5f99ea67560 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/IdeMetaPlugin.kt @@ -0,0 +1,6 @@ +package arrow.meta.plugin.idea + +import arrow.meta.MetaPlugin +import arrow.meta.plugin.idea.internal.registry.IdeInternalRegistry + +class IdeMetaPlugin : MetaPlugin(), IdeInternalRegistry \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/gradle/ArrowGradleImportHandler.kt b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/gradle/ArrowGradleImportHandler.kt new file mode 100644 index 00000000000..457e400f731 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/gradle/ArrowGradleImportHandler.kt @@ -0,0 +1,23 @@ + +package arrow.meta.plugin.idea.gradle + +import com.intellij.openapi.externalSystem.model.DataNode +import com.intellij.openapi.externalSystem.model.project.ModuleData +import org.jetbrains.kotlin.idea.configuration.GradleProjectImportHandler +import org.jetbrains.kotlin.idea.facet.KotlinFacet +import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData + +class ArrowGradleImportHandler : GradleProjectImportHandler { + + override fun importBySourceSet(facet: KotlinFacet, sourceSetNode: DataNode) { + println("ArrowGradleImportHandler.importBySourceSet") + MetaClasspathContributor.modifyCompilerArguments(facet, PLUGIN_GRADLE_JAR) + } + + override fun importByModule(facet: KotlinFacet, moduleNode: DataNode) { + println("ArrowGradleImportHandler.importByModule") + MetaClasspathContributor.modifyCompilerArguments(facet, PLUGIN_GRADLE_JAR) + } + + private val PLUGIN_GRADLE_JAR = "gradle-plugin" +} diff --git a/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/gradle/MetaClasspathContributor.kt b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/gradle/MetaClasspathContributor.kt new file mode 100644 index 00000000000..06f20cf0405 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/gradle/MetaClasspathContributor.kt @@ -0,0 +1,73 @@ +package arrow.meta.plugin.idea.gradle + +import arrow.meta.MetaCliProcessor +import com.intellij.openapi.application.PathManager +import com.intellij.openapi.diagnostic.Logger +import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments +import org.jetbrains.kotlin.idea.facet.KotlinFacet +import java.io.File +import java.io.FileInputStream +import java.util.jar.JarInputStream + +internal object MetaClasspathContributor { + /** + * The path to the IntelliJ compatible compiler plugin version. + */ + private val PLUGIN_JPS_JAR: String? + get() = PathManager.getJarPathForClass(MetaCliProcessor::class.java) + + /** + * The [Logger] instance for this class. + */ + private val logger = Logger.getInstance(MetaClasspathContributor::class.java) + + /** + * Modify the compiler arguments for the specified [KotlinFacet] to remove the incompatible compiler plugin from + * the classpath and replace it with an IntelliJ compatible version. + * + * @param facet The facet to modify. + * @param buildSystemPluginJar The name of the jar file to remove rom the classpath. + */ + fun modifyCompilerArguments(facet: KotlinFacet, buildSystemPluginJar: String) { + logger.info("Probing for Gradle plugin") + + val facetSettings = facet.configuration.settings + val commonArguments = facetSettings.compilerArguments ?: CommonCompilerArguments.DummyImpl() + val regex = ".*\\${File.separator}?$buildSystemPluginJar-.*\\.jar".toRegex() + + val oldPluginClasspaths = + (commonArguments.pluginClasspaths ?: emptyArray()).filterTo(mutableListOf()) { + val match = regex.matches(it) && validateJar(it) + !match + } + + // Add the compatible compiler plugin version to the classpath if available and is enabled in Gradle + val newPluginClasspaths = oldPluginClasspaths + PLUGIN_JPS_JAR + + println("newPluginClasspaths: $newPluginClasspaths") + + commonArguments.apply { + pluginClasspaths = newPluginClasspaths.filterNotNull().toTypedArray() + listPhases = true + } + + facetSettings.compilerArguments = commonArguments + } + + /** + * Validate whether the specified jar file is actually our compiler plugin. + * + * We need to perform this rather ugly check, because the artifact id of the Gradle plugin is not unique and rather + * general (`plugin-gradle`). We therefore check whether the manifest contains references to this project. + */ + private fun validateJar(path: String): Boolean { + return try { + val jar = JarInputStream(FileInputStream(path)) + val manifest = jar.manifest + manifest.mainAttributes.getValue("Implementation-Title") + .startsWith("arrow.meta.plugin.gradle") + } catch (_: Exception) { + false + } + } +} diff --git a/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/internal/registry/IdeInternalRegistry.kt b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/internal/registry/IdeInternalRegistry.kt new file mode 100644 index 00000000000..3987ef59add --- /dev/null +++ b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/internal/registry/IdeInternalRegistry.kt @@ -0,0 +1,24 @@ +package arrow.meta.plugin.idea.internal.registry + +import arrow.meta.dsl.platform.ide +import arrow.meta.internal.registry.InternalRegistry +import arrow.meta.phases.ExtensionPhase +import arrow.meta.plugin.idea.phases.analysis.MetaIdeAnalyzer +import org.jetbrains.kotlin.container.useImpl + +internal interface IdeInternalRegistry : InternalRegistry { + + override fun registerMetaAnalyzer(): ExtensionPhase = + ide { + storageComponent( + registerModuleComponents = { container, moduleDescriptor -> + println("Registering meta analyzer") + container.useImpl() + // + }, + check = { declaration, descriptor, context -> + } + ) + } ?: ExtensionPhase.Empty + +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/phases/analysis/MetaIdeAnalyzer.kt b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/phases/analysis/MetaIdeAnalyzer.kt new file mode 100644 index 00000000000..e6bd0cf86b0 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/phases/analysis/MetaIdeAnalyzer.kt @@ -0,0 +1,336 @@ +package arrow.meta.plugin.idea.phases.analysis + +import arrow.meta.phases.CompilerContext +import arrow.meta.phases.analysis.MetaAnalyzer +import arrow.meta.plugin.idea.phases.config.currentProject +import arrow.meta.quotes.Quote +import arrow.meta.quotes.functionNames +import arrow.meta.quotes.ktClassOrObject +import arrow.meta.quotes.ktFile +import arrow.meta.quotes.nestedClassNames +import com.intellij.AppTopics +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.compiler.CompilationStatusListener +import com.intellij.openapi.compiler.CompileContext +import com.intellij.openapi.compiler.CompilerTopics +import com.intellij.openapi.editor.Document +import com.intellij.openapi.fileEditor.FileDocumentManagerListener +import com.intellij.openapi.fileEditor.FileEditor +import com.intellij.openapi.fileEditor.FileEditorManager +import com.intellij.openapi.fileEditor.FileEditorManagerEvent +import com.intellij.openapi.fileEditor.FileEditorManagerListener +import com.intellij.openapi.fileEditor.FileEditorProvider +import com.intellij.openapi.project.Project +import com.intellij.openapi.util.Key +import com.intellij.openapi.util.UserDataHolderBase +import com.intellij.openapi.vfs.VirtualFile +import com.intellij.util.keyFMap.KeyFMap +import org.jetbrains.kotlin.analyzer.AnalysisResult +import org.jetbrains.kotlin.analyzer.ModuleInfo +import org.jetbrains.kotlin.container.get +import org.jetbrains.kotlin.context.SimpleGlobalContext +import org.jetbrains.kotlin.context.withModule +import org.jetbrains.kotlin.context.withProject +import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor +import org.jetbrains.kotlin.descriptors.ClassDescriptor +import org.jetbrains.kotlin.descriptors.DeclarationDescriptor +import org.jetbrains.kotlin.descriptors.ModuleDescriptor +import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor +import org.jetbrains.kotlin.descriptors.PropertyDescriptor +import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor +import org.jetbrains.kotlin.frontend.di.createContainerForBodyResolve +import org.jetbrains.kotlin.idea.caches.project.forcedModuleInfo +import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks +import org.jetbrains.kotlin.idea.core.util.toPsiFile +import org.jetbrains.kotlin.idea.project.IdeaModuleStructureOracle +import org.jetbrains.kotlin.idea.project.findAnalyzerServices +import org.jetbrains.kotlin.idea.project.languageVersionSettings +import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi +import org.jetbrains.kotlin.name.FqName +import org.jetbrains.kotlin.name.Name +import org.jetbrains.kotlin.platform.CommonPlatforms +import org.jetbrains.kotlin.psi.KtClassOrObject +import org.jetbrains.kotlin.psi.KtElement +import org.jetbrains.kotlin.psi.KtFile +import org.jetbrains.kotlin.resolve.BindingTrace +import org.jetbrains.kotlin.resolve.BodyResolver +import org.jetbrains.kotlin.resolve.StatementFilter +import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe +import org.jetbrains.kotlin.resolve.descriptorUtil.module +import org.jetbrains.kotlin.resolve.lazy.ResolveSession +import org.jetbrains.kotlin.resolve.lazy.declarations.ClassMemberDeclarationProvider +import org.jetbrains.kotlin.resolve.lazy.declarations.PackageMemberDeclarationProvider +import org.jetbrains.kotlin.types.KotlinType +import org.jetbrains.kotlin.types.TypeUtils +import org.jetbrains.kotlin.utils.addToStdlib.safeAs +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicBoolean +import kotlin.collections.set + +private val subscribedToEditorHooks: AtomicBoolean = AtomicBoolean(false) + +class MetaIdeAnalyzer : MetaAnalyzer { + + private val cache: ConcurrentHashMap = ConcurrentHashMap() + + private val FILE_KEY = Key.create("FILE_KEY") + + fun DeclarationDescriptor?.isGenerated(): Boolean = + this?.findPsi()?.ktFile()?.name?.startsWith("_meta_") == true + + val DeclarationDescriptor?.syntheticCache: SyntheticDescriptorCache? + get() = this?.let { + if (!it.isGenerated()) { + val file: VirtualFile? = it.ktFile()?.virtualFile + file?.let { cache[it.metaCacheId] } + } else null + } + + override fun metaPackageFragments( + module: ModuleDescriptor, + fqName: FqName + ): List = + cache.values.firstOrNull { + it.module.name == module.name + }?.module?.getPackage(fqName)?.fragments ?: emptyList() + + + override fun metaSubPackagesOf( + module: ModuleDescriptor, + fqName: FqName, + nameFilter: (Name) -> Boolean + ): Collection = + cache.values.firstOrNull { + it.module.name == module.name + }?.module?.getSubPackagesOf(fqName, nameFilter) ?: emptyList() + + override fun metaSyntheticFunctionNames(thisDescriptor: ClassDescriptor): List = + thisDescriptor.syntheticCache?.let { + val compiledDescriptor = it.descriptorCache[thisDescriptor.fqNameSafe].safeAs() + compiledDescriptor?.let { classDescriptor -> + val originalNames = thisDescriptor.findPsi().safeAs()?.functionNames()?.toSet() ?: emptySet() + val diff = classDescriptor.unsubstitutedMemberScope.getFunctionNames().toList() - originalNames + diff - blackList + } + } ?: emptyList() + + override fun metaSyntheticNestedClassNames(thisDescriptor: ClassDescriptor): List = + thisDescriptor.syntheticCache?.let { + val compiledDescriptor = it.descriptorCache[thisDescriptor.fqNameSafe].safeAs() + compiledDescriptor?.let { classDescriptor -> + val originalNames = thisDescriptor.ktClassOrObject()?.nestedClassNames()?.toSet()?.map(Name::identifier) ?: emptyList() + val compiledNames = classDescriptor.ktClassOrObject()?.nestedClassNames()?.toSet()?.map(Name::identifier) ?: emptyList() + val diff = compiledNames - originalNames + diff + } + } ?: emptyList() + + override fun metaSyntheticMethods(name: Name, thisDescriptor: ClassDescriptor): List = + thisDescriptor.syntheticCache?.let { + val compiledDescriptor = it.descriptorCache[thisDescriptor.fqNameSafe].safeAs() + compiledDescriptor?.let { + val compiledFunctions = it.unsubstitutedMemberScope.getContributedDescriptors { true }.filterIsInstance() + val originalFunctions = thisDescriptor.unsubstitutedMemberScope.getFunctionNames() + compiledFunctions.filter { cf -> + cf.name == name && cf.name !in originalFunctions && cf.name !in blackList + }.map { fn -> + fn.copy( + thisDescriptor, + fn.modality, + fn.visibility, + CallableMemberDescriptor.Kind.SYNTHESIZED, + true + ) + } + } + } ?: emptyList() + + override fun metaSyntheticProperties(name: Name, thisDescriptor: ClassDescriptor): List = + thisDescriptor.syntheticCache?.let { + val compiledDescriptor = it.descriptorCache[thisDescriptor.fqNameSafe].safeAs() + compiledDescriptor?.let { + val compiledProperties = it.unsubstitutedMemberScope.getContributedDescriptors { true }.filterIsInstance() + val originalProperties = thisDescriptor.unsubstitutedMemberScope.getVariableNames() + compiledProperties.filter { cf -> + cf.name == name && cf.name !in originalProperties && cf.name !in blackList + }.mapNotNull { fn -> + fn.copy( + thisDescriptor, + fn.modality, + fn.visibility, + CallableMemberDescriptor.Kind.SYNTHESIZED, + true + ).safeAs() + } + } + } ?: emptyList() + + override fun metaSyntheticSupertypes(classDescriptor: ClassDescriptor): List = + classDescriptor.syntheticCache?.let { + it.descriptorCache[classDescriptor.fqNameSafe].safeAs()?.let { compiled -> + val superTypes = TypeUtils.getAllSupertypes(compiled.defaultType) + .filter { tpe -> tpe != classDescriptor.module.builtIns.anyType } + superTypes + } + } ?: emptyList() + + override fun metaCompanionObjectNameIfNeeded(classDescriptor: ClassDescriptor): Name? = + classDescriptor.syntheticCache?.let { + val compiledDescriptor = it.descriptorCache[classDescriptor.fqNameSafe].safeAs() + compiledDescriptor?.let { c -> + c.ktClassOrObject()?.companionObjects?.firstOrNull()?.nameAsSafeName + } + } + + override fun metaSyntheticPackageClasses(name: Name, packageDescriptor: PackageFragmentDescriptor, declarationProvider: PackageMemberDeclarationProvider): List = + packageDescriptor.syntheticCache?.let { + val compiledDescriptor = it.descriptorCache[packageDescriptor.fqNameSafe].safeAs() + compiledDescriptor?.let { + val compiledClasses = it.getMemberScope().getContributedDescriptors { true }.filterIsInstance() + val originalClasses = packageDescriptor.getMemberScope().getClassifierNames() ?: emptySet() + compiledClasses.filter { cf -> + cf.name == name && cf.name !in originalClasses + } + } + } ?: emptyList() + + override fun metaSyntheticClasses(name: Name, classDescriptor: ClassDescriptor, declarationProvider: ClassMemberDeclarationProvider): List = + classDescriptor.syntheticCache?.let { + val compiledDescriptor = it.descriptorCache[classDescriptor.fqNameSafe].safeAs() + compiledDescriptor?.let { + val compiledClasses = it.unsubstitutedMemberScope.getContributedDescriptors { true }.filterIsInstance() + val originalClasses = classDescriptor.unsubstitutedMemberScope.getClassifierNames() ?: emptySet() + compiledClasses.filter { cf -> + cf.name == name && cf.name !in originalClasses + } + } + } ?: emptyList() + + private fun Document.getFile(): VirtualFile? { + val userMapField = + UserDataHolderBase::class.java.getDeclaredField("myUserMap") + .also { it.isAccessible = true } + val userData: KeyFMap = userMapField.get(this) as KeyFMap + return userData.keys.find { it.toString() == FILE_KEY.toString() }?.let { + userData[it] as VirtualFile? + } + } + + override fun KtFile.metaAnalysys(moduleInfo: ModuleInfo?): AnalysisResult { + moduleInfo?.let { forcedModuleInfo = it } + return analyzeWithAllCompilerChecks() + } + + override fun

CompilerContext.subscribeToEditorHooks( + project: Project, + quoteFactory: Quote.Factory, + match: K.() -> Boolean, + map: S.(K) -> List, + transformation: (VirtualFile, Document) -> Pair?): Unit { + if (!subscribedToEditorHooks.get()) { + val application = ApplicationManager.getApplication() + val projectBus = currentProject()?.messageBus?.connect() + val connection = application.messageBus.connect() + projectBus?.subscribe( + FileEditorManagerListener.FILE_EDITOR_MANAGER, + object : FileEditorManagerListener { + override fun selectionChanged(event: FileEditorManagerEvent) { + println("FileEditorManagerListener.selectionChanged: ${this@MetaIdeAnalyzer} $event") + super.selectionChanged(event) + } + + override fun fileOpened(source: FileEditorManager, file: VirtualFile) { + println("FileEditorManagerListener.fileOpened: ${this@MetaIdeAnalyzer} $file") + file.document(project)?.let { + println("FileEditorManagerListener.fileOpened: populateSyntheticCache $it") + populateSyntheticCache(it, transformation) + } + super.fileOpened(source, file) + } + + override fun fileOpenedSync(source: FileEditorManager, file: VirtualFile, editors: com.intellij.openapi.util.Pair, Array>) { + println("FileEditorManagerListener.fileOpenedSync: ${this@MetaIdeAnalyzer} $file") + super.fileOpenedSync(source, file, editors) + } + + override fun fileClosed(source: FileEditorManager, file: VirtualFile) { + println("FileEditorManagerListener.fileClosed: ${this@MetaIdeAnalyzer}, removing cache for $file") + cache.remove(file.metaCacheId) + super.fileClosed(source, file) + } + } + ) + projectBus?.subscribe( + CompilerTopics.COMPILATION_STATUS, + object : CompilationStatusListener { + override fun compilationFinished(aborted: Boolean, errors: Int, warnings: Int, compileContext: CompileContext) { + println("CompilationStatusListener.compilationFinished: ${this@MetaIdeAnalyzer} errors: $errors, context: $compileContext") + super.compilationFinished(aborted, errors, warnings, compileContext) + } + + override fun automakeCompilationFinished(errors: Int, warnings: Int, compileContext: CompileContext) { + println("CompilationStatusListener.automakeCompilationFinished: ${this@MetaIdeAnalyzer} errors: $errors, context: $compileContext") + super.automakeCompilationFinished(errors, warnings, compileContext) + } + + override fun fileGenerated(outputRoot: String, relativePath: String) { + println("CompilationStatusListener.fileGenerated: ${this@MetaIdeAnalyzer} $outputRoot $relativePath") + super.fileGenerated(outputRoot, relativePath) + } + } + ) + connection.subscribe( + AppTopics.FILE_DOCUMENT_SYNC, + object : FileDocumentManagerListener { + override fun fileContentReloaded(file: VirtualFile, document: Document) { + println("MetaOnFileSaveComponent.fileContentReloaded: ${this@MetaIdeAnalyzer} $file") + super.fileContentReloaded(file, document) + } + + override fun fileContentLoaded(file: VirtualFile, document: Document) { + println("MetaOnFileSaveComponent.fileContentLoaded: ${this@MetaIdeAnalyzer} $file") + super.fileContentLoaded(file, document) + } + + override fun beforeDocumentSaving(document: Document) { + populateSyntheticCache(document, transformation) + println("MetaOnFileSaveComponent.beforeDocumentSaving: ${this@MetaIdeAnalyzer} $document") + } + }) + subscribedToEditorHooks.set(true) + } + } + + override fun populateSyntheticCache(document: Document, transformation: (VirtualFile, Document) -> Pair?) { + document.getFile()?.let { file -> + transformation(file, document)?.let { (ktFile, result) -> + cache[file.metaCacheId] = SyntheticDescriptorCache.fromAnalysis(ktFile, result) + println("Added cache transformation: cache[${file.name}] $result") + } + } + } + + override fun createBodyResolver( + resolveSession: ResolveSession, + trace: BindingTrace, + file: KtFile, + statementFilter: StatementFilter + ): BodyResolver { + val globalContext = SimpleGlobalContext(resolveSession.storageManager, resolveSession.exceptionTracker) + val module = resolveSession.moduleDescriptor + return createContainerForBodyResolve( + globalContext.withProject(file.project).withModule(module), + trace, + CommonPlatforms.defaultCommonPlatform, + statementFilter, + CommonPlatforms.defaultCommonPlatform.findAnalyzerServices, + file.languageVersionSettings, + IdeaModuleStructureOracle() + ).get() + } +} + +fun VirtualFile.document(project: Project): Document? = + toPsiFile(project)?.viewProvider?.document + + diff --git a/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/phases/analysis/SyntheticDescriptorCache.kt b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/phases/analysis/SyntheticDescriptorCache.kt new file mode 100644 index 00000000000..e3ccc51a527 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/phases/analysis/SyntheticDescriptorCache.kt @@ -0,0 +1,69 @@ +package arrow.meta.plugin.idea.phases.analysis + +import arrow.meta.plugin.idea.phases.resolve.MetaRecursiveVisitor +import arrow.meta.quotes.isMetaFile +import arrow.meta.quotes.ktFile +import com.intellij.openapi.vfs.VirtualFile +import org.jetbrains.kotlin.analyzer.AnalysisResult +import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor +import org.jetbrains.kotlin.descriptors.ClassDescriptor +import org.jetbrains.kotlin.descriptors.DeclarationDescriptor +import org.jetbrains.kotlin.descriptors.ModuleDescriptor +import org.jetbrains.kotlin.descriptors.PackageViewDescriptor +import org.jetbrains.kotlin.descriptors.impl.DeclarationDescriptorVisitorEmptyBodies +import org.jetbrains.kotlin.name.FqName +import org.jetbrains.kotlin.name.Name +import org.jetbrains.kotlin.psi.KtFile +import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe +import java.util.concurrent.ConcurrentHashMap + +internal val blackList: Set = + listOf("equals", "hashCode", "toString") + .map(Name::identifier).toSet() + +internal data class CacheId(val value: String) + +internal val VirtualFile.metaCacheId: CacheId + get() = CacheId(path) + +class SyntheticDescriptorCache( + val module: ModuleDescriptor, + val descriptorCache: ConcurrentHashMap = ConcurrentHashMap() +) { + companion object { + fun fromAnalysis(file: KtFile, analysis: AnalysisResult): SyntheticDescriptorCache { + val moduleDescriptor = analysis.moduleDescriptor + val packageViewDescriptor = moduleDescriptor.getPackage(file.packageFqName) + val cache = SyntheticDescriptorCache(moduleDescriptor) + packageViewDescriptor.accept( + MetaRecursiveVisitor(object : DeclarationDescriptorVisitorEmptyBodies() { + override fun visitDeclarationDescriptor(descriptor: DeclarationDescriptor?, data: Unit?) { + descriptor?.let { + if (descriptor.name !in blackList) { + if (descriptor is CallableMemberDescriptor) { // constructors functions and properties + if (descriptor.ktFile()?.isMetaFile() == true && descriptor.kind != CallableMemberDescriptor.Kind.FAKE_OVERRIDE) { + println("Callable: Added to cache: ${descriptor.fqNameSafe}") + cache.descriptorCache[it.fqNameSafe] = it + } + } else if (descriptor is ClassDescriptor) { // constructors functions and properties + if (descriptor.ktFile()?.isMetaFile() == true) { + println("Class: Added to cache: ${descriptor.fqNameSafe}") + cache.descriptorCache[it.fqNameSafe] = it + } + } else if (descriptor is PackageViewDescriptor) { // constructors functions and properties + if (descriptor.ktFile()?.isMetaFile() == true) { + println("Package: Added to cache: ${descriptor.fqNameSafe}") + cache.descriptorCache[it.fqNameSafe] = it + } + } else { + println("skipped synthetic cache entry: $descriptor: ${descriptor.name}") + } + } + } + } + }), Unit) + return cache + } + + } +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/phases/config/utils.kt b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/phases/config/utils.kt new file mode 100644 index 00000000000..9679c644c96 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/phases/config/utils.kt @@ -0,0 +1,20 @@ +package arrow.meta.plugin.idea.phases.config + +import com.intellij.openapi.module.ModuleManager +import com.intellij.openapi.project.Project +import com.intellij.openapi.project.ProjectManager +import com.intellij.openapi.roots.ModuleRootManager +import com.intellij.openapi.vfs.VirtualFile +import com.intellij.openapi.wm.WindowManager + +fun currentProject(): Project? = + ProjectManager.getInstance().openProjects.firstOrNull { project -> + val window = WindowManager.getInstance().suggestParentWindow(project) + (window != null && window.isActive) + } + +fun Project.buildFolders(): List = + ModuleManager.getInstance(this).modules + .flatMap { ModuleRootManager.getInstance(it).excludeRoots.toList() } + .filter { it.name == "build" } + diff --git a/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/phases/resolve/MetaRecursiveVisitor.kt b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/phases/resolve/MetaRecursiveVisitor.kt new file mode 100644 index 00000000000..5010ce2eeec --- /dev/null +++ b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/phases/resolve/MetaRecursiveVisitor.kt @@ -0,0 +1,128 @@ +package arrow.meta.plugin.idea.phases.resolve + +import org.jetbrains.kotlin.descriptors.CallableDescriptor +import org.jetbrains.kotlin.descriptors.ClassDescriptor +import org.jetbrains.kotlin.descriptors.ConstructorDescriptor +import org.jetbrains.kotlin.descriptors.DeclarationDescriptor +import org.jetbrains.kotlin.descriptors.DeclarationDescriptorVisitor +import org.jetbrains.kotlin.descriptors.FunctionDescriptor +import org.jetbrains.kotlin.descriptors.ModuleDescriptor +import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor +import org.jetbrains.kotlin.descriptors.PackageViewDescriptor +import org.jetbrains.kotlin.descriptors.PropertyDescriptor +import org.jetbrains.kotlin.descriptors.PropertyGetterDescriptor +import org.jetbrains.kotlin.descriptors.PropertySetterDescriptor +import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor +import org.jetbrains.kotlin.descriptors.ScriptDescriptor +import org.jetbrains.kotlin.descriptors.TypeAliasDescriptor +import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor +import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor +import org.jetbrains.kotlin.descriptors.VariableDescriptor +import org.jetbrains.kotlin.name.FqName +import org.jetbrains.kotlin.resolve.DescriptorUtils + +internal class MetaRecursiveVisitor constructor(private val worker: DeclarationDescriptorVisitor) : DeclarationDescriptorVisitor { + + private fun visitChildren(descriptors: Collection, data: Unit): Unit { + for (descriptor in descriptors) { + descriptor.accept(this, data) + } + } + + private fun visitChildren(descriptor: DeclarationDescriptor?, data: Unit): Unit { + descriptor?.accept(this, data) + } + + private fun applyWorker(descriptor: DeclarationDescriptor, data: Unit): Unit { + descriptor.accept(worker, data) + } + + private fun processCallable(descriptor: CallableDescriptor, data: Unit): Unit? { + applyWorker(descriptor, data) + visitChildren(descriptor.typeParameters, data) + visitChildren(descriptor.extensionReceiverParameter, data) + visitChildren(descriptor.valueParameters, data) + return null + } + + override fun visitPackageFragmentDescriptor(descriptor: PackageFragmentDescriptor, data: Unit): Unit? { + applyWorker(descriptor, data) + visitChildren(DescriptorUtils.getAllDescriptors(descriptor.getMemberScope()), data) + return null + } + + override fun visitPackageViewDescriptor(descriptor: PackageViewDescriptor, data: Unit): Unit? { + applyWorker(descriptor, data) + visitChildren(DescriptorUtils.getAllDescriptors(descriptor.memberScope), data) + return null + } + + override fun visitVariableDescriptor(descriptor: VariableDescriptor, data: Unit): Unit? { + processCallable(descriptor, data) + return null + } + + override fun visitPropertyDescriptor(descriptor: PropertyDescriptor, data: Unit): Unit? { + processCallable(descriptor, data) + visitChildren(descriptor.getter, data) + return null + } + + override fun visitFunctionDescriptor(descriptor: FunctionDescriptor, data: Unit): Unit? { + processCallable(descriptor, data) + return null + } + + override fun visitTypeParameterDescriptor(descriptor: TypeParameterDescriptor, data: Unit): Unit? { + applyWorker(descriptor, data) + return null + } + + override fun visitClassDescriptor(descriptor: ClassDescriptor, data: Unit): Unit? { + applyWorker(descriptor, data) + visitChildren(descriptor.thisAsReceiverParameter, data) + visitChildren(descriptor.constructors, data) + visitChildren(descriptor.typeConstructor.parameters, data) + visitChildren(DescriptorUtils.getAllDescriptors(descriptor.defaultType.memberScope), data) + return null + } + + override fun visitTypeAliasDescriptor(descriptor: TypeAliasDescriptor, data: Unit): Unit? { + applyWorker(descriptor, data) + visitChildren(descriptor.declaredTypeParameters, data) + return null + } + + override fun visitModuleDeclaration(descriptor: ModuleDescriptor, data: Unit): Unit? { + applyWorker(descriptor, data) + visitChildren(descriptor.getPackage(FqName.ROOT), data) + return null + } + + override fun visitConstructorDescriptor(constructorDescriptor: ConstructorDescriptor, data: Unit): Unit? { + visitFunctionDescriptor(constructorDescriptor, data) + return null + } + + override fun visitScriptDescriptor(scriptDescriptor: ScriptDescriptor, data: Unit): Unit? { + visitClassDescriptor(scriptDescriptor, data) + return null + } + + override fun visitValueParameterDescriptor(descriptor: ValueParameterDescriptor, data: Unit): Unit? { + return visitVariableDescriptor(descriptor, data) + } + + override fun visitPropertyGetterDescriptor(descriptor: PropertyGetterDescriptor, data: Unit): Unit? { + return visitFunctionDescriptor(descriptor, data) + } + + override fun visitPropertySetterDescriptor(descriptor: PropertySetterDescriptor, data: Unit): Unit? { + return visitFunctionDescriptor(descriptor, data) + } + + override fun visitReceiverParameterDescriptor(descriptor: ReceiverParameterDescriptor, data: Unit): Unit? { + applyWorker(descriptor, data) + return null + } +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/phases/resolve/MetaSyntheticPackageFragmentProvider.kt b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/phases/resolve/MetaSyntheticPackageFragmentProvider.kt new file mode 100644 index 00000000000..e5fed7d1ef2 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/kotlin/arrow/meta/plugin/idea/phases/resolve/MetaSyntheticPackageFragmentProvider.kt @@ -0,0 +1,217 @@ +package arrow.meta.plugin.idea.phases.resolve + +import arrow.meta.plugin.idea.IdeMetaPlugin +import arrow.meta.plugin.idea.phases.config.buildFolders +import arrow.meta.plugin.idea.phases.config.currentProject +import com.intellij.openapi.Disposable +import com.intellij.openapi.project.Project +import com.intellij.openapi.util.io.FileUtil +import com.intellij.openapi.vfs.AsyncFileListener +import com.intellij.openapi.vfs.LocalFileSystem +import com.intellij.openapi.vfs.VirtualFile +import com.intellij.openapi.vfs.VirtualFileManager +import com.intellij.openapi.vfs.newvfs.events.VFileEvent +import com.intellij.psi.ClassFileViewProviderFactory +import com.intellij.psi.PsiManager +import org.jetbrains.kotlin.analyzer.ModuleInfo +import org.jetbrains.kotlin.caches.resolve.KotlinCacheService +import org.jetbrains.kotlin.config.CompilerConfiguration +import org.jetbrains.kotlin.descriptors.ClassifierDescriptor +import org.jetbrains.kotlin.descriptors.DeclarationDescriptor +import org.jetbrains.kotlin.descriptors.ModuleDescriptor +import org.jetbrains.kotlin.descriptors.PackageFragmentProvider +import org.jetbrains.kotlin.descriptors.PackageFragmentProviderImpl +import org.jetbrains.kotlin.descriptors.PropertyDescriptor +import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor +import org.jetbrains.kotlin.descriptors.impl.PackageFragmentDescriptorImpl +import org.jetbrains.kotlin.idea.KotlinLanguage +import org.jetbrains.kotlin.idea.resolve.ResolutionFacade +import org.jetbrains.kotlin.incremental.components.LookupLocation +import org.jetbrains.kotlin.incremental.components.LookupTracker +import org.jetbrains.kotlin.name.FqName +import org.jetbrains.kotlin.name.Name +import org.jetbrains.kotlin.psi.KtDeclaration +import org.jetbrains.kotlin.psi.KtFile +import org.jetbrains.kotlin.psi.stubs.elements.KtFileStubBuilder +import org.jetbrains.kotlin.resolve.BindingTrace +import org.jetbrains.kotlin.resolve.jvm.extensions.PackageFragmentProviderExtension +import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode +import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter +import org.jetbrains.kotlin.resolve.scopes.MemberScope +import org.jetbrains.kotlin.storage.StorageManager +import org.jetbrains.kotlin.utils.Printer +import java.io.File +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicBoolean +import java.util.regex.Pattern + +private val metaPlugin = IdeMetaPlugin() + +private val registered = AtomicBoolean(false) + +class MetaSyntheticPackageFragmentProvider : PackageFragmentProviderExtension, AsyncFileListener, AsyncFileListener.ChangeApplier, Disposable { + + private val fileListenerInitialized: AtomicBoolean = AtomicBoolean(false) + + @Synchronized + private fun Project.registerIdeStack(postInitialize : () -> Unit) { + if (!registered.getAndSet(true)) { + val project = currentProject() + if (project != null) { + val configuration = CompilerConfiguration() + metaPlugin.registerMetaComponents(this, configuration) + println("registerIdeProjectComponents DONE") + postInitialize() + } else { + registered.set(false) + } + } + } + + @Synchronized + private fun initializeFileListener() { + if (!fileListenerInitialized.get()) { + currentProject()?.let { project -> + val virtualFileManager = project.getComponent(VirtualFileManager::class.java) + virtualFileManager?.addAsyncFileListener(this, this) + fileListenerInitialized.set(true) + } + } + } + + override fun getPackageFragmentProvider( + project: Project, + module: ModuleDescriptor, + storageManager: StorageManager, + trace: BindingTrace, + moduleInfo: ModuleInfo?, + lookupTracker: LookupTracker + ): PackageFragmentProvider? { + project.registerIdeStack { + computeCache(project) + } + initializeFileListener() + println("MetaSyntheticPackageFragmentProvider.getPackageFragmentProvider:, cache:\n $descriptorCache") + return PackageFragmentProviderImpl( + descriptorCache.keys().toList().map { packageName -> + BuildCachePackageFragmentDescriptor(module, packageName) + } + ) + } + + inner class BuildCachePackageFragmentDescriptor(module: ModuleDescriptor, fqName: FqName) : PackageFragmentDescriptorImpl(module, fqName) { + + override fun getMemberScope(): MemberScope = scope + + private val scope = Scope() + + inner class Scope : MemberScope { + override fun getClassifierNames(): Set? = + descriptorCache[fqName]?.filterIsInstance()?.map { it.name }?.toSet() + + override fun getContributedClassifier(name: Name, location: LookupLocation): ClassifierDescriptor? = + descriptorCache[fqName]?.filterIsInstance()?.firstOrNull { it.name == name } + + override fun getContributedDescriptors(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean): Collection = + descriptorCache[fqName]?.filter { it.name == name } ?: emptyList() + + override fun getContributedFunctions(name: Name, location: LookupLocation): Collection = + descriptorCache[fqName]?.filterIsInstance() ?: emptyList() + + override fun getContributedVariables(name: Name, location: LookupLocation): Collection = + descriptorCache[fqName]?.filterIsInstance() ?: emptyList() + + override fun getFunctionNames(): Set = + descriptorCache[fqName]?.filterIsInstance()?.map { it.name }?.toSet() ?: emptySet() + + override fun getVariableNames(): Set = + descriptorCache[fqName]?.filterIsInstance()?.map { it.name }?.toSet() ?: emptySet() + + override fun printScopeStructure(p: Printer) { + } + } + } + + override fun dispose() { + println("MetaSyntheticPackageFragmentProvider.dispose") + descriptorCache.clear() + } + + override fun beforeVfsChange() { + println("MetaSyntheticPackageFragmentProvider.beforeVfsChange") + } + + override fun afterVfsChange() { + println("MetaSyntheticPackageFragmentProvider.afterVfsChange") + currentProject()?.let { computeCache(it) } + refreshingFiles.forEach { + it.refresh(false, true) { + println("Refreshed: $it") + } + } + refreshingFiles.clear() + } + + private val refreshingFiles: HashSet = hashSetOf() + + override fun prepareChange(events: MutableList): AsyncFileListener.ChangeApplier? { + refreshingFiles.addAll(events.mapNotNull { it.file }) + return this + } + + private val descriptorCache: ConcurrentHashMap> = ConcurrentHashMap() + + @Synchronized + private fun computeCache(project: Project): Unit { + println("initializing new PackageFragmentProvider") + descriptorCache.clear() + val localFileSystem = LocalFileSystem.getInstance() + val psiManager = project.getComponent(PsiManager::class.java) + val buildFolders = project.buildFolders() + val cacheService = KotlinCacheService.getInstance(project) + val classFileViewProvider = ClassFileViewProviderFactory() + val classFiles = buildFolders.packagedClasses(localFileSystem, classFileViewProvider, psiManager) + if (classFiles.isNotEmpty()) { + val resolutionFacade = cacheService.getResolutionFacade(classFiles.map { it.second }) + val resolvedDeclarations = classFiles.resolveClassesDeclarations(resolutionFacade) + resolvedDeclarations.forEach { (packageName, declarations) -> + val cachedDescriptors = descriptorCache[packageName] ?: emptyList() + val leftovers = cachedDescriptors.filterNot { it in declarations } + val newCachedPackageDescriptors = declarations + leftovers + println("Adding to cache: $newCachedPackageDescriptors") + descriptorCache[packageName] = newCachedPackageDescriptors + } + } + } + + private fun List>.resolveClassesDeclarations(resolutionFacade: ResolutionFacade): List>> = + flatMap { (packageName, file) -> + listOf(packageName to file.declarations.resolveDeclarations(resolutionFacade)) + } + + private fun List.resolveDeclarations(resolutionFacade: ResolutionFacade): List = + map { ktDeclaration -> ktDeclaration.resolveDeclaration(resolutionFacade) } + + private fun KtDeclaration.resolveDeclaration(resolutionFacade: ResolutionFacade) = + resolutionFacade.resolveToDescriptor(this, BodyResolveMode.PARTIAL_FOR_COMPLETION) + + private fun List.packagedClasses(localFileSystem: LocalFileSystem, classFileViewProvider: ClassFileViewProviderFactory, psiManager: PsiManager): List> = + flatMap { buildFolder -> + val buildRoot = File(buildFolder.path) + val matchedFiles = arrayListOf() + FileUtil.collectMatchedFiles(buildRoot, Pattern.compile("(.*)\\.class$"), matchedFiles) + matchedFiles + .filterNot { it.name.endsWith("DefaultImpls.class") } //we don't want this synthetic files in the way + .mapNotNull { file -> + val maybeVirtualFile = localFileSystem.findFileByIoFile(file) + maybeVirtualFile?.let { virtualFile -> + val viewProvider = classFileViewProvider.createFileViewProvider(virtualFile, KotlinLanguage.INSTANCE, psiManager, true) + val ktFile = KtFile(viewProvider, true) + KtFileStubBuilder().buildStubTree(ktFile) + val packageName = ktFile.packageFqName + packageName to ktFile + } + } + } + +} \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/idea-plugin/src/main/resources/META-INF/plugin.xml b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/resources/META-INF/plugin.xml new file mode 100644 index 00000000000..0b7d686aff6 --- /dev/null +++ b/modules/meta/arrow-meta-prototype/idea-plugin/src/main/resources/META-INF/plugin.xml @@ -0,0 +1,26 @@ + + arrow-plugin + Arrow + + Arrow + + + most HTML tags may be used + ]]> + + + + + org.jetbrains.plugins.gradle + org.jetbrains.kotlin + + + + + + + \ No newline at end of file diff --git a/modules/meta/arrow-meta-prototype/settings.gradle b/modules/meta/arrow-meta-prototype/settings.gradle new file mode 100644 index 00000000000..0a458aa490e --- /dev/null +++ b/modules/meta/arrow-meta-prototype/settings.gradle @@ -0,0 +1,3 @@ +include ':compiler-plugin' +include ':gradle-plugin' +include ':idea-plugin'