├── .gitignore ├── .idea ├── codeStyles │ └── Project.xml ├── inspectionProfiles │ └── Project_Default.xml └── kotlinc.xml ├── LICENSE ├── README.md ├── build.gradle ├── gradle-plugin ├── build.gradle └── src │ └── main │ └── kotlin │ └── debuglog │ ├── DebugLogGradleExtension.kt │ ├── DebugLogGradlePlugin.kt │ └── DebugLogGradleSubplugin.kt ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── kotlin-plugin ├── build.gradle └── src │ └── main │ └── kotlin │ └── debuglog │ └── plugin │ ├── DebugLogClassBuilder.kt │ ├── DebugLogClassGenerationInterceptor.kt │ ├── DebugLogCommandLineProcessor.kt │ └── DebugLogComponentRegistrar.kt └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/osx,linux,kotlin,gradle,windows,intellij,androidstudio 3 | 4 | ### AndroidStudio ### 5 | # Covers files to be ignored for android development using Android Studio. 6 | 7 | # Built application files 8 | *.apk 9 | *.ap_ 10 | 11 | # Files for the ART/Dalvik VM 12 | *.dex 13 | 14 | # Java class files 15 | *.class 16 | 17 | # Generated files 18 | bin/ 19 | gen/ 20 | out/ 21 | 22 | # Gradle files 23 | .gradle 24 | .gradle/ 25 | build/ 26 | 27 | # Signing files 28 | .signing/ 29 | 30 | # Local configuration file (sdk path, etc) 31 | local.properties 32 | 33 | # Proguard folder generated by Eclipse 34 | proguard/ 35 | 36 | # Log Files 37 | *.log 38 | 39 | # Android Studio 40 | /*/build/ 41 | /*/local.properties 42 | /*/out 43 | /*/*/build 44 | /*/*/production 45 | captures/ 46 | .navigation/ 47 | *.ipr 48 | *~ 49 | *.swp 50 | 51 | # Android Patch 52 | gen-external-apklibs 53 | 54 | # External native build folder generated in Android Studio 2.2 and later 55 | .externalNativeBuild 56 | 57 | # NDK 58 | obj/ 59 | 60 | # IntelliJ IDEA 61 | *.iml 62 | *.iws 63 | /out/ 64 | 65 | # User-specific configurations 66 | .idea/caches/ 67 | .idea/libraries/ 68 | .idea/shelf/ 69 | .idea/workspace.xml 70 | .idea/tasks.xml 71 | .idea/.name 72 | .idea/compiler.xml 73 | .idea/copyright/profiles_settings.xml 74 | .idea/encodings.xml 75 | .idea/misc.xml 76 | .idea/modules.xml 77 | .idea/scopes/scope_settings.xml 78 | .idea/dictionaries 79 | .idea/vcs.xml 80 | .idea/jsLibraryMappings.xml 81 | .idea/datasources.xml 82 | .idea/dataSources.ids 83 | .idea/sqlDataSources.xml 84 | .idea/dynamic.xml 85 | .idea/uiDesigner.xml 86 | 87 | # OS-specific files 88 | .DS_Store 89 | .DS_Store? 90 | ._* 91 | .Spotlight-V100 92 | .Trashes 93 | ehthumbs.db 94 | Thumbs.db 95 | 96 | # Legacy Eclipse project files 97 | .classpath 98 | .project 99 | .cproject 100 | .settings/ 101 | 102 | # Mobile Tools for Java (J2ME) 103 | .mtj.tmp/ 104 | 105 | # Package Files # 106 | *.war 107 | *.ear 108 | 109 | # virtual machine crash logs (Reference: http://www.java.com/en/download/help/error_hotspot.xml) 110 | hs_err_pid* 111 | 112 | ## Plugin-specific files: 113 | 114 | # mpeltonen/sbt-idea plugin 115 | .idea_modules/ 116 | 117 | # JIRA plugin 118 | atlassian-ide-plugin.xml 119 | 120 | # Mongo Explorer plugin 121 | .idea/mongoSettings.xml 122 | 123 | # Crashlytics plugin (for Android Studio and IntelliJ) 124 | com_crashlytics_export_strings.xml 125 | crashlytics.properties 126 | crashlytics-build.properties 127 | fabric.properties 128 | 129 | ### AndroidStudio Patch ### 130 | 131 | !/gradle/wrapper/gradle-wrapper.jar 132 | 133 | ### Intellij ### 134 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 135 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 136 | 137 | # User-specific stuff 138 | .idea/**/workspace.xml 139 | .idea/**/tasks.xml 140 | .idea/**/usage.statistics.xml 141 | .idea/**/dictionaries 142 | .idea/**/shelf 143 | 144 | # Generated files 145 | .idea/**/contentModel.xml 146 | 147 | # Sensitive or high-churn files 148 | .idea/**/dataSources/ 149 | .idea/**/dataSources.ids 150 | .idea/**/dataSources.local.xml 151 | .idea/**/sqlDataSources.xml 152 | .idea/**/dynamic.xml 153 | .idea/**/uiDesigner.xml 154 | .idea/**/dbnavigator.xml 155 | 156 | # Gradle 157 | .idea/**/gradle.xml 158 | .idea/**/libraries 159 | 160 | # Gradle and Maven with auto-import 161 | # When using Gradle or Maven with auto-import, you should exclude module files, 162 | # since they will be recreated, and may cause churn. Uncomment if using 163 | # auto-import. 164 | # .idea/modules.xml 165 | # .idea/*.iml 166 | # .idea/modules 167 | 168 | # CMake 169 | cmake-build-*/ 170 | 171 | # Mongo Explorer plugin 172 | .idea/**/mongoSettings.xml 173 | 174 | # File-based project format 175 | 176 | # IntelliJ 177 | 178 | # mpeltonen/sbt-idea plugin 179 | 180 | # JIRA plugin 181 | 182 | # Cursive Clojure plugin 183 | .idea/replstate.xml 184 | 185 | # Crashlytics plugin (for Android Studio and IntelliJ) 186 | 187 | # Editor-based Rest Client 188 | .idea/httpRequests 189 | 190 | # Android studio 3.1+ serialized cache file 191 | .idea/caches/build_file_checksums.ser 192 | 193 | ### Intellij Patch ### 194 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 195 | 196 | # *.iml 197 | # modules.xml 198 | # .idea/misc.xml 199 | # *.ipr 200 | 201 | # Sonarlint plugin 202 | .idea/sonarlint 203 | 204 | ### Kotlin ### 205 | # Compiled class file 206 | 207 | # Log file 208 | 209 | # BlueJ files 210 | *.ctxt 211 | 212 | # Mobile Tools for Java (J2ME) 213 | 214 | # Package Files # 215 | *.jar 216 | *.nar 217 | *.zip 218 | *.tar.gz 219 | *.rar 220 | 221 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 222 | 223 | ### Linux ### 224 | 225 | # temporary files which can be created if a process still has a handle open of a deleted file 226 | .fuse_hidden* 227 | 228 | # KDE directory preferences 229 | .directory 230 | 231 | # Linux trash folder which might appear on any partition or disk 232 | .Trash-* 233 | 234 | # .nfs files are created when an open file is removed but is still being accessed 235 | .nfs* 236 | 237 | ### OSX ### 238 | # General 239 | .AppleDouble 240 | .LSOverride 241 | 242 | # Icon must end with two \r 243 | Icon 244 | 245 | # Thumbnails 246 | 247 | # Files that might appear in the root of a volume 248 | .DocumentRevisions-V100 249 | .fseventsd 250 | .TemporaryItems 251 | .VolumeIcon.icns 252 | .com.apple.timemachine.donotpresent 253 | 254 | # Directories potentially created on remote AFP share 255 | .AppleDB 256 | .AppleDesktop 257 | Network Trash Folder 258 | Temporary Items 259 | .apdisk 260 | 261 | ### Windows ### 262 | # Windows thumbnail cache files 263 | ehthumbs_vista.db 264 | 265 | # Dump file 266 | *.stackdump 267 | 268 | # Folder config file 269 | [Dd]esktop.ini 270 | 271 | # Recycle Bin used on file shares 272 | $RECYCLE.BIN/ 273 | 274 | # Windows Installer files 275 | *.cab 276 | *.msi 277 | *.msix 278 | *.msm 279 | *.msp 280 | 281 | # Windows shortcuts 282 | *.lnk 283 | 284 | ### Gradle ### 285 | /build/ 286 | 287 | # Ignore Gradle GUI config 288 | gradle-app.setting 289 | 290 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 291 | !gradle-wrapper.jar 292 | 293 | # Cache of project 294 | .gradletasknamecache 295 | 296 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 297 | # gradle/wrapper/gradle-wrapper.properties 298 | 299 | 300 | # End of https://www.gitignore.io/api/osx,linux,kotlin,gradle,windows,intellij,androidstudio -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 15 | 16 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /.idea/kotlinc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Kevin Most 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | DebugLog: An exploratory Compiler Plugin for Kotlin 2 | --- 3 | 4 | This repository contains a Kotlin Compiler Plugin that automagically adds 5 | method tracing (to stdout) to any function annotated with a user-specified 6 | "DebugLog" annotation. 7 | 8 | Currently, there are _many_ bugs in this code, as it was a toy project made 9 | specifically for a talk I gave on Kotlin Compiler plugins at KotlinConf 10 | ([video here](https://youtu.be/w-GMlaziIyo), 11 | [slides here](https://speakerdeck.com/kevinmost/writing-your-first-kotlin-compiler-plugin), 12 | [talk abstract here](https://kotlinconf.com/schedule/#date=4-october&session=41262)). 13 | 14 | Usage 15 | --- 16 | 17 | Build the artifacts for both the `:gradle-plugin` and `:kotlin-plugin` 18 | modules, and publish them to a Maven repo. 19 | 20 | Add a dependency on the `:gradle-plugin` artifact to your root `build.gradle`: 21 | 22 | ```groovy 23 | buildscript { 24 | dependencies { 25 | classpath "debuglog:gradle-plugin:0.0.1" 26 | } 27 | } 28 | ``` 29 | 30 | and then in your module-specific `build.gradle`, apply/configure the plugin: 31 | 32 | ```groovy 33 | apply plugin: "debuglog.plugin" 34 | 35 | debugLog { 36 | enabled = true 37 | annotations = [ "com.sample.myapp.annotations.DebugLog" ] 38 | } 39 | ``` 40 | 41 | Bugs 42 | --- 43 | 44 | You tell me! 45 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext.ktVersion = "1.2.70" 3 | repositories { jcenter() } 4 | dependencies { 5 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$ktVersion" 6 | } 7 | } 8 | 9 | subprojects { 10 | repositories { jcenter() } 11 | 12 | // Install into local Maven repo with `./gradlew :kotlin-plugin:install :gradle-plugin:install` 13 | apply plugin: "maven" 14 | group = "debuglog" 15 | version = "0.0.1" 16 | } 17 | -------------------------------------------------------------------------------- /gradle-plugin/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: "java-gradle-plugin" 2 | apply plugin: "org.jetbrains.kotlin.jvm" 3 | apply plugin: "kotlin-kapt" 4 | 5 | gradlePlugin { 6 | plugins { 7 | simplePlugin { 8 | id = "debuglog.plugin" // users will do `apply plugin: "debuglog.plugin"` 9 | implementationClass = "debuglog.DebugLogGradlePlugin" // entry-point class 10 | } 11 | } 12 | } 13 | 14 | dependencies { 15 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$ktVersion" 16 | 17 | // contains classes like Subplugin, SubpluginOption, etc 18 | implementation "org.jetbrains.kotlin:kotlin-gradle-plugin-api:$ktVersion" 19 | 20 | // Needed to register Subplugin as a service 21 | compileOnly "com.google.auto.service:auto-service:1.0-rc4" 22 | kapt "com.google.auto.service:auto-service:1.0-rc4" 23 | } 24 | -------------------------------------------------------------------------------- /gradle-plugin/src/main/kotlin/debuglog/DebugLogGradleExtension.kt: -------------------------------------------------------------------------------- 1 | package debuglog 2 | 3 | open class DebugLogGradleExtension { 4 | /** If [false], this plugin won't actually be applied */ 5 | var enabled: Boolean = true 6 | 7 | /** FQ names of annotations that should count as debuglog annotations */ 8 | var annotations: List = emptyList() 9 | } 10 | -------------------------------------------------------------------------------- /gradle-plugin/src/main/kotlin/debuglog/DebugLogGradlePlugin.kt: -------------------------------------------------------------------------------- 1 | package debuglog 2 | 3 | import org.gradle.api.Plugin 4 | import org.gradle.api.Project 5 | 6 | class DebugLogGradlePlugin : Plugin { 7 | override fun apply(project: Project) { 8 | /* 9 | * Users can configure this extension in their build.gradle like this: 10 | * debugLog { 11 | * enabled = false 12 | * // ... set other members on the DebugLogGradleExtension class 13 | * } 14 | */ 15 | project.extensions.create( 16 | "debugLog", 17 | DebugLogGradleExtension::class.java 18 | ) 19 | } 20 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/kotlin/debuglog/DebugLogGradleSubplugin.kt: -------------------------------------------------------------------------------- 1 | package debuglog 2 | 3 | import com.google.auto.service.AutoService 4 | import org.gradle.api.Project 5 | import org.gradle.api.tasks.compile.AbstractCompile 6 | import org.jetbrains.kotlin.gradle.plugin.KotlinCompilation 7 | import org.jetbrains.kotlin.gradle.plugin.KotlinGradleSubplugin 8 | import org.jetbrains.kotlin.gradle.plugin.SubpluginArtifact 9 | import org.jetbrains.kotlin.gradle.plugin.SubpluginOption 10 | 11 | @AutoService(KotlinGradleSubplugin::class) // don't forget! 12 | class DebugLogGradleSubplugin : KotlinGradleSubplugin { 13 | 14 | override fun isApplicable(project: Project, task: AbstractCompile) = 15 | project.plugins.hasPlugin(DebugLogGradlePlugin::class.java) 16 | 17 | override fun apply( 18 | project: Project, 19 | kotlinCompile: AbstractCompile, 20 | javaCompile: AbstractCompile?, 21 | variantData: Any?, 22 | androidProjectHandler: Any?, 23 | kotlinCompilation: KotlinCompilation? 24 | ): List { 25 | val extension = project.extensions.findByType(DebugLogGradleExtension::class.java) 26 | ?: DebugLogGradleExtension() 27 | 28 | if (extension.enabled && extension.annotations.isEmpty()) { 29 | error("DebugLog is enabled, but no annotations were set") 30 | } 31 | 32 | val annotationOptions = extension.annotations.map { SubpluginOption(key = "debugLogAnnotation", value = it) } 33 | val enabledOption = SubpluginOption(key = "enabled", value = extension.enabled.toString()) 34 | return annotationOptions + enabledOption 35 | } 36 | 37 | /** 38 | * Just needs to be consistent with the key for DebugLogCommandLineProcessor#pluginId 39 | */ 40 | override fun getCompilerPluginId(): String = "debuglog" 41 | 42 | override fun getPluginArtifact(): SubpluginArtifact = SubpluginArtifact( 43 | groupId = "debuglog", 44 | artifactId = "kotlin-plugin", 45 | version = "0.0.1" // remember to bump this version before any release! 46 | ) 47 | } 48 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kevinmost/debuglog/55c491ce071f4a03f4f1a04ace816f19466bfd7e/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sun Sep 16 10:57:51 EDT 2018 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.8-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /kotlin-plugin/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: "org.jetbrains.kotlin.jvm" 2 | apply plugin: "kotlin-kapt" 3 | 4 | dependencies { 5 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$ktVersion" 6 | compileOnly "org.jetbrains.kotlin:kotlin-compiler-embeddable:$ktVersion" 7 | 8 | compileOnly "com.google.auto.service:auto-service:1.0-rc4" 9 | kapt "com.google.auto.service:auto-service:1.0-rc4" 10 | } 11 | -------------------------------------------------------------------------------- /kotlin-plugin/src/main/kotlin/debuglog/plugin/DebugLogClassBuilder.kt: -------------------------------------------------------------------------------- 1 | package debuglog.plugin 2 | 3 | import org.jetbrains.kotlin.codegen.ClassBuilder 4 | import org.jetbrains.kotlin.descriptors.FunctionDescriptor 5 | import org.jetbrains.kotlin.js.descriptorUtils.nameIfStandardType 6 | import org.jetbrains.kotlin.name.FqName 7 | import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin 8 | import org.jetbrains.org.objectweb.asm.MethodVisitor 9 | import org.jetbrains.org.objectweb.asm.Opcodes 10 | import org.jetbrains.org.objectweb.asm.Type 11 | import org.jetbrains.org.objectweb.asm.Type.LONG_TYPE 12 | import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter 13 | 14 | internal class DebugLogClassBuilder( 15 | private val debugLogAnnotations: List, 16 | delegateBuilder: ClassBuilder 17 | ) : DelegatingClassBuilder(delegateBuilder) { 18 | override fun newMethod( 19 | origin: JvmDeclarationOrigin, 20 | /* not used: */ access: Int, name: String, desc: String, signature: String?, exceptions: Array? 21 | ): MethodVisitor { 22 | val original = super.newMethod(origin, access, name, desc, signature, exceptions) 23 | 24 | val function = origin.descriptor as? FunctionDescriptor ?: return original 25 | if (debugLogAnnotations.none { function.annotations.hasAnnotation(FqName(it)) }) { 26 | // none of the debugLogAnnotations were on this function; return the original behavior 27 | return original 28 | } 29 | 30 | return object : MethodVisitor(Opcodes.ASM5, original) { 31 | override fun visitCode() { 32 | super.visitCode() 33 | InstructionAdapter(this).onEnterFunction(function) 34 | } 35 | 36 | override fun visitInsn(opcode: Int) { 37 | when (opcode) { 38 | // all of the opcodes that result in a return 39 | Opcodes.RETURN, // void return 40 | Opcodes.ARETURN, // object return 41 | Opcodes.IRETURN, Opcodes.FRETURN, Opcodes.LRETURN, Opcodes.DRETURN // int, float, long, double return 42 | -> { 43 | InstructionAdapter(this).onExitFunction(function) 44 | } 45 | } 46 | super.visitInsn(opcode) 47 | } 48 | } 49 | } 50 | } 51 | 52 | private fun InstructionAdapter.onEnterFunction(function: FunctionDescriptor) { 53 | getstatic("java/lang/System", "out", "Ljava/io/PrintStream;") 54 | 55 | anew(Type.getType("java/lang/StringBuilder")) 56 | dup() 57 | invokespecial("java/lang/StringBuilder", "", "()V", false) 58 | 59 | visitLdcInsn("⇢ ${function.name}(") 60 | 61 | invokevirtual( 62 | "java/lang/StringBuilder", 63 | "append", 64 | "(Ljava/lang/Object;)Ljava/lang/StringBuilder;", 65 | false 66 | ) 67 | 68 | function.valueParameters.forEachIndexed { i, parameter -> 69 | visitLdcInsn("${parameter.name}=") 70 | invokevirtual("java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false) 71 | 72 | val varIndex = i + 1 73 | when (parameter.type.unwrap().nameIfStandardType.toString()) { 74 | "Int" -> { 75 | visitVarInsn(Opcodes.ILOAD, varIndex) 76 | invokevirtual("java/lang/StringBuilder", "append", "(I)Ljava/lang/StringBuilder;", false) 77 | } 78 | "Long" -> { 79 | visitVarInsn(Opcodes.ILOAD, varIndex) 80 | invokevirtual("java/lang/StringBuilder", "append", "(J)Ljava/lang/StringBuilder;", false) 81 | } 82 | else -> { 83 | visitVarInsn(Opcodes.ALOAD, varIndex) 84 | invokevirtual( 85 | "java/lang/StringBuilder", 86 | "append", 87 | "(Ljava/lang/Object;)Ljava/lang/StringBuilder;", 88 | false 89 | ) 90 | } 91 | } 92 | 93 | if (i < function.valueParameters.lastIndex) { 94 | visitLdcInsn(", ") 95 | } else { 96 | // if this is the last one, we should append a close-paren instead of a comma 97 | visitLdcInsn(")") 98 | } 99 | invokevirtual( 100 | "java/lang/StringBuilder", 101 | "append", 102 | "(Ljava/lang/String;)Ljava/lang/StringBuilder;", 103 | false 104 | ) 105 | } 106 | 107 | invokevirtual("java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false) 108 | 109 | invokevirtual("java/io/PrintStream", "println", "(Ljava/lang/String;)V", false) 110 | 111 | invokestatic("java/lang/System", "currentTimeMillis", "()J", false) 112 | store(6001, LONG_TYPE) 113 | } 114 | 115 | private fun InstructionAdapter.onExitFunction(function: FunctionDescriptor) { 116 | dup() 117 | getstatic("java/lang/System", "out", "Ljava/io/PrintStream;") 118 | swap() 119 | 120 | anew(Type.getType("java/lang/StringBuilder")) 121 | dup() 122 | invokespecial("java/lang/StringBuilder", "", "()V", false) 123 | 124 | 125 | visitLdcInsn("⇠ ${function.name} [ran in ") 126 | invokevirtual( 127 | "java/lang/StringBuilder", 128 | "append", 129 | "(Ljava/lang/String;)Ljava/lang/StringBuilder;", 130 | false 131 | ) 132 | 133 | 134 | // Loads up a new System.currentTimeMillis() and subtracts the local variable #242 from it; which is the 135 | // System.currentTimeMillis() we stored at the start of this method. So we now have the elapsed time 136 | // this method took on the top of the stack 137 | invokestatic("java/lang/System", "currentTimeMillis", "()J", false) 138 | load(6001, LONG_TYPE) 139 | sub(LONG_TYPE) 140 | invokevirtual( 141 | "java/lang/StringBuilder", 142 | "append", 143 | "(J)Ljava/lang/StringBuilder;", 144 | false 145 | ) 146 | 147 | 148 | visitLdcInsn(" ms] = ") 149 | invokevirtual( 150 | "java/lang/StringBuilder", 151 | "append", 152 | "(Ljava/lang/String;)Ljava/lang/StringBuilder;", 153 | false 154 | ) 155 | 156 | swap() 157 | invokevirtual( 158 | "java/lang/StringBuilder", 159 | "append", 160 | "(Ljava/lang/Object;)Ljava/lang/StringBuilder;", 161 | false 162 | ) 163 | 164 | // Pop the StringBuilder and call toString() on it which ends up on the stack. Stack: String, System.out 165 | invokevirtual("java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false) 166 | 167 | // Pop the last 2 values (System.out, String) and call println with the value we constructed 168 | invokevirtual("java/io/PrintStream", "println", "(Ljava/lang/String;)V", false) 169 | } 170 | -------------------------------------------------------------------------------- /kotlin-plugin/src/main/kotlin/debuglog/plugin/DebugLogClassGenerationInterceptor.kt: -------------------------------------------------------------------------------- 1 | package debuglog.plugin 2 | 3 | import org.jetbrains.kotlin.codegen.ClassBuilder 4 | import org.jetbrains.kotlin.codegen.ClassBuilderFactory 5 | import org.jetbrains.kotlin.codegen.extensions.ClassBuilderInterceptorExtension 6 | import org.jetbrains.kotlin.diagnostics.DiagnosticSink 7 | import org.jetbrains.kotlin.resolve.BindingContext 8 | import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin 9 | 10 | abstract class DelegatingClassBuilder(val delegatingClassBuilder: ClassBuilder) : org.jetbrains.kotlin.codegen.DelegatingClassBuilder() { 11 | override fun getDelegate(): ClassBuilder = delegatingClassBuilder 12 | } 13 | 14 | class DebugLogClassGenerationInterceptor( 15 | val debugLogAnnotations: List 16 | ) : ClassBuilderInterceptorExtension { 17 | /** 18 | * Our [ClassBuilderFactory] has identical behavior to the [interceptedFactory] parameter given, but returns a 19 | * [DelegatingClassBuilder] that wraps any [ClassBuilder] returned by [ClassBuilderFactory.newClassBuilder] 20 | */ 21 | override fun interceptClassBuilderFactory( 22 | interceptedFactory: ClassBuilderFactory, 23 | bindingContext: BindingContext, 24 | diagnostics: DiagnosticSink 25 | ): ClassBuilderFactory = object : ClassBuilderFactory by interceptedFactory { 26 | override fun newClassBuilder(origin: JvmDeclarationOrigin) = 27 | DebugLogClassBuilder(debugLogAnnotations, interceptedFactory.newClassBuilder(origin)) 28 | } 29 | 30 | } 31 | 32 | -------------------------------------------------------------------------------- /kotlin-plugin/src/main/kotlin/debuglog/plugin/DebugLogCommandLineProcessor.kt: -------------------------------------------------------------------------------- 1 | package debuglog.plugin 2 | 3 | import com.google.auto.service.AutoService 4 | import org.jetbrains.kotlin.compiler.plugin.CliOption 5 | import org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor 6 | import org.jetbrains.kotlin.config.CompilerConfiguration 7 | import org.jetbrains.kotlin.config.CompilerConfigurationKey 8 | 9 | @AutoService(CommandLineProcessor::class) // don't forget! 10 | class DebugLogCommandLineProcessor : CommandLineProcessor { 11 | /** 12 | * Just needs to be consistent with the key for DebugLogGradleSubplugin#getCompilerPluginId 13 | */ 14 | override val pluginId: String = "debuglog" 15 | 16 | /** 17 | * Should match up with the options we return from our DebugLogGradleSubplugin. 18 | * Should also have matching when branches for each name in the [processOption] function below 19 | */ 20 | override val pluginOptions: Collection = listOf( 21 | CliOption( 22 | name = "enabled", valueDescription = "", 23 | description = "whether to enable the debuglog plugin or not" 24 | ), 25 | CliOption( 26 | name = "debugLogAnnotation", valueDescription = "", 27 | description = "fully qualified name of the annotation(s) to use as debug-log", 28 | required = true, allowMultipleOccurrences = true 29 | ) 30 | ) 31 | 32 | override fun processOption( 33 | option: CliOption, 34 | value: String, 35 | configuration: CompilerConfiguration 36 | ) = when (option.name) { 37 | "enabled" -> configuration.put(KEY_ENABLED, value.toBoolean()) 38 | "debugLogAnnotation" -> configuration.appendList(KEY_ANNOTATIONS, value) 39 | else -> error("Unexpected config option ${option.name}") 40 | } 41 | } 42 | 43 | val KEY_ENABLED = CompilerConfigurationKey("whether the plugin is enabled") 44 | val KEY_ANNOTATIONS = CompilerConfigurationKey>("our debuglog annotations") 45 | -------------------------------------------------------------------------------- /kotlin-plugin/src/main/kotlin/debuglog/plugin/DebugLogComponentRegistrar.kt: -------------------------------------------------------------------------------- 1 | package debuglog.plugin 2 | 3 | import com.google.auto.service.AutoService 4 | import org.jetbrains.kotlin.codegen.extensions.ClassBuilderInterceptorExtension 5 | import org.jetbrains.kotlin.com.intellij.mock.MockProject 6 | import org.jetbrains.kotlin.compiler.plugin.ComponentRegistrar 7 | import org.jetbrains.kotlin.config.CompilerConfiguration 8 | 9 | @AutoService(ComponentRegistrar::class) 10 | class DebugLogComponentRegistrar : ComponentRegistrar { 11 | override fun registerProjectComponents( 12 | project: MockProject, 13 | configuration: CompilerConfiguration 14 | ) { 15 | if (configuration[KEY_ENABLED] == false) { 16 | return 17 | } 18 | ClassBuilderInterceptorExtension.registerExtension( 19 | project, 20 | DebugLogClassGenerationInterceptor( 21 | debugLogAnnotations = configuration[KEY_ANNOTATIONS] 22 | ?: error("debuglog plugin requires at least one annotation class option passed to it") 23 | ) 24 | ) 25 | // TODO: IrGenerationExtension.registerExtension for Kotlin Native :) 26 | } 27 | } 28 | 29 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'debuglog' 2 | include 'gradle-plugin' 3 | include 'kotlin-plugin' 4 | include 'sample' 5 | 6 | --------------------------------------------------------------------------------