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
2 changes: 1 addition & 1 deletion docs/modules/style-guide/pages/index.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ Too many lines separate `foo` and `baz`.
Properties that override an existing property shouldn't have doc comments nor type annotations,
unless the type is intentionally overridden via `extends`.

[source%tested,{pkl}]
[source%parsed,{pkl}]
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Currently, amends "..." REPL statements don't do anything. In this PR, the header still mostly does nothing, but it will throw if the amends has a relative path.

This is because our REPL logic has changed; before the AstBuilder can visit an expression, it first needs to visit the module to collect names. In the process of visiting the module, it will validate this module header.

----
amends "myOtherModule.pkl"

Expand Down
29 changes: 29 additions & 0 deletions pkl-core/pkl-core.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ dependencies {

add("generatorImplementation", libs.javaPoet)
add("generatorImplementation", libs.truffleApi)
add("generatorImplementation", projects.pklParser)

javaExecutableConfiguration(project(":pkl-cli", "javaExecutable"))
}
Expand Down Expand Up @@ -124,6 +125,34 @@ tasks.test {
maxHeapSize = "1g"
}

val generateBaseModuleMemberRegistry by
tasks.registering(JavaExec::class) {
val outputDir = layout.buildDirectory.dir("generated/sources/baseModuleMembers")

val basePklFile = layout.projectDirectory.file("../stdlib/base.pkl")

inputs
.file(basePklFile)
.withPropertyName("basePkl")
.withPathSensitivity(PathSensitivity.RELATIVE)

outputs.dir(outputDir)

classpath =
generatorSourceSet.get().runtimeClasspath + tasks.processResources.get().outputs.files
mainClass = "org.pkl.core.generator.BaseModuleMemberRegistryGenerator"

argumentProviders.add(
CommandLineArgumentProvider {
listOf(basePklFile.asFile.absolutePath, outputDir.get().asFile.absolutePath)
}
)
}

sourceSets.main { java.srcDir(layout.buildDirectory.dir("generated/sources/baseModuleMembers")) }

tasks.compileJava { dependsOn(generateBaseModuleMemberRegistry) }

val testJavaExecutable by
tasks.registering(Test::class) {
configureExecutableTest("LanguageSnippetTestsEngine")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
/*
* Copyright © 2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* 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
*
* https://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 org.pkl.core.generator;

import com.palantir.javapoet.CodeBlock;
import com.palantir.javapoet.JavaFile;
import com.palantir.javapoet.MethodSpec;
import com.palantir.javapoet.TypeName;
import com.palantir.javapoet.TypeSpec;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.lang.model.element.Modifier;
import org.pkl.parser.Parser;
import org.pkl.parser.syntax.Modifier.ModifierValue;

public final class BaseModuleMemberRegistryGenerator {
Copy link
Copy Markdown
Member

@bioball bioball May 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This generates a class called BaseModuleMembers, and gets called as part of java compilation.

This generates a class that looks something like:

public final class BaseModuleMembers {
  private BaseModuleMembers() {
  }

  public static boolean hasProperty(String name) {
    return switch (name) {
      case "AlsoKnownAs",
        "Annotation",
        "Any",
        "BaseValueRenderer",
        "Boolean",
        "Bytes",
        "BytesRenderer",
        "Char",
        "Charset",
        "Class",
        "Collection",
        "Comparable",
        "ConvertProperty",
        // etc
        "YamlRenderer" -> true;
      default -> false;
    }
  }
}

This is used by SymbolTable to figure out if some name is defined on the base module or not.
This is much faster than looking up members on BaseModule.getModule().

record Members(Set<String> properties, Set<String> methods) {}

public static void main(String[] args) {
if (args.length < 2) {
throw new IllegalArgumentException(
"Usage: BaseModuleMemberRegistryGenerator <path-to-base.pkl> <output-dir>");
}
var members = buildMembers(args[0]);
generateJavaCode(members, args[1]);
}

private static void generateJavaCode(Members members, String outputDir) {
var privateConstructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build();

var hasPropertyMethod =
buildHasMethod("hasProperty", members.properties().stream().sorted().toList());
var hasMethodMethod = buildHasMethod("hasMethod", members.methods().stream().sorted().toList());

var classSpec =
TypeSpec.classBuilder("BaseModuleMembers")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addMethod(privateConstructor)
.addMethod(hasPropertyMethod)
.addMethod(hasMethodMethod)
.build();

var javaFile =
JavaFile.builder("org.pkl.core.runtime", classSpec)
.addFileComment("DO NOT EDIT — generated by BaseModuleMemberRegistryGenerator")
.build();

try {
javaFile.writeTo(Path.of(outputDir));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}

private static MethodSpec buildHasMethod(String methodName, List<String> names) {
var code = CodeBlock.builder();
code.add("return switch (name) {\n");
code.indent();
code.add("case $S", names.get(0));
if (names.size() == 1) {
code.add(" -> true;\n");
} else {
code.add(",\n");
code.indent();
for (var i = 1; i < names.size() - 1; i++) {
code.add("$S,\n", names.get(i));
}
code.add("$S -> true;\n", names.get(names.size() - 1));
code.unindent();
}
code.add("default -> false;\n");
code.unindent();
code.add("};\n");

return MethodSpec.methodBuilder(methodName)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.returns(TypeName.BOOLEAN)
.addParameter(String.class, "name")
.addCode(code.build())
.build();
}

private static String getBaseModuleText(String path) {
try {
return Files.readString(Path.of(path));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}

private static Members buildMembers(String basePklPath) {
var text = getBaseModuleText(basePklPath);
var parsed = new Parser().parseModule(text);
var properties = new HashSet<String>();
var methods = new HashSet<String>();
for (var property : parsed.getProperties()) {
if (isLocal(property.getModifiers())) {
continue;
}
properties.add(property.getName().getValue());
}
for (var clazz : parsed.getClasses()) {
if (isLocal(clazz.getModifiers())) {
continue;
}
properties.add(clazz.getName().getValue());
}
for (var typealias : parsed.getTypeAliases()) {
if (isLocal(typealias.getModifiers())) {
continue;
}
properties.add(typealias.getName().getValue());
}
for (var method : parsed.getMethods()) {
if (isLocal(method.getModifiers())) {
continue;
}
methods.add(method.getName().getValue());
}
return new Members(properties, methods);
}

private static boolean isLocal(List<org.pkl.parser.syntax.Modifier> modifiers) {
return modifiers.stream().anyMatch((it) -> it.getValue() == ModifierValue.LOCAL);
}
}
10 changes: 10 additions & 0 deletions pkl-core/src/main/java/org/pkl/core/ast/VmModifier.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ private VmModifier() {}

public static final int GLOB = 0x1000;

public static final int AMBIGUOUS_LOCALITY = 0x10000;

// modifier sets

public static final int NONE = 0;
Expand Down Expand Up @@ -126,6 +128,10 @@ public static boolean isConst(int modifiers) {
return (modifiers & CONST) != 0;
}

public static boolean isAmbiguousLocality(int modifiers) {
return (modifiers & AMBIGUOUS_LOCALITY) != 0;
}

public static boolean isElement(int modifiers) {
return (modifiers & ELEMENT) != 0;
}
Expand Down Expand Up @@ -154,6 +160,10 @@ public static boolean isConstOrFixed(int modifiers) {
return (modifiers & (CONST | FIXED)) != 0;
}

public static boolean hasSameModifier(int modifiersA, int modifiersB, int modifier) {
return (modifiersA & modifier) == (modifiersB & modifier);
}

public static Set<Modifier> export(int modifiers, boolean isClass) {
var result = EnumSet.noneOf(Modifier.class);

Expand Down
Loading
Loading