Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 46 additions & 16 deletions design/pattern/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Classic patterns of objects for Kotlin and Java, grouped as the Gang of Four gro
them: creational, structural, behavioral, plus the patterns of Patterns of Enterprise
Application Architecture by Fowler in a group of our own, enterprise. A package per group,
a package per pattern inside it. Plain Kotlin, no framework; adapters come as modules of their own:
`semantic-pattern-spring` for Spring.
`semantic-pattern-spring` for Spring, `semantic-pattern-ksp` for the checks of KSP at compilation.

In place so far: a registry with its store, a registrar and a factory in the creational group;
the contracts of Composite, Decorator and Proxy and the annotations of Facade in the structural one;
Expand Down Expand Up @@ -470,8 +470,8 @@ marker of its own. The rules of the two annotations:
the database.
- A type counts with its arguments in all the rules: a `List<FileEntity>` or a `CrudRepository<FileEntity, FileId>`
is a type of the subsystem.
- `@Facade` goes on a class, not an interface, and names one subsystem at least; each annotation it names carries
`@Facade.Subsystem`.
- `@Facade` goes on a class, not an interface or an annotation, and names one subsystem at least; each annotation it
names carries `@Facade.Subsystem`.
- A class carries the marker of one subsystem at most, and a facade carries none: a facade stands outside its
subsystems.

Expand All @@ -484,15 +484,15 @@ writes no name, a Java one writes `@Facade(subsystems = FileSubsystem.class)`.
The way past the facade is a marker: a class that carries one joins its subsystem, and the rules take it at its
word. A review sees the marker, and a search by it finds each class that joined a subsystem.

The annotations check nothing themselves: the processor of the plan checks the rules when a module is compiled, the
check of Spring the first one when the application starts. Kotlin has no visibility of a package, as Java has, and
`internal` covers a whole Gradle module: in one service every class of a subsystem is open to every client. The
compiler closes a class to those that do not declare `@OptIn` of its marker, if the marker is annotated with
`@RequiresOptIn` of the level `ERROR`, as `@InternalCoroutinesApi` closes the internals of kotlinx.coroutines.
Kotlin takes no other annotation for `@OptIn`, though: a facade would name its subsystem twice, in `@Facade` and in
`@OptIn`. The marker here is a plain annotation, and the checks of the plan read it from the classes; the compiler
still checks the bodies of functions for a project that adds `@RequiresOptIn` to its marker and `@OptIn` to its
facade.
The annotations check nothing themselves: `semantic-pattern-ksp` checks the rules of the annotations when a module
is compiled, and the plan adds the other rules to it and the check of Spring when the application starts. Kotlin has
no visibility of a package, as Java has, and `internal` covers a whole Gradle module: in one service every class of
a subsystem is open to every client. The compiler closes a class to those that do not declare `@OptIn` of its
marker, if the marker is annotated with `@RequiresOptIn` of the level `ERROR`, as `@InternalCoroutinesApi` closes
the internals of kotlinx.coroutines. Kotlin takes no other annotation for `@OptIn`, though: a facade would name its
subsystem twice, in `@Facade` and in `@OptIn`. The marker here is a plain annotation, and the checks read it from
the classes; the compiler still checks the bodies of functions for a project that adds `@RequiresOptIn` to its
marker and `@OptIn` to its facade.

`@Facade` and the marker are annotations, not interfaces, as the layers of `semantic-explicit` are: a facade has no
operation that every facade shares, and the annotations ask nothing of a class. `@Facade.Subsystem` marks an
Expand Down Expand Up @@ -527,13 +527,43 @@ The samples:
`@NamedInterface` opens one of them. `ApplicationModules.verify()` fails a test on an access to the internals of
a module.

### KSP

`semantic-pattern-ksp` is a processor of KSP that fails the build of a module on a broken rule, at the line that
breaks it, as Dagger fails a build on a broken graph of dependencies. Each module with facades or subsystems applies
it:

```kotlin
plugins {
id("com.google.devtools.ksp") version "2.3.12"
}

dependencies {
implementation("pro.vlprojects.semantic:semantic-pattern:<version>")
ksp("pro.vlprojects.semantic:semantic-pattern-ksp:<version>")
}
```

A facade that names no subsystem stops the build with:

```text
e: [ksp] /…/FileFacade.kt:3: Facade FileFacade names no subsystem
```

- It checks the annotation of each facade and the markers each class of the module is annotated with, nested ones
too, in Kotlin and in Java, under a type alias as well. The markers of supertypes and the rules of members and of
clients come next, by the plan.
- `FacadeSymbolProcessorProvider` is listed in `META-INF/services`, where KSP finds its processors by `ServiceLoader`.

### Plan of Facade

1. `Facade` and `Facade.Subsystem`.
2. `semantic-pattern-ksp`, a processor of KSP that fails the build of a module on a broken rule, at the line
that breaks it, as Dagger fails a build on a broken graph of dependencies. KSP sees the declarations, not the
bodies of functions: a class of a subsystem made in a body goes unseen. Each module with clients applies it.
3. A check of `semantic-pattern-spring` that stops the startup on an injection that breaks the first rule, as
2. `semantic-pattern-ksp`, a processor of KSP that checks the rules of the annotations at compilation.
3. The rule of public members of a facade in `semantic-pattern-ksp`.
4. The rules of clients in `semantic-pattern-ksp`: the constructors, properties and signatures of functions of each
class and each top-level declaration, and the markers of supertypes. KSP sees no bodies of functions: a class of
a subsystem made in a body goes unseen.
5. A check of `semantic-pattern-spring` that stops the startup on an injection that breaks the first rule, as
`ApplicationModules.verify()` of Spring Modulith checks the modules in a test. It reads the dependencies Spring
records between beans, as `getDependentBeans` of `ConfigurableBeanFactory` tells them, and catches beans that
no processor saw. `@Facade` and the markers are looked up on the user class of a bean and its interfaces
Expand Down
5 changes: 5 additions & 0 deletions design/pattern/ksp/api/semantic-pattern-ksp.api

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions design/pattern/ksp/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
plugins {
id("semantic.kotlin-library")
}

dependencies {
implementation(project(":semantic-pattern"))
implementation(project(":semantic-ksp-helper"))
compileOnly(libs.ksp.symbol.processing.api)

testImplementation(libs.ksp.symbol.processing.api)
testImplementation(libs.kctfork.ksp)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package pro.vlprojects.semantic.pattern.structural.facade

import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSAnnotation
import com.google.devtools.ksp.symbol.KSType
import pro.vlprojects.semantic.ksp.helper.getFirstAnnotationOrNull
import pro.vlprojects.semantic.ksp.helper.getTypeValues
import pro.vlprojects.semantic.ksp.helper.resolveClassDeclaration

internal class FacadeAnnotation private constructor(val symbol: KSAnnotation) {

fun hasSubsystems() = this
.getSubsystemTypes()
.isNotEmpty()

// An unresolved class is left to the compiler, which names it better.
fun getSubsystems() = this
.getSubsystemTypes()
.filterNot(KSType::isError)
.mapNotNull(KSType::resolveClassDeclaration)

private fun getSubsystemTypes() = this.symbol.getTypeValues(Facade::subsystems.name)

companion object Factory {

fun find(declaration: KSAnnotated) = declaration
.getFirstAnnotationOrNull(Facade::class)
?.let(::FacadeAnnotation)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package pro.vlprojects.semantic.pattern.structural.facade

import com.google.devtools.ksp.processing.KSPLogger
import com.google.devtools.ksp.symbol.ClassKind
import com.google.devtools.ksp.symbol.KSClassDeclaration
import pro.vlprojects.semantic.ksp.helper.getShortName

internal class FacadeOnClassChecker(private val logger: KSPLogger) {

fun check(declaration: KSClassDeclaration, annotation: FacadeAnnotation) {
val facadeName = declaration.getShortName()

when (declaration.classKind) {
ClassKind.INTERFACE -> this.reportMisplaced(annotation, "the interface $facadeName")
ClassKind.ANNOTATION_CLASS -> this.reportMisplaced(annotation, "the annotation $facadeName")
else -> Unit
}
}

private fun reportMisplaced(annotation: FacadeAnnotation, target: String) = this.logger.error(
"@Facade goes on a class, not on $target",
annotation.symbol,
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package pro.vlprojects.semantic.pattern.structural.facade

import com.google.devtools.ksp.processing.KSPLogger
import com.google.devtools.ksp.symbol.KSClassDeclaration
import pro.vlprojects.semantic.ksp.helper.getShortName

internal class FacadeOutsideSubsystemsChecker(private val logger: KSPLogger) {

fun check(declaration: KSClassDeclaration) {
val facadeName = declaration.getShortName()

SubsystemMembership
.findAll(declaration)
.forEach { membership ->
val subsystemName = membership.describe()

this.logger.error(
"Facade $facadeName carries $subsystemName: a facade stands outside its subsystems",
membership.annotation,
)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package pro.vlprojects.semantic.pattern.structural.facade

import com.google.devtools.ksp.processing.KSPLogger
import com.google.devtools.ksp.symbol.KSClassDeclaration
import pro.vlprojects.semantic.ksp.helper.getShortName

internal class FacadeSubsystemsNotEmptyChecker(private val logger: KSPLogger) {

fun check(declaration: KSClassDeclaration, annotation: FacadeAnnotation) {
if (!annotation.hasSubsystems()) {
val facadeName = declaration.getShortName()

this.logger.error("Facade $facadeName names no subsystem", annotation.symbol)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package pro.vlprojects.semantic.pattern.structural.facade

import com.google.devtools.ksp.processing.KSPLogger
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.processing.SymbolProcessor
import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSFile
import pro.vlprojects.semantic.ksp.helper.getDeclaredClasses

internal class FacadeSymbolProcessor(logger: KSPLogger) : SymbolProcessor {

private val singleSubsystemMembershipChecker = SingleSubsystemMembershipChecker(logger)

private val facadeOnClassChecker = FacadeOnClassChecker(logger)

private val facadeSubsystemsNotEmptyChecker = FacadeSubsystemsNotEmptyChecker(logger)

private val subsystemAnnotationPresenceChecker = SubsystemAnnotationPresenceChecker(logger)

private val facadeOutsideSubsystemsChecker = FacadeOutsideSubsystemsChecker(logger)

override fun process(resolver: Resolver): List<KSAnnotated> {
resolver
.getNewFiles()
.flatMap(KSFile::declarations)
.filterIsInstance<KSClassDeclaration>()
.flatMap(::flattenClasses)
.forEach(::checkClass)

return emptyList()
}

private fun checkClass(declaration: KSClassDeclaration) {
this.singleSubsystemMembershipChecker.check(declaration)

FacadeAnnotation
.find(declaration)
?.let { annotation -> this.checkFacade(declaration, annotation) }
}

private fun checkFacade(declaration: KSClassDeclaration, annotation: FacadeAnnotation) {
this.facadeOnClassChecker.check(declaration, annotation)
this.facadeSubsystemsNotEmptyChecker.check(declaration, annotation)
this.subsystemAnnotationPresenceChecker.check(declaration, annotation)
this.facadeOutsideSubsystemsChecker.check(declaration)
}

private fun flattenClasses(declaration: KSClassDeclaration): Sequence<KSClassDeclaration> = declaration
.getDeclaredClasses()
.flatMap(::flattenClasses)
.let { nested -> sequenceOf(declaration) + nested }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package pro.vlprojects.semantic.pattern.structural.facade

import com.google.devtools.ksp.processing.SymbolProcessor
import com.google.devtools.ksp.processing.SymbolProcessorEnvironment
import com.google.devtools.ksp.processing.SymbolProcessorProvider

public class FacadeSymbolProcessorProvider : SymbolProcessorProvider {

override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor =
FacadeSymbolProcessor(environment.logger)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package pro.vlprojects.semantic.pattern.structural.facade

import com.google.devtools.ksp.processing.KSPLogger
import com.google.devtools.ksp.symbol.KSClassDeclaration
import pro.vlprojects.semantic.ksp.helper.getShortName
import pro.vlprojects.semantic.ksp.helper.hasAnnotation

internal class SingleSubsystemMembershipChecker(private val logger: KSPLogger) {

// A marker on a facade is reported as a facade inside a subsystem.
fun check(declaration: KSClassDeclaration) {
if (!declaration.hasAnnotation(Facade::class)) {
this.checkMemberships(declaration)
}
}

private fun checkMemberships(declaration: KSClassDeclaration) {
val memberships = SubsystemMembership.findAll(declaration)

if (memberships.size > 1) {
val name = declaration.getShortName()
val subsystemNames = memberships.joinToString(transform = SubsystemMembership::describe)
val symbol = memberships.last().annotation

this.logger.error("$name carries the markers of several subsystems: $subsystemNames", symbol)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package pro.vlprojects.semantic.pattern.structural.facade

import com.google.devtools.ksp.processing.KSPLogger
import com.google.devtools.ksp.symbol.KSClassDeclaration
import pro.vlprojects.semantic.ksp.helper.getShortName
import pro.vlprojects.semantic.ksp.helper.hasAnnotation

internal class SubsystemAnnotationPresenceChecker(private val logger: KSPLogger) {

fun check(declaration: KSClassDeclaration, annotation: FacadeAnnotation) {
val facadeName = declaration.getShortName()

annotation
.getSubsystems()
.filterNot { subsystem -> subsystem.hasAnnotation(Facade.Subsystem::class) }
.map(KSClassDeclaration::getShortName)
.forEach { subsystemName ->
this.logger.error(
"Facade $facadeName names @$subsystemName, which is not marked with @Facade.Subsystem",
annotation.symbol,
)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package pro.vlprojects.semantic.pattern.structural.facade

import com.google.devtools.ksp.symbol.KSAnnotation
import com.google.devtools.ksp.symbol.KSClassDeclaration
import pro.vlprojects.semantic.ksp.helper.getQualifiedName
import pro.vlprojects.semantic.ksp.helper.getShortName
import pro.vlprojects.semantic.ksp.helper.hasAnnotation
import pro.vlprojects.semantic.ksp.helper.resolveClassDeclaration

internal class SubsystemMembership private constructor(
val annotation: KSAnnotation,
private val subsystem: KSClassDeclaration,
) {

fun getSubsystemName() = this.subsystem.getQualifiedName()

fun describe() = "@${this.subsystem.getShortName()}"

companion object Factory {

fun findAll(declaration: KSClassDeclaration) = declaration.annotations
.mapNotNull(::createOrNull)
.distinctBy(SubsystemMembership::getSubsystemName)
.toList()

private fun createOrNull(annotation: KSAnnotation) = annotation
.resolveClassDeclaration()
?.takeIf { subsystem -> subsystem.hasAnnotation(Facade.Subsystem::class) }
?.let { subsystem -> SubsystemMembership(annotation, subsystem) }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pro.vlprojects.semantic.pattern.structural.facade.FacadeSymbolProcessorProvider
Loading
Loading