diff --git a/pkl-cli/src/test/kotlin/org/pkl/cli/CliCommandRunnerTest.kt b/pkl-cli/src/test/kotlin/org/pkl/cli/CliCommandRunnerTest.kt index 521e69387..6b53dd713 100644 --- a/pkl-cli/src/test/kotlin/org/pkl/cli/CliCommandRunnerTest.kt +++ b/pkl-cli/src/test/kotlin/org/pkl/cli/CliCommandRunnerTest.kt @@ -1286,4 +1286,41 @@ class CliCommandRunnerTest { ;;""" ) } + + @Test + fun `exec of amended subcommand`() { + writePklFile( + "sub.pkl", + """ + extends "pkl:Command" + target: String + """ + .trimIndent(), + ) + val moduleUri = + writePklFile( + "cmd.pkl", + """ + amends "pkl:Command" + import "sub.pkl" + + command { + name = "root" + subcommands { + new sub { target = "foo" } + } + } + """ + .trimIndent(), + ) + val output = runToStdout(CliBaseOptions(sourceModules = listOf(moduleUri)), listOf("sub")) + assertThat(output) + .isEqualTo( + """ + target = "foo" + + """ + .trimIndent() + ) + } } diff --git a/pkl-core/src/main/java/org/pkl/core/runtime/CommandSpecParser.java b/pkl-core/src/main/java/org/pkl/core/runtime/CommandSpecParser.java index 8a3b4bc95..a1a4d1a1b 100644 --- a/pkl-core/src/main/java/org/pkl/core/runtime/CommandSpecParser.java +++ b/pkl-core/src/main/java/org/pkl/core/runtime/CommandSpecParser.java @@ -24,8 +24,11 @@ import java.io.UncheckedIOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Path; +import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; +import java.util.Deque; +import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; @@ -49,6 +52,7 @@ import org.pkl.core.PklBugException; import org.pkl.core.SecurityManager; import org.pkl.core.SecurityManagerException; import org.pkl.core.StackFrameTransformer; +import org.pkl.core.ast.ConstantValueNode; import org.pkl.core.ast.ExpressionNode; import org.pkl.core.ast.VmModifier; import org.pkl.core.ast.expression.literal.AmendModuleNodeGen; @@ -98,6 +102,36 @@ public final class CommandSpecParser { } public CommandSpec parse(VmTyped command) { + var path = new ArrayDeque(); + path.push("[root]"); + try { + return doParse(command, path); + } catch (VmException e) { + var hint = new StringBuilder("Error occurred while parsing command definition: "); + assert !path.isEmpty(); + var iter = path.descendingIterator(); + hint.append(iter.next()); + while (iter.hasNext()) { + hint.append(" > ").append(iter.next()); + } + + var hintBuilder = e.getHintBuilder(); + if (hintBuilder != null) { + e.setHintBuilder( + (builder, flag) -> { + hintBuilder.accept(builder, flag); + builder.append("\n\n"); + builder.append(hint); + }); + } else { + e.setHint(hint.toString()); + } + + throw e; + } + } + + private CommandSpec doParse(VmTyped command, Deque path) { VmUtils.checkAmends(command, CommandModule.getModule().getVmClass()); checkPropertyIsUndefined(command, Identifier.OPTIONS); checkPropertyIsUndefined(command, Identifier.PARENT); @@ -107,22 +141,27 @@ public final class CommandSpecParser { VmUtils.checkAmends( VmUtils.readMember(command, Identifier.COMMAND), CommandModule.getCommandInfoClass()); var commandName = (String) VmUtils.readMember(commandInfo, Identifier.NAME); + if (path.size() > 1) { + path.pop(); + path.push(commandName); + } var optionSpecs = collectOptions(optionsClass); return new CommandSpec( commandName, exportNullableString(commandInfo, Identifier.DESCRIPTION), - (Boolean) VmUtils.readMember(commandInfo, Identifier.HIDE), - (Boolean) VmUtils.readMember(commandInfo, Identifier.NOOP), + (boolean) VmUtils.readMember(commandInfo, Identifier.HIDE), + (boolean) VmUtils.readMember(commandInfo, Identifier.NOOP), optionSpecs, - collectSubcommands(commandInfo), + collectSubcommands(commandInfo, path), (options, parent) -> new CommandSpec.State( buildExecutionModule( command, buildObject(optionsClass, options), // NB: these next two lines are the only place where we lose type safety. - // SubcommandState is type-erased to Object in the public API to hide internals. + // SubcommandState is type-erased to Object in the public API to hide + // internals. // Consumers of this API must ensure CommandSpec.apply is only ever passed an // instance of CommandSpec.State previously returned from a prior invocation // of CommandSpec.apply. @@ -130,24 +169,31 @@ public final class CommandSpecParser { (it) -> handleErrors(() -> evaluateResult(command, (SubcommandState) it)))); } - private List collectSubcommands(VmTyped commandInfo) { + private List collectSubcommands(VmTyped commandInfo, Deque path) { var subcommands = new ArrayList(); - var subcommandNames = new HashSet(); + var subcommandNames = new HashMap(); var subcommandsProperty = (VmObject) VmUtils.readMember(commandInfo, Identifier.SUBCOMMANDS); subcommandsProperty.force(false, false); subcommandsProperty.iterateAlreadyForcedMemberValues( (key, member, value) -> { - var spec = parse((VmTyped) value); - if (subcommandNames.contains(spec.name())) { + // track the subcommand index at first + // replaced by subcommand name in doParse if reading name succeeds + path.push("subcommands[" + key + "]"); + var spec = doParse((VmTyped) value, path); + path.pop(); + var existingNameIndex = subcommandNames.get(spec.name()); + if (existingNameIndex != null) { throw exceptionBuilder() .withSourceSection(member.getSourceSection()) .evalError( "commandSubcommandConflict", VmUtils.readMember(commandInfo, Identifier.NAME), - spec.name()) + spec.name(), + existingNameIndex, + key) .build(); } - subcommandNames.add(spec.name()); + subcommandNames.put(spec.name(), key); subcommands.add(spec); return true; }); @@ -282,7 +328,7 @@ public final class CommandSpecParser { boolean hide = false; if (flagAnnotation != null) { shortName = exportNullableString(flagAnnotation, Identifier.SHORT_NAME); - hide = (Boolean) VmUtils.readMember(flagAnnotation, Identifier.HIDE); + hide = (boolean) VmUtils.readMember(flagAnnotation, Identifier.HIDE); } checkFlagNames(prop, name, shortName); @@ -1176,11 +1222,13 @@ public final class CommandSpecParser { new ExpressionNode[] {}, parent.members, moduleInfo, - new ImportNode( - language, - VmUtils.unavailableSourceSection(), - resolvedModule, - module.getModuleInfo().getResolvedModuleKey().getUri())); + module.isModuleObject() + ? new ImportNode( + language, + VmUtils.unavailableSourceSection(), + resolvedModule, + module.getModuleInfo().getResolvedModuleKey().getUri()) + : new ConstantValueNode(VmUtils.unavailableSourceSection(), module)); var moduleNode = new ModuleNode( diff --git a/pkl-core/src/main/java/org/pkl/core/runtime/VmException.java b/pkl-core/src/main/java/org/pkl/core/runtime/VmException.java index e11912e14..10e48a6b4 100644 --- a/pkl-core/src/main/java/org/pkl/core/runtime/VmException.java +++ b/pkl-core/src/main/java/org/pkl/core/runtime/VmException.java @@ -37,7 +37,7 @@ public abstract class VmException extends AbstractTruffleException { private final List leadingStackFrames; @Nullable private final BiConsumer messageBuilder; @Nullable protected BiConsumer hintBuilder; - private boolean forExpressionInput; + private boolean forExpressionInput = false; public VmException( @Nullable String message, @@ -63,7 +63,6 @@ public abstract class VmException extends AbstractTruffleException { this.insertedStackFrames = insertedStackFrames; this.leadingStackFrames = leadingStackFrames; this.hintBuilder = hintBuilder; - this.forExpressionInput = forExpressionInput; } public final boolean isExternalMessage() { @@ -110,6 +109,10 @@ public abstract class VmException extends AbstractTruffleException { return hintBuilder; } + public void setHintBuilder(BiConsumer hintBuilder) { + this.hintBuilder = hintBuilder; + } + public void setHint(String hint) { this.hintBuilder = ((builder, aBoolean) -> builder.append(hint)); } diff --git a/pkl-core/src/main/resources/org/pkl/core/errorMessages.properties b/pkl-core/src/main/resources/org/pkl/core/errorMessages.properties index 5cc22591b..055283e09 100644 --- a/pkl-core/src/main/resources/org/pkl/core/errorMessages.properties +++ b/pkl-core/src/main/resources/org/pkl/core/errorMessages.properties @@ -1123,7 +1123,7 @@ characterCodingException=\ Invalid bytes for charset "{0}". commandSubcommandConflict=\ -Command `{0}` has subcommands with conflicting name "{1}".\n\ +Command `{0}` has subcommands with conflicting name "{1}" at index `{2}` and index `{3}`.\n\ Elements of `command.subcommands` must have unique `name` values. commandMustNotAssignOrAmendProperty=\ diff --git a/pkl-core/src/test/kotlin/org/pkl/core/runtime/CommandSpecParserTest.kt b/pkl-core/src/test/kotlin/org/pkl/core/runtime/CommandSpecParserTest.kt index f8504ce57..a09c645f8 100644 --- a/pkl-core/src/test/kotlin/org/pkl/core/runtime/CommandSpecParserTest.kt +++ b/pkl-core/src/test/kotlin/org/pkl/core/runtime/CommandSpecParserTest.kt @@ -699,7 +699,10 @@ class CommandSpecParserTest { ) val exc = assertThrows { parse(moduleUri) } - assertThat(exc.message).contains("Command `cmd` has subcommands with conflicting name \"foo\".") + assertThat(exc.message) + .contains( + "Command `cmd` has subcommands with conflicting name \"foo\" at index `0` and index `1`." + ) } @Test @@ -839,4 +842,72 @@ class CommandSpecParserTest { assertThat(this.showAsRequired).isFalse() } } + + @Test + fun `amend-only command parses without error and has null description`() { + val moduleUri = + writePklFile( + "cmd.pkl", + """ + amends "pkl:Command" + import "sub.pkl" + + command { + name = "root" + subcommands { + new sub { target = "foo" } + } + } + """ + .trimIndent(), + ) + writePklFile( + "sub.pkl", + """ + extends "pkl:Command" + target: String + """ + .trimIndent(), + ) + + val spec = parse(moduleUri) + assertThat(spec.helpText).isNull() + } + + @Test + fun `command parsing output includes command path`() { + val moduleUri = + writePklFile( + "cmd.pkl", + """ + extends "pkl:Command" + import "pkl:Command" + + command { + name = "root" + subcommands { + new Sub1 { + command { + subcommands { + new Sub2 { + command { + name = throw("oops") + } + } + } + } + } + } + } + + class Sub1 extends Command + class Sub2 extends Command + """ + .trimIndent(), + ) + + val exc = assertThrows { parse(moduleUri) } + assertThat(exc.message) + .contains("Error occurred while parsing command definition: [root] > Sub1 > subcommands[0]") + } } diff --git a/stdlib/Command.pkl b/stdlib/Command.pkl index fd1630625..1d7605aa6 100644 --- a/stdlib/Command.pkl +++ b/stdlib/Command.pkl @@ -36,12 +36,15 @@ import "pkl:Command" import "pkl:reflect" local commandClass = reflect.Class(getClass()) +local commandModule = reflect.Module(Command) /// Command configuration. hidden command: CommandInfo = new { - name = // choose the name of the module if the command is a module or the class otherwise - if (commandClass.name == "ModuleClass") reflect.Module(module).name else commandClass.name - description = commandClass.docComment // works for both classes and module classes + when (commandClass != commandModule.moduleClass) { + name = + if (commandClass.name == "ModuleClass") reflect.moduleOf(module).name else commandClass.name + description = commandClass.docComment + } } /// Command line options.