You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2026/04/21 06:13:11 UTC
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 171ca5ce1219e6d02d14058c0eb111a6a1db14f5
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Apr 20 14:04:55 2026 +1000
GROOVY-8877: document top-level scripts + cross-link embedded classes
---
.../org/apache/groovy/antlr/GroovydocVisitor.java | 139 ++++++++++++++++++++-
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 72 +++++++++++
.../testfiles/ClassWithClosureInAnnotation.groovy | 43 +++++++
.../ClassWithSpockStyleAnnotations.groovy | 45 +++++++
.../testfiles/ScriptWithOnlyMemberDoc.groovy | 29 +++++
.../testfiles/ScriptWithTopLevelDoc.groovy | 35 ++++++
6 files changed, 362 insertions(+), 1 deletion(-)
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java b/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
index fd5ade1779..435b146870 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
@@ -139,7 +139,18 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
for (ClassNode iface : node.getInterfaces()) {
currentClassDoc.addInterfaceName(makeType(iface));
}
- currentClassDoc.setRawCommentText(getDocContent(node.getGroovydoc()));
+ String rawDoc = getDocContent(node.getGroovydoc());
+ if (rawDoc.isEmpty() && node.isScript()) {
+ // GROOVY-8877: the Groovy parser does not attach a leading /** */
+ // comment to the synthetic script class. Fall back to scanning the
+ // source for one. The helper applies a peek-ahead rule and (for
+ // the annotation case) a cross-check against existing member docs
+ // so we neither drop legitimate script-level docs (e.g. before
+ // `@BaseScript` where the declaration gets transformed away) nor
+ // duplicate member docs that the parser already attached.
+ rawDoc = extractLeadingScriptDocContent(node);
+ }
+ currentClassDoc.setRawCommentText(rawDoc);
currentClassDoc.setNameWithTypeArgs(name + genericTypesAsString(node.getGenericsTypes()));
if (!node.isInterface() && !node.isEnum() && node.getSuperClass() != null) {
String superName = makeType(node.getSuperClass());
@@ -198,6 +209,132 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
return result;
}
+ /**
+ * GROOVY-8877: extract the first Javadoc-style comment block
+ * ({@code /** ... *}{@code /}) from the top of the source file, skipping
+ * line comments, plain block comments, whitespace, {@code package}
+ * declarations, and {@code import} declarations.
+ *
+ * <p>Lifting policy, by what follows the candidate comment:
+ * <ul>
+ * <li><b>package / import / another comment / end of file</b> — lift.
+ * These are unambiguous; the comment cannot belong to a following
+ * member because there isn't one.</li>
+ * <li><b>an annotation ({@code @Xxx})</b> — lift only if no member
+ * of the script class already owns the same comment content. This
+ * covers the {@code @BaseScript} / {@code @Grab} pattern where the
+ * annotated declaration is consumed by an AST transform and no
+ * member survives to carry the doc, while still avoiding duplication
+ * for cases like {@code @Override void foo()} where the parser
+ * attached the comment to a real method.</li>
+ * <li><b>anything else</b> (e.g. {@code def x = 42} which could be a
+ * local variable or a field/property, or a bare declaration) —
+ * don't lift. Groovy's script form makes it unreliable to tell
+ * these apart without full parsing, so we err toward preserving
+ * what the parser decided.</li>
+ * </ul>
+ *
+ * <p>Script authors who want a script-level doc should follow the
+ * convention of separating it with a package/import/comment or putting
+ * another Javadoc comment before the next member.
+ */
+ private String extractLeadingScriptDocContent(ClassNode scriptNode) {
+ String src;
+ try (java.io.Reader r = unit.getSource().getReader()) {
+ StringBuilder sb = new StringBuilder();
+ char[] buf = new char[8192];
+ int n;
+ while ((n = r.read(buf)) > 0) sb.append(buf, 0, n);
+ src = sb.toString();
+ } catch (java.io.IOException e) {
+ return "";
+ }
+ int i = 0, n = src.length();
+ while (i < n) {
+ char c = src.charAt(i);
+ if (Character.isWhitespace(c)) { i++; continue; }
+ if (c == '/' && i + 1 < n) {
+ char next = src.charAt(i + 1);
+ if (next == '/') {
+ int eol = src.indexOf('\n', i);
+ i = eol < 0 ? n : eol + 1;
+ continue;
+ }
+ if (next == '*') {
+ boolean isJavadoc = i + 2 < n && src.charAt(i + 2) == '*'
+ && (i + 3 >= n || src.charAt(i + 3) != '/');
+ int close = src.indexOf("*/", i + 2);
+ if (close < 0) return "";
+ if (isJavadoc) {
+ String full = src.substring(i, close + 2);
+ Matcher m = JAVADOC_COMMENT_PATTERN.matcher(full);
+ String content = m.find() ? m.group(1).trim() : "";
+ LiftDecision decision = decideLift(src, close + 2);
+ switch (decision) {
+ case LIFT: return content;
+ case SKIP: return "";
+ case CHECK_CLAIM:
+ return isClaimedByMember(scriptNode, content) ? "" : content;
+ }
+ return "";
+ }
+ i = close + 2;
+ continue;
+ }
+ }
+ // Skip `package X` / `import X` declarations by advancing to end
+ // of line; any other construct means there's no leading script doc.
+ if (src.startsWith("package", i) || src.startsWith("import", i)) {
+ int eol = src.indexOf('\n', i);
+ i = eol < 0 ? n : eol + 1;
+ continue;
+ }
+ return "";
+ }
+ return "";
+ }
+
+ private enum LiftDecision { LIFT, SKIP, CHECK_CLAIM }
+
+ /**
+ * Classify what follows the candidate leading Javadoc comment and return
+ * the matching lift decision. See {@link #extractLeadingScriptDocContent}
+ * for the rationale.
+ */
+ private static LiftDecision decideLift(String src, int from) {
+ int i = from, n = src.length();
+ while (i < n && Character.isWhitespace(src.charAt(i))) i++;
+ if (i >= n) return LiftDecision.LIFT;
+ char c = src.charAt(i);
+ if (c == '/' && i + 1 < n) {
+ char next = src.charAt(i + 1);
+ if (next == '/' || next == '*') return LiftDecision.LIFT;
+ }
+ if (src.startsWith("package", i) || src.startsWith("import", i)) return LiftDecision.LIFT;
+ if (c == '@') return LiftDecision.CHECK_CLAIM;
+ return LiftDecision.SKIP;
+ }
+
+ /**
+ * Returns true if any method, field, or property of the script class
+ * already owns a Groovydoc whose stripped content matches the candidate.
+ * Used to resolve the {@code @Xxx} peek-ahead case — if a real member
+ * claims the comment, don't lift it to script-level.
+ */
+ private boolean isClaimedByMember(ClassNode scriptNode, String candidate) {
+ if (candidate.isEmpty()) return false;
+ for (MethodNode m : scriptNode.getMethods()) {
+ if (candidate.equals(getDocContent(m.getGroovydoc()))) return true;
+ }
+ for (FieldNode f : scriptNode.getFields()) {
+ if (candidate.equals(getDocContent(f.getGroovydoc()))) return true;
+ }
+ for (PropertyNode p : scriptNode.getProperties()) {
+ if (candidate.equals(getDocContent(p.getGroovydoc()))) return true;
+ }
+ return false;
+ }
+
private void processAnnotations(SimpleGroovyProgramElementDoc element, AnnotatedNode node) {
for (AnnotationNode an : node.getAnnotations()) {
String name = an.getClassNode().getName();
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index 4ef83d3f68..c1f739c799 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -131,6 +131,78 @@ public class GroovyDocToolTest extends GroovyTestCase {
doc.contains("https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Object.html"));
}
+ // GROOVY-8025: annotations whose members are closure expressions must
+ // not NPE during groovydoc processing. The original bug was in the old
+ // SimpleGroovyClassDocAssembler — the refactor to GroovydocVisitor
+ // inherently handles ClosureExpression via the ClassCodeVisitorSupport
+ // walk, so these fixtures exercise the fixed path.
+ public void testAnnotationWithClosureMemberDoesNotCrash() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ String klass = "ClassWithClosureInAnnotation";
+ htmlTool.add(List.of(base + "/" + klass + ".groovy"));
+
+ MockOutputTool output = new MockOutputTool();
+ htmlTool.renderToOutput(output, MOCK_DIR);
+
+ String doc = output.getText(MOCK_DIR + "/" + base + "/" + klass + ".html");
+ assertNotNull("Expected a page for the closure-annotated class", doc);
+ assertTrue("Expected the class title in:\n" + doc, doc.contains(klass));
+ }
+
+ // GROOVY-8025: broader coverage — single-expression closure, no-arg
+ // closure with explicit `-> body`, closure with generic-typed params, and
+ // multiline closure body, all as annotation members.
+ public void testSpockStyleClosureAnnotationsDoNotCrash() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ String klass = "ClassWithSpockStyleAnnotations";
+ htmlTool.add(List.of(base + "/" + klass + ".groovy"));
+
+ MockOutputTool output = new MockOutputTool();
+ htmlTool.renderToOutput(output, MOCK_DIR);
+
+ String doc = output.getText(MOCK_DIR + "/" + base + "/" + klass + ".html");
+ assertNotNull("Expected a page for the Spock-style-annotated class", doc);
+ assertTrue("Expected method 'simpleClosure' in:\n" + doc, doc.contains("simpleClosure"));
+ assertTrue("Expected method 'multilineClosureWithGenericParam' in:\n" + doc,
+ doc.contains("multilineClosureWithGenericParam"));
+ assertTrue("Expected method 'multilineBodyClosure' in:\n" + doc, doc.contains("multilineBodyClosure"));
+ }
+
+ // GROOVY-8877
+ public void testScriptTopLevelDocCommentAppearsInOutput() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ htmlTool.add(List.of(base + "/ScriptWithTopLevelDoc.groovy"));
+
+ MockOutputTool output = new MockOutputTool();
+ htmlTool.renderToOutput(output, MOCK_DIR);
+
+ String doc = output.getText(MOCK_DIR + "/" + base + "/ScriptWithTopLevelDoc.html");
+ assertNotNull("Expected a script page", doc);
+ assertTrue("Script-level doc should appear in:\n" + doc,
+ doc.contains("GROOVY-8877 script-level documentation"));
+ }
+
+ // GROOVY-8877: a script whose only /** */ is attached by the parser to a
+ // member should NOT also be lifted to script-level, or the same text
+ // would appear in three places (script description + method summary
+ // first-sentence + method detail) rather than two (summary + detail).
+ public void testScriptMemberDocIsNotLiftedToScriptLevel() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ String klass = "ScriptWithOnlyMemberDoc";
+ htmlTool.add(List.of(base + "/" + klass + ".groovy"));
+
+ MockOutputTool output = new MockOutputTool();
+ htmlTool.renderToOutput(output, MOCK_DIR);
+
+ String doc = output.getText(MOCK_DIR + "/" + base + "/" + klass + ".html");
+ assertNotNull("Expected a script page", doc);
+ int occurrences = doc.split("member-doc-not-lifted-to-script", -1).length - 1;
+ // 2 = summary + detail. 3 would mean the comment was also lifted to
+ // the script-level description.
+ assertEquals("Member doc should appear exactly twice (summary + detail), got "
+ + occurrences + " in:\n" + doc, 2, occurrences);
+ }
+
// GROOVY-10162
public void testAbstractMethodEnumWithPerConstantBodiesDoesNotProduceAnonymousInnerPages() throws Exception {
String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithClosureInAnnotation.groovy b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithClosureInAnnotation.groovy
new file mode 100644
index 0000000000..d5fc0517a9
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithClosureInAnnotation.groovy
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.codehaus.groovy.tools.groovydoc.testfiles
+
+/**
+ * GROOVY-8025: groovydoc used to NPE on annotations whose members are
+ * closure expressions (e.g. Spock's {@code @IgnoreIf}). This fixture
+ * exercises a closure-valued annotation on the class, a method, and a
+ * field to verify the refactored {@code GroovydocVisitor} handles them
+ * without error.
+ */
+@GroovyConditional({ System.getProperty('os.name') ==~ /.*Linux.*/ })
+class ClassWithClosureInAnnotation {
+
+ @GroovyConditional({ -> 1 + 1 == 2 })
+ String annotatedField
+
+ @GroovyConditional(value = { it > 0 })
+ String annotatedMethod() {
+ "hello"
+ }
+}
+
+/** Helper annotation that accepts a closure value. */
+@interface GroovyConditional {
+ Class value()
+}
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithSpockStyleAnnotations.groovy b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithSpockStyleAnnotations.groovy
new file mode 100644
index 0000000000..9b950aff08
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithSpockStyleAnnotations.groovy
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.codehaus.groovy.tools.groovydoc.testfiles
+
+/**
+ * GROOVY-8025: closure-valued annotations such as Spock's
+ * {@code @IgnoreIf({ ... })} / {@code @Requires({ ... })} / parametrised
+ * {@code @Retry(condition = { ... })} should not trip up groovydoc.
+ */
+@SpockStyleAnnotation({ System.getProperty('java.version').startsWith('17') })
+class ClassWithSpockStyleAnnotations {
+
+ @SpockStyleAnnotation({ -> true })
+ void simpleClosure() {}
+
+ @SpockStyleAnnotation(condition = { List<Integer> xs -> xs.every { it > 0 } })
+ void multilineClosureWithGenericParam(List<Integer> xs) {}
+
+ @SpockStyleAnnotation({ Map m ->
+ m.keySet().every { it instanceof String }
+ })
+ String multilineBodyClosure(Map m) { "ok" }
+}
+
+/** Helper annotation mimicking the Spock pattern. */
+@interface SpockStyleAnnotation {
+ Class value() default Object.class
+ Class condition() default Object.class
+}
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ScriptWithOnlyMemberDoc.groovy b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ScriptWithOnlyMemberDoc.groovy
new file mode 100644
index 0000000000..4482e31a3b
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ScriptWithOnlyMemberDoc.groovy
@@ -0,0 +1,29 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.codehaus.groovy.tools.groovydoc.testfiles
+
+/**
+ * GROOVY-8877 member-doc-not-lifted-to-script: this comment belongs to
+ * the greet() method. It should NOT appear as the script-level doc.
+ */
+void greet(String name) {
+ println "hello $name"
+}
+
+greet('world')
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ScriptWithTopLevelDoc.groovy b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ScriptWithTopLevelDoc.groovy
new file mode 100644
index 0000000000..5e499bc5e5
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ScriptWithTopLevelDoc.groovy
@@ -0,0 +1,35 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.codehaus.groovy.tools.groovydoc.testfiles
+
+/**
+ * GROOVY-8877 script-level documentation. This text should appear as
+ * the description of the synthetic script class in the generated
+ * groovydoc output.
+ */
+
+import groovy.transform.Field
+
+@Field int counter = 0
+
+def greet(String name) {
+ "hello $name"
+}
+
+println greet('world')
(groovy) 14/34: GROOVY-11941: Support --add-stylesheet (additive, multiple stylesheets)
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit d3aabc8a73825b74cbdd5d49527ef87feed6da58
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Apr 20 19:18:11 2026 +1000
GROOVY-11941: Support --add-stylesheet (additive, multiple stylesheets)
---
.../java/org/codehaus/groovy/ant/Groovydoc.java | 43 ++++++++++++++++++++++
.../codehaus/groovy/tools/groovydoc/Main.groovy | 21 +++++++++++
.../groovy/tools/groovydoc/Main.properties | 2 +
.../gstringTemplates/classLevel/classDocName.html | 3 ++
.../packageLevel/package-frame.html | 3 ++
.../packageLevel/package-summary.html | 3 ++
.../topLevel/allclasses-frame.html | 3 ++
.../gstringTemplates/topLevel/deprecated-list.html | 3 ++
.../gstringTemplates/topLevel/help-doc.html | 3 ++
.../gstringTemplates/topLevel/index-all.html | 3 ++
.../gstringTemplates/topLevel/overview-frame.html | 3 ++
.../topLevel/overview-summary.html | 3 ++
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 22 +++++++++++
13 files changed, 115 insertions(+)
diff --git a/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java b/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java
index cd9e76506c..939d05f820 100644
--- a/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java
+++ b/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java
@@ -74,6 +74,8 @@ public class Groovydoc extends Task {
private final List<LinkArgument> links = new ArrayList<>();
private File overviewFile;
private File styleSheetFile;
+ // GROOVY-11941: additional stylesheets populated via nested <addStylesheet file="..."/>.
+ private final List<File> addStylesheetFiles = new ArrayList<>();
// dev note: update javadoc comment for #setExtensions(String) if updating below
private String extensions = ".java:.groovy:.gv:.gvy:.gsh";
@@ -350,6 +352,28 @@ public class Groovydoc extends Task {
this.styleSheetFile = styleSheetFile;
}
+ /**
+ * GROOVY-11941: Ant nested element {@code <addStylesheet file="custom.css"/>}
+ * to include an additional stylesheet in the generated docs alongside the
+ * default. Repeatable — specify once per extra stylesheet.
+ *
+ * @return a holder that Ant will populate with the nested element's file attribute
+ */
+ public AddStylesheet createAddStylesheet() {
+ AddStylesheet a = new AddStylesheet();
+ return a;
+ }
+
+ /** Nested-element holder populated by Ant introspection for {@code <addStylesheet file="..."/>}. */
+ public class AddStylesheet {
+ private File file;
+ public void setFile(File f) {
+ this.file = f;
+ if (f != null) addStylesheetFiles.add(f);
+ }
+ public File getFile() { return file; }
+ }
+
/**
* Add the directories matched by the nested dirsets to the resulting
* packages list and the base directories of the dirsets to the Path.
@@ -478,6 +502,13 @@ public class Groovydoc extends Task {
properties.setProperty("timestamp", Boolean.valueOf(!noTimestamp).toString());
properties.setProperty("versionStamp", Boolean.valueOf(!noVersionStamp).toString());
properties.setProperty("showInternal", showInternal.toString());
+ // GROOVY-11941: expose additional stylesheet basenames to templates.
+ StringBuilder extras = new StringBuilder();
+ for (int k = 0; k < addStylesheetFiles.size(); k++) {
+ if (k > 0) extras.append(',');
+ extras.append(addStylesheetFiles.get(k).getName());
+ }
+ properties.setProperty("additionalStylesheets", extras.toString());
String phaseOverride = SystemUtil.getSystemPropertySafe("groovydoc.phase.override");
if (phaseOverride != null) properties.put("phaseOverride", phaseOverride);
@@ -519,6 +550,18 @@ public class Groovydoc extends Task {
styleSheetFile.getAbsolutePath(), e.getMessage());
}
}
+ // GROOVY-11941: copy each additional stylesheet next to the default,
+ // preserving basename.
+ for (File f : addStylesheetFiles) {
+ try {
+ String css = ResourceGroovyMethods.getText(f);
+ File outfile = new File(destDir, f.getName());
+ ResourceGroovyMethods.setText(outfile, css);
+ } catch (IOException e) {
+ LOGGER.log(WARNING, "Unable to copy additional stylesheet ''{0}'': {1}",
+ f.getAbsolutePath(), e.getMessage());
+ }
+ }
}
private void checkScopeProperties(Properties properties) {
diff --git a/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy b/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy
index 376c982c1d..5cc782d877 100644
--- a/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy
+++ b/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy
@@ -32,6 +32,7 @@ import org.codehaus.groovy.tools.shell.util.MessageSource
class Main {
private static final MessageSource messages = new MessageSource(Main)
private static File styleSheetFile;
+ private static List<File> addStylesheetFiles = []
private static File overviewFile
private static File destDir
private static String windowTitle
@@ -91,6 +92,7 @@ class Main {
cli.footer(args:1, argName: 'html', messages['cli.option.footer.description'])
cli.exclude(args:1, argName: 'pkglist', messages['cli.option.exclude.description'])
cli.stylesheetfile(args:1, argName: 'path', messages['cli.option.stylesheetfile.description'])
+ cli.addStylesheet(args:1, argName: 'path', messages['cli.option.addStylesheet.description'])
cli.sourcepath(args:1, argName: 'pathlist', messages['cli.option.sourcepath.description'])
cli.javaVersion(args: 1, argName: 'javaVersion', messages['cli.option.javaVersion.description'])
cli.showInternal(messages['cli.option.showInternal.description'])
@@ -110,6 +112,14 @@ class Main {
if (options.stylesheetfile) {
styleSheetFile = new File(options.stylesheetfile)
}
+ if (options.addStylesheet) {
+ // CliBuilder with args:1 gives a single value; use comma separator
+ // to accept multiple paths in one flag. Example:
+ // --add-stylesheet custom1.css,custom2.css
+ options.addStylesheet.toString().tokenize(',').each { p ->
+ addStylesheetFiles << new File(p.trim())
+ }
+ }
if (options.overview) {
overviewFile = new File(options.overview)
@@ -216,6 +226,8 @@ class Main {
properties.put("processScripts", (!noScripts).toString())
properties.put("includeMainForScripts", (!noMainForScripts).toString())
properties.put("showInternal", showInternal.toString())
+ // GROOVY-11941: expose additional stylesheet basenames to templates.
+ properties.put("additionalStylesheets", addStylesheetFiles*.name.join(','))
properties.put("timestamp", (!noTimestamp).toString())
properties.put("versionStamp", (!noVersionStamp).toString())
properties.put("overviewFile", overviewFile?.absolutePath ?: "")
@@ -247,6 +259,15 @@ class Main {
println "Warning: Unable to copy specified stylesheet '" + styleSheetFile.absolutePath + "'. Using default stylesheet instead. Due to: " + e.message
}
}
+ // GROOVY-11941: copy any additional stylesheets alongside the default,
+ // preserving each file's basename.
+ addStylesheetFiles.each { f ->
+ try {
+ new File(destDir, f.name).text = f.text
+ } catch (IOException e) {
+ System.err.println "Warning: Unable to copy additional stylesheet '${f.absolutePath}': ${e.message}"
+ }
+ }
return htmlTool.errorCount
}
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/Main.properties b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/Main.properties
index aa44b40fa0..c933f57e98 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/Main.properties
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/Main.properties
@@ -80,4 +80,6 @@ cli.option.javaVersion.description=Specify the Java Version for parsed java file
cli.option.showInternal.description=Include members annotated with groovy.transform.@Internal (hidden by default)
+cli.option.addStylesheet.description=Additional stylesheet file(s) to include alongside the default (comma-separated for multiple)
+
cli.info.version=@|green GroovyDoc|@ {0}
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.html
index c08f2d1abd..968b8eb3d3 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.html
@@ -93,6 +93,9 @@
<link href="${classDoc.relativeRootPath}groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="${classDoc.relativeRootPath}groovy.ico" type="image/x-icon" rel="icon">
<link rel="stylesheet" type="text/css" href="${classDoc.relativeRootPath}stylesheet.css" title="Style">
+<% if (props.additionalStylesheets) props.additionalStylesheets.tokenize(',').each { __ss -> %>
+ <link rel="stylesheet" type="text/css" href="${classDoc.relativeRootPath}${__ss.trim()}">
+<% } %>
<body class="center">
<script type="text/javascript"><!--
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-frame.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-frame.html
index 1ce729fb86..8f5f52d33e 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-frame.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-frame.html
@@ -42,6 +42,9 @@
<link href="groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="groovy.ico" type="image/x-icon" rel="icon">
<link rel="stylesheet" type="text/css" href="${packageDoc.relativeRootPath}stylesheet.css" title="Style">
+<% if (props.additionalStylesheets) props.additionalStylesheets.tokenize(',').each { __ss -> %>
+ <link rel="stylesheet" type="text/css" href="${packageDoc.relativeRootPath}${__ss.trim()}">
+<% } %>
</head>
<body class="left">
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html
index 288c0867b6..ead666d25a 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html
@@ -40,6 +40,9 @@ def classTypes = [
<meta name="keywords" content="${packageDoc.nameWithDots()} package">
<meta http-equiv="Content-Type" content="text/html; charset=${props.charset}">
<link rel ="stylesheet" TYPE="text/css" HREF="${packageDoc.relativeRootPath}stylesheet.css" title="Style">
+<% if (props.additionalStylesheets) props.additionalStylesheets.tokenize(',').each { __ss -> %>
+<link rel="stylesheet" type="text/css" href="${packageDoc.relativeRootPath}${__ss.trim()}">
+<% } %>
<link href="${packageDoc.relativeRootPath}groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="${packageDoc.relativeRootPath}groovy.ico" type="image/x-icon" rel="icon">
<script type="text/javascript">
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/allclasses-frame.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/allclasses-frame.html
index fce9ce1f6e..77e6ba0765 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/allclasses-frame.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/allclasses-frame.html
@@ -26,6 +26,9 @@
<link href="groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="groovy.ico" type="image/x-icon" rel="icon">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
+<% if (props.additionalStylesheets) props.additionalStylesheets.tokenize(',').each { __ss -> %>
+<link rel="stylesheet" type="text/css" href="${__ss.trim()}">
+<% } %>
</head>
<body class="left">
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/deprecated-list.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/deprecated-list.html
index dc978099e1..7f13927545 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/deprecated-list.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/deprecated-list.html
@@ -85,6 +85,9 @@ def nameFromParams = { n -> n.name() + '(' + n.parameters().collect{ param -> pa
<title>${title}</title>
<% if (props.timestamp != 'false') { %><meta name="date" content="${new java.text.SimpleDateFormat('yyyy-MM-dd').format(new Date())}"><% } %>
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
+<% if (props.additionalStylesheets) props.additionalStylesheets.tokenize(',').each { __ss -> %>
+ <link rel="stylesheet" type="text/css" href="${__ss.trim()}">
+<% } %>
<link href="groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="groovy.ico" type="image/x-icon" rel="icon">
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/help-doc.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/help-doc.html
index 4d08c5e808..c64cb8b135 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/help-doc.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/help-doc.html
@@ -30,6 +30,9 @@
<link href="groovy.ico" type="image/x-icon" rel="icon">
<% if (props.timestamp != 'false') { %><meta name="date" content="${new java.text.SimpleDateFormat('yyyy-MM-dd').format(new Date())}"><% } %>
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
+<% if (props.additionalStylesheets) props.additionalStylesheets.tokenize(',').each { __ss -> %>
+ <link rel="stylesheet" type="text/css" href="${__ss.trim()}">
+<% } %>
</head>
<body class="center">
<script type="text/javascript"><!--
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/index-all.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/index-all.html
index 568c6f3f66..2020f5e56b 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/index-all.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/index-all.html
@@ -42,6 +42,9 @@ def nameFromParams = { n -> n.name() + '(' + n.parameters().collect{ param -> pa
<title>${title}</title>
<% if (props.timestamp != 'false') { %><meta name="date" content="${new java.text.SimpleDateFormat('yyyy-MM-dd').format(new Date())}"><% } %>
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
+<% if (props.additionalStylesheets) props.additionalStylesheets.tokenize(',').each { __ss -> %>
+ <link rel="stylesheet" type="text/css" href="${__ss.trim()}">
+<% } %>
</head>
<body class="center">
<script type="text/javascript"><!--
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-frame.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-frame.html
index 955f566e57..e13cb29ba8 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-frame.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-frame.html
@@ -26,6 +26,9 @@
<meta name="keywords" content="Overview">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
+<% if (props.additionalStylesheets) props.additionalStylesheets.tokenize(',').each { __ss -> %>
+<link rel="stylesheet" type="text/css" href="${__ss.trim()}">
+<% } %>
</head>
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary.html
index 38e42d9525..37ecd51e5a 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary.html
@@ -26,6 +26,9 @@
<meta http-equiv="Content-Type" content="text/html; charset=${props.charset}">
<meta name="keywords" content="Overview">
<link rel ="stylesheet" type="text/css" href="stylesheet.css" title="Style">
+<% if (props.additionalStylesheets) props.additionalStylesheets.tokenize(',').each { __ss -> %>
+<link rel="stylesheet" type="text/css" href="${__ss.trim()}">
+<% } %>
<link href="groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="groovy.ico" type="image/x-icon" rel="icon">
</head>
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index 04fa39a19d..8a267ff53d 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -147,6 +147,28 @@ public class GroovyDocToolTest extends GroovyTestCase {
doc.contains("{<DL><DT><B>inheritDoc") || doc.contains("inheritDoc:</B>"));
}
+ // GROOVY-11941: additionalStylesheets property causes templates to emit
+ // extra <link rel="stylesheet"> tags at the appropriate relative-root path.
+ public void testAdditionalStylesheetsInTemplates() throws Exception {
+ Properties props = new Properties();
+ props.setProperty("additionalStylesheets", "custom1.css,custom2.css");
+ GroovyDocTool tool = makeHtmltool(new ArrayList<>(), null, props);
+
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ tool.add(List.of(base + "/DocumentedClass.groovy"));
+ MockOutputTool output = new MockOutputTool();
+ tool.renderToOutput(output, MOCK_DIR);
+
+ String classDoc = output.getText(MOCK_DIR + "/" + base + "/DocumentedClass.html");
+ assertNotNull(classDoc);
+ // Class-level template uses classDoc.relativeRootPath as prefix.
+ String prefix = "../../../../../../";
+ assertTrue("Expected additional stylesheet link with relative root prefix in:\n" + classDoc,
+ classDoc.contains("href=\"" + prefix + "custom1.css\""));
+ assertTrue("Expected second additional stylesheet link in:\n" + classDoc,
+ classDoc.contains("href=\"" + prefix + "custom2.css\""));
+ }
+
// GROOVY-11938 stage 2: external {@snippet file="..."} reads from the
// package's snippet-files/ directory.
public void testSnippetTagExternalFormLoadsFromSnippetFiles() throws Exception {
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 39894ba4ce1c0f9550ab1bd8268cf5c21108ec53
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Apr 20 21:40:11 2026 +1000
GROOVY-11943: Add javadoc-style disable flags: -noindex, -nodeprecatedlist, -nohelp
---
.../java/org/codehaus/groovy/ant/Groovydoc.java | 34 ++++++++++++++++++
.../codehaus/groovy/tools/groovydoc/Main.groovy | 13 +++++++
.../groovy/tools/groovydoc/GroovyDocWriter.java | 10 ++++++
.../groovy/tools/groovydoc/Main.properties | 6 ++++
.../gstringTemplates/classLevel/classDocName.html | 12 +++----
.../packageLevel/package-summary.html | 12 +++----
.../packageLevel/package-tree.html | 12 +++----
.../gstringTemplates/topLevel/deprecated-list.html | 8 ++---
.../gstringTemplates/topLevel/help-doc.html | 8 ++---
.../gstringTemplates/topLevel/index-all.html | 8 ++---
.../topLevel/overview-summary.html | 12 +++----
.../gstringTemplates/topLevel/overview-tree.html | 12 +++----
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 41 ++++++++++++++++++++++
13 files changed, 146 insertions(+), 42 deletions(-)
diff --git a/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java b/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java
index 939d05f820..a05f2dcc9d 100644
--- a/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java
+++ b/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java
@@ -68,6 +68,9 @@ public class Groovydoc extends Task {
private Boolean noTimestamp;
private Boolean noVersionStamp;
private Boolean showInternal;
+ private Boolean noIndex;
+ private Boolean noDeprecatedList;
+ private Boolean noHelp;
private String javaVersion;
private final List<DirSet> packageSets;
private final List<String> sourceFilesToDoc;
@@ -99,6 +102,9 @@ public class Groovydoc extends Task {
noTimestamp = false;
noVersionStamp = false;
showInternal = false;
+ noIndex = false;
+ noDeprecatedList = false;
+ noHelp = false;
}
/**
@@ -172,6 +178,30 @@ public class Groovydoc extends Task {
this.showInternal = showInternal;
}
+ /**
+ * GROOVY-11943: if set to true, suppress generation of the alphabetical
+ * index page ({@code index-all.html}) and its nav-bar link.
+ */
+ public void setNoIndex(boolean noIndex) {
+ this.noIndex = noIndex;
+ }
+
+ /**
+ * GROOVY-11943: if set to true, suppress generation of the deprecated-list
+ * page ({@code deprecated-list.html}) and its nav-bar link.
+ */
+ public void setNoDeprecatedList(boolean noDeprecatedList) {
+ this.noDeprecatedList = noDeprecatedList;
+ }
+
+ /**
+ * GROOVY-11943: if set to true, suppress generation of the help page
+ * ({@code help-doc.html}) and its nav-bar link.
+ */
+ public void setNoHelp(boolean noHelp) {
+ this.noHelp = noHelp;
+ }
+
/**
* If set to false, Scripts will not be processed.
* Defaults to true.
@@ -502,6 +532,10 @@ public class Groovydoc extends Task {
properties.setProperty("timestamp", Boolean.valueOf(!noTimestamp).toString());
properties.setProperty("versionStamp", Boolean.valueOf(!noVersionStamp).toString());
properties.setProperty("showInternal", showInternal.toString());
+ // GROOVY-11943: javadoc-parity disable flags.
+ properties.setProperty("noIndex", noIndex.toString());
+ properties.setProperty("noDeprecatedList", noDeprecatedList.toString());
+ properties.setProperty("noHelp", noHelp.toString());
// GROOVY-11941: expose additional stylesheet basenames to templates.
StringBuilder extras = new StringBuilder();
for (int k = 0; k < addStylesheetFiles.size(); k++) {
diff --git a/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy b/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy
index 5cc782d877..54b2be7b61 100644
--- a/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy
+++ b/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy
@@ -46,6 +46,9 @@ class Main {
private static Boolean noMainForScripts
private static Boolean noTimestamp
private static Boolean noVersionStamp
+ private static Boolean noIndex
+ private static Boolean noDeprecatedList
+ private static Boolean noHelp
private static Boolean privateScope
private static Boolean packageScope
private static Boolean publicScope
@@ -79,6 +82,9 @@ class Main {
cli.nomainforscripts(messages['cli.option.nomainforscripts.description'])
cli.notimestamp(messages['cli.option.notimestamp.description'])
cli.noversionstamp(messages['cli.option.noversionstamp.description'])
+ cli.noindex(messages['cli.option.noindex.description'])
+ cli.nodeprecatedlist(messages['cli.option.nodeprecatedlist.description'])
+ cli.nohelp(messages['cli.option.nohelp.description'])
cli.overview(args:1, argName: 'file', messages['cli.option.overview.description'])
cli.public(messages['cli.option.public.description'])
cli.protected(messages['cli.option.protected.description'])
@@ -145,6 +151,9 @@ class Main {
noMainForScripts = Boolean.valueOf(options.nomainforscripts) ?: false
noTimestamp = Boolean.valueOf(options.notimestamp) ?: false
noVersionStamp = Boolean.valueOf(options.noversionstamp) ?: false
+ noIndex = Boolean.valueOf(options.noindex) ?: false
+ noDeprecatedList = Boolean.valueOf(options.nodeprecatedlist) ?: false
+ noHelp = Boolean.valueOf(options.nohelp) ?: false
showInternal = Boolean.valueOf(options.showInternal) ?: false
packageScope = Boolean.valueOf(options.package) ?: false
privateScope = Boolean.valueOf(options.private) ?: false
@@ -230,6 +239,10 @@ class Main {
properties.put("additionalStylesheets", addStylesheetFiles*.name.join(','))
properties.put("timestamp", (!noTimestamp).toString())
properties.put("versionStamp", (!noVersionStamp).toString())
+ // GROOVY-11943: javadoc-parity disable flags for auxiliary top-level pages.
+ properties.put("noIndex", noIndex.toString())
+ properties.put("noDeprecatedList", noDeprecatedList.toString())
+ properties.put("noHelp", noHelp.toString())
properties.put("overviewFile", overviewFile?.absolutePath ?: "")
String phaseOverride = SystemUtil.getSystemPropertySafe("groovydoc.phase.override")
if (phaseOverride) properties.put("phaseOverride", phaseOverride)
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyDocWriter.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyDocWriter.java
index 886d3fbd12..f3fb75b518 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyDocWriter.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyDocWriter.java
@@ -161,6 +161,7 @@ public class GroovyDocWriter {
Iterator<String> templates = templateEngine.docTemplatesIterator();
while (templates.hasNext()) {
String template = templates.next();
+ if (isDisabledRootTemplate(template)) continue;
String destFileName = destdir + FS + GroovyDocUtil.getFile(template);
log.debug("Generating " + destFileName);
if (hasBinaryExtension(template)) {
@@ -172,6 +173,15 @@ public class GroovyDocWriter {
}
}
+ // GROOVY-11943: javadoc-parity disable flags skip the matching top-level page.
+ private boolean isDisabledRootTemplate(String template) {
+ String name = GroovyDocUtil.getFile(template);
+ if ("true".equals(properties.getProperty("noIndex")) && "index-all.html".equals(name)) return true;
+ if ("true".equals(properties.getProperty("noDeprecatedList")) && "deprecated-list.html".equals(name)) return true;
+ if ("true".equals(properties.getProperty("noHelp")) && "help-doc.html".equals(name)) return true;
+ return false;
+ }
+
private static boolean hasBinaryExtension(String template) {
return template.endsWith(".gif") || template.endsWith(".ico");
}
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/Main.properties b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/Main.properties
index c933f57e98..b650bed86e 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/Main.properties
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/Main.properties
@@ -60,6 +60,12 @@ cli.option.notimestamp.description=Don't include timestamp within hidden comment
cli.option.noversionstamp.description=Don't include Groovy version within hidden comment in generated HTML
+cli.option.noindex.description=Don't generate the class/member index page
+
+cli.option.nodeprecatedlist.description=Don't generate the deprecated-list page
+
+cli.option.nohelp.description=Don't generate the help page
+
cli.option.public.description=Show only public classes and members
cli.option.protected.description=Show protected/public classes and members (default)
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.html
index 0020fc5761..d609933b20 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.html
@@ -118,9 +118,9 @@ if (location.href.indexOf('is-external=true') == -1) {
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
- <li><a href="${classDoc.relativeRootPath}deprecated-list.html">Deprecated</a></li>
- <li><a href="${classDoc.relativeRootPath}index-all.html">Index</a></li>
- <li><a href="${classDoc.relativeRootPath}help-doc.html">Help</a></li>
+ <% if (props.noDeprecatedList != 'true') { %><li><a href="${classDoc.relativeRootPath}deprecated-list.html">Deprecated</a></li><% } %>
+ <% if (props.noIndex != 'true') { %><li><a href="${classDoc.relativeRootPath}index-all.html">Index</a></li><% } %>
+ <% if (props.noHelp != 'true') { %><li><a href="${classDoc.relativeRootPath}help-doc.html">Help</a></li><% } %>
</ul>
</div>
@@ -726,9 +726,9 @@ if (classDoc.isInterface() && classDoc.interfaces()) {
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
- <li><a href="${classDoc.relativeRootPath}deprecated-list.html">Deprecated</a></li>
- <li><a href="${classDoc.relativeRootPath}index-all.html">Index</a></li>
- <li><a href="${classDoc.relativeRootPath}help-doc.html">Help</a></li>
+ <% if (props.noDeprecatedList != 'true') { %><li><a href="${classDoc.relativeRootPath}deprecated-list.html">Deprecated</a></li><% } %>
+ <% if (props.noIndex != 'true') { %><li><a href="${classDoc.relativeRootPath}index-all.html">Index</a></li><% } %>
+ <% if (props.noHelp != 'true') { %><li><a href="${classDoc.relativeRootPath}help-doc.html">Help</a></li><% } %>
</ul>
</div>
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html
index c21594666a..06d1bc0691 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html
@@ -70,9 +70,9 @@ function windowTitle()
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-tree.html">Tree</a></li>
- <li><a href="${packageDoc.relativeRootPath}deprecated-list.html">Deprecated</a></li>
- <li><a href="${packageDoc.relativeRootPath}index-all.html">Index</a></li>
- <li><a href="${packageDoc.relativeRootPath}help-doc.html">Help</a></li>
+ <% if (props.noDeprecatedList != 'true') { %><li><a href="${packageDoc.relativeRootPath}deprecated-list.html">Deprecated</a></li><% } %>
+ <% if (props.noIndex != 'true') { %><li><a href="${packageDoc.relativeRootPath}index-all.html">Index</a></li><% } %>
+ <% if (props.noHelp != 'true') { %><li><a href="${packageDoc.relativeRootPath}help-doc.html">Help</a></li><% } %>
</ul>
</div>
@@ -142,9 +142,9 @@ classTypes.each { k, v ->
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-tree.html">Tree</a></li>
- <li><a href="deprecated-list.html">Deprecated</a></li>
- <li><a href="index-all.html">Index</a></li>
- <li><a href="help-doc.html">Help</a></li>
+ <% if (props.noDeprecatedList != 'true') { %><% if (props.noDeprecatedList != 'true') { %><li><a href="deprecated-list.html">Deprecated</a></li><% } %><% } %>
+ <% if (props.noIndex != 'true') { %><% if (props.noIndex != 'true') { %><li><a href="index-all.html">Index</a></li><% } %><% } %>
+ <% if (props.noHelp != 'true') { %><% if (props.noHelp != 'true') { %><li><a href="help-doc.html">Help</a></li><% } %><% } %>
</ul>
</div>
<div class="subNav">
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-tree.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-tree.html
index ef38160e4a..4dee916e02 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-tree.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-tree.html
@@ -42,9 +42,9 @@
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Tree</li>
- <li><a href="${packageDoc.relativeRootPath}deprecated-list.html">Deprecated</a></li>
- <li><a href="${packageDoc.relativeRootPath}index-all.html">Index</a></li>
- <li><a href="${packageDoc.relativeRootPath}help-doc.html">Help</a></li>
+ <% if (props.noDeprecatedList != 'true') { %><li><a href="${packageDoc.relativeRootPath}deprecated-list.html">Deprecated</a></li><% } %>
+ <% if (props.noIndex != 'true') { %><li><a href="${packageDoc.relativeRootPath}index-all.html">Index</a></li><% } %>
+ <% if (props.noHelp != 'true') { %><li><a href="${packageDoc.relativeRootPath}help-doc.html">Help</a></li><% } %>
</ul>
</div>
<div class="subNav">
@@ -128,9 +128,9 @@
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Tree</li>
- <li><a href="${packageDoc.relativeRootPath}deprecated-list.html">Deprecated</a></li>
- <li><a href="${packageDoc.relativeRootPath}index-all.html">Index</a></li>
- <li><a href="${packageDoc.relativeRootPath}help-doc.html">Help</a></li>
+ <% if (props.noDeprecatedList != 'true') { %><li><a href="${packageDoc.relativeRootPath}deprecated-list.html">Deprecated</a></li><% } %>
+ <% if (props.noIndex != 'true') { %><li><a href="${packageDoc.relativeRootPath}index-all.html">Index</a></li><% } %>
+ <% if (props.noHelp != 'true') { %><li><a href="${packageDoc.relativeRootPath}help-doc.html">Help</a></li><% } %>
</ul>
</div>
<div class="subNav">
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/deprecated-list.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/deprecated-list.html
index 7f13927545..1cd7aa5d2c 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/deprecated-list.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/deprecated-list.html
@@ -113,8 +113,8 @@ if (location.href.indexOf('is-external=true') == -1) {
<li>Package</li>
<li>Class</li>
<li class="navBarCell1Rev">Deprecated</li>
- <li><a href="index-all.html">Index</a></li>
- <li><a href="help-doc.html">Help</a></li>
+ <% if (props.noIndex != 'true') { %><li><a href="index-all.html">Index</a></li><% } %>
+ <% if (props.noHelp != 'true') { %><li><a href="help-doc.html">Help</a></li><% } %>
</ul>
</div>
<div class="subNav">
@@ -250,8 +250,8 @@ methodTypes.each{ k, v ->
<li>Package</li>
<li>Class</li>
<li class="navBarCell1Rev">Deprecated</li>
- <li><a href="index-all.html">Index</a></li>
- <li><a href="help-doc.html">Help</a></li>
+ <% if (props.noIndex != 'true') { %><li><a href="index-all.html">Index</a></li><% } %>
+ <% if (props.noHelp != 'true') { %><li><a href="help-doc.html">Help</a></li><% } %>
</ul>
</div>
<div class="subNav">
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/help-doc.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/help-doc.html
index c64cb8b135..6a863098a8 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/help-doc.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/help-doc.html
@@ -54,8 +54,8 @@ if (location.href.indexOf('is-external=true') == -1) {
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
- <li><a href="deprecated-list.html">Deprecated</a></li>
- <li><a href="index-all.html">Index</a></li>
+ <% if (props.noDeprecatedList != 'true') { %><li><a href="deprecated-list.html">Deprecated</a></li><% } %>
+ <% if (props.noIndex != 'true') { %><li><a href="index-all.html">Index</a></li><% } %>
<li class="navBarCell1Rev">Help</li>
</ul>
</div>
@@ -180,8 +180,8 @@ if (location.href.indexOf('is-external=true') == -1) {
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
- <li><a href="deprecated-list.html">Deprecated</a></li>
- <li><a href="index-all.html">Index</a></li>
+ <% if (props.noDeprecatedList != 'true') { %><li><a href="deprecated-list.html">Deprecated</a></li><% } %>
+ <% if (props.noIndex != 'true') { %><li><a href="index-all.html">Index</a></li><% } %>
<li class="navBarCell1Rev">Help</li>
</ul>
</div>
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/index-all.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/index-all.html
index 2020f5e56b..6ea64d0cf2 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/index-all.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/index-all.html
@@ -67,9 +67,9 @@ if (location.href.indexOf('is-external=true') == -1) {
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
- <li><a href="deprecated-list.html">Deprecated</a></li>
+ <% if (props.noDeprecatedList != 'true') { %><li><a href="deprecated-list.html">Deprecated</a></li><% } %>
<li class="navBarCell1Rev">Index</li>
- <li><a href="help-doc.html">Help</a></li>
+ <% if (props.noHelp != 'true') { %><li><a href="help-doc.html">Help</a></li><% } %>
</ul>
</div>
<div class="subNav">
@@ -156,9 +156,9 @@ letters.each { letter ->
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
- <li><a href="deprecated-list.html">Deprecated</a></li>
+ <% if (props.noDeprecatedList != 'true') { %><li><a href="deprecated-list.html">Deprecated</a></li><% } %>
<li class="navBarCell1Rev">Index</li>
- <li><a href="help-doc.html">Help</a></li>
+ <% if (props.noHelp != 'true') { %><li><a href="help-doc.html">Help</a></li><% } %>
</ul>
</div>
<div class="subNav">
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary.html
index a013df2b30..66e7d44eee 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary.html
@@ -54,9 +54,9 @@ if (location.href.indexOf('is-external=true') == -1) {
<li>Package</li>
<li>Class</li>
<li><a href="overview-tree.html">Tree</a></li>
- <li><a href="deprecated-list.html">Deprecated</a></li>
- <li><a href="index-all.html">Index</a></li>
- <li><a href="help-doc.html">Help</a></li>
+ <% if (props.noDeprecatedList != 'true') { %><li><a href="deprecated-list.html">Deprecated</a></li><% } %>
+ <% if (props.noIndex != 'true') { %><li><a href="index-all.html">Index</a></li><% } %>
+ <% if (props.noHelp != 'true') { %><li><a href="help-doc.html">Help</a></li><% } %>
</ul>
</div>
<div class="subNav">
@@ -128,9 +128,9 @@ if (location.href.indexOf('is-external=true') == -1) {
<li>Package</li>
<li>Class</li>
<li><a href="overview-tree.html">Tree</a></li>
- <li><a href="deprecated-list.html">Deprecated</a></li>
- <li><a href="index-all.html">Index</a></li>
- <li><a href="help-doc.html">Help</a></li>
+ <% if (props.noDeprecatedList != 'true') { %><li><a href="deprecated-list.html">Deprecated</a></li><% } %>
+ <% if (props.noIndex != 'true') { %><li><a href="index-all.html">Index</a></li><% } %>
+ <% if (props.noHelp != 'true') { %><li><a href="help-doc.html">Help</a></li><% } %>
</ul>
</div>
<div class="subNav">
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-tree.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-tree.html
index dc171d224c..07acbdef56 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-tree.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-tree.html
@@ -42,9 +42,9 @@
<li>Package</li>
<li>Class</li>
<li class="navBarCell1Rev">Tree</li>
- <li><a href="deprecated-list.html">Deprecated</a></li>
- <li><a href="index-all.html">Index</a></li>
- <li><a href="help-doc.html">Help</a></li>
+ <% if (props.noDeprecatedList != 'true') { %><li><a href="deprecated-list.html">Deprecated</a></li><% } %>
+ <% if (props.noIndex != 'true') { %><li><a href="index-all.html">Index</a></li><% } %>
+ <% if (props.noHelp != 'true') { %><li><a href="help-doc.html">Help</a></li><% } %>
</ul>
</div>
<div class="subNav">
@@ -129,9 +129,9 @@
<li>Package</li>
<li>Class</li>
<li class="navBarCell1Rev">Tree</li>
- <li><a href="deprecated-list.html">Deprecated</a></li>
- <li><a href="index-all.html">Index</a></li>
- <li><a href="help-doc.html">Help</a></li>
+ <% if (props.noDeprecatedList != 'true') { %><li><a href="deprecated-list.html">Deprecated</a></li><% } %>
+ <% if (props.noIndex != 'true') { %><li><a href="index-all.html">Index</a></li><% } %>
+ <% if (props.noHelp != 'true') { %><li><a href="help-doc.html">Help</a></li><% } %>
</ul>
</div>
<div class="subNav">
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index 8bdeecfc93..10b18e8d54 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -436,6 +436,47 @@ public class GroovyDocToolTest extends GroovyTestCase {
+ occurrences + " in:\n" + doc, 2, occurrences);
}
+ // GROOVY-11943: -noindex / -nodeprecatedlist / -nohelp skip the matching
+ // auxiliary top-level page AND suppress its nav-bar link on every page
+ // that would otherwise reference it.
+ public void testDisableFlagsSkipPageAndNavLink() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ Properties props = new Properties();
+ props.put("noIndex", "true");
+ props.put("noDeprecatedList", "true");
+ props.put("noHelp", "true");
+ GroovyDocTool tool = makeHtmltool(new ArrayList<>(), null, props);
+ tool.add(List.of(base + "/DocumentedClass.groovy"));
+
+ MockOutputTool output = new MockOutputTool();
+ tool.renderToOutput(output, MOCK_DIR);
+
+ assertNull("index-all.html should be skipped when noIndex=true",
+ output.getText(MOCK_DIR + "/index-all.html"));
+ assertNull("deprecated-list.html should be skipped when noDeprecatedList=true",
+ output.getText(MOCK_DIR + "/deprecated-list.html"));
+ assertNull("help-doc.html should be skipped when noHelp=true",
+ output.getText(MOCK_DIR + "/help-doc.html"));
+
+ String overview = output.getText(MOCK_DIR + "/overview-summary.html");
+ assertNotNull(overview);
+ assertFalse("Overview nav should not link to suppressed index-all.html:\n" + overview,
+ overview.contains("href=\"index-all.html\""));
+ assertFalse("Overview nav should not link to suppressed deprecated-list.html:\n" + overview,
+ overview.contains("href=\"deprecated-list.html\""));
+ assertFalse("Overview nav should not link to suppressed help-doc.html:\n" + overview,
+ overview.contains("href=\"help-doc.html\""));
+
+ String classPage = output.getText(MOCK_DIR + "/" + base + "/DocumentedClass.html");
+ assertNotNull(classPage);
+ assertFalse("Class nav should not link to suppressed index-all.html:\n" + classPage,
+ classPage.contains("index-all.html"));
+ assertFalse("Class nav should not link to suppressed deprecated-list.html:\n" + classPage,
+ classPage.contains("deprecated-list.html"));
+ assertFalse("Class nav should not link to suppressed help-doc.html:\n" + classPage,
+ classPage.contains("help-doc.html"));
+ }
+
// GROOVY-11942: overview-tree.html renders the class hierarchy rooted at
// java.lang.Object and an Interface Hierarchy section for traits/interfaces.
public void testTreePagesRenderExpectedHierarchy() throws Exception {
(groovy) 03/34: GROOVY-4634: honor @Documented on annotation refs
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit cb8b0d06a620ced592dab3cd16dbb671e910d6e8
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Apr 20 08:07:29 2026 +1000
GROOVY-4634: honor @Documented on annotation refs
---
src/main/java/groovy/transform/Generated.java | 2 +
src/main/java/groovy/transform/NamedParam.java | 2 +
src/main/java/groovy/transform/NamedParams.java | 2 +
src/main/java/groovy/transform/NamedVariant.java | 2 +
.../org/apache/groovy/antlr/GroovydocVisitor.java | 17 +++++++
.../groovydoc/antlr4/GroovydocJavaVisitor.java | 57 +++++++++++++++++++++-
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 22 +++++----
.../tools/groovydoc/testfiles/anno/Groovy.groovy | 5 +-
.../tools/groovydoc/testfiles/anno/Java.java | 5 +-
9 files changed, 99 insertions(+), 15 deletions(-)
diff --git a/src/main/java/groovy/transform/Generated.java b/src/main/java/groovy/transform/Generated.java
index 218e2b8bf9..2379842c20 100644
--- a/src/main/java/groovy/transform/Generated.java
+++ b/src/main/java/groovy/transform/Generated.java
@@ -18,6 +18,7 @@
*/
package groovy.transform;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -28,6 +29,7 @@ import java.lang.annotation.Target;
*
* @since 2.5.0
*/
+@Documented
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Generated {
diff --git a/src/main/java/groovy/transform/NamedParam.java b/src/main/java/groovy/transform/NamedParam.java
index 19835e3062..1a6f5cd772 100644
--- a/src/main/java/groovy/transform/NamedParam.java
+++ b/src/main/java/groovy/transform/NamedParam.java
@@ -18,6 +18,7 @@
*/
package groovy.transform;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
@@ -31,6 +32,7 @@ import java.lang.annotation.Target;
*
* @since 2.5.0
*/
+@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@Repeatable(NamedParams.class)
diff --git a/src/main/java/groovy/transform/NamedParams.java b/src/main/java/groovy/transform/NamedParams.java
index e61d9b4315..025d35eeca 100644
--- a/src/main/java/groovy/transform/NamedParams.java
+++ b/src/main/java/groovy/transform/NamedParams.java
@@ -18,6 +18,7 @@
*/
package groovy.transform;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -28,6 +29,7 @@ import java.lang.annotation.Target;
*
* @since 2.5.0
*/
+@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface NamedParams {
diff --git a/src/main/java/groovy/transform/NamedVariant.java b/src/main/java/groovy/transform/NamedVariant.java
index 1882734486..a0f3ad8867 100644
--- a/src/main/java/groovy/transform/NamedVariant.java
+++ b/src/main/java/groovy/transform/NamedVariant.java
@@ -20,6 +20,7 @@ package groovy.transform;
import org.codehaus.groovy.transform.GroovyASTTransformationClass;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -107,6 +108,7 @@ import java.lang.annotation.Target;
* @see NamedDelegate
* @since 2.5.0
*/
+@Documented
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
@GroovyASTTransformationClass("org.codehaus.groovy.transform.NamedVariantASTTransformation")
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java b/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
index 51690fa3ae..8ad221d67c 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
@@ -193,6 +193,7 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
private void processAnnotations(SimpleGroovyProgramElementDoc element, AnnotatedNode node) {
for (AnnotationNode an : node.getAnnotations()) {
String name = an.getClassNode().getName();
+ if (!shouldDocument(name)) continue;
element.addAnnotationRef(new SimpleGroovyAnnotationRef(name, an.getText()));
}
}
@@ -200,10 +201,26 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
private void processAnnotations(SimpleGroovyParameter param, AnnotatedNode node) {
for (AnnotationNode an : node.getAnnotations()) {
String name = an.getClassNode().getName();
+ if (!shouldDocument(name)) continue;
param.addAnnotationRef(new SimpleGroovyAnnotationRef(name, an.getText()));
}
}
+ // GROOVY-4634: emit an annotation reference only when the annotation type is
+ // itself marked {@code @Documented}, matching Javadoc's behavior. When the
+ // annotation type cannot be resolved on the current classpath (common for
+ // user-defined annotations in the source tree being documented), default
+ // to including it so that groovydoc does not silently drop user annotations.
+ private static boolean shouldDocument(String fqn) {
+ try {
+ Class<?> c = Class.forName(fqn);
+ if (!c.isAnnotation()) return true;
+ return c.isAnnotationPresent(java.lang.annotation.Documented.class);
+ } catch (Throwable t) {
+ return true;
+ }
+ }
+
@Override
public void visitConstructor(ConstructorNode node) {
if (node.isSynthetic()) return;
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/antlr4/GroovydocJavaVisitor.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/antlr4/GroovydocJavaVisitor.java
index 440d81c5e3..3b8ec53c16 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/antlr4/GroovydocJavaVisitor.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/antlr4/GroovydocJavaVisitor.java
@@ -245,13 +245,66 @@ public class GroovydocJavaVisitor
private void processAnnotations(SimpleGroovyProgramElementDoc element, NodeWithAnnotations<?> n) {
for (AnnotationExpr an : n.getAnnotations()) {
- element.addAnnotationRef(new SimpleGroovyAnnotationRef(an.getNameAsString(), getAnnotationText(an)));
+ String name = an.getNameAsString();
+ if (!shouldDocument(name)) continue;
+ element.addAnnotationRef(new SimpleGroovyAnnotationRef(name, getAnnotationText(an)));
}
}
private void processAnnotations(SimpleGroovyParameter param, NodeWithAnnotations<?> n) {
for (AnnotationExpr an : n.getAnnotations()) {
- param.addAnnotationRef(new SimpleGroovyAnnotationRef(an.getNameAsString(), getAnnotationText(an)));
+ String name = an.getNameAsString();
+ if (!shouldDocument(name)) continue;
+ param.addAnnotationRef(new SimpleGroovyAnnotationRef(name, getAnnotationText(an)));
+ }
+ }
+
+ // GROOVY-4634: emit an annotation reference only when the annotation type is
+ // itself marked {@code @Documented}, matching Javadoc's behavior. When the
+ // annotation type cannot be resolved on the current classpath, default to
+ // including it so that groovydoc does not silently drop user annotations.
+ private boolean shouldDocument(String name) {
+ String fqn = resolveAnnotationFqn(name);
+ if (fqn == null) return true; // unresolved — show
+ try {
+ Class<?> c = Class.forName(fqn);
+ if (!c.isAnnotation()) return true;
+ return c.isAnnotationPresent(java.lang.annotation.Documented.class);
+ } catch (Throwable t) {
+ return true;
+ }
+ }
+
+ private String resolveAnnotationFqn(String name) {
+ // already fully qualified
+ if (name.contains(".")) {
+ if (tryLoad(name) != null) return name;
+ // nested-name like "CommandLine.Parameters" — resolve outer via aliases
+ int dot = name.indexOf('.');
+ String outer = name.substring(0, dot);
+ String rest = name.substring(dot);
+ String outerFqn = aliases.get(outer);
+ if (outerFqn != null) {
+ String candidate = outerFqn.replace('/', '.') + rest.replace('.', '$');
+ if (tryLoad(candidate) != null) return candidate;
+ }
+ return null;
+ }
+ String importedFqn = aliases.get(name);
+ if (importedFqn != null) {
+ String candidate = importedFqn.replace('/', '.');
+ if (tryLoad(candidate) != null) return candidate;
+ }
+ String javaLang = "java.lang." + name;
+ if (tryLoad(javaLang) != null) return javaLang;
+ return null;
+ }
+
+ private static Class<?> tryLoad(String fqn) {
+ try {
+ return Class.forName(fqn);
+ } catch (Throwable t) {
+ return null;
}
}
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index 64f8db2cfe..af96e13e58 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -1257,17 +1257,19 @@ public class GroovyDocToolTest extends GroovyTestCase {
"class Groovy"
)).matcher(groovydoc).find());
- assertTrue("The Java class declaration header should have the annotation in:\n" + javadoc, Pattern.compile(
+ // GROOVY-4634: @SuppressWarnings is not @Documented so is filtered out (matches Javadoc behavior)
+ assertTrue("The Java class declaration header should have only the @Documented annotation in:\n" + javadoc, Pattern.compile(
"<pre>@(<a href='https://docs.oracle.com/javase/8/docs/api/java/lang/Deprecated.html' title='Deprecated'>Deprecated</a>|java.lang.Deprecated)\n" +
- "@(<a href='https://docs.oracle.com/javase/8/docs/api/java/lang/SuppressWarnings.html' title='SuppressWarnings'>SuppressWarnings</a>|java.lang.SuppressWarnings)\\(\"foo\"\\)\n" +
"public class Java"
).matcher(javadoc).find());
+ assertFalse("@SuppressWarnings (not @Documented) should not appear in:\n" + javadoc,
+ javadoc.contains("SuppressWarnings"));
- assertTrue("The Groovy field details should have the annotation in:" + groovydoc, Pattern.compile(
- "<h4>@groovy.transform.Internal<br>" +
- "public (<a href='https://docs.oracle.com/javase/8/docs/api/java/lang/String.html' title='String'>String</a>|java.lang.String) " +
- "<strong>annotatedField</strong></h4>"
- ).matcher(groovydoc).find());
+ // GROOVY-4634: @groovy.transform.Internal is not @Documented so is filtered out
+ assertFalse("@Internal (not @Documented) should not appear on annotatedField in:\n" + groovydoc,
+ Pattern.compile("<h4>@groovy.transform.Internal<br>\\s*public .*annotatedField").matcher(groovydoc).find());
+ assertTrue("The Groovy field details should still render the field itself in:\n" + groovydoc,
+ Pattern.compile("<strong>annotatedField</strong></h4>").matcher(groovydoc).find());
assertTrue("The Java field details should have the annotation", Pattern.compile(
"<h4>@(<a href='https://docs.oracle.com/javase/8/docs/api/java/lang/Deprecated.html' title='Deprecated'>Deprecated</a>|java.lang.Deprecated)<br>" +
@@ -1317,13 +1319,15 @@ public class GroovyDocToolTest extends GroovyTestCase {
"\\)</h4>"
).matcher(groovydoc).find());
- assertTrue("The Java method details should have the annotations in:\n" + javadoc, Pattern.compile(
+ // GROOVY-4634: @CommandLine.Parameters (picocli) is not @Documented so is filtered out
+ assertTrue("The Java method details should have the @Documented annotation in:\n" + javadoc, Pattern.compile(
"<h4>@(<a href='https://docs.oracle.com/javase/8/docs/api/java/lang/Deprecated.html' title='Deprecated'>Deprecated</a>|java.lang.Deprecated)<br>" +
"public void <strong>annotatedMethod</strong>\\(" +
- "@CommandLine.Parameters\\(hidden = true\\)<br>" +
"(<a href='https://docs.oracle.com/javase/8/docs/api/java/lang/String.html' title='String'>String</a>|java.lang.String) annotatedParam" +
"\\)</h4>"
).matcher(javadoc).find());
+ assertFalse("@CommandLine.Parameters (not @Documented) should not appear on annotatedParam in:\n" + javadoc,
+ javadoc.contains("@CommandLine.Parameters"));
}
public void testAbstractMethods() throws Exception {
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/anno/Groovy.groovy b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/anno/Groovy.groovy
index 1362c88fb0..db052b0dee 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/anno/Groovy.groovy
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/anno/Groovy.groovy
@@ -22,8 +22,9 @@ import groovy.transform.EqualsAndHashCode
import groovy.transform.NamedParam
import groovy.transform.NamedVariant
-// The annotations that are used here don't really matter,
-// since groovydoc shows all annotations, not just @Documented ones.
+// GROOVY-4634: groovydoc now filters by @Documented (like Javadoc). @Internal
+// (not @Documented) should be filtered out; user-facing transform annotations
+// like @EqualsAndHashCode, @NamedVariant, @NamedParam, @Generated keep showing.
@EqualsAndHashCode(cache = true)
class Groovy implements Serializable {
@groovy.transform.Internal
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/anno/Java.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/anno/Java.java
index a84c66f081..4519217690 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/anno/Java.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/anno/Java.java
@@ -23,8 +23,9 @@ import picocli.CommandLine;
import java.io.Serializable;
-// The annotations that are used here don't really matter,
-// since groovydoc shows all annotations, not just @Documented ones.
+// GROOVY-4634: groovydoc now filters by @Documented (like Javadoc). Mix of
+// @Documented (e.g. @Deprecated) and non-@Documented (e.g. @SuppressWarnings,
+// @CommandLine.Parameters) used to exercise both arms of the filter.
@Deprecated
@SuppressWarnings("foo")
public class Java implements Serializable {
(groovy) 04/34: GROOVY-9572: some __$stMC fields are inherited from base class in groovydoc
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit c6ed59d00ac03e549083d20722af2b617276cdd3
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Apr 20 08:53:46 2026 +1000
GROOVY-9572: some __$stMC fields are inherited from base class in groovydoc
---
.../org/codehaus/groovy/classgen/Verifier.java | 7 ++++
src/test/groovy/bugs/Groovy9572.groovy | 40 ++++++++++++++++++++++
.../java/org/codehaus/groovy/ant/Groovydoc.java | 14 ++++++++
.../codehaus/groovy/tools/groovydoc/Main.groovy | 4 +++
.../org/apache/groovy/antlr/GroovydocVisitor.java | 13 +++++++
.../tools/groovydoc/antlr4/GroovyDocParser.java | 2 +-
.../groovydoc/antlr4/GroovydocJavaVisitor.java | 27 +++++++++++++++
.../groovy/tools/groovydoc/Main.properties | 2 ++
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 39 ++++++++++++++++++---
9 files changed, 142 insertions(+), 6 deletions(-)
diff --git a/src/main/java/org/codehaus/groovy/classgen/Verifier.java b/src/main/java/org/codehaus/groovy/classgen/Verifier.java
index 4300c57743..e9fdb4c782 100644
--- a/src/main/java/org/codehaus/groovy/classgen/Verifier.java
+++ b/src/main/java/org/codehaus/groovy/classgen/Verifier.java
@@ -96,6 +96,7 @@ import static java.util.stream.Collectors.joining;
import static org.apache.groovy.ast.tools.AnnotatedNodeUtils.hasAnnotation;
import static org.apache.groovy.ast.tools.AnnotatedNodeUtils.isGenerated;
import static org.apache.groovy.ast.tools.AnnotatedNodeUtils.markAsGenerated;
+import static org.apache.groovy.ast.tools.AnnotatedNodeUtils.markAsInternal;
import static org.apache.groovy.ast.tools.ConstructorNodeUtils.getFirstIfSpecialConstructorCall;
import static org.apache.groovy.ast.tools.ExpressionUtils.transformInlineConstants;
import static org.codehaus.groovy.ast.ClassHelper.isObjectType;
@@ -486,6 +487,12 @@ public class Verifier implements GroovyClassVisitor, Opcodes {
ACC_PUBLIC | ACC_STATIC | ACC_SYNTHETIC | ACC_TRANSIENT,
ClassHelper.boolean_TYPE, null);
stMCB.setSynthetic(true);
+ // GROOVY-9572: mark as @Internal (GEP-17) so groovydoc hides it from
+ // inherited-field listings. Skip for classes built programmatically
+ // without a module context (matches the guard used by markAsGenerated).
+ if (node.getModule() != null && node.getModule().getContext() != null) {
+ markAsInternal(stMCB);
+ }
}
}
diff --git a/src/test/groovy/bugs/Groovy9572.groovy b/src/test/groovy/bugs/Groovy9572.groovy
new file mode 100644
index 0000000000..24e59bee23
--- /dev/null
+++ b/src/test/groovy/bugs/Groovy9572.groovy
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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 bugs
+
+import groovy.transform.Internal
+import org.codehaus.groovy.classgen.Verifier
+import org.junit.jupiter.api.Test
+
+/**
+ * GROOVY-9572B: the Verifier-generated {@code __$stMC} field (constant
+ * {@link Verifier#STATIC_METACLASS_BOOL}) should carry
+ * {@link groovy.transform.Internal} so that tooling (groovydoc per GEP-17)
+ * can hide it from generated documentation of subclasses that inherit it.
+ */
+final class Groovy9572 {
+
+ @Test
+ void stMCFieldIsMarkedInternal() {
+ def cls = new GroovyClassLoader().parseClass('class Sample9572 {}')
+ def field = cls.getDeclaredField(Verifier.STATIC_METACLASS_BOOL)
+ assert field != null
+ assert field.isAnnotationPresent(Internal)
+ }
+}
diff --git a/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java b/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java
index ec4b53fb90..cd9e76506c 100644
--- a/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java
+++ b/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java
@@ -67,6 +67,7 @@ public class Groovydoc extends Task {
private boolean includeNoSourcePackages;
private Boolean noTimestamp;
private Boolean noVersionStamp;
+ private Boolean showInternal;
private String javaVersion;
private final List<DirSet> packageSets;
private final List<String> sourceFilesToDoc;
@@ -95,6 +96,7 @@ public class Groovydoc extends Task {
includeMainForScripts = true;
noTimestamp = false;
noVersionStamp = false;
+ showInternal = false;
}
/**
@@ -157,6 +159,17 @@ public class Groovydoc extends Task {
this.javaVersion = javaVersion;
}
+ /**
+ * If set to true, members annotated with {@code groovy.transform.@Internal}
+ * (per GEP-17) are still included in the generated documentation. Defaults
+ * to false, so internal members are hidden.
+ *
+ * @param showInternal new value
+ */
+ public void setShowInternal(boolean showInternal) {
+ this.showInternal = showInternal;
+ }
+
/**
* If set to false, Scripts will not be processed.
* Defaults to true.
@@ -464,6 +477,7 @@ public class Groovydoc extends Task {
properties.setProperty("fileEncoding", fileEncoding != null ? fileEncoding : "");
properties.setProperty("timestamp", Boolean.valueOf(!noTimestamp).toString());
properties.setProperty("versionStamp", Boolean.valueOf(!noVersionStamp).toString());
+ properties.setProperty("showInternal", showInternal.toString());
String phaseOverride = SystemUtil.getSystemPropertySafe("groovydoc.phase.override");
if (phaseOverride != null) properties.put("phaseOverride", phaseOverride);
diff --git a/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy b/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy
index a18ddb5555..376c982c1d 100644
--- a/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy
+++ b/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy
@@ -50,6 +50,7 @@ class Main {
private static Boolean publicScope
private static Boolean protectedScope
private static Boolean debug = false
+ private static Boolean showInternal
private static String[] sourcepath
private static String javaVersion
private static List<String> sourceFilesToDoc
@@ -92,6 +93,7 @@ class Main {
cli.stylesheetfile(args:1, argName: 'path', messages['cli.option.stylesheetfile.description'])
cli.sourcepath(args:1, argName: 'pathlist', messages['cli.option.sourcepath.description'])
cli.javaVersion(args: 1, argName: 'javaVersion', messages['cli.option.javaVersion.description'])
+ cli.showInternal(messages['cli.option.showInternal.description'])
def options = cli.parse(args)
@@ -133,6 +135,7 @@ class Main {
noMainForScripts = Boolean.valueOf(options.nomainforscripts) ?: false
noTimestamp = Boolean.valueOf(options.notimestamp) ?: false
noVersionStamp = Boolean.valueOf(options.noversionstamp) ?: false
+ showInternal = Boolean.valueOf(options.showInternal) ?: false
packageScope = Boolean.valueOf(options.package) ?: false
privateScope = Boolean.valueOf(options.private) ?: false
protectedScope = Boolean.valueOf(options.protected) ?: false
@@ -212,6 +215,7 @@ class Main {
properties.put("author", author.toString())
properties.put("processScripts", (!noScripts).toString())
properties.put("includeMainForScripts", (!noMainForScripts).toString())
+ properties.put("showInternal", showInternal.toString())
properties.put("timestamp", (!noTimestamp).toString())
properties.put("versionStamp", (!noVersionStamp).toString())
properties.put("overviewFile", overviewFile?.absolutePath ?: "")
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java b/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
index 8ad221d67c..950b15ed18 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
@@ -61,6 +61,7 @@ import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import static org.apache.groovy.ast.tools.AnnotatedNodeUtils.deemedInternal;
import static org.codehaus.groovy.transform.trait.Traits.isTrait;
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
import static org.objectweb.asm.Opcodes.ACC_PROTECTED;
@@ -221,9 +222,18 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
}
}
+ // GROOVY-9572: hide members annotated with groovy.transform.@Internal (per GEP-17)
+ // or deemed internal by name convention (contains '$'), unless the user opts
+ // in with -showInternal / showInternal=true.
+ private boolean isInternal(AnnotatedNode node) {
+ if ("true".equals(properties.getProperty("showInternal", "false"))) return false;
+ return deemedInternal(node);
+ }
+
@Override
public void visitConstructor(ConstructorNode node) {
if (node.isSynthetic()) return;
+ if (isInternal(node)) return;
SimpleGroovyConstructorDoc cons = new SimpleGroovyConstructorDoc(currentClassDoc.simpleTypeName(), currentClassDoc);
setConstructorOrMethodCommon(node, cons);
currentClassDoc.add(cons);
@@ -235,6 +245,7 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
if (currentClassDoc.isEnum() && "$INIT".equals(node.getName()))
return;
if (node.isSynthetic()) return;
+ if (isInternal(node)) return;
if ("false".equals(properties.getProperty("includeMainForScripts", "true"))
&& currentClassDoc.isScript() && "main".equals(node.getName()) && node.isStatic() && node.getParameters().length == 1)
return;
@@ -321,6 +332,7 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
@Override
public void visitProperty(PropertyNode node) {
+ if (isInternal(node.getField())) return;
String name = node.getName();
SimpleGroovyFieldDoc fieldDoc = new SimpleGroovyFieldDoc(name, currentClassDoc);
fieldDoc.setType(new SimpleGroovyType(makeType(node.getType())));
@@ -387,6 +399,7 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
@Override
public void visitField(FieldNode node) {
if (node.isSynthetic()) return;
+ if (isInternal(node)) return;
String name = node.getName();
SimpleGroovyFieldDoc fieldDoc = new SimpleGroovyFieldDoc(name, currentClassDoc);
fieldDoc.setType(new SimpleGroovyType(makeType(node.getType())));
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/antlr4/GroovyDocParser.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/antlr4/GroovyDocParser.java
index c507ff79fc..79e2be7535 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/antlr4/GroovyDocParser.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/antlr4/GroovyDocParser.java
@@ -70,7 +70,7 @@ public class GroovyDocParser implements GroovyDocParserI {
}
private Map<String, GroovyClassDoc> parseJava(String packagePath, String file, String src) throws RuntimeException {
- GroovydocJavaVisitor visitor = new GroovydocJavaVisitor(packagePath, links);
+ GroovydocJavaVisitor visitor = new GroovydocJavaVisitor(packagePath, links, properties);
try {
visitor.visit(StaticJavaParser.parse(src), null);
} catch (Throwable t) {
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/antlr4/GroovydocJavaVisitor.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/antlr4/GroovydocJavaVisitor.java
index 3b8ec53c16..827fb61b1b 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/antlr4/GroovydocJavaVisitor.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/antlr4/GroovydocJavaVisitor.java
@@ -63,6 +63,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.Properties;
public class GroovydocJavaVisitor
extends VoidVisitorAdapter<Object> {
@@ -72,11 +73,17 @@ public class GroovydocJavaVisitor
private final String packagePath;
private final Map<String, String> aliases = new LinkedHashMap<>();
private final List<String> imports = new ArrayList<>();
+ private final Properties properties;
private static final String FS = "/";
public GroovydocJavaVisitor(String packagePath, List<LinkArgument> links) {
+ this(packagePath, links, new Properties());
+ }
+
+ public GroovydocJavaVisitor(String packagePath, List<LinkArgument> links, Properties properties) {
this.packagePath = packagePath;
this.links = links;
+ this.properties = properties;
}
@Override
@@ -315,6 +322,23 @@ public class GroovydocJavaVisitor
return "";
}
+ // GROOVY-9572: hide members annotated with groovy.transform.@Internal (per GEP-17)
+ // or deemed internal by name convention (contains '$'), unless the user opts
+ // in with -showInternal / showInternal=true. Mirrors the policy of
+ // {@link org.apache.groovy.ast.tools.AnnotatedNodeUtils#deemedInternal} on
+ // the Groovy-AST side, expressed against JavaParser AST nodes here.
+ private boolean isInternal(NodeWithAnnotations<?> n) {
+ if ("true".equals(properties.getProperty("showInternal", "false"))) return false;
+ for (AnnotationExpr an : n.getAnnotations()) {
+ String name = an.getNameAsString();
+ if ("Internal".equals(name) || name.endsWith(".Internal")) return true;
+ }
+ if (n instanceof FieldDeclaration fd && fd.getVariable(0).getNameAsString().contains("$")) return true;
+ if (n instanceof MethodDeclaration md && md.getNameAsString().contains("$")) return true;
+ if (n instanceof ConstructorDeclaration cd && cd.getNameAsString().contains("$")) return true;
+ return false;
+ }
+
private void setModifiers(NodeList<Modifier> modifiers, SimpleGroovyAbstractableElementDoc elementDoc) {
if (modifiers.contains(Modifier.publicModifier())) {
elementDoc.setPublic(true);
@@ -342,6 +366,7 @@ public class GroovydocJavaVisitor
@Override
public void visit(MethodDeclaration m, Object arg) {
+ if (isInternal(m)) return;
SimpleGroovyMethodDoc meth = new SimpleGroovyMethodDoc(m.getNameAsString(), currentClassDoc);
meth.setTypeParameters(genericTypesAsString(m.getTypeParameters()));
meth.setReturnType(makeType(m.getType()));
@@ -356,6 +381,7 @@ public class GroovydocJavaVisitor
@Override
public void visit(ConstructorDeclaration c, Object arg) {
+ if (isInternal(c)) return;
SimpleGroovyConstructorDoc meth = new SimpleGroovyConstructorDoc(c.getNameAsString(), currentClassDoc);
setConstructorOrMethodCommon(c, meth);
currentClassDoc.add(meth);
@@ -398,6 +424,7 @@ public class GroovydocJavaVisitor
@Override
public void visit(FieldDeclaration f, Object arg) {
+ if (isInternal(f)) return;
String name = f.getVariable(0).getNameAsString();
SimpleGroovyFieldDoc field = new SimpleGroovyFieldDoc(name, currentClassDoc);
field.setType(makeType(f.getVariable(0).getType()));
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/Main.properties b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/Main.properties
index 8636d1d79d..aa44b40fa0 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/Main.properties
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/Main.properties
@@ -78,4 +78,6 @@ cli.option.exclude.description=Specify a list of packages to exclude (separated
cli.option.javaVersion.description=Specify the Java Version for parsed java files (e.g. JAVA_11)
+cli.option.showInternal.description=Include members annotated with groovy.transform.@Internal (hidden by default)
+
cli.info.version=@|green GroovyDoc|@ {0}
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index af96e13e58..ebc6337f69 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -1265,11 +1265,9 @@ public class GroovyDocToolTest extends GroovyTestCase {
assertFalse("@SuppressWarnings (not @Documented) should not appear in:\n" + javadoc,
javadoc.contains("SuppressWarnings"));
- // GROOVY-4634: @groovy.transform.Internal is not @Documented so is filtered out
- assertFalse("@Internal (not @Documented) should not appear on annotatedField in:\n" + groovydoc,
- Pattern.compile("<h4>@groovy.transform.Internal<br>\\s*public .*annotatedField").matcher(groovydoc).find());
- assertTrue("The Groovy field details should still render the field itself in:\n" + groovydoc,
- Pattern.compile("<strong>annotatedField</strong></h4>").matcher(groovydoc).find());
+ // GROOVY-9572: @Internal-annotated members (per GEP-17) are hidden from groovydoc output
+ assertFalse("Field annotated with @Internal should be hidden in:\n" + groovydoc,
+ groovydoc.contains("<strong>annotatedField</strong>"));
assertTrue("The Java field details should have the annotation", Pattern.compile(
"<h4>@(<a href='https://docs.oracle.com/javase/8/docs/api/java/lang/Deprecated.html' title='Deprecated'>Deprecated</a>|java.lang.Deprecated)<br>" +
@@ -1330,6 +1328,37 @@ public class GroovyDocToolTest extends GroovyTestCase {
javadoc.contains("@CommandLine.Parameters"));
}
+ // GROOVY-9572A: members annotated with groovy.transform.@Internal are hidden,
+ // unless -showInternal / showInternal=true is set.
+ public void testInternalAnnotationHidesMembers() throws Exception {
+ final String base = "org/codehaus/groovy/tools/groovydoc/testfiles/anno";
+ Properties props = new Properties();
+ props.put("phaseOverride", "7");
+
+ // default: hidden
+ GroovyDocTool defaultTool = makeHtmltool(new ArrayList<>(), null, props);
+ defaultTool.add(Arrays.asList(base + "/Groovy.groovy"));
+ MockOutputTool defaultOut = new MockOutputTool();
+ defaultTool.renderToOutput(defaultOut, MOCK_DIR);
+ String defaultDoc = defaultOut.getText(MOCK_DIR + "/" + base + "/Groovy.html");
+ assertNotNull(defaultDoc);
+ assertFalse("annotatedField is @Internal and should be hidden by default in:\n" + defaultDoc,
+ defaultDoc.contains("<strong>annotatedField</strong>"));
+
+ // opt-in: shown
+ Properties opted = new Properties();
+ opted.put("phaseOverride", "7");
+ opted.put("showInternal", "true");
+ GroovyDocTool optedTool = makeHtmltool(new ArrayList<>(), null, opted);
+ optedTool.add(Arrays.asList(base + "/Groovy.groovy"));
+ MockOutputTool optedOut = new MockOutputTool();
+ optedTool.renderToOutput(optedOut, MOCK_DIR);
+ String optedDoc = optedOut.getText(MOCK_DIR + "/" + base + "/Groovy.html");
+ assertNotNull(optedDoc);
+ assertTrue("annotatedField should reappear with showInternal=true in:\n" + optedDoc,
+ optedDoc.contains("<strong>annotatedField</strong>"));
+ }
+
public void testAbstractMethods() throws Exception {
final String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
htmlTool.add(Arrays.asList(
(groovy) 19/34: add test to ensure script-level comments and runtime comments are compatible
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 0a9ca497e34840100ffcc2bded4ce97d3aeba4aa
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Apr 20 22:31:30 2026 +1000
add test to ensure script-level comments and runtime comments are compatible
---
src/test-resources/core/Groovydoc_02x.groovy | 43 ++++++++++++++++++++++
.../groovy/parser/antlr4/GroovyParserTest.groovy | 1 +
2 files changed, 44 insertions(+)
diff --git a/src/test-resources/core/Groovydoc_02x.groovy b/src/test-resources/core/Groovydoc_02x.groovy
new file mode 100644
index 0000000000..16e18c4501
--- /dev/null
+++ b/src/test-resources/core/Groovydoc_02x.groovy
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.
+ */
+
+// Task #24: verify runtime-groovydoc (/**@) attachment on script members
+// alongside GROOVY-8877 leading-doc scenarios. Runtime-doc attachment is
+// performed by the parser (GroovydocManager), independent of the groovydoc
+// visitor's HTML-generation lift — this fixture confirms the two systems
+// aren't accidentally coupled for the member-level case.
+//
+// Known runtime-doc gaps (pre-existing, independent of GROOVY-8877):
+// * Script-level /**@: a leading /**@ on a bare script is not attached to
+// the synthesised Script class — no AST node to claim it.
+// * @Field lift: /**@ before an @Field declaration is lost when the AST
+// transform lifts the local into a FieldNode; the annotation isn't
+// carried across.
+// Both are candidates for the separate runtime-groovydoc enhancement ticket.
+
+/**@
+ * Top-level method m.
+ */
+void m() {}
+
+// /**@ on a script's top-level method reaches the synthesised method.
+def mMethod = this.class.getDeclaredMethods().find { it.name == 'm' }
+assert mMethod != null
+assert mMethod.groovydoc.isPresent()
+assert mMethod.groovydoc.content.contains('Top-level method m')
diff --git a/src/test/groovy/org/apache/groovy/parser/antlr4/GroovyParserTest.groovy b/src/test/groovy/org/apache/groovy/parser/antlr4/GroovyParserTest.groovy
index 1abb9bd8cb..575b54bda6 100644
--- a/src/test/groovy/org/apache/groovy/parser/antlr4/GroovyParserTest.groovy
+++ b/src/test/groovy/org/apache/groovy/parser/antlr4/GroovyParserTest.groovy
@@ -460,6 +460,7 @@ final class GroovyParserTest {
compilerConfiguration.setOptimizationOptions([(CompilerConfiguration.RUNTIME_GROOVYDOC): true])
doRunAndTestAntlr4('core/Groovydoc_01x.groovy', compilerConfiguration)
+ doRunAndTestAntlr4('core/Groovydoc_02x.groovy', compilerConfiguration)
}
@Test
(groovy) 29/34: groovydoc theming
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit e2731a502c0a159d7776b2485cf4d4812bc51322
Author: Paul King <pa...@asert.com.au>
AuthorDate: Tue Apr 21 12:57:27 2026 +1000
groovydoc theming
---
.../java/org/codehaus/groovy/ant/Groovydoc.java | 34 ++++++
.../codehaus/groovy/tools/groovydoc/Main.groovy | 10 ++
.../groovy/tools/groovydoc/Main.properties | 2 +
.../gstringTemplates/classLevel/classDocName.html | 7 ++
.../packageLevel/package-summary.html | 9 +-
.../packageLevel/package-tree.html | 9 +-
.../topLevel/overview-summary.html | 9 +-
.../gstringTemplates/topLevel/overview-tree.html | 9 +-
.../gstringTemplates/topLevel/stylesheet.css | 111 +++++++++++++----
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 134 +++++++++++++++++++++
10 files changed, 309 insertions(+), 25 deletions(-)
diff --git a/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java b/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java
index 58d5b84841..caa165c600 100644
--- a/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java
+++ b/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java
@@ -72,6 +72,7 @@ public class Groovydoc extends Task {
private Boolean noDeprecatedList;
private Boolean noHelp;
private String syntaxHighlighter;
+ private String theme;
private String javaVersion;
private final List<DirSet> packageSets;
private final List<String> sourceFilesToDoc;
@@ -107,6 +108,7 @@ public class Groovydoc extends Task {
noDeprecatedList = false;
noHelp = false;
syntaxHighlighter = "none";
+ theme = "auto";
}
/**
@@ -214,6 +216,20 @@ public class Groovydoc extends Task {
this.syntaxHighlighter = syntaxHighlighter;
}
+ /**
+ * GROOVY-11947: theme lock mode for the generated docs.
+ * <ul>
+ * <li>{@code "auto"} (default) — emit a {@code prefers-color-scheme}
+ * media query so each reader sees their OS preference.</li>
+ * <li>{@code "light"} — lock the palette to light regardless of OS.</li>
+ * <li>{@code "dark"} — lock the palette to dark regardless of OS.</li>
+ * </ul>
+ * Any other value is treated as {@code "auto"}.
+ */
+ public void setTheme(String theme) {
+ this.theme = theme;
+ }
+
/**
* If set to false, Scripts will not be processed.
* Defaults to true.
@@ -258,6 +274,23 @@ public class Groovydoc extends Task {
}
}
+ /**
+ * Set the packages to exclude from documentation. Mirrors the CLI
+ * {@code -exclude} option; the Ant task already honoured
+ * {@code excludePackageNames} internally when generating but lacked
+ * the public setter.
+ *
+ * @param packages a comma-separated (or colon-separated, to match
+ * the CLI form) list of package specs, possibly
+ * wildcarded.
+ */
+ public void setExcludePackageNames(String packages) {
+ StringTokenizer tok = new StringTokenizer(packages, ",:");
+ while (tok.hasMoreTokens()) {
+ excludePackageNames.add(tok.nextToken());
+ }
+ }
+
public void setUse(boolean b) {
//ignore as 'use external file' irrelevant with groovydoc :-)
}
@@ -549,6 +582,7 @@ public class Groovydoc extends Task {
properties.setProperty("noDeprecatedList", noDeprecatedList.toString());
properties.setProperty("noHelp", noHelp.toString());
properties.setProperty("syntaxHighlighter", syntaxHighlighter != null ? syntaxHighlighter : "none");
+ properties.setProperty("theme", theme != null ? theme : "auto");
// GROOVY-11941: expose additional stylesheet basenames to templates.
StringBuilder extras = new StringBuilder();
for (int k = 0; k < addStylesheetFiles.size(); k++) {
diff --git a/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy b/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy
index 7070ad1937..8a6ac77878 100644
--- a/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy
+++ b/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy
@@ -50,6 +50,7 @@ class Main {
private static Boolean noDeprecatedList
private static Boolean noHelp
private static String syntaxHighlighter
+ private static String theme
private static Boolean privateScope
private static Boolean packageScope
private static Boolean publicScope
@@ -87,6 +88,7 @@ class Main {
cli.nodeprecatedlist(messages['cli.option.nodeprecatedlist.description'])
cli.nohelp(messages['cli.option.nohelp.description'])
cli.syntaxHighlighter(args: 1, argName: 'name', messages['cli.option.syntaxHighlighter.description'])
+ cli.theme(args: 1, argName: 'mode', messages['cli.option.theme.description'])
cli.overview(args:1, argName: 'file', messages['cli.option.overview.description'])
cli.public(messages['cli.option.public.description'])
cli.protected(messages['cli.option.protected.description'])
@@ -157,6 +159,12 @@ class Main {
noDeprecatedList = Boolean.valueOf(options.nodeprecatedlist) ?: false
noHelp = Boolean.valueOf(options.nohelp) ?: false
syntaxHighlighter = options.syntaxHighlighter ?: 'none'
+ theme = options.theme ?: 'auto'
+ if (!(theme in ['auto', 'light', 'dark'])) {
+ System.err.println "groovydoc: Error - -theme must be one of auto, light, dark (was: $theme)."
+ cli.usage()
+ System.exit(1)
+ }
showInternal = Boolean.valueOf(options.showInternal) ?: false
packageScope = Boolean.valueOf(options.package) ?: false
privateScope = Boolean.valueOf(options.private) ?: false
@@ -248,6 +256,8 @@ class Main {
properties.put("noHelp", noHelp.toString())
// GROOVY-11938 stage 4: client-side syntax highlighter ("prism"|"none").
properties.put("syntaxHighlighter", syntaxHighlighter)
+ // GROOVY-11947: generator-level theme lock ("auto"|"light"|"dark").
+ properties.put("theme", theme)
properties.put("overviewFile", overviewFile?.absolutePath ?: "")
String phaseOverride = SystemUtil.getSystemPropertySafe("groovydoc.phase.override")
if (phaseOverride) properties.put("phaseOverride", phaseOverride)
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/Main.properties b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/Main.properties
index 69dce4b90a..88e678df7d 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/Main.properties
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/Main.properties
@@ -68,6 +68,8 @@ cli.option.nohelp.description=Don't generate the help page
cli.option.syntaxHighlighter.description=Client-side syntax highlighter for snippets and Markdown fenced code blocks: "prism" (bundled) or "none" (default).
+cli.option.theme.description=Theme mode: "auto" (default, follow OS prefers-color-scheme), "light" (force light always), or "dark" (force dark always).
+
cli.option.public.description=Show only public classes and members
cli.option.protected.description=Show protected/public classes and members (default)
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.html
index 954f2dc2c4..f1c844dc03 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.html
@@ -97,7 +97,14 @@
<link rel="stylesheet" type="text/css" href="${classDoc.relativeRootPath}${__ss.trim()}">
<% } %>
<% if (props.syntaxHighlighter == 'prism') { def __p = "${classDoc.relativeRootPath}" %>
+ <% if (props.theme == 'dark') { %>
+ <link rel="stylesheet" type="text/css" href="${__p}prism-dark.min.css">
+ <% } else if (props.theme == 'light') { %>
<link rel="stylesheet" type="text/css" href="${__p}prism.min.css">
+ <% } else { %>
+ <link rel="stylesheet" type="text/css" href="${__p}prism.min.css" media="(prefers-color-scheme: light)">
+ <link rel="stylesheet" type="text/css" href="${__p}prism-dark.min.css" media="(prefers-color-scheme: dark)">
+ <% } %>
<script src="${__p}prism.js"></script>
<script src="${__p}prism-groovy.min.js"></script>
<script src="${__p}prism-java.min.js"></script>
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html
index 79996ecf60..1a6a17d852 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html
@@ -55,7 +55,14 @@ function windowTitle()
</noscript>
<% if (props.syntaxHighlighter == 'prism') { def __p = '${packageDoc.relativeRootPath}' %>
-<link rel="stylesheet" type="text/css" href="${__p}prism.min.css">
+ <% if (props.theme == 'dark') { %>
+ <link rel="stylesheet" type="text/css" href="${__p}prism-dark.min.css">
+ <% } else if (props.theme == 'light') { %>
+ <link rel="stylesheet" type="text/css" href="${__p}prism.min.css">
+ <% } else { %>
+ <link rel="stylesheet" type="text/css" href="${__p}prism.min.css" media="(prefers-color-scheme: light)">
+ <link rel="stylesheet" type="text/css" href="${__p}prism-dark.min.css" media="(prefers-color-scheme: dark)">
+ <% } %>
<script src="${__p}prism.js"></script>
<script src="${__p}prism-groovy.min.js"></script>
<script src="${__p}prism-java.min.js"></script>
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-tree.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-tree.html
index cc82eb7e45..b3aead4016 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-tree.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-tree.html
@@ -32,7 +32,14 @@
<link href="${packageDoc.relativeRootPath}groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="${packageDoc.relativeRootPath}groovy.ico" type="image/x-icon" rel="icon">
<% if (props.syntaxHighlighter == 'prism') { def __p = '${packageDoc.relativeRootPath}' %>
-<link rel="stylesheet" type="text/css" href="${__p}prism.min.css">
+ <% if (props.theme == 'dark') { %>
+ <link rel="stylesheet" type="text/css" href="${__p}prism-dark.min.css">
+ <% } else if (props.theme == 'light') { %>
+ <link rel="stylesheet" type="text/css" href="${__p}prism.min.css">
+ <% } else { %>
+ <link rel="stylesheet" type="text/css" href="${__p}prism.min.css" media="(prefers-color-scheme: light)">
+ <link rel="stylesheet" type="text/css" href="${__p}prism-dark.min.css" media="(prefers-color-scheme: dark)">
+ <% } %>
<script src="${__p}prism.js"></script>
<script src="${__p}prism-groovy.min.js"></script>
<script src="${__p}prism-java.min.js"></script>
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary.html
index 253cd12feb..201cfcf48f 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary.html
@@ -32,7 +32,14 @@
<link href="groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="groovy.ico" type="image/x-icon" rel="icon">
<% if (props.syntaxHighlighter == 'prism') { def __p = '' %>
-<link rel="stylesheet" type="text/css" href="${__p}prism.min.css">
+ <% if (props.theme == 'dark') { %>
+ <link rel="stylesheet" type="text/css" href="${__p}prism-dark.min.css">
+ <% } else if (props.theme == 'light') { %>
+ <link rel="stylesheet" type="text/css" href="${__p}prism.min.css">
+ <% } else { %>
+ <link rel="stylesheet" type="text/css" href="${__p}prism.min.css" media="(prefers-color-scheme: light)">
+ <link rel="stylesheet" type="text/css" href="${__p}prism-dark.min.css" media="(prefers-color-scheme: dark)">
+ <% } %>
<script src="${__p}prism.js"></script>
<script src="${__p}prism-groovy.min.js"></script>
<script src="${__p}prism-java.min.js"></script>
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-tree.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-tree.html
index 212f8ba893..528cb2c404 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-tree.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-tree.html
@@ -32,7 +32,14 @@
<link href="groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="groovy.ico" type="image/x-icon" rel="icon">
<% if (props.syntaxHighlighter == 'prism') { def __p = '' %>
-<link rel="stylesheet" type="text/css" href="${__p}prism.min.css">
+ <% if (props.theme == 'dark') { %>
+ <link rel="stylesheet" type="text/css" href="${__p}prism-dark.min.css">
+ <% } else if (props.theme == 'light') { %>
+ <link rel="stylesheet" type="text/css" href="${__p}prism.min.css">
+ <% } else { %>
+ <link rel="stylesheet" type="text/css" href="${__p}prism.min.css" media="(prefers-color-scheme: light)">
+ <link rel="stylesheet" type="text/css" href="${__p}prism-dark.min.css" media="(prefers-color-scheme: dark)">
+ <% } %>
<script src="${__p}prism.js"></script>
<script src="${__p}prism-groovy.min.js"></script>
<script src="${__p}prism-java.min.js"></script>
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/stylesheet.css b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/stylesheet.css
index 59e73c7913..8fdd3b3ba5 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/stylesheet.css
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/stylesheet.css
@@ -1,5 +1,48 @@
@charset "${props.charset}";
+/* GROOVY-11946: semantic CSS tokens for theming. Light values match the
+ historical palette (so OS-light users see no visible change); dark
+ overrides live in the @media (prefers-color-scheme: dark) block at
+ the bottom of this file. Author stylesheets supplied via
+ -addStylesheet can reference these same tokens to stay theme-aware.
+ GROOVY-11947: -theme=light|dark locks the palette; -theme=auto (default)
+ keeps the media-query-driven OS preference behaviour. */
+<% if (props.theme == 'dark') { %>
+:root {
+ --fg: #e4e4e4;
+ --bg-outer: #1a1a1a;
+ --bg: #242424;
+ --bg-alt: #2a2a2a;
+ --bg-panel: #2f2f2f;
+ --heading-fg: #f0f0f0;
+ --link: #7cc7dc;
+ --muted-fg: #808080;
+ --muted-fg-2: #a0a0a0;
+ --border: #3a3a3a;
+ --caption-bg: #e05a1a;
+ --caption-fg: #fff;
+ --mark-bg: #5a4e1c;
+ --mark-fg: #fff1a8;
+}
+<% } else { %>
+:root {
+ --fg: #343437;
+ --bg-outer: #ededed;
+ --bg: #FFF;
+ --bg-alt: #f9f9f9;
+ --bg-panel: #f2f2f2;
+ --heading-fg: #333;
+ --link: #4290ad;
+ --muted-fg: #BBB;
+ --muted-fg-2: #999;
+ --border: #EEE;
+ --caption-bg: #db4800;
+ --caption-fg: #fff;
+ --mark-bg: #ff0;
+ --mark-fg: #000;
+}
+<% } %>
+
/*! normalize.css v2.1.0 | MIT License | git.io/normalize */
article, aside, details, figcaption, figure, footer, header, hgroup, main, nav, section, summary {
display: block
@@ -60,8 +103,8 @@ hr {
}
mark {
- background: #ff0;
- color: #000
+ background: var(--mark-bg);
+ color: var(--mark-fg)
}
code, kbd, pre, samp {
@@ -2043,8 +2086,8 @@ input[type="submit"].btn-block, input[type="reset"].btn-block, input[type="butto
body, html {
font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
margin: 0;
- background: #ededed;
- color: #343437;
+ background: var(--bg-outer);
+ color: var(--fg);
line-height: 2em;
font-weight: 300;
font-size: .95em
@@ -2057,7 +2100,7 @@ h1 {
body.center {
padding: 0 30px;
- background: #FFF;
+ background: var(--bg);
font-size: 1em
}
@@ -2066,7 +2109,7 @@ ul li {
}
a {
- color: #4290ad;
+ color: var(--link);
text-decoration: none;
font-weight: normal
}
@@ -2081,7 +2124,7 @@ h1, h2, h3 {
}
.topNav, .bottomNav {
- background: #f2f2f2;
+ background: var(--bg-panel);
margin: 0 -30px;
margin-bottom: 20px
}
@@ -2116,8 +2159,8 @@ h1, h2, h3 {
}
.aboutLanguage {
- color: #BBB;
- background: white;
+ color: var(--muted-fg);
+ background: var(--bg);
text-align: center;
padding: 20px 0
}
@@ -2125,7 +2168,7 @@ h1, h2, h3 {
.subNav {
padding-bottom: 10px;
margin-bottom: 10px;
- border-bottom: 1px solid #EEE
+ border-bottom: 1px solid var(--border)
}
.subNav:before, .subNav:after {
@@ -2171,8 +2214,8 @@ table.overviewSummary caption, .contentContainer ul li table caption {
float: left;
padding: 0 10px;
margin-top: 10px;
- background: #db4800;
- color: white
+ background: var(--caption-bg);
+ color: var(--caption-fg)
}
table.overviewSummary tr th, .contentContainer ul li table tr th {
@@ -2186,11 +2229,11 @@ table.overviewSummary tr td, .contentContainer ul li table tr td {
vertical-align: top;
font-size: .9em;
padding: 5px 10px;
- border-top: 1px solid #EEE
+ border-top: 1px solid var(--border)
}
table.overviewSummary tbody > tr:nth-child(odd) > td, .contentContainer ul li table tbody > tr:nth-child(odd) > td {
- background-color: #f9f9f9
+ background-color: var(--bg-alt)
}
body.left {
@@ -2205,8 +2248,8 @@ body.left h1, body.left h2 {
margin: 0 10px;
padding: 3px 10px;
margin-top: 10px;
- background: #db4800;
- color: white;
+ background: var(--caption-bg);
+ color: var(--caption-fg);
line-height: 40px
}
@@ -2260,13 +2303,13 @@ body.left ul li a:hover {
.contentContainer hr {
border: 0 none;
- border-top: 1px solid #EEE;
+ border-top: 1px solid var(--border);
margin-top: 30px;
margin-botom: 0
}
ul.blockList ul.blockList, ul.blockList ul.blockListLast {
- border: 1px solid #EEE;
+ border: 1px solid var(--border);
margin: 20px 0;
padding: 0 20px
}
@@ -2276,10 +2319,10 @@ ul.blockList ul.blockList h4, ul.blockList ul.blockListLast h4, ul.blockList ul.
font-weight: bold;
line-height: 2em;
text-indent: 10px;
- border-bottom: 1px solid #EEE;
+ border-bottom: 1px solid var(--border);
margin: 0 -20px;
padding: 5px 0;
- background: #f2f2f2
+ background: var(--bg-panel)
}
ul.blockList ul.blockList li, ul.blockList ul.blockListLast li {
@@ -2303,4 +2346,30 @@ span.strong {
a span.strong {
font-weight: normal
-}
\ No newline at end of file
+}
+
+<% if (!(props.theme in ['light', 'dark'])) { %>
+/* GROOVY-11946: dark-mode palette. Triggered automatically by the OS /
+ browser reporting prefers-color-scheme: dark. Tokens only — no new
+ selectors — so the HTML structure is unchanged. The Groovy-orange
+ caption is kept brand-true but slightly warmed for a darker background.
+ Omitted when -theme=light|dark locks the palette at doc-gen time. */
+@media (prefers-color-scheme: dark) {
+ :root {
+ --fg: #e4e4e4;
+ --bg-outer: #1a1a1a;
+ --bg: #242424;
+ --bg-alt: #2a2a2a;
+ --bg-panel: #2f2f2f;
+ --heading-fg: #f0f0f0;
+ --link: #7cc7dc;
+ --muted-fg: #808080;
+ --muted-fg-2: #a0a0a0;
+ --border: #3a3a3a;
+ --caption-bg: #e05a1a;
+ --caption-fg: #fff;
+ --mark-bg: #5a4e1c;
+ --mark-fg: #fff1a8;
+ }
+}
+<% } %>
\ No newline at end of file
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index 9098e34e21..f9ca1804fd 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -638,6 +638,140 @@ public class GroovyDocToolTest extends GroovyTestCase {
page.contains("def farewell() { "Bye!" }"));
}
+ // GROOVY-11947: -theme=light locks the palette to light. The stylesheet
+ // should emit only the light :root values and NO prefers-color-scheme
+ // dark @media block. Prism templates link only the light theme.
+ public void testThemeLightLocksLightPaletteAndOmitsDarkMedia() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ Properties props = new Properties();
+ props.put("theme", "light");
+ props.put("syntaxHighlighter", "prism");
+ GroovyDocTool tool = makeHtmltool(new ArrayList<>(), null, props);
+ tool.add(List.of(base + "/DocumentedClass.groovy"));
+ MockOutputTool output = new MockOutputTool();
+ tool.renderToOutput(output, MOCK_DIR);
+
+ String stylesheet = output.getText(MOCK_DIR + "/stylesheet.css");
+ assertNotNull(stylesheet);
+ // Light-palette values only; no dark media block.
+ assertTrue("Light --fg expected in stylesheet",
+ stylesheet.contains("--fg: #343437"));
+ assertFalse("@media (prefers-color-scheme: dark) must NOT appear when theme=light",
+ stylesheet.contains("@media (prefers-color-scheme: dark) {"));
+
+ String classPage = output.getText(MOCK_DIR + "/" + base + "/DocumentedClass.html");
+ assertNotNull(classPage);
+ assertTrue("Prism light theme expected (no media attr) when theme=light:\n" + classPage,
+ classPage.matches("(?s).*href=\"[^\"]*prism\\.min\\.css\">.*"));
+ assertFalse("Prism dark theme must NOT be linked when theme=light",
+ classPage.contains("prism-dark.min.css"));
+ }
+
+ // GROOVY-11947: -theme=dark locks the palette to dark. The stylesheet
+ // :root gets dark values; no @media block. Prism links only the dark theme.
+ public void testThemeDarkLocksDarkPaletteAndOmitsMediaBlock() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ Properties props = new Properties();
+ props.put("theme", "dark");
+ props.put("syntaxHighlighter", "prism");
+ GroovyDocTool tool = makeHtmltool(new ArrayList<>(), null, props);
+ tool.add(List.of(base + "/DocumentedClass.groovy"));
+ MockOutputTool output = new MockOutputTool();
+ tool.renderToOutput(output, MOCK_DIR);
+
+ String stylesheet = output.getText(MOCK_DIR + "/stylesheet.css");
+ assertNotNull(stylesheet);
+ assertTrue("Dark --fg expected in stylesheet",
+ stylesheet.contains("--fg: #e4e4e4"));
+ assertFalse("Light --fg should NOT appear when theme=dark",
+ stylesheet.contains("--fg: #343437"));
+ assertFalse("@media (prefers-color-scheme: dark) must NOT appear when theme=dark",
+ stylesheet.contains("@media (prefers-color-scheme: dark) {"));
+
+ String classPage = output.getText(MOCK_DIR + "/" + base + "/DocumentedClass.html");
+ assertNotNull(classPage);
+ assertTrue("Prism dark theme expected (no media attr) when theme=dark:\n" + classPage,
+ classPage.matches("(?s).*href=\"[^\"]*prism-dark\\.min\\.css\">.*"));
+ // Light theme link must NOT appear — careful not to confuse with prism-dark.min.css
+ // which also contains 'prism.' — check for 'prism.min.css' with the expected href terminator.
+ assertFalse("Prism light theme must NOT be linked when theme=dark:\n" + classPage,
+ classPage.matches("(?s).*href=\"[^\"]*/prism\\.min\\.css[\"].*"));
+ }
+
+ // GROOVY-11947: -theme=auto (default) keeps the media-query-driven
+ // behaviour — both palettes and both Prism themes present with media.
+ public void testThemeAutoKeepsMediaQueryBehaviour() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ Properties props = new Properties();
+ props.put("theme", "auto");
+ props.put("syntaxHighlighter", "prism");
+ GroovyDocTool tool = makeHtmltool(new ArrayList<>(), null, props);
+ tool.add(List.of(base + "/DocumentedClass.groovy"));
+ MockOutputTool output = new MockOutputTool();
+ tool.renderToOutput(output, MOCK_DIR);
+
+ String stylesheet = output.getText(MOCK_DIR + "/stylesheet.css");
+ assertNotNull(stylesheet);
+ assertTrue(stylesheet.contains("--fg: #343437"));
+ assertTrue(stylesheet.contains("@media (prefers-color-scheme: dark) {"));
+
+ String classPage = output.getText(MOCK_DIR + "/" + base + "/DocumentedClass.html");
+ assertNotNull(classPage);
+ assertTrue(classPage.contains("prism.min.css\" media=\"(prefers-color-scheme: light)\""));
+ assertTrue(classPage.contains("prism-dark.min.css\" media=\"(prefers-color-scheme: dark)\""));
+ }
+
+ // GROOVY-11946: the stylesheet declares CSS custom properties on :root and
+ // a matching @media (prefers-color-scheme: dark) override. OS-light readers
+ // see no visual change; OS-dark readers get the dark palette automatically.
+ public void testStylesheetContainsCssVariablesAndDarkMediaBlock() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ htmlTool.add(List.of(base + "/DocumentedClass.groovy"));
+ MockOutputTool output = new MockOutputTool();
+ htmlTool.renderToOutput(output, MOCK_DIR);
+
+ String stylesheet = output.getText(MOCK_DIR + "/stylesheet.css");
+ assertNotNull("stylesheet.css expected in output", stylesheet);
+ // Semantic tokens live on :root and are referenced via var(--...).
+ assertTrue(":root block expected:\n" + stylesheet.substring(0, Math.min(stylesheet.length(), 600)),
+ stylesheet.contains(":root"));
+ assertTrue("--fg token expected:\n" + stylesheet.substring(0, Math.min(stylesheet.length(), 600)),
+ stylesheet.contains("--fg:"));
+ assertTrue("var(--fg) reference expected somewhere in stylesheet",
+ stylesheet.contains("var(--fg)"));
+ // Dark-mode media query with token overrides.
+ assertTrue("@media prefers-color-scheme: dark block expected in stylesheet",
+ stylesheet.contains("@media (prefers-color-scheme: dark) {"));
+ // Key tokens should be redefined inside the dark block — a reasonable
+ // assertion that at minimum --fg and --bg have dark-mode values.
+ int darkStart = stylesheet.indexOf("@media (prefers-color-scheme: dark)");
+ String darkBlock = stylesheet.substring(darkStart);
+ assertTrue("--fg override expected in dark block:\n" + darkBlock,
+ darkBlock.contains("--fg:"));
+ assertTrue("--bg override expected in dark block:\n" + darkBlock,
+ darkBlock.contains("--bg:"));
+ }
+
+ // GROOVY-11946: when syntax highlighting is on, both Prism themes should
+ // be linked with matching prefers-color-scheme media attributes so the
+ // browser auto-selects the appropriate one.
+ public void testPrismThemesHaveColorSchemeMediaAttributes() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ Properties props = new Properties();
+ props.put("syntaxHighlighter", "prism");
+ GroovyDocTool tool = makeHtmltool(new ArrayList<>(), null, props);
+ tool.add(List.of(base + "/DocumentedClass.groovy"));
+ MockOutputTool output = new MockOutputTool();
+ tool.renderToOutput(output, MOCK_DIR);
+
+ String classPage = output.getText(MOCK_DIR + "/" + base + "/DocumentedClass.html");
+ assertNotNull(classPage);
+ assertTrue("Light Prism theme should carry prefers-color-scheme:light media:\n" + classPage,
+ classPage.contains("prism.min.css\" media=\"(prefers-color-scheme: light)\""));
+ assertTrue("Dark Prism theme should be linked with prefers-color-scheme:dark media:\n" + classPage,
+ classPage.contains("prism-dark.min.css\" media=\"(prefers-color-scheme: dark)\""));
+ }
+
// GROOVY-11938 stage 4: opt-in client-side syntax highlighting via Prism.
// When -syntaxHighlighter=prism is passed, the head of each content page
// should include prism.min.css and the bundled language scripts; when
(groovy) 09/34: GROOVY-6016: {@value} inline tag
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 60264c025509ebcdfd074b31d75c87ea8311af2c
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Apr 20 17:54:52 2026 +1000
GROOVY-6016: {@value} inline tag
---
.../org/apache/groovy/antlr/GroovydocVisitor.java | 22 +++++
.../groovy/tools/groovydoc/TagRenderer.java | 108 ++++++++++++++++++---
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 20 ++++
.../groovydoc/testfiles/ClassWithValueTag.groovy | 32 ++++++
4 files changed, 170 insertions(+), 12 deletions(-)
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java b/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
index 435b146870..f24e4cf215 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
@@ -550,6 +550,15 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
processModifiers(fieldDoc, node, node.getModifiers());
processAnnotations(fieldDoc, node);
fieldDoc.setRawCommentText(getDocContent(node.getGroovydoc()));
+ // GROOVY-6016: record the source form of simple-constant initializers
+ // so {@value #FIELD} can resolve them at render time. Javadoc's
+ // convention is to re-quote strings/chars; ConstantExpression.getText()
+ // returns the raw value without quotes.
+ org.codehaus.groovy.ast.expr.Expression init = node.getInitialExpression();
+ if (init instanceof org.codehaus.groovy.ast.expr.ConstantExpression) {
+ Object value = ((org.codehaus.groovy.ast.expr.ConstantExpression) init).getValue();
+ fieldDoc.setConstantValueExpression(formatConstantValue(value));
+ }
if (node.isEnum()) {
currentClassDoc.addEnumConstant(fieldDoc);
} else {
@@ -584,4 +593,17 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
public Map<String, GroovyClassDoc> getGroovyClassDocs() {
return classDocs;
}
+
+ /**
+ * Format a compile-time constant value for {@code {@value}} rendering.
+ * Strings are wrapped in double quotes and characters in single quotes,
+ * matching Javadoc's behaviour. Null, numeric, and boolean values are
+ * emitted via {@code String.valueOf}.
+ */
+ private static String formatConstantValue(Object value) {
+ if (value == null) return "null";
+ if (value instanceof String) return "\"" + value + "\"";
+ if (value instanceof Character) return "'" + value + "'";
+ return String.valueOf(value);
+ }
}
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
index 61fa8ec61d..e687b81fa8 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
@@ -18,6 +18,7 @@
*/
package org.codehaus.groovy.tools.groovydoc;
+import org.codehaus.groovy.groovydoc.GroovyClassDoc;
import org.codehaus.groovy.groovydoc.GroovyRootDoc;
import java.util.ArrayList;
@@ -26,17 +27,39 @@ import java.util.List;
import java.util.Map;
/**
- * Single-pass tokenizer and renderer for Javadoc-style inline tags
- * ({@code {@link ...}}, {@code {@code ...}}, {@code {@literal ...}}) and
- * block tags ({@code @see}, {@code @param}, {@code @return}, etc.) in
- * groovydoc text. Replaces the earlier chain of regex-based passes in
- * {@link SimpleGroovyClassDoc#replaceTags} and provides a single extension
- * point for new tags (GROOVY-6016 {@code {@value}}, GROOVY-3782
- * {@code {@inheritDoc}}, GROOVY-11938 {@code {@snippet}}, GROOVY-11542
- * Markdown reference links).
+ * Single-pass tokenizer and renderer for Javadoc-style inline tags and
+ * block tags in groovydoc text. Replaces the earlier chain of regex-based
+ * passes in {@link SimpleGroovyClassDoc#replaceTags} and provides a single
+ * extension point for new tags.
*
- * <p>Output is intentionally byte-identical to the previous multi-pass
- * implementation so the refactor is invisible in rendered docs.</p>
+ * <p>Supported inline tags: {@code {@link ...}}, {@code {@see ...}},
+ * {@code {@code ...}}, {@code {@literal ...}} (class-level only),
+ * {@code {@interface ...}} (swallowed), {@code {@value #FIELD}} /
+ * {@code {@value pkg.Class#FIELD}} (GROOVY-6016).
+ *
+ * <p>Supported block tags: {@code @see}, {@code @param}, {@code @return},
+ * {@code @throws} / {@code @exception}, {@code @since}, {@code @author},
+ * {@code @version}, {@code @default}, plus synthesised {@code typeparam}
+ * (from {@code @param <T>}). Unknown block tags fall through to a generic
+ * {@code <DL>} rendering.
+ *
+ * <h2>Known limitations / pending work</h2>
+ * <ul>
+ * <li>Bare {@code {@value}} (no body, referencing the current field's own
+ * constant value) is not yet supported. It requires threading the
+ * current member through {@code TagRenderer}; the tag currently falls
+ * through to verbatim emission. {@code {@value #FIELD}} and
+ * {@code {@value Class#FIELD}} both work.</li>
+ * <li>{@code {@inheritDoc}} — GROOVY-3782, pending.</li>
+ * <li>{@code {@snippet}} — GROOVY-11938, pending.</li>
+ * <li>JEP 467 Markdown reference links — GROOVY-11542, pending.</li>
+ * </ul>
+ *
+ * <p>Output is byte-for-byte compatible with the previous multi-pass
+ * implementation for inputs the old code handled; see the GROOVY-11939
+ * commit notes for the small set of semantic improvements introduced by
+ * the refactor (e.g. {@code {@linkplain X}} passed through verbatim
+ * instead of broken as a bogus block tag).
*/
final class TagRenderer {
@@ -196,6 +219,7 @@ final class TagRenderer {
case "see":
case "code":
case "interface":
+ case "value":
return true;
case "literal":
return cfg.literalEnabled;
@@ -226,9 +250,69 @@ final class TagRenderer {
case "code":
out.append(cfg.codeOpen).append(SimpleGroovyClassDoc.encodeAngleBrackets(body)).append(cfg.codeClose);
return;
+ case "value": {
+ // GROOVY-6016: resolve {@value #FIELD} or {@value Class#FIELD}
+ // to the field's source-form constant value. Bare {@value}
+ // (current field) is not supported here because we don't
+ // thread the current member through TagRenderer — fall back
+ // to emitting the tag verbatim in that case.
+ String resolved = resolveValueTag(body, rootDoc, classDoc);
+ if (resolved != null) {
+ out.append(SimpleGroovyClassDoc.encodeAngleBrackets(resolved));
+ return;
+ }
+ break; // unresolved — emit verbatim
+ }
+ }
+ // Unknown or unresolved inline tag — emit body verbatim (matches prior regex behaviour).
+ out.append('{').append('@').append(name);
+ if (!body.isEmpty()) out.append(' ').append(body);
+ out.append('}');
+ }
+
+ /**
+ * Resolve a {@code {@value}} tag body to the target field's source-form
+ * constant value, or {@code null} if the reference couldn't be resolved.
+ *
+ * <p>Body forms:
+ * <ul>
+ * <li>{@code #FIELD} — field {@code FIELD} in {@code classDoc}</li>
+ * <li>{@code Class#FIELD} / {@code pkg.Class#FIELD} — field in another class</li>
+ * <li>empty — not supported here (needs current-member context); returns {@code null}</li>
+ * </ul>
+ */
+ private static String resolveValueTag(String body, GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc) {
+ if (body == null || body.isEmpty()) return null;
+ String className;
+ String fieldName;
+ int hash = body.indexOf('#');
+ if (hash < 0) {
+ // Bare name — treat as same-class field ref (lenient).
+ className = null;
+ fieldName = body.trim();
+ } else {
+ className = body.substring(0, hash).trim();
+ fieldName = body.substring(hash + 1).trim();
+ }
+ if (fieldName.isEmpty()) return null;
+ SimpleGroovyClassDoc target = classDoc;
+ if (className != null && !className.isEmpty() && classDoc != null && rootDoc != null) {
+ String slashed = className.replace('.', '/');
+ GroovyClassDoc resolved = rootDoc.classNamed(classDoc, slashed);
+ if (resolved instanceof SimpleGroovyClassDoc) target = (SimpleGroovyClassDoc) resolved;
+ else return null;
+ }
+ if (target == null) return null;
+ for (org.codehaus.groovy.groovydoc.GroovyFieldDoc f : target.fields()) {
+ if (fieldName.equals(f.name())) return f.constantValueExpression();
+ }
+ for (org.codehaus.groovy.groovydoc.GroovyFieldDoc f : target.enumConstants()) {
+ if (fieldName.equals(f.name())) return f.constantValueExpression();
+ }
+ for (org.codehaus.groovy.groovydoc.GroovyFieldDoc f : target.properties()) {
+ if (fieldName.equals(f.name())) return f.constantValueExpression();
}
- // Unknown inline tag — emit body verbatim (matches prior regex pass not matching).
- out.append('{').append('@').append(name).append(' ').append(body).append('}');
+ return null;
}
// -------- block tags --------
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index c1f739c799..fe950e9033 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -131,6 +131,26 @@ public class GroovyDocToolTest extends GroovyTestCase {
doc.contains("https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Object.html"));
}
+ // GROOVY-6016: {@value #FIELD} inline tag resolves same-class constants.
+ public void testValueTagResolvesSameClassConstants() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ String klass = "ClassWithValueTag";
+ htmlTool.add(List.of(base + "/" + klass + ".groovy"));
+
+ MockOutputTool output = new MockOutputTool();
+ htmlTool.renderToOutput(output, MOCK_DIR);
+
+ String doc = output.getText(MOCK_DIR + "/" + base + "/" + klass + ".html");
+ assertNotNull("Expected a page for the value-tag class", doc);
+ assertTrue("Expected {@value #MAX} to render as 42 in:\n" + doc,
+ doc.contains("Max allowed: 42"));
+ // GREETING's source form is "hello" (quoted). Angle-bracket encoding
+ // doesn't affect the quotes — we expect to see " or the literal "hello"
+ // depending on encoding. At minimum, 'hello' should appear next to 'Greeting:'.
+ assertTrue("Expected {@value #GREETING} to render with 'hello' in:\n" + doc,
+ doc.contains("Greeting: \"hello\""));
+ }
+
// GROOVY-8025: annotations whose members are closure expressions must
// not NPE during groovydoc processing. The original bug was in the old
// SimpleGroovyClassDocAssembler — the refactor to GroovydocVisitor
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithValueTag.groovy b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithValueTag.groovy
new file mode 100644
index 0000000000..1ff003a831
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithValueTag.groovy
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.codehaus.groovy.tools.groovydoc.testfiles
+
+/**
+ * GROOVY-6016: demonstrates the {@code {@value}} inline tag referencing
+ * constants. The class doc below uses {@value #MAX} and {@value #GREETING}
+ * which should be substituted with the constants' source-form values.
+ *
+ * Max allowed: {@value #MAX}
+ * Greeting: {@value #GREETING}
+ */
+class ClassWithValueTag {
+ public static final int MAX = 42
+ public static final String GREETING = "hello"
+}
(groovy) 17/34: GROOVY-6016: {@value} inline tag (bare case)
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit a8ce39c627fa795938453a9e470c333c87af9567
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Apr 20 21:23:48 2026 +1000
GROOVY-6016: {@value} inline tag (bare case)
---
.../groovy/tools/groovydoc/TagRenderer.java | 23 +++++++++++++---------
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 14 +++++++++++++
.../groovydoc/testfiles/ClassWithValueTag.groovy | 8 ++++++++
3 files changed, 36 insertions(+), 9 deletions(-)
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
index add9fbb849..e1b1736cbe 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
@@ -19,6 +19,7 @@
package org.codehaus.groovy.tools.groovydoc;
import org.codehaus.groovy.groovydoc.GroovyClassDoc;
+import org.codehaus.groovy.groovydoc.GroovyFieldDoc;
import org.codehaus.groovy.groovydoc.GroovyMemberDoc;
import org.codehaus.groovy.groovydoc.GroovyMethodDoc;
import org.codehaus.groovy.groovydoc.GroovyParameter;
@@ -45,7 +46,8 @@ import java.util.regex.Pattern;
* <p>Supported inline tags: {@code {@link ...}}, {@code {@see ...}},
* {@code {@code ...}}, {@code {@literal ...}} (class-level only),
* {@code {@interface ...}} (swallowed), {@code {@value #FIELD}} /
- * {@code {@value pkg.Class#FIELD}} (GROOVY-6016),
+ * {@code {@value pkg.Class#FIELD}} / bare {@code {@value}} on a field's
+ * own comment (GROOVY-6016),
* {@code {@inheritDoc}} (GROOVY-3782 — inline form, full parent comment
* substituted), inline {@code {@snippet}} (GROOVY-11938 stage 1 — renders
* as {@code <pre><code>} with language/id/class attributes and
@@ -59,9 +61,6 @@ import java.util.regex.Pattern;
*
* <h2>Known limitations / pending work</h2>
* <ul>
- * <li>Bare {@code {@value}} (no body, referencing the current field's own
- * constant value) is not yet supported — see task #25. The forms
- * {@code {@value #FIELD}} and {@code {@value Class#FIELD}} both work.</li>
* <li>{@code {@snippet}} external form ({@code file="..."} /
* {@code region="..."} reading from a package's
* {@code snippet-files/} directory) not yet implemented — stage 2
@@ -521,8 +520,14 @@ final class TagRenderer {
return;
case "value": {
// GROOVY-6016: resolve {@value #FIELD} or {@value Class#FIELD}.
- // Bare {@value} (current field) is pending — see task #25.
- String resolved = resolveValueTag(body, rootDoc, classDoc);
+ // Bare {@value} resolves to the enclosing field's own value
+ // when the comment is attached to a field (Javadoc semantics).
+ String resolved;
+ if (body.isEmpty() && memberDoc instanceof GroovyFieldDoc) {
+ resolved = ((GroovyFieldDoc) memberDoc).constantValueExpression();
+ } else {
+ resolved = resolveValueTag(body, rootDoc, classDoc);
+ }
if (resolved != null) {
out.append(SimpleGroovyClassDoc.encodeAngleBrackets(resolved));
return;
@@ -646,13 +651,13 @@ final class TagRenderer {
else return null;
}
if (target == null) return null;
- for (org.codehaus.groovy.groovydoc.GroovyFieldDoc f : target.fields()) {
+ for (GroovyFieldDoc f : target.fields()) {
if (fieldName.equals(f.name())) return f.constantValueExpression();
}
- for (org.codehaus.groovy.groovydoc.GroovyFieldDoc f : target.enumConstants()) {
+ for (GroovyFieldDoc f : target.enumConstants()) {
if (fieldName.equals(f.name())) return f.constantValueExpression();
}
- for (org.codehaus.groovy.groovydoc.GroovyFieldDoc f : target.properties()) {
+ for (GroovyFieldDoc f : target.properties()) {
if (fieldName.equals(f.name())) return f.constantValueExpression();
}
return null;
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index caeb524434..8bdeecfc93 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -348,6 +348,20 @@ public class GroovyDocToolTest extends GroovyTestCase {
doc.contains("Sum: 42"));
assertTrue("Expected {@value #COMBINED} to fold string concat to \"hello\" in:\n" + doc,
doc.contains("Combined: \"hello\""));
+ // Bare {@value} on a field's own comment resolves to that field's value.
+ assertTrue("Expected bare {@value} on MAX to render as 42 in:\n" + doc,
+ doc.contains("Max allowed (bare: 42)"));
+ assertTrue("Expected bare {@value} on GREETING to render as \"hello\" in:\n" + doc,
+ doc.contains("Greeting (bare: \"hello\")"));
+ // PROBE: BIG_TIMEOUT = SMALL_TIMEOUT + MEDIUM_TIMEOUT
+ // Documented limits: {@value} only resolves when the initializer folds to
+ // a ConstantExpression at the phase groovydoc runs (CONVERSION by default).
+ // Same-class field references (VariableExpression) aren't resolved that
+ // early, and runtime method calls never fold. Both render verbatim.
+ assertTrue("BIG_TIMEOUT: cross-field arithmetic should stay verbatim in:\n" + doc,
+ doc.contains("Default: {@value}."));
+ assertTrue("FOUR: method-call initializer should stay verbatim in:\n" + doc,
+ doc.contains("Four is: {@value}."));
}
// GROOVY-8025: annotations whose members are closure expressions must
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithValueTag.groovy b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithValueTag.groovy
index a365527ae3..46c243c84e 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithValueTag.groovy
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithValueTag.groovy
@@ -30,8 +30,16 @@ package org.codehaus.groovy.tools.groovydoc.testfiles
* Combined: {@value #COMBINED}
*/
class ClassWithValueTag {
+ /** Max allowed (bare: {@value}). */
public static final int MAX = 42
+ /** Greeting (bare: {@value}). */
public static final String GREETING = "hello"
public static final int SUM = 40 + 2
public static final String COMBINED = "hel" + "lo"
+ public static final int SMALL_TIMEOUT = 1000
+ public static final int MEDIUM_TIMEOUT = 3000
+ /** Big timeout in ms. Default: {@value}. */
+ public static final int BIG_TIMEOUT = SMALL_TIMEOUT + MEDIUM_TIMEOUT
+ /** Four is: {@value}. */
+ public static final int FOUR = 'four'.size()
}
(groovy) 25/34: GROOVY-11938: {@snippet} per JEP 413 (markup comments: highlight/replace/link/region)
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 7971da0b2b6509ba1050205ea3ad7333e98d8054
Author: Paul King <pa...@asert.com.au>
AuthorDate: Tue Apr 21 06:32:08 2026 +1000
GROOVY-11938: {@snippet} per JEP 413 (markup comments: highlight/replace/link/region)
---
.../groovy/tools/groovydoc/TagRenderer.java | 278 ++++++++++++++++++++-
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 71 ++++++
.../testfiles/ClassWithSnippetMarkup.groovy | 44 ++++
3 files changed, 391 insertions(+), 2 deletions(-)
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
index aba098dccf..d4f9ea023d 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
@@ -35,7 +35,9 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import java.util.regex.PatternSyntaxException;
/**
* Single-pass tokenizer and renderer for Javadoc-style inline tags and
@@ -245,7 +247,7 @@ final class TagRenderer {
// before an optional `:`, then a brace-balanced body that may contain
// source code with its own `{`/`}`. Needs its own parser.
if ("snippet".equals(name)) {
- return renderSnippetAt(text, start, nameEnd, out, rootDoc, classDoc);
+ return renderSnippetAt(text, start, nameEnd, out, links, relPath, rootDoc, classDoc);
}
int bodyStart = skipWhitespace(text, nameEnd);
// Match the previous regex's laxness: body extends to the first '}'.
@@ -280,6 +282,7 @@ final class TagRenderer {
* or 0 if the tag is malformed.
*/
private static int renderSnippetAt(String text, int start, int nameEnd, StringBuilder out,
+ List<LinkArgument> links, String relPath,
GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc) {
int n = text.length();
int i = skipWhitespace(text, nameEnd);
@@ -378,11 +381,17 @@ final class TagRenderer {
String combined = (langClass.isEmpty() ? "" : "language-" + langClass)
+ (extraClass.isEmpty() ? "" : (langClass.isEmpty() ? extraClass : " " + extraClass));
String dedented = dedent(body);
+ // GROOVY-11938 stage 3: process JEP 413 markup comments (// @highlight,
+ // // @replace, // @link) inside the snippet body. Markup-comment lines
+ // are stripped from the rendered output; their directives annotate the
+ // target line with bold/italic/highlight wrappers, inline replacements,
+ // or hyperlinks.
+ String processed = processSnippetMarkup(dedented, links, relPath, rootDoc, classDoc);
out.append("<pre><code");
if (!combined.isEmpty()) out.append(" class=\"").append(combined).append('"');
String id = attrs.get("id");
if (id != null && !id.isEmpty()) out.append(" id=\"").append(id).append('"');
- out.append('>').append(SimpleGroovyClassDoc.encodeAngleBrackets(dedented)).append("</code></pre>");
+ out.append('>').append(processed).append("</code></pre>");
return endPos - start;
}
@@ -445,6 +454,271 @@ final class TagRenderer {
return sb.toString();
}
+ /**
+ * GROOVY-11938 stage 3: JEP 413 markup-comment processor. Walks the snippet
+ * body line-by-line looking for {@code // @highlight}, {@code // @replace},
+ * and {@code // @link} directives. Directive comments are stripped from
+ * the output. Each directive targets the same line if written after code,
+ * or the next non-directive line if written standalone.
+ *
+ * <p>Directive forms accepted:
+ * <ul>
+ * <li>{@code @highlight [substring="..."|regex="..."] [type="bold|italic|highlighted"]}
+ * — wraps matching text in {@code <b>}/{@code <i>}/{@code <mark>}.
+ * Default type is {@code bold}.</li>
+ * <li>{@code @replace [substring="..."|regex="..."] replacement="..."}
+ * — substitutes matching text.</li>
+ * <li>{@code @link [substring="..."|regex="..."] target="Class[#member]"}
+ * — resolves {@code target} via the existing {@code {@link}} machinery
+ * and wraps matching text in an {@code <a href="...">} anchor.</li>
+ * </ul>
+ *
+ * <p>Out of scope in this pass: region-scoped variants
+ * ({@code region="name"}), which are a natural follow-up layered on top of
+ * the existing external-file region machinery.
+ */
+ private static String processSnippetMarkup(String body, List<LinkArgument> links, String relPath,
+ GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc) {
+ String[] lines = body.split("\n", -1);
+ List<Directive> pending = new ArrayList<>();
+ // GROOVY-11938 stage 3 region support: directives that carry a
+ // `region="name"` attribute activate at their own line and remain in
+ // effect until the matching `// @end` marker (or end of snippet).
+ List<Directive> regionActive = new ArrayList<>();
+ StringBuilder out = new StringBuilder();
+ boolean first = true;
+ for (String line : lines) {
+ // Region markers `// @start region="name"` / `// @end [region="name"]`
+ // are stripped from the output regardless of any directive state.
+ if (isRegionStart(line) != null) continue;
+ String endRegion = isRegionEnd(line);
+ if (endRegion != null) {
+ deactivateRegion(regionActive, endRegion);
+ continue;
+ }
+ int commentIdx = findMarkupCommentStart(line);
+ Directive parsed = null;
+ if (commentIdx >= 0) {
+ String commentText = line.substring(commentIdx + 2).trim();
+ parsed = parseDirective(commentText);
+ }
+ if (parsed != null) {
+ String region = parsed.attrs.get("region");
+ String before = line.substring(0, commentIdx);
+ if (region != null && !region.isEmpty()) {
+ // Region-scoped directive — activate, drop this line.
+ regionActive.add(parsed);
+ continue;
+ }
+ if (before.trim().isEmpty()) {
+ // Standalone directive — queue for next code line, drop this line.
+ pending.add(parsed);
+ continue;
+ } else {
+ // EOL directive — apply to the code portion only (trailing
+ // whitespace trimmed off), drop the directive comment.
+ String code = before.replaceFirst("\\s+$", "");
+ List<Directive> effective = new ArrayList<>(regionActive);
+ effective.add(parsed);
+ String rendered = applyDirectives(code, effective, links, relPath, rootDoc, classDoc);
+ if (!first) out.append('\n');
+ out.append(rendered);
+ first = false;
+ continue;
+ }
+ }
+ // Normal line — apply active region directives plus any queued
+ // standalone directives (latter only consumed once).
+ List<Directive> effective = new ArrayList<>(regionActive);
+ effective.addAll(pending);
+ String rendered = applyDirectives(line, effective, links, relPath, rootDoc, classDoc);
+ pending.clear();
+ if (!first) out.append('\n');
+ out.append(rendered);
+ first = false;
+ }
+ return out.toString();
+ }
+
+ /** Return the region name if the line is a `// @start region="name"` marker, else {@code null}. */
+ private static String isRegionStart(String line) {
+ Matcher m = Pattern.compile("^\\s*//\\s*@start\\b([^\\n]*)").matcher(line);
+ if (!m.find()) return null;
+ Matcher r = Pattern.compile("region\\s*=\\s*(['\"]?)([^'\"\\s]+)\\1").matcher(m.group(1));
+ return r.find() ? r.group(2) : "";
+ }
+
+ /** Return the region name if the line is a `// @end [region="name"]` marker, empty string for an unnamed `// @end`, or {@code null} otherwise. */
+ private static String isRegionEnd(String line) {
+ Matcher m = Pattern.compile("^\\s*//\\s*@end\\b([^\\n]*)").matcher(line);
+ if (!m.find()) return null;
+ Matcher r = Pattern.compile("region\\s*=\\s*(['\"]?)([^'\"\\s]+)\\1").matcher(m.group(1));
+ return r.find() ? r.group(2) : "";
+ }
+
+ /** Remove directives from {@code regionActive} that match the given end-region name. An unnamed {@code // @end} deactivates every region-scoped directive. */
+ private static void deactivateRegion(List<Directive> regionActive, String endRegion) {
+ if (endRegion.isEmpty()) { regionActive.clear(); return; }
+ regionActive.removeIf(d -> endRegion.equals(d.attrs.get("region")));
+ }
+
+ /** Scan a line for the start of a recognised markup comment ({@code //} + optional space + {@code @highlight}/{@code @replace}/{@code @link}); returns the offset of the {@code //} or {@code -1}. */
+ private static int findMarkupCommentStart(String line) {
+ int i = 0, n = line.length();
+ while (i <= n - 2) {
+ if (line.charAt(i) == '/' && line.charAt(i + 1) == '/') {
+ int j = i + 2;
+ while (j < n && (line.charAt(j) == ' ' || line.charAt(j) == '\t')) j++;
+ if (j < n && line.charAt(j) == '@') {
+ int k = j + 1;
+ while (k < n && Character.isLetterOrDigit(line.charAt(k))) k++;
+ String name = line.substring(j + 1, k);
+ if ("highlight".equals(name) || "replace".equals(name) || "link".equals(name)) {
+ return i;
+ }
+ }
+ }
+ i++;
+ }
+ return -1;
+ }
+
+ /** Parsed markup directive with name + attributes. */
+ private static final class Directive {
+ final String name;
+ final Map<String, String> attrs;
+ Directive(String name, Map<String, String> attrs) { this.name = name; this.attrs = attrs; }
+ }
+
+ /** Parse a string of the form {@code @name attr1="v1" attr2=v2} into a {@link Directive}. Returns {@code null} on unrecognised names or malformed input. */
+ private static Directive parseDirective(String s) {
+ if (s == null || !s.startsWith("@")) return null;
+ int i = 1, n = s.length();
+ while (i < n && Character.isLetterOrDigit(s.charAt(i))) i++;
+ String name = s.substring(1, i);
+ if (!"highlight".equals(name) && !"replace".equals(name) && !"link".equals(name)) return null;
+ Map<String, String> attrs = new LinkedHashMap<>();
+ while (i < n) {
+ while (i < n && Character.isWhitespace(s.charAt(i))) i++;
+ if (i >= n) break;
+ int nameS = i;
+ while (i < n && (Character.isLetterOrDigit(s.charAt(i)) || s.charAt(i) == '_')) i++;
+ String attrName = s.substring(nameS, i);
+ if (attrName.isEmpty()) break;
+ while (i < n && Character.isWhitespace(s.charAt(i))) i++;
+ String val = "";
+ if (i < n && s.charAt(i) == '=') {
+ i++;
+ while (i < n && Character.isWhitespace(s.charAt(i))) i++;
+ if (i < n && (s.charAt(i) == '"' || s.charAt(i) == '\'')) {
+ char q = s.charAt(i);
+ int close = s.indexOf(q, i + 1);
+ if (close < 0) return null;
+ val = s.substring(i + 1, close);
+ i = close + 1;
+ } else {
+ int valS = i;
+ while (i < n && !Character.isWhitespace(s.charAt(i))) i++;
+ val = s.substring(valS, i);
+ }
+ }
+ attrs.put(attrName, val);
+ }
+ return new Directive(name, attrs);
+ }
+
+ /** Apply a list of directives to a single line, HTML-escaping untouched content. */
+ private static String applyDirectives(String line, List<Directive> directives,
+ List<LinkArgument> links, String relPath,
+ GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc) {
+ String escaped = SimpleGroovyClassDoc.encodeAngleBrackets(line);
+ if (directives.isEmpty()) return escaped;
+ for (Directive d : directives) {
+ escaped = applyDirective(escaped, d, links, relPath, rootDoc, classDoc);
+ }
+ return escaped;
+ }
+
+ /** Apply one directive to an already HTML-escaped line. */
+ private static String applyDirective(String escaped, Directive d,
+ List<LinkArgument> links, String relPath,
+ GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc) {
+ Pattern pat = buildMatchPattern(d);
+ if (pat == null) return escaped; // no match clause — nothing to do
+ Matcher m = pat.matcher(escaped);
+ StringBuilder sb = new StringBuilder();
+ int last = 0;
+ while (m.find()) {
+ sb.append(escaped, last, m.start());
+ String match = m.group();
+ String wrapped = wrapForDirective(match, d, links, relPath, rootDoc, classDoc);
+ sb.append(wrapped);
+ last = m.end();
+ }
+ sb.append(escaped, last, escaped.length());
+ return sb.toString();
+ }
+
+ /**
+ * Build a regex matching the directive's {@code substring} or {@code regex}
+ * attribute, run against the already-escaped line text. Returns {@code null}
+ * when neither attribute is present.
+ */
+ private static Pattern buildMatchPattern(Directive d) {
+ String substring = d.attrs.get("substring");
+ String regex = d.attrs.get("regex");
+ if (substring != null && !substring.isEmpty()) {
+ // Escape the user's literal substring with the same angle-bracket
+ // encoder applied to the line, then quote for regex.
+ String escapedSub = SimpleGroovyClassDoc.encodeAngleBrackets(substring);
+ return Pattern.compile(Pattern.quote(escapedSub));
+ }
+ if (regex != null && !regex.isEmpty()) {
+ try {
+ return Pattern.compile(regex);
+ } catch (PatternSyntaxException e) {
+ return null;
+ }
+ }
+ return null;
+ }
+
+ /** Produce the HTML wrapping that a directive applies to one match. */
+ private static String wrapForDirective(String match, Directive d,
+ List<LinkArgument> links, String relPath,
+ GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc) {
+ switch (d.name) {
+ case "highlight": {
+ String type = d.attrs.getOrDefault("type", "bold");
+ switch (type) {
+ case "italic": return "<i>" + match + "</i>";
+ case "highlighted": return "<mark>" + match + "</mark>";
+ case "bold":
+ default: return "<b>" + match + "</b>";
+ }
+ }
+ case "replace": {
+ String replacement = d.attrs.getOrDefault("replacement", "");
+ return SimpleGroovyClassDoc.encodeAngleBrackets(replacement);
+ }
+ case "link": {
+ String target = d.attrs.getOrDefault("target", "");
+ if (target.isEmpty()) return match;
+ String url = SimpleGroovyClassDoc.getDocUrl(target, false, links, relPath, rootDoc, classDoc);
+ // getDocUrl returns HTML like `<a href='...' title='...'>text</a>` —
+ // pull just the href and wrap the match in our own anchor so the
+ // visible text remains the code's own identifier.
+ Matcher hrefM = Pattern.compile("href='([^']+)'").matcher(url);
+ if (hrefM.find()) {
+ return "<a href=\"" + hrefM.group(1) + "\">" + match + "</a>";
+ }
+ return match;
+ }
+ default:
+ return match;
+ }
+ }
+
/**
* Strip leading blank lines from a snippet body and remove the common
* indentation (smallest non-empty leading-whitespace prefix) — matches
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index 739540a40c..17f17296bb 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -495,6 +495,77 @@ public class GroovyDocToolTest extends GroovyTestCase {
page.contains("the doubled value"));
}
+ // GROOVY-11938 stage 3: {@snippet} markup comments. Recognises three
+ // directives inside a snippet body — @highlight, @replace, @link — in
+ // either EOL (after code) or standalone-line (applies to next line) form.
+ // Markup-comment lines are stripped from the output.
+ public void testSnippetMarkupDirectives() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ htmlTool.add(List.of(base + "/ClassWithSnippetMarkup.groovy",
+ base + "/ScriptWithSiblingClassLinks.groovy"));
+ MockOutputTool output = new MockOutputTool();
+ htmlTool.renderToOutput(output, MOCK_DIR);
+
+ String page = output.getText(MOCK_DIR + "/" + base + "/ClassWithSnippetMarkup.html");
+ assertNotNull(page);
+ int snippetIdx = page.indexOf("<pre><code class=\"language-groovy\">");
+ assertTrue("Snippet block expected in:\n" + page, snippetIdx >= 0);
+ int snippetEnd = page.indexOf("</code></pre>", snippetIdx);
+ String snippet = page.substring(snippetIdx, snippetEnd + "</code></pre>".length());
+
+ // @highlight: "greet" wrapped in <b>.
+ assertTrue("@highlight bold expected around `greet` in:\n" + snippet,
+ snippet.contains("<b>greet</b>"));
+ // @replace: "TODO: fill this in" string substituted with replacement text.
+ assertFalse("Replaced text TODO should NOT appear in snippet:\n" + snippet,
+ snippet.contains("TODO: fill this in"));
+ assertTrue("Replacement text expected in snippet:\n" + snippet,
+ snippet.contains("see SiblingHelper"));
+ // @link: SiblingHelper wrapped in an anchor to its doc page.
+ assertTrue("@link anchor wrapping SiblingHelper expected in:\n" + snippet,
+ snippet.matches("(?s).*<a href=\"[^\"]*SiblingHelper\\.html\">SiblingHelper</a>.*"));
+ // Markup-comment lines themselves must be stripped.
+ assertFalse("// @highlight directive line should be stripped:\n" + snippet,
+ snippet.contains("@highlight"));
+ assertFalse("// @replace directive line should be stripped:\n" + snippet,
+ snippet.contains("@replace"));
+ assertFalse("// @link directive line should be stripped:\n" + snippet,
+ snippet.contains("@link"));
+ }
+
+ // GROOVY-11938 stage 3 region support: a directive with region="name"
+ // activates at its line and applies until the matching // @end marker.
+ public void testSnippetMarkupRegionScoping() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ htmlTool.add(List.of(base + "/ClassWithSnippetMarkup.groovy",
+ base + "/ScriptWithSiblingClassLinks.groovy"));
+ MockOutputTool output = new MockOutputTool();
+ htmlTool.renderToOutput(output, MOCK_DIR);
+
+ String page = output.getText(MOCK_DIR + "/" + base + "/ClassWithSnippetMarkup.html");
+ assertNotNull(page);
+ // Locate the SECOND snippet block (the region-scoped one).
+ int first = page.indexOf("<pre><code class=\"language-groovy\">");
+ int second = page.indexOf("<pre><code class=\"language-groovy\">", first + 1);
+ assertTrue("Second snippet block expected", second > first);
+ int end = page.indexOf("</code></pre>", second);
+ String snippet = page.substring(second, end);
+
+ // Inside region: both `call` and `call2` should have <mark> wrapping "call".
+ assertTrue("Region-scoped highlight should mark `call` inside def call(x):\n" + snippet,
+ snippet.contains("def <mark>call</mark>(x)"));
+ assertTrue("Region-scoped highlight should mark `call` inside def call2(x):\n" + snippet,
+ snippet.contains("def <mark>call</mark>2(x)"));
+ // Outside region: `call` on the afterRegion line should NOT be highlighted.
+ int afterIdx = snippet.indexOf("afterRegion");
+ String afterPortion = snippet.substring(afterIdx);
+ assertFalse("Highlight must not leak past @end into afterRegion line:\n" + afterPortion,
+ afterPortion.contains("<mark>"));
+ // @end / @start marker lines themselves stripped.
+ assertFalse("@end region marker line should be stripped:\n" + snippet,
+ snippet.contains("@end"));
+ }
+
// GROOVY-11938 stage 5: Markdown and {@snippet} interop. A /// doc comment
// containing a Markdown heading, an inline {@snippet}, and a fenced
// Markdown code block emits three distinct HTML chunks without the
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithSnippetMarkup.groovy b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithSnippetMarkup.groovy
new file mode 100644
index 0000000000..7bf8553805
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithSnippetMarkup.groovy
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.codehaus.groovy.tools.groovydoc.testfiles
+
+/**
+ * GROOVY-11938 stage 3 fixture: {@snippet} markup comments.
+ *
+ * {@snippet lang="groovy" :
+ * def greet(name) { "Hello, $name!" } // @highlight substring="greet" type="bold"
+ * def aside = "TODO: fill this in" // @replace substring="TODO: fill this in" replacement="see SiblingHelper"
+ * // @link substring="SiblingHelper" target="SiblingHelper"
+ * def helper = SiblingHelper.otherMethod()
+ * }
+ *
+ * Region-scoped variant — a {@code region} attribute activates the directive
+ * until a matching {@code // @end} marker:
+ *
+ * {@snippet lang="groovy" :
+ * def regular = 1
+ * // @highlight region="api" substring="call" type="highlighted"
+ * def call(x) { x }
+ * def call2(x) { x + 1 }
+ * // @end region="api"
+ * def afterRegion = "call"
+ * }
+ */
+class ClassWithSnippetMarkup {
+}
(groovy) 33/34: avoid GitHub security/CodeQL warning which I think was a false positive for us, but avoided anyway
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 4f56767ea52204097f46e60667f49d388faa941f
Author: Paul King <pa...@asert.com.au>
AuthorDate: Tue Apr 21 15:10:21 2026 +1000
avoid GitHub security/CodeQL warning which I think was a false positive for us, but avoided anyway
---
.../org/apache/groovy/antlr/GroovydocVisitor.java | 26 +++++++++++-----------
1 file changed, 13 insertions(+), 13 deletions(-)
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java b/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
index c7fb514e15..069803a7be 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
@@ -63,8 +63,6 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
import static org.apache.groovy.ast.tools.AnnotatedNodeUtils.deemedInternal;
import static org.apache.groovy.ast.tools.ExpressionUtils.transformInlineConstants;
@@ -222,17 +220,18 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
return imports;
}
- private static final Pattern JAVADOC_COMMENT_PATTERN = Pattern.compile("(?s)/\\*\\*(.*?)\\*/");
-
private String getDocContent(Groovydoc groovydoc) {
if (groovydoc == null) return "";
String result = groovydoc.getContent();
- if (result == null) result = "";
- Matcher m = JAVADOC_COMMENT_PATTERN.matcher(result);
- if (m.find()) {
- result = m.group(1).trim();
- }
- return result;
+ if (result == null) return "";
+ // The parser supplies the raw `/** ... */` token; strip the delimiters
+ // directly instead of a regex match. Equivalent to the former
+ // (?s)/\*\*(.*?)\*/ pattern but avoids a spurious CodeQL polynomial-
+ // regex alert and runs in linear time unambiguously.
+ if (result.length() >= 5 && result.startsWith("/**") && result.endsWith("*/")) {
+ return result.substring(3, result.length() - 2).trim();
+ }
+ return result.trim();
}
/**
@@ -292,9 +291,10 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
int close = src.indexOf("*/", i + 2);
if (close < 0) return "";
if (isJavadoc) {
- String full = src.substring(i, close + 2);
- Matcher m = JAVADOC_COMMENT_PATTERN.matcher(full);
- String content = m.find() ? m.group(1).trim() : "";
+ // full = `/** ... */`; `close` is the first `*/` from
+ // position i+2 so the delimiters bound exactly. Strip
+ // them without a regex match.
+ String content = src.substring(i + 3, close).trim();
LiftDecision decision = decideLift(src, close + 2);
switch (decision) {
case LIFT: return content;
(groovy) 16/34: GROOVY-11942: class hierarchy tree pages (overview-tree, package-tree)
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 9b37f880453c64b0e2a1deb10ed1ec824a4ed9a3
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Apr 20 21:04:45 2026 +1000
GROOVY-11942: class hierarchy tree pages (overview-tree, package-tree)
---
.../codehaus/groovy/tools/groovydoc/ClassTree.java | 177 +++++++++++++++++++++
.../gstringTemplates/GroovyDocTemplateInfo.java | 4 +-
.../gstringTemplates/classLevel/classDocName.html | 2 +
.../packageLevel/package-summary.html | 2 +
.../packageLevel/package-tree.html | 146 +++++++++++++++++
.../topLevel/overview-summary.html | 4 +-
.../gstringTemplates/topLevel/overview-tree.html | 147 +++++++++++++++++
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 36 +++++
8 files changed, 515 insertions(+), 3 deletions(-)
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/ClassTree.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/ClassTree.java
new file mode 100644
index 0000000000..37da538327
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/ClassTree.java
@@ -0,0 +1,177 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.codehaus.groovy.tools.groovydoc;
+
+import org.codehaus.groovy.groovydoc.GroovyClassDoc;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+/**
+ * GROOVY-11942: builds the inheritance/extension trees rendered by the
+ * {@code overview-tree.html} and {@code package-tree.html} templates.
+ *
+ * <p>Produces two separate trees:
+ * <ul>
+ * <li>The <em>class tree</em> is rooted at {@code java.lang.Object} and
+ * built by walking each class's {@code getParentClasses()} chain,
+ * so external ancestors (like {@code java.lang.Throwable}) appear
+ * as non-link nodes joining the documented classes to Object.</li>
+ * <li>The <em>interface tree</em> lists top-level interfaces and traits
+ * whose parent interfaces are not themselves documented in this
+ * tree, with children determined by direct {@code extends}
+ * relationships between documented interfaces. Interfaces with
+ * multiple parents may appear under more than one root.</li>
+ * </ul>
+ *
+ * <p>Traits are treated as interfaces for the purposes of grouping,
+ * matching their JVM representation, but retain their {@code isTrait()}
+ * flag so templates can render them with a distinct label.
+ */
+public final class ClassTree {
+
+ private ClassTree() {}
+
+ /**
+ * A node in an inheritance/extension tree.
+ *
+ * <p>If {@link #classDoc} is non-null the node represents a documented
+ * type (rendered as a link); otherwise it represents an external type
+ * joining documented children to a common ancestor (rendered as plain
+ * text using {@link #qualifiedName}).
+ */
+ public static final class Node {
+ private final String qualifiedName;
+ private final GroovyClassDoc classDoc;
+ private final Map<String, Node> children = new LinkedHashMap<>();
+
+ Node(String qualifiedName, GroovyClassDoc classDoc) {
+ this.qualifiedName = qualifiedName;
+ this.classDoc = classDoc;
+ }
+
+ public String getQualifiedName() { return qualifiedName; }
+ public GroovyClassDoc getClassDoc() { return classDoc; }
+
+ /** Children in insertion order; callers typically sort before rendering. */
+ public List<Node> getChildren() {
+ List<Node> sorted = new ArrayList<>(children.values());
+ sorted.sort(Comparator.comparing(Node::getQualifiedName));
+ return sorted;
+ }
+ }
+
+ /**
+ * Build the class tree for the given documented classes. The returned
+ * root is a synthetic node for {@code java.lang.Object}; traits,
+ * interfaces, and annotation types are excluded (they belong in the
+ * interface tree).
+ */
+ public static Node buildClassTree(GroovyClassDoc[] classes) {
+ Node root = new Node("java.lang.Object", null);
+ for (GroovyClassDoc c : classes) {
+ if (isInterfaceLike(c)) continue;
+ if (!(c instanceof SimpleGroovyClassDoc)) continue;
+ List<GroovyClassDoc> chain = ((SimpleGroovyClassDoc) c).getParentClasses();
+ Node cursor = root;
+ for (GroovyClassDoc ancestor : chain) {
+ String qn = ancestor.qualifiedTypeName();
+ if ("java.lang.Object".equals(qn)) continue; // root itself
+ Node child = cursor.children.get(qn);
+ if (child == null) {
+ GroovyClassDoc docForLink = ancestor == c ? c :
+ (ancestor instanceof SimpleGroovyClassDoc ? ancestor : null);
+ child = new Node(qn, docForLink);
+ cursor.children.put(qn, child);
+ } else if (child.classDoc == null && ancestor instanceof SimpleGroovyClassDoc) {
+ // upgrade a previously-external node to a linkable one
+ Node upgraded = new Node(qn, ancestor);
+ upgraded.children.putAll(child.children);
+ cursor.children.put(qn, upgraded);
+ child = upgraded;
+ }
+ cursor = child;
+ }
+ }
+ return root;
+ }
+
+ /**
+ * Build the interface tree for the given documented classes.
+ * Returns a synthetic top-level node whose children are the top-level
+ * interfaces/traits — i.e. those whose super-interfaces aren't
+ * themselves present in the input set.
+ */
+ public static Node buildInterfaceTree(GroovyClassDoc[] classes) {
+ Map<String, GroovyClassDoc> docByName = new LinkedHashMap<>();
+ for (GroovyClassDoc c : classes) {
+ if (isInterfaceLike(c)) docByName.put(c.qualifiedTypeName(), c);
+ }
+ Node root = new Node("", null);
+ // Children of a given interface = documented interfaces that directly extend it.
+ Map<String, Map<String, Node>> childrenOf = new TreeMap<>();
+ Map<String, Node> nodesByName = new LinkedHashMap<>();
+ for (Map.Entry<String, GroovyClassDoc> e : docByName.entrySet()) {
+ nodesByName.put(e.getKey(), new Node(e.getKey(), e.getValue()));
+ }
+ for (Map.Entry<String, GroovyClassDoc> e : docByName.entrySet()) {
+ GroovyClassDoc c = e.getValue();
+ GroovyClassDoc[] supers = c.interfaces();
+ boolean attached = false;
+ if (supers != null) {
+ for (GroovyClassDoc s : supers) {
+ String sn = s == null ? null : s.qualifiedTypeName();
+ if (sn != null && docByName.containsKey(sn)) {
+ childrenOf.computeIfAbsent(sn, k -> new LinkedHashMap<>())
+ .put(e.getKey(), nodesByName.get(e.getKey()));
+ attached = true;
+ }
+ }
+ }
+ if (!attached) {
+ root.children.put(e.getKey(), nodesByName.get(e.getKey()));
+ }
+ }
+ // Wire documented parent/child relationships.
+ for (Map.Entry<String, Map<String, Node>> e : childrenOf.entrySet()) {
+ Node parent = nodesByName.get(e.getKey());
+ if (parent != null) parent.children.putAll(e.getValue());
+ }
+ return root;
+ }
+
+ private static boolean isInterfaceLike(GroovyClassDoc c) {
+ if (c == null) return false;
+ if (c.isInterface() || c.isAnnotationType()) return true;
+ return c instanceof SimpleGroovyDoc && ((SimpleGroovyDoc) c).isTrait();
+ }
+
+ /**
+ * Helper used by templates: list of children of a node, sorted by
+ * qualified name. Returns an empty list when {@code node} is {@code null}.
+ */
+ public static List<Node> sortedChildren(Node node) {
+ return node == null ? Collections.emptyList() : node.getChildren();
+ }
+}
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/gstringTemplates/GroovyDocTemplateInfo.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/gstringTemplates/GroovyDocTemplateInfo.java
index 7fefef238d..66bd46cdaf 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/gstringTemplates/GroovyDocTemplateInfo.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/gstringTemplates/GroovyDocTemplateInfo.java
@@ -29,13 +29,15 @@ public class GroovyDocTemplateInfo {
TEMPLATE_BASEDIR + "topLevel/help-doc.html",
TEMPLATE_BASEDIR + "topLevel/index-all.html",
TEMPLATE_BASEDIR + "topLevel/deprecated-list.html",
+ TEMPLATE_BASEDIR + "topLevel/overview-tree.html",
TEMPLATE_BASEDIR + "topLevel/stylesheet.css", // copy default one, may override later
TEMPLATE_BASEDIR + "topLevel/inherit.gif",
DOCGEN_BASEDIR + "groovy.ico",
};
public static final String[] DEFAULT_PACKAGE_TEMPLATES = new String[]{ // package level templates
TEMPLATE_BASEDIR + "packageLevel/package-frame.html",
- TEMPLATE_BASEDIR + "packageLevel/package-summary.html"
+ TEMPLATE_BASEDIR + "packageLevel/package-summary.html",
+ TEMPLATE_BASEDIR + "packageLevel/package-tree.html"
};
public static final String[] DEFAULT_CLASS_TEMPLATES = new String[]{ // class level templates
TEMPLATE_BASEDIR + "classLevel/classDocName.html"
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.html
index 968b8eb3d3..0020fc5761 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.html
@@ -117,6 +117,7 @@ if (location.href.indexOf('is-external=true') == -1) {
<li><a href="${classDoc.relativeRootPath}overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
+ <li><a href="package-tree.html">Tree</a></li>
<li><a href="${classDoc.relativeRootPath}deprecated-list.html">Deprecated</a></li>
<li><a href="${classDoc.relativeRootPath}index-all.html">Index</a></li>
<li><a href="${classDoc.relativeRootPath}help-doc.html">Help</a></li>
@@ -724,6 +725,7 @@ if (classDoc.isInterface() && classDoc.interfaces()) {
<li><a href="${classDoc.relativeRootPath}overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
+ <li><a href="package-tree.html">Tree</a></li>
<li><a href="${classDoc.relativeRootPath}deprecated-list.html">Deprecated</a></li>
<li><a href="${classDoc.relativeRootPath}index-all.html">Index</a></li>
<li><a href="${classDoc.relativeRootPath}help-doc.html">Help</a></li>
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html
index ead666d25a..c21594666a 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html
@@ -69,6 +69,7 @@ function windowTitle()
<li><a href="${packageDoc.relativeRootPath}overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
+ <li><a href="package-tree.html">Tree</a></li>
<li><a href="${packageDoc.relativeRootPath}deprecated-list.html">Deprecated</a></li>
<li><a href="${packageDoc.relativeRootPath}index-all.html">Index</a></li>
<li><a href="${packageDoc.relativeRootPath}help-doc.html">Help</a></li>
@@ -140,6 +141,7 @@ classTypes.each { k, v ->
<li><a href="overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
+ <li><a href="package-tree.html">Tree</a></li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li><a href="index-all.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-tree.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-tree.html
new file mode 100644
index 0000000000..ef38160e4a
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-tree.html
@@ -0,0 +1,146 @@
+<!--
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you 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
+
+ http://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.
+
+-->
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<% def title = packageDoc.nameWithDots() + " Class Hierarchy" + (props.windowTitle ? " (${props.windowTitle})" : "") %>
+<html>
+<head>
+<title>${title}</title>
+<meta http-equiv="Content-Type" content="text/html; charset=${props.charset}">
+<meta name="keywords" content="${packageDoc.nameWithDots()} Class Hierarchy">
+<link rel="stylesheet" type="text/css" href="${packageDoc.relativeRootPath}stylesheet.css" title="Style">
+<% if (props.additionalStylesheets) props.additionalStylesheets.tokenize(',').each { __ss -> %>
+<link rel="stylesheet" type="text/css" href="${packageDoc.relativeRootPath}${__ss.trim()}">
+<% } %>
+<link href="${packageDoc.relativeRootPath}groovy.ico" type="image/x-icon" rel="shortcut icon">
+<link href="${packageDoc.relativeRootPath}groovy.ico" type="image/x-icon" rel="icon">
+</head>
+<body>
+<!-- ========= START OF TOP NAVBAR ======= -->
+<div class="topNav"><a name="navbar_top"><!-- --></a>
+<a href="#skip-navbar_top" title="Skip navigation links"></a>
+<a name="navbar_top_firstrow"><!-- --></a>
+<ul class="navList" title="Navigation">
+ <li><a href="${packageDoc.relativeRootPath}overview-summary.html">Overview</a></li>
+ <li><a href="package-summary.html">Package</a></li>
+ <li>Class</li>
+ <li class="navBarCell1Rev">Tree</li>
+ <li><a href="${packageDoc.relativeRootPath}deprecated-list.html">Deprecated</a></li>
+ <li><a href="${packageDoc.relativeRootPath}index-all.html">Index</a></li>
+ <li><a href="${packageDoc.relativeRootPath}help-doc.html">Help</a></li>
+</ul>
+</div>
+<div class="subNav">
+ <ul class="navList">
+ <li><a href="${packageDoc.relativeRootPath}index.html?${packageDoc.name()}/package-tree.html" target="_top">Frames</a></li>
+ <li><a href="package-tree.html" target="_top">No Frames</a></li>
+ </ul>
+ <a name="skip-navbar_top"><!-- --></a>
+</div>
+<!-- ========= END OF TOP NAVBAR ========= -->
+<%
+ def tree = org.codehaus.groovy.tools.groovydoc.ClassTree
+ def classes = packageDoc.allClasses()
+ def classRoot = tree.buildClassTree(classes)
+ def interfaceRoot = tree.buildInterfaceTree(classes)
+ def hasClasses = !classRoot.children.isEmpty()
+ def hasInterfaces = !interfaceRoot.children.isEmpty()
+ def relRoot = packageDoc.relativeRootPath
+ def labelFor = { cd ->
+ if (cd == null) return 'class'
+ if (cd.isTrait()) return 'trait'
+ if (cd.isInterface()) return 'interface'
+ if (cd.isAnnotationType()) return 'annotation'
+ if (cd.isEnum()) return 'enum'
+ return 'class'
+ }
+ def renderNode
+ renderNode = { node ->
+ def cd = node.classDoc
+ def label = '<li type="circle">'
+ if (cd != null) {
+ def pkg = cd.containingPackage()?.nameWithDots() ?: ''
+ label += "${labelFor(cd)} <a href=\"${relRoot}${cd.fullPathName}.html\" title=\"${labelFor(cd)} in ${pkg}\"><strong>${cd.qualifiedTypeName()}</strong></a>"
+ } else {
+ label += "class ${node.qualifiedName}"
+ }
+ def kids = node.children
+ if (!kids.isEmpty()) {
+ label += '<ul>'
+ kids.each { label += renderNode(it) }
+ label += '</ul>'
+ }
+ label += '</li>'
+ return label
+ }
+%>
+<div class="header">
+ <h1 class="title">Hierarchy For Package ${packageDoc.nameWithDots()}</h1>
+ <span class="packageHierarchyLabel">Package Hierarchies:</span>
+ <ul class="horizontal">
+ <li><a href="${packageDoc.relativeRootPath}overview-tree.html">All Packages</a></li>
+ </ul>
+</div>
+<div class="contentContainer">
+<% if (hasClasses) { %>
+ <h2 class="title">Class Hierarchy</h2>
+ <ul>
+ <li type="circle">class <strong>java.lang.Object</strong>
+ <ul>
+<% classRoot.children.each { out << renderNode(it) } %>
+ </ul>
+ </li>
+ </ul>
+<% } %>
+<% if (hasInterfaces) { %>
+ <h2 class="title">Interface Hierarchy</h2>
+ <ul>
+<% interfaceRoot.children.each { out << renderNode(it) } %>
+ </ul>
+<% } %>
+<% if (!hasClasses && !hasInterfaces) { %>
+ <p>No documented types in this package.</p>
+<% } %>
+</div>
+<!-- ======= START OF BOTTOM NAVBAR ====== -->
+<div class="bottomNav"><a name="navbar_bottom"><!-- --></a>
+<a href="#skip-navbar_bottom" title="Skip navigation links"></a>
+<a name="navbar_bottom_firstrow"><!-- --></a>
+<ul class="navList" title="Navigation">
+ <li><a href="${packageDoc.relativeRootPath}overview-summary.html">Overview</a></li>
+ <li><a href="package-summary.html">Package</a></li>
+ <li>Class</li>
+ <li class="navBarCell1Rev">Tree</li>
+ <li><a href="${packageDoc.relativeRootPath}deprecated-list.html">Deprecated</a></li>
+ <li><a href="${packageDoc.relativeRootPath}index-all.html">Index</a></li>
+ <li><a href="${packageDoc.relativeRootPath}help-doc.html">Help</a></li>
+</ul>
+</div>
+<div class="subNav">
+ <ul class="navList">
+ <li><a href="${packageDoc.relativeRootPath}index.html?${packageDoc.name()}/package-tree.html" target="_top">Frames</a></li>
+ <li><a href="package-tree.html" target="_top">No Frames</a></li>
+ </ul>
+ <div class="aboutLanguage"><em>${props['footer']?:""}</em></div>
+ <a name="skip-navbar_bottom"><!-- --></a>
+</div>
+<!-- ======== END OF BOTTOM NAVBAR ======= -->
+</body>
+</html>
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary.html
index 37ecd51e5a..a013df2b30 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary.html
@@ -53,7 +53,7 @@ if (location.href.indexOf('is-external=true') == -1) {
<li class="navBarCell1Rev">Overview</li>
<li>Package</li>
<li>Class</li>
- <!--<li><a href="overview-tree.html">Tree</a></li>-->
+ <li><a href="overview-tree.html">Tree</a></li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li><a href="index-all.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
@@ -127,7 +127,7 @@ if (location.href.indexOf('is-external=true') == -1) {
<li class="navBarCell1Rev">Overview</li>
<li>Package</li>
<li>Class</li>
- <!--<li><a href="overview-tree.html">Tree</a></li>-->
+ <li><a href="overview-tree.html">Tree</a></li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li><a href="index-all.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-tree.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-tree.html
new file mode 100644
index 0000000000..dc171d224c
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-tree.html
@@ -0,0 +1,147 @@
+<!--
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you 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
+
+ http://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.
+
+-->
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<% def title = "Class Hierarchy" + (props.windowTitle ? " (${props.windowTitle})" : "") %>
+<html>
+<head>
+<title>${title}</title>
+<meta http-equiv="Content-Type" content="text/html; charset=${props.charset}">
+<meta name="keywords" content="Class Hierarchy">
+<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
+<% if (props.additionalStylesheets) props.additionalStylesheets.tokenize(',').each { __ss -> %>
+<link rel="stylesheet" type="text/css" href="${__ss.trim()}">
+<% } %>
+<link href="groovy.ico" type="image/x-icon" rel="shortcut icon">
+<link href="groovy.ico" type="image/x-icon" rel="icon">
+</head>
+<body>
+<!-- ========= START OF TOP NAVBAR ======= -->
+<div class="topNav"><a name="navbar_top"><!-- --></a>
+<a href="#skip-navbar_top" title="Skip navigation links"></a>
+<a name="navbar_top_firstrow"><!-- --></a>
+<ul class="navList" title="Navigation">
+ <li><a href="overview-summary.html">Overview</a></li>
+ <li>Package</li>
+ <li>Class</li>
+ <li class="navBarCell1Rev">Tree</li>
+ <li><a href="deprecated-list.html">Deprecated</a></li>
+ <li><a href="index-all.html">Index</a></li>
+ <li><a href="help-doc.html">Help</a></li>
+</ul>
+</div>
+<div class="subNav">
+ <ul class="navList">
+ <li><a href="index.html?overview-tree.html" target="_top">Frames</a></li>
+ <li><a href="overview-tree.html" target="_top">No Frames</a></li>
+ </ul>
+ <a name="skip-navbar_top"><!-- --></a>
+</div>
+<!-- ========= END OF TOP NAVBAR ========= -->
+<%
+ def tree = org.codehaus.groovy.tools.groovydoc.ClassTree
+ def classRoot = tree.buildClassTree(rootDoc.classes())
+ def interfaceRoot = tree.buildInterfaceTree(rootDoc.classes())
+ def hasClasses = !classRoot.children.isEmpty()
+ def hasInterfaces = !interfaceRoot.children.isEmpty()
+ def relRoot = ''
+ def labelFor = { cd ->
+ if (cd == null) return 'class'
+ if (cd.isTrait()) return 'trait'
+ if (cd.isInterface()) return 'interface'
+ if (cd.isAnnotationType()) return 'annotation'
+ if (cd.isEnum()) return 'enum'
+ return 'class'
+ }
+ def renderNode
+ renderNode = { node ->
+ def cd = node.classDoc
+ def label = '<li type="circle">'
+ if (cd != null) {
+ def pkg = cd.containingPackage()?.nameWithDots() ?: ''
+ label += "${labelFor(cd)} <a href=\"${relRoot}${cd.fullPathName}.html\" title=\"${labelFor(cd)} in ${pkg}\"><strong>${cd.qualifiedTypeName()}</strong></a>"
+ } else {
+ label += "class ${node.qualifiedName}"
+ }
+ def kids = node.children
+ if (!kids.isEmpty()) {
+ label += '<ul>'
+ kids.each { label += renderNode(it) }
+ label += '</ul>'
+ }
+ label += '</li>'
+ return label
+ }
+%>
+<div class="header">
+ <h1 class="title">Hierarchy For All Packages</h1>
+ <span class="packageHierarchyLabel">Package Hierarchies:</span>
+ <ul class="horizontal">
+<% rootDoc.specifiedPackages().eachWithIndex { packageDoc, i -> %>
+ <li><a href="${packageDoc.name()}/package-tree.html">${packageDoc.nameWithDots()}</a>${i < rootDoc.specifiedPackages().length - 1 ? ',' : ''}</li>
+<% } %>
+ </ul>
+</div>
+<div class="contentContainer">
+<% if (hasClasses) { %>
+ <h2 class="title">Class Hierarchy</h2>
+ <ul>
+ <li type="circle">class <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Object.html" title="class in java.lang" target="_blank"><strong>java.lang.Object</strong></a>
+ <ul>
+<% classRoot.children.each { out << renderNode(it) } %>
+ </ul>
+ </li>
+ </ul>
+<% } %>
+<% if (hasInterfaces) { %>
+ <h2 class="title">Interface Hierarchy</h2>
+ <ul>
+<% interfaceRoot.children.each { out << renderNode(it) } %>
+ </ul>
+<% } %>
+<% if (!hasClasses && !hasInterfaces) { %>
+ <p>No documented types to display.</p>
+<% } %>
+</div>
+<!-- ======= START OF BOTTOM NAVBAR ====== -->
+<div class="bottomNav"><a name="navbar_bottom"><!-- --></a>
+<a href="#skip-navbar_bottom" title="Skip navigation links"></a>
+<a name="navbar_bottom_firstrow"><!-- --></a>
+<ul class="navList" title="Navigation">
+ <li><a href="overview-summary.html">Overview</a></li>
+ <li>Package</li>
+ <li>Class</li>
+ <li class="navBarCell1Rev">Tree</li>
+ <li><a href="deprecated-list.html">Deprecated</a></li>
+ <li><a href="index-all.html">Index</a></li>
+ <li><a href="help-doc.html">Help</a></li>
+</ul>
+</div>
+<div class="subNav">
+ <ul class="navList">
+ <li><a href="index.html?overview-tree.html" target="_top">Frames</a></li>
+ <li><a href="overview-tree.html" target="_top">No Frames</a></li>
+ </ul>
+ <div class="aboutLanguage"><em>${props['footer']?:""}</em></div>
+ <a name="skip-navbar_bottom"><!-- --></a>
+</div>
+<!-- ======== END OF BOTTOM NAVBAR ======= -->
+</body>
+</html>
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index c54900cf7e..caeb524434 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -422,6 +422,42 @@ public class GroovyDocToolTest extends GroovyTestCase {
+ occurrences + " in:\n" + doc, 2, occurrences);
}
+ // GROOVY-11942: overview-tree.html renders the class hierarchy rooted at
+ // java.lang.Object and an Interface Hierarchy section for traits/interfaces.
+ public void testTreePagesRenderExpectedHierarchy() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ htmlTool.add(List.of(
+ base + "/GroovyClassWithMultipleInterfaces.groovy",
+ base + "/GroovyInterface1.groovy"));
+
+ MockOutputTool output = new MockOutputTool();
+ htmlTool.renderToOutput(output, MOCK_DIR);
+
+ String overview = output.getText(MOCK_DIR + "/overview-tree.html");
+ assertNotNull("Expected overview-tree.html in output", overview);
+ assertTrue("Overview tree should contain Class Hierarchy section:\n" + overview,
+ overview.contains("Class Hierarchy"));
+ assertTrue("Overview tree should list GroovyClassWithMultipleInterfaces under Object:\n" + overview,
+ overview.contains("GroovyClassWithMultipleInterfaces"));
+ assertTrue("Overview tree should contain Interface Hierarchy section:\n" + overview,
+ overview.contains("Interface Hierarchy"));
+ assertTrue("Interface tree should list GroovyInterface1:\n" + overview,
+ overview.contains("GroovyInterface1"));
+
+ String pkgTree = output.getText(MOCK_DIR + "/" + base + "/package-tree.html");
+ assertNotNull("Expected package-tree.html in output", pkgTree);
+ assertTrue("Package tree should mention the package name:\n" + pkgTree,
+ pkgTree.contains("org.codehaus.groovy.tools.groovydoc.testfiles"));
+ assertTrue("Package tree should link back to All Packages overview:\n" + pkgTree,
+ pkgTree.contains("overview-tree.html"));
+
+ // Nav bar on the class page should now link to package-tree.html.
+ String klassPage = output.getText(MOCK_DIR + "/" + base + "/GroovyClassWithMultipleInterfaces.html");
+ assertNotNull(klassPage);
+ assertTrue("Class page nav should link to package-tree.html:\n" + klassPage,
+ klassPage.contains("href=\"package-tree.html\""));
+ }
+
// GROOVY-10162
public void testAbstractMethodEnumWithPerConstantBodiesDoesNotProduceAnonymousInnerPages() throws Exception {
String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
(groovy) 32/34: update license/notice info
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit feb85052a971e3a07c35d3c9ace2bf1de5386f1b
Author: Paul King <pa...@asert.com.au>
AuthorDate: Tue Apr 21 14:58:29 2026 +1000
update license/notice info
---
LICENSE | 11 +++++++++
NOTICE | 5 +++-
licenses/LICENSE-BINZIP | 11 +++++++++
licenses/LICENSE-DOC | 11 +++++++++
licenses/LICENSE-SDK | 11 +++++++++
licenses/prism-BINZIP-DOC-SRC.txt | 8 ++++++
licenses/prism-groovy-groovydoc.txt | 41 +++++++++++++++++++++++++++++++
licenses/prism-license.txt | 21 ++++++++++++++++
notices/NOTICE-BINZIP | 5 +++-
notices/NOTICE-SDK | 3 +++
notices/prism-BINZIP-DOC-SRC.txt | 2 ++
subprojects/groovy-groovydoc/build.gradle | 1 +
12 files changed, 128 insertions(+), 2 deletions(-)
diff --git a/LICENSE b/LICENSE
index a6e3cfd3b4..bb55906137 100644
--- a/LICENSE
+++ b/LICENSE
@@ -268,3 +268,14 @@ The stylesheet.css file (originally normalize.css) is used by the
groovydoc and docgenerator components for groovy-jdk/gapi documentation.
It is made available under a MIT License:
licenses/normalize-stylesheet-license.txt
+
+------------------------------------------------------------------------
+
+Prism License
+
+The prism.js, prism.min.css, prism-dark.min.css, and the
+prism-*.min.js language components bundled by the groovydoc
+component provide client-side syntax highlighting for code
+snippets in the generated documentation. They are made available
+under a MIT License:
+licenses/prism-license.txt
diff --git a/NOTICE b/NOTICE
index 707f4610e4..df08896b11 100644
--- a/NOTICE
+++ b/NOTICE
@@ -10,4 +10,7 @@ Copyright 2010-2012 Google Inc. All Rights Reserved.
The Java source file src/main/java/org/apache/groovy/util/concurrent/ConcurrentReferenceHashMap
is from https://github.com/hazelcast/hazelcast and the following notice applies:
-Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
\ No newline at end of file
+Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
+
+This product bundles Prism.js (prismjs.com)
+which is available under the terms of the MIT License.
\ No newline at end of file
diff --git a/licenses/LICENSE-BINZIP b/licenses/LICENSE-BINZIP
index f2d373510b..b57e12f4be 100644
--- a/licenses/LICENSE-BINZIP
+++ b/licenses/LICENSE-BINZIP
@@ -297,6 +297,17 @@ licenses/normalize-stylesheet-license.txt
------------------------------------------------------------------------
+Prism License
+
+The prism.js, prism.min.css, prism-dark.min.css, and the
+prism-*.min.js language components bundled by the groovydoc
+component provide client-side syntax highlighting for code
+snippets in the generated documentation. They are made available
+under a MIT License:
+licenses/prism-license.txt
+
+------------------------------------------------------------------------
+
XStream License (optional dependency when serializing AST as XML)
This product bundles the XStream jar, which is available under a
diff --git a/licenses/LICENSE-DOC b/licenses/LICENSE-DOC
index b72eeb2209..0a6fde5157 100644
--- a/licenses/LICENSE-DOC
+++ b/licenses/LICENSE-DOC
@@ -228,3 +228,14 @@ The stylesheet.css file (originally normalize.css) is used by the
groovydoc and docgenerator components for groovy-jdk/gapi documentation.
It is made available under a MIT License:
licenses/normalize-stylesheet-license.txt
+
+------------------------------------------------------------------------
+
+Prism License
+
+The prism.js, prism.min.css, prism-dark.min.css, and the
+prism-*.min.js language components bundled by the groovydoc
+component provide client-side syntax highlighting for code
+snippets in the generated documentation. They are made available
+under a MIT License:
+licenses/prism-license.txt
diff --git a/licenses/LICENSE-SDK b/licenses/LICENSE-SDK
index 271fa4944e..c37fbbfb50 100644
--- a/licenses/LICENSE-SDK
+++ b/licenses/LICENSE-SDK
@@ -297,6 +297,17 @@ licenses/normalize-stylesheet-license.txt
------------------------------------------------------------------------
+Prism License
+
+The prism.js, prism.min.css, prism-dark.min.css, and the
+prism-*.min.js language components bundled by the groovydoc
+component provide client-side syntax highlighting for code
+snippets in the generated documentation. They are made available
+under a MIT License:
+licenses/prism-license.txt
+
+------------------------------------------------------------------------
+
XStream License (optional dependency when serializing AST as XML)
This product bundles the XStream jar, which is available under a
diff --git a/licenses/prism-BINZIP-DOC-SRC.txt b/licenses/prism-BINZIP-DOC-SRC.txt
new file mode 100644
index 0000000000..45077b7108
--- /dev/null
+++ b/licenses/prism-BINZIP-DOC-SRC.txt
@@ -0,0 +1,8 @@
+Prism License
+
+The prism.js, prism.min.css, prism-dark.min.css, and the
+prism-*.min.js language components bundled by the groovydoc
+component provide client-side syntax highlighting for code
+snippets in the generated documentation. They are made available
+under a MIT License:
+licenses/prism-license.txt
diff --git a/licenses/prism-groovy-groovydoc.txt b/licenses/prism-groovy-groovydoc.txt
new file mode 100644
index 0000000000..933ef5ea53
--- /dev/null
+++ b/licenses/prism-groovy-groovydoc.txt
@@ -0,0 +1,41 @@
+PRISM LICENSE
+
+The following files are used to provide client-side syntax highlighting
+of code snippets in the generated documentation:
+
+ org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism.js
+ org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism.min.css
+ org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-dark.min.css
+ org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-csv.min.js
+ org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-groovy.min.js
+ org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-java.min.js
+ org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-javadoclike.min.js
+ org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-javascript.min.js
+ org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-json.min.js
+ org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-markdown.min.js
+ org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-properties.min.js
+ org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-regex.min.js
+ org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-sql.min.js
+ org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-toml.min.js
+ org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-xml-doc.min.js
+ org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-yaml.min.js
+
+Copyright (c) 2012 Lea Verou
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/licenses/prism-license.txt b/licenses/prism-license.txt
new file mode 100644
index 0000000000..654f3bc279
--- /dev/null
+++ b/licenses/prism-license.txt
@@ -0,0 +1,21 @@
+MIT LICENSE
+
+Copyright (c) 2012 Lea Verou
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/notices/NOTICE-BINZIP b/notices/NOTICE-BINZIP
index 78c2d2ca41..18d66e2bfa 100644
--- a/notices/NOTICE-BINZIP
+++ b/notices/NOTICE-BINZIP
@@ -31,4 +31,7 @@ licensed to the Apache Software Foundation under the "Software Grant and Corpora
Contribution License Agreement" and for which the following copyright notices apply
(C) Copyright 2005 Intel Corporation
(C) Copyright 2005-2006 Intel Corporation
- (C) Copyright 2006 Intel Corporation
\ No newline at end of file
+ (C) Copyright 2006 Intel Corporation
+
+This product bundles Prism.js (prismjs.com)
+which is available under the terms of the MIT License.
\ No newline at end of file
diff --git a/notices/NOTICE-SDK b/notices/NOTICE-SDK
index 1de6a08c55..5849ef2681 100644
--- a/notices/NOTICE-SDK
+++ b/notices/NOTICE-SDK
@@ -33,5 +33,8 @@ Contribution License Agreement" and for which the following copyright notices ap
(C) Copyright 2005-2006 Intel Corporation
(C) Copyright 2006 Intel Corporation
+This product bundles Prism.js (prismjs.com)
+which is available under the terms of the MIT License.
+
This convenience zip embeds Groovy's src and doc zips.
See also src/NOTICE and doc/NOTICE files for additional notice information.
\ No newline at end of file
diff --git a/notices/prism-BINZIP-DOC-SRC.txt b/notices/prism-BINZIP-DOC-SRC.txt
new file mode 100644
index 0000000000..b8cb51a6ad
--- /dev/null
+++ b/notices/prism-BINZIP-DOC-SRC.txt
@@ -0,0 +1,2 @@
+This product bundles Prism.js (prismjs.com)
+which is available under the terms of the MIT License.
diff --git a/subprojects/groovy-groovydoc/build.gradle b/subprojects/groovy-groovydoc/build.gradle
index ae74ac0ed7..6ecc5d09a1 100644
--- a/subprojects/groovy-groovydoc/build.gradle
+++ b/subprojects/groovy-groovydoc/build.gradle
@@ -48,4 +48,5 @@ plugins.withId('eclipse') {
tasks.named('rat') {
excludes << '**/stylesheet.css' // MIT license as per NOTICE/LICENSE files
+ excludes << '**/prism*.js' << '**/prism*.css' // Prism, MIT license as per NOTICE/LICENSE files
}
(groovy) 07/34: GROOVY-10162: spurious Foo.1.html for abstract-method enum
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit c4b05e785f41ec59fc97ea0afb56e08d5f0f7859
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Apr 20 13:04:25 2026 +1000
GROOVY-10162: spurious Foo.1.html for abstract-method enum
---
.../org/apache/groovy/antlr/GroovydocVisitor.java | 9 ++++-
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 24 ++++++++++++++
.../EnumWithAbstractMethodAndConstantBodies.groovy | 38 ++++++++++++++++++++++
3 files changed, 70 insertions(+), 1 deletion(-)
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java b/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
index 950b15ed18..fd5ade1779 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
@@ -97,6 +97,11 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
@Override
public void visitClass(ClassNode node) {
+ // GROOVY-10162: anonymous inner classes (e.g. those generated for each
+ // enum constant with a body when the enum has an abstract method)
+ // aren't user-visible types and shouldn't produce separate HTML pages
+ // like `Foo.1.html` / `Foo.2.html`.
+ if (node instanceof InnerClassNode && ((InnerClassNode) node).isAnonymous()) return;
final Map<String, String> aliases = new LinkedHashMap<>();
final List<String> imports = new ArrayList<>();
for (ImportNode iNode : node.getModule().getImports()) {
@@ -163,7 +168,9 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
}
Iterator<InnerClassNode> innerClasses = node.getInnerClasses();
while (innerClasses.hasNext()) {
- visitClass(innerClasses.next());
+ InnerClassNode inner = innerClasses.next();
+ if (inner.isAnonymous()) continue; // GROOVY-10162
+ visitClass(inner);
parent.addNested(currentClassDoc);
currentClassDoc = parent;
}
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index 2cc285ee38..4ef83d3f68 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -131,6 +131,30 @@ public class GroovyDocToolTest extends GroovyTestCase {
doc.contains("https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Object.html"));
}
+ // GROOVY-10162
+ public void testAbstractMethodEnumWithPerConstantBodiesDoesNotProduceAnonymousInnerPages() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ String klass = "EnumWithAbstractMethodAndConstantBodies";
+ Properties props = new Properties();
+ // phase 7 = CLASS_GENERATION, by which point the per-constant anonymous
+ // inner classes have been synthesised. The fix must keep them out of
+ // the doc output at any phase.
+ props.put("phaseOverride", "7");
+ GroovyDocTool tool = makeHtmltool(new ArrayList<>(), null, props);
+ tool.add(List.of(base + "/" + klass + ".groovy"));
+
+ MockOutputTool output = new MockOutputTool();
+ tool.renderToOutput(output, MOCK_DIR);
+
+ String enumDoc = output.getText(MOCK_DIR + "/" + base + "/" + klass + ".html");
+ assertNotNull("Expected the enum's own HTML page", enumDoc);
+
+ assertNull("Unexpected anonymous inner page " + klass + ".1.html",
+ output.getText(MOCK_DIR + "/" + base + "/" + klass + ".1.html"));
+ assertNull("Unexpected anonymous inner page " + klass + ".2.html",
+ output.getText(MOCK_DIR + "/" + base + "/" + klass + ".2.html"));
+ }
+
// GROOVY-5986
public void testDocFilesAndSnippetFilesAreCopiedIntoOutput() throws Exception {
String fixtureSourcePath = "src/test/resources/docfiles-fixture";
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/EnumWithAbstractMethodAndConstantBodies.groovy b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/EnumWithAbstractMethodAndConstantBodies.groovy
new file mode 100644
index 0000000000..9a94857b7a
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/EnumWithAbstractMethodAndConstantBodies.groovy
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.codehaus.groovy.tools.groovydoc.testfiles
+
+/**
+ * GROOVY-10162: an enum with an abstract method and per-constant bodies
+ * used to produce spurious {@code EnumWithAbstractMethodAndConstantBodies.1.html}
+ * and {@code .2.html} pages from the anonymous inner classes that back each
+ * constant. Those should be filtered out.
+ */
+enum EnumWithAbstractMethodAndConstantBodies {
+ CIRCLE {
+ @Override
+ String draw() { "circle" }
+ },
+ SQUARE {
+ @Override
+ String draw() { "square" }
+ }
+
+ abstract String draw()
+}
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 485c84c05d0fc2d646d48f8af2879a9574b02a76
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Apr 20 11:46:58 2026 +1000
GROOVY-11939: tag-pipeline refactor
---
.../tools/groovydoc/GroovyRootDocBuilder.java | 27 +-
.../tools/groovydoc/SimpleGroovyClassDoc.java | 131 +-----
.../groovy/tools/groovydoc/TagRenderer.java | 448 +++++++++++++++++++++
3 files changed, 461 insertions(+), 145 deletions(-)
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyRootDocBuilder.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyRootDocBuilder.java
index a3090b0251..af24ef27d9 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyRootDocBuilder.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyRootDocBuilder.java
@@ -34,12 +34,8 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
-import java.util.regex.Pattern;
import static java.lang.System.Logger.Level.WARNING;
-import static org.codehaus.groovy.tools.groovydoc.SimpleGroovyClassDoc.CODE_REGEX;
-import static org.codehaus.groovy.tools.groovydoc.SimpleGroovyClassDoc.LINK_REGEX;
-import static org.codehaus.groovy.tools.groovydoc.SimpleGroovyClassDoc.TAG_REGEX;
/*
* todo: order methods alphabetically (implement compareTo enough?)
@@ -176,26 +172,11 @@ public class GroovyRootDocBuilder {
return description;
}
- // TODO remove dup with SimpleGroovyClassDoc
+ // GROOVY-11939: package-info tag processing goes through the same single-pass
+ // tokenizer as class-level docs, just with a different rendering profile.
private String replaceTags(String orig, String relPath) {
- String result = orig.replaceAll("(?m)^\\s*\\*", ""); // todo precompile regex
-
- // {@link processing hack}
- result = replaceAllTags(result, "", "", LINK_REGEX, relPath);
-
- // {@code processing hack}
- result = replaceAllTags(result, "<TT>", "</TT>", CODE_REGEX, relPath);
-
- // hack to reformat other groovydoc block tags (@see, @return, @param, @throws, @author, @since) into html
- result = replaceAllTags(result + " @endMarker", "<DL><DT><B>$1:</B></DT><DD>", "</DD></DL>", TAG_REGEX, relPath);
- // remove @endMarker
- result = result.substring(0, result.length() - 10);
-
- return SimpleGroovyClassDoc.decodeSpecialSymbols(result);
- }
-
- private String replaceAllTags(String self, String s1, String s2, Pattern regex, String relPath) {
- return SimpleGroovyClassDoc.replaceAllTags(self, s1, s2, regex, links, relPath, rootDoc, null);
+ String result = orig.replaceAll("(?m)^\\s*\\*", "");
+ return TagRenderer.render(result, links, relPath, rootDoc, null, TagRenderer.PACKAGE_LEVEL);
}
private static void calcThenSetSummary(String src, SimpleGroovyPackageDoc packageDoc) {
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyClassDoc.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyClassDoc.java
index a4f31b5084..a9e5e7aad7 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyClassDoc.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyClassDoc.java
@@ -47,38 +47,22 @@ import java.util.regex.Pattern;
public class SimpleGroovyClassDoc extends SimpleGroovyAbstractableElementDoc implements GroovyClassDoc {
- public static final Pattern TAG_REGEX = Pattern.compile("(?sm)\\s*@([a-zA-Z.]+)\\s+(.*?)(?=\\s+@)");
public static final String DOCROOT_PATTERN2 = "(?m)[{]@docRoot}/";
public static final String DOCROOT_PATTERN = "(?m)[{]@docRoot}";
- // group 1: tag name, group 2: tag body
- public static final Pattern LINK_REGEX = Pattern.compile("(?m)[{]@(link)\\s+([^}]*)}");
- public static final Pattern LITERAL_REGEX = Pattern.compile("(?m)[{]@(literal)\\s+([^}]*)}");
+ // Retained for use by test helpers (SimpleGroovyClassDocTests) that pass it
+ // to {@link #encodeAngleBracketsInTagBody}. No longer used internally — the
+ // tag-processing pipeline is now {@link TagRenderer}.
public static final Pattern CODE_REGEX = Pattern.compile("(?m)[{]@(code)\\s+([^}]*)}");
public static final Pattern REF_LABEL_REGEX = Pattern.compile("([\\w.#\\$]*(\\(.*\\))?)(\\s(.*))?");
public static final Pattern NAME_ARGS_REGEX = Pattern.compile("([^(]+)\\(([^)]*)\\)");
public static final Pattern SPLIT_ARGS_REGEX = Pattern.compile(",\\s*");
private static final List<String> PRIMITIVES = Arrays.asList("void", "boolean", "byte", "short", "char", "int", "long", "float", "double");
- private static final Map<String, String> TAG_TEXT = new LinkedHashMap<>();
private static final GroovyConstructorDoc[] EMPTY_GROOVYCONSTRUCTORDOC_ARRAY = new GroovyConstructorDoc[0];
private static final GroovyClassDoc[] EMPTY_GROOVYCLASSDOC_ARRAY = new GroovyClassDoc[0];
private static final GroovyFieldDoc[] EMPTY_GROOVYFIELDDOC_ARRAY = new GroovyFieldDoc[0];
private static final GroovyMethodDoc[] EMPTY_GROOVYMETHODDOC_ARRAY = new GroovyMethodDoc[0];
-
- static {
- TAG_TEXT.put("see", "See Also");
- TAG_TEXT.put("param", "Parameters");
- TAG_TEXT.put("throw", "Throws");
- TAG_TEXT.put("exception", "Throws");
- TAG_TEXT.put("return", "Returns");
- TAG_TEXT.put("since", "Since");
- TAG_TEXT.put("author", "Authors");
- TAG_TEXT.put("version", "Version");
- TAG_TEXT.put("default", "Default");
- // typeparam is used internally as a specialization of param to separate type params from regular params.
- TAG_TEXT.put("typeparam", "Type Parameters");
- }
private final List<GroovyConstructorDoc> constructors;
private final List<GroovyFieldDoc> fields;
private final List<GroovyFieldDoc> properties;
@@ -905,8 +889,11 @@ public class SimpleGroovyClassDoc extends SimpleGroovyAbstractableElementDoc imp
}
public String replaceTags(String comment) {
- String result = comment.replaceAll("(?m)^\\s*\\*", ""); // todo precompile regex
+ // Strip the leading ' * ' block-comment prefix from each line.
+ String result = comment.replaceAll("(?m)^\\s*\\*", "");
+ // Expand {@docRoot} before tag processing since it is a path substitution
+ // rather than a tag-rendering operation.
String relativeRootPath = getRelativeRootPath();
if (!relativeRootPath.endsWith("/")) {
relativeRootPath += "/";
@@ -914,100 +901,8 @@ public class SimpleGroovyClassDoc extends SimpleGroovyAbstractableElementDoc imp
result = result.replaceAll(DOCROOT_PATTERN2, relativeRootPath);
result = result.replaceAll(DOCROOT_PATTERN, relativeRootPath);
- // {@link processing hack}
- result = replaceAllTags(result, "", "", LINK_REGEX);
-
- // {@literal tag}
- result = encodeAngleBracketsInTagBody(result, LITERAL_REGEX);
- result = replaceAllTags(result, "", "", LITERAL_REGEX);
-
- // {@code tag}
- result = encodeAngleBracketsInTagBody(result, CODE_REGEX);
- result = replaceAllTags(result, "<CODE>", "</CODE>", CODE_REGEX);
-
- // hack to reformat other groovydoc block tags (@see, @return, @param, @throws, @author, @since) into html
- result = replaceAllTagsCollated(result, "<DL><DT><B>", ":</B></DT><DD>", "</DD><DD>", "</DD></DL>", TAG_REGEX);
-
- return decodeSpecialSymbols(result);
- }
-
- public String replaceAllTags(String self, String s1, String s2, Pattern regex) {
- return replaceAllTags(self, s1, s2, regex, links, getRelativeRootPath(), savedRootDoc, this);
- }
-
- // TODO: this should go away once we have proper tags
- public static String replaceAllTags(String self, String s1, String s2, Pattern regex, List<LinkArgument> links, String relPath, GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc) {
- Matcher matcher = regex.matcher(self);
- if (matcher.find()) {
- matcher.reset();
- StringBuilder sb = new StringBuilder();
- while (matcher.find()) {
- String tagname = matcher.group(1);
- if (!"interface".equals(tagname)) {
- String content = encodeSpecialSymbols(matcher.group(2));
- if ("link".equals(tagname) || "see".equals(tagname)) {
- content = getDocUrl(content, false, links, relPath, rootDoc, classDoc);
- }
- matcher.appendReplacement(sb, s1 + content + s2);
- }
- }
- matcher.appendTail(sb);
- return sb.toString();
- } else {
- return self;
- }
- }
-
- // TODO: is there a better way to do this?
- public String replaceAllTagsCollated(String self, String preKey, String postKey,
- String valueSeparator, String postValues, Pattern regex) {
- Matcher matcher = regex.matcher(self + " @endMarker");
- if (matcher.find()) {
- matcher.reset();
- Map<String, List<String>> savedTags = new LinkedHashMap<>();
- StringBuilder sb = new StringBuilder();
- while (matcher.find()) {
- String tagname = matcher.group(1);
- if (!"interface".equals(tagname)) {
- String content = encodeSpecialSymbols(matcher.group(2));
- if ("see".equals(tagname) || "link".equals(tagname)) {
- content = getDocUrl(content);
- } else if ("param".equals(tagname)) {
- int index = content.indexOf(' ');
- if (index >= 0) {
- String paramName = content.substring(0, index);
- String paramDesc = content.substring(index);
- if (paramName.startsWith("<") && paramName.endsWith(">")) {
- paramName = paramName.substring(1, paramName.length() - 1);
- tagname = "typeparam";
- }
- content = "<code>" + paramName + "</code> - " + paramDesc;
- }
- }
- if (TAG_TEXT.containsKey(tagname)) {
- String text = TAG_TEXT.get(tagname);
- List<String> contents = savedTags.computeIfAbsent(text, k -> new ArrayList<String>());
- contents.add(content);
- matcher.appendReplacement(sb, "");
- } else {
- matcher.appendReplacement(sb, preKey + tagname + postKey + content + postValues);
- }
- }
- }
- matcher.appendTail(sb);
- // remove @endMarker
- sb = new StringBuilder(sb.substring(0, sb.length() - 10));
- for (Map.Entry<String, List<String>> e : savedTags.entrySet()) {
- sb.append(preKey);
- sb.append(e.getKey());
- sb.append(postKey);
- sb.append(DefaultGroovyMethods.join((Iterable)e.getValue(), valueSeparator));
- sb.append(postValues);
- }
- return sb.toString();
- } else {
- return self;
- }
+ // GROOVY-11939: single-pass tokenize + render for inline and block tags.
+ return TagRenderer.render(result, links, relativeRootPath, savedRootDoc, this);
}
/**
@@ -1039,14 +934,6 @@ public class SimpleGroovyClassDoc extends SimpleGroovyAbstractableElementDoc imp
return text == null ? null : text.replace("<", "<").replace(">", ">");
}
- public static String encodeSpecialSymbols(String text) {
- return Matcher.quoteReplacement(text.replace("@", "&at;"));
- }
-
- public static String decodeSpecialSymbols(String text) {
- return text.replace("&at;", "@");
- }
-
public void setNameWithTypeArgs(String nameWithTypeArgs) {
this.nameWithTypeArgs = nameWithTypeArgs;
}
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
new file mode 100644
index 0000000000..61fa8ec61d
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
@@ -0,0 +1,448 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.codehaus.groovy.tools.groovydoc;
+
+import org.codehaus.groovy.groovydoc.GroovyRootDoc;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Single-pass tokenizer and renderer for Javadoc-style inline tags
+ * ({@code {@link ...}}, {@code {@code ...}}, {@code {@literal ...}}) and
+ * block tags ({@code @see}, {@code @param}, {@code @return}, etc.) in
+ * groovydoc text. Replaces the earlier chain of regex-based passes in
+ * {@link SimpleGroovyClassDoc#replaceTags} and provides a single extension
+ * point for new tags (GROOVY-6016 {@code {@value}}, GROOVY-3782
+ * {@code {@inheritDoc}}, GROOVY-11938 {@code {@snippet}}, GROOVY-11542
+ * Markdown reference links).
+ *
+ * <p>Output is intentionally byte-identical to the previous multi-pass
+ * implementation so the refactor is invisible in rendered docs.</p>
+ */
+final class TagRenderer {
+
+ /** Block-tag names that get merged under a single display heading. */
+ static final Map<String, String> COLLATED_TAGS = new LinkedHashMap<>();
+ static {
+ COLLATED_TAGS.put("see", "See Also");
+ COLLATED_TAGS.put("param", "Parameters");
+ COLLATED_TAGS.put("throw", "Throws");
+ COLLATED_TAGS.put("exception", "Throws");
+ COLLATED_TAGS.put("return", "Returns");
+ COLLATED_TAGS.put("since", "Since");
+ COLLATED_TAGS.put("author", "Authors");
+ COLLATED_TAGS.put("version", "Version");
+ COLLATED_TAGS.put("default", "Default");
+ // typeparam is synthesised from `@param <T> desc`
+ COLLATED_TAGS.put("typeparam", "Type Parameters");
+ }
+
+ private static final String BLOCK_PRE_KEY = "<DL><DT><B>";
+ private static final String BLOCK_POST_KEY = ":</B></DT><DD>";
+ private static final String BLOCK_VALUE_SEP = "</DD><DD>";
+ private static final String BLOCK_POST_VALUES = "</DD></DL>";
+
+ /**
+ * Rendering profile — class-level docs vs package-level docs historically
+ * produced slightly different HTML for the same tags. Captured here so one
+ * tokenizer implementation can drive both.
+ */
+ static final class Config {
+ final String codeOpen;
+ final String codeClose;
+ final boolean literalEnabled;
+ final boolean collateBlockTags;
+
+ Config(String codeOpen, String codeClose, boolean literalEnabled, boolean collateBlockTags) {
+ this.codeOpen = codeOpen;
+ this.codeClose = codeClose;
+ this.literalEnabled = literalEnabled;
+ this.collateBlockTags = collateBlockTags;
+ }
+ }
+
+ /** Config used when rendering tags in a class-level doc comment. */
+ static final Config CLASS_LEVEL = new Config("<CODE>", "</CODE>", true, true);
+
+ /**
+ * Config used when rendering tags in a package-info doc comment. Historical
+ * quirks: {@code {@code}} wraps with {@code <TT>} (a deprecated HTML tag)
+ * rather than {@code <CODE>}; {@code {@literal}} is not recognised; block
+ * tags are emitted inline rather than collated. Preserved for byte-for-byte
+ * parity with the previous {@code GroovyRootDocBuilder.replaceTags}
+ * implementation.
+ */
+ static final Config PACKAGE_LEVEL = new Config("<TT>", "</TT>", false, false);
+
+ private TagRenderer() {}
+
+ /**
+ * Render inline and block tags in {@code text}, emitting an HTML fragment.
+ * Equivalent to the previous {@code replaceTags} + {@code replaceAllTags}
+ * + {@code replaceAllTagsCollated} pipeline, collapsed into one pass.
+ */
+ static String render(String text,
+ List<LinkArgument> links,
+ String relPath,
+ GroovyRootDoc rootDoc,
+ SimpleGroovyClassDoc classDoc) {
+ return render(text, links, relPath, rootDoc, classDoc, CLASS_LEVEL);
+ }
+
+ static String render(String text,
+ List<LinkArgument> links,
+ String relPath,
+ GroovyRootDoc rootDoc,
+ SimpleGroovyClassDoc classDoc,
+ Config cfg) {
+ StringBuilder out = new StringBuilder(text.length() + 64);
+ // Whitespace preceding a block tag must be dropped (matches the
+ // prior regex's leading `\s*` before `@`). Buffer whitespace runs
+ // so we can discard them if followed by a block tag, or flush them
+ // to output otherwise.
+ StringBuilder pendingWs = new StringBuilder();
+ Map<String, List<String>> collated = new LinkedHashMap<>();
+ boolean anyBlockTag = false;
+ int i = 0;
+ int n = text.length();
+ while (i < n) {
+ char c = text.charAt(i);
+ if (c == '{' && i + 1 < n && text.charAt(i + 1) == '@') {
+ out.append(pendingWs);
+ pendingWs.setLength(0);
+ int consumed = renderInlineTagAt(text, i, out, links, relPath, rootDoc, classDoc, cfg);
+ if (consumed > 0) { i += consumed; continue; }
+ }
+ if (c == '@' && isBlockTagBoundary(text, i)) {
+ int consumed = renderBlockTagAt(text, i, out, collated, links, relPath, rootDoc, classDoc, cfg);
+ if (consumed > 0) {
+ pendingWs.setLength(0); // discard ws preceding the tag
+ anyBlockTag = true;
+ i += consumed;
+ continue;
+ }
+ }
+ if (Character.isWhitespace(c)) {
+ pendingWs.append(c);
+ } else {
+ out.append(pendingWs);
+ pendingWs.setLength(0);
+ out.append(c);
+ }
+ i++;
+ }
+ out.append(pendingWs);
+ // Package-level rendering always tacked on a trailing space (the old
+ // `self + " @endMarker"` + substring(0, len-10) pipeline produced it
+ // even when no block tags matched). Preserve for byte-for-byte parity.
+ boolean emitTrailingSpace = anyBlockTag || !cfg.collateBlockTags;
+ appendCollatedOrTrailingSpace(out, collated, emitTrailingSpace);
+ return out.toString();
+ }
+
+ // -------- inline tags --------
+
+ /**
+ * Try to parse and render an inline tag starting at {@code start}.
+ * Returns the number of characters consumed, or 0 if the position does
+ * not actually begin a well-formed inline tag (in which case the caller
+ * should emit the literal '{' and advance one character).
+ */
+ private static int renderInlineTagAt(String text, int start, StringBuilder out,
+ List<LinkArgument> links, String relPath,
+ GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc,
+ Config cfg) {
+ int nameStart = start + 2; // skip '{@'
+ int nameEnd = readTagName(text, nameStart);
+ if (nameEnd == nameStart) return 0;
+ String name = text.substring(nameStart, nameEnd);
+ // Historical behaviour: only the known inline tags are recognised.
+ // Anything else (e.g. Javadoc `{@linkplain}` or `{@inheritDoc}`) flows
+ // through as plain text so that later passes / subsequent tickets
+ // can decide how to handle it. Skipping unknown tags here preserves
+ // byte-for-byte parity with the old LINK/LITERAL/CODE regex chain.
+ if (!isKnownInlineTag(name, cfg)) return 0;
+ int bodyStart = skipWhitespace(text, nameEnd);
+ // Match the previous regex's laxness: body extends to the first '}'.
+ int close = text.indexOf('}', bodyStart);
+ if (close < 0) return 0;
+ String body = text.substring(bodyStart, close);
+ renderInlineTag(name, body, out, links, relPath, rootDoc, classDoc, cfg);
+ return close + 1 - start;
+ }
+
+ private static boolean isKnownInlineTag(String name, Config cfg) {
+ switch (name) {
+ case "link":
+ case "see":
+ case "code":
+ case "interface":
+ return true;
+ case "literal":
+ return cfg.literalEnabled;
+ default:
+ return false;
+ }
+ }
+
+ private static void renderInlineTag(String name, String body, StringBuilder out,
+ List<LinkArgument> links, String relPath,
+ GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc,
+ Config cfg) {
+ switch (name) {
+ case "interface":
+ // Historical behaviour: swallow `{@interface ...}` so Javadoc-style
+ // annotation declarations in comments don't pollute output.
+ return;
+ case "link":
+ case "see":
+ out.append(SimpleGroovyClassDoc.getDocUrl(body, false, links, relPath, rootDoc, classDoc));
+ return;
+ case "literal":
+ if (cfg.literalEnabled) {
+ out.append(SimpleGroovyClassDoc.encodeAngleBrackets(body));
+ return;
+ }
+ break; // fall through to emit verbatim
+ case "code":
+ out.append(cfg.codeOpen).append(SimpleGroovyClassDoc.encodeAngleBrackets(body)).append(cfg.codeClose);
+ return;
+ }
+ // Unknown inline tag — emit body verbatim (matches prior regex pass not matching).
+ out.append('{').append('@').append(name).append(' ').append(body).append('}');
+ }
+
+ // -------- block tags --------
+
+ /**
+ * Try to parse and render a block tag starting at {@code start}. A block
+ * tag starts at {@code '@'} that sits at the start of the text or is
+ * preceded by whitespace.
+ */
+ private static int renderBlockTagAt(String text, int start, StringBuilder out,
+ Map<String, List<String>> collated,
+ List<LinkArgument> links, String relPath,
+ GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc,
+ Config cfg) {
+ int nameStart = start + 1; // skip '@'
+ int nameEnd = readTagName(text, nameStart);
+ if (nameEnd == nameStart) return 0;
+ // Require at least one whitespace after the tag name (mirrors the old
+ // regex's `\s+` between name and body). Rejects things like
+ // `@CompileStatic(TypeCheckingMode.SKIP)` mid-sentence — those should
+ // stay as literal text, not be parsed as a block tag.
+ int n = text.length();
+ if (nameEnd >= n || !Character.isWhitespace(text.charAt(nameEnd))) return 0;
+ int bodyStart = skipWhitespace(text, nameEnd);
+ int bodyEnd = findBlockTagEnd(text, bodyStart);
+ String name = text.substring(nameStart, nameEnd);
+ // Trim trailing whitespace from the body, matching the prior regex's
+ // non-greedy `(.*?)(?=\s+@)` / " @endMarker" behaviour.
+ int trimmedEnd = bodyEnd;
+ while (trimmedEnd > bodyStart && Character.isWhitespace(text.charAt(trimmedEnd - 1))) {
+ trimmedEnd--;
+ }
+ String rawBody = text.substring(bodyStart, trimmedEnd);
+ handleBlockTag(name, rawBody, out, collated, links, relPath, rootDoc, classDoc, cfg);
+ // Advance only past the trimmed body — trailing whitespace flows back
+ // through the main loop as plain text so that any whitespace trailing
+ // the overall input (for the last block tag) is preserved verbatim
+ // before the collated block is appended. This reproduces the old
+ // " @endMarker" + substring(0, length-10) artifact exactly.
+ return trimmedEnd - start;
+ }
+
+ private static void handleBlockTag(String name, String rawBody, StringBuilder out,
+ Map<String, List<String>> collated,
+ List<LinkArgument> links, String relPath,
+ GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc,
+ Config cfg) {
+ if ("interface".equals(name)) return; // swallow, matches prior behaviour
+
+ // Block-tag bodies may embed inline tags like {@link ...}; render those
+ // now so that collation sees fully-rendered HTML.
+ String body = renderInline(rawBody, links, relPath, rootDoc, classDoc, cfg);
+
+ if (cfg.collateBlockTags) {
+ if ("see".equals(name) || "link".equals(name)) {
+ body = SimpleGroovyClassDoc.getDocUrl(body, false, links, relPath, rootDoc, classDoc);
+ } else if ("param".equals(name)) {
+ int space = body.indexOf(' ');
+ if (space >= 0) {
+ String paramName = body.substring(0, space);
+ String paramDesc = body.substring(space);
+ if (paramName.startsWith("<") && paramName.endsWith(">")) {
+ paramName = paramName.substring(1, paramName.length() - 1);
+ name = "typeparam";
+ }
+ body = "<code>" + paramName + "</code> - " + paramDesc;
+ }
+ }
+ String displayName = COLLATED_TAGS.get(name);
+ if (displayName != null) {
+ collated.computeIfAbsent(displayName, k -> new ArrayList<>()).add(body);
+ return;
+ }
+ }
+ // Non-collated (or unknown) block tag — emit inline.
+ out.append(BLOCK_PRE_KEY).append(name).append(BLOCK_POST_KEY)
+ .append(body).append(BLOCK_POST_VALUES);
+ }
+
+ /**
+ * Render inline tags only (no block-tag recognition). Used for block-tag
+ * bodies which may themselves embed {@code {@link}} / {@code {@code}} /
+ * {@code {@literal}}.
+ */
+ private static String renderInline(String text,
+ List<LinkArgument> links, String relPath,
+ GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc,
+ Config cfg) {
+ StringBuilder out = new StringBuilder(text.length());
+ int i = 0;
+ int n = text.length();
+ while (i < n) {
+ char c = text.charAt(i);
+ if (c == '{' && i + 1 < n && text.charAt(i + 1) == '@') {
+ int consumed = renderInlineTagAt(text, i, out, links, relPath, rootDoc, classDoc, cfg);
+ if (consumed > 0) { i += consumed; continue; }
+ }
+ out.append(c);
+ i++;
+ }
+ return out.toString();
+ }
+
+ private static void appendCollatedOrTrailingSpace(StringBuilder out,
+ Map<String, List<String>> collated,
+ boolean emitTrailingSpace) {
+ if (!emitTrailingSpace) return;
+ // Historical quirk: the previous implementation appended " @endMarker"
+ // to its input then stripped only 10 of those 11 chars after regex
+ // replacement, leaving a single trailing space whenever any block tag
+ // was present. Preserved here for byte-identical output.
+ out.append(' ');
+ for (Map.Entry<String, List<String>> e : collated.entrySet()) {
+ out.append(BLOCK_PRE_KEY).append(e.getKey()).append(BLOCK_POST_KEY);
+ List<String> values = e.getValue();
+ for (int j = 0; j < values.size(); j++) {
+ if (j > 0) out.append(BLOCK_VALUE_SEP);
+ out.append(values.get(j));
+ }
+ out.append(BLOCK_POST_VALUES);
+ }
+ }
+
+ // -------- scanning helpers --------
+
+ /** Matches {@code [a-zA-Z.]+} (same character class used by the prior TAG_REGEX). */
+ private static int readTagName(String text, int start) {
+ int i = start;
+ int n = text.length();
+ while (i < n) {
+ char c = text.charAt(i);
+ if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '.') {
+ i++;
+ } else {
+ break;
+ }
+ }
+ return i;
+ }
+
+ private static int skipWhitespace(String text, int start) {
+ int i = start;
+ int n = text.length();
+ while (i < n && Character.isWhitespace(text.charAt(i))) i++;
+ return i;
+ }
+
+ /**
+ * A '@' begins a block tag only if it's at text start or preceded by
+ * whitespace. The old TAG_REGEX had a laxer lookbehind ({@code \s*} —
+ * matches zero whitespace, so things like {@code {@linkplain ...}} got
+ * picked up as block tags even though the {@code '@'} was preceded by
+ * {@code '{'}). The stricter check here is a semantic improvement: a
+ * stray {@code '@'} sitting in the middle of a word or after punctuation
+ * should not be treated as a tag.
+ */
+ private static boolean isBlockTagBoundary(String text, int i) {
+ return i == 0 || Character.isWhitespace(text.charAt(i - 1));
+ }
+
+ /**
+ * Find the end of a block-tag body starting at {@code bodyStart}. The
+ * body extends up to (but not including) the whitespace preceding the
+ * next block tag (a {@code '@'} preceded by whitespace and followed by
+ * a valid tag name), or the end of the text.
+ *
+ * <p>Mirrors the lookahead {@code (?=\s+@)} in the former TAG_REGEX, with
+ * the additional guard that an {@code '@'} sitting <em>inside</em> an
+ * inline tag (e.g. {@code {@code @NotNull}}) does not terminate the block
+ * tag. The previous implementation got away without this because it
+ * replaced all inline tags before running the block-tag regex — any
+ * {@code @whatever} inside {@code {@code ...}} was already wrapped in
+ * HTML and the regex's {@code \s+@} lookahead no longer matched.</p>
+ */
+ private static int findBlockTagEnd(String text, int bodyStart) {
+ int n = text.length();
+ int i = bodyStart;
+ while (i < n) {
+ char c = text.charAt(i);
+ if (c == '{' && i + 1 < n && text.charAt(i + 1) == '@') {
+ int skipTo = skipInlineTag(text, i);
+ if (skipTo > i) { i = skipTo; continue; }
+ }
+ if (Character.isWhitespace(c)) {
+ int ws = i;
+ int afterWs = i;
+ while (afterWs < n && Character.isWhitespace(text.charAt(afterWs))) afterWs++;
+ // Only terminate the block-tag body at a well-formed next tag
+ // (`@<name>`). The old TAG_REGEX's lookahead was `\s+@` with
+ // no name check, so things like `@-files` inside a body would
+ // spuriously break it off — corrected here for semantic
+ // equivalence rather than strict byte equivalence.
+ if (afterWs < n && text.charAt(afterWs) == '@') {
+ int nameEnd = readTagName(text, afterWs + 1);
+ if (nameEnd > afterWs + 1) {
+ return ws;
+ }
+ }
+ i = afterWs;
+ } else {
+ i++;
+ }
+ }
+ return n;
+ }
+
+ /** Position past the closing '}' of an inline tag starting at {@code start},
+ * or {@code start} itself if the tag is malformed (no closing '}' or no name). */
+ private static int skipInlineTag(String text, int start) {
+ int nameStart = start + 2; // past '{@'
+ int nameEnd = readTagName(text, nameStart);
+ if (nameEnd == nameStart) return start;
+ int close = text.indexOf('}', nameEnd);
+ if (close < 0) return start;
+ return close + 1;
+ }
+}
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit c65ce62b86305eb36e4b6003b0a11d422ae07716
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Apr 20 20:13:56 2026 +1000
minor refactor: Add missing @Documented annotations + FQN fixes
---
src/main/groovy/groovy/cli/OptionField.groovy | 3 +
src/main/groovy/groovy/cli/UnparsedField.groovy | 3 +
src/main/java/groovy/lang/Grab.java | 2 +
src/main/java/groovy/lang/GrabConfig.java | 2 +
src/main/java/groovy/lang/GrabExclude.java | 2 +
src/main/java/groovy/lang/GrabResolver.java | 2 +
src/main/java/groovy/lang/Grapes.java | 2 +
src/main/java/groovy/transform/CompileStatic.java | 2 +
src/main/java/groovy/transform/NamedDelegate.java | 2 +
src/main/java/groovy/transform/Sortable.java | 2 +
src/main/java/groovy/transform/TailRecursive.java | 2 +
src/main/java/groovy/transform/TypeChecked.java | 2 +
src/main/java/groovy/transform/stc/POJO.java | 2 +
.../src/main/java/groovy/contracts/Contracted.java | 2 +
.../src/main/java/groovy/contracts/Decreases.java | 2 +
.../src/main/java/groovy/contracts/Ensures.java | 2 +
.../java/groovy/contracts/EnsuresConditions.java | 2 +
.../src/main/java/groovy/contracts/Invariant.java | 2 +
.../src/main/java/groovy/contracts/Invariants.java | 2 +
.../src/main/java/groovy/contracts/Modifies.java | 2 +
.../java/groovy/contracts/ModifiesConditions.java | 2 +
.../src/main/java/groovy/contracts/Requires.java | 2 +
.../java/groovy/contracts/RequiresConditions.java | 2 +
.../org/apache/groovy/antlr/GroovydocVisitor.java | 25 ++++----
.../groovy/tools/groovydoc/TagRenderer.java | 33 ++++++-----
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 67 ++++++++++++----------
26 files changed, 120 insertions(+), 53 deletions(-)
diff --git a/src/main/groovy/groovy/cli/OptionField.groovy b/src/main/groovy/groovy/cli/OptionField.groovy
index 69cc1f5dad..66f59bfb27 100644
--- a/src/main/groovy/groovy/cli/OptionField.groovy
+++ b/src/main/groovy/groovy/cli/OptionField.groovy
@@ -21,6 +21,9 @@ package groovy.cli
import groovy.transform.AnnotationCollector
import groovy.transform.Field
+import java.lang.annotation.Documented
+
+@Documented
@Option
@Field
@AnnotationCollector
diff --git a/src/main/groovy/groovy/cli/UnparsedField.groovy b/src/main/groovy/groovy/cli/UnparsedField.groovy
index b1854316b0..c028452da4 100644
--- a/src/main/groovy/groovy/cli/UnparsedField.groovy
+++ b/src/main/groovy/groovy/cli/UnparsedField.groovy
@@ -21,6 +21,9 @@ package groovy.cli
import groovy.transform.AnnotationCollector
import groovy.transform.Field
+import java.lang.annotation.Documented
+
+@Documented
@Unparsed
@Field
@AnnotationCollector
diff --git a/src/main/java/groovy/lang/Grab.java b/src/main/java/groovy/lang/Grab.java
index d7800b8f7d..bd1c9e1695 100644
--- a/src/main/java/groovy/lang/Grab.java
+++ b/src/main/java/groovy/lang/Grab.java
@@ -21,6 +21,7 @@ package groovy.lang;
import groovy.lang.annotation.ExtendedElementType;
import groovy.lang.annotation.ExtendedTarget;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -51,6 +52,7 @@ import java.lang.annotation.Target;
* how to customise artifact resolution etc., can be found on the Grape documentation page:
* <a href="http://groovy-lang.org/grape.html">http://groovy-lang.org/grape.html</a>.
*/
+@Documented
@Retention(RetentionPolicy.SOURCE)
@Target({
ElementType.CONSTRUCTOR,
diff --git a/src/main/java/groovy/lang/GrabConfig.java b/src/main/java/groovy/lang/GrabConfig.java
index ec3ab58204..1dc883b59a 100644
--- a/src/main/java/groovy/lang/GrabConfig.java
+++ b/src/main/java/groovy/lang/GrabConfig.java
@@ -21,6 +21,7 @@ package groovy.lang;
import groovy.lang.annotation.ExtendedElementType;
import groovy.lang.annotation.ExtendedTarget;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -73,6 +74,7 @@ import java.lang.annotation.Target;
* Further information about customising grape behavior can be found on the Grape documentation page:
* <a href="http://groovy-lang.org/grape.html">http://groovy-lang.org/grape.html</a>.
*/
+@Documented
@Retention(RetentionPolicy.SOURCE)
@Target({
ElementType.CONSTRUCTOR,
diff --git a/src/main/java/groovy/lang/GrabExclude.java b/src/main/java/groovy/lang/GrabExclude.java
index 91d4364be1..1eeba3818c 100644
--- a/src/main/java/groovy/lang/GrabExclude.java
+++ b/src/main/java/groovy/lang/GrabExclude.java
@@ -21,6 +21,7 @@ package groovy.lang;
import groovy.lang.annotation.ExtendedElementType;
import groovy.lang.annotation.ExtendedTarget;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -36,6 +37,7 @@ import java.lang.annotation.Target;
* Further information about customising grape behavior can be found on the Grape documentation page:
* <a href="http://groovy-lang.org/grape.html">http://groovy-lang.org/grape.html</a>.
*/
+@Documented
@Retention(RetentionPolicy.SOURCE)
@Target({
ElementType.CONSTRUCTOR,
diff --git a/src/main/java/groovy/lang/GrabResolver.java b/src/main/java/groovy/lang/GrabResolver.java
index 1e979c0ba2..80594d380b 100644
--- a/src/main/java/groovy/lang/GrabResolver.java
+++ b/src/main/java/groovy/lang/GrabResolver.java
@@ -21,6 +21,7 @@ package groovy.lang;
import groovy.lang.annotation.ExtendedElementType;
import groovy.lang.annotation.ExtendedTarget;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -46,6 +47,7 @@ import java.lang.annotation.Target;
* Further information about customising grape behavior can be found on the Grape documentation page:
* <a href="http://groovy-lang.org/grape.html">http://groovy-lang.org/grape.html</a>.
*/
+@Documented
@Retention(RetentionPolicy.SOURCE)
@Target({
ElementType.CONSTRUCTOR,
diff --git a/src/main/java/groovy/lang/Grapes.java b/src/main/java/groovy/lang/Grapes.java
index d13151c2eb..bdae9ed27b 100644
--- a/src/main/java/groovy/lang/Grapes.java
+++ b/src/main/java/groovy/lang/Grapes.java
@@ -21,6 +21,7 @@ package groovy.lang;
import groovy.lang.annotation.ExtendedElementType;
import groovy.lang.annotation.ExtendedTarget;
+import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -63,6 +64,7 @@ import java.lang.annotation.RetentionPolicy;
* It is also sometimes also useful to use {@code @GrabConfig} to further adjust how dependencies
* are grabbed. See {@code @GrabConfig} for further information.
*/
+@Documented
@Retention(RetentionPolicy.SOURCE)
@ExtendedTarget(ExtendedElementType.IMPORT)
public @interface Grapes {
diff --git a/src/main/java/groovy/transform/CompileStatic.java b/src/main/java/groovy/transform/CompileStatic.java
index 746902db0a..9f71838041 100644
--- a/src/main/java/groovy/transform/CompileStatic.java
+++ b/src/main/java/groovy/transform/CompileStatic.java
@@ -20,6 +20,7 @@ package groovy.transform;
import org.codehaus.groovy.transform.GroovyASTTransformationClass;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -42,6 +43,7 @@ import java.lang.annotation.Target;
* @see CompileDynamic
* @since 2.0.0
*/
+@Documented
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.TYPE,ElementType.METHOD,ElementType.CONSTRUCTOR})
@GroovyASTTransformationClass("org.codehaus.groovy.transform.sc.StaticCompileTransformation")
diff --git a/src/main/java/groovy/transform/NamedDelegate.java b/src/main/java/groovy/transform/NamedDelegate.java
index e9a4489d5f..1cec8165e6 100644
--- a/src/main/java/groovy/transform/NamedDelegate.java
+++ b/src/main/java/groovy/transform/NamedDelegate.java
@@ -18,6 +18,7 @@
*/
package groovy.transform;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -30,6 +31,7 @@ import java.lang.annotation.Target;
*
* @since 2.5.0
*/
+@Documented
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.PARAMETER)
public @interface NamedDelegate {
diff --git a/src/main/java/groovy/transform/Sortable.java b/src/main/java/groovy/transform/Sortable.java
index e6b1e6ec7a..52cfcd7c59 100644
--- a/src/main/java/groovy/transform/Sortable.java
+++ b/src/main/java/groovy/transform/Sortable.java
@@ -20,6 +20,7 @@ package groovy.transform;
import org.codehaus.groovy.transform.GroovyASTTransformationClass;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -150,6 +151,7 @@ import java.lang.annotation.Target;
*
* </pre>
*/
+@Documented
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
@GroovyASTTransformationClass("org.codehaus.groovy.transform.SortableASTTransformation")
diff --git a/src/main/java/groovy/transform/TailRecursive.java b/src/main/java/groovy/transform/TailRecursive.java
index 537d90a8ac..de343d5f90 100644
--- a/src/main/java/groovy/transform/TailRecursive.java
+++ b/src/main/java/groovy/transform/TailRecursive.java
@@ -20,6 +20,7 @@ package groovy.transform;
import org.codehaus.groovy.transform.GroovyASTTransformationClass;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -79,6 +80,7 @@ import java.lang.annotation.Target;
*
* @since 2.3
*/
+@Documented
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.METHOD)
@GroovyASTTransformationClass({"org.codehaus.groovy.transform.tailrec.TailRecursiveASTTransformation"})
diff --git a/src/main/java/groovy/transform/TypeChecked.java b/src/main/java/groovy/transform/TypeChecked.java
index 23e6b962e5..cf96fc6e90 100644
--- a/src/main/java/groovy/transform/TypeChecked.java
+++ b/src/main/java/groovy/transform/TypeChecked.java
@@ -20,6 +20,7 @@ package groovy.transform;
import org.codehaus.groovy.transform.GroovyASTTransformationClass;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -30,6 +31,7 @@ import java.lang.annotation.Target;
*
* @since 2.0.0
*/
+@Documented
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR})
@GroovyASTTransformationClass("org.codehaus.groovy.transform.StaticTypesTransformation")
diff --git a/src/main/java/groovy/transform/stc/POJO.java b/src/main/java/groovy/transform/stc/POJO.java
index 34c82b77ad..a6f632a5f3 100644
--- a/src/main/java/groovy/transform/stc/POJO.java
+++ b/src/main/java/groovy/transform/stc/POJO.java
@@ -20,6 +20,7 @@ package groovy.transform.stc;
import org.apache.groovy.lang.annotation.Incubating;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -30,6 +31,7 @@ import java.lang.annotation.Target;
*
* @since 4.0.0
*/
+@Documented
@Incubating
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
diff --git a/subprojects/groovy-contracts/src/main/java/groovy/contracts/Contracted.java b/subprojects/groovy-contracts/src/main/java/groovy/contracts/Contracted.java
index 050a99ea75..06204f1ffc 100644
--- a/subprojects/groovy-contracts/src/main/java/groovy/contracts/Contracted.java
+++ b/subprojects/groovy-contracts/src/main/java/groovy/contracts/Contracted.java
@@ -18,6 +18,7 @@
*/
package groovy.contracts;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -35,6 +36,7 @@ import java.lang.annotation.Target;
* import groovy.contracts.*
* </pre>
*/
+@Documented
@Target({ElementType.PACKAGE, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Contracted {
diff --git a/subprojects/groovy-contracts/src/main/java/groovy/contracts/Decreases.java b/subprojects/groovy-contracts/src/main/java/groovy/contracts/Decreases.java
index dace842070..96fc9d484f 100644
--- a/subprojects/groovy-contracts/src/main/java/groovy/contracts/Decreases.java
+++ b/subprojects/groovy-contracts/src/main/java/groovy/contracts/Decreases.java
@@ -23,6 +23,7 @@ import groovy.lang.annotation.ExtendedTarget;
import org.apache.groovy.lang.annotation.Incubating;
import org.codehaus.groovy.transform.GroovyASTTransformationClass;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -53,6 +54,7 @@ import java.lang.annotation.Target;
* @since 6.0.0
* @see Invariant
*/
+@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@ExtendedTarget(ExtendedElementType.LOOP)
diff --git a/subprojects/groovy-contracts/src/main/java/groovy/contracts/Ensures.java b/subprojects/groovy-contracts/src/main/java/groovy/contracts/Ensures.java
index 930a403097..897678eb15 100644
--- a/subprojects/groovy-contracts/src/main/java/groovy/contracts/Ensures.java
+++ b/subprojects/groovy-contracts/src/main/java/groovy/contracts/Ensures.java
@@ -23,6 +23,7 @@ import org.apache.groovy.contracts.annotations.meta.Postcondition;
import org.apache.groovy.contracts.common.impl.EnsuresAnnotationProcessor;
import org.apache.groovy.lang.annotation.Incubating;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
@@ -77,6 +78,7 @@ import java.lang.annotation.Target;
* </pre>
* </p>
*/
+@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
@Incubating
diff --git a/subprojects/groovy-contracts/src/main/java/groovy/contracts/EnsuresConditions.java b/subprojects/groovy-contracts/src/main/java/groovy/contracts/EnsuresConditions.java
index 8e5a21210d..3d83d7bbc5 100644
--- a/subprojects/groovy-contracts/src/main/java/groovy/contracts/EnsuresConditions.java
+++ b/subprojects/groovy-contracts/src/main/java/groovy/contracts/EnsuresConditions.java
@@ -20,6 +20,7 @@ package groovy.contracts;
import org.apache.groovy.lang.annotation.Incubating;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -28,6 +29,7 @@ import java.lang.annotation.Target;
/**
* Represents multiple postconditions.
*/
+@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
@Incubating
diff --git a/subprojects/groovy-contracts/src/main/java/groovy/contracts/Invariant.java b/subprojects/groovy-contracts/src/main/java/groovy/contracts/Invariant.java
index bdc0f2fff1..051e126e7b 100644
--- a/subprojects/groovy-contracts/src/main/java/groovy/contracts/Invariant.java
+++ b/subprojects/groovy-contracts/src/main/java/groovy/contracts/Invariant.java
@@ -26,6 +26,7 @@ import org.apache.groovy.contracts.common.impl.ClassInvariantAnnotationProcessor
import org.apache.groovy.lang.annotation.Incubating;
import org.codehaus.groovy.transform.GroovyASTTransformationClass;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
@@ -61,6 +62,7 @@ import java.lang.annotation.Target;
* with the actual class's invariant (by using a logical AND).
* </p>
*/
+@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Incubating
diff --git a/subprojects/groovy-contracts/src/main/java/groovy/contracts/Invariants.java b/subprojects/groovy-contracts/src/main/java/groovy/contracts/Invariants.java
index ac37f83b60..01694ae5bf 100644
--- a/subprojects/groovy-contracts/src/main/java/groovy/contracts/Invariants.java
+++ b/subprojects/groovy-contracts/src/main/java/groovy/contracts/Invariants.java
@@ -20,6 +20,7 @@ package groovy.contracts;
import org.apache.groovy.lang.annotation.Incubating;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -28,6 +29,7 @@ import java.lang.annotation.Target;
/**
* Represents multiple invariants
*/
+@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Incubating
diff --git a/subprojects/groovy-contracts/src/main/java/groovy/contracts/Modifies.java b/subprojects/groovy-contracts/src/main/java/groovy/contracts/Modifies.java
index 694d0f8a84..95e70ec279 100644
--- a/subprojects/groovy-contracts/src/main/java/groovy/contracts/Modifies.java
+++ b/subprojects/groovy-contracts/src/main/java/groovy/contracts/Modifies.java
@@ -21,6 +21,7 @@ package groovy.contracts;
import org.apache.groovy.lang.annotation.Incubating;
import org.codehaus.groovy.transform.GroovyASTTransformationClass;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
@@ -59,6 +60,7 @@ import java.lang.annotation.Target;
* @see Ensures
* @see Requires
*/
+@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
@Incubating
diff --git a/subprojects/groovy-contracts/src/main/java/groovy/contracts/ModifiesConditions.java b/subprojects/groovy-contracts/src/main/java/groovy/contracts/ModifiesConditions.java
index 8cc4d86595..0542c0304f 100644
--- a/subprojects/groovy-contracts/src/main/java/groovy/contracts/ModifiesConditions.java
+++ b/subprojects/groovy-contracts/src/main/java/groovy/contracts/ModifiesConditions.java
@@ -20,6 +20,7 @@ package groovy.contracts;
import org.apache.groovy.lang.annotation.Incubating;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -31,6 +32,7 @@ import java.lang.annotation.Target;
* @since 6.0.0
* @see Modifies
*/
+@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
@Incubating
diff --git a/subprojects/groovy-contracts/src/main/java/groovy/contracts/Requires.java b/subprojects/groovy-contracts/src/main/java/groovy/contracts/Requires.java
index 5e4a276943..74da96e290 100644
--- a/subprojects/groovy-contracts/src/main/java/groovy/contracts/Requires.java
+++ b/subprojects/groovy-contracts/src/main/java/groovy/contracts/Requires.java
@@ -23,6 +23,7 @@ import org.apache.groovy.contracts.annotations.meta.Precondition;
import org.apache.groovy.contracts.common.impl.RequiresAnnotationProcessor;
import org.apache.groovy.lang.annotation.Incubating;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
@@ -54,6 +55,7 @@ import java.lang.annotation.Target;
* </pre>
* </p>
*/
+@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
@Incubating
diff --git a/subprojects/groovy-contracts/src/main/java/groovy/contracts/RequiresConditions.java b/subprojects/groovy-contracts/src/main/java/groovy/contracts/RequiresConditions.java
index 0ff81b3332..c7e5a45ad2 100644
--- a/subprojects/groovy-contracts/src/main/java/groovy/contracts/RequiresConditions.java
+++ b/subprojects/groovy-contracts/src/main/java/groovy/contracts/RequiresConditions.java
@@ -20,6 +20,7 @@ package groovy.contracts;
import org.apache.groovy.lang.annotation.Incubating;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -28,6 +29,7 @@ import java.lang.annotation.Target;
/**
* Represents multiple preconditions.
*/
+@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
@Incubating
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java b/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
index 17f426bb56..9f16e32c1c 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
@@ -31,7 +31,9 @@ import org.codehaus.groovy.ast.InnerClassNode;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.ast.Parameter;
import org.codehaus.groovy.ast.PropertyNode;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.DeclarationExpression;
+import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.VariableExpression;
import org.codehaus.groovy.control.ResolveVisitor;
import org.codehaus.groovy.control.SourceUnit;
@@ -51,6 +53,9 @@ import org.codehaus.groovy.tools.groovydoc.SimpleGroovyParameter;
import org.codehaus.groovy.tools.groovydoc.SimpleGroovyProgramElementDoc;
import org.codehaus.groovy.tools.groovydoc.SimpleGroovyType;
+import java.io.IOException;
+import java.io.Reader;
+import java.lang.annotation.Documented;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Iterator;
@@ -62,6 +67,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.apache.groovy.ast.tools.AnnotatedNodeUtils.deemedInternal;
+import static org.apache.groovy.ast.tools.ExpressionUtils.transformInlineConstants;
import static org.codehaus.groovy.transform.trait.Traits.isTrait;
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
import static org.objectweb.asm.Opcodes.ACC_PROTECTED;
@@ -240,13 +246,13 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
*/
private String extractLeadingScriptDocContent(ClassNode scriptNode) {
String src;
- try (java.io.Reader r = unit.getSource().getReader()) {
+ try (Reader r = unit.getSource().getReader()) {
StringBuilder sb = new StringBuilder();
char[] buf = new char[8192];
int n;
while ((n = r.read(buf)) > 0) sb.append(buf, 0, n);
src = sb.toString();
- } catch (java.io.IOException e) {
+ } catch (IOException e) {
return "";
}
int i = 0, n = src.length();
@@ -360,7 +366,7 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
try {
Class<?> c = Class.forName(fqn);
if (!c.isAnnotation()) return true;
- return c.isAnnotationPresent(java.lang.annotation.Documented.class);
+ return c.isAnnotationPresent(Documented.class);
} catch (Throwable t) {
return true;
}
@@ -558,20 +564,19 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
// to other static-final constants, and casts — not just bare literals.
// Javadoc's convention is to re-quote strings/chars;
// ConstantExpression.getText() returns the raw value without quotes.
- org.codehaus.groovy.ast.expr.Expression init = node.getInitialExpression();
+ Expression init = node.getInitialExpression();
if (init != null) {
// Typed variant does numeric arithmetic folding but needs the
// target type to equal ClassHelper.STRING_TYPE for string concat,
// which isn't always the case at CONVERSION phase. Type-less
// variant handles string concat via isStringType on operand types.
// Try both; take whichever yields a ConstantExpression.
- org.codehaus.groovy.ast.expr.Expression folded =
- org.apache.groovy.ast.tools.ExpressionUtils.transformInlineConstants(init, node.getType());
- if (!(folded instanceof org.codehaus.groovy.ast.expr.ConstantExpression)) {
- folded = org.apache.groovy.ast.tools.ExpressionUtils.transformInlineConstants(init);
+ Expression folded = transformInlineConstants(init, node.getType());
+ if (!(folded instanceof ConstantExpression)) {
+ folded = transformInlineConstants(init);
}
- if (folded instanceof org.codehaus.groovy.ast.expr.ConstantExpression) {
- Object value = ((org.codehaus.groovy.ast.expr.ConstantExpression) folded).getValue();
+ if (folded instanceof ConstantExpression) {
+ Object value = ((ConstantExpression) folded).getValue();
fieldDoc.setConstantValueExpression(formatConstantValue(value));
}
}
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
index afc5c9acf2..add9fbb849 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
@@ -24,10 +24,17 @@ import org.codehaus.groovy.groovydoc.GroovyMethodDoc;
import org.codehaus.groovy.groovydoc.GroovyParameter;
import org.codehaus.groovy.groovydoc.GroovyRootDoc;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.ArrayList;
+import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
+import java.util.regex.Pattern;
/**
* Single-pass tokenizer and renderer for Javadoc-style inline tags and
@@ -278,7 +285,7 @@ final class TagRenderer {
int n = text.length();
int i = skipWhitespace(text, nameEnd);
- java.util.Map<String, String> attrs = new LinkedHashMap<>();
+ Map<String, String> attrs = new LinkedHashMap<>();
while (i < n) {
char c = text.charAt(i);
if (c == ':' || c == '}') break;
@@ -385,11 +392,11 @@ final class TagRenderer {
int lastSlash = full.lastIndexOf('/');
String pkgPath = lastSlash >= 0 ? full.substring(0, lastSlash) : "";
for (String sourcepath : sourcepaths) {
- java.nio.file.Path path = java.nio.file.Paths.get(sourcepath, pkgPath, "snippet-files", fileName);
- if (java.nio.file.Files.isRegularFile(path)) {
+ Path path = Paths.get(sourcepath, pkgPath, "snippet-files", fileName);
+ if (Files.isRegularFile(path)) {
try {
- return java.nio.file.Files.readString(path);
- } catch (java.io.IOException e) {
+ return Files.readString(path);
+ } catch (IOException e) {
return null;
}
}
@@ -408,10 +415,10 @@ final class TagRenderer {
String[] lines = source.split("\n", -1);
int startIdx = -1;
int endIdx = -1;
- java.util.regex.Pattern startPat = java.util.regex.Pattern.compile(
- "//\\s*@start\\b[^\\n]*\\bregion\\s*=\\s*(['\"]?)" + java.util.regex.Pattern.quote(regionName) + "\\1");
- java.util.regex.Pattern endPat = java.util.regex.Pattern.compile(
- "//\\s*@end\\b(?:[^\\n]*\\bregion\\s*=\\s*(['\"]?)" + java.util.regex.Pattern.quote(regionName) + "\\1)?");
+ Pattern startPat = Pattern.compile(
+ "//\\s*@start\\b[^\\n]*\\bregion\\s*=\\s*(['\"]?)" + Pattern.quote(regionName) + "\\1");
+ Pattern endPat = Pattern.compile(
+ "//\\s*@end\\b(?:[^\\n]*\\bregion\\s*=\\s*(['\"]?)" + Pattern.quote(regionName) + "\\1)?");
for (int k = 0; k < lines.length; k++) {
if (startIdx < 0 && startPat.matcher(lines[k]).find()) {
startIdx = k + 1;
@@ -525,7 +532,7 @@ final class TagRenderer {
case "inheritDoc": {
// GROOVY-3782: only meaningful on a method; pull the parent
// method's already-rendered comment text into this position.
- String inherited = resolveInheritDoc(memberDoc, classDoc, new java.util.HashSet<>());
+ String inherited = resolveInheritDoc(memberDoc, classDoc, new HashSet<>());
if (inherited != null) {
out.append(inherited);
return;
@@ -564,13 +571,13 @@ final class TagRenderer {
*/
private static String resolveInheritDoc(GroovyMemberDoc memberDoc,
SimpleGroovyClassDoc classDoc,
- java.util.Set<GroovyMethodDoc> visited) {
+ Set<GroovyMethodDoc> visited) {
if (!(memberDoc instanceof GroovyMethodDoc)) return null;
GroovyMethodDoc thisMethod = (GroovyMethodDoc) memberDoc;
if (!visited.add(thisMethod)) return null; // cycle
if (classDoc == null) return null;
- GroovyMethodDoc parent = findInheritedMethod(thisMethod, classDoc, new java.util.HashSet<>());
+ GroovyMethodDoc parent = findInheritedMethod(thisMethod, classDoc, new HashSet<>());
if (parent == null) return null;
// Calling commentText() on the parent runs it through the full
// replaceTags pipeline — so any {@inheritDoc} nested in the parent
@@ -582,7 +589,7 @@ final class TagRenderer {
private static GroovyMethodDoc findInheritedMethod(GroovyMethodDoc thisMethod,
GroovyClassDoc startingClass,
- java.util.Set<GroovyClassDoc> seen) {
+ Set<GroovyClassDoc> seen) {
// Javadoc's search order: superclass chain first, then interfaces.
for (GroovyClassDoc sup = startingClass.superclass(); sup != null; sup = sup.superclass()) {
if (!seen.add(sup)) break;
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index 8a267ff53d..c54900cf7e 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -27,14 +27,21 @@ import org.codehaus.groovy.groovydoc.GroovyRootDoc;
import org.codehaus.groovy.runtime.StringGroovyMethods;
import org.codehaus.groovy.tools.groovydoc.gstringTemplates.GroovyDocTemplateInfo;
+import java.io.IOException;
import java.nio.charset.Charset;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Comparator;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
+import java.util.stream.Stream;
public class GroovyDocToolTest extends GroovyTestCase {
private static final String MOCK_DIR = "mock/doc";
@@ -205,10 +212,10 @@ public class GroovyDocToolTest extends GroovyTestCase {
// Synthesise a class on the fly that uses {@snippet file=... region=...}
// Actually, just use a testfile in src/test/groovy that we add to sourcepath.
// Here we reuse a class with an inline doc reference via the resource-dir.
- java.nio.file.Path tmp = java.nio.file.Files.createTempDirectory("snippet-region-");
- java.nio.file.Path pkgDir = tmp.resolve(pkg);
- java.nio.file.Files.createDirectories(pkgDir);
- java.nio.file.Files.writeString(pkgDir.resolve("RegionClass.groovy"),
+ Path tmp = Files.createTempDirectory("snippet-region-");
+ Path pkgDir = tmp.resolve(pkg);
+ Files.createDirectories(pkgDir);
+ Files.writeString(pkgDir.resolve("RegionClass.groovy"),
"/*\n * Licensed to the Apache Software Foundation (ASF) under one\n" +
" * or more contributor license agreements. See the NOTICE file\n" +
" * distributed with this work for additional information\n" +
@@ -225,16 +232,16 @@ public class GroovyDocToolTest extends GroovyTestCase {
" */\n" +
"class RegionClass {}\n");
// Symlink/copy the snippet-files dir from fixture into the tmp tree.
- java.nio.file.Path srcSnippetDir = java.nio.file.Paths.get(
+ Path srcSnippetDir = Paths.get(
"src/test/resources/docfiles-fixture", pkg, "snippet-files");
- java.nio.file.Path dstSnippetDir = pkgDir.resolve("snippet-files");
- java.nio.file.Files.createDirectories(dstSnippetDir);
- try (java.util.stream.Stream<java.nio.file.Path> s = java.nio.file.Files.walk(srcSnippetDir)) {
- s.filter(java.nio.file.Files::isRegularFile).forEach(f -> {
+ Path dstSnippetDir = pkgDir.resolve("snippet-files");
+ Files.createDirectories(dstSnippetDir);
+ try (Stream<Path> s = Files.walk(srcSnippetDir)) {
+ s.filter(Files::isRegularFile).forEach(f -> {
try {
- java.nio.file.Files.copy(f, dstSnippetDir.resolve(f.getFileName()),
- java.nio.file.StandardCopyOption.REPLACE_EXISTING);
- } catch (java.io.IOException e) { throw new RuntimeException(e); }
+ Files.copy(f, dstSnippetDir.resolve(f.getFileName()),
+ StandardCopyOption.REPLACE_EXISTING);
+ } catch (IOException e) { throw new RuntimeException(e); }
});
}
@@ -260,9 +267,9 @@ public class GroovyDocToolTest extends GroovyTestCase {
assertFalse("Should not include 'def teardown' (outside region) in:\n" + doc,
doc.contains("def teardown()"));
} finally {
- try (java.util.stream.Stream<java.nio.file.Path> s = java.nio.file.Files.walk(tmp)) {
- s.sorted(java.util.Comparator.reverseOrder())
- .forEach(p -> { try { java.nio.file.Files.delete(p); } catch (java.io.IOException ignore) {} });
+ try (Stream<Path> s = Files.walk(tmp)) {
+ s.sorted(Comparator.reverseOrder())
+ .forEach(p -> { try { Files.delete(p); } catch (IOException ignore) {} });
}
}
}
@@ -444,7 +451,7 @@ public class GroovyDocToolTest extends GroovyTestCase {
String fixtureSourcePath = "src/test/resources/docfiles-fixture";
String pkg = "org/codehaus/groovy/tools/groovydoc/testfiles/docfiles";
- java.nio.file.Path tmpOut = java.nio.file.Files.createTempDirectory("groovydoc-docfiles-");
+ Path tmpOut = Files.createTempDirectory("groovydoc-docfiles-");
try {
GroovyDocTool tool = new GroovyDocTool(
new FileSystemResourceManager("src/main/resources"),
@@ -457,33 +464,33 @@ public class GroovyDocToolTest extends GroovyTestCase {
tool.add(List.of(pkg + "/HasDocFiles.groovy"));
tool.renderToOutput(new FileOutputTool(), tmpOut.toString());
- java.nio.file.Path docFilesSample = tmpOut.resolve(pkg + "/doc-files/sample.html");
- java.nio.file.Path docFilesNested = tmpOut.resolve(pkg + "/doc-files/sub/nested.txt");
- java.nio.file.Path snippetFile = tmpOut.resolve(pkg + "/snippet-files/Example.groovy");
+ Path docFilesSample = tmpOut.resolve(pkg + "/doc-files/sample.html");
+ Path docFilesNested = tmpOut.resolve(pkg + "/doc-files/sub/nested.txt");
+ Path snippetFile = tmpOut.resolve(pkg + "/snippet-files/Example.groovy");
assertTrue("Expected doc-files/sample.html to be copied, not found at " + docFilesSample,
- java.nio.file.Files.isRegularFile(docFilesSample));
+ Files.isRegularFile(docFilesSample));
assertTrue("Expected doc-files/sub/nested.txt (nested subdir) to be copied, not found at " + docFilesNested,
- java.nio.file.Files.isRegularFile(docFilesNested));
+ Files.isRegularFile(docFilesNested));
assertTrue("Expected snippet-files/Example.groovy to be copied, not found at " + snippetFile,
- java.nio.file.Files.isRegularFile(snippetFile));
+ Files.isRegularFile(snippetFile));
- String sampleContent = java.nio.file.Files.readString(docFilesSample);
+ String sampleContent = Files.readString(docFilesSample);
assertTrue("doc-files/sample.html content mismatch", sampleContent.contains("GROOVY-5986 sample doc-files content"));
- String nestedContent = java.nio.file.Files.readString(docFilesNested);
+ String nestedContent = Files.readString(docFilesNested);
assertTrue("doc-files/sub/nested.txt content mismatch", nestedContent.contains("nested doc-files content"));
- String snippetContent = java.nio.file.Files.readString(snippetFile);
+ String snippetContent = Files.readString(snippetFile);
assertTrue("snippet-files/Example.groovy content mismatch", snippetContent.contains("hello from Example"));
} finally {
deleteRecursively(tmpOut);
}
}
- private static void deleteRecursively(java.nio.file.Path root) throws java.io.IOException {
- if (!java.nio.file.Files.exists(root)) return;
- try (java.util.stream.Stream<java.nio.file.Path> stream = java.nio.file.Files.walk(root)) {
- stream.sorted(java.util.Comparator.reverseOrder()).forEach(p -> {
- try { java.nio.file.Files.delete(p); } catch (java.io.IOException ignored) {}
+ private static void deleteRecursively(Path root) throws IOException {
+ if (!Files.exists(root)) return;
+ try (Stream<Path> stream = Files.walk(root)) {
+ stream.sorted(Comparator.reverseOrder()).forEach(p -> {
+ try { Files.delete(p); } catch (IOException ignored) {}
});
}
}
(groovy) 23/34: GROOVY-11938: {@snippet} per JEP 413 (syntax highlighting assets)
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 2b26cbf340efe70451095f251277126e7e806252
Author: Paul King <pa...@asert.com.au>
AuthorDate: Tue Apr 21 00:09:41 2026 +1000
GROOVY-11938: {@snippet} per JEP 413 (syntax highlighting assets)
---
.../gstringTemplates/topLevel/prism-csv.min.js | 1 +
.../gstringTemplates/topLevel/prism-dark.min.css | 1 +
.../gstringTemplates/topLevel/prism-groovy.min.js | 1 +
.../gstringTemplates/topLevel/prism-java.min.js | 1 +
.../topLevel/prism-javadoclike.min.js | 1 +
.../topLevel/prism-javascript.min.js | 1 +
.../gstringTemplates/topLevel/prism-json.min.js | 1 +
.../topLevel/prism-markdown.min.js | 1 +
.../topLevel/prism-properties.min.js | 1 +
.../gstringTemplates/topLevel/prism-regex.min.js | 1 +
.../gstringTemplates/topLevel/prism-sql.min.js | 1 +
.../gstringTemplates/topLevel/prism-toml.min.js | 1 +
.../gstringTemplates/topLevel/prism-xml-doc.min.js | 1 +
.../gstringTemplates/topLevel/prism-yaml.min.js | 1 +
.../groovydoc/gstringTemplates/topLevel/prism.js | 1946 ++++++++++++++++++++
.../gstringTemplates/topLevel/prism.min.css | 1 +
16 files changed, 1961 insertions(+)
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-csv.min.js b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-csv.min.js
new file mode 100644
index 0000000000..259e1da569
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-csv.min.js
@@ -0,0 +1 @@
+Prism.languages.csv={value:/[^\r\n,"]+|"(?:[^"]|"")*"(?!")/,punctuation:/,/};
\ No newline at end of file
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-dark.min.css b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-dark.min.css
new file mode 100644
index 0000000000..e592b5b769
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-dark.min.css
@@ -0,0 +1 @@
+code[class*=language-],pre[class*=language-]{color:#fff;background:0 0;text-shadow:0 -.1em .2em #000;font-family:Consolas,Monaco,'Andale Mono','Ubuntu Mono',monospace;font-size:1em;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}@media print{code[class*=language-],pre[class*=language-]{text-shadow:none}}:not(pre)>code[class*= [...]
\ No newline at end of file
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-groovy.min.js b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-groovy.min.js
new file mode 100644
index 0000000000..2242f9f61c
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-groovy.min.js
@@ -0,0 +1 @@
+!function(e){var n={pattern:/((?:^|[^\\$])(?:\\{2})*)\$(?:\w+|\{[^{}]*\})/,lookbehind:!0,inside:{"interpolation-punctuation":{pattern:/^\$\{?|\}$/,alias:"punctuation"},expression:{pattern:/[\s\S]+/,inside:null}}};e.languages.groovy=e.languages.extend("clike",{string:{pattern:/'''(?:[^\\]|\\[\s\S])*?'''|'(?:\\.|[^\\'\r\n])*'/,greedy:!0},keyword:/\b(?:abstract|as|assert|boolean|break|byte|case|catch|char|class|const|continue|def|default|do|double|else|enum|extends|final|finally|float|for|g [...]
\ No newline at end of file
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-java.min.js b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-java.min.js
new file mode 100644
index 0000000000..9b90cf3cc3
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-java.min.js
@@ -0,0 +1 @@
+!function(e){var n=/\b(?:abstract|assert|boolean|break|byte|case|catch|char|class|const|continue|default|do|double|else|enum|exports|extends|final|finally|float|for|goto|if|implements|import|instanceof|int|interface|long|module|native|new|non-sealed|null|open|opens|package|permits|private|protected|provides|public|record(?!\s*[(){}[\]<>=%~.:,;?+\-*/&|^])|requires|return|sealed|short|static|strictfp|super|switch|synchronized|this|throw|throws|to|transient|transitive|try|uses|var|void|vola [...]
\ No newline at end of file
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-javadoclike.min.js b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-javadoclike.min.js
new file mode 100644
index 0000000000..429dd491ea
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-javadoclike.min.js
@@ -0,0 +1 @@
+!function(a){var e=a.languages.javadoclike={parameter:{pattern:/(^[\t ]*(?:\/{3}|\*|\/\*\*)\s*@(?:arg|arguments|param)\s+)\w+/m,lookbehind:!0},keyword:{pattern:/(^[\t ]*(?:\/{3}|\*|\/\*\*)\s*|\{)@[a-z][a-zA-Z-]+\b/m,lookbehind:!0},punctuation:/[{}]/};Object.defineProperty(e,"addSupport",{value:function(e,n){"string"==typeof e&&(e=[e]),e.forEach((function(e){!function(e,n){var t="doc-comment",r=a.languages[e];if(r){var o=r[t];if(o||(o=(r=a.languages.insertBefore(e,"comment",{"doc-comment" [...]
\ No newline at end of file
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-javascript.min.js b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-javascript.min.js
new file mode 100644
index 0000000000..22292c41f6
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-javascript.min.js
@@ -0,0 +1 @@
+Prism.languages.javascript=Prism.languages.extend("clike",{"class-name":[Prism.languages.clike["class-name"],{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,lookbehind:!0}],keyword:[{pattern:/((?:^|\})\s*)catch\b/,lookbehind:!0},{pattern:/(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|final [...]
\ No newline at end of file
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-json.min.js b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-json.min.js
new file mode 100644
index 0000000000..4256f8200d
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-json.min.js
@@ -0,0 +1 @@
+Prism.languages.json={property:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?=\s*:)/,lookbehind:!0,greedy:!0},string:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,lookbehind:!0,greedy:!0},comment:{pattern:/\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/,greedy:!0},number:/-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,punctuation:/[{}[\],]/,operator:/:/,boolean:/\b(?:false|true)\b/,null:{pattern:/\bnull\b/,alias:"keyword"}},Prism.languages.webmanifest=Prism.languages.json;
\ No newline at end of file
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-markdown.min.js b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-markdown.min.js
new file mode 100644
index 0000000000..2b16ba515f
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-markdown.min.js
@@ -0,0 +1 @@
+!function(n){function e(n){return n=n.replace(/<inner>/g,(function(){return"(?:\\\\.|[^\\\\\n\r]|(?:\n|\r\n?)(?![\r\n]))"})),RegExp("((?:^|[^\\\\])(?:\\\\{2})*)(?:"+n+")")}var t="(?:\\\\.|``(?:[^`\r\n]|`(?!`))+``|`[^`\r\n]+`|[^\\\\|\r\n`])+",a="\\|?__(?:\\|__)+\\|?(?:(?:\n|\r\n?)|(?![^]))".replace(/__/g,(function(){return t})),i="\\|?[ \t]*:?-{3,}:?[ \t]*(?:\\|[ \t]*:?-{3,}:?[ \t]*)+\\|?(?:\n|\r\n?)";n.languages.markdown=n.languages.extend("markup",{}),n.languages.insertBefore("markdown" [...]
\ No newline at end of file
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-properties.min.js b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-properties.min.js
new file mode 100644
index 0000000000..5976d47656
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-properties.min.js
@@ -0,0 +1 @@
+Prism.languages.properties={comment:/^[ \t]*[#!].*$/m,value:{pattern:/(^[ \t]*(?:\\(?:\r\n|[\s\S])|[^\\\s:=])+(?: *[=:] *(?! )| ))(?:\\(?:\r\n|[\s\S])|[^\\\r\n])+/m,lookbehind:!0,alias:"attr-value"},key:{pattern:/^[ \t]*(?:\\(?:\r\n|[\s\S])|[^\\\s:=])+(?= *[=:]| )/m,alias:"attr-name"},punctuation:/[=:]/};
\ No newline at end of file
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-regex.min.js b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-regex.min.js
new file mode 100644
index 0000000000..f14e7f0a5f
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-regex.min.js
@@ -0,0 +1 @@
+!function(a){var e={pattern:/\\[\\(){}[\]^$+*?|.]/,alias:"escape"},n=/\\(?:x[\da-fA-F]{2}|u[\da-fA-F]{4}|u\{[\da-fA-F]+\}|0[0-7]{0,2}|[123][0-7]{2}|c[a-zA-Z]|.)/,t="(?:[^\\\\-]|"+n.source+")",s=RegExp(t+"-"+t),i={pattern:/(<|')[^<>']+(?=[>']$)/,lookbehind:!0,alias:"variable"};a.languages.regex={"char-class":{pattern:/((?:^|[^\\])(?:\\\\)*)\[(?:[^\\\]]|\\[\s\S])*\]/,lookbehind:!0,inside:{"char-class-negation":{pattern:/(^\[)\^/,lookbehind:!0,alias:"operator"},"char-class-punctuation":{pat [...]
\ No newline at end of file
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-sql.min.js b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-sql.min.js
new file mode 100644
index 0000000000..86259a6b4f
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-sql.min.js
@@ -0,0 +1 @@
+Prism.languages.sql={comment:{pattern:/(^|[^\\])(?:\/\*[\s\S]*?\*\/|(?:--|\/\/|#).*)/,lookbehind:!0},variable:[{pattern:/@(["'`])(?:\\[\s\S]|(?!\1)[^\\])+\1/,greedy:!0},/@[\w.$]+/],string:{pattern:/(^|[^@\\])("|')(?:\\[\s\S]|(?!\2)[^\\]|\2\2)*\2/,greedy:!0,lookbehind:!0},identifier:{pattern:/(^|[^@\\])`(?:\\[\s\S]|[^`\\]|``)*`/,greedy:!0,lookbehind:!0,inside:{punctuation:/^`|`$/}},function:/\b(?:AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/i,keyword [...]
\ No newline at end of file
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-toml.min.js b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-toml.min.js
new file mode 100644
index 0000000000..0dec967cde
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-toml.min.js
@@ -0,0 +1 @@
+!function(e){function n(e){return e.replace(/__/g,(function(){return"(?:[\\w-]+|'[^'\n\r]*'|\"(?:\\\\.|[^\\\\\"\r\n])*\")"}))}e.languages.toml={comment:{pattern:/#.*/,greedy:!0},table:{pattern:RegExp(n("(^[\t ]*\\[\\s*(?:\\[\\s*)?)__(?:\\s*\\.\\s*__)*(?=\\s*\\])"),"m"),lookbehind:!0,greedy:!0,alias:"class-name"},key:{pattern:RegExp(n("(^[\t ]*|[{,]\\s*)__(?:\\s*\\.\\s*__)*(?=\\s*=)"),"m"),lookbehind:!0,greedy:!0,alias:"property"},string:{pattern:/"""(?:\\[\s\S]|[^\\])*?"""|'''[\s\S]*?''' [...]
\ No newline at end of file
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-xml-doc.min.js b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-xml-doc.min.js
new file mode 100644
index 0000000000..85074eb378
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-xml-doc.min.js
@@ -0,0 +1 @@
+!function(a){function e(e,n){a.languages[e]&&a.languages.insertBefore(e,"comment",{"doc-comment":n})}var n=a.languages.markup.tag,t={pattern:/\/\/\/.*/,greedy:!0,alias:"comment",inside:{tag:n}},g={pattern:/'''.*/,greedy:!0,alias:"comment",inside:{tag:n}};e("csharp",t),e("fsharp",t),e("vbnet",g)}(Prism);
\ No newline at end of file
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-yaml.min.js b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-yaml.min.js
new file mode 100644
index 0000000000..5cd16d3d7f
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism-yaml.min.js
@@ -0,0 +1 @@
+!function(e){var n=/[*&][^\s[\]{},]+/,r=/!(?:<[\w\-%#;/?:@&=+$,.!~*'()[\]]+>|(?:[a-zA-Z\d-]*!)?[\w\-%#;/?:@&=+$.~*'()]+)?/,t="(?:"+r.source+"(?:[ \t]+"+n.source+")?|"+n.source+"(?:[ \t]+"+r.source+")?)",a="(?:[^\\s\\x00-\\x08\\x0e-\\x1f!\"#%&'*,\\-:>?@[\\]`{|}\\x7f-\\x84\\x86-\\x9f\\ud800-\\udfff\\ufffe\\uffff]|[?:-]<PLAIN>)(?:[ \t]*(?:(?![#:])<PLAIN>|:<PLAIN>))*".replace(/<PLAIN>/g,(function(){return"[^\\s\\x00-\\x08\\x0e-\\x1f,[\\]{}\\x7f-\\x84\\x86-\\x9f\\ud800-\\udfff\\ufffe\\uffff]" [...]
\ No newline at end of file
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism.js b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism.js
new file mode 100644
index 0000000000..13a9c66960
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism.js
@@ -0,0 +1,1946 @@
+
+/* **********************************************
+ Begin prism-core.js
+********************************************** */
+
+/// <reference lib="WebWorker"/>
+
+var _self = (typeof window !== 'undefined')
+ ? window // if in browser
+ : (
+ (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope)
+ ? self // if in worker
+ : {} // if in node js
+ );
+
+/**
+ * Prism: Lightweight, robust, elegant syntax highlighting
+ *
+ * @license MIT <https://opensource.org/licenses/MIT>
+ * @author Lea Verou <https://lea.verou.me>
+ * @namespace
+ * @public
+ */
+var Prism = (function (_self) {
+
+ // Private helper vars
+ var lang = /(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i;
+ var uniqueId = 0;
+
+ // The grammar object for plaintext
+ var plainTextGrammar = {};
+
+
+ var _ = {
+ /**
+ * By default, Prism will attempt to highlight all code elements (by calling {@link Prism.highlightAll}) on the
+ * current page after the page finished loading. This might be a problem if e.g. you wanted to asynchronously load
+ * additional languages or plugins yourself.
+ *
+ * By setting this value to `true`, Prism will not automatically highlight all code elements on the page.
+ *
+ * You obviously have to change this value before the automatic highlighting started. To do this, you can add an
+ * empty Prism object into the global scope before loading the Prism script like this:
+ *
+ * ```js
+ * window.Prism = window.Prism || {};
+ * Prism.manual = true;
+ * // add a new <script> to load Prism's script
+ * ```
+ *
+ * @default false
+ * @type {boolean}
+ * @memberof Prism
+ * @public
+ */
+ manual: _self.Prism && _self.Prism.manual,
+ /**
+ * By default, if Prism is in a web worker, it assumes that it is in a worker it created itself, so it uses
+ * `addEventListener` to communicate with its parent instance. However, if you're using Prism manually in your
+ * own worker, you don't want it to do this.
+ *
+ * By setting this value to `true`, Prism will not add its own listeners to the worker.
+ *
+ * You obviously have to change this value before Prism executes. To do this, you can add an
+ * empty Prism object into the global scope before loading the Prism script like this:
+ *
+ * ```js
+ * window.Prism = window.Prism || {};
+ * Prism.disableWorkerMessageHandler = true;
+ * // Load Prism's script
+ * ```
+ *
+ * @default false
+ * @type {boolean}
+ * @memberof Prism
+ * @public
+ */
+ disableWorkerMessageHandler: _self.Prism && _self.Prism.disableWorkerMessageHandler,
+
+ /**
+ * A namespace for utility methods.
+ *
+ * All function in this namespace that are not explicitly marked as _public_ are for __internal use only__ and may
+ * change or disappear at any time.
+ *
+ * @namespace
+ * @memberof Prism
+ */
+ util: {
+ encode: function encode(tokens) {
+ if (tokens instanceof Token) {
+ return new Token(tokens.type, encode(tokens.content), tokens.alias);
+ } else if (Array.isArray(tokens)) {
+ return tokens.map(encode);
+ } else {
+ return tokens.replace(/&/g, '&').replace(/</g, '<').replace(/\u00a0/g, ' ');
+ }
+ },
+
+ /**
+ * Returns the name of the type of the given value.
+ *
+ * @param {any} o
+ * @returns {string}
+ * @example
+ * type(null) === 'Null'
+ * type(undefined) === 'Undefined'
+ * type(123) === 'Number'
+ * type('foo') === 'String'
+ * type(true) === 'Boolean'
+ * type([1, 2]) === 'Array'
+ * type({}) === 'Object'
+ * type(String) === 'Function'
+ * type(/abc+/) === 'RegExp'
+ */
+ type: function (o) {
+ return Object.prototype.toString.call(o).slice(8, -1);
+ },
+
+ /**
+ * Returns a unique number for the given object. Later calls will still return the same number.
+ *
+ * @param {Object} obj
+ * @returns {number}
+ */
+ objId: function (obj) {
+ if (!obj['__id']) {
+ Object.defineProperty(obj, '__id', { value: ++uniqueId });
+ }
+ return obj['__id'];
+ },
+
+ /**
+ * Creates a deep clone of the given object.
+ *
+ * The main intended use of this function is to clone language definitions.
+ *
+ * @param {T} o
+ * @param {Record<number, any>} [visited]
+ * @returns {T}
+ * @template T
+ */
+ clone: function deepClone(o, visited) {
+ visited = visited || {};
+
+ var clone; var id;
+ switch (_.util.type(o)) {
+ case 'Object':
+ id = _.util.objId(o);
+ if (visited[id]) {
+ return visited[id];
+ }
+ clone = /** @type {Record<string, any>} */ ({});
+ visited[id] = clone;
+
+ for (var key in o) {
+ if (o.hasOwnProperty(key)) {
+ clone[key] = deepClone(o[key], visited);
+ }
+ }
+
+ return /** @type {any} */ (clone);
+
+ case 'Array':
+ id = _.util.objId(o);
+ if (visited[id]) {
+ return visited[id];
+ }
+ clone = [];
+ visited[id] = clone;
+
+ (/** @type {Array} */(/** @type {any} */(o))).forEach(function (v, i) {
+ clone[i] = deepClone(v, visited);
+ });
+
+ return /** @type {any} */ (clone);
+
+ default:
+ return o;
+ }
+ },
+
+ /**
+ * Returns the Prism language of the given element set by a `language-xxxx` or `lang-xxxx` class.
+ *
+ * If no language is set for the element or the element is `null` or `undefined`, `none` will be returned.
+ *
+ * @param {Element} element
+ * @returns {string}
+ */
+ getLanguage: function (element) {
+ while (element) {
+ var m = lang.exec(element.className);
+ if (m) {
+ return m[1].toLowerCase();
+ }
+ element = element.parentElement;
+ }
+ return 'none';
+ },
+
+ /**
+ * Sets the Prism `language-xxxx` class of the given element.
+ *
+ * @param {Element} element
+ * @param {string} language
+ * @returns {void}
+ */
+ setLanguage: function (element, language) {
+ // remove all `language-xxxx` classes
+ // (this might leave behind a leading space)
+ element.className = element.className.replace(RegExp(lang, 'gi'), '');
+
+ // add the new `language-xxxx` class
+ // (using `classList` will automatically clean up spaces for us)
+ element.classList.add('language-' + language);
+ },
+
+ /**
+ * Returns the script element that is currently executing.
+ *
+ * This does __not__ work for line script element.
+ *
+ * @returns {HTMLScriptElement | null}
+ */
+ currentScript: function () {
+ if (typeof document === 'undefined') {
+ return null;
+ }
+ if (document.currentScript && document.currentScript.tagName === 'SCRIPT' && 1 < 2 /* hack to trip TS' flow analysis */) {
+ return /** @type {any} */ (document.currentScript);
+ }
+
+ // IE11 workaround
+ // we'll get the src of the current script by parsing IE11's error stack trace
+ // this will not work for inline scripts
+
+ try {
+ throw new Error();
+ } catch (err) {
+ // Get file src url from stack. Specifically works with the format of stack traces in IE.
+ // A stack will look like this:
+ //
+ // Error
+ // at _.util.currentScript (http://localhost/components/prism-core.js:119:5)
+ // at Global code (http://localhost/components/prism-core.js:606:1)
+
+ var src = (/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(err.stack) || [])[1];
+ if (src) {
+ var scripts = document.getElementsByTagName('script');
+ for (var i in scripts) {
+ if (scripts[i].src == src) {
+ return scripts[i];
+ }
+ }
+ }
+ return null;
+ }
+ },
+
+ /**
+ * Returns whether a given class is active for `element`.
+ *
+ * The class can be activated if `element` or one of its ancestors has the given class and it can be deactivated
+ * if `element` or one of its ancestors has the negated version of the given class. The _negated version_ of the
+ * given class is just the given class with a `no-` prefix.
+ *
+ * Whether the class is active is determined by the closest ancestor of `element` (where `element` itself is
+ * closest ancestor) that has the given class or the negated version of it. If neither `element` nor any of its
+ * ancestors have the given class or the negated version of it, then the default activation will be returned.
+ *
+ * In the paradoxical situation where the closest ancestor contains __both__ the given class and the negated
+ * version of it, the class is considered active.
+ *
+ * @param {Element} element
+ * @param {string} className
+ * @param {boolean} [defaultActivation=false]
+ * @returns {boolean}
+ */
+ isActive: function (element, className, defaultActivation) {
+ var no = 'no-' + className;
+
+ while (element) {
+ var classList = element.classList;
+ if (classList.contains(className)) {
+ return true;
+ }
+ if (classList.contains(no)) {
+ return false;
+ }
+ element = element.parentElement;
+ }
+ return !!defaultActivation;
+ }
+ },
+
+ /**
+ * This namespace contains all currently loaded languages and the some helper functions to create and modify languages.
+ *
+ * @namespace
+ * @memberof Prism
+ * @public
+ */
+ languages: {
+ /**
+ * The grammar for plain, unformatted text.
+ */
+ plain: plainTextGrammar,
+ plaintext: plainTextGrammar,
+ text: plainTextGrammar,
+ txt: plainTextGrammar,
+
+ /**
+ * Creates a deep copy of the language with the given id and appends the given tokens.
+ *
+ * If a token in `redef` also appears in the copied language, then the existing token in the copied language
+ * will be overwritten at its original position.
+ *
+ * ## Best practices
+ *
+ * Since the position of overwriting tokens (token in `redef` that overwrite tokens in the copied language)
+ * doesn't matter, they can technically be in any order. However, this can be confusing to others that trying to
+ * understand the language definition because, normally, the order of tokens matters in Prism grammars.
+ *
+ * Therefore, it is encouraged to order overwriting tokens according to the positions of the overwritten tokens.
+ * Furthermore, all non-overwriting tokens should be placed after the overwriting ones.
+ *
+ * @param {string} id The id of the language to extend. This has to be a key in `Prism.languages`.
+ * @param {Grammar} redef The new tokens to append.
+ * @returns {Grammar} The new language created.
+ * @public
+ * @example
+ * Prism.languages['css-with-colors'] = Prism.languages.extend('css', {
+ * // Prism.languages.css already has a 'comment' token, so this token will overwrite CSS' 'comment' token
+ * // at its original position
+ * 'comment': { ... },
+ * // CSS doesn't have a 'color' token, so this token will be appended
+ * 'color': /\b(?:red|green|blue)\b/
+ * });
+ */
+ extend: function (id, redef) {
+ var lang = _.util.clone(_.languages[id]);
+
+ for (var key in redef) {
+ lang[key] = redef[key];
+ }
+
+ return lang;
+ },
+
+ /**
+ * Inserts tokens _before_ another token in a language definition or any other grammar.
+ *
+ * ## Usage
+ *
+ * This helper method makes it easy to modify existing languages. For example, the CSS language definition
+ * not only defines CSS highlighting for CSS documents, but also needs to define highlighting for CSS embedded
+ * in HTML through `<style>` elements. To do this, it needs to modify `Prism.languages.markup` and add the
+ * appropriate tokens. However, `Prism.languages.markup` is a regular JavaScript object literal, so if you do
+ * this:
+ *
+ * ```js
+ * Prism.languages.markup.style = {
+ * // token
+ * };
+ * ```
+ *
+ * then the `style` token will be added (and processed) at the end. `insertBefore` allows you to insert tokens
+ * before existing tokens. For the CSS example above, you would use it like this:
+ *
+ * ```js
+ * Prism.languages.insertBefore('markup', 'cdata', {
+ * 'style': {
+ * // token
+ * }
+ * });
+ * ```
+ *
+ * ## Special cases
+ *
+ * If the grammars of `inside` and `insert` have tokens with the same name, the tokens in `inside`'s grammar
+ * will be ignored.
+ *
+ * This behavior can be used to insert tokens after `before`:
+ *
+ * ```js
+ * Prism.languages.insertBefore('markup', 'comment', {
+ * 'comment': Prism.languages.markup.comment,
+ * // tokens after 'comment'
+ * });
+ * ```
+ *
+ * ## Limitations
+ *
+ * The main problem `insertBefore` has to solve is iteration order. Since ES2015, the iteration order for object
+ * properties is guaranteed to be the insertion order (except for integer keys) but some browsers behave
+ * differently when keys are deleted and re-inserted. So `insertBefore` can't be implemented by temporarily
+ * deleting properties which is necessary to insert at arbitrary positions.
+ *
+ * To solve this problem, `insertBefore` doesn't actually insert the given tokens into the target object.
+ * Instead, it will create a new object and replace all references to the target object with the new one. This
+ * can be done without temporarily deleting properties, so the iteration order is well-defined.
+ *
+ * However, only references that can be reached from `Prism.languages` or `insert` will be replaced. I.e. if
+ * you hold the target object in a variable, then the value of the variable will not change.
+ *
+ * ```js
+ * var oldMarkup = Prism.languages.markup;
+ * var newMarkup = Prism.languages.insertBefore('markup', 'comment', { ... });
+ *
+ * assert(oldMarkup !== Prism.languages.markup);
+ * assert(newMarkup === Prism.languages.markup);
+ * ```
+ *
+ * @param {string} inside The property of `root` (e.g. a language id in `Prism.languages`) that contains the
+ * object to be modified.
+ * @param {string} before The key to insert before.
+ * @param {Grammar} insert An object containing the key-value pairs to be inserted.
+ * @param {Object<string, any>} [root] The object containing `inside`, i.e. the object that contains the
+ * object to be modified.
+ *
+ * Defaults to `Prism.languages`.
+ * @returns {Grammar} The new grammar object.
+ * @public
+ */
+ insertBefore: function (inside, before, insert, root) {
+ root = root || /** @type {any} */ (_.languages);
+ var grammar = root[inside];
+ /** @type {Grammar} */
+ var ret = {};
+
+ for (var token in grammar) {
+ if (grammar.hasOwnProperty(token)) {
+
+ if (token == before) {
+ for (var newToken in insert) {
+ if (insert.hasOwnProperty(newToken)) {
+ ret[newToken] = insert[newToken];
+ }
+ }
+ }
+
+ // Do not insert token which also occur in insert. See #1525
+ if (!insert.hasOwnProperty(token)) {
+ ret[token] = grammar[token];
+ }
+ }
+ }
+
+ var old = root[inside];
+ root[inside] = ret;
+
+ // Update references in other language definitions
+ _.languages.DFS(_.languages, function (key, value) {
+ if (value === old && key != inside) {
+ this[key] = ret;
+ }
+ });
+
+ return ret;
+ },
+
+ // Traverse a language definition with Depth First Search
+ DFS: function DFS(o, callback, type, visited) {
+ visited = visited || {};
+
+ var objId = _.util.objId;
+
+ for (var i in o) {
+ if (o.hasOwnProperty(i)) {
+ callback.call(o, i, o[i], type || i);
+
+ var property = o[i];
+ var propertyType = _.util.type(property);
+
+ if (propertyType === 'Object' && !visited[objId(property)]) {
+ visited[objId(property)] = true;
+ DFS(property, callback, null, visited);
+ } else if (propertyType === 'Array' && !visited[objId(property)]) {
+ visited[objId(property)] = true;
+ DFS(property, callback, i, visited);
+ }
+ }
+ }
+ }
+ },
+
+ plugins: {},
+
+ /**
+ * This is the most high-level function in Prism’s API.
+ * It fetches all the elements that have a `.language-xxxx` class and then calls {@link Prism.highlightElement} on
+ * each one of them.
+ *
+ * This is equivalent to `Prism.highlightAllUnder(document, async, callback)`.
+ *
+ * @param {boolean} [async=false] Same as in {@link Prism.highlightAllUnder}.
+ * @param {HighlightCallback} [callback] Same as in {@link Prism.highlightAllUnder}.
+ * @memberof Prism
+ * @public
+ */
+ highlightAll: function (async, callback) {
+ _.highlightAllUnder(document, async, callback);
+ },
+
+ /**
+ * Fetches all the descendants of `container` that have a `.language-xxxx` class and then calls
+ * {@link Prism.highlightElement} on each one of them.
+ *
+ * The following hooks will be run:
+ * 1. `before-highlightall`
+ * 2. `before-all-elements-highlight`
+ * 3. All hooks of {@link Prism.highlightElement} for each element.
+ *
+ * @param {ParentNode} container The root element, whose descendants that have a `.language-xxxx` class will be highlighted.
+ * @param {boolean} [async=false] Whether each element is to be highlighted asynchronously using Web Workers.
+ * @param {HighlightCallback} [callback] An optional callback to be invoked on each element after its highlighting is done.
+ * @memberof Prism
+ * @public
+ */
+ highlightAllUnder: function (container, async, callback) {
+ var env = {
+ callback: callback,
+ container: container,
+ selector: 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'
+ };
+
+ _.hooks.run('before-highlightall', env);
+
+ env.elements = Array.prototype.slice.apply(env.container.querySelectorAll(env.selector));
+
+ _.hooks.run('before-all-elements-highlight', env);
+
+ for (var i = 0, element; (element = env.elements[i++]);) {
+ _.highlightElement(element, async === true, env.callback);
+ }
+ },
+
+ /**
+ * Highlights the code inside a single element.
+ *
+ * The following hooks will be run:
+ * 1. `before-sanity-check`
+ * 2. `before-highlight`
+ * 3. All hooks of {@link Prism.highlight}. These hooks will be run by an asynchronous worker if `async` is `true`.
+ * 4. `before-insert`
+ * 5. `after-highlight`
+ * 6. `complete`
+ *
+ * Some the above hooks will be skipped if the element doesn't contain any text or there is no grammar loaded for
+ * the element's language.
+ *
+ * @param {Element} element The element containing the code.
+ * It must have a class of `language-xxxx` to be processed, where `xxxx` is a valid language identifier.
+ * @param {boolean} [async=false] Whether the element is to be highlighted asynchronously using Web Workers
+ * to improve performance and avoid blocking the UI when highlighting very large chunks of code. This option is
+ * [disabled by default](https://prismjs.com/faq.html#why-is-asynchronous-highlighting-disabled-by-default).
+ *
+ * Note: All language definitions required to highlight the code must be included in the main `prism.js` file for
+ * asynchronous highlighting to work. You can build your own bundle on the
+ * [Download page](https://prismjs.com/download.html).
+ * @param {HighlightCallback} [callback] An optional callback to be invoked after the highlighting is done.
+ * Mostly useful when `async` is `true`, since in that case, the highlighting is done asynchronously.
+ * @memberof Prism
+ * @public
+ */
+ highlightElement: function (element, async, callback) {
+ // Find language
+ var language = _.util.getLanguage(element);
+ var grammar = _.languages[language];
+
+ // Set language on the element, if not present
+ _.util.setLanguage(element, language);
+
+ // Set language on the parent, for styling
+ var parent = element.parentElement;
+ if (parent && parent.nodeName.toLowerCase() === 'pre') {
+ _.util.setLanguage(parent, language);
+ }
+
+ var code = element.textContent;
+
+ var env = {
+ element: element,
+ language: language,
+ grammar: grammar,
+ code: code
+ };
+
+ function insertHighlightedCode(highlightedCode) {
+ env.highlightedCode = highlightedCode;
+
+ _.hooks.run('before-insert', env);
+
+ env.element.innerHTML = env.highlightedCode;
+
+ _.hooks.run('after-highlight', env);
+ _.hooks.run('complete', env);
+ callback && callback.call(env.element);
+ }
+
+ _.hooks.run('before-sanity-check', env);
+
+ // plugins may change/add the parent/element
+ parent = env.element.parentElement;
+ if (parent && parent.nodeName.toLowerCase() === 'pre' && !parent.hasAttribute('tabindex')) {
+ parent.setAttribute('tabindex', '0');
+ }
+
+ if (!env.code) {
+ _.hooks.run('complete', env);
+ callback && callback.call(env.element);
+ return;
+ }
+
+ _.hooks.run('before-highlight', env);
+
+ if (!env.grammar) {
+ insertHighlightedCode(_.util.encode(env.code));
+ return;
+ }
+
+ if (async && _self.Worker) {
+ var worker = new Worker(_.filename);
+
+ worker.onmessage = function (evt) {
+ insertHighlightedCode(evt.data);
+ };
+
+ worker.postMessage(JSON.stringify({
+ language: env.language,
+ code: env.code,
+ immediateClose: true
+ }));
+ } else {
+ insertHighlightedCode(_.highlight(env.code, env.grammar, env.language));
+ }
+ },
+
+ /**
+ * Low-level function, only use if you know what you’re doing. It accepts a string of text as input
+ * and the language definitions to use, and returns a string with the HTML produced.
+ *
+ * The following hooks will be run:
+ * 1. `before-tokenize`
+ * 2. `after-tokenize`
+ * 3. `wrap`: On each {@link Token}.
+ *
+ * @param {string} text A string with the code to be highlighted.
+ * @param {Grammar} grammar An object containing the tokens to use.
+ *
+ * Usually a language definition like `Prism.languages.markup`.
+ * @param {string} language The name of the language definition passed to `grammar`.
+ * @returns {string} The highlighted HTML.
+ * @memberof Prism
+ * @public
+ * @example
+ * Prism.highlight('var foo = true;', Prism.languages.javascript, 'javascript');
+ */
+ highlight: function (text, grammar, language) {
+ var env = {
+ code: text,
+ grammar: grammar,
+ language: language
+ };
+ _.hooks.run('before-tokenize', env);
+ if (!env.grammar) {
+ throw new Error('The language "' + env.language + '" has no grammar.');
+ }
+ env.tokens = _.tokenize(env.code, env.grammar);
+ _.hooks.run('after-tokenize', env);
+ return Token.stringify(_.util.encode(env.tokens), env.language);
+ },
+
+ /**
+ * This is the heart of Prism, and the most low-level function you can use. It accepts a string of text as input
+ * and the language definitions to use, and returns an array with the tokenized code.
+ *
+ * When the language definition includes nested tokens, the function is called recursively on each of these tokens.
+ *
+ * This method could be useful in other contexts as well, as a very crude parser.
+ *
+ * @param {string} text A string with the code to be highlighted.
+ * @param {Grammar} grammar An object containing the tokens to use.
+ *
+ * Usually a language definition like `Prism.languages.markup`.
+ * @returns {TokenStream} An array of strings and tokens, a token stream.
+ * @memberof Prism
+ * @public
+ * @example
+ * let code = `var foo = 0;`;
+ * let tokens = Prism.tokenize(code, Prism.languages.javascript);
+ * tokens.forEach(token => {
+ * if (token instanceof Prism.Token && token.type === 'number') {
+ * console.log(`Found numeric literal: ${token.content}`);
+ * }
+ * });
+ */
+ tokenize: function (text, grammar) {
+ var rest = grammar.rest;
+ if (rest) {
+ for (var token in rest) {
+ grammar[token] = rest[token];
+ }
+
+ delete grammar.rest;
+ }
+
+ var tokenList = new LinkedList();
+ addAfter(tokenList, tokenList.head, text);
+
+ matchGrammar(text, tokenList, grammar, tokenList.head, 0);
+
+ return toArray(tokenList);
+ },
+
+ /**
+ * @namespace
+ * @memberof Prism
+ * @public
+ */
+ hooks: {
+ all: {},
+
+ /**
+ * Adds the given callback to the list of callbacks for the given hook.
+ *
+ * The callback will be invoked when the hook it is registered for is run.
+ * Hooks are usually directly run by a highlight function but you can also run hooks yourself.
+ *
+ * One callback function can be registered to multiple hooks and the same hook multiple times.
+ *
+ * @param {string} name The name of the hook.
+ * @param {HookCallback} callback The callback function which is given environment variables.
+ * @public
+ */
+ add: function (name, callback) {
+ var hooks = _.hooks.all;
+
+ hooks[name] = hooks[name] || [];
+
+ hooks[name].push(callback);
+ },
+
+ /**
+ * Runs a hook invoking all registered callbacks with the given environment variables.
+ *
+ * Callbacks will be invoked synchronously and in the order in which they were registered.
+ *
+ * @param {string} name The name of the hook.
+ * @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.
+ * @public
+ */
+ run: function (name, env) {
+ var callbacks = _.hooks.all[name];
+
+ if (!callbacks || !callbacks.length) {
+ return;
+ }
+
+ for (var i = 0, callback; (callback = callbacks[i++]);) {
+ callback(env);
+ }
+ }
+ },
+
+ Token: Token
+ };
+ _self.Prism = _;
+
+
+ // Typescript note:
+ // The following can be used to import the Token type in JSDoc:
+ //
+ // @typedef {InstanceType<import("./prism-core")["Token"]>} Token
+
+ /**
+ * Creates a new token.
+ *
+ * @param {string} type See {@link Token#type type}
+ * @param {string | TokenStream} content See {@link Token#content content}
+ * @param {string|string[]} [alias] The alias(es) of the token.
+ * @param {string} [matchedStr=""] A copy of the full string this token was created from.
+ * @class
+ * @global
+ * @public
+ */
+ function Token(type, content, alias, matchedStr) {
+ /**
+ * The type of the token.
+ *
+ * This is usually the key of a pattern in a {@link Grammar}.
+ *
+ * @type {string}
+ * @see GrammarToken
+ * @public
+ */
+ this.type = type;
+ /**
+ * The strings or tokens contained by this token.
+ *
+ * This will be a token stream if the pattern matched also defined an `inside` grammar.
+ *
+ * @type {string | TokenStream}
+ * @public
+ */
+ this.content = content;
+ /**
+ * The alias(es) of the token.
+ *
+ * @type {string|string[]}
+ * @see GrammarToken
+ * @public
+ */
+ this.alias = alias;
+ // Copy of the full string this token was created from
+ this.length = (matchedStr || '').length | 0;
+ }
+
+ /**
+ * A token stream is an array of strings and {@link Token Token} objects.
+ *
+ * Token streams have to fulfill a few properties that are assumed by most functions (mostly internal ones) that process
+ * them.
+ *
+ * 1. No adjacent strings.
+ * 2. No empty strings.
+ *
+ * The only exception here is the token stream that only contains the empty string and nothing else.
+ *
+ * @typedef {Array<string | Token>} TokenStream
+ * @global
+ * @public
+ */
+
+ /**
+ * Converts the given token or token stream to an HTML representation.
+ *
+ * The following hooks will be run:
+ * 1. `wrap`: On each {@link Token}.
+ *
+ * @param {string | Token | TokenStream} o The token or token stream to be converted.
+ * @param {string} language The name of current language.
+ * @returns {string} The HTML representation of the token or token stream.
+ * @memberof Token
+ * @static
+ */
+ Token.stringify = function stringify(o, language) {
+ if (typeof o == 'string') {
+ return o;
+ }
+ if (Array.isArray(o)) {
+ var s = '';
+ o.forEach(function (e) {
+ s += stringify(e, language);
+ });
+ return s;
+ }
+
+ var env = {
+ type: o.type,
+ content: stringify(o.content, language),
+ tag: 'span',
+ classes: ['token', o.type],
+ attributes: {},
+ language: language
+ };
+
+ var aliases = o.alias;
+ if (aliases) {
+ if (Array.isArray(aliases)) {
+ Array.prototype.push.apply(env.classes, aliases);
+ } else {
+ env.classes.push(aliases);
+ }
+ }
+
+ _.hooks.run('wrap', env);
+
+ var attributes = '';
+ for (var name in env.attributes) {
+ attributes += ' ' + name + '="' + (env.attributes[name] || '').replace(/"/g, '"') + '"';
+ }
+
+ return '<' + env.tag + ' class="' + env.classes.join(' ') + '"' + attributes + '>' + env.content + '</' + env.tag + '>';
+ };
+
+ /**
+ * @param {RegExp} pattern
+ * @param {number} pos
+ * @param {string} text
+ * @param {boolean} lookbehind
+ * @returns {RegExpExecArray | null}
+ */
+ function matchPattern(pattern, pos, text, lookbehind) {
+ pattern.lastIndex = pos;
+ var match = pattern.exec(text);
+ if (match && lookbehind && match[1]) {
+ // change the match to remove the text matched by the Prism lookbehind group
+ var lookbehindLength = match[1].length;
+ match.index += lookbehindLength;
+ match[0] = match[0].slice(lookbehindLength);
+ }
+ return match;
+ }
+
+ /**
+ * @param {string} text
+ * @param {LinkedList<string | Token>} tokenList
+ * @param {any} grammar
+ * @param {LinkedListNode<string | Token>} startNode
+ * @param {number} startPos
+ * @param {RematchOptions} [rematch]
+ * @returns {void}
+ * @private
+ *
+ * @typedef RematchOptions
+ * @property {string} cause
+ * @property {number} reach
+ */
+ function matchGrammar(text, tokenList, grammar, startNode, startPos, rematch) {
+ for (var token in grammar) {
+ if (!grammar.hasOwnProperty(token) || !grammar[token]) {
+ continue;
+ }
+
+ var patterns = grammar[token];
+ patterns = Array.isArray(patterns) ? patterns : [patterns];
+
+ for (var j = 0; j < patterns.length; ++j) {
+ if (rematch && rematch.cause == token + ',' + j) {
+ return;
+ }
+
+ var patternObj = patterns[j];
+ var inside = patternObj.inside;
+ var lookbehind = !!patternObj.lookbehind;
+ var greedy = !!patternObj.greedy;
+ var alias = patternObj.alias;
+
+ if (greedy && !patternObj.pattern.global) {
+ // Without the global flag, lastIndex won't work
+ var flags = patternObj.pattern.toString().match(/[imsuy]*$/)[0];
+ patternObj.pattern = RegExp(patternObj.pattern.source, flags + 'g');
+ }
+
+ /** @type {RegExp} */
+ var pattern = patternObj.pattern || patternObj;
+
+ for ( // iterate the token list and keep track of the current token/string position
+ var currentNode = startNode.next, pos = startPos;
+ currentNode !== tokenList.tail;
+ pos += currentNode.value.length, currentNode = currentNode.next
+ ) {
+
+ if (rematch && pos >= rematch.reach) {
+ break;
+ }
+
+ var str = currentNode.value;
+
+ if (tokenList.length > text.length) {
+ // Something went terribly wrong, ABORT, ABORT!
+ return;
+ }
+
+ if (str instanceof Token) {
+ continue;
+ }
+
+ var removeCount = 1; // this is the to parameter of removeBetween
+ var match;
+
+ if (greedy) {
+ match = matchPattern(pattern, pos, text, lookbehind);
+ if (!match || match.index >= text.length) {
+ break;
+ }
+
+ var from = match.index;
+ var to = match.index + match[0].length;
+ var p = pos;
+
+ // find the node that contains the match
+ p += currentNode.value.length;
+ while (from >= p) {
+ currentNode = currentNode.next;
+ p += currentNode.value.length;
+ }
+ // adjust pos (and p)
+ p -= currentNode.value.length;
+ pos = p;
+
+ // the current node is a Token, then the match starts inside another Token, which is invalid
+ if (currentNode.value instanceof Token) {
+ continue;
+ }
+
+ // find the last node which is affected by this match
+ for (
+ var k = currentNode;
+ k !== tokenList.tail && (p < to || typeof k.value === 'string');
+ k = k.next
+ ) {
+ removeCount++;
+ p += k.value.length;
+ }
+ removeCount--;
+
+ // replace with the new match
+ str = text.slice(pos, p);
+ match.index -= pos;
+ } else {
+ match = matchPattern(pattern, 0, str, lookbehind);
+ if (!match) {
+ continue;
+ }
+ }
+
+ // eslint-disable-next-line no-redeclare
+ var from = match.index;
+ var matchStr = match[0];
+ var before = str.slice(0, from);
+ var after = str.slice(from + matchStr.length);
+
+ var reach = pos + str.length;
+ if (rematch && reach > rematch.reach) {
+ rematch.reach = reach;
+ }
+
+ var removeFrom = currentNode.prev;
+
+ if (before) {
+ removeFrom = addAfter(tokenList, removeFrom, before);
+ pos += before.length;
+ }
+
+ removeRange(tokenList, removeFrom, removeCount);
+
+ var wrapped = new Token(token, inside ? _.tokenize(matchStr, inside) : matchStr, alias, matchStr);
+ currentNode = addAfter(tokenList, removeFrom, wrapped);
+
+ if (after) {
+ addAfter(tokenList, currentNode, after);
+ }
+
+ if (removeCount > 1) {
+ // at least one Token object was removed, so we have to do some rematching
+ // this can only happen if the current pattern is greedy
+
+ /** @type {RematchOptions} */
+ var nestedRematch = {
+ cause: token + ',' + j,
+ reach: reach
+ };
+ matchGrammar(text, tokenList, grammar, currentNode.prev, pos, nestedRematch);
+
+ // the reach might have been extended because of the rematching
+ if (rematch && nestedRematch.reach > rematch.reach) {
+ rematch.reach = nestedRematch.reach;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * @typedef LinkedListNode
+ * @property {T} value
+ * @property {LinkedListNode<T> | null} prev The previous node.
+ * @property {LinkedListNode<T> | null} next The next node.
+ * @template T
+ * @private
+ */
+
+ /**
+ * @template T
+ * @private
+ */
+ function LinkedList() {
+ /** @type {LinkedListNode<T>} */
+ var head = { value: null, prev: null, next: null };
+ /** @type {LinkedListNode<T>} */
+ var tail = { value: null, prev: head, next: null };
+ head.next = tail;
+
+ /** @type {LinkedListNode<T>} */
+ this.head = head;
+ /** @type {LinkedListNode<T>} */
+ this.tail = tail;
+ this.length = 0;
+ }
+
+ /**
+ * Adds a new node with the given value to the list.
+ *
+ * @param {LinkedList<T>} list
+ * @param {LinkedListNode<T>} node
+ * @param {T} value
+ * @returns {LinkedListNode<T>} The added node.
+ * @template T
+ */
+ function addAfter(list, node, value) {
+ // assumes that node != list.tail && values.length >= 0
+ var next = node.next;
+
+ var newNode = { value: value, prev: node, next: next };
+ node.next = newNode;
+ next.prev = newNode;
+ list.length++;
+
+ return newNode;
+ }
+ /**
+ * Removes `count` nodes after the given node. The given node will not be removed.
+ *
+ * @param {LinkedList<T>} list
+ * @param {LinkedListNode<T>} node
+ * @param {number} count
+ * @template T
+ */
+ function removeRange(list, node, count) {
+ var next = node.next;
+ for (var i = 0; i < count && next !== list.tail; i++) {
+ next = next.next;
+ }
+ node.next = next;
+ next.prev = node;
+ list.length -= i;
+ }
+ /**
+ * @param {LinkedList<T>} list
+ * @returns {T[]}
+ * @template T
+ */
+ function toArray(list) {
+ var array = [];
+ var node = list.head.next;
+ while (node !== list.tail) {
+ array.push(node.value);
+ node = node.next;
+ }
+ return array;
+ }
+
+
+ if (!_self.document) {
+ if (!_self.addEventListener) {
+ // in Node.js
+ return _;
+ }
+
+ if (!_.disableWorkerMessageHandler) {
+ // In worker
+ _self.addEventListener('message', function (evt) {
+ var message = JSON.parse(evt.data);
+ var lang = message.language;
+ var code = message.code;
+ var immediateClose = message.immediateClose;
+
+ _self.postMessage(_.highlight(code, _.languages[lang], lang));
+ if (immediateClose) {
+ _self.close();
+ }
+ }, false);
+ }
+
+ return _;
+ }
+
+ // Get current script and highlight
+ var script = _.util.currentScript();
+
+ if (script) {
+ _.filename = script.src;
+
+ if (script.hasAttribute('data-manual')) {
+ _.manual = true;
+ }
+ }
+
+ function highlightAutomaticallyCallback() {
+ if (!_.manual) {
+ _.highlightAll();
+ }
+ }
+
+ if (!_.manual) {
+ // If the document state is "loading", then we'll use DOMContentLoaded.
+ // If the document state is "interactive" and the prism.js script is deferred, then we'll also use the
+ // DOMContentLoaded event because there might be some plugins or languages which have also been deferred and they
+ // might take longer one animation frame to execute which can create a race condition where only some plugins have
+ // been loaded when Prism.highlightAll() is executed, depending on how fast resources are loaded.
+ // See https://github.com/PrismJS/prism/issues/2102
+ var readyState = document.readyState;
+ if (readyState === 'loading' || readyState === 'interactive' && script && script.defer) {
+ document.addEventListener('DOMContentLoaded', highlightAutomaticallyCallback);
+ } else {
+ if (window.requestAnimationFrame) {
+ window.requestAnimationFrame(highlightAutomaticallyCallback);
+ } else {
+ window.setTimeout(highlightAutomaticallyCallback, 16);
+ }
+ }
+ }
+
+ return _;
+
+}(_self));
+
+if (typeof module !== 'undefined' && module.exports) {
+ module.exports = Prism;
+}
+
+// hack for components to work correctly in node.js
+if (typeof global !== 'undefined') {
+ global.Prism = Prism;
+}
+
+// some additional documentation/types
+
+/**
+ * The expansion of a simple `RegExp` literal to support additional properties.
+ *
+ * @typedef GrammarToken
+ * @property {RegExp} pattern The regular expression of the token.
+ * @property {boolean} [lookbehind=false] If `true`, then the first capturing group of `pattern` will (effectively)
+ * behave as a lookbehind group meaning that the captured text will not be part of the matched text of the new token.
+ * @property {boolean} [greedy=false] Whether the token is greedy.
+ * @property {string|string[]} [alias] An optional alias or list of aliases.
+ * @property {Grammar} [inside] The nested grammar of this token.
+ *
+ * The `inside` grammar will be used to tokenize the text value of each token of this kind.
+ *
+ * This can be used to make nested and even recursive language definitions.
+ *
+ * Note: This can cause infinite recursion. Be careful when you embed different languages or even the same language into
+ * each another.
+ * @global
+ * @public
+ */
+
+/**
+ * @typedef Grammar
+ * @type {Object<string, RegExp | GrammarToken | Array<RegExp | GrammarToken>>}
+ * @property {Grammar} [rest] An optional grammar object that will be appended to this grammar.
+ * @global
+ * @public
+ */
+
+/**
+ * A function which will invoked after an element was successfully highlighted.
+ *
+ * @callback HighlightCallback
+ * @param {Element} element The element successfully highlighted.
+ * @returns {void}
+ * @global
+ * @public
+ */
+
+/**
+ * @callback HookCallback
+ * @param {Object<string, any>} env The environment variables of the hook.
+ * @returns {void}
+ * @global
+ * @public
+ */
+
+
+/* **********************************************
+ Begin prism-markup.js
+********************************************** */
+
+Prism.languages.markup = {
+ 'comment': {
+ pattern: /<!--(?:(?!<!--)[\s\S])*?-->/,
+ greedy: true
+ },
+ 'prolog': {
+ pattern: /<\?[\s\S]+?\?>/,
+ greedy: true
+ },
+ 'doctype': {
+ // https://www.w3.org/TR/xml/#NT-doctypedecl
+ pattern: /<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,
+ greedy: true,
+ inside: {
+ 'internal-subset': {
+ pattern: /(^[^\[]*\[)[\s\S]+(?=\]>$)/,
+ lookbehind: true,
+ greedy: true,
+ inside: null // see below
+ },
+ 'string': {
+ pattern: /"[^"]*"|'[^']*'/,
+ greedy: true
+ },
+ 'punctuation': /^<!|>$|[[\]]/,
+ 'doctype-tag': /^DOCTYPE/i,
+ 'name': /[^\s<>'"]+/
+ }
+ },
+ 'cdata': {
+ pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
+ greedy: true
+ },
+ 'tag': {
+ pattern: /<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,
+ greedy: true,
+ inside: {
+ 'tag': {
+ pattern: /^<\/?[^\s>\/]+/,
+ inside: {
+ 'punctuation': /^<\/?/,
+ 'namespace': /^[^\s>\/:]+:/
+ }
+ },
+ 'special-attr': [],
+ 'attr-value': {
+ pattern: /=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,
+ inside: {
+ 'punctuation': [
+ {
+ pattern: /^=/,
+ alias: 'attr-equals'
+ },
+ {
+ pattern: /^(\s*)["']|["']$/,
+ lookbehind: true
+ }
+ ]
+ }
+ },
+ 'punctuation': /\/?>/,
+ 'attr-name': {
+ pattern: /[^\s>\/]+/,
+ inside: {
+ 'namespace': /^[^\s>\/:]+:/
+ }
+ }
+
+ }
+ },
+ 'entity': [
+ {
+ pattern: /&[\da-z]{1,8};/i,
+ alias: 'named-entity'
+ },
+ /&#x?[\da-f]{1,8};/i
+ ]
+};
+
+Prism.languages.markup['tag'].inside['attr-value'].inside['entity'] =
+ Prism.languages.markup['entity'];
+Prism.languages.markup['doctype'].inside['internal-subset'].inside = Prism.languages.markup;
+
+// Plugin to make entity title show the real entity, idea by Roman Komarov
+Prism.hooks.add('wrap', function (env) {
+
+ if (env.type === 'entity') {
+ env.attributes['title'] = env.content.replace(/&/, '&');
+ }
+});
+
+Object.defineProperty(Prism.languages.markup.tag, 'addInlined', {
+ /**
+ * Adds an inlined language to markup.
+ *
+ * An example of an inlined language is CSS with `<style>` tags.
+ *
+ * @param {string} tagName The name of the tag that contains the inlined language. This name will be treated as
+ * case insensitive.
+ * @param {string} lang The language key.
+ * @example
+ * addInlined('style', 'css');
+ */
+ value: function addInlined(tagName, lang) {
+ var includedCdataInside = {};
+ includedCdataInside['language-' + lang] = {
+ pattern: /(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,
+ lookbehind: true,
+ inside: Prism.languages[lang]
+ };
+ includedCdataInside['cdata'] = /^<!\[CDATA\[|\]\]>$/i;
+
+ var inside = {
+ 'included-cdata': {
+ pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
+ inside: includedCdataInside
+ }
+ };
+ inside['language-' + lang] = {
+ pattern: /[\s\S]+/,
+ inside: Prism.languages[lang]
+ };
+
+ var def = {};
+ def[tagName] = {
+ pattern: RegExp(/(<__[^>]*>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(/__/g, function () { return tagName; }), 'i'),
+ lookbehind: true,
+ greedy: true,
+ inside: inside
+ };
+
+ Prism.languages.insertBefore('markup', 'cdata', def);
+ }
+});
+Object.defineProperty(Prism.languages.markup.tag, 'addAttribute', {
+ /**
+ * Adds an pattern to highlight languages embedded in HTML attributes.
+ *
+ * An example of an inlined language is CSS with `style` attributes.
+ *
+ * @param {string} attrName The name of the tag that contains the inlined language. This name will be treated as
+ * case insensitive.
+ * @param {string} lang The language key.
+ * @example
+ * addAttribute('style', 'css');
+ */
+ value: function (attrName, lang) {
+ Prism.languages.markup.tag.inside['special-attr'].push({
+ pattern: RegExp(
+ /(^|["'\s])/.source + '(?:' + attrName + ')' + /\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))/.source,
+ 'i'
+ ),
+ lookbehind: true,
+ inside: {
+ 'attr-name': /^[^\s=]+/,
+ 'attr-value': {
+ pattern: /=[\s\S]+/,
+ inside: {
+ 'value': {
+ pattern: /(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,
+ lookbehind: true,
+ alias: [lang, 'language-' + lang],
+ inside: Prism.languages[lang]
+ },
+ 'punctuation': [
+ {
+ pattern: /^=/,
+ alias: 'attr-equals'
+ },
+ /"|'/
+ ]
+ }
+ }
+ }
+ });
+ }
+});
+
+Prism.languages.html = Prism.languages.markup;
+Prism.languages.mathml = Prism.languages.markup;
+Prism.languages.svg = Prism.languages.markup;
+
+Prism.languages.xml = Prism.languages.extend('markup', {});
+Prism.languages.ssml = Prism.languages.xml;
+Prism.languages.atom = Prism.languages.xml;
+Prism.languages.rss = Prism.languages.xml;
+
+
+/* **********************************************
+ Begin prism-css.js
+********************************************** */
+
+(function (Prism) {
+
+ var string = /(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;
+
+ Prism.languages.css = {
+ 'comment': /\/\*[\s\S]*?\*\//,
+ 'atrule': {
+ pattern: RegExp('@[\\w-](?:' + /[^;{\s"']|\s+(?!\s)/.source + '|' + string.source + ')*?' + /(?:;|(?=\s*\{))/.source),
+ inside: {
+ 'rule': /^@[\w-]+/,
+ 'selector-function-argument': {
+ pattern: /(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,
+ lookbehind: true,
+ alias: 'selector'
+ },
+ 'keyword': {
+ pattern: /(^|[^\w-])(?:and|not|only|or)(?![\w-])/,
+ lookbehind: true
+ }
+ // See rest below
+ }
+ },
+ 'url': {
+ // https://drafts.csswg.org/css-values-3/#urls
+ pattern: RegExp('\\burl\\((?:' + string.source + '|' + /(?:[^\\\r\n()"']|\\[\s\S])*/.source + ')\\)', 'i'),
+ greedy: true,
+ inside: {
+ 'function': /^url/i,
+ 'punctuation': /^\(|\)$/,
+ 'string': {
+ pattern: RegExp('^' + string.source + '$'),
+ alias: 'url'
+ }
+ }
+ },
+ 'selector': {
+ pattern: RegExp('(^|[{}\\s])[^{}\\s](?:[^{};"\'\\s]|\\s+(?![\\s{])|' + string.source + ')*(?=\\s*\\{)'),
+ lookbehind: true
+ },
+ 'string': {
+ pattern: string,
+ greedy: true
+ },
+ 'property': {
+ pattern: /(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,
+ lookbehind: true
+ },
+ 'important': /!important\b/i,
+ 'function': {
+ pattern: /(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,
+ lookbehind: true
+ },
+ 'punctuation': /[(){};:,]/
+ };
+
+ Prism.languages.css['atrule'].inside.rest = Prism.languages.css;
+
+ var markup = Prism.languages.markup;
+ if (markup) {
+ markup.tag.addInlined('style', 'css');
+ markup.tag.addAttribute('style', 'css');
+ }
+
+}(Prism));
+
+
+/* **********************************************
+ Begin prism-clike.js
+********************************************** */
+
+Prism.languages.clike = {
+ 'comment': [
+ {
+ pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,
+ lookbehind: true,
+ greedy: true
+ },
+ {
+ pattern: /(^|[^\\:])\/\/.*/,
+ lookbehind: true,
+ greedy: true
+ }
+ ],
+ 'string': {
+ pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
+ greedy: true
+ },
+ 'class-name': {
+ pattern: /(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,
+ lookbehind: true,
+ inside: {
+ 'punctuation': /[.\\]/
+ }
+ },
+ 'keyword': /\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,
+ 'boolean': /\b(?:false|true)\b/,
+ 'function': /\b\w+(?=\()/,
+ 'number': /\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,
+ 'operator': /[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,
+ 'punctuation': /[{}[\];(),.:]/
+};
+
+
+/* **********************************************
+ Begin prism-javascript.js
+********************************************** */
+
+Prism.languages.javascript = Prism.languages.extend('clike', {
+ 'class-name': [
+ Prism.languages.clike['class-name'],
+ {
+ pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,
+ lookbehind: true
+ }
+ ],
+ 'keyword': [
+ {
+ pattern: /((?:^|\})\s*)catch\b/,
+ lookbehind: true
+ },
+ {
+ pattern: /(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,
+ lookbehind: true
+ },
+ ],
+ // Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444)
+ 'function': /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,
+ 'number': {
+ pattern: RegExp(
+ /(^|[^\w$])/.source +
+ '(?:' +
+ (
+ // constant
+ /NaN|Infinity/.source +
+ '|' +
+ // binary integer
+ /0[bB][01]+(?:_[01]+)*n?/.source +
+ '|' +
+ // octal integer
+ /0[oO][0-7]+(?:_[0-7]+)*n?/.source +
+ '|' +
+ // hexadecimal integer
+ /0[xX][\dA-Fa-f]+(?:_[\dA-Fa-f]+)*n?/.source +
+ '|' +
+ // decimal bigint
+ /\d+(?:_\d+)*n/.source +
+ '|' +
+ // decimal number (integer or float) but no bigint
+ /(?:\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\.\d+(?:_\d+)*)(?:[Ee][+-]?\d+(?:_\d+)*)?/.source
+ ) +
+ ')' +
+ /(?![\w$])/.source
+ ),
+ lookbehind: true
+ },
+ 'operator': /--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/
+});
+
+Prism.languages.javascript['class-name'][0].pattern = /(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/;
+
+Prism.languages.insertBefore('javascript', 'keyword', {
+ 'regex': {
+ pattern: RegExp(
+ // lookbehind
+ // eslint-disable-next-line regexp/no-dupe-characters-character-class
+ /((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)/.source +
+ // Regex pattern:
+ // There are 2 regex patterns here. The RegExp set notation proposal added support for nested character
+ // classes if the `v` flag is present. Unfortunately, nested CCs are both context-free and incompatible
+ // with the only syntax, so we have to define 2 different regex patterns.
+ /\//.source +
+ '(?:' +
+ /(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}/.source +
+ '|' +
+ // `v` flag syntax. This supports 3 levels of nested character classes.
+ /(?:\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.)*\])*\])*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}v[dgimyus]{0,7}/.source +
+ ')' +
+ // lookahead
+ /(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/.source
+ ),
+ lookbehind: true,
+ greedy: true,
+ inside: {
+ 'regex-source': {
+ pattern: /^(\/)[\s\S]+(?=\/[a-z]*$)/,
+ lookbehind: true,
+ alias: 'language-regex',
+ inside: Prism.languages.regex
+ },
+ 'regex-delimiter': /^\/|\/$/,
+ 'regex-flags': /^[a-z]+$/,
+ }
+ },
+ // This must be declared before keyword because we use "function" inside the look-forward
+ 'function-variable': {
+ pattern: /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,
+ alias: 'function'
+ },
+ 'parameter': [
+ {
+ pattern: /(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,
+ lookbehind: true,
+ inside: Prism.languages.javascript
+ },
+ {
+ pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,
+ lookbehind: true,
+ inside: Prism.languages.javascript
+ },
+ {
+ pattern: /(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,
+ lookbehind: true,
+ inside: Prism.languages.javascript
+ },
+ {
+ pattern: /((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(? [...]
+ lookbehind: true,
+ inside: Prism.languages.javascript
+ }
+ ],
+ 'constant': /\b[A-Z](?:[A-Z_]|\dx?)*\b/
+});
+
+Prism.languages.insertBefore('javascript', 'string', {
+ 'hashbang': {
+ pattern: /^#!.*/,
+ greedy: true,
+ alias: 'comment'
+ },
+ 'template-string': {
+ pattern: /`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,
+ greedy: true,
+ inside: {
+ 'template-punctuation': {
+ pattern: /^`|`$/,
+ alias: 'string'
+ },
+ 'interpolation': {
+ pattern: /((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,
+ lookbehind: true,
+ inside: {
+ 'interpolation-punctuation': {
+ pattern: /^\$\{|\}$/,
+ alias: 'punctuation'
+ },
+ rest: Prism.languages.javascript
+ }
+ },
+ 'string': /[\s\S]+/
+ }
+ },
+ 'string-property': {
+ pattern: /((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,
+ lookbehind: true,
+ greedy: true,
+ alias: 'property'
+ }
+});
+
+Prism.languages.insertBefore('javascript', 'operator', {
+ 'literal-property': {
+ pattern: /((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,
+ lookbehind: true,
+ alias: 'property'
+ },
+});
+
+if (Prism.languages.markup) {
+ Prism.languages.markup.tag.addInlined('script', 'javascript');
+
+ // add attribute support for all DOM events.
+ // https://developer.mozilla.org/en-US/docs/Web/Events#Standard_events
+ Prism.languages.markup.tag.addAttribute(
+ /on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)/.source,
+ 'javascript'
+ );
+}
+
+Prism.languages.js = Prism.languages.javascript;
+
+
+/* **********************************************
+ Begin prism-file-highlight.js
+********************************************** */
+
+(function () {
+
+ if (typeof Prism === 'undefined' || typeof document === 'undefined') {
+ return;
+ }
+
+ // https://developer.mozilla.org/en-US/docs/Web/API/Element/matches#Polyfill
+ if (!Element.prototype.matches) {
+ Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
+ }
+
+ var LOADING_MESSAGE = 'Loading…';
+ var FAILURE_MESSAGE = function (status, message) {
+ return '✖ Error ' + status + ' while fetching file: ' + message;
+ };
+ var FAILURE_EMPTY_MESSAGE = '✖ Error: File does not exist or is empty';
+
+ var EXTENSIONS = {
+ 'js': 'javascript',
+ 'py': 'python',
+ 'rb': 'ruby',
+ 'ps1': 'powershell',
+ 'psm1': 'powershell',
+ 'sh': 'bash',
+ 'bat': 'batch',
+ 'h': 'c',
+ 'tex': 'latex'
+ };
+
+ var STATUS_ATTR = 'data-src-status';
+ var STATUS_LOADING = 'loading';
+ var STATUS_LOADED = 'loaded';
+ var STATUS_FAILED = 'failed';
+
+ var SELECTOR = 'pre[data-src]:not([' + STATUS_ATTR + '="' + STATUS_LOADED + '"])'
+ + ':not([' + STATUS_ATTR + '="' + STATUS_LOADING + '"])';
+
+ /**
+ * Loads the given file.
+ *
+ * @param {string} src The URL or path of the source file to load.
+ * @param {(result: string) => void} success
+ * @param {(reason: string) => void} error
+ */
+ function loadFile(src, success, error) {
+ var xhr = new XMLHttpRequest();
+ xhr.open('GET', src, true);
+ xhr.onreadystatechange = function () {
+ if (xhr.readyState == 4) {
+ if (xhr.status < 400 && xhr.responseText) {
+ success(xhr.responseText);
+ } else {
+ if (xhr.status >= 400) {
+ error(FAILURE_MESSAGE(xhr.status, xhr.statusText));
+ } else {
+ error(FAILURE_EMPTY_MESSAGE);
+ }
+ }
+ }
+ };
+ xhr.send(null);
+ }
+
+ /**
+ * Parses the given range.
+ *
+ * This returns a range with inclusive ends.
+ *
+ * @param {string | null | undefined} range
+ * @returns {[number, number | undefined] | undefined}
+ */
+ function parseRange(range) {
+ var m = /^\s*(\d+)\s*(?:(,)\s*(?:(\d+)\s*)?)?$/.exec(range || '');
+ if (m) {
+ var start = Number(m[1]);
+ var comma = m[2];
+ var end = m[3];
+
+ if (!comma) {
+ return [start, start];
+ }
+ if (!end) {
+ return [start, undefined];
+ }
+ return [start, Number(end)];
+ }
+ return undefined;
+ }
+
+ Prism.hooks.add('before-highlightall', function (env) {
+ env.selector += ', ' + SELECTOR;
+ });
+
+ Prism.hooks.add('before-sanity-check', function (env) {
+ var pre = /** @type {HTMLPreElement} */ (env.element);
+ if (pre.matches(SELECTOR)) {
+ env.code = ''; // fast-path the whole thing and go to complete
+
+ pre.setAttribute(STATUS_ATTR, STATUS_LOADING); // mark as loading
+
+ // add code element with loading message
+ var code = pre.appendChild(document.createElement('CODE'));
+ code.textContent = LOADING_MESSAGE;
+
+ var src = pre.getAttribute('data-src');
+
+ var language = env.language;
+ if (language === 'none') {
+ // the language might be 'none' because there is no language set;
+ // in this case, we want to use the extension as the language
+ var extension = (/\.(\w+)$/.exec(src) || [, 'none'])[1];
+ language = EXTENSIONS[extension] || extension;
+ }
+
+ // set language classes
+ Prism.util.setLanguage(code, language);
+ Prism.util.setLanguage(pre, language);
+
+ // preload the language
+ var autoloader = Prism.plugins.autoloader;
+ if (autoloader) {
+ autoloader.loadLanguages(language);
+ }
+
+ // load file
+ loadFile(
+ src,
+ function (text) {
+ // mark as loaded
+ pre.setAttribute(STATUS_ATTR, STATUS_LOADED);
+
+ // handle data-range
+ var range = parseRange(pre.getAttribute('data-range'));
+ if (range) {
+ var lines = text.split(/\r\n?|\n/g);
+
+ // the range is one-based and inclusive on both ends
+ var start = range[0];
+ var end = range[1] == null ? lines.length : range[1];
+
+ if (start < 0) { start += lines.length; }
+ start = Math.max(0, Math.min(start - 1, lines.length));
+ if (end < 0) { end += lines.length; }
+ end = Math.max(0, Math.min(end, lines.length));
+
+ text = lines.slice(start, end).join('\n');
+
+ // add data-start for line numbers
+ if (!pre.hasAttribute('data-start')) {
+ pre.setAttribute('data-start', String(start + 1));
+ }
+ }
+
+ // highlight code
+ code.textContent = text;
+ Prism.highlightElement(code);
+ },
+ function (error) {
+ // mark as failed
+ pre.setAttribute(STATUS_ATTR, STATUS_FAILED);
+
+ code.textContent = error;
+ }
+ );
+ }
+ });
+
+ Prism.plugins.fileHighlight = {
+ /**
+ * Executes the File Highlight plugin for all matching `pre` elements under the given container.
+ *
+ * Note: Elements which are already loaded or currently loading will not be touched by this method.
+ *
+ * @param {ParentNode} [container=document]
+ */
+ highlight: function highlight(container) {
+ var elements = (container || document).querySelectorAll(SELECTOR);
+
+ for (var i = 0, element; (element = elements[i++]);) {
+ Prism.highlightElement(element);
+ }
+ }
+ };
+
+ var logged = false;
+ /** @deprecated Use `Prism.plugins.fileHighlight.highlight` instead. */
+ Prism.fileHighlight = function () {
+ if (!logged) {
+ console.warn('Prism.fileHighlight is deprecated. Use `Prism.plugins.fileHighlight.highlight` instead.');
+ logged = true;
+ }
+ Prism.plugins.fileHighlight.highlight.apply(this, arguments);
+ };
+
+}());
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism.min.css b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism.min.css
new file mode 100644
index 0000000000..8c4cc0576b
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/prism.min.css
@@ -0,0 +1 @@
+code[class*=language-],pre[class*=language-]{color:#000;background:0 0;text-shadow:0 1px #fff;font-family:Consolas,Monaco,'Andale Mono','Ubuntu Mono',monospace;font-size:1em;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}code[class*=language-] ::-moz-selection,code[class*=language-]::-moz-selection,pre[class*=language-] ::-m [...]
\ No newline at end of file
(groovy) 28/34: Extend JavadocAssertionTestBuilder for new comment forms
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit b6ff1b7aa376bd6b446b4238101e43bea981103a
Author: Paul King <pa...@asert.com.au>
AuthorDate: Tue Apr 21 08:09:22 2026 +1000
Extend JavadocAssertionTestBuilder for new comment forms
---
.../groovy/test/JavadocAssertionTestBuilder.groovy | 82 +++++++++++++++++++---
.../test/JavadocAssertionTestBuilderTest.groovy | 73 +++++++++++++++++++
2 files changed, 144 insertions(+), 11 deletions(-)
diff --git a/subprojects/groovy-test/src/main/groovy/groovy/test/JavadocAssertionTestBuilder.groovy b/subprojects/groovy-test/src/main/groovy/groovy/test/JavadocAssertionTestBuilder.groovy
index 71cc863e42..e0df783171 100644
--- a/subprojects/groovy-test/src/main/groovy/groovy/test/JavadocAssertionTestBuilder.groovy
+++ b/subprojects/groovy-test/src/main/groovy/groovy/test/JavadocAssertionTestBuilder.groovy
@@ -21,20 +21,44 @@ package groovy.test
import java.util.regex.Pattern
/**
- * <code>JavadocAssertionTestBuilder</code> will dynamically create a test cases from Groovy assertions placed within
- * the Javadoc comments of a source file. Assertions should be placed within an html tag with a <code>class="groovyTestCase"</code>
- * attribute assignment. Example:
- * <pre><pre class="groovyTestCase"> assert "example".size() == 7 </pre></pre>
- * When extracting the code for the test, single-line snippets of code without braces within a {{@code @code} ...}
- * tag will have the javadoc {@code code} tag stripped. Similarly, html entities are converted back when extracting
- * code, so {@code <} and {@code >} will be converted to {@code <} and {@code >}.
+ * <code>JavadocAssertionTestBuilder</code> dynamically creates test cases from Groovy assertions placed within
+ * the doc comments of a source file. Three authoring forms are recognised:
+ *
+ * <ol>
+ * <li>Traditional Javadoc with an HTML wrapper carrying <code>class="groovyTestCase"</code>:
+ * <pre>/** <pre class="groovyTestCase"> assert "example".size() == 7 </pre> */</pre></li>
+ * <li>JEP 467 Markdown doc comments (triple-slash <code>///</code> runs) with the same HTML wrapper — Markdown
+ * passes inline HTML through, so the existing convention works unchanged:
+ * <pre>/// <pre class="groovyTestCase"> assert 1 + 1 == 2 </pre></pre></li>
+ * <li>Fenced Markdown code block inside a <code>///</code> run whose infostring is <code>groovy groovyTestCase</code>.
+ * CommonMark uses the first word as the language (so Prism/highlight.js still highlight the body as Groovy); the
+ * second word is the test marker recognised by this builder when it scans the source:
+ * <pre>
+ * /// ```groovy groovyTestCase
+ * /// assert 2 + 2 == 4
+ * /// ```
+ * </pre></li>
+ * </ol>
+ *
+ * When extracting the code for an HTML-wrapper test, single-line snippets of code within a {{@code @code} ...}
+ * tag have the javadoc {@code code} tag stripped, and HTML entities are converted back so that {@code <} and
+ * {@code >} become {@code <} and {@code >}. Fenced-block extractions pass through without HTML decoding
+ * because Markdown fenced blocks hold raw source already.
*/
class JavadocAssertionTestBuilder {
// TODO write tests for this classes functionality
+ // Match both traditional `/** ... */` Javadoc and contiguous `///` Markdown doc-comment runs.
private static final Pattern javadocPattern =
- Pattern.compile( /(?ims)\/\*\*.*?\*\// )
+ Pattern.compile( /(?ims)\/\*\*.*?\*\/|(?-s:(?:^[ \t]*\/\/\/[^\n]*\n?)+)/ )
+ // Two authoring forms for the assertion inside a doc comment:
+ // - HTML wrapper: <pre class="groovyTestCase">...</pre> (or <code>, <samp>, ...)
+ // - Fenced Markdown: ```groovy groovyTestCase ... ``` — only recognised within `///` runs
+ // (Javadoc `/** */` is not Markdown, so there's no ambiguity).
private static final Pattern assertionPattern =
- Pattern.compile( /(?ims)<([a-z]+)\s+class\s*=\s*['"]groovyTestCase['"]\s*>.*?<\s*\/\s*\1>/ )
+ Pattern.compile(
+ /(?ims)<([a-z]+)\s+class\s*=\s*['"]groovyTestCase['"]\s*>.*?<\s*\/\s*\1>/
+ + /|(?m:^[ \t]*\/\/\/[ \t]*```groovy[ \t]+groovyTestCase\b[^\n]*\n(?s:.*?)^[ \t]*\/\/\/[ \t]*```)/
+ )
Class buildTest(String filename, String code) {
Class test = null
@@ -77,7 +101,12 @@ class JavadocAssertionTestBuilder {
int codeIndex = 0
assertionTags.each { tag ->
codeIndex = code.indexOf(tag, codeIndex)
- int lineNumber = code.substring(0, codeIndex).findAll("(?m)^").size()
+ // Counting newlines (+1 for the starting line) rather than matching
+ // `(?m)^` avoids the end-of-input edge case where a match that
+ // anchors at a line start lands on the first character right after
+ // the substring's trailing newline — Java's (?m)^ does not match
+ // at end-of-input, which would otherwise under-count by one.
+ int lineNumber = code.substring(0, codeIndex).count('\n') + 1
codeIndex += tag.size()
String assertion = getAssertion(tag)
@@ -89,8 +118,19 @@ class JavadocAssertionTestBuilder {
}
private String getAssertion(String tag) {
+ // Dispatch on the leading non-whitespace character — the unified
+ // assertion pattern can match either an HTML wrapper (`<...>...</...>`)
+ // or a fenced code block (whose first non-blank line starts with
+ // `///` leading a backtick fence).
+ String trimmed = tag.trim()
+ if (trimmed.startsWith('<')) return getHtmlWrapperAssertion(tag)
+ return getFencedAssertion(tag)
+ }
+
+ private String getHtmlWrapperAssertion(String tag) {
String tagInner = tag.substring(tag.indexOf(">")+1, tag.lastIndexOf("<"))
- String htmlAssertion = tagInner.replaceAll("(?m)^\\s*\\*\\s?", "")
+ // Strip `* ` (traditional Javadoc) OR `/// ` (JEP 467 Markdown) line prefixes.
+ String htmlAssertion = tagInner.replaceAll("(?m)^\\s*(?:\\*|\\/\\/\\/)\\s?", "")
String assertion = htmlAssertion
// TODO improve on this
[nbsp:' ', gt:'>', lt:'<', quot:'"', apos:"'", at:'@', '#64':'@', ndash:'-', amp:'&'].each { key, value ->
@@ -100,6 +140,26 @@ class JavadocAssertionTestBuilder {
return assertion
}
+ // Extract the body of a fenced `` ```groovy groovyTestCase ... ``` `` block
+ // embedded in a `///` run. Strip the opening and closing fence lines, and
+ // remove the `///` line prefix (plus one optional space) from each body line.
+ // No HTML-entity decoding — fenced code holds raw source already.
+ private String getFencedAssertion(String tag) {
+ def lines = tag.split('\n', -1)
+ if (lines.size() < 2) return ''
+ // Drop the opening fence line. Also drop the closing fence line if the
+ // last line is one; otherwise keep everything after the opener.
+ int start = 1
+ int end = lines.size()
+ if (lines[-1].trim().matches(/\/\/\/\s*```.*/)) end = lines.size() - 1
+ StringBuilder sb = new StringBuilder()
+ for (int k = start; k < end; k++) {
+ if (sb.length() > 0) sb.append('\n')
+ sb.append(lines[k].replaceFirst(/^\s*\/\/\/\s?/, ''))
+ }
+ return sb.toString()
+ }
+
private List getTestMethods(Map lineNumberToAssertions, String filename) {
List testMethods = lineNumberToAssertions.collect { lineNumber, assertions ->
Character differentiator = 'a'
diff --git a/subprojects/groovy-test/src/test/groovy/groovy/test/JavadocAssertionTestBuilderTest.groovy b/subprojects/groovy-test/src/test/groovy/groovy/test/JavadocAssertionTestBuilderTest.groovy
index a560a2ff96..86426a56d0 100644
--- a/subprojects/groovy-test/src/test/groovy/groovy/test/JavadocAssertionTestBuilderTest.groovy
+++ b/subprojects/groovy-test/src/test/groovy/groovy/test/JavadocAssertionTestBuilderTest.groovy
@@ -135,6 +135,79 @@ class JavadocAssertionTestBuilderTest {
}
}
+ // Stage A — /// Markdown doc comment with the existing HTML-wrapper convention.
+ @Test
+ void testTripleSlashCommentWithHtmlWrapper() {
+ Class test = builder.buildTest("SomeClass.groovy", '''
+ /// <pre class="groovyTestCase"> assert 1 + 1 == 2 </pre>
+ class SomeClass { }
+ ''')
+ assert test != null
+ assert test.methods.findAll { it.name =~ /test.*/ }.size() == 1
+ test.newInstance().testAssertionFromSomeClassLine2()
+ }
+
+ // Stage A — /// Markdown doc comment spanning multiple lines with a HTML wrapper.
+ @Test
+ void testTripleSlashCommentMultilineHtmlWrapper() {
+ Class test = builder.buildTest("SomeClass.groovy", '''
+ /// <pre class="groovyTestCase">
+ /// assert 2 + 2 == 4
+ /// assert "x".size() == 1
+ /// </pre>
+ class SomeClass { }
+ ''')
+ assert test != null
+ test.newInstance().testAssertionFromSomeClassLine2()
+ }
+
+ // Stage B — fenced Markdown code block inside a /// run. The infostring
+ // `groovy groovyTestCase` uses the first word as the language (keeps syntax
+ // highlighting working) and the second as the test marker.
+ @Test
+ void testFencedCodeBlockAssertion() {
+ Class test = builder.buildTest("SomeClass.groovy", '''
+ /// Some intro prose.
+ ///
+ /// ```groovy groovyTestCase
+ /// assert 2 + 2 == 4
+ /// ```
+ ///
+ /// More prose.
+ class SomeClass { }
+ ''')
+ assert test != null
+ assert test.methods.findAll { it.name =~ /test.*/ }.size() == 1
+ test.newInstance().testAssertionFromSomeClassLine4()
+ }
+
+ // Stage B — fenced block assertion that fails still fails.
+ @Test
+ void testFencedCodeBlockFailingAssertion() {
+ Class test = builder.buildTest("SomeClass.groovy", '''
+ /// ```groovy groovyTestCase
+ /// assert false
+ /// ```
+ class SomeClass { }
+ ''')
+ shouldFail(AssertionError) {
+ test.newInstance().testAssertionFromSomeClassLine2()
+ }
+ }
+
+ // Stage B — a fenced block whose infostring is just `groovy` (no
+ // groovyTestCase marker) must NOT be turned into a test.
+ @Test
+ void testFencedCodeBlockWithoutMarkerIgnored() {
+ Class test = builder.buildTest("SomeClass.groovy", '''
+ /// ```groovy
+ /// assert false
+ /// ```
+ class SomeClass { }
+ ''')
+ assert test == null
+ }
+
@Test
void testDecodesCommonHtml() {
Class test = builder.buildTest("SomeClass.java", '''
(groovy) 31/34: update doco
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit c1e892cd7d924eb4a4b3326fa547adf10f7873e4
Author: Paul King <pa...@asert.com.au>
AuthorDate: Tue Apr 21 13:25:55 2026 +1000
update doco
---
subprojects/groovy-groovydoc/src/spec/doc/groovydoc.adoc | 15 ++++++++++++++-
1 file changed, 14 insertions(+), 1 deletion(-)
diff --git a/subprojects/groovy-groovydoc/src/spec/doc/groovydoc.adoc b/subprojects/groovy-groovydoc/src/spec/doc/groovydoc.adoc
index 39d5940485..c3c3b802d7 100644
--- a/subprojects/groovy-groovydoc/src/spec/doc/groovydoc.adoc
+++ b/subprojects/groovy-groovydoc/src/spec/doc/groovydoc.adoc
@@ -286,12 +286,25 @@ package specs to exclude. |No
|doctitle |HTML shown at the top of the overview page. |No
|header, footer |HTML shown at the top/bottom of every page. |No
|overview |HTML file read as the overview page. |No
+|charset |Charset for cross-platform viewing of generated HTML. |No
+|fileEncoding |Charset used when writing the generated files. |No
+|author |Include `@author` paragraphs. Defaults to `true`. |No
+|processScripts |Process Groovy scripts. Defaults to `true`; set to
+`false` to mirror the CLI `-noscripts` flag. |No
+|includeMainForScripts |Include the synthetic `public static void main`
+method when documenting scripts. Defaults to `true`; set to `false` to
+mirror the CLI `-nomainforscripts` flag. |No
|stylesheetFile |Replace the default stylesheet with a supplied one. |No
|private |Show all classes and members (including private ones). |No
-|access |Visibility scope: `public`, `protected`, `package`, `private`. |No
+|public, protected, package |Set individually to control the visibility
+scope; equivalent to the CLI `-public`, `-protected`, `-package` flags. |No
+|access |Alternative to the boolean scope attributes above. Accepts
+`public`, `protected`, `package`, or `private`. |No
|javaVersion |Language version for Java source files. |No
|extensions |Colon-separated source extensions (default
`.java:.groovy:.gv:.gvy:.gsh`). |No
+|use |Legacy Javadoc option accepted for parity. Has no effect on
+groovydoc output. |No
|showInternal |Include members annotated with
`groovy.transform.@Internal`. |No
|noIndex, noDeprecatedList, noHelp |Suppress the matching auxiliary page. |No
(groovy) 34/34: minor refactor: copilot flagged concerns
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit f83ec905f92576f0b76b4c2415b984c07515fff4
Author: Paul King <pa...@asert.com.au>
AuthorDate: Tue Apr 21 15:35:20 2026 +1000
minor refactor: copilot flagged concerns
---
.../src/main/java/org/codehaus/groovy/ant/Groovydoc.java | 3 ++-
.../org/codehaus/groovy/tools/groovydoc/Main.groovy | 16 ++++++++++------
.../tools/groovydoc/antlr4/GroovydocJavaVisitor.java | 10 +++++++++-
.../gstringTemplates/packageLevel/package-summary.html | 6 +++---
4 files changed, 24 insertions(+), 11 deletions(-)
diff --git a/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java b/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java
index caa165c600..050d0b5a82 100644
--- a/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java
+++ b/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java
@@ -287,7 +287,8 @@ public class Groovydoc extends Task {
public void setExcludePackageNames(String packages) {
StringTokenizer tok = new StringTokenizer(packages, ",:");
while (tok.hasMoreTokens()) {
- excludePackageNames.add(tok.nextToken());
+ String name = tok.nextToken().trim();
+ if (!name.isEmpty()) excludePackageNames.add(name);
}
}
diff --git a/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy b/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy
index 8a6ac77878..3748370f81 100644
--- a/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy
+++ b/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy
@@ -122,12 +122,16 @@ class Main {
if (options.stylesheetfile) {
styleSheetFile = new File(options.stylesheetfile)
}
- if (options.addStylesheet) {
- // CliBuilder with args:1 gives a single value; use comma separator
- // to accept multiple paths in one flag. Example:
- // --add-stylesheet custom1.css,custom2.css
- options.addStylesheet.toString().tokenize(',').each { p ->
- addStylesheetFiles << new File(p.trim())
+ if (options.addStylesheets) {
+ // Accept both `-addStylesheet a.css -addStylesheet b.css`
+ // (repeated flag — `options.addStylesheets` plural returns every
+ // occurrence) and comma-separated forms in a single flag
+ // (e.g. `-addStylesheet a.css,b.css`). Empty tokens dropped.
+ options.addStylesheets.each { raw ->
+ String.valueOf(raw).tokenize(',').each { p ->
+ def trimmed = p.trim()
+ if (trimmed) addStylesheetFiles << new File(trimmed)
+ }
}
}
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/antlr4/GroovydocJavaVisitor.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/antlr4/GroovydocJavaVisitor.java
index 720220bf09..9578bdaee4 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/antlr4/GroovydocJavaVisitor.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/antlr4/GroovydocJavaVisitor.java
@@ -328,7 +328,15 @@ public class GroovydocJavaVisitor
String name = an.getNameAsString();
if ("Internal".equals(name) || name.endsWith(".Internal")) return true;
}
- if (n instanceof FieldDeclaration fd && fd.getVariable(0).getNameAsString().contains("$")) return true;
+ if (n instanceof FieldDeclaration fd) {
+ // Java allows multiple variables per field declaration (`int a, b$;`).
+ // Treat the whole declaration as internal if *any* variable name
+ // contains the synthetic-name marker; picking only the first would
+ // mis-classify `int a, b$;` as non-internal.
+ for (int k = 0; k < fd.getVariables().size(); k++) {
+ if (fd.getVariable(k).getNameAsString().contains("$")) return true;
+ }
+ }
if (n instanceof MethodDeclaration md && md.getNameAsString().contains("$")) return true;
if (n instanceof ConstructorDeclaration cd && cd.getNameAsString().contains("$")) return true;
return false;
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html
index 1a6a17d852..db85fd1a8a 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html
@@ -163,9 +163,9 @@ classTypes.each { k, v ->
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-tree.html">Tree</a></li>
- <% if (props.noDeprecatedList != 'true') { %><% if (props.noDeprecatedList != 'true') { %><li><a href="deprecated-list.html">Deprecated</a></li><% } %><% } %>
- <% if (props.noIndex != 'true') { %><% if (props.noIndex != 'true') { %><li><a href="index-all.html">Index</a></li><% } %><% } %>
- <% if (props.noHelp != 'true') { %><% if (props.noHelp != 'true') { %><li><a href="help-doc.html">Help</a></li><% } %><% } %>
+ <% if (props.noDeprecatedList != 'true') { %><li><a href="deprecated-list.html">Deprecated</a></li><% } %>
+ <% if (props.noIndex != 'true') { %><li><a href="index-all.html">Index</a></li><% } %>
+ <% if (props.noHelp != 'true') { %><li><a href="help-doc.html">Help</a></li><% } %>
</ul>
</div>
<div class="subNav">
(groovy) 12/34: GROOVY-11938: {@snippet} per JEP 413 (phase 1: inline {@snippet} with attributes, HTML escape, dedent )
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit d27df886a293350b7785e5acc50fc99bec089a79
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Apr 20 18:57:55 2026 +1000
GROOVY-11938: {@snippet} per JEP 413 (phase 1: inline {@snippet} with attributes, HTML escape, dedent )
---
.../groovy/tools/groovydoc/TagRenderer.java | 182 ++++++++++++++++++++-
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 36 ++++
.../groovydoc/testfiles/ClassWithSnippetTag.groovy | 38 +++++
3 files changed, 249 insertions(+), 7 deletions(-)
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
index 50ce5b7d9f..8bb6a701e3 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
@@ -38,7 +38,11 @@ import java.util.Map;
* <p>Supported inline tags: {@code {@link ...}}, {@code {@see ...}},
* {@code {@code ...}}, {@code {@literal ...}} (class-level only),
* {@code {@interface ...}} (swallowed), {@code {@value #FIELD}} /
- * {@code {@value pkg.Class#FIELD}} (GROOVY-6016).
+ * {@code {@value pkg.Class#FIELD}} (GROOVY-6016),
+ * {@code {@inheritDoc}} (GROOVY-3782 — inline form, full parent comment
+ * substituted), inline {@code {@snippet}} (GROOVY-11938 stage 1 — renders
+ * as {@code <pre><code>} with language/id/class attributes and
+ * HTML-escaped body).
*
* <p>Supported block tags: {@code @see}, {@code @param}, {@code @return},
* {@code @throws} / {@code @exception}, {@code @since}, {@code @author},
@@ -49,12 +53,21 @@ import java.util.Map;
* <h2>Known limitations / pending work</h2>
* <ul>
* <li>Bare {@code {@value}} (no body, referencing the current field's own
- * constant value) is not yet supported. It requires threading the
- * current member through {@code TagRenderer}; the tag currently falls
- * through to verbatim emission. {@code {@value #FIELD}} and
- * {@code {@value Class#FIELD}} both work.</li>
- * <li>{@code {@inheritDoc}} — GROOVY-3782, pending.</li>
- * <li>{@code {@snippet}} — GROOVY-11938, pending.</li>
+ * constant value) is not yet supported — see task #25. The forms
+ * {@code {@value #FIELD}} and {@code {@value Class#FIELD}} both work.</li>
+ * <li>{@code {@snippet}} external form ({@code file="..."} /
+ * {@code region="..."} reading from a package's
+ * {@code snippet-files/} directory) not yet implemented — stage 2
+ * of GROOVY-11938.</li>
+ * <li>{@code {@snippet}} markup comments ({@code // @highlight},
+ * {@code @replace}, {@code @link}, {@code @start}/{@code @end})
+ * not yet implemented — stage 3 of GROOVY-11938.</li>
+ * <li>Client-side syntax highlighting assets (Prism.js / highlight.js)
+ * not yet wired in — stage 4 of GROOVY-11938.</li>
+ * <li>{@code {@inheritDoc}} inherits the full parent comment rather than
+ * position-aware substitution inside specific block tags (e.g.
+ * {@code @param x {@inheritDoc}} inheriting just the parent's
+ * {@code @param x}). Reasonable initial implementation.</li>
* <li>JEP 467 Markdown reference links — GROOVY-11542, pending.</li>
* </ul>
*
@@ -222,6 +235,12 @@ final class TagRenderer {
if (nameEnd == nameStart) return 0;
String name = text.substring(nameStart, nameEnd);
if (!isKnownInlineTag(name, cfg)) return 0;
+ // GROOVY-11938: {@snippet} has JEP 413 body-parsing rules — attributes
+ // before an optional `:`, then a brace-balanced body that may contain
+ // source code with its own `{`/`}`. Needs its own parser.
+ if ("snippet".equals(name)) {
+ return renderSnippetAt(text, start, nameEnd, out);
+ }
int bodyStart = skipWhitespace(text, nameEnd);
// Match the previous regex's laxness: body extends to the first '}'.
int close = text.indexOf('}', bodyStart);
@@ -231,6 +250,154 @@ final class TagRenderer {
return close + 1 - start;
}
+ /**
+ * GROOVY-11938: render a {@code {@snippet}} tag per JEP 413.
+ *
+ * <p>Stage 1 supports the inline form:
+ * <pre>
+ * {@snippet [attr=value ...] :
+ * ... code body (may contain matched braces) ...
+ * }
+ * </pre>
+ * Emitted as {@code <pre><code class="language-xxx">...escaped body...</code></pre>}
+ * with HTML-safe angle-bracket encoding of the body so code is preserved
+ * verbatim. Attributes recognised so far: {@code lang} (→ language class),
+ * {@code id}, {@code class} (attribute merged with language).
+ *
+ * <p>Deferred stages: external form with {@code file=...}/{@code region=...}
+ * reading from a package's {@code snippet-files/} directory; markup comments
+ * {@code // @highlight}, {@code // @replace}, {@code // @link},
+ * {@code // @start}/{@code // @end} for annotated regions; client-side
+ * syntax highlighting assets. See the ticket for the full scope.
+ *
+ * @return characters consumed starting from {@code start} (the {@code '{'})
+ * or 0 if the tag is malformed.
+ */
+ private static int renderSnippetAt(String text, int start, int nameEnd, StringBuilder out) {
+ int n = text.length();
+ int i = skipWhitespace(text, nameEnd);
+
+ java.util.Map<String, String> attrs = new LinkedHashMap<>();
+ while (i < n) {
+ char c = text.charAt(i);
+ if (c == ':' || c == '}') break;
+ if (Character.isWhitespace(c)) { i++; continue; }
+ // Read attribute name.
+ int nameS = i;
+ while (i < n) {
+ char ch = text.charAt(i);
+ if (ch == '=' || ch == ':' || ch == '}' || Character.isWhitespace(ch)) break;
+ i++;
+ }
+ String attrName = text.substring(nameS, i);
+ i = skipWhitespace(text, i);
+ String attrValue = "";
+ if (i < n && text.charAt(i) == '=') {
+ i++;
+ i = skipWhitespace(text, i);
+ if (i >= n) return 0;
+ char q = text.charAt(i);
+ if (q == '"' || q == '\'') {
+ int close = text.indexOf(q, i + 1);
+ if (close < 0) return 0;
+ attrValue = text.substring(i + 1, close);
+ i = close + 1;
+ } else {
+ int valS = i;
+ while (i < n) {
+ char ch = text.charAt(i);
+ if (ch == ':' || ch == '}' || Character.isWhitespace(ch)) break;
+ i++;
+ }
+ attrValue = text.substring(valS, i);
+ }
+ }
+ if (!attrName.isEmpty()) attrs.put(attrName, attrValue);
+ }
+ if (i >= n) return 0;
+
+ String body;
+ int endPos;
+ if (text.charAt(i) == ':') {
+ int bodyStart = i + 1;
+ // Brace-balanced body — consume until the matching close of the
+ // outer {@snippet ...}.
+ int depth = 1;
+ int j = bodyStart;
+ while (j < n && depth > 0) {
+ char c = text.charAt(j);
+ if (c == '{') depth++;
+ else if (c == '}') {
+ depth--;
+ if (depth == 0) break;
+ }
+ j++;
+ }
+ if (depth != 0) return 0; // unterminated
+ body = text.substring(bodyStart, j);
+ endPos = j + 1; // past the final '}'
+ } else {
+ // External form ({@snippet file="..." region="..."}) — not yet
+ // implemented. Bail and let the outer caller emit verbatim.
+ return 0;
+ }
+
+ String langClass = attrs.getOrDefault("lang", "");
+ String extraClass = attrs.getOrDefault("class", "");
+ String combined = (langClass.isEmpty() ? "" : "language-" + langClass)
+ + (extraClass.isEmpty() ? "" : (langClass.isEmpty() ? extraClass : " " + extraClass));
+ String dedented = dedent(body);
+ out.append("<pre><code");
+ if (!combined.isEmpty()) out.append(" class=\"").append(combined).append('"');
+ String id = attrs.get("id");
+ if (id != null && !id.isEmpty()) out.append(" id=\"").append(id).append('"');
+ out.append('>').append(SimpleGroovyClassDoc.encodeAngleBrackets(dedented)).append("</code></pre>");
+ return endPos - start;
+ }
+
+ /**
+ * Strip leading blank lines from a snippet body and remove the common
+ * indentation (smallest non-empty leading-whitespace prefix) — matches
+ * JEP 413's convention so indentation in the source doesn't leak into
+ * the rendered snippet.
+ */
+ private static String dedent(String body) {
+ // Drop the first line if it's only whitespace (typical when the body
+ // starts right after the `:` with a newline).
+ int firstNl = body.indexOf('\n');
+ if (firstNl >= 0) {
+ boolean firstLineBlank = true;
+ for (int k = 0; k < firstNl; k++) {
+ if (!Character.isWhitespace(body.charAt(k))) { firstLineBlank = false; break; }
+ }
+ if (firstLineBlank) body = body.substring(firstNl + 1);
+ }
+ // Strip trailing whitespace on the final line (body text before the
+ // closing `}` often has one) so `</code></pre>` lands cleanly.
+ int end = body.length();
+ while (end > 0 && (body.charAt(end - 1) == ' ' || body.charAt(end - 1) == '\t')) end--;
+ body = body.substring(0, end);
+ // Compute common leading indentation across non-blank lines.
+ String[] lines = body.split("\n", -1);
+ int common = Integer.MAX_VALUE;
+ for (String line : lines) {
+ if (line.isEmpty()) continue;
+ int lead = 0;
+ while (lead < line.length() && (line.charAt(lead) == ' ' || line.charAt(lead) == '\t')) lead++;
+ if (lead == line.length()) continue; // all-whitespace line
+ if (lead < common) common = lead;
+ }
+ if (common == Integer.MAX_VALUE || common == 0) return body;
+ StringBuilder sb = new StringBuilder(body.length());
+ for (int li = 0; li < lines.length; li++) {
+ if (li > 0) sb.append('\n');
+ String line = lines[li];
+ if (line.length() >= common) sb.append(line, common, line.length());
+ else sb.append(line);
+ }
+ return sb.toString();
+ }
+
private static boolean isKnownInlineTag(String name, Config cfg) {
switch (name) {
case "link":
@@ -239,6 +406,7 @@ final class TagRenderer {
case "interface":
case "value":
case "inheritDoc":
+ case "snippet":
return true;
case "literal":
return cfg.literalEnabled;
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index eca92b1b49..6ef31fdd59 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -147,6 +147,42 @@ public class GroovyDocToolTest extends GroovyTestCase {
doc.contains("{<DL><DT><B>inheritDoc") || doc.contains("inheritDoc:</B>"));
}
+ // GROOVY-11938 stage 1: the inline {@snippet} tag renders its body as a
+ // verbatim <pre><code>...</code></pre> block with HTML-escaped content,
+ // an optional language class, id, and extra class.
+ public void testSnippetTagInlineFormRendersAsPreCode() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ htmlTool.add(List.of(base + "/ClassWithSnippetTag.groovy"));
+
+ MockOutputTool output = new MockOutputTool();
+ htmlTool.renderToOutput(output, MOCK_DIR);
+
+ String doc = output.getText(MOCK_DIR + "/" + base + "/ClassWithSnippetTag.html");
+ assertNotNull(doc);
+ // Groovy snippet: check <pre><code class="language-groovy"> wrapping.
+ assertTrue("Expected <pre><code class='language-groovy'> in:\n" + doc,
+ doc.contains("<pre><code class=\"language-groovy\">"));
+ // Body content preserved: the `def greet` line should appear escape-free
+ // (Groovy has no angle brackets in this snippet).
+ assertTrue("Expected snippet body content in:\n" + doc,
+ doc.contains("def greet(String name)"));
+ // HTML escaping: `<` in the Java snippet must appear as <
+ assertTrue("Expected HTML-escaped '<' in snippet body in:\n" + doc,
+ doc.contains("if (x < y)"));
+ // Language + class merged.
+ assertTrue("Expected language-java + example class merged in:\n" + doc,
+ doc.contains("class=\"language-java example\""));
+ // id attribute emitted.
+ assertTrue("Expected id=\"hello\" in:\n" + doc,
+ doc.contains("id=\"hello\""));
+ // No literal `{@snippet lang=...` with attributes (i.e. an unprocessed
+ // real snippet tag). Note that `{@code {@snippet}}` patterns in the
+ // surrounding description legitimately render as literal text inside
+ // a <CODE> block, so checking for bare `{@snippet` is too strict.
+ assertFalse("{@snippet ... } with attributes should be substituted in:\n" + doc,
+ doc.contains("{@snippet lang="));
+ }
+
// GROOVY-3782 (the actual {@inheritDoc} tag): the child method's doc
// should be expanded with the parent's rendered description plus tags.
public void testInheritDocSubstitutesParentMethodDoc() throws Exception {
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithSnippetTag.groovy b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithSnippetTag.groovy
new file mode 100644
index 0000000000..acd1da078d
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithSnippetTag.groovy
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.codehaus.groovy.tools.groovydoc.testfiles
+
+/**
+ * GROOVY-11938: exercise the inline {@code {@snippet}} tag per JEP 413.
+ *
+ * {@snippet lang=groovy :
+ * def greet(String name) {
+ * "hello $name"
+ * }
+ * assert greet('world') == 'hello world'
+ * }
+ *
+ * Also with a class attribute and id:
+ *
+ * {@snippet lang=java class="example" id=hello :
+ * if (x < y) { System.out.println("ok"); }
+ * }
+ */
+class ClassWithSnippetTag {
+}
(groovy) 13/34: GROOVY-11938: {@snippet} per JEP 413 (phase 2: external {@snippet file=…})
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 9f56fed06e03de9136c99e4e57e1611677c4d055
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Apr 20 19:04:47 2026 +1000
GROOVY-11938: {@snippet} per JEP 413 (phase 2: external {@snippet file=…})
---
.../testfiles/docfiles/doc-files/sample.html | 19 +++++
.../testfiles/docfiles/doc-files/sub/nested.txt | 18 ++++
.../docfiles/snippet-files/Example.groovy} | 11 +--
.../docfiles/snippet-files/Regioned.groovy} | 19 +++--
.../tools/groovydoc/GroovyRootDocBuilder.java | 2 +
.../tools/groovydoc/SimpleGroovyRootDoc.java | 10 +++
.../groovy/tools/groovydoc/TagRenderer.java | 84 +++++++++++++++++--
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 98 ++++++++++++++++++++++
.../testfiles/docfiles/HasDocFiles.groovy | 4 +
.../Regioned.groovy} | 19 +++--
10 files changed, 256 insertions(+), 28 deletions(-)
diff --git a/subprojects/groovy-groovydoc/mock/doc/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/doc-files/sample.html b/subprojects/groovy-groovydoc/mock/doc/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/doc-files/sample.html
new file mode 100644
index 0000000000..13cb5468c2
--- /dev/null
+++ b/subprojects/groovy-groovydoc/mock/doc/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/doc-files/sample.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you 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
+
+ http://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.
+-->
+<html><body><p>GROOVY-5986 sample doc-files content.</p></body></html>
diff --git a/subprojects/groovy-groovydoc/mock/doc/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/doc-files/sub/nested.txt b/subprojects/groovy-groovydoc/mock/doc/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/doc-files/sub/nested.txt
new file mode 100644
index 0000000000..6dfb255360
--- /dev/null
+++ b/subprojects/groovy-groovydoc/mock/doc/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/doc-files/sub/nested.txt
@@ -0,0 +1,18 @@
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you 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
+
+ http://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.
+
+GROOVY-5986: nested doc-files content, verifies recursive copy.
diff --git a/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/HasDocFiles.groovy b/subprojects/groovy-groovydoc/mock/doc/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/snippet-files/Example.groovy
similarity index 76%
copy from subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/HasDocFiles.groovy
copy to subprojects/groovy-groovydoc/mock/doc/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/snippet-files/Example.groovy
index 3be3ce5450..a84f295664 100644
--- a/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/HasDocFiles.groovy
+++ b/subprojects/groovy-groovydoc/mock/doc/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/snippet-files/Example.groovy
@@ -16,12 +16,5 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.codehaus.groovy.tools.groovydoc.testfiles.docfiles
-
-/**
- * GROOVY-5986: sample class in a package that has a {@code doc-files/}
- * and {@code snippet-files/} subdirectory to be copied verbatim into
- * the generated docs.
- */
-class HasDocFiles {
-}
+// GROOVY-5986 / GROOVY-11938: sample snippet for future {@snippet file=...} use.
+println "hello from Example"
diff --git a/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/HasDocFiles.groovy b/subprojects/groovy-groovydoc/mock/doc/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/snippet-files/Regioned.groovy
similarity index 76%
copy from subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/HasDocFiles.groovy
copy to subprojects/groovy-groovydoc/mock/doc/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/snippet-files/Regioned.groovy
index 3be3ce5450..f252d74a6f 100644
--- a/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/HasDocFiles.groovy
+++ b/subprojects/groovy-groovydoc/mock/doc/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/snippet-files/Regioned.groovy
@@ -16,12 +16,17 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.codehaus.groovy.tools.groovydoc.testfiles.docfiles
-/**
- * GROOVY-5986: sample class in a package that has a {@code doc-files/}
- * and {@code snippet-files/} subdirectory to be copied verbatim into
- * the generated docs.
- */
-class HasDocFiles {
+def setup() {
+ println "this is outside the region"
+}
+
+// @start region=core
+def coreLogic(int x) {
+ return x * 2
+}
+// @end region=core
+
+def teardown() {
+ println "also outside"
}
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyRootDocBuilder.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyRootDocBuilder.java
index af24ef27d9..901c72cb01 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyRootDocBuilder.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyRootDocBuilder.java
@@ -59,6 +59,8 @@ public class GroovyRootDocBuilder {
this.sourcepaths = sourcepaths == null ? null : Arrays.copyOf(sourcepaths, sourcepaths.length);
this.links = links;
this.rootDoc = new SimpleGroovyRootDoc("root");
+ // GROOVY-11938: propagate for render-time snippet-file resolution.
+ this.rootDoc.setSourcepaths(this.sourcepaths);
this.properties = properties;
}
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyRootDoc.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyRootDoc.java
index 931e910ec4..a218193c65 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyRootDoc.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyRootDoc.java
@@ -44,6 +44,8 @@ public class SimpleGroovyRootDoc extends SimpleGroovyDoc implements GroovyRootDo
private final ClassNamedCache classNamedCache;
private String description = "";
+ /** GROOVY-11938: snippet-file resolution needs access to source dirs at render time. */
+ private String[] sourcepaths = new String[0];
public SimpleGroovyRootDoc(String name) {
super(name);
@@ -53,6 +55,14 @@ public class SimpleGroovyRootDoc extends SimpleGroovyDoc implements GroovyRootDo
classNamedCache = new ClassNamedCache(classDocs);
}
+ public String[] getSourcepaths() {
+ return sourcepaths;
+ }
+
+ public void setSourcepaths(String[] sourcepaths) {
+ this.sourcepaths = sourcepaths == null ? new String[0] : java.util.Arrays.copyOf(sourcepaths, sourcepaths.length);
+ }
+
@Override
public GroovyClassDoc classNamed(GroovyClassDoc groovyClassDoc, String name) {
GroovyClassDoc doc = classDocs.get(name);
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
index 8bb6a701e3..afc5c9acf2 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
@@ -239,7 +239,7 @@ final class TagRenderer {
// before an optional `:`, then a brace-balanced body that may contain
// source code with its own `{`/`}`. Needs its own parser.
if ("snippet".equals(name)) {
- return renderSnippetAt(text, start, nameEnd, out);
+ return renderSnippetAt(text, start, nameEnd, out, rootDoc, classDoc);
}
int bodyStart = skipWhitespace(text, nameEnd);
// Match the previous regex's laxness: body extends to the first '}'.
@@ -273,7 +273,8 @@ final class TagRenderer {
* @return characters consumed starting from {@code start} (the {@code '{'})
* or 0 if the tag is malformed.
*/
- private static int renderSnippetAt(String text, int start, int nameEnd, StringBuilder out) {
+ private static int renderSnippetAt(String text, int start, int nameEnd, StringBuilder out,
+ GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc) {
int n = text.length();
int i = skipWhitespace(text, nameEnd);
@@ -337,9 +338,23 @@ final class TagRenderer {
body = text.substring(bodyStart, j);
endPos = j + 1; // past the final '}'
} else {
- // External form ({@snippet file="..." region="..."}) — not yet
- // implemented. Bail and let the outer caller emit verbatim.
- return 0;
+ // External form: {@snippet file="..." [region="..."]}
+ // Read the referenced file from the current package's
+ // snippet-files/ directory (already copied into output by
+ // GROOVY-5986's resource-copy pass).
+ String fileName = attrs.get("file");
+ if (fileName == null || fileName.isEmpty()) return 0;
+ String loaded = loadSnippetFile(fileName, rootDoc, classDoc);
+ if (loaded == null) return 0;
+ String region = attrs.get("region");
+ if (region != null && !region.isEmpty()) {
+ String extracted = extractRegion(loaded, region);
+ if (extracted == null) return 0;
+ loaded = extracted;
+ }
+ body = loaded;
+ endPos = text.charAt(i) == '}' ? i + 1 : 0;
+ if (endPos == 0) return 0;
}
String langClass = attrs.getOrDefault("lang", "");
@@ -355,6 +370,65 @@ final class TagRenderer {
return endPos - start;
}
+ /**
+ * GROOVY-11938 stage 2: look up a snippet file in the current package's
+ * {@code snippet-files/} directory under any configured sourcepath and
+ * return its contents, or {@code null} if not found.
+ */
+ private static String loadSnippetFile(String fileName, GroovyRootDoc rootDoc, SimpleGroovyClassDoc classDoc) {
+ if (classDoc == null || !(rootDoc instanceof SimpleGroovyRootDoc)) return null;
+ String[] sourcepaths = ((SimpleGroovyRootDoc) rootDoc).getSourcepaths();
+ if (sourcepaths == null || sourcepaths.length == 0) return null;
+ // Package path is fullPathName minus the class simple name.
+ String full = classDoc.getFullPathName();
+ if (full == null) return null;
+ int lastSlash = full.lastIndexOf('/');
+ String pkgPath = lastSlash >= 0 ? full.substring(0, lastSlash) : "";
+ for (String sourcepath : sourcepaths) {
+ java.nio.file.Path path = java.nio.file.Paths.get(sourcepath, pkgPath, "snippet-files", fileName);
+ if (java.nio.file.Files.isRegularFile(path)) {
+ try {
+ return java.nio.file.Files.readString(path);
+ } catch (java.io.IOException e) {
+ return null;
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * GROOVY-11938 stage 2: extract a named region from a snippet file.
+ * Regions are bounded by {@code // @start region=NAME} and
+ * {@code // @end [region=NAME]} markers. The markers themselves are
+ * stripped from the returned slice. Returns {@code null} if the region
+ * isn't found.
+ */
+ private static String extractRegion(String source, String regionName) {
+ String[] lines = source.split("\n", -1);
+ int startIdx = -1;
+ int endIdx = -1;
+ java.util.regex.Pattern startPat = java.util.regex.Pattern.compile(
+ "//\\s*@start\\b[^\\n]*\\bregion\\s*=\\s*(['\"]?)" + java.util.regex.Pattern.quote(regionName) + "\\1");
+ java.util.regex.Pattern endPat = java.util.regex.Pattern.compile(
+ "//\\s*@end\\b(?:[^\\n]*\\bregion\\s*=\\s*(['\"]?)" + java.util.regex.Pattern.quote(regionName) + "\\1)?");
+ for (int k = 0; k < lines.length; k++) {
+ if (startIdx < 0 && startPat.matcher(lines[k]).find()) {
+ startIdx = k + 1;
+ } else if (startIdx >= 0 && endPat.matcher(lines[k]).find()) {
+ endIdx = k;
+ break;
+ }
+ }
+ if (startIdx < 0 || endIdx < 0) return null;
+ StringBuilder sb = new StringBuilder();
+ for (int k = startIdx; k < endIdx; k++) {
+ if (k > startIdx) sb.append('\n');
+ sb.append(lines[k]);
+ }
+ return sb.toString();
+ }
+
/**
* Strip leading blank lines from a snippet body and remove the common
* indentation (smallest non-empty leading-whitespace prefix) — matches
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index 6ef31fdd59..04fa39a19d 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -147,6 +147,104 @@ public class GroovyDocToolTest extends GroovyTestCase {
doc.contains("{<DL><DT><B>inheritDoc") || doc.contains("inheritDoc:</B>"));
}
+ // GROOVY-11938 stage 2: external {@snippet file="..."} reads from the
+ // package's snippet-files/ directory.
+ public void testSnippetTagExternalFormLoadsFromSnippetFiles() throws Exception {
+ String fixtureSourcePath = "src/test/resources/docfiles-fixture";
+ String pkg = "org/codehaus/groovy/tools/groovydoc/testfiles/docfiles";
+
+ GroovyDocTool tool = new GroovyDocTool(
+ new FileSystemResourceManager("src/main/resources"),
+ new String[]{fixtureSourcePath},
+ GroovyDocTemplateInfo.DEFAULT_DOC_TEMPLATES,
+ GroovyDocTemplateInfo.DEFAULT_PACKAGE_TEMPLATES,
+ GroovyDocTemplateInfo.DEFAULT_CLASS_TEMPLATES,
+ new ArrayList<>(), null, new Properties()
+ );
+ tool.add(List.of(pkg + "/HasDocFiles.groovy"));
+
+ MockOutputTool output = new MockOutputTool();
+ tool.renderToOutput(output, MOCK_DIR);
+
+ String doc = output.getText(MOCK_DIR + "/" + pkg + "/HasDocFiles.html");
+ assertNotNull(doc);
+ assertTrue("Expected <pre><code class='language-groovy'> wrapping snippet file in:\n" + doc,
+ doc.contains("<pre><code class=\"language-groovy\">"));
+ // Example.groovy's content should appear:
+ assertTrue("Expected snippet file content in:\n" + doc,
+ doc.contains("hello from Example"));
+ }
+
+ // GROOVY-11938 stage 2: external snippet with region= selects a slice.
+ public void testSnippetTagExternalFormWithRegion() throws Exception {
+ String fixtureSourcePath = "src/test/resources/docfiles-fixture";
+ String pkg = "org/codehaus/groovy/tools/groovydoc/testfiles/docfiles";
+
+ // Synthesise a class on the fly that uses {@snippet file=... region=...}
+ // Actually, just use a testfile in src/test/groovy that we add to sourcepath.
+ // Here we reuse a class with an inline doc reference via the resource-dir.
+ java.nio.file.Path tmp = java.nio.file.Files.createTempDirectory("snippet-region-");
+ java.nio.file.Path pkgDir = tmp.resolve(pkg);
+ java.nio.file.Files.createDirectories(pkgDir);
+ java.nio.file.Files.writeString(pkgDir.resolve("RegionClass.groovy"),
+ "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n" +
+ " * or more contributor license agreements. See the NOTICE file\n" +
+ " * distributed with this work for additional information\n" +
+ " * regarding copyright ownership. The ASF licenses this file\n" +
+ " * to you under the Apache License, Version 2.0 (the\n" +
+ " * \"License\"); you may not use this file except in compliance\n" +
+ " * with the License. You may obtain a copy of the License at\n" +
+ " *\n" +
+ " * http://www.apache.org/licenses/LICENSE-2.0\n" +
+ " */\n" +
+ "package " + pkg.replace('/', '.') + "\n" +
+ "/**\n" +
+ " * {@snippet file=\"Regioned.groovy\" region=\"core\"}\n" +
+ " */\n" +
+ "class RegionClass {}\n");
+ // Symlink/copy the snippet-files dir from fixture into the tmp tree.
+ java.nio.file.Path srcSnippetDir = java.nio.file.Paths.get(
+ "src/test/resources/docfiles-fixture", pkg, "snippet-files");
+ java.nio.file.Path dstSnippetDir = pkgDir.resolve("snippet-files");
+ java.nio.file.Files.createDirectories(dstSnippetDir);
+ try (java.util.stream.Stream<java.nio.file.Path> s = java.nio.file.Files.walk(srcSnippetDir)) {
+ s.filter(java.nio.file.Files::isRegularFile).forEach(f -> {
+ try {
+ java.nio.file.Files.copy(f, dstSnippetDir.resolve(f.getFileName()),
+ java.nio.file.StandardCopyOption.REPLACE_EXISTING);
+ } catch (java.io.IOException e) { throw new RuntimeException(e); }
+ });
+ }
+
+ try {
+ GroovyDocTool tool = new GroovyDocTool(
+ new FileSystemResourceManager("src/main/resources"),
+ new String[]{tmp.toString()},
+ GroovyDocTemplateInfo.DEFAULT_DOC_TEMPLATES,
+ GroovyDocTemplateInfo.DEFAULT_PACKAGE_TEMPLATES,
+ GroovyDocTemplateInfo.DEFAULT_CLASS_TEMPLATES,
+ new ArrayList<>(), null, new Properties()
+ );
+ tool.add(List.of(pkg + "/RegionClass.groovy"));
+ MockOutputTool output = new MockOutputTool();
+ tool.renderToOutput(output, MOCK_DIR);
+
+ String doc = output.getText(MOCK_DIR + "/" + pkg + "/RegionClass.html");
+ assertNotNull(doc);
+ assertTrue("Expected coreLogic (inside region) in:\n" + doc,
+ doc.contains("def coreLogic(int x)"));
+ assertFalse("Should not include 'def setup' (outside region) in:\n" + doc,
+ doc.contains("def setup()"));
+ assertFalse("Should not include 'def teardown' (outside region) in:\n" + doc,
+ doc.contains("def teardown()"));
+ } finally {
+ try (java.util.stream.Stream<java.nio.file.Path> s = java.nio.file.Files.walk(tmp)) {
+ s.sorted(java.util.Comparator.reverseOrder())
+ .forEach(p -> { try { java.nio.file.Files.delete(p); } catch (java.io.IOException ignore) {} });
+ }
+ }
+ }
+
// GROOVY-11938 stage 1: the inline {@snippet} tag renders its body as a
// verbatim <pre><code>...</code></pre> block with HTML-escaped content,
// an optional language class, id, and extra class.
diff --git a/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/HasDocFiles.groovy b/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/HasDocFiles.groovy
index 3be3ce5450..d8464b668f 100644
--- a/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/HasDocFiles.groovy
+++ b/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/HasDocFiles.groovy
@@ -22,6 +22,10 @@ package org.codehaus.groovy.tools.groovydoc.testfiles.docfiles
* GROOVY-5986: sample class in a package that has a {@code doc-files/}
* and {@code snippet-files/} subdirectory to be copied verbatim into
* the generated docs.
+ *
+ * <p>GROOVY-11938 stage 2: reference a snippet file from the class doc.
+ *
+ * {@snippet file="Example.groovy" lang=groovy}
*/
class HasDocFiles {
}
diff --git a/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/HasDocFiles.groovy b/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/snippet-files/Regioned.groovy
similarity index 76%
copy from subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/HasDocFiles.groovy
copy to subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/snippet-files/Regioned.groovy
index 3be3ce5450..f252d74a6f 100644
--- a/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/HasDocFiles.groovy
+++ b/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/snippet-files/Regioned.groovy
@@ -16,12 +16,17 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.codehaus.groovy.tools.groovydoc.testfiles.docfiles
-/**
- * GROOVY-5986: sample class in a package that has a {@code doc-files/}
- * and {@code snippet-files/} subdirectory to be copied verbatim into
- * the generated docs.
- */
-class HasDocFiles {
+def setup() {
+ println "this is outside the region"
+}
+
+// @start region=core
+def coreLogic(int x) {
+ return x * 2
+}
+// @end region=core
+
+def teardown() {
+ println "also outside"
}
(groovy) 22/34: GROOVY-11938: {@snippet} per JEP 413 (syntax highlighting assets)
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 6e9db0a6808b579743a52d07531d608440d7b8db
Author: Paul King <pa...@asert.com.au>
AuthorDate: Tue Apr 21 00:08:50 2026 +1000
GROOVY-11938: {@snippet} per JEP 413 (syntax highlighting assets)
---
.../java/org/codehaus/groovy/ant/Groovydoc.java | 13 +++++++
.../codehaus/groovy/tools/groovydoc/Main.groovy | 5 +++
.../groovy/tools/groovydoc/GroovyDocWriter.java | 9 ++++-
.../gstringTemplates/GroovyDocTemplateInfo.java | 21 +++++++++++
.../groovy/tools/groovydoc/Main.properties | 2 ++
.../gstringTemplates/classLevel/classDocName.html | 14 ++++++++
.../packageLevel/package-summary.html | 14 ++++++++
.../packageLevel/package-tree.html | 14 ++++++++
.../topLevel/overview-summary.html | 14 ++++++++
.../gstringTemplates/topLevel/overview-tree.html | 14 ++++++++
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 42 ++++++++++++++++++++++
11 files changed, 161 insertions(+), 1 deletion(-)
diff --git a/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java b/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java
index a05f2dcc9d..58d5b84841 100644
--- a/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java
+++ b/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java
@@ -71,6 +71,7 @@ public class Groovydoc extends Task {
private Boolean noIndex;
private Boolean noDeprecatedList;
private Boolean noHelp;
+ private String syntaxHighlighter;
private String javaVersion;
private final List<DirSet> packageSets;
private final List<String> sourceFilesToDoc;
@@ -105,6 +106,7 @@ public class Groovydoc extends Task {
noIndex = false;
noDeprecatedList = false;
noHelp = false;
+ syntaxHighlighter = "none";
}
/**
@@ -202,6 +204,16 @@ public class Groovydoc extends Task {
this.noHelp = noHelp;
}
+ /**
+ * GROOVY-11938 stage 4: selects a client-side syntax highlighter for
+ * {@code {@snippet}} and fenced Markdown code blocks. Valid values are
+ * {@code "prism"} (bundled) or {@code "none"} (default). Any other value
+ * is treated as {@code "none"}.
+ */
+ public void setSyntaxHighlighter(String syntaxHighlighter) {
+ this.syntaxHighlighter = syntaxHighlighter;
+ }
+
/**
* If set to false, Scripts will not be processed.
* Defaults to true.
@@ -536,6 +548,7 @@ public class Groovydoc extends Task {
properties.setProperty("noIndex", noIndex.toString());
properties.setProperty("noDeprecatedList", noDeprecatedList.toString());
properties.setProperty("noHelp", noHelp.toString());
+ properties.setProperty("syntaxHighlighter", syntaxHighlighter != null ? syntaxHighlighter : "none");
// GROOVY-11941: expose additional stylesheet basenames to templates.
StringBuilder extras = new StringBuilder();
for (int k = 0; k < addStylesheetFiles.size(); k++) {
diff --git a/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy b/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy
index 54b2be7b61..7070ad1937 100644
--- a/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy
+++ b/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy
@@ -49,6 +49,7 @@ class Main {
private static Boolean noIndex
private static Boolean noDeprecatedList
private static Boolean noHelp
+ private static String syntaxHighlighter
private static Boolean privateScope
private static Boolean packageScope
private static Boolean publicScope
@@ -85,6 +86,7 @@ class Main {
cli.noindex(messages['cli.option.noindex.description'])
cli.nodeprecatedlist(messages['cli.option.nodeprecatedlist.description'])
cli.nohelp(messages['cli.option.nohelp.description'])
+ cli.syntaxHighlighter(args: 1, argName: 'name', messages['cli.option.syntaxHighlighter.description'])
cli.overview(args:1, argName: 'file', messages['cli.option.overview.description'])
cli.public(messages['cli.option.public.description'])
cli.protected(messages['cli.option.protected.description'])
@@ -154,6 +156,7 @@ class Main {
noIndex = Boolean.valueOf(options.noindex) ?: false
noDeprecatedList = Boolean.valueOf(options.nodeprecatedlist) ?: false
noHelp = Boolean.valueOf(options.nohelp) ?: false
+ syntaxHighlighter = options.syntaxHighlighter ?: 'none'
showInternal = Boolean.valueOf(options.showInternal) ?: false
packageScope = Boolean.valueOf(options.package) ?: false
privateScope = Boolean.valueOf(options.private) ?: false
@@ -243,6 +246,8 @@ class Main {
properties.put("noIndex", noIndex.toString())
properties.put("noDeprecatedList", noDeprecatedList.toString())
properties.put("noHelp", noHelp.toString())
+ // GROOVY-11938 stage 4: client-side syntax highlighter ("prism"|"none").
+ properties.put("syntaxHighlighter", syntaxHighlighter)
properties.put("overviewFile", overviewFile?.absolutePath ?: "")
String phaseOverride = SystemUtil.getSystemPropertySafe("groovydoc.phase.override")
if (phaseOverride) properties.put("phaseOverride", phaseOverride)
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyDocWriter.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyDocWriter.java
index f3fb75b518..cebd9c60cf 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyDocWriter.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyDocWriter.java
@@ -183,7 +183,14 @@ public class GroovyDocWriter {
}
private static boolean hasBinaryExtension(String template) {
- return template.endsWith(".gif") || template.endsWith(".ico");
+ if (template.endsWith(".gif") || template.endsWith(".ico")) return true;
+ // GROOVY-11938 stage 4: Prism.js bundle. The minified JS/CSS files
+ // contain `$` characters which the GString template engine would
+ // otherwise try to interpret as expressions, so copy verbatim.
+ int lastSlash = template.lastIndexOf('/');
+ String name = lastSlash >= 0 ? template.substring(lastSlash + 1) : template;
+ if (name.startsWith("prism") && (name.endsWith(".js") || name.endsWith(".css"))) return true;
+ return false;
}
}
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/gstringTemplates/GroovyDocTemplateInfo.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/gstringTemplates/GroovyDocTemplateInfo.java
index 66bd46cdaf..a706ab997e 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/gstringTemplates/GroovyDocTemplateInfo.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/gstringTemplates/GroovyDocTemplateInfo.java
@@ -33,6 +33,27 @@ public class GroovyDocTemplateInfo {
TEMPLATE_BASEDIR + "topLevel/stylesheet.css", // copy default one, may override later
TEMPLATE_BASEDIR + "topLevel/inherit.gif",
DOCGEN_BASEDIR + "groovy.ico",
+ // GROOVY-11938 stage 4: Prism.js for client-side syntax highlighting of
+ // {@snippet} bodies and fenced Markdown code blocks. These files are
+ // always copied so an opt-in flag ({@code -syntaxHighlighter=prism})
+ // can enable highlighting at any time without re-running with a
+ // different template set.
+ TEMPLATE_BASEDIR + "topLevel/prism.js",
+ TEMPLATE_BASEDIR + "topLevel/prism.min.css",
+ TEMPLATE_BASEDIR + "topLevel/prism-dark.min.css",
+ TEMPLATE_BASEDIR + "topLevel/prism-csv.min.js",
+ TEMPLATE_BASEDIR + "topLevel/prism-groovy.min.js",
+ TEMPLATE_BASEDIR + "topLevel/prism-java.min.js",
+ TEMPLATE_BASEDIR + "topLevel/prism-javadoclike.min.js",
+ TEMPLATE_BASEDIR + "topLevel/prism-javascript.min.js",
+ TEMPLATE_BASEDIR + "topLevel/prism-json.min.js",
+ TEMPLATE_BASEDIR + "topLevel/prism-markdown.min.js",
+ TEMPLATE_BASEDIR + "topLevel/prism-properties.min.js",
+ TEMPLATE_BASEDIR + "topLevel/prism-regex.min.js",
+ TEMPLATE_BASEDIR + "topLevel/prism-sql.min.js",
+ TEMPLATE_BASEDIR + "topLevel/prism-toml.min.js",
+ TEMPLATE_BASEDIR + "topLevel/prism-xml-doc.min.js",
+ TEMPLATE_BASEDIR + "topLevel/prism-yaml.min.js",
};
public static final String[] DEFAULT_PACKAGE_TEMPLATES = new String[]{ // package level templates
TEMPLATE_BASEDIR + "packageLevel/package-frame.html",
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/Main.properties b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/Main.properties
index b650bed86e..69dce4b90a 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/Main.properties
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/Main.properties
@@ -66,6 +66,8 @@ cli.option.nodeprecatedlist.description=Don't generate the deprecated-list page
cli.option.nohelp.description=Don't generate the help page
+cli.option.syntaxHighlighter.description=Client-side syntax highlighter for snippets and Markdown fenced code blocks: "prism" (bundled) or "none" (default).
+
cli.option.public.description=Show only public classes and members
cli.option.protected.description=Show protected/public classes and members (default)
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.html
index d609933b20..954f2dc2c4 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/classLevel/classDocName.html
@@ -96,6 +96,20 @@
<% if (props.additionalStylesheets) props.additionalStylesheets.tokenize(',').each { __ss -> %>
<link rel="stylesheet" type="text/css" href="${classDoc.relativeRootPath}${__ss.trim()}">
<% } %>
+<% if (props.syntaxHighlighter == 'prism') { def __p = "${classDoc.relativeRootPath}" %>
+ <link rel="stylesheet" type="text/css" href="${__p}prism.min.css">
+ <script src="${__p}prism.js"></script>
+ <script src="${__p}prism-groovy.min.js"></script>
+ <script src="${__p}prism-java.min.js"></script>
+ <script src="${__p}prism-json.min.js"></script>
+ <script src="${__p}prism-yaml.min.js"></script>
+ <script src="${__p}prism-toml.min.js"></script>
+ <script src="${__p}prism-sql.min.js"></script>
+ <script src="${__p}prism-csv.min.js"></script>
+ <script src="${__p}prism-markdown.min.js"></script>
+ <script src="${__p}prism-xml-doc.min.js"></script>
+ <script src="${__p}prism-javadoclike.min.js"></script>
+<% } %>
<body class="center">
<script type="text/javascript"><!--
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html
index 06d1bc0691..79996ecf60 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-summary.html
@@ -54,6 +54,20 @@ function windowTitle()
<noscript>
</noscript>
+<% if (props.syntaxHighlighter == 'prism') { def __p = '${packageDoc.relativeRootPath}' %>
+<link rel="stylesheet" type="text/css" href="${__p}prism.min.css">
+<script src="${__p}prism.js"></script>
+<script src="${__p}prism-groovy.min.js"></script>
+<script src="${__p}prism-java.min.js"></script>
+<script src="${__p}prism-json.min.js"></script>
+<script src="${__p}prism-yaml.min.js"></script>
+<script src="${__p}prism-toml.min.js"></script>
+<script src="${__p}prism-sql.min.js"></script>
+<script src="${__p}prism-csv.min.js"></script>
+<script src="${__p}prism-markdown.min.js"></script>
+<script src="${__p}prism-xml-doc.min.js"></script>
+<script src="${__p}prism-javadoclike.min.js"></script>
+<% } %>
</head>
<body class="center" onload="windowTitle();">
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-tree.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-tree.html
index 4dee916e02..cc82eb7e45 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-tree.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/packageLevel/package-tree.html
@@ -31,6 +31,20 @@
<% } %>
<link href="${packageDoc.relativeRootPath}groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="${packageDoc.relativeRootPath}groovy.ico" type="image/x-icon" rel="icon">
+<% if (props.syntaxHighlighter == 'prism') { def __p = '${packageDoc.relativeRootPath}' %>
+<link rel="stylesheet" type="text/css" href="${__p}prism.min.css">
+<script src="${__p}prism.js"></script>
+<script src="${__p}prism-groovy.min.js"></script>
+<script src="${__p}prism-java.min.js"></script>
+<script src="${__p}prism-json.min.js"></script>
+<script src="${__p}prism-yaml.min.js"></script>
+<script src="${__p}prism-toml.min.js"></script>
+<script src="${__p}prism-sql.min.js"></script>
+<script src="${__p}prism-csv.min.js"></script>
+<script src="${__p}prism-markdown.min.js"></script>
+<script src="${__p}prism-xml-doc.min.js"></script>
+<script src="${__p}prism-javadoclike.min.js"></script>
+<% } %>
</head>
<body>
<!-- ========= START OF TOP NAVBAR ======= -->
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary.html
index 66e7d44eee..253cd12feb 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-summary.html
@@ -31,6 +31,20 @@
<% } %>
<link href="groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="groovy.ico" type="image/x-icon" rel="icon">
+<% if (props.syntaxHighlighter == 'prism') { def __p = '' %>
+<link rel="stylesheet" type="text/css" href="${__p}prism.min.css">
+<script src="${__p}prism.js"></script>
+<script src="${__p}prism-groovy.min.js"></script>
+<script src="${__p}prism-java.min.js"></script>
+<script src="${__p}prism-json.min.js"></script>
+<script src="${__p}prism-yaml.min.js"></script>
+<script src="${__p}prism-toml.min.js"></script>
+<script src="${__p}prism-sql.min.js"></script>
+<script src="${__p}prism-csv.min.js"></script>
+<script src="${__p}prism-markdown.min.js"></script>
+<script src="${__p}prism-xml-doc.min.js"></script>
+<script src="${__p}prism-javadoclike.min.js"></script>
+<% } %>
</head>
<body class="center">
<script type="text/javascript"><!--
diff --git a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-tree.html b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-tree.html
index 07acbdef56..212f8ba893 100644
--- a/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-tree.html
+++ b/subprojects/groovy-groovydoc/src/main/resources/org/codehaus/groovy/tools/groovydoc/gstringTemplates/topLevel/overview-tree.html
@@ -31,6 +31,20 @@
<% } %>
<link href="groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="groovy.ico" type="image/x-icon" rel="icon">
+<% if (props.syntaxHighlighter == 'prism') { def __p = '' %>
+<link rel="stylesheet" type="text/css" href="${__p}prism.min.css">
+<script src="${__p}prism.js"></script>
+<script src="${__p}prism-groovy.min.js"></script>
+<script src="${__p}prism-java.min.js"></script>
+<script src="${__p}prism-json.min.js"></script>
+<script src="${__p}prism-yaml.min.js"></script>
+<script src="${__p}prism-toml.min.js"></script>
+<script src="${__p}prism-sql.min.js"></script>
+<script src="${__p}prism-csv.min.js"></script>
+<script src="${__p}prism-markdown.min.js"></script>
+<script src="${__p}prism-xml-doc.min.js"></script>
+<script src="${__p}prism-javadoclike.min.js"></script>
+<% } %>
</head>
<body>
<!-- ========= START OF TOP NAVBAR ======= -->
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index 5c9c0b27ff..90b0e71761 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -495,6 +495,48 @@ public class GroovyDocToolTest extends GroovyTestCase {
page.contains("the doubled value"));
}
+ // GROOVY-11938 stage 4: opt-in client-side syntax highlighting via Prism.
+ // When -syntaxHighlighter=prism is passed, the head of each content page
+ // should include prism.min.css and the bundled language scripts; when
+ // it's unset (default), none of the prism refs should appear.
+ public void testSyntaxHighlighterPrismInjectsHead() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ Properties props = new Properties();
+ props.put("syntaxHighlighter", "prism");
+ GroovyDocTool tool = makeHtmltool(new ArrayList<>(), null, props);
+ tool.add(List.of(base + "/DocumentedClass.groovy"));
+
+ MockOutputTool output = new MockOutputTool();
+ tool.renderToOutput(output, MOCK_DIR);
+
+ String classPage = output.getText(MOCK_DIR + "/" + base + "/DocumentedClass.html");
+ assertNotNull(classPage);
+ assertTrue("Expected prism.min.css <link> in class page head:\n" + classPage,
+ classPage.contains("prism.min.css"));
+ assertTrue("Expected prism.js <script> in class page head:\n" + classPage,
+ classPage.contains("prism.js"));
+ assertTrue("Expected prism-groovy language component in class page head:\n" + classPage,
+ classPage.contains("prism-groovy.min.js"));
+
+ String overview = output.getText(MOCK_DIR + "/overview-summary.html");
+ assertNotNull(overview);
+ assertTrue("Expected prism.min.css in overview:\n" + overview,
+ overview.contains("prism.min.css"));
+ }
+
+ public void testSyntaxHighlighterOffByDefault() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ htmlTool.add(List.of(base + "/DocumentedClass.groovy"));
+ MockOutputTool output = new MockOutputTool();
+ htmlTool.renderToOutput(output, MOCK_DIR);
+ String classPage = output.getText(MOCK_DIR + "/" + base + "/DocumentedClass.html");
+ assertNotNull(classPage);
+ assertFalse("Prism should NOT be referenced when default (syntaxHighlighter=none):\n" + classPage,
+ classPage.contains("prism.js"));
+ assertFalse("Prism CSS should NOT be referenced when default:\n" + classPage,
+ classPage.contains("prism.min.css"));
+ }
+
// GROOVY-11542 stage 3a: inline tags inside a Markdown code fence or
// code span stay literal (TagRenderer must not expand them).
public void testMarkdownCodeFencePreservesInlineTagSyntax() throws Exception {
(groovy) 01/34: GROOVY-9057 — non-zero exit code on errors
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit e3e5648837d731c972a1111ac165182aa926c82b
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Apr 20 07:12:24 2026 +1000
GROOVY-9057 — non-zero exit code on errors
---
.../java/org/codehaus/groovy/ant/Groovydoc.java | 6 ++++-
.../codehaus/groovy/tools/groovydoc/Main.groovy | 18 ++++++++++++---
.../groovy/tools/groovydoc/GroovyDocTool.java | 7 ++++++
.../tools/groovydoc/GroovyRootDocBuilder.java | 6 +++++
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 10 +++++++++
.../src/test/resources/broken/BrokenSyntax.groovy | 26 ++++++++++++++++++++++
6 files changed, 69 insertions(+), 4 deletions(-)
diff --git a/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java b/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java
index b23f4b0c95..ec4b53fb90 100644
--- a/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java
+++ b/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovydoc.java
@@ -488,7 +488,11 @@ public class Groovydoc extends Task {
FileOutputTool output = new FileOutputTool();
htmlTool.renderToOutput(output, destDir.getCanonicalPath()); // TODO push destDir through APIs?
} catch (Exception e) {
- e.printStackTrace();
+ throw new BuildException("Groovydoc generation failed: " + e.getMessage(), e);
+ }
+ int errorCount = htmlTool.getErrorCount();
+ if (errorCount > 0) {
+ throw new BuildException("Groovydoc failed to parse " + errorCount + " source file(s).");
}
// try to override the default stylesheet with custom specified one if needed
if (styleSheetFile != null) {
diff --git a/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy b/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy
index 1ccc2c024b..a18ddb5555 100644
--- a/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy
+++ b/subprojects/groovy-groovydoc/src/main/groovy/org/codehaus/groovy/tools/groovydoc/Main.groovy
@@ -148,7 +148,7 @@ class Main {
} else if (scopeCount > 1) {
System.err.println "groovydoc: Error - More than one of -public, -private, -package, or -protected specified."
cli.usage()
- return
+ System.exit(1)
}
windowTitle = options.windowtitle ?: ''
@@ -181,12 +181,23 @@ class Main {
if (!remainingArgs) {
System.err.println "groovydoc: Error - No packages or classes specified."
cli.usage()
+ System.exit(1)
+ }
+ int errorCount
+ try {
+ errorCount = execute()
+ } catch (Throwable t) {
+ t.printStackTrace(System.err)
+ System.exit(1)
return
}
- execute()
+ if (errorCount > 0) {
+ System.err.println "groovydoc: Error - $errorCount source file(s) failed to parse."
+ System.exit(1)
+ }
}
- static void execute() {
+ static int execute() {
Properties properties = new Properties()
properties.put("windowTitle", windowTitle)
properties.put("docTitle", docTitle)
@@ -232,6 +243,7 @@ class Main {
println "Warning: Unable to copy specified stylesheet '" + styleSheetFile.absolutePath + "'. Using default stylesheet instead. Due to: " + e.message
}
}
+ return htmlTool.errorCount
}
static collectSourceFileNames(List<String> remainingArgs, String[] sourceDirs, List<String> exclusions) {
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyDocTool.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyDocTool.java
index bf8f40b120..77b2417b4c 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyDocTool.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyDocTool.java
@@ -139,6 +139,13 @@ public class GroovyDocTool {
return rootDocBuilder.getRootDoc();
}
+ /**
+ * @return the number of source files that could not be parsed
+ */
+ public int getErrorCount() {
+ return rootDocBuilder.getErrorCount();
+ }
+
public void renderToOutput(OutputTool output, String destdir) throws Exception {
// expect just one scope to be set on the way in but now also set higher levels of visibility
if ("true".equals(properties.getProperty("privateScope"))) properties.setProperty("packageScope", "true");
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyRootDocBuilder.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyRootDocBuilder.java
index 1c36ecee37..a3090b0251 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyRootDocBuilder.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyRootDocBuilder.java
@@ -52,6 +52,7 @@ public class GroovyRootDocBuilder {
private final String[] sourcepaths;
private final SimpleGroovyRootDoc rootDoc;
private final Properties properties;
+ private int errorCount;
@Deprecated
public GroovyRootDocBuilder(GroovyDocTool tool, String[] sourcepaths, List<LinkArgument> links, Properties properties) {
@@ -142,12 +143,17 @@ public class GroovyRootDocBuilder {
packageDoc.putAll(classDocs);
rootDoc.put(packagePath, packageDoc);
} catch (RuntimeException e) {
+ errorCount++;
e.printStackTrace(System.err);
log.error("ignored due to parsing exception: " + filename + " [" + e.getMessage() + "]");
log.debug("ignored due to parsing exception: " + filename + " [" + e.getMessage() + "]", e);
}
}
+ public int getErrorCount() {
+ return errorCount;
+ }
+
/* package private */ void processPackageInfo(String src, String filename, SimpleGroovyPackageDoc packageDoc) {
String relPath = packageDoc.getRelativeRootPath();
String description = calcThenSetPackageDescription(src, filename, relPath);
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index 3033c0142c..6e9b3b0ba2 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -94,6 +94,16 @@ public class GroovyDocToolTest extends GroovyTestCase {
);
}
+ // GROOVY-9057
+ public void testParseErrorIsTrackedInErrorCount() throws Exception {
+ assertEquals("Initial error count should be zero", 0, xmlToolForTests.getErrorCount());
+ List<String> srcList = new ArrayList<>();
+ srcList.add("broken/BrokenSyntax.groovy");
+ xmlToolForTests.add(srcList);
+ assertTrue("Expected errorCount > 0 after parsing malformed source, was "
+ + xmlToolForTests.getErrorCount(), xmlToolForTests.getErrorCount() > 0);
+ }
+
public void testPlainGroovyDocTool() throws Exception {
List<String> srcList = new ArrayList<>();
srcList.add("org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java");
diff --git a/subprojects/groovy-groovydoc/src/test/resources/broken/BrokenSyntax.groovy b/subprojects/groovy-groovydoc/src/test/resources/broken/BrokenSyntax.groovy
new file mode 100644
index 0000000000..9f2a0c0bfa
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/test/resources/broken/BrokenSyntax.groovy
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.
+ */
+// Intentionally malformed source used by
+// org.codehaus.groovy.tools.groovydoc.GroovyDocToolTest.testParseErrorIsTrackedInErrorCount
+// (GROOVY-9057) to verify that parse failures bump the error count.
+package broken
+
+class BrokenSyntax {
+ def foo(
+}
(groovy) 21/34: GROOVY-11542: JEP 467 Markdown doc comments
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 7c394cdb70531f45e3856fcb49c475aa7fd0b15f
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Apr 20 23:29:52 2026 +1000
GROOVY-11542: JEP 467 Markdown doc comments
---
subprojects/groovy-groovydoc/build.gradle | 2 +
.../org/apache/groovy/antlr/GroovydocVisitor.java | 162 +++++++++++++++-
.../groovy/tools/groovydoc/MarkdownRenderer.java | 216 +++++++++++++++++++++
.../tools/groovydoc/SimpleGroovyClassDoc.java | 30 ++-
.../groovy/tools/groovydoc/SimpleGroovyDoc.java | 13 ++
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 107 ++++++++++
.../testfiles/ClassWithMarkdownCodeFence.groovy | 35 ++++
.../testfiles/ClassWithMarkdownDoc.groovy | 37 ++++
.../testfiles/ScriptWithMarkdownTopLevelDoc.groovy | 25 +++
versions.properties | 1 +
10 files changed, 619 insertions(+), 9 deletions(-)
diff --git a/subprojects/groovy-groovydoc/build.gradle b/subprojects/groovy-groovydoc/build.gradle
index 94cccb55e5..ae74ac0ed7 100644
--- a/subprojects/groovy-groovydoc/build.gradle
+++ b/subprojects/groovy-groovydoc/build.gradle
@@ -26,6 +26,8 @@ dependencies {
implementation projects.groovyTemplates
implementation projects.groovyDocgenerator
+ // GROOVY-11542: JEP 467 Markdown doc comment rendering (/// runs).
+ implementation "org.commonmark:commonmark:${versions.commonmark}"
testImplementation projects.groovyAnt
testImplementation projects.groovyTest
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java b/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
index 9f16e32c1c..98c2a9577a 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
@@ -84,6 +84,10 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
private Map<String, GroovyClassDoc> classDocs = new LinkedHashMap<>();
private final Properties properties;
private static final String FS = "/";
+ // GROOVY-11542 stage 1: source cached lazily so per-member Markdown-run
+ // scans don't re-read the file per declaration.
+ private String cachedSource;
+ private String[] cachedSourceLines;
public GroovydocVisitor(final SourceUnit unit, String packagePath, List<LinkArgument> links) {
this(unit, packagePath, links, new Properties());
@@ -146,6 +150,7 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
currentClassDoc.addInterfaceName(makeType(iface));
}
String rawDoc = getDocContent(node.getGroovydoc());
+ boolean markdownFromSource = false;
if (rawDoc.isEmpty() && node.isScript()) {
// GROOVY-8877: the Groovy parser does not attach a leading /** */
// comment to the synthetic script class. Fall back to scanning the
@@ -155,7 +160,22 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
// `@BaseScript` where the declaration gets transformed away) nor
// duplicate member docs that the parser already attached.
rawDoc = extractLeadingScriptDocContent(node);
+ // GROOVY-11542: Markdown sibling of the script-level lift.
+ if (rawDoc.isEmpty()) {
+ rawDoc = extractLeadingScriptMarkdownDocContent(node);
+ if (!rawDoc.isEmpty()) markdownFromSource = true;
+ }
+ }
+ if (rawDoc.isEmpty() && node.getLineNumber() > 0) {
+ // GROOVY-11542 stage 1: try Markdown doc comment (/// run)
+ // immediately preceding the declaration.
+ String md = extractMarkdownDocContent(node.getLineNumber());
+ if (!md.isEmpty()) {
+ rawDoc = md;
+ markdownFromSource = true;
+ }
}
+ if (markdownFromSource) currentClassDoc.setMarkdown(true);
currentClassDoc.setRawCommentText(rawDoc);
currentClassDoc.setNameWithTypeArgs(name + genericTypesAsString(node.getGenericsTypes()));
if (!node.isInterface() && !node.isEnum() && node.getSuperClass() != null) {
@@ -300,6 +320,127 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
return "";
}
+ /**
+ * GROOVY-11542 + GROOVY-8877: script-level Markdown lift. Scan the source
+ * from line 1 looking for the first contiguous run of {@code ///} lines
+ * that satisfies the same lift rules used for traditional Javadoc comments
+ * in {@link #extractLeadingScriptDocContent}: the run must be followed by
+ * a package/import/member declaration (or nothing), and must not be
+ * claimed by a member that the parser already attached doc to.
+ */
+ private String extractLeadingScriptMarkdownDocContent(ClassNode scriptNode) {
+ String[] lines = sourceLines();
+ if (lines == null) return "";
+ int i = 0;
+ // Skip blank lines and block comments before the candidate run.
+ while (i < lines.length) {
+ String trimmed = lines[i].trim();
+ if (trimmed.isEmpty()) { i++; continue; }
+ if (trimmed.startsWith("/*") && !trimmed.startsWith("/**")) {
+ // Skip multi-line /* ... */ header comments (e.g. ASF licences).
+ int closeLine = i;
+ while (closeLine < lines.length && !lines[closeLine].contains("*/")) closeLine++;
+ i = closeLine + 1;
+ continue;
+ }
+ // If we hit anything that isn't a /// line, there's no script-level
+ // Markdown doc here; don't consume single-line // comments either.
+ if (!trimmed.startsWith("///")) return "";
+ break;
+ }
+ if (i >= lines.length) return "";
+ int start = i;
+ while (i < lines.length && lines[i].trim().startsWith("///")) i++;
+ int end = i - 1;
+ // Peek ahead: require the next non-blank thing to be package/import
+ // or nothing. `@Foo` triggers the claim-check as for /** */.
+ int j = i;
+ while (j < lines.length && lines[j].trim().isEmpty()) j++;
+ boolean isClaim = false;
+ if (j < lines.length) {
+ String next = lines[j].trim();
+ if (next.startsWith("package ") || next.startsWith("import ")) {
+ // lift
+ } else if (next.startsWith("//") || next.startsWith("/*")) {
+ // lift
+ } else if (next.startsWith("@")) {
+ isClaim = true;
+ } else {
+ return "";
+ }
+ }
+ StringBuilder body = new StringBuilder();
+ for (int k = start; k <= end; k++) {
+ String trimmed = lines[k].trim();
+ String rest = trimmed.substring(3);
+ if (rest.startsWith(" ")) rest = rest.substring(1);
+ if (body.length() > 0) body.append('\n');
+ body.append(rest);
+ }
+ String content = body.toString();
+ if (isClaim && isClaimedByMember(scriptNode, content)) return "";
+ return content;
+ }
+
+ /**
+ * GROOVY-11542 stage 1: scan the source for a contiguous run of {@code ///}
+ * Markdown doc-comment lines immediately preceding the given declaration
+ * line. Returns the joined body (with {@code ///} and one optional leading
+ * space stripped from each line) or {@code ""} if no Markdown run is found.
+ *
+ * <p>Annotation-only lines and blank lines between the comment and the
+ * declaration are tolerated, matching JEP 467's "comment attaches to the
+ * declaration that immediately follows, allowing annotations in between"
+ * rule.
+ */
+ private String extractMarkdownDocContent(int declLineNumber) {
+ if (declLineNumber <= 1) return "";
+ String[] lines = sourceLines();
+ if (lines == null) return "";
+ // 1-based declLineNumber → 0-based index of line immediately above.
+ int i = declLineNumber - 2;
+ // Skip blank lines and lines that are only annotations.
+ while (i >= 0) {
+ String trimmed = lines[i].trim();
+ if (trimmed.isEmpty()) { i--; continue; }
+ if (trimmed.startsWith("@") && !trimmed.startsWith("///")) { i--; continue; }
+ break;
+ }
+ if (i < 0) return "";
+ // Walk upward collecting contiguous /// lines. Stop on anything else.
+ int end = i;
+ while (i >= 0 && lines[i].trim().startsWith("///")) i--;
+ int start = i + 1;
+ if (start > end) return "";
+ StringBuilder body = new StringBuilder();
+ for (int k = start; k <= end; k++) {
+ String trimmed = lines[k].trim();
+ // Strip the leading "///"; tolerate one optional space after.
+ String rest = trimmed.substring(3);
+ if (rest.startsWith(" ")) rest = rest.substring(1);
+ if (body.length() > 0) body.append('\n');
+ body.append(rest);
+ }
+ return body.toString();
+ }
+
+ private String[] sourceLines() {
+ if (cachedSourceLines != null) return cachedSourceLines;
+ if (cachedSource == null) {
+ try (Reader r = unit.getSource().getReader()) {
+ StringBuilder sb = new StringBuilder();
+ char[] buf = new char[8192];
+ int n;
+ while ((n = r.read(buf)) > 0) sb.append(buf, 0, n);
+ cachedSource = sb.toString();
+ } catch (IOException e) {
+ cachedSource = "";
+ }
+ }
+ cachedSourceLines = cachedSource.split("\n", -1);
+ return cachedSourceLines;
+ }
+
private enum LiftDecision { LIFT, SKIP, CHECK_CLAIM }
/**
@@ -490,7 +631,12 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
if (!hasAnno(node.getField(), "PackageScope")) {
processModifiers(fieldDoc, node.getField(), mods);
Groovydoc groovydoc = node.getGroovydoc();
- fieldDoc.setRawCommentText(groovydoc == null ? "" : getDocContent(groovydoc));
+ String propDoc = groovydoc == null ? "" : getDocContent(groovydoc);
+ if (propDoc.isEmpty() && node.getLineNumber() > 0) {
+ String md = extractMarkdownDocContent(node.getLineNumber());
+ if (!md.isEmpty()) { propDoc = md; fieldDoc.setMarkdown(true); }
+ }
+ fieldDoc.setRawCommentText(propDoc);
currentClassDoc.addProperty(fieldDoc);
}
processAnnotations(fieldDoc, node.getField());
@@ -555,7 +701,12 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
fieldDoc.setType(new SimpleGroovyType(makeType(node.getType())));
processModifiers(fieldDoc, node, node.getModifiers());
processAnnotations(fieldDoc, node);
- fieldDoc.setRawCommentText(getDocContent(node.getGroovydoc()));
+ String fieldDoc0 = getDocContent(node.getGroovydoc());
+ if (fieldDoc0.isEmpty() && node.getLineNumber() > 0) {
+ String md = extractMarkdownDocContent(node.getLineNumber());
+ if (!md.isEmpty()) { fieldDoc0 = md; fieldDoc.setMarkdown(true); }
+ }
+ fieldDoc.setRawCommentText(fieldDoc0);
// GROOVY-6016: record the source form of compile-time-constant
// initializers so {@value #FIELD} can resolve them at render time.
// Leverage ExpressionUtils.transformInlineConstants (same utility used
@@ -589,7 +740,12 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
}
private void setConstructorOrMethodCommon(MethodNode node, SimpleGroovyExecutableMemberDoc methOrCons) {
- methOrCons.setRawCommentText(getDocContent(node.getGroovydoc()));
+ String raw = getDocContent(node.getGroovydoc());
+ if (raw.isEmpty() && node.getLineNumber() > 0) {
+ String md = extractMarkdownDocContent(node.getLineNumber());
+ if (!md.isEmpty()) { raw = md; methOrCons.setMarkdown(true); }
+ }
+ methOrCons.setRawCommentText(raw);
processModifiers(methOrCons, node, node.getModifiers());
processAnnotations(methOrCons, node);
if (node.isAbstract()) {
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/MarkdownRenderer.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/MarkdownRenderer.java
new file mode 100644
index 0000000000..0cb5160369
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/MarkdownRenderer.java
@@ -0,0 +1,216 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.codehaus.groovy.tools.groovydoc;
+
+import org.commonmark.node.AbstractVisitor;
+import org.commonmark.node.Code;
+import org.commonmark.node.FencedCodeBlock;
+import org.commonmark.node.IndentedCodeBlock;
+import org.commonmark.node.Node;
+import org.commonmark.parser.Parser;
+import org.commonmark.renderer.html.HtmlRenderer;
+
+/**
+ * GROOVY-11542: support for JEP 467 Markdown documentation comments
+ * (triple-slash {@code ///} runs, captured by {@link
+ * org.apache.groovy.antlr.GroovydocVisitor}).
+ *
+ * <p>Two concerns are kept here:
+ * <ul>
+ * <li>Splitting a raw comment body into its Markdown body (the prose) and
+ * its Javadoc block-tag trail ({@code @param}, {@code @return}, …).
+ * Block-tag detection matches Javadoc's JEP 467 rule: a line is a
+ * block tag when its first non-blank character is {@code @}, it is
+ * not inside a fenced code block ({@code ``` }/{@code ~~~}), and the
+ * {@code @} is followed by a tag word (an ASCII letter).</li>
+ * <li>Rendering the Markdown body to HTML. Headings are shifted down by
+ * two levels ({@code #} → {@code <h3>}, {@code ##} → {@code <h4>}, …)
+ * so they slot under the class/member page's own {@code <h1>} and
+ * {@code <h2>} structure, matching Javadoc's layout.</li>
+ * </ul>
+ *
+ * <p>The renderer is stateless and thread-safe; a single {@link Parser} +
+ * {@link HtmlRenderer} pair is cached per class.
+ */
+public final class MarkdownRenderer {
+
+ private static final Parser PARSER = Parser.builder().build();
+ private static final HtmlRenderer RENDERER = HtmlRenderer.builder().build();
+ // Shift class-level headings down by two so `#` becomes `<h3>` (leaving
+ // `<h1>`/`<h2>` for the page title and section banners).
+ private static final int HEADING_SHIFT = 2;
+ // Unicode control characters used to mask `{` and `}` inside Markdown
+ // code spans / code blocks so that the downstream TagRenderer pass does
+ // not expand inline tags (e.g. {@link}) that are meant to be literal
+ // code samples. We substitute them back for the real braces after the
+ // TagRenderer pass; see {@link #unmaskBracesInCode(String)}.
+ static final char LBRACE_MASK = '\u0001';
+ static final char RBRACE_MASK = '\u0002';
+
+ private MarkdownRenderer() {}
+
+ /**
+ * Split a raw comment body (already stripped of {@code ///} prefixes)
+ * into its Markdown body and block-tag trail. Returns a two-element
+ * array {@code [body, tags]}; either may be empty.
+ */
+ public static String[] splitBodyAndTags(String raw) {
+ if (raw == null || raw.isEmpty()) return new String[] {"", ""};
+ String[] lines = raw.split("\n", -1);
+ int split = -1;
+ boolean inFence = false;
+ String fenceMarker = null;
+ for (int i = 0; i < lines.length; i++) {
+ String line = lines[i];
+ String trimmed = line.trim();
+ // Track fenced code blocks so `@Override` inside a code sample
+ // isn't mistaken for a block tag.
+ if (inFence) {
+ if (trimmed.startsWith(fenceMarker)) {
+ inFence = false;
+ fenceMarker = null;
+ }
+ continue;
+ }
+ if (trimmed.startsWith("```")) {
+ inFence = true; fenceMarker = "```"; continue;
+ }
+ if (trimmed.startsWith("~~~")) {
+ inFence = true; fenceMarker = "~~~"; continue;
+ }
+ // Block tag start: first non-blank is '@', followed by an ASCII
+ // letter (so email-like `@mention` is tolerated only when it
+ // actually leads with a letter tag word, matching Javadoc).
+ if (trimmed.length() >= 2 && trimmed.charAt(0) == '@'
+ && Character.isLetter(trimmed.charAt(1))) {
+ split = i;
+ break;
+ }
+ }
+ if (split < 0) return new String[] {raw, ""};
+ StringBuilder body = new StringBuilder();
+ for (int i = 0; i < split; i++) {
+ if (i > 0) body.append('\n');
+ body.append(lines[i]);
+ }
+ StringBuilder tags = new StringBuilder();
+ for (int i = split; i < lines.length; i++) {
+ if (i > split) tags.append('\n');
+ tags.append(lines[i]);
+ }
+ return new String[] {body.toString(), tags.toString()};
+ }
+
+ /**
+ * Render a Markdown body to HTML and shift heading levels down so that
+ * JEP 467 top-level headings ({@code #}) become {@code <h3>}, fitting
+ * under the page's existing {@code <h1>}/{@code <h2>} structure.
+ */
+ public static String render(String markdownBody) {
+ if (markdownBody == null || markdownBody.isEmpty()) return "";
+ Node document = PARSER.parse(markdownBody);
+ // Mask `{` / `}` inside code spans and code blocks so inline tags
+ // like {@link Foo} appearing in a code sample are treated as literal
+ // text by the subsequent TagRenderer pass. The masks are translated
+ // back to real braces via unmaskBracesInCode() after TagRenderer runs.
+ document.accept(new CodeBraceMasker());
+ String html = RENDERER.render(document);
+ return shiftHeadings(html);
+ }
+
+ /**
+ * Translate the {@code \u0001} / {@code \u0002} placeholders left inside
+ * code spans / code blocks by {@link #render(String)} back to literal
+ * {@code {} / {@code }} numeric HTML entities, so browsers
+ * display them as {@code {} and {@code }} while keeping the content
+ * distinguishable from tag syntax. Called after {@code TagRenderer} has
+ * run so inline-tag expansion has already skipped over them.
+ */
+ public static String unmaskBracesInCode(String html) {
+ if (html == null || html.isEmpty()) return html;
+ if (html.indexOf(LBRACE_MASK) < 0 && html.indexOf(RBRACE_MASK) < 0) return html;
+ StringBuilder sb = new StringBuilder(html.length());
+ for (int i = 0, n = html.length(); i < n; i++) {
+ char c = html.charAt(i);
+ if (c == LBRACE_MASK) sb.append("{");
+ else if (c == RBRACE_MASK) sb.append("}");
+ else sb.append(c);
+ }
+ return sb.toString();
+ }
+
+ /**
+ * CommonMark AST visitor that replaces every occurrence of {@code '{'}
+ * and {@code '}'} in the literal text of {@link Code}, {@link
+ * FencedCodeBlock}, and {@link IndentedCodeBlock} nodes with the
+ * placeholder characters defined by {@link MarkdownRenderer}. The
+ * placeholders are immune to TagRenderer's {@code '{@'} trigger so
+ * inline-tag-looking text inside code samples is preserved verbatim.
+ */
+ private static final class CodeBraceMasker extends AbstractVisitor {
+ @Override
+ public void visit(Code code) {
+ code.setLiteral(mask(code.getLiteral()));
+ }
+ @Override
+ public void visit(FencedCodeBlock block) {
+ block.setLiteral(mask(block.getLiteral()));
+ }
+ @Override
+ public void visit(IndentedCodeBlock block) {
+ block.setLiteral(mask(block.getLiteral()));
+ }
+ private static String mask(String text) {
+ if (text == null || text.isEmpty()) return text;
+ if (text.indexOf('{') < 0 && text.indexOf('}') < 0) return text;
+ return text.replace('{', LBRACE_MASK).replace('}', RBRACE_MASK);
+ }
+ }
+
+ private static String shiftHeadings(String html) {
+ if (html.indexOf("<h") < 0) return html;
+ StringBuilder out = new StringBuilder(html.length());
+ int i = 0, n = html.length();
+ while (i < n) {
+ char c = html.charAt(i);
+ if (c == '<') {
+ // Look for <hN> or </hN> where 1 <= N <= 6.
+ boolean closing = i + 1 < n && html.charAt(i + 1) == '/';
+ int tagStart = closing ? i + 2 : i + 1;
+ if (tagStart + 1 < n && html.charAt(tagStart) == 'h'
+ && Character.isDigit(html.charAt(tagStart + 1))) {
+ int level = html.charAt(tagStart + 1) - '0';
+ int endAngle = html.indexOf('>', tagStart + 2);
+ if (level >= 1 && level <= 6 && endAngle > 0) {
+ int newLevel = Math.min(6, level + HEADING_SHIFT);
+ out.append('<');
+ if (closing) out.append('/');
+ out.append('h').append(newLevel);
+ out.append(html, tagStart + 2, endAngle + 1);
+ i = endAngle + 1;
+ continue;
+ }
+ }
+ }
+ out.append(c);
+ i++;
+ }
+ return out.toString();
+ }
+}
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyClassDoc.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyClassDoc.java
index 1cf711507c..8a2380c957 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyClassDoc.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyClassDoc.java
@@ -899,20 +899,38 @@ public class SimpleGroovyClassDoc extends SimpleGroovyAbstractableElementDoc imp
* to find its overridden parent) can resolve.
*/
public String replaceTags(String comment, org.codehaus.groovy.groovydoc.GroovyMemberDoc memberDoc) {
- // Strip the leading ' * ' block-comment prefix from each line.
- String result = comment.replaceAll("(?m)^\\s*\\*", "");
-
- // Expand {@docRoot} before tag processing since it is a path substitution
- // rather than a tag-rendering operation.
String relativeRootPath = getRelativeRootPath();
if (!relativeRootPath.endsWith("/")) {
relativeRootPath += "/";
}
+ // GROOVY-11542: Markdown doc comments (/// runs per JEP 467).
+ // Pre-render the Markdown body to HTML and splice it in before
+ // TagRenderer processes inline and block tags. Block tags stay as
+ // source text so TagRenderer handles them through the normal path.
+ boolean markdown = (memberDoc instanceof SimpleGroovyDoc && ((SimpleGroovyDoc) memberDoc).isMarkdown())
+ || (memberDoc == null && this.isMarkdown());
+ String result;
+ if (markdown) {
+ String[] parts = MarkdownRenderer.splitBodyAndTags(comment);
+ String bodyHtml = MarkdownRenderer.render(parts[0]);
+ result = parts[1].isEmpty() ? bodyHtml : bodyHtml + "\n" + parts[1];
+ } else {
+ // Strip the leading ' * ' block-comment prefix from each line.
+ result = comment.replaceAll("(?m)^\\s*\\*", "");
+ }
+
+ // Expand {@docRoot} before tag processing since it is a path substitution
+ // rather than a tag-rendering operation.
result = result.replaceAll(DOCROOT_PATTERN2, relativeRootPath);
result = result.replaceAll(DOCROOT_PATTERN, relativeRootPath);
// GROOVY-11939: single-pass tokenize + render for inline and block tags.
- return TagRenderer.render(result, links, relativeRootPath, savedRootDoc, this, memberDoc);
+ String rendered = TagRenderer.render(result, links, relativeRootPath, savedRootDoc, this, memberDoc);
+ // GROOVY-11542: if the body came from a Markdown comment, swap the
+ // brace masks MarkdownRenderer used to hide `{@...}` inside code
+ // spans / code blocks back to numeric HTML entities. Safe on
+ // non-Markdown paths too (no masks present → no-op).
+ return markdown ? MarkdownRenderer.unmaskBracesInCode(rendered) : rendered;
}
/**
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyDoc.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyDoc.java
index ea67d026f0..7ff2bf2328 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyDoc.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyDoc.java
@@ -49,6 +49,11 @@ public class SimpleGroovyDoc implements GroovyDoc/*, GroovyTokenTypes*/ {
private int definitionType;
private boolean deprecated;
private boolean isScript;
+ // GROOVY-11542 stage 1: marks a comment whose body is Markdown (/// runs
+ // per JEP 467). The flag is set during AST visit; templates / renderers
+ // inspect it to decide whether to route the body through a Markdown
+ // renderer (stage 2) instead of the traditional Javadoc/HTML handling.
+ private boolean markdown;
private GroovyTag[] tags;
public SimpleGroovyDoc(String name) {
@@ -95,6 +100,14 @@ public class SimpleGroovyDoc implements GroovyDoc/*, GroovyTokenTypes*/ {
calculateTags(rawCommentText);
}
+ public boolean isMarkdown() {
+ return markdown;
+ }
+
+ public void setMarkdown(boolean markdown) {
+ this.markdown = markdown;
+ }
+
public void setScript(boolean script) {
isScript = script;
}
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index 48ed34e1b9..5c9c0b27ff 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -436,6 +436,113 @@ public class GroovyDocToolTest extends GroovyTestCase {
+ occurrences + " in:\n" + doc, 2, occurrences);
}
+ // GROOVY-11542 stage 1: verify that /// Markdown doc comments are
+ // captured by GroovydocVisitor and surface as rawCommentText on the
+ // matching SimpleGroovy*Doc, with the `markdown` flag set. Rendering
+ // through CommonMark is stage 2.
+ public void testMarkdownDocCaptureStage1() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ htmlTool.add(List.of(base + "/ClassWithMarkdownDoc.groovy"));
+
+ MockOutputTool output = new MockOutputTool();
+ htmlTool.renderToOutput(output, MOCK_DIR);
+
+ String page = output.getText(MOCK_DIR + "/" + base + "/ClassWithMarkdownDoc.html");
+ assertNotNull("Expected a page for the Markdown-doc class", page);
+ // Stage 1: content makes it through (not yet Markdown-rendered, so the
+ // raw * and ` characters may appear verbatim in the HTML output).
+ assertTrue("Class-level /// body should flow through in:\n" + page,
+ page.contains("stage 1 fixture"));
+ assertTrue("Field-level /// body should flow through in:\n" + page,
+ page.contains("Field-level Markdown doc"));
+ assertTrue("Method-level /// body should flow through in:\n" + page,
+ page.contains("Method Markdown body"));
+ // Block tags inside the /// run still surface — until stage 3 they
+ // travel as part of rawCommentText and get picked up by the existing
+ // block-tag handling.
+ assertTrue("@param x from /// run should be captured in:\n" + page,
+ page.contains("an input"));
+ assertTrue("@return from /// run should be captured in:\n" + page,
+ page.contains("the doubled value"));
+ }
+
+ // GROOVY-11542 stage 2: /// Markdown doc comments render through CommonMark;
+ // headings shift down (# -> <h3>), bullets, emphasis and fenced code blocks
+ // all survive; block tags still flow through the existing TagRenderer.
+ public void testMarkdownDocRendersAsHtml() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ htmlTool.add(List.of(base + "/ClassWithMarkdownDoc.groovy"));
+
+ MockOutputTool output = new MockOutputTool();
+ htmlTool.renderToOutput(output, MOCK_DIR);
+
+ String page = output.getText(MOCK_DIR + "/" + base + "/ClassWithMarkdownDoc.html");
+ assertNotNull(page);
+ // Emphasis, code spans, and lists should become HTML.
+ assertTrue("Expected **body** to render as <strong>body</strong> in:\n" + page,
+ page.contains("<strong>body</strong>"));
+ assertTrue("Expected `Markdown` to render as <code>Markdown</code> in:\n" + page,
+ page.contains("<code>Markdown</code>"));
+ assertTrue("Expected bullet list to render as <ul><li>first bullet</li> in:\n" + page,
+ page.contains("<li>first bullet</li>"));
+ // Field-level doc: *emphasis* -> <em>emphasis</em>.
+ assertTrue("Expected *emphasis* to render as <em>emphasis</em> in:\n" + page,
+ page.contains("<em>emphasis</em>"));
+ // Block tags from the /// run still reach the rendered output.
+ assertTrue("@param description should survive through TagRenderer in:\n" + page,
+ page.contains("an input"));
+ assertTrue("@return description should survive through TagRenderer in:\n" + page,
+ page.contains("the doubled value"));
+ }
+
+ // GROOVY-11542 stage 3a: inline tags inside a Markdown code fence or
+ // code span stay literal (TagRenderer must not expand them).
+ public void testMarkdownCodeFencePreservesInlineTagSyntax() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ htmlTool.add(List.of(base + "/ClassWithMarkdownCodeFence.groovy"));
+
+ MockOutputTool output = new MockOutputTool();
+ htmlTool.renderToOutput(output, MOCK_DIR);
+
+ String page = output.getText(MOCK_DIR + "/" + base + "/ClassWithMarkdownCodeFence.html");
+ assertNotNull(page);
+ // Outside the fence, {@code markdown-outside-fence} should expand —
+ // TagRenderer renders it as <CODE>markdown-outside-fence</CODE> (or
+ // similar) wrapped in code markup.
+ assertTrue("Expected {@code ...} outside the fence to expand in:\n" + page,
+ page.contains("markdown-outside-fence"));
+ // Inside a fenced block, {@link Foo} must stay LITERAL. The masked
+ // braces come back as { / } numeric entities — the browser
+ // shows them as { / } but TagRenderer never saw them as a tag.
+ assertFalse("{@link Foo} inside a ``` fence must NOT render as an anchor in:\n" + page,
+ page.contains(">Foo</a>"));
+ assertTrue("Inside fence, `{@link Foo}` should appear with masked braces as entities in:\n" + page,
+ page.contains("{@link Foo}"));
+ // Inside an inline `...` span, same rule applies to {@link Bar}.
+ assertFalse("{@link Bar} inside a code span must NOT render as an anchor in:\n" + page,
+ page.contains(">Bar</a>"));
+ assertTrue("Inside a code span, `{@link Bar}` should appear with masked braces in:\n" + page,
+ page.contains("{@link Bar}"));
+ }
+
+ // GROOVY-11542 stage 3b: /// leading a script file lifts to the
+ // synthetic Script class, parallel to the GROOVY-8877 /** */ lift.
+ public void testMarkdownScriptLevelDocLifts() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ htmlTool.add(List.of(base + "/ScriptWithMarkdownTopLevelDoc.groovy"));
+
+ MockOutputTool output = new MockOutputTool();
+ htmlTool.renderToOutput(output, MOCK_DIR);
+
+ String page = output.getText(MOCK_DIR + "/" + base + "/ScriptWithMarkdownTopLevelDoc.html");
+ assertNotNull("Expected a page for the Markdown-script", page);
+ assertTrue("Expected the script-level /// body to surface on the script page in:\n" + page,
+ page.contains("Markdown"));
+ // The **Markdown** emphasis in the body should render as <strong>.
+ assertTrue("Expected **Markdown** to render as <strong>Markdown</strong> in:\n" + page,
+ page.contains("<strong>Markdown</strong>"));
+ }
+
// Task #23: {@link} cross-references between a script and classes declared
// in the same source file resolve to working hyperlinks. The script and
// sibling classes compile to top-level classes in the same package, so the
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithMarkdownCodeFence.groovy b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithMarkdownCodeFence.groovy
new file mode 100644
index 0000000000..a42a8375ad
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithMarkdownCodeFence.groovy
@@ -0,0 +1,35 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.codehaus.groovy.tools.groovydoc.testfiles
+
+/// GROOVY-11542 stage 3 fixture: inline tags inside Markdown code fences
+/// and code spans should be preserved verbatim (not expanded by TagRenderer).
+///
+/// Outside fence (expanded): {@code markdown-outside-fence}
+///
+/// ```
+/// def example() {
+/// // {@link Foo} should NOT be expanded here
+/// return 'fence-body'
+/// }
+/// ```
+///
+/// Inline span with `{@link Bar}` as literal text should stay literal.
+class ClassWithMarkdownCodeFence {
+}
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithMarkdownDoc.groovy b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithMarkdownDoc.groovy
new file mode 100644
index 0000000000..2843f9fdd9
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithMarkdownDoc.groovy
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.codehaus.groovy.tools.groovydoc.testfiles
+
+/// GROOVY-11542 stage 1 fixture: a class-level Markdown doc comment using
+/// the triple-slash syntax. The **body** is treated as `Markdown` by the
+/// groovydoc tool.
+///
+/// - first bullet
+/// - second bullet
+class ClassWithMarkdownDoc {
+
+ /// Field-level Markdown doc. *emphasis* and `code`.
+ public int answer = 42
+
+ /// Method Markdown body.
+ ///
+ /// @param x an input
+ /// @return the doubled value
+ int twice(int x) { x * 2 }
+}
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ScriptWithMarkdownTopLevelDoc.groovy b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ScriptWithMarkdownTopLevelDoc.groovy
new file mode 100644
index 0000000000..81dc549148
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ScriptWithMarkdownTopLevelDoc.groovy
@@ -0,0 +1,25 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.
+ */
+
+/// GROOVY-11542 + GROOVY-8877 fixture: a **Markdown** script-level doc that
+/// should be lifted to the synthesised Script class via the same rules used
+/// for traditional Javadoc comments.
+package org.codehaus.groovy.tools.groovydoc.testfiles
+
+println 'body not important'
diff --git a/versions.properties b/versions.properties
index 35db48f989..301388bdf3 100644
--- a/versions.properties
+++ b/versions.properties
@@ -28,6 +28,7 @@ commonmark=0.28.0
commonsCli=1.11.0
commonsMath3=3.6.1
flatLaf=3.7.1
+commonmark=0.28.0
gpars=1.2.1
ivy=2.5.3
jackson=2.21.2
(groovy) 27/34: minor refactor: extract some shared code into a helper
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 733d19a9142345b86ef99deb5e18189c831119e7
Author: Paul King <pa...@asert.com.au>
AuthorDate: Tue Apr 21 07:20:52 2026 +1000
minor refactor: extract some shared code into a helper
---
.../org/apache/groovy/antlr/GroovydocVisitor.java | 21 ++------
.../tools/groovydoc/GroovydocAnnotationUtils.java | 56 ++++++++++++++++++++++
.../groovydoc/antlr4/GroovydocJavaVisitor.java | 9 +---
3 files changed, 61 insertions(+), 25 deletions(-)
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java b/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
index 98c2a9577a..c7fb514e15 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
@@ -41,6 +41,7 @@ import org.codehaus.groovy.groovydoc.GroovyClassDoc;
import org.codehaus.groovy.groovydoc.GroovyFieldDoc;
import org.codehaus.groovy.groovydoc.GroovyMethodDoc;
import org.codehaus.groovy.runtime.ArrayGroovyMethods;
+import org.codehaus.groovy.tools.groovydoc.GroovydocAnnotationUtils;
import org.codehaus.groovy.tools.groovydoc.LinkArgument;
import org.codehaus.groovy.tools.groovydoc.SimpleGroovyAnnotationRef;
import org.codehaus.groovy.tools.groovydoc.SimpleGroovyClassDoc;
@@ -55,7 +56,6 @@ import org.codehaus.groovy.tools.groovydoc.SimpleGroovyType;
import java.io.IOException;
import java.io.Reader;
-import java.lang.annotation.Documented;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Iterator;
@@ -485,7 +485,7 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
private void processAnnotations(SimpleGroovyProgramElementDoc element, AnnotatedNode node) {
for (AnnotationNode an : node.getAnnotations()) {
String name = an.getClassNode().getName();
- if (!shouldDocument(name)) continue;
+ if (!GroovydocAnnotationUtils.shouldDocument(name)) continue;
element.addAnnotationRef(new SimpleGroovyAnnotationRef(name, an.getText()));
}
}
@@ -493,26 +493,11 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
private void processAnnotations(SimpleGroovyParameter param, AnnotatedNode node) {
for (AnnotationNode an : node.getAnnotations()) {
String name = an.getClassNode().getName();
- if (!shouldDocument(name)) continue;
+ if (!GroovydocAnnotationUtils.shouldDocument(name)) continue;
param.addAnnotationRef(new SimpleGroovyAnnotationRef(name, an.getText()));
}
}
- // GROOVY-4634: emit an annotation reference only when the annotation type is
- // itself marked {@code @Documented}, matching Javadoc's behavior. When the
- // annotation type cannot be resolved on the current classpath (common for
- // user-defined annotations in the source tree being documented), default
- // to including it so that groovydoc does not silently drop user annotations.
- private static boolean shouldDocument(String fqn) {
- try {
- Class<?> c = Class.forName(fqn);
- if (!c.isAnnotation()) return true;
- return c.isAnnotationPresent(Documented.class);
- } catch (Throwable t) {
- return true;
- }
- }
-
// GROOVY-9572: hide members annotated with groovy.transform.@Internal (per GEP-17)
// or deemed internal by name convention (contains '$'), unless the user opts
// in with -showInternal / showInternal=true.
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovydocAnnotationUtils.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovydocAnnotationUtils.java
new file mode 100644
index 0000000000..f16e273052
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovydocAnnotationUtils.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.codehaus.groovy.tools.groovydoc;
+
+import java.lang.annotation.Documented;
+
+/**
+ * Utilities shared between {@code GroovydocVisitor} (Groovy AST) and
+ * {@code GroovydocJavaVisitor} (JavaParser AST). Kept narrow on purpose:
+ * only logic that is genuinely pure (no AST-type dependency) belongs here.
+ * Everything else is parallel in both visitors because their input AST
+ * types are fundamentally different hierarchies and the adapter layer
+ * needed to unify them would cost more than the duplication it saves.
+ */
+public final class GroovydocAnnotationUtils {
+
+ private GroovydocAnnotationUtils() {}
+
+ /**
+ * GROOVY-4634: emit an annotation reference only when the annotation
+ * type is itself marked {@link Documented}, matching Javadoc's
+ * behavior. When the annotation type cannot be resolved on the
+ * current classpath (common for user-defined annotations in the
+ * source tree being documented), default to {@code true} so that
+ * groovydoc does not silently drop user annotations.
+ *
+ * <p>Takes a fully-qualified annotation type name and returns
+ * {@code true} when the annotation should be shown in the rendered
+ * documentation.
+ */
+ public static boolean shouldDocument(String fqn) {
+ try {
+ Class<?> c = Class.forName(fqn);
+ if (!c.isAnnotation()) return true;
+ return c.isAnnotationPresent(Documented.class);
+ } catch (Throwable t) {
+ return true;
+ }
+ }
+}
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/antlr4/GroovydocJavaVisitor.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/antlr4/GroovydocJavaVisitor.java
index 827fb61b1b..720220bf09 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/antlr4/GroovydocJavaVisitor.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/antlr4/GroovydocJavaVisitor.java
@@ -45,6 +45,7 @@ import org.codehaus.groovy.GroovyBugError;
import org.codehaus.groovy.control.ResolveVisitor;
import org.codehaus.groovy.groovydoc.GroovyClassDoc;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;
+import org.codehaus.groovy.tools.groovydoc.GroovydocAnnotationUtils;
import org.codehaus.groovy.tools.groovydoc.LinkArgument;
import org.codehaus.groovy.tools.groovydoc.SimpleGroovyAbstractableElementDoc;
import org.codehaus.groovy.tools.groovydoc.SimpleGroovyAnnotationRef;
@@ -273,13 +274,7 @@ public class GroovydocJavaVisitor
private boolean shouldDocument(String name) {
String fqn = resolveAnnotationFqn(name);
if (fqn == null) return true; // unresolved — show
- try {
- Class<?> c = Class.forName(fqn);
- if (!c.isAnnotation()) return true;
- return c.isAnnotationPresent(java.lang.annotation.Documented.class);
- } catch (Throwable t) {
- return true;
- }
+ return GroovydocAnnotationUtils.shouldDocument(fqn);
}
private String resolveAnnotationFqn(String name) {
(groovy) 20/34: add test to ensure linking within scripts to class definitions
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit ce8a7a2261a7d4326260b557a3236a9bef11f180
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Apr 20 22:50:37 2026 +1000
add test to ensure linking within scripts to class definitions
---
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 28 +++++++++++++++++++
.../testfiles/ScriptWithSiblingClassLinks.groovy | 31 ++++++++++++++++++++++
2 files changed, 59 insertions(+)
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index 10b18e8d54..48ed34e1b9 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -436,6 +436,34 @@ public class GroovyDocToolTest extends GroovyTestCase {
+ occurrences + " in:\n" + doc, 2, occurrences);
}
+ // Task #23: {@link} cross-references between a script and classes declared
+ // in the same source file resolve to working hyperlinks. The script and
+ // sibling classes compile to top-level classes in the same package, so the
+ // existing same-package {@link} resolver handles them symmetrically — no
+ // code change needed; this test locks the behaviour down.
+ public void testScriptAndSiblingClassCrossLinks() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ htmlTool.add(List.of(base + "/ScriptWithSiblingClassLinks.groovy"));
+
+ MockOutputTool output = new MockOutputTool();
+ htmlTool.renderToOutput(output, MOCK_DIR);
+
+ String scriptPage = output.getText(MOCK_DIR + "/" + base + "/ScriptWithSiblingClassLinks.html");
+ String helperPage = output.getText(MOCK_DIR + "/" + base + "/SiblingHelper.html");
+ assertNotNull("Expected a page for the script", scriptPage);
+ assertNotNull("Expected a page for the sibling class", helperPage);
+
+ // Script → sibling class: {@link SiblingHelper#otherMethod()}
+ assertTrue("Script page should link to SiblingHelper.otherMethod in:\n" + scriptPage,
+ scriptPage.contains("SiblingHelper.html#otherMethod()")
+ && scriptPage.contains(">SiblingHelper.otherMethod</a>"));
+
+ // Sibling class → script: {@link ScriptWithSiblingClassLinks#method()}
+ assertTrue("Sibling page should link to ScriptWithSiblingClassLinks.method in:\n" + helperPage,
+ helperPage.contains("ScriptWithSiblingClassLinks.html#method()")
+ && helperPage.contains(">ScriptWithSiblingClassLinks.method</a>"));
+ }
+
// GROOVY-11943: -noindex / -nodeprecatedlist / -nohelp skip the matching
// auxiliary top-level page AND suppress its nav-bar link on every page
// that would otherwise reference it.
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ScriptWithSiblingClassLinks.groovy b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ScriptWithSiblingClassLinks.groovy
new file mode 100644
index 0000000000..2c1ce8d499
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ScriptWithSiblingClassLinks.groovy
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.codehaus.groovy.tools.groovydoc.testfiles
+
+/**
+ * Script doc uses {@link SiblingHelper#otherMethod()}.
+ */
+def method() {}
+
+/**
+ * Used by {@link ScriptWithSiblingClassLinks#method()}.
+ */
+class SiblingHelper {
+ static otherMethod() {}
+}
(groovy) 06/34: GROOVY-5986: doc-files and snippet-files resource copy
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit ee15109d6f9386b8f465b1164ecb3986e2b5d43b
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Apr 20 12:59:53 2026 +1000
GROOVY-5986: doc-files and snippet-files resource copy
---
.../groovy/tools/groovydoc/GroovyDocTool.java | 4 +-
.../groovy/tools/groovydoc/GroovyDocWriter.java | 60 ++++++++++++++++++++++
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 49 ++++++++++++++++++
.../testfiles/docfiles/HasDocFiles.groovy | 27 ++++++++++
.../testfiles/docfiles/doc-files/sample.html | 19 +++++++
.../testfiles/docfiles/doc-files/sub/nested.txt | 18 +++++++
.../docfiles/snippet-files/Example.groovy | 20 ++++++++
7 files changed, 196 insertions(+), 1 deletion(-)
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyDocTool.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyDocTool.java
index 77b2417b4c..1094a9d363 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyDocTool.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyDocTool.java
@@ -36,6 +36,7 @@ public class GroovyDocTool {
private final GroovyRootDocBuilder rootDocBuilder;
private final GroovyDocTemplateEngine templateEngine;
private final ParserConfiguration.LanguageLevel javaLanguageLevel;
+ private final String[] sourcepaths;
protected Properties properties;
@@ -65,6 +66,7 @@ public class GroovyDocTool {
* @param properties additional properties to be used when generating the groovydoc
*/
public GroovyDocTool(ResourceManager resourceManager, String[] sourcepaths, String[] docTemplates, String[] packageTemplates, String[] classTemplates, List<LinkArgument> links, String javaVersion, Properties properties) {
+ this.sourcepaths = sourcepaths == null ? new String[0] : java.util.Arrays.copyOf(sourcepaths, sourcepaths.length);
rootDocBuilder = new GroovyRootDocBuilder(sourcepaths, links, properties);
javaLanguageLevel = calculateLanguageLevel(javaVersion);
@@ -152,7 +154,7 @@ public class GroovyDocTool {
if ("true".equals(properties.getProperty("packageScope"))) properties.setProperty("protectedScope", "true");
if ("true".equals(properties.getProperty("protectedScope"))) properties.setProperty("publicScope", "true");
if (templateEngine != null) {
- GroovyDocWriter writer = new GroovyDocWriter(output, templateEngine, properties);
+ GroovyDocWriter writer = new GroovyDocWriter(output, templateEngine, properties, sourcepaths);
GroovyRootDoc rootDoc = rootDocBuilder.getRootDoc();
writer.writeRoot(rootDoc, destdir);
writer.writePackages(rootDoc, destdir);
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyDocWriter.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyDocWriter.java
index 7926348c0c..886d3fbd12 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyDocWriter.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/GroovyDocWriter.java
@@ -25,8 +25,16 @@ import org.codehaus.groovy.groovydoc.GroovyRootDoc;
import org.codehaus.groovy.tools.shell.util.Logger;
import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.util.Arrays;
import java.util.Iterator;
+import java.util.List;
import java.util.Properties;
+import java.util.stream.Stream;
/**
* Write GroovyDoc resources to destination.
@@ -36,7 +44,15 @@ public class GroovyDocWriter {
private final OutputTool output;
private final GroovyDocTemplateEngine templateEngine;
private static final String FS = "/";
+ /**
+ * Per-package subdirectories in source whose contents are mirrored verbatim
+ * into the output. GROOVY-5986 ({@code doc-files}) is the Javadoc-inherited
+ * case; GROOVY-11938 ({@code snippet-files}, for {@code {@snippet file=...}})
+ * piggybacks on the same scanner.
+ */
+ private static final List<String> RESOURCE_DIRS = Arrays.asList("doc-files", "snippet-files");
private final Properties properties;
+ private final String[] sourcepaths;
@Deprecated
public GroovyDocWriter(GroovyDocTool tool, OutputTool output, GroovyDocTemplateEngine templateEngine, Properties properties) {
@@ -44,9 +60,14 @@ public class GroovyDocWriter {
}
public GroovyDocWriter(OutputTool output, GroovyDocTemplateEngine templateEngine, Properties properties) {
+ this(output, templateEngine, properties, null);
+ }
+
+ public GroovyDocWriter(OutputTool output, GroovyDocTemplateEngine templateEngine, Properties properties, String[] sourcepaths) {
this.output = output;
this.templateEngine = templateEngine;
this.properties = properties;
+ this.sourcepaths = sourcepaths == null ? new String[0] : Arrays.copyOf(sourcepaths, sourcepaths.length);
}
public void writeClasses(GroovyRootDoc rootDoc, String destdir) throws Exception {
@@ -70,6 +91,7 @@ public class GroovyDocWriter {
if (new File(packageDoc.name()).isAbsolute()) continue;
output.makeOutputArea(destdir + FS + packageDoc.name());
writePackageToOutput(packageDoc, destdir);
+ copyResourceFiles(packageDoc, destdir);
}
StringBuilder sb = new StringBuilder();
for (GroovyPackageDoc packageDoc : rootDoc.specifiedPackages()) {
@@ -81,6 +103,44 @@ public class GroovyDocWriter {
output.writeToOutput(destFileName, sb.toString(), properties.getProperty("fileEncoding"));
}
+ /**
+ * GROOVY-5986 / GROOVY-11938: mirror any {@code doc-files/} or
+ * {@code snippet-files/} subdirectory found under the package in any
+ * sourcepath entry into the corresponding output package. Matches
+ * Javadoc's "Miscellaneous Unprocessed Files" behaviour.
+ */
+ private void copyResourceFiles(GroovyPackageDoc packageDoc, String destdir) {
+ for (String sourcepath : sourcepaths) {
+ for (String resourceDir : RESOURCE_DIRS) {
+ Path srcDir = Paths.get(sourcepath, packageDoc.name(), resourceDir);
+ if (!Files.isDirectory(srcDir)) continue;
+ Path dstDir = Paths.get(destdir, packageDoc.name(), resourceDir);
+ copyTree(srcDir, dstDir);
+ }
+ }
+ }
+
+ private void copyTree(Path srcDir, Path dstDir) {
+ try (Stream<Path> stream = Files.walk(srcDir)) {
+ stream.forEach(srcFile -> {
+ Path rel = srcDir.relativize(srcFile);
+ Path dstFile = dstDir.resolve(rel);
+ try {
+ if (Files.isDirectory(srcFile)) {
+ Files.createDirectories(dstFile);
+ } else {
+ Files.createDirectories(dstFile.getParent());
+ Files.copy(srcFile, dstFile, StandardCopyOption.REPLACE_EXISTING);
+ }
+ } catch (IOException e) {
+ log.warn("Failed to copy " + srcFile + " to " + dstFile + ": " + e.getMessage());
+ }
+ });
+ } catch (IOException e) {
+ log.warn("Failed to walk " + srcDir + ": " + e.getMessage());
+ }
+ }
+
public void writePackageToOutput(GroovyPackageDoc packageDoc, String destdir) throws Exception {
Iterator<String> templates = templateEngine.packageTemplatesIterator();
while (templates.hasNext()) {
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index ebc6337f69..2cc285ee38 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -131,6 +131,55 @@ public class GroovyDocToolTest extends GroovyTestCase {
doc.contains("https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Object.html"));
}
+ // GROOVY-5986
+ public void testDocFilesAndSnippetFilesAreCopiedIntoOutput() throws Exception {
+ String fixtureSourcePath = "src/test/resources/docfiles-fixture";
+ String pkg = "org/codehaus/groovy/tools/groovydoc/testfiles/docfiles";
+
+ java.nio.file.Path tmpOut = java.nio.file.Files.createTempDirectory("groovydoc-docfiles-");
+ try {
+ GroovyDocTool tool = new GroovyDocTool(
+ new FileSystemResourceManager("src/main/resources"),
+ new String[]{fixtureSourcePath},
+ GroovyDocTemplateInfo.DEFAULT_DOC_TEMPLATES,
+ GroovyDocTemplateInfo.DEFAULT_PACKAGE_TEMPLATES,
+ GroovyDocTemplateInfo.DEFAULT_CLASS_TEMPLATES,
+ new ArrayList<>(), null, new Properties()
+ );
+ tool.add(List.of(pkg + "/HasDocFiles.groovy"));
+ tool.renderToOutput(new FileOutputTool(), tmpOut.toString());
+
+ java.nio.file.Path docFilesSample = tmpOut.resolve(pkg + "/doc-files/sample.html");
+ java.nio.file.Path docFilesNested = tmpOut.resolve(pkg + "/doc-files/sub/nested.txt");
+ java.nio.file.Path snippetFile = tmpOut.resolve(pkg + "/snippet-files/Example.groovy");
+
+ assertTrue("Expected doc-files/sample.html to be copied, not found at " + docFilesSample,
+ java.nio.file.Files.isRegularFile(docFilesSample));
+ assertTrue("Expected doc-files/sub/nested.txt (nested subdir) to be copied, not found at " + docFilesNested,
+ java.nio.file.Files.isRegularFile(docFilesNested));
+ assertTrue("Expected snippet-files/Example.groovy to be copied, not found at " + snippetFile,
+ java.nio.file.Files.isRegularFile(snippetFile));
+
+ String sampleContent = java.nio.file.Files.readString(docFilesSample);
+ assertTrue("doc-files/sample.html content mismatch", sampleContent.contains("GROOVY-5986 sample doc-files content"));
+ String nestedContent = java.nio.file.Files.readString(docFilesNested);
+ assertTrue("doc-files/sub/nested.txt content mismatch", nestedContent.contains("nested doc-files content"));
+ String snippetContent = java.nio.file.Files.readString(snippetFile);
+ assertTrue("snippet-files/Example.groovy content mismatch", snippetContent.contains("hello from Example"));
+ } finally {
+ deleteRecursively(tmpOut);
+ }
+ }
+
+ private static void deleteRecursively(java.nio.file.Path root) throws java.io.IOException {
+ if (!java.nio.file.Files.exists(root)) return;
+ try (java.util.stream.Stream<java.nio.file.Path> stream = java.nio.file.Files.walk(root)) {
+ stream.sorted(java.util.Comparator.reverseOrder()).forEach(p -> {
+ try { java.nio.file.Files.delete(p); } catch (java.io.IOException ignored) {}
+ });
+ }
+ }
+
// GROOVY-9057
public void testParseErrorIsTrackedInErrorCount() throws Exception {
assertEquals("Initial error count should be zero", 0, xmlToolForTests.getErrorCount());
diff --git a/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/HasDocFiles.groovy b/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/HasDocFiles.groovy
new file mode 100644
index 0000000000..3be3ce5450
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/HasDocFiles.groovy
@@ -0,0 +1,27 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.codehaus.groovy.tools.groovydoc.testfiles.docfiles
+
+/**
+ * GROOVY-5986: sample class in a package that has a {@code doc-files/}
+ * and {@code snippet-files/} subdirectory to be copied verbatim into
+ * the generated docs.
+ */
+class HasDocFiles {
+}
diff --git a/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/doc-files/sample.html b/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/doc-files/sample.html
new file mode 100644
index 0000000000..13cb5468c2
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/doc-files/sample.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you 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
+
+ http://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.
+-->
+<html><body><p>GROOVY-5986 sample doc-files content.</p></body></html>
diff --git a/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/doc-files/sub/nested.txt b/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/doc-files/sub/nested.txt
new file mode 100644
index 0000000000..6dfb255360
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/doc-files/sub/nested.txt
@@ -0,0 +1,18 @@
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you 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
+
+ http://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.
+
+GROOVY-5986: nested doc-files content, verifies recursive copy.
diff --git a/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/snippet-files/Example.groovy b/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/snippet-files/Example.groovy
new file mode 100644
index 0000000000..a84f295664
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/test/resources/docfiles-fixture/org/codehaus/groovy/tools/groovydoc/testfiles/docfiles/snippet-files/Example.groovy
@@ -0,0 +1,20 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.
+ */
+// GROOVY-5986 / GROOVY-11938: sample snippet for future {@snippet file=...} use.
+println "hello from Example"
(groovy) 30/34: update doco
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 6e8d54a6fec66105d4422cec4b903eae11d42196
Author: Paul King <pa...@asert.com.au>
AuthorDate: Tue Apr 21 13:21:25 2026 +1000
update doco
---
.../groovy/ant/GroovydocExcludeTest.groovy | 63 +++
.../groovy-groovydoc/src/spec/doc/groovydoc.adoc | 629 ++++++++++++++++-----
2 files changed, 561 insertions(+), 131 deletions(-)
diff --git a/subprojects/groovy-ant/src/test/groovy/org/codehaus/groovy/ant/GroovydocExcludeTest.groovy b/subprojects/groovy-ant/src/test/groovy/org/codehaus/groovy/ant/GroovydocExcludeTest.groovy
new file mode 100644
index 0000000000..48a0c937b5
--- /dev/null
+++ b/subprojects/groovy-ant/src/test/groovy/org/codehaus/groovy/ant/GroovydocExcludeTest.groovy
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.codehaus.groovy.ant
+
+import org.junit.jupiter.api.Test
+
+import java.lang.reflect.Field
+
+/**
+ * Exercises the {@code excludePackageNames} setter on the Ant Groovydoc
+ * task. The private backing list was consumed by {@code generate()} from
+ * day one but had no public setter — the parity sweep added one.
+ */
+class GroovydocExcludeTest {
+ private static List<String> readExcludeList(Groovydoc task) {
+ Field f = Groovydoc.getDeclaredField('excludePackageNames')
+ f.setAccessible(true)
+ return (List<String>) f.get(task)
+ }
+
+ @Test
+ void testSetExcludePackageNamesCommaSeparated() {
+ def task = new Groovydoc()
+ task.setExcludePackageNames('com.example.internal,com.example.legacy')
+ def names = readExcludeList(task)
+ assert names == ['com.example.internal', 'com.example.legacy']
+ }
+
+ @Test
+ void testSetExcludePackageNamesColonSeparated() {
+ def task = new Groovydoc()
+ // The CLI -exclude flag uses ':' as separator; the Ant setter
+ // tolerates both so scripts porting from CLI don't stumble.
+ task.setExcludePackageNames('com.example.internal:com.example.legacy')
+ def names = readExcludeList(task)
+ assert names == ['com.example.internal', 'com.example.legacy']
+ }
+
+ @Test
+ void testSetExcludePackageNamesAccumulatesAcrossCalls() {
+ def task = new Groovydoc()
+ task.setExcludePackageNames('com.foo')
+ task.setExcludePackageNames('com.bar,com.baz')
+ def names = readExcludeList(task)
+ assert names == ['com.foo', 'com.bar', 'com.baz']
+ }
+}
diff --git a/subprojects/groovy-groovydoc/src/spec/doc/groovydoc.adoc b/subprojects/groovy-groovydoc/src/spec/doc/groovydoc.adoc
index aaddfe293e..39d5940485 100644
--- a/subprojects/groovy-groovydoc/src/spec/doc/groovydoc.adoc
+++ b/subprojects/groovy-groovydoc/src/spec/doc/groovydoc.adoc
@@ -21,73 +21,242 @@
= groovydoc, the Groovy & Java documentation generator
-GroovyDoc is a tool responsible for generating documentation from your code. It acts like the Javadoc tool in the
-Java world but is capable of handling both `groovy` and `java` files. The distribution comes with two ways of generating
-documentation: from <<Groovydoc-CommandLine,command line>> or from <<Groovydoc-Ant,Apache Ant>>. Other build tools
-like Maven or Gradle also offer wrappers for Groovydoc.
+GroovyDoc generates API documentation from your source code. It plays the
+role the Javadoc tool plays in the Java ecosystem, but accepts both
+`.groovy` and `.java` sources and adds conveniences suited to Groovy.
+
+The documentation generator is driven from the
+<<Groovydoc-CommandLine,command line>>, from <<Groovydoc-Ant,Apache Ant>>,
+or from build-tool wrappers such as the GMavenPlus Maven plugin. The
+sections below cover the everyday authoring and invocation patterns;
+<<Groovydoc-Advanced,Advanced topics>> collects the lesser-used features.
+
+[[Groovydoc-Writing]]
+== Writing doc comments
+
+GroovyDoc recognises three forms of doc comment, all of which can
+coexist in the same source file:
+
+* Traditional Javadoc `/**` ... `*/` block comments.
+* https://openjdk.org/jeps/467[JEP 467]-style Markdown comments using
+ runs of `///` line prefixes.
+* Runtime-retained Javadoc `/**@` ... `*/` block comments, whose
+ content is reflectable at runtime via the `@Groovydoc` annotation (see
+ <<Groovydoc-Runtime,Runtime Groovydoc>>).
+
+[[Groovydoc-CommentForms]]
+=== Comment forms
+
+==== Traditional Javadoc
+
+[source,groovy]
+----
+/**
+ * Summary sentence. More description.
+ *
+ * @param name the subject to greet
+ * @return the greeting
+ */
+String greet(String name) { "Hello, $name" }
+----
+
+Leading `* ` prefixes on each line are stripped. The first sentence
+(up to the first period followed by whitespace) is used as the short
+summary on index/package pages.
+
+==== JEP 467 Markdown (`///`)
+
+Each line of the run starts with `///`. Inside the comment, CommonMark
+Markdown is supported — headings, bullets, emphasis, links, and fenced
+code blocks all render as you would expect:
+
+[source,groovy]
+----
+/// # Greet
+///
+/// Returns a friendly greeting. Supports the usual inline tags:
+/// {@link String} and {@code greet} still work.
+///
+/// ```groovy
+/// assert greeter.greet('world') == 'Hello, world'
+/// ```
+///
+/// @param name the subject to greet
+/// @return the greeting
+String greet(String name) { "Hello, $name" }
+----
+
+Markdown is rendered through CommonMark. Headings are shifted down by
+two levels (so `#` becomes `<h3>`) to fit under the page's existing
+title and section banners. Inline Javadoc tags like `{@link ...}` are
+preserved inside Markdown bodies. `{@link ...}` tokens appearing inside
+fenced code blocks are left literal — the fence is treated as code, not
+documentation.
+
+For the full Markdown syntax and semantics, see
+https://openjdk.org/jeps/467[JEP 467] and
+https://commonmark.org[CommonMark].
+
+==== Runtime Groovydoc (`/**@`)
+
+If the comment opens with `/**@` instead of `/**`, Groovy's parser can
+retain the raw comment text as a `groovy.lang.@Groovydoc` annotation on
+the enclosing class/method/field. Enable the feature through the
+compiler option `runtimeGroovydoc`; see <<Groovydoc-Runtime,Runtime
+Groovydoc>>.
+
+[[Groovydoc-BlockTags]]
+=== Block tags
+
+Block tags appear at the end of the comment, one per paragraph, leading
+with `@`. Common tags:
+
+[cols="1,3",options="header"]
+|===
+|Tag |Purpose
+
+|`@param <name> <description>`
+|Describes a parameter. Use `@param <T>` for a type parameter.
+
+|`@return <description>`
+|Describes the return value.
+
+|`@throws <exception> <description>`, `@exception <exception> <description>`
+|Describes an exception the method might throw.
+
+|`@since <version>`
+|Indicates when the feature was added.
+
+|`@author <name>`
+|Author of the element. Rendered only when `-author` is enabled.
+
+|`@version <text>`
+|Version information.
+
+|`@deprecated <explanation>`
+|Marks the element as deprecated; recommend a replacement.
+
+|`@see <reference>`
+|Adds a "See Also" entry. The reference is a class or member.
+
+|`@apiNote <text>`
+|Guidance intended for callers of the API.
+
+|`@implSpec <text>`
+|Contract that overriders must preserve.
+
+|`@implNote <text>`
+|Non-contract implementation detail.
+|===
+
+Multiple `@param`, `@throws`, and `@see` entries are collated under a
+single heading in the rendered output.
+
+[[Groovydoc-InlineTags]]
+=== Inline tags
+
+Inline tags appear within a comment body and are expanded in place.
+
+[cols="1,3",options="header"]
+|===
+|Tag |Purpose
+
+|`{@link <reference>}`
+|Cross-reference to a class or member. Produces a hyperlink.
+
+|`{@code <text>}`
+|Renders the text in a monospaced code style. HTML metacharacters are
+escaped.
+
+|`{@literal <text>}`
+|Renders the text verbatim without code styling.
+
+|`{@value #FIELD}`, `{@value Class#FIELD}`
+|Inlines the value of a compile-time-constant field. Same-class
+references and cross-class references both work. On a constant field's
+own comment, bare `{@value}` inlines that field's own value.
+
+|`{@inheritDoc}`
+|Inherits the parent class's/interface's corresponding doc.
+
+|`{@snippet ...}`
+|Embeds a code snippet. See <<Groovydoc-Snippet,{@snippet}>> under
+advanced topics.
+
+|`{@docRoot}`
+|Path to the root of the generated documentation. Useful when writing
+a relative link that must work from pages at any depth.
+|===
+
+[[Groovydoc-Running]]
+== Running groovydoc
[[Groovydoc-CommandLine]]
-== The groovydoc command line tool
+=== The `groovydoc` command line tool
-The `groovydoc` command line can be invoked to generate groovydocs:
+The `groovydoc` command line invocation:
----
groovydoc [options] [packagenames] [sourcefiles]
----
-where options must be picked from the following table:
+Most commonly-used options:
[cols="2,2,5",options="header,footer"]
|=======================================================================
|Short version |Long version |Description
-|-author | |Include @author paragraphs (currently not used)
-|-charset <charset>| |Charset for cross-platform viewing of generated documentation
-|-classpath, -cp | --classpath |Specify where to find the class files - must be
-first argument
+
|-d |--destdir <dir> |Destination directory for output files
-| |--debug|Enable debug output
-|-doctitle <html> | |Include title for the overview page
-|-exclude <pkglist>| | Specify a list of packages to exclude
-(separated by colons for all operating systems)
-|-fileEncoding <charset>| |Charset for generated documentation files
-|-footer <html> | |Include footer text for each page
-|-header <html> | |Include header text for each page
-|-help|--help|Display help message
-|-nomainforscripts| |Don't include the implicit 'public static void
-main' method for scripts
-|-noscripts| |Don't process Groovy Scripts
-|-notimestamp| |Don't include timestamp within hidden comment in generated HTML
-|-noversionstamp| |Don't include Groovy version within hidden comment in generated HTML
-|-overview <file>| |Read overview documentation from HTML file
+|-sourcepath <pathlist>| |Directories to find source files (platform path separator)
+|-classpath, -cp | --classpath |Where to find class files (must be first argument)
+
+|-public| |Show only public classes and members
+|-protected| |Show protected/public classes and members (default)
|-package| |Show package/protected/public classes and members
|-private| |Show all classes and members
-|-protected| |Show protected/public classes and members (default)
-|-public| |Show only public classes and members
-|-quiet| |Suppress superfluous output
-|-sourcepath <pathlist>| |Specify where to find source files (dirs
-separated by platform path separator)
-|-stylesheetfile <path>| |File to change style of the generated documentation
-|-verbose| |Enable verbose output
-| |--version|Display the version
-|-windowtitle <text>| |Browser window title for the documentation
-|-javaversion <version> | | The version of the Java source files
-|=======================================================================
-=== Java Versions
-
-The supported Java Versions for `groovydoc` are defined by the JavaParser library's link:https://www.javadoc.io/doc/com.github.javaparser/javaparser-core/{javaParserVersion}/com/github/javaparser/ParserConfiguration.LanguageLevel.html[LanguageLevel] class.
+|-charset <charset>| |Charset for cross-platform viewing of generated HTML
+|-fileEncoding <charset>| |Charset for generated documentation files
-[[Groovydoc-Ant]]
-== The groovydoc Ant task
+|-doctitle <html> | |Title for the overview page
+|-windowtitle <text>| |Browser window title
+|-header <html> | |Include header text on each page
+|-footer <html> | |Include footer text on each page
+|-overview <file>| |Read overview documentation from HTML file
-The `groovydoc` Ant task allows generating groovydocs from an Ant build.
+|-exclude <pkglist>| |Exclude listed packages (colon-separated)
+|-noscripts| |Don't process Groovy Scripts
+|-author| |Include `@author` paragraphs
+
+|-stylesheetfile <path>| |Replace the default stylesheet with a supplied one
+|-addStylesheet <path>| |Add a stylesheet *alongside* the default (can be
+given multiple times with comma-separated values)
+|-theme <mode>| |Theme: `auto` (default, follow OS), `light`, or `dark`
+|-syntaxHighlighter <name>| |Client-side syntax highlighter: `prism`
+(bundled) or `none` (default)
+
+|-showInternal| |Include members annotated with `groovy.transform.@Internal`
+(hidden by default)
+|-noindex| |Skip generating the alphabetical index page
+|-nodeprecatedlist| |Skip generating the deprecated list
+|-nohelp| |Skip generating the help page
+
+|-notimestamp| |Don't include generation timestamp in output
+|-noversionstamp| |Don't include Groovy version in output
+|-nomainforscripts| |Don't include the implicit `public static void main`
+method for scripts
+
+|-help, -h |--help |Display help message
+|-verbose, -quiet, --debug| |Adjust logging verbosity
+| |--version|Display the version
+|-javaVersion <version> | | Language version for parsed Java files (e.g. `JAVA_17`)
+|=======================================================================
-[[ThegroovydocAnttask-Requiredtaskdef]]
-=== Required taskdef
+[[Groovydoc-Ant]]
+=== The `groovydoc` Ant task
-Assuming all the groovy jars you need are in _my.classpath_ (this will be `groovy-VERSION.jar`,
-`groovy-ant-VERSION.jar`, `groovy-groovydoc-VERSION.jar` plus any modules and transitive dependencies you might be using)
-you will need to declare this task at some point in the build.xml prior to the groovydoc task being invoked.
+The Ant task exposes the same feature set. You will need the task
+defined before invoking it:
[source,xml]
-----------------------------------------------------------
@@ -96,45 +265,69 @@ you will need to declare this task at some point in the build.xml prior to the g
classpathref = "my.classpath"/>
-----------------------------------------------------------
-[[ThegroovydocAnttask-groovydocAttributes]]
-=== <groovydoc> Attributes
+where _my.classpath_ references the Groovy distribution jars
+(`groovy-VERSION.jar`, `groovy-ant-VERSION.jar`,
+`groovy-groovydoc-VERSION.jar`, plus any modules and transitive
+dependencies you use).
+
+==== `<groovydoc>` attributes
-[cols="1,2,1",options="header,footer"]
+[cols="1,3,1",options="header,footer"]
|=======================================================================
|Attribute |Description |Required
-|destdir |Location to store the class files. |Yes
-|sourcepath |The sourcepath to use. |No
-|packagenames |Comma separated list of package files (with terminating
-wildcard). |No
-|use |Create class and package usage pages. |No
-|windowtitle |Browser window title for the documentation (text). |No
-|doctitle |Include title for the package index(first) page (html-code).
-|No
-|header |Include header text for each page (html-code). |No
-|footer |Include footer text for each page (html-code). |No
-|overview |Read overview documentation from HTML file. |No
-|private |Show all classes and members (i.e. including private ones) if
-set to ``true''. |No
-|javaversion |The version of the Java source files. |No
+
+|destdir |Location to write generated documentation to. |Yes
+|sourcepath |Directories to scan for source files. |No
+|packagenames |Comma-separated list of package specs (wildcards allowed,
+e.g. `com.foo.**`). |No
+|excludePackageNames |Comma-separated (or colon-separated) list of
+package specs to exclude. |No
+|windowtitle |Browser window title. |No
+|doctitle |HTML shown at the top of the overview page. |No
+|header, footer |HTML shown at the top/bottom of every page. |No
+|overview |HTML file read as the overview page. |No
+|stylesheetFile |Replace the default stylesheet with a supplied one. |No
+|private |Show all classes and members (including private ones). |No
+|access |Visibility scope: `public`, `protected`, `package`, `private`. |No
+|javaVersion |Language version for Java source files. |No
+|extensions |Colon-separated source extensions (default
+`.java:.groovy:.gv:.gvy:.gsh`). |No
+|showInternal |Include members annotated with
+`groovy.transform.@Internal`. |No
+|noIndex, noDeprecatedList, noHelp |Suppress the matching auxiliary page. |No
+|syntaxHighlighter |`prism` or `none` (default). |No
+|theme |Theme lock: `auto` (default), `light`, or `dark`. |No
+|noTimestamp, noVersionStamp |Omit the matching stamp from output. |No
|=======================================================================
-[[ThegroovydocAnttask-groovydocNestedElements]]
-=== <groovydoc> Nested Elements
+==== `<groovydoc>` nested elements
+
+===== `<link>`
+
+Create cross-references to external Javadoc/groovydoc output. See
+<<Groovydoc-Link,Linking to external APIs>>.
+
+[cols="1,3,1",options="header,footer"]
+|=======================================================
+|Attribute |Description |Required
+|packages |Comma-separated list of package prefixes. |Yes
+|href |Base URL of the external site. |Yes
+|module |JPMS module name; inserted as a path segment for
+modular Javadoc layouts. |No
+|=======================================================
-[[ThegroovydocAnttask-link]]
-==== link
+===== `<addStylesheet>`
-Create link to groovydoc/javadoc output at the given URL.
+Add an extra stylesheet alongside the default. Repeat the element to add
+multiple stylesheets.
-[cols="<,<,<",options="header,footer"]
+[cols="1,3,1",options="header,footer"]
|=======================================================
|Attribute |Description |Required
-|packages |Comma separated list of package prefixes |Yes
-|href |Base URL of external site |Yes
+|file |Path to the stylesheet file. |Yes
|=======================================================
-[[ThegroovydocAnttask-Example1-groovydocAnttask]]
-==== Example #1 - <groovydoc> Ant task
+==== Ant task example
[source,xml]
----------------------------------------------------------------------------------------------------------------
@@ -152,50 +345,233 @@ Create link to groovydoc/javadoc output at the given URL.
footer = "${docFooter}"
overview = "src/main/overview.html"
private = "false">
- <link packages="java.,org.xml.,javax.,org.xml." href="http://docs.oracle.com/javase/8/docs/api/"/>
- <link packages="org.apache.tools.ant." href="http://docs.groovy-lang.org/docs/ant/api/"/>
- <link packages="org.junit.,junit.framework." href="http://junit.org/junit4/javadoc/latest/"/>
- <link packages="groovy.,org.codehaus.groovy." href="http://docs.groovy-lang.org/latest/html/api/"/>
- <link packages="org.codehaus.gmaven." href="http://groovy.github.io/gmaven/apidocs/"/>
+ <link packages="java.,org.xml.,javax.,org.xml." href="https://docs.oracle.com/javase/8/docs/api/"/>
+ <link packages="org.apache.tools.ant." href="https://docs.groovy-lang.org/docs/ant/api/"/>
+ <link packages="org.junit.,junit.framework." href="https://junit.org/junit4/javadoc/latest/"/>
+ <link packages="groovy.,org.codehaus.groovy." href="https://docs.groovy-lang.org/latest/html/api/"/>
</groovydoc>
----------------------------------------------------------------------------------------------------------------
-[[ThegroovydocAnttask-Example2-ExecutinggroovydocfromGroovy]]
-==== Example #2 - Executing <groovydoc> from Groovy
+Running the task from Groovy via `AntBuilder` works the same way.
+
+[[Groovydoc-Link]]
+== Linking to external APIs
+
+`<link>` (Ant) and `-link` (CLI) let cross-references resolve to an
+external Javadoc/groovydoc site. Packages are matched by the `packages`
+attribute as a comma-separated list of prefixes; when a documented
+reference matches one of the prefixes the link goes to the configured
+`href` base.
+
+The `module` attribute on `<link>` supports modular Javadoc layouts,
+where an external site places each JPMS module's docs under a
+module-named subdirectory. With `module="java.base"` and
+`href="https://docs.oracle.com/en/java/javase/17/docs/api/"`, a link to
+`java.lang.Object` resolves to
+`https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Object.html`.
+
+[[Groovydoc-Customising]]
+== Customising the output
+
+=== Stylesheets
+
+Two mechanisms cover most customisation needs:
+
+* `-stylesheetfile <path>` (CLI) / `stylesheetFile="..."` (Ant) —
+ *replaces* the default stylesheet. The supplied file is copied verbatim
+ over `stylesheet.css` in the output. If the file has no dark-mode
+ support of its own, the generated docs will be light-only regardless
+ of the theme settings below.
+* `-addStylesheet <path>` (CLI) / `<addStylesheet file="..."/>` (Ant) —
+ *adds* an extra stylesheet alongside the default. The default is still
+ loaded and supplies the baseline look; the added stylesheet layers on
+ top. This is the safer choice for theme tweaks.
+
+Author stylesheets can opt into the baseline palette by referencing the
+default stylesheet's CSS custom properties (`--fg`, `--bg`, `--link`,
+`--bg-panel`, `--border`, `--caption-bg`, and related semantic tokens).
+Doing so makes the added stylesheet automatically dark-mode aware.
+
+=== Theme
+
+`-theme <mode>` / `theme="..."` controls the palette strategy:
+
+* `auto` (default) — the generated stylesheet emits a
+ `prefers-color-scheme` media query. Each reader's browser picks the
+ light or dark palette that matches their OS preference. Syntax
+ highlighting (if enabled) switches Prism themes in sync.
+* `light` — locks the output to the light palette regardless of OS
+ preference.
+* `dark` — locks the output to the dark palette regardless of OS
+ preference.
+
+`auto` is the right choice for public-facing docs that should adapt to
+the reader. `light` and `dark` are useful for branded sites where a
+consistent look matters more than honouring OS preference.
+
+=== Syntax highlighting
+
+`-syntaxHighlighter prism` / `syntaxHighlighter="prism"` enables
+client-side syntax highlighting for `{@snippet}` blocks and Markdown
+fenced code blocks. Prism.js is bundled and covers at minimum Groovy,
+Java, XML, JSON, YAML, TOML, SQL, CSV, Markdown, JavaScript, and
+regex. The light/dark theme selection tracks the
+<<Groovydoc-Theme,theme>> setting automatically. The default is `none`
+(no highlighting); code blocks are rendered as plain preformatted text.
+
+=== Disable optional pages
+
+GroovyDoc generates auxiliary pages by default:
+
+* `index-all.html` — alphabetical index of every class and member
+* `deprecated-list.html` — everything marked `@deprecated`
+* `help-doc.html` — explanation of the page layout
+
+Any of these can be suppressed with `-noindex`, `-nodeprecatedlist`,
+`-nohelp` (CLI) or the corresponding `noIndex`, `noDeprecatedList`,
+`noHelp` Ant attributes. When suppressed, the page is not generated and
+navigation bars on other pages omit the corresponding link.
+
+[[Groovydoc-GMavenPlus]]
+== GMavenPlus Maven plugin
+
+https://github.com/groovy/GMavenPlus[GMavenPlus] is a Maven plugin with
+goals that drive groovydoc. Consult the plugin documentation for the
+current list of options it exposes.
+
+[[Groovydoc-Advanced]]
+== Advanced topics
+
+[[Groovydoc-Snippet]]
+=== `{@snippet}` code snippets
+
+`{@snippet}` embeds a code sample that renders as a preformatted block
+and, when syntax highlighting is enabled, is coloured according to its
+declared language. Three forms are supported:
+
+==== Inline body
[source,groovy]
---------------------------------------------------------------------------------------------------------------
-def ant = new AntBuilder()
-ant.taskdef(name: "groovydoc", classname: "org.codehaus.groovy.ant.Groovydoc")
-ant.groovydoc(
- destdir : "${docsDirectory}/gapi",
- sourcepath : "${mainSourceDirectory}",
- packagenames : "**.*",
- use : "true",
- windowtitle : "${title}",
- doctitle : "${title}",
- header : "${title}",
- footer : "${docFooter}",
- overview : "src/main/overview.html",
- private : "false") {
- link(packages:"java.,org.xml.,javax.,org.xml.",href:"http://docs.oracle.com/javase/8/docs/api/")
- link(packages:"groovy.,org.codehaus.groovy.", href:"http://docs.groovy-lang.org/latest/html/api/")
- link(packages:"org.apache.tools.ant.", href:"http://docs.groovy-lang.org/docs/ant/api/")
- link(packages:"org.junit.,junit.framework.", href:"http://junit.org/junit4/javadoc/latest/")
- link(packages:"org.codehaus.gmaven.", href:"http://groovy.github.io/gmaven/apidocs/")
-}
---------------------------------------------------------------------------------------------------------------
+----
+/**
+ * {@snippet lang="groovy" :
+ * def greet(name) { "Hello, $name" }
+ * greet('world')
+ * }
+ */
+----
-=== Custom templates
+The language is optional; when set, it becomes the Prism language class
+used for syntax highlighting. Any text from the opening brace to the
+matching closing brace is the snippet body.
+
+==== External file reference
+
+Place the source of the snippet in a `snippet-files/` subdirectory of
+the current package, then reference it:
+
+[source,groovy]
+----
+/** {@snippet file="GreetExample.groovy"} */
+----
-The `groovydoc` Ant task supports custom templates, but it requires two steps:
+The `snippet-files/` directory is discovered via the `-sourcepath`.
+The file is copied to the output site verbatim so that the snippet
+remains browsable in the rendered docs.
-. A custom groovydoc class
-. A new groovydoc task definition
+A `region="name"` attribute selects a slice of the file bounded by
+`// @start region="name"` and `// @end region="name"` marker comments.
-==== Custom Groovydoc class
+==== Markup comments inside a snippet body
-The first step requires you to extend the `Groovydoc` class, like in the following example:
+Markup comments let snippet authors highlight, replace, or link portions
+of the code without changing the source itself:
+
+[cols="1,3",options="header"]
+|===
+|Directive |Effect
+
+|`// @highlight [substring="text"\|regex="pattern"] [type="bold\|italic\|highlighted"]`
+|Wrap matches in `<b>`/`<i>`/`<mark>`. Type defaults to `bold`.
+
+|`// @replace [substring="text"\|regex="pattern"] replacement="text"`
+|Replace matching text in the rendered output.
+
+|`// @link [substring="text"\|regex="pattern"] target="Class[#member]"`
+|Turn matches into anchors pointing at the referenced element.
+
+|`// @start region="name"`, `// @end [region="name"]`
+|Define a named region for the external-file form, or as a scoping
+bound for any of the above directives.
+|===
+
+A directive written on its own line applies to the next code line. A
+directive written at the end of a code line (after the code) applies to
+that line's code portion. Adding a `region="name"` attribute to a
+directive activates it until the matching `// @end`. Directive comment
+lines are stripped from the rendered output.
+
+For the complete semantics see https://openjdk.org/jeps/413[JEP 413].
+
+=== Class hierarchy tree pages
+
+GroovyDoc generates a global `overview-tree.html` and per-package
+`package-tree.html` showing class and interface hierarchies. Classes are
+rooted at `java.lang.Object`; interfaces and traits form a separate
+tree. External ancestors (types the tool can't see) render as plain
+text joining documented classes up the chain.
+
+[[Groovydoc-Runtime]]
+=== Runtime Groovydoc (`/**@`)
+
+A doc comment whose opening marker is `/**@` instead of `/**` can be
+retained as runtime metadata. Enable it by setting the compiler
+option:
+
+[source,groovy]
+----
+compilerConfiguration.setOptimizationOptions(
+ [(CompilerConfiguration.RUNTIME_GROOVYDOC): true]
+)
+----
+
+When enabled, the parser attaches the raw comment text (still in source
+form — including `/**@`, per-line `*`, and `*/`) to the declaration as
+a `groovy.lang.@Groovydoc` annotation. Readers access the text
+reflectively:
+
+[source,groovy]
+----
+assert SomeClass.class.groovydoc.content.contains('class summary')
+----
+
+`/**@` comments do not need to be marked specially to participate in
+normal groovydoc HTML generation; they render identically to `/**`.
+
+[[Groovydoc-DocFiles]]
+=== `doc-files/` and `snippet-files/`
+
+Each package may contain a `doc-files/` subdirectory whose content is
+copied verbatim into the rendered output under the same package path.
+Useful for bundling images, diagrams, and supplementary HTML alongside
+the generated pages.
+
+The sibling convention `snippet-files/` is used by
+<<Groovydoc-Snippet,`{@snippet file=...`>>. Both conventions are sourced
+from `-sourcepath` directories and preserve nested subdirectories.
+
+=== Java source version
+
+`-javaVersion` (CLI) / `javaVersion` (Ant attribute) declares the
+language level at which `.java` source files are parsed. The accepted
+values are the names of the
+link:https://www.javadoc.io/doc/com.github.javaparser/javaparser-core/{javaParserVersion}/com/github/javaparser/ParserConfiguration.LanguageLevel.html[`ParserConfiguration.LanguageLevel`]
+enum — for example `JAVA_8`, `JAVA_17`, `JAVA_21`.
+
+=== Custom templates
+
+The default template set can be replaced by extending `Groovydoc` in a
+small Java class:
[source,java]
----
@@ -203,43 +579,34 @@ package org.codehaus.groovy.tools.groovydoc;
import org.codehaus.groovy.ant.Groovydoc;
-/**
- * Overrides GroovyDoc's default class template - for testing purpose only.
- */
public class CustomGroovyDoc extends Groovydoc {
@Override
protected String[] getClassTemplates() {
- return new String[]{"org/codehaus/groovy/tools/groovydoc/testfiles/classDocName.html"};
+ return new String[]{"path/to/custom/classDocName.html"};
}
}
----
-You can override the following methods:
+The following methods can be overridden:
-* `getClassTemplates` for class-level templates
-* `getPackageTemplates` for package-level templates
-* `getDocTemplates` for top-level templates
+* `getClassTemplates` — class-level templates
+* `getPackageTemplates` — package-level templates
+* `getDocTemplates` — top-level (overview, index, tree, etc.) templates
-You can find the list of default templates in the `org.codehaus.groovy.tools.groovydoc.gstringTemplates.GroovyDocTemplateInfo`
-class.
+The list of default templates is in
+`org.codehaus.groovy.tools.groovydoc.gstringTemplates.GroovyDocTemplateInfo`.
-==== Using the custom groovydoc task
-
-Once you've written the class, using it is just a matter of redefining the `groovydoc` task:
+Having extended the task, you then register it as an Ant task under the
+same name:
[source,xml]
----
-<taskdef name = "groovydoc"
- classname = "org.codehaus.groovy.ant.CustomGroovyDoc"
- classpathref = "path_to_groovy_all"/>
+<taskdef name = "groovydoc"
+ classname = "org.codehaus.groovy.tools.groovydoc.CustomGroovyDoc"
+ classpathref = "path_to_groovy_all"/>
----
-Please note that template customization is provided as is. APIs are subject to change, so you must consider this as a
-fragile feature.
-
-[[Groovydoc-GMavenPlus]]
-== GMavenPlus Maven Plugin
-https://github.com/groovy/GMavenPlus[GMavenPlus] is a Maven plugin with goals that
-support GroovyDoc generation.
+Template customisation is provided as is — the template APIs are subject
+to change between releases.
(groovy) 24/34: GROOVY-11938: {@snippet} per JEP 413 (tests)
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit cdbd152557896d1154720dbbc3617910ba33afb4
Author: Paul King <pa...@asert.com.au>
AuthorDate: Tue Apr 21 00:20:13 2026 +1000
GROOVY-11938: {@snippet} per JEP 413 (tests)
---
.../groovy/tools/groovydoc/TagRenderer.java | 27 ++++++++++++++-
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 38 ++++++++++++++++++++++
.../testfiles/ClassWithMarkdownAndSnippet.groovy | 38 ++++++++++++++++++++++
3 files changed, 102 insertions(+), 1 deletion(-)
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
index e1b1736cbe..aba098dccf 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
@@ -304,7 +304,17 @@ final class TagRenderer {
i = skipWhitespace(text, i);
if (i >= n) return 0;
char q = text.charAt(i);
- if (q == '"' || q == '\'') {
+ // GROOVY-11938 stage 5: a Markdown body is HTML-escaped by
+ // CommonMark before TagRenderer runs, so `"` appears as
+ // `"` (and `'` as `'` / `'`). Recognise those
+ // entity forms as quote delimiters in addition to literal.
+ String entityEnd = matchQuoteEntity(text, i);
+ if (entityEnd != null) {
+ int close = text.indexOf(entityEnd, i + entityEnd.length());
+ if (close < 0) return 0;
+ attrValue = text.substring(i + entityEnd.length(), close);
+ i = close + entityEnd.length();
+ } else if (q == '"' || q == '\'') {
int close = text.indexOf(q, i + 1);
if (close < 0) return 0;
attrValue = text.substring(i + 1, close);
@@ -805,6 +815,21 @@ final class TagRenderer {
return i;
}
+ /**
+ * GROOVY-11938 stage 5: detect an HTML-entity-encoded quote delimiter at
+ * position {@code i} in {@code text}. Returns the exact sequence
+ * ({@code """}, {@code "'"}, {@code """}, or
+ * {@code "'"}) when matched so the caller can find the matching
+ * closing sequence; returns {@code null} otherwise.
+ */
+ private static String matchQuoteEntity(String text, int i) {
+ if (text.startsWith(""", i)) return """;
+ if (text.startsWith("'", i)) return "'";
+ if (text.startsWith(""", i)) return """;
+ if (text.startsWith("'", i)) return "'";
+ return null;
+ }
+
/**
* A '@' begins a block tag only if it's at text start or preceded by
* whitespace. The old TAG_REGEX had a laxer lookbehind ({@code \s*} —
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index 90b0e71761..739540a40c 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -495,6 +495,44 @@ public class GroovyDocToolTest extends GroovyTestCase {
page.contains("the doubled value"));
}
+ // GROOVY-11938 stage 5: Markdown and {@snippet} interop. A /// doc comment
+ // containing a Markdown heading, an inline {@snippet}, and a fenced
+ // Markdown code block emits three distinct HTML chunks without the
+ // rendering passes interfering.
+ public void testMarkdownAndSnippetInterop() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ htmlTool.add(List.of(base + "/ClassWithMarkdownAndSnippet.groovy"));
+ MockOutputTool output = new MockOutputTool();
+ htmlTool.renderToOutput(output, MOCK_DIR);
+
+ String page = output.getText(MOCK_DIR + "/" + base + "/ClassWithMarkdownAndSnippet.html");
+ assertNotNull(page);
+ // The Markdown heading (# Markdown + snippet interop) becomes <h3>
+ // (heading-shift from class-level context — see MarkdownRenderer).
+ assertTrue("Expected Markdown # heading shifted to <h3> in:\n" + page,
+ page.contains("<h3>Markdown + snippet interop</h3>"));
+ // Both code blocks should emit <pre><code class="language-groovy">.
+ // The {@snippet lang="groovy" :...} one (TagRenderer output) and the
+ // fenced ```groovy block (CommonMark output) share the same class.
+ int occurrences = page.split("<code class=\"language-groovy\">", -1).length - 1;
+ assertEquals("Expected exactly two <code class=\"language-groovy\"> blocks — "
+ + "one from {@snippet}, one from the Markdown fence — in:\n" + page,
+ 2, occurrences);
+ // {@snippet} body: `$name` dollar-sign must be preserved (no GString
+ // interpretation, no mangling), inside-string quotes get HTML-escaped
+ // to " but the value text is intact.
+ assertTrue("Expected snippet body to preserve $name literal in:\n" + page,
+ page.contains("$name!"));
+ assertTrue("Expected snippet greet() body in:\n" + page,
+ page.contains("def greet(name)"));
+ // Markdown fenced block body: CommonMark HTML-escapes quotes the same
+ // way TagRenderer does, and our CodeBraceMasker converts `{` / `}`
+ // inside code fences to numeric entities so inline-tag-looking text
+ // stays literal.
+ assertTrue("Expected fenced-block farewell body with masked braces in:\n" + page,
+ page.contains("def farewell() { "Bye!" }"));
+ }
+
// GROOVY-11938 stage 4: opt-in client-side syntax highlighting via Prism.
// When -syntaxHighlighter=prism is passed, the head of each content page
// should include prism.min.css and the bundled language scripts; when
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithMarkdownAndSnippet.groovy b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithMarkdownAndSnippet.groovy
new file mode 100644
index 0000000000..0d55742a27
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithMarkdownAndSnippet.groovy
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.codehaus.groovy.tools.groovydoc.testfiles
+
+/// # Markdown + snippet interop
+///
+/// This class mixes **Markdown** prose, an inline `{@snippet}`, and a
+/// fenced Markdown code block. All three should render as distinct chunks
+/// of HTML without interfering with one another.
+///
+/// {@snippet lang="groovy" :
+/// def greet(name) { "Hello, $name!" }
+/// greet("world")
+/// }
+///
+/// A fenced Markdown code block renders via CommonMark:
+///
+/// ```groovy
+/// def farewell() { "Bye!" }
+/// ```
+class ClassWithMarkdownAndSnippet {
+}
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 91646945a1081434d4f11d1830b9f5e4616a7775
Author: Paul King <pa...@asert.com.au>
AuthorDate: Tue Apr 21 06:42:30 2026 +1000
GROOVY-11945: recognise @apiNote, @implSpec, @implNote block tags
---
.../groovy/tools/groovydoc/TagRenderer.java | 8 +++++
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 34 +++++++++++++++++++
.../testfiles/ClassWithImplNoteTags.groovy | 38 ++++++++++++++++++++++
3 files changed, 80 insertions(+)
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
index d4f9ea023d..ad9083f171 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/TagRenderer.java
@@ -90,6 +90,14 @@ final class TagRenderer {
/** Block-tag names that get merged under a single display heading. */
static final Map<String, String> COLLATED_TAGS = new LinkedHashMap<>();
static {
+ // GROOVY-11945: three "note" tags standardised by Javadoc's stdlib
+ // doclet since JEP 172. Recognised so the display heading is right
+ // (not the raw lowercase tag name) and so the bodies are collated
+ // with the rest of the block tags rather than emitted inline at
+ // source position.
+ COLLATED_TAGS.put("apiNote", "API Note");
+ COLLATED_TAGS.put("implSpec", "Implementation Requirements");
+ COLLATED_TAGS.put("implNote", "Implementation Note");
COLLATED_TAGS.put("see", "See Also");
COLLATED_TAGS.put("param", "Parameters");
COLLATED_TAGS.put("throw", "Throws");
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index 17f17296bb..9098e34e21 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -533,6 +533,40 @@ public class GroovyDocToolTest extends GroovyTestCase {
snippet.contains("@link"));
}
+ // GROOVY-11945: @apiNote / @implSpec / @implNote render with their
+ // Javadoc-standard display headings (not the raw lowercase tag names),
+ // and their bodies get collated into the tags section alongside
+ // @param / @return.
+ public void testImplNoteTagsRenderWithProperHeadings() throws Exception {
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ htmlTool.add(List.of(base + "/ClassWithImplNoteTags.groovy"));
+ MockOutputTool output = new MockOutputTool();
+ htmlTool.renderToOutput(output, MOCK_DIR);
+
+ String page = output.getText(MOCK_DIR + "/" + base + "/ClassWithImplNoteTags.html");
+ assertNotNull(page);
+ assertTrue("API Note heading expected in:\n" + page,
+ page.contains("<B>API Note:</B>"));
+ assertTrue("Implementation Requirements heading expected in:\n" + page,
+ page.contains("<B>Implementation Requirements:</B>"));
+ assertTrue("Implementation Note heading expected in:\n" + page,
+ page.contains("<B>Implementation Note:</B>"));
+ // Bodies reach the rendered page.
+ assertTrue("apiNote body expected:\n" + page,
+ page.contains("null-check the result"));
+ assertTrue("implSpec body expected:\n" + page,
+ page.contains("non-negative contract"));
+ assertTrue("implNote body expected:\n" + page,
+ page.contains("uses a sieve for efficiency"));
+ // Raw lowercase tag name should NOT appear as a heading.
+ assertFalse("Raw 'implNote:' should not leak as a heading:\n" + page,
+ page.contains("<B>implNote:</B>"));
+ assertFalse("Raw 'implSpec:' should not leak as a heading:\n" + page,
+ page.contains("<B>implSpec:</B>"));
+ assertFalse("Raw 'apiNote:' should not leak as a heading:\n" + page,
+ page.contains("<B>apiNote:</B>"));
+ }
+
// GROOVY-11938 stage 3 region support: a directive with region="name"
// activates at its line and applies until the matching // @end marker.
public void testSnippetMarkupRegionScoping() throws Exception {
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithImplNoteTags.groovy b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithImplNoteTags.groovy
new file mode 100644
index 0000000000..0ebdb9495f
--- /dev/null
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithImplNoteTags.groovy
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.codehaus.groovy.tools.groovydoc.testfiles
+
+/**
+ * GROOVY-11945 fixture: a method documented with the three Javadoc "note"
+ * tags standardised since JEP 172, alongside ordinary block tags.
+ */
+class ClassWithImplNoteTags {
+ /**
+ * Compute something.
+ *
+ * @apiNote Callers should null-check the result before use.
+ * @implSpec Overriders must preserve the non-negative contract.
+ * @implNote This implementation uses a sieve for efficiency.
+ * @param n the input value
+ * @return a non-negative integer
+ */
+ int compute(int n) {
+ return Math.abs(n)
+ }
+}
(groovy) 10/34: GROOVY-6016: {@value} inline tag
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit e58d238888dae4dfe6f4b409a98990f0c8284a80
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Apr 20 18:03:03 2026 +1000
GROOVY-6016: {@value} inline tag
---
.../org/apache/groovy/antlr/GroovydocVisitor.java | 30 +++++++++++++++++-----
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 8 +++---
.../groovydoc/testfiles/ClassWithValueTag.groovy | 9 +++++--
3 files changed, 35 insertions(+), 12 deletions(-)
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java b/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
index f24e4cf215..17f426bb56 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/apache/groovy/antlr/GroovydocVisitor.java
@@ -550,14 +550,30 @@ public class GroovydocVisitor extends ClassCodeVisitorSupport {
processModifiers(fieldDoc, node, node.getModifiers());
processAnnotations(fieldDoc, node);
fieldDoc.setRawCommentText(getDocContent(node.getGroovydoc()));
- // GROOVY-6016: record the source form of simple-constant initializers
- // so {@value #FIELD} can resolve them at render time. Javadoc's
- // convention is to re-quote strings/chars; ConstantExpression.getText()
- // returns the raw value without quotes.
+ // GROOVY-6016: record the source form of compile-time-constant
+ // initializers so {@value #FIELD} can resolve them at render time.
+ // Leverage ExpressionUtils.transformInlineConstants (same utility used
+ // by Verifier, JavaStubGenerator, AnnotationVisitor, etc.) to fold
+ // simple constant expressions like `40 + 2`, `"a" + "b"`, references
+ // to other static-final constants, and casts — not just bare literals.
+ // Javadoc's convention is to re-quote strings/chars;
+ // ConstantExpression.getText() returns the raw value without quotes.
org.codehaus.groovy.ast.expr.Expression init = node.getInitialExpression();
- if (init instanceof org.codehaus.groovy.ast.expr.ConstantExpression) {
- Object value = ((org.codehaus.groovy.ast.expr.ConstantExpression) init).getValue();
- fieldDoc.setConstantValueExpression(formatConstantValue(value));
+ if (init != null) {
+ // Typed variant does numeric arithmetic folding but needs the
+ // target type to equal ClassHelper.STRING_TYPE for string concat,
+ // which isn't always the case at CONVERSION phase. Type-less
+ // variant handles string concat via isStringType on operand types.
+ // Try both; take whichever yields a ConstantExpression.
+ org.codehaus.groovy.ast.expr.Expression folded =
+ org.apache.groovy.ast.tools.ExpressionUtils.transformInlineConstants(init, node.getType());
+ if (!(folded instanceof org.codehaus.groovy.ast.expr.ConstantExpression)) {
+ folded = org.apache.groovy.ast.tools.ExpressionUtils.transformInlineConstants(init);
+ }
+ if (folded instanceof org.codehaus.groovy.ast.expr.ConstantExpression) {
+ Object value = ((org.codehaus.groovy.ast.expr.ConstantExpression) folded).getValue();
+ fieldDoc.setConstantValueExpression(formatConstantValue(value));
+ }
}
if (node.isEnum()) {
currentClassDoc.addEnumConstant(fieldDoc);
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index fe950e9033..5d3c47260b 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -144,11 +144,13 @@ public class GroovyDocToolTest extends GroovyTestCase {
assertNotNull("Expected a page for the value-tag class", doc);
assertTrue("Expected {@value #MAX} to render as 42 in:\n" + doc,
doc.contains("Max allowed: 42"));
- // GREETING's source form is "hello" (quoted). Angle-bracket encoding
- // doesn't affect the quotes — we expect to see " or the literal "hello"
- // depending on encoding. At minimum, 'hello' should appear next to 'Greeting:'.
assertTrue("Expected {@value #GREETING} to render with 'hello' in:\n" + doc,
doc.contains("Greeting: \"hello\""));
+ // Folded via ExpressionUtils.transformInlineConstants:
+ assertTrue("Expected {@value #SUM} to fold 40+2 to 42 in:\n" + doc,
+ doc.contains("Sum: 42"));
+ assertTrue("Expected {@value #COMBINED} to fold string concat to \"hello\" in:\n" + doc,
+ doc.contains("Combined: \"hello\""));
}
// GROOVY-8025: annotations whose members are closure expressions must
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithValueTag.groovy b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithValueTag.groovy
index 1ff003a831..a365527ae3 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithValueTag.groovy
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/testfiles/ClassWithValueTag.groovy
@@ -20,13 +20,18 @@ package org.codehaus.groovy.tools.groovydoc.testfiles
/**
* GROOVY-6016: demonstrates the {@code {@value}} inline tag referencing
- * constants. The class doc below uses {@value #MAX} and {@value #GREETING}
- * which should be substituted with the constants' source-form values.
+ * constants. Substitutions should happen for bare literals, folded
+ * constant expressions, string concatenations, and references to other
+ * static-final fields (via {@code ExpressionUtils.transformInlineConstants}).
*
* Max allowed: {@value #MAX}
* Greeting: {@value #GREETING}
+ * Sum: {@value #SUM}
+ * Combined: {@value #COMBINED}
*/
class ClassWithValueTag {
public static final int MAX = 42
public static final String GREETING = "hello"
+ public static final int SUM = 40 + 2
+ public static final String COMBINED = "hel" + "lo"
}
(groovy) 02/34: GROOVY-11682 — module attribute on
Posted by pa...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 56415b246b905a551f2e8bec504e5231550cee07
Author: Paul King <pa...@asert.com.au>
AuthorDate: Mon Apr 20 07:25:57 2026 +1000
GROOVY-11682 — module attribute on <link>
---
.../groovy/tools/groovydoc/LinkArgument.java | 39 ++++++++++++++++++----
.../groovy/tools/groovydoc/GroovyDocToolTest.java | 37 ++++++++++++++++++++
2 files changed, 70 insertions(+), 6 deletions(-)
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/LinkArgument.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/LinkArgument.java
index 3c62bc3b16..42f8f0b5ec 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/LinkArgument.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/LinkArgument.java
@@ -19,12 +19,15 @@
package org.codehaus.groovy.tools.groovydoc;
/**
- * Represents a link pair (href, packages).
- * The packages are comma separated.
+ * Represents a link pair (href, packages) with optional JPMS module.
+ * The packages are comma separated. When a module is specified, the
+ * module name is inserted between the base href and the package path,
+ * matching the JPMS-era Javadoc layout (e.g. {@code .../api/java.base/java/lang/Object.html}).
*/
public class LinkArgument {
private String href = "";
private String packages = "";
+ private String module = "";
/**
* Get the packages attribute.
@@ -45,12 +48,16 @@ public class LinkArgument {
}
/**
- * Get the href attribute.
+ * Get the href attribute, with the module name appended when set.
+ * For pre-JPMS external docs, returns the raw href; for JPMS-aware
+ * external docs (e.g. JDK 9+), returns {@code href + module + "/"}.
*
- * @return the href attribute.
+ * @return the effective base URL for this link
*/
public String getHref() {
- return href;
+ if (module == null || module.isEmpty()) return href;
+ String base = href.endsWith("/") ? href : href + "/";
+ return base + module + "/";
}
/**
@@ -62,4 +69,24 @@ public class LinkArgument {
href = hr;
}
-}
\ No newline at end of file
+ /**
+ * Get the module attribute.
+ *
+ * @return the module attribute, or an empty string if not set
+ */
+ public String getModule() {
+ return module;
+ }
+
+ /**
+ * Set the module attribute. When set, the module name is inserted
+ * between the base href and the package path, yielding JPMS-era
+ * Javadoc URLs such as {@code .../api/java.base/java/lang/Object.html}.
+ *
+ * @param module the JPMS module name (e.g. {@code java.base})
+ */
+ public void setModule(String module) {
+ this.module = module;
+ }
+
+}
diff --git a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
index 6e9b3b0ba2..64f8db2cfe 100644
--- a/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
+++ b/subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocToolTest.java
@@ -94,6 +94,43 @@ public class GroovyDocToolTest extends GroovyTestCase {
);
}
+ // GROOVY-11682
+ public void testLinkArgumentModuleComposesJpmsStyleUrl() {
+ LinkArgument link = new LinkArgument();
+ link.setHref("https://docs.oracle.com/en/java/javase/17/docs/api/");
+ assertEquals("https://docs.oracle.com/en/java/javase/17/docs/api/", link.getHref());
+
+ link.setModule("java.base");
+ assertEquals("https://docs.oracle.com/en/java/javase/17/docs/api/java.base/", link.getHref());
+
+ LinkArgument noSlash = new LinkArgument();
+ noSlash.setHref("https://example.org/api");
+ noSlash.setModule("java.sql");
+ assertEquals("https://example.org/api/java.sql/", noSlash.getHref());
+ }
+
+ // GROOVY-11682
+ public void testLinkWithModuleProducesJpmsStyleUrlInRenderedDoc() throws Exception {
+ ArrayList<LinkArgument> links = new ArrayList<>();
+ LinkArgument link = new LinkArgument();
+ link.setHref("https://docs.oracle.com/en/java/javase/17/docs/api/");
+ link.setModule("java.base");
+ link.setPackages("java.,javax.");
+ links.add(link);
+
+ GroovyDocTool jpmsTool = makeHtmltool(links, null, new Properties());
+ String base = "org/codehaus/groovy/tools/groovydoc/testfiles";
+ jpmsTool.add(List.of(base + "/DocumentedClass.groovy"));
+
+ MockOutputTool output = new MockOutputTool();
+ jpmsTool.renderToOutput(output, MOCK_DIR);
+
+ String doc = output.getText(MOCK_DIR + "/" + base + "/DocumentedClass.html");
+ assertNotNull("Expected DocumentedClass.html in output", doc);
+ assertTrue("Expected JPMS-style module segment in URL, got:\n" + doc,
+ doc.contains("https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Object.html"));
+ }
+
// GROOVY-9057
public void testParseErrorIsTrackedInErrorCount() throws Exception {
assertEquals("Initial error count should be zero", 0, xmlToolForTests.getErrorCount());