• Stars
    star
    362
  • Rank 117,637 (Top 3 %)
  • Language
    Kotlin
  • License
    Apache License 2.0
  • Created about 4 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A plugin for Kotlin compiler for compile-time reflection

JetBrains Research Gradle Build Run deteKT Run diKTat

Reflekt

Reflekt is a compile-time reflection library that leverages the flows of the standard reflection approach and can find classes, objects (singleton classes) or functions by some conditions in compile-time.

Instead of relying on JVM reflection, Reflekt performs compile-time resolution of reflection queries using Kotlin compiler analysis, providing a convenient reflection API without actually using reflection.

Reflekt is a joint project of JetBrains Research and the Kotless team. The main reason for its creation was the necessity of GraalVM support in modern Java applications, especially on Serverless workloads. With the help of the Reflekt project, Kotless will be able to provide access to GraalVM to users of historically reflection-based frameworks such as Spring or their own Kotless DSL.

We have implemented two approaches - searching classes\objects or functions via a limited DSL and by custom user condition via an extended DSL. The first one will be called Reflekt, and the second SmartReflekt.

Restrictions. Reflekt analyses only .kt files (in the project and in the libraries); uses Kotlin 1.7.0. Reflekt does not currently support incremental compilation.

Note, we use Intermediate Representation of code in this plugin. It means, that Reflekt can be used for all available platforms: JVM, Native and JavaScript.


Table of contents

Getting started

Note, currently we support the following Reflekt and Kotlin versions: 1.7.0 (only for local usage), 1.5.30, 1.5.21, 1.5.20, 1.5.10, 1.5.0

Reflekt uses Gradle. If you have a Gradle project, you only need to do three things.

Firstly, set up the Reflekt plugin. You need to apply the plugin. In the build.gradle.kts file, add the following lines in the plugins section:

plugins {
    // Version of Kotlin should be 1.5.0+ that supports IR backend
    kotlin("jvm") version "1.7.0"

    // Please, use the same version with the Kotlin version in your project
    id("org.jetbrains.reflekt") version "1.7.0"

    // Necessary only for this example, for Kotless library
    id("io.kotless") version "0.1.6"
}

At the same time, add to the settings.gradle.kts file the following snippet:

pluginManagement {
    repositories {
        //add the dependency to Reflekt Maven repository
        maven(url = uri("https://packages.jetbrains.team/maven/p/reflekt/reflekt"))

        // Necessary only for this example, for Kotless library
        maven(url = uri("https://plugins.gradle.org/m2/"))
    }
}

Secondly, add the Reflekt DSL as a library to your application. In the build.gradle.kts file, add the following lines in the dependencies section:

dependencies {
    // The version here and the version in the plugins sections should be equal
    implementation("org.jetbrains.reflekt", "reflekt-dsl", "1.7.0")

    // Necessary for this example
    compileOnly("io.kotless", "kotless-lang", "0.1.6")
}

At the same time, add the following lines in the repositories section:

repositories {
    //... Any other repositories
    // add Reflekt repository for libraries resolving
    maven(url = uri("https://packages.jetbrains.team/maven/p/reflekt/reflekt"))
}

Thirdly, customize the Reflekt plugin. In the build.gradle.kts file, add the reflekt object:

reflekt {
    // Enable or disable Reflekt plugin
    enabled = true
}

Please note that the Reflekt can also analyze the files from the external libraries. Reflekt can handle only libraries from the dependencies section and DependencyHandlers of them should be canBeResolve = True, e.g.:

val reflektConfiguration by configurations.creating {
    isCanBeResolved = true
}

configurations["implementation"].extendsFrom(reflektConfiguration)

Also, this library should contain a special file ReflektMeta. The last point means the library should use Reflekt with the following configuration:

reflekt {
    // Enable or disable Reflekt plugin
    enabled = true
    // Create ReflektMeta file
    toSaveMetadata = true
}

To avoid some bugs and enable IR, please add the following compilation settings for Java and Kotlin in the build.gradle.kts file:

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

kotlin.jvmToolchain(11)

tasks.withType<KotlinCompile> {
    kotlinOptions {
        // Current Reflekt version does not support incremental compilation process
        incremental = false
    }
}

Note: Please note that the current version of Reflekt and SmartReflekt does not support incremental compilation process

This gives you access to the limited Reflekt DSL interfaces.

This gives you access to the extended SmartReflekt DSL, which allow filtering classes/objects\functions by user condition.

Now you can use the Reflekt plugin to find objects, classes, and functions in your project:

val objects = Reflekt.objects().withSupertype<AInterface>()
    .withAnnotations<AInterface>(FirstAnnotation::class, SecondAnnotation::class).toList()

val classes = Reflekt.classes().withSupertype<BInterface>().toSet()

val functions = Reflekt.functions().withAnnotations<() -> Unit>().toList()

And the SmartReflekt plugin:

val objects = SmartReflekt.objects<AInterface>().filter { TODO("some user's condition") }.resolve()

val classes = SmartReflekt.classes<BInterface>().filter { TODO("some user's condition") }.resolve()

val functions =
    SmartReflekt.functions<() -> Unit>().filter { TODO("some user's condition") }.toList()

Local start

You can use any unpublished Reflekt version. You should do the following steps:

  • Clone the Reflekt project (the official repo, any fork, branch, etc.).
  • Build the project ./gradlew build
  • Publish the project to maven local ./gradlew publishToMavenLocal
  • Add mavenLocal() in the repositories section in the build.gradle.kts file in your project:
repositories {
    mavenLocal()
}

Please note that if you build a Reflekt version with a customized version number, write this version in the plugins and dependencies sections.

Supported features

  • Compile-time reflection by Reflekt DSL for multi-module projects:
    • project's files
    • external libraries
  • Compile-time reflection by custom users' filters for multi-module projects by SmartReflekt DSL
    • project's files
    • external libraries
  • Bytecode generation -> IR generation
  • Incremental compilation process
  • Search in all modules of the project
  • Code generation.

Note: We analyze modules independently of each other. If an object\class\function is in module A, and you run Reflekt in module B, then the object\class\function will not be found. You can find this example in the examples folder.

Examples

Any explanation becomes much better with a proper example.

In the repository's examples folder, you can find an example project that uses the Reflekt plugin by Reflekt DSL and by SmartReflekt DSL.

You can also find many examples of searching algorithm work in the test folder.

By default, the examples project uses Reflekt from the local maven repository. If you would like to use a released version, please, uncomment the corresponding lines in the setting.gradle.kts and build.gradle.kts files in the examples project.

Want to know more?

The Reflekt code itself is widely documented, and you can take a look into its interfaces to get to know Reflekt better.

You may ask questions and participate in discussions on repository issues.

Contribution

Please be sure to review project's contributing guidelines to learn how to help the project.

More Repositories

1

astminer

A library for mining of path-based representations of code (and more)
Kotlin
280
star
2

kinference

Running ONNX models in vanilla Kotlin
Kotlin
151
star
3

viktor

Efficient f64-only ndarray in Kotlin
Kotlin
119
star
4

RefactorInsight

An IntelliJ IDEA plugin that detects refactorings in Git commits
Java
103
star
5

anti-copy-paster

A plugin for IntelliJ IDEA for extracting code duplicates into a new method as soon as they are introduced.
Java
101
star
6

code2seq

PyTorch's implementation of the code2seq model.
Python
61
star
7

snakecharm

Plugin for PyCharm / IntelliJ IDEA Platform IDEs which adds support for Snakemake language.
Python
58
star
8

commit_message_generation

🌟 replication package for 📜 From Commit Message Generation to History-Aware Commit Message Completion, ASE 2023
Python
56
star
9

psiminer

A Tool for Mining Rich Abstract Syntax Trees from Code
Kotlin
56
star
10

IntelliJDeodorant

The project is not actively supported.
Java
56
star
11

npy

NPY and NPZ support for the JVM
Kotlin
51
star
12

PyNose

A test smell detector for Python.
Kotlin
49
star
13

TestSpark

TestSpark - a plugin for generating unit tests. TestSpark natively integrates different AI-based test generation tools and techniques in the IDE. Started by SERG TU Delft. Currently under implementation by JetBrains Research (Software Testing Research) for research purposes.
Kotlin
47
star
14

sosed

Finding similar repositories on GitHub
Python
45
star
15

coqpilot

VSCode extension that is designed to help automate writing of Coq proofs.
TypeScript
44
star
16

pubtrends

Scientific literature explorer. Runs a Pubmed or Semantic Scholar search and allows user to explore high-level structure of result papers
Jupyter Notebook
35
star
17

bioinf-commons

Bioinformatics library in Kotlin
Kotlin
29
star
18

pubtrends-review

Automatic generation of reviews of scientific papers
Jupyter Notebook
28
star
19

buckwheat

A multi-language tokenizer for extracting identifiers from source code.
Jupyter Notebook
24
star
20

Lupa

A framework for the large scale analysis of programming language usage.
Jupyter Notebook
24
star
21

sorrel

Plugin for checking license compatibility in IntelliJ IDEA
Kotlin
22
star
22

embeddings-for-trees

Set of PyTorch modules for developing and evaluating different algorithms for embedding trees.
Python
22
star
23

lca-baselines

Baselines for all tasks from Long Code Arena benchmarks 🏟️
Python
22
star
24

authorship-detection

Evaluation of source authorship attribution tool
Python
21
star
25

paddle

Young and dynamic build system for Python
Kotlin
20
star
26

python-change-miner

A tool for mining graph-based change patterns in Python code
Python
19
star
27

IRen

Java
19
star
28

bumblebee

An IntelliJ-based IDE plugin for Python AST transformations
Kotlin
18
star
29

Matroskin

A library for the large scale analysis of Jupyter notebooks
Python
18
star
30

kotlinRMiner

Detects performed refactorings in the changes in Kotlin code
Java
16
star
31

tnm

Kotlin
14
star
32

cuBool

Sparse linear Boolean algebra for Nvidia Cuda
C++
14
star
33

adhd-study

Jupyter Notebook
13
star
34

big

BigWIG, BigBED and TDF for the JVM
Kotlin
12
star
35

spbla

Sparse Boolean linear algebra for Nvidia Cuda, OpenCL and CPU computations
C++
12
star
36

CFPQ_PyAlgo

The collection of Context-Free Path Querying algorithms
Python
10
star
37

jbr

JBR Genome Browser
Dockerfile
10
star
38

gorshochek

[WIP] A tool for C++ code modification to augment data for clone detection tools
C++
10
star
39

hldiff

Language-independent high-level differencing tool
Kotlin
10
star
40

CFPQ-on-GPGPU

Cuda
10
star
41

data-driven-type-migration

An IntelliJ IDEA plugin improving type migration refactoring using inferred type conversion rules
Java
9
star
42

task-tracker-plugin

Kotlin
8
star
43

revizor

A data-driven PyCharm plugin for code enhancement using graph patterns.
Kotlin
8
star
44

spla

An open-source generalized sparse linear algebra framework with vendor-agnostic GPUs accelerated computations
C++
8
star
45

kotlin-code-anomaly

Code anomaly detection in Kotlin compiler
Jupyter Notebook
7
star
46

span

SPAN Semi-supervised Peak Analyzer
Kotlin
7
star
47

batcore

Baselines and testing framework for code reviewer recommendation
Python
7
star
48

DeepBugsPlugin

Deep learning-based bug detector for IntelliJ
Kotlin
6
star
49

CoFRA

A CFL-r-based static analyser
C#
6
star
50

code-summarization-dataset

Kotlin
6
star
51

task-tracker-post-processing

Python
6
star
52

CFPQ_Data

Graphs and grammars for Context-Free Path Querying algorithms evaluation.
Python
6
star
53

code-completion-benchmark-toolkit

IntelliJ Code Completion Benchmarking Toolkit
Kotlin
6
star
54

JetNN

Python
6
star
55

bitcode-tools

Gradle tools to analyze bitcode of a Kotlin/Native project
Kotlin
5
star
56

litmuskt

Litmus testing tool for Kotlin/Native (WIP)
Kotlin
5
star
57

scasat-smk-pipeline

Single cell ATAC-Seq Snakemake pipeline
Python
5
star
58

ReSplit

An algorithm that re-splits Jupyter notebooks by merging and splitting their cells.
Jupyter Notebook
5
star
59

python-ml-type-hints

5
star
60

bus-factor-explorer

A web app for exploring Bus Factor of GitHub projects by analyzing the commit history.
Jupyter Notebook
5
star
61

code-quality-ij-server

Kotlin
5
star
62

planning-library

🌟 library with planning algorithms for AI Agents
Python
5
star
63

fine-tuning-ml-models

Python
5
star
64

kinference-primitives

Kotlin
5
star
65

sc-atacseq-explorer

Single cell ATAC-Seq preprocessing for single cell explorer
Jupyter Notebook
5
star
66

depminer

Kotlin
5
star
67

refactoring-workshop-demo

Kotlin
4
star
68

kinference-examples

Kotlin
4
star
69

louvain

Louvain method for community detection, implemented in Kotlin
Kotlin
4
star
70

topias

IntelliJ plugin for visualization of VCS changes statistics.
Java
4
star
71

docs-fine-tuning

Python
4
star
72

contrastive-learning-framework

Python
4
star
73

cncourse

Materials for Computational Neuroscience Course 2020
4
star
74

file-importance

ICTL + BILSEN project on using file importance in risk assessment
Python
4
star
75

overcoming

Jupyter Notebook
4
star
76

HumanEval-Dafny

Translating humaneval into dafny
Dafny
4
star
77

code-changes-clustering

Jupyter Notebook
4
star
78

similar-python-dependencies

Analyzing dependencies in Python projects and their dynamics
Python
4
star
79

tasktracker-3

Kotlin
3
star
80

bugs-classification

Java
3
star
81

KotlinMemoryModelResearch

3
star
82

nn-design-smells

Python
3
star
83

plugin-utilities

Repository for utilities to create and test IntelliJ plugins
Kotlin
3
star
84

MR-loader

Kotlin
3
star
85

chipseq-smk-pipeline

ChIP-Seq processing pipeline on snakemake
Python
3
star
86

lumberjack

Exploring automated BPE-like approaches to reduce the size of parse-trees
Kotlin
3
star
87

extract-method-experiments

Jupyter Notebook
3
star
88

FormalLanguageConstrainedReachability-LectureNotes

Материалы по достижимости с ограничениями в терминах формальных языков
TeX
3
star
89

ai-agents-code-editing

Exploring context retrieval strategies for code editing
Python
3
star
90

tag-prediction

2
star
91

effective-inference

2
star
92

mads

Multi-Agent Dynamic Simulation framework
Kotlin
2
star
93

metrics-evaluation

Evaluating metrics for code generation
Python
2
star
94

feature-recommendations

Python
2
star
95

spla-bench

Benchmark suite for performance analysis of sparse graphs frameworks
Python
2
star
96

formal-lang-course

Курс по формальным языкам: шаблон для домашних работ + материалы
Python
2
star
97

linktracker

Kotlin
2
star
98

kinference-compiler

Build ONNX models in compile-time
Kotlin
2
star
99

agents-eval

Jupyter Notebook
2
star
100

fishbone

Fishbone Ishikawa diagrams construction and visualising
JavaScript
2
star