You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by su...@apache.org on 2026/10/11 18:26:00 UTC
(groovy) branch GROOVY-12448 updated (1ce033ccd0 -> d7323793e7)
This is an automated email from the ASF dual-hosted git repository.
asf-gitbox-commits pushed a change to branch GROOVY-12448
in repository https://gitbox.apache.org/repos/asf/groovy.git
discard 1ce033ccd0 GROOVY-12448: Wire Groovy Console and groovysh to the in-process language engine
new d7323793e7 GROOVY-12448: Wire Groovy Console and groovysh to the in-process language engine
This update added new revisions after undoing existing revisions.
That is to say, some revisions that were in the old version of the
branch are not in the new version. This situation occurs
when a user --force pushes a change and generates a repository
containing something like this:
* -- * -- B -- O -- O -- O (1ce033ccd0)
\
N -- N -- N refs/heads/GROOVY-12448 (d7323793e7)
You should already have received notification emails for all of the O
revisions, and so the following emails describe only the N revisions
from the common base, B.
Any revisions marked "omit" are not gone; other references still
refer to them. Any revisions marked "discard" are gone forever.
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.../main/groovy/groovy/console/ui/Console.groovy | 2 +-
.../groovy/groovy/console/ui/ObjectBrowser.groovy | 8 +-
.../groovy/groovy/console/ui/ThemeManager.groovy | 2 +-
.../console/ui/text/SmartDocumentFilter.java | 244 ++++++++-------------
.../src/spec/doc/groovy-console.adoc | 3 +
.../console/ui/text/SmartDocumentFilterTest.groovy | 15 +-
subprojects/groovy-lsp/ARCHITECTURE.md | 8 +-
.../groovy/lsp/internal/util/GroovyKeywords.java | 33 +++
.../lsp/internal/util/GroovySourceTokens.java | 37 +++-
.../groovy-lsp/src/spec/doc/lsp-userguide.adoc | 1 +
.../lsp/internal/util/GroovyKeywordsTest.groovy | 14 ++
.../internal/util/GroovySourceTokensTest.groovy | 9 +
12 files changed, 202 insertions(+), 174 deletions(-)
(groovy) 01/01: GROOVY-12448: Wire Groovy Console and groovysh to the in-process language engine
Posted by su...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
asf-gitbox-commits pushed a commit to branch GROOVY-12448
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit d7323793e7519744c82c713ae3fd2e0c5251f0a9
Author: Daniel Sun <su...@apache.org>
AuthorDate: Sun Oct 11 23:31:52 2026 +0900
GROOVY-12448: Wire Groovy Console and groovysh to the in-process language engine
---
THREAT_MODEL.md | 3 +-
licenses/LICENSE-BINZIP | 2 +-
licenses/LICENSE-SDK | 2 +-
licenses/lsp4j-BINZIP.txt | 2 +-
notices/NOTICE-BINZIP | 2 +-
notices/NOTICE-SDK | 2 +-
notices/lsp4j-BINZIP.txt | 2 +-
subprojects/groovy-console/build.gradle | 1 +
.../main/groovy/groovy/console/ui/Console.groovy | 22 +-
.../groovy/groovy/console/ui/ObjectBrowser.groovy | 8 +-
.../groovy/groovy/console/ui/ThemeManager.groovy | 2 +-
.../console/ui/language/ConsoleLanguageHost.groovy | 397 +++++++++++++++++++++
.../groovy/groovy/console/ui/language/package.html | 27 ++
.../console/ui/text/SmartDocumentFilter.java | 244 +++++--------
.../src/spec/doc/groovy-console.adoc | 9 +
.../ui/language/ConsoleLanguageHostTest.groovy | 268 ++++++++++++++
.../console/ui/text/SmartDocumentFilterTest.groovy | 15 +-
subprojects/groovy-groovysh/ARCHITECTURE.md | 18 +
subprojects/groovy-groovysh/build.gradle | 1 +
.../groovy/org/apache/groovy/groovysh/Main.groovy | 20 ++
.../language/GroovyshLanguageSession.groovy | 299 ++++++++++++++++
.../groovy/groovysh/language/package-info.groovy | 25 ++
.../groovy-groovysh/src/spec/doc/groovysh.adoc | 9 +
.../language/GroovyshLanguageSessionTest.groovy | 321 +++++++++++++++++
subprojects/groovy-lsp/AGENTS.md | 4 +-
subprojects/groovy-lsp/ARCHITECTURE.md | 32 +-
.../groovy/lsp/internal/LanguageServerContext.java | 62 +++-
.../lsp/internal/compile/CompilerSettings.java | 17 +-
.../lsp/internal/compile/GroovyCompiler.java | 15 +-
.../lsp/internal/engine/GroovyLanguageEngine.java | 314 +++++++++++++++-
.../groovy/lsp/internal/util/GroovyKeywords.java | 33 ++
.../lsp/internal/util/GroovySourceTokens.java | 37 +-
.../groovy-lsp/src/spec/doc/lsp-userguide.adoc | 15 +-
.../engine/GroovyLanguageEngineBufferTest.groovy | 74 ++++
.../internal/feature/LanguageQualityTest.groovy | 5 +
.../lsp/internal/util/GroovyKeywordsTest.groovy | 14 +
.../internal/util/GroovySourceTokensTest.groovy | 9 +
37 files changed, 2122 insertions(+), 210 deletions(-)
diff --git a/THREAT_MODEL.md b/THREAT_MODEL.md
index 0f26ad77f1..6f3878447e 100644
--- a/THREAT_MODEL.md
+++ b/THREAT_MODEL.md
@@ -636,7 +636,8 @@ If you embed or script with Groovy, **you** own these:
11. **Ship only the modules you use.** `org.apache.groovy:groovy` is the
core runtime and compiler. `groovy-all` is an aggregate that also brings
in the interactive and developer tooling — `groovy-groovysh`,
- `groovy-console`, `groovy-swing`, `groovy-servlet`, `groovy-jmx`,
+ `groovy-console` (and their `groovy-lsp` runtime dependency),
+ `groovy-swing`, `groovy-servlet`, `groovy-jmx`,
`groovy-groovydoc`, `groovy-docgenerator` — and both Grape engines;
a server-side application rarely needs any of them. This is not only
about what an attacker can reach. A module changes behavior by being
diff --git a/licenses/LICENSE-BINZIP b/licenses/LICENSE-BINZIP
index f23e78c49c..1d54648ec6 100644
--- a/licenses/LICENSE-BINZIP
+++ b/licenses/LICENSE-BINZIP
@@ -308,7 +308,7 @@ Eclipse LSP4J License
This product bundles Eclipse LSP4J (`org.eclipse.lsp4j:org.eclipse.lsp4j`)
and Eclipse LSP4J JSON-RPC (`org.eclipse.lsp4j:org.eclipse.lsp4j.jsonrpc`)
-as binary dependencies of the optional `groovy-lsp` module.
+as binary dependencies of `groovy-lsp`, which Groovy Console and groovysh require.
Those artifacts are licensed under the Eclipse Public License 2.0.
See licenses/lsp4j-license.txt for the full license text.
diff --git a/licenses/LICENSE-SDK b/licenses/LICENSE-SDK
index c7cf037cb3..fd3ad899bd 100644
--- a/licenses/LICENSE-SDK
+++ b/licenses/LICENSE-SDK
@@ -308,7 +308,7 @@ Eclipse LSP4J License
This product bundles Eclipse LSP4J (`org.eclipse.lsp4j:org.eclipse.lsp4j`)
and Eclipse LSP4J JSON-RPC (`org.eclipse.lsp4j:org.eclipse.lsp4j.jsonrpc`)
-as binary dependencies of the optional `groovy-lsp` module.
+as binary dependencies of `groovy-lsp`, which Groovy Console and groovysh require.
Those artifacts are licensed under the Eclipse Public License 2.0.
See licenses/lsp4j-license.txt for the full license text.
diff --git a/licenses/lsp4j-BINZIP.txt b/licenses/lsp4j-BINZIP.txt
index 56cc889a94..7c328d9eb0 100644
--- a/licenses/lsp4j-BINZIP.txt
+++ b/licenses/lsp4j-BINZIP.txt
@@ -2,7 +2,7 @@ Eclipse LSP4J License
This product bundles Eclipse LSP4J (`org.eclipse.lsp4j:org.eclipse.lsp4j`)
and Eclipse LSP4J JSON-RPC (`org.eclipse.lsp4j:org.eclipse.lsp4j.jsonrpc`)
-as binary dependencies of the optional `groovy-lsp` module.
+as binary dependencies of `groovy-lsp`, which Groovy Console and groovysh require.
Those artifacts are licensed under the Eclipse Public License 2.0.
See licenses/lsp4j-license.txt for the full license text.
diff --git a/notices/NOTICE-BINZIP b/notices/NOTICE-BINZIP
index 1b037b97e6..2e4caab6b4 100644
--- a/notices/NOTICE-BINZIP
+++ b/notices/NOTICE-BINZIP
@@ -43,7 +43,7 @@ which are available under the terms of the Eclipse Public License v2.0
Eclipse LSP4J
This product bundles Eclipse LSP4J and Eclipse LSP4J JSON-RPC
-(org.eclipse.lsp4j) as binary dependencies of the optional groovy-lsp module.
+(org.eclipse.lsp4j) as binary dependencies of groovy-lsp, which Groovy Console and groovysh require.
Those artifacts are licensed under the Eclipse Public License 2.0.
See licenses/lsp4j-license.txt.
diff --git a/notices/NOTICE-SDK b/notices/NOTICE-SDK
index fce2cdf6ec..e7ad63ccc5 100644
--- a/notices/NOTICE-SDK
+++ b/notices/NOTICE-SDK
@@ -43,7 +43,7 @@ which are available under the terms of the Eclipse Public License v2.0
Eclipse LSP4J
This product bundles Eclipse LSP4J and Eclipse LSP4J JSON-RPC
-(org.eclipse.lsp4j) as binary dependencies of the optional groovy-lsp module.
+(org.eclipse.lsp4j) as binary dependencies of groovy-lsp, which Groovy Console and groovysh require.
Those artifacts are licensed under the Eclipse Public License 2.0.
See licenses/lsp4j-license.txt.
diff --git a/notices/lsp4j-BINZIP.txt b/notices/lsp4j-BINZIP.txt
index ebe16b2a60..83d0f9f909 100644
--- a/notices/lsp4j-BINZIP.txt
+++ b/notices/lsp4j-BINZIP.txt
@@ -1,6 +1,6 @@
Eclipse LSP4J
This product bundles Eclipse LSP4J and Eclipse LSP4J JSON-RPC
-(org.eclipse.lsp4j) as binary dependencies of the optional groovy-lsp module.
+(org.eclipse.lsp4j) as binary dependencies of groovy-lsp, which Groovy Console and groovysh require.
Those artifacts are licensed under the Eclipse Public License 2.0.
See licenses/lsp4j-license.txt.
diff --git a/subprojects/groovy-console/build.gradle b/subprojects/groovy-console/build.gradle
index 695c3f2e3c..83f62a5e39 100644
--- a/subprojects/groovy-console/build.gradle
+++ b/subprojects/groovy-console/build.gradle
@@ -32,6 +32,7 @@ dependencies {
runtimeOnly "org.abego.treelayout:org.abego.treelayout.core:${versions.treelayout}"
testImplementation projects.groovyTest
testImplementation testFixtures(projects.groovySwing)
+ implementation projects.groovyLsp
groovyCompilerClasspath(project(":")) {
capabilities {
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/console/ui/Console.groovy b/subprojects/groovy-console/src/main/groovy/groovy/console/ui/Console.groovy
index 2c4d7afcaf..59e05e09db 100644
--- a/subprojects/groovy-console/src/main/groovy/groovy/console/ui/Console.groovy
+++ b/subprojects/groovy-console/src/main/groovy/groovy/console/ui/Console.groovy
@@ -25,6 +25,7 @@ import com.github.javaparser.ast.CompilationUnit
import com.github.javaparser.ast.body.TypeDeclaration
import groovy.cli.internal.CliBuilderInternal
import groovy.cli.internal.OptionAccessor
+import groovy.console.ui.language.ConsoleLanguageHost
import groovy.console.ui.text.FindReplaceUtility
import groovy.console.ui.text.GroovyFilter
import groovy.console.ui.text.SmartDocumentFilter
@@ -294,6 +295,8 @@ class Console implements CaretListener, HyperlinkListener, ComponentListener, Fo
CompilerConfiguration config
/** Shell used to compile and run scripts. */
GroovyShell shell
+ /** In-process language host for diagnostics and completions. */
+ private ConsoleLanguageHost languageHost
/** Counter used for generated script names. */
int scriptNameCounter = 0
/** Interceptor that captures stdout. */
@@ -507,6 +510,7 @@ class Console implements CaretListener, HyperlinkListener, ComponentListener, Fo
config.addCompilationCustomizers(new ASTTransformationCustomizer(ThreadInterrupt))
}
shell = new GroovyShell(parent, binding, config)
+ languageHost?.bind(shell.classLoader, config)
}
/** Default Swing delegates used to build the console frame and menu bar. */
@@ -579,9 +583,19 @@ class Console implements CaretListener, HyperlinkListener, ComponentListener, Fo
}
installInterceptor()
updateTitle()
+ installLanguageHost()
swing.doLater inputArea.&requestFocus
}
+ /**
+ * Attaches the in-process language host to the editor. groovy-console
+ * depends on groovy-lsp, so the host is always constructed.
+ */
+ @CompileStatic
+ private void installLanguageHost() {
+ languageHost = ConsoleLanguageHost.attach(inputArea, shell.classLoader, config)
+ }
+
/**
* Make the console frames capable of native fullscreen
* for Mac OS X Lion and beyond.
@@ -954,7 +968,7 @@ class Console implements CaretListener, HyperlinkListener, ComponentListener, Fo
}
}
- // update SmartDocumentFilter styles (ANTLR token-based highlighting)
+ // update SmartDocumentFilter styles (groovy-lsp lexer highlighting)
SmartDocumentFilter.updateStyles()
// force re-parse to apply new colors to existing text — suppress
@@ -1067,6 +1081,8 @@ class Console implements CaretListener, HyperlinkListener, ComponentListener, Fo
if (askToInterruptScript()) {
def exit = askToSaveFile()
if (exit) {
+ languageHost?.close()
+ languageHost = null
if (frame instanceof Window) {
frame.hide()
frame.dispose()
@@ -1114,6 +1130,7 @@ class Console implements CaretListener, HyperlinkListener, ComponentListener, Fo
nativeFullScreenForMac(swing.consoleFrame)
swing.consoleFrame.pack()
swing.consoleFrame.show()
+ consoleController.installLanguageHost()
swing.doLater swing.inputArea.&requestFocus
}
@@ -1145,6 +1162,7 @@ class Console implements CaretListener, HyperlinkListener, ComponentListener, Fo
listeners.each { inputArea.document.addDocumentListener(it) }
setDirty(false)
inputArea.caretPosition = 0
+ languageHost?.refresh()
}
} finally {
swing.edt { inputArea.editable = true }
@@ -1713,6 +1731,7 @@ class Console implements CaretListener, HyperlinkListener, ComponentListener, Fo
fc.selectedFiles?.each { file ->
shell.getClassLoader().addURL(file.toURL())
}
+ languageHost?.bind(shell.classLoader, config)
}
}
@@ -1725,6 +1744,7 @@ class Console implements CaretListener, HyperlinkListener, ComponentListener, Fo
currentClasspathDir = fc.currentDirectory
Preferences.userNodeForPackage(Console).put('currentClasspathDir', currentClasspathDir.path)
shell.getClassLoader().addURL(fc.selectedFile.toURL())
+ languageHost?.bind(shell.classLoader, config)
}
}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/console/ui/ObjectBrowser.groovy b/subprojects/groovy-console/src/main/groovy/groovy/console/ui/ObjectBrowser.groovy
index 59c710781d..2b677c76cb 100644
--- a/subprojects/groovy-console/src/main/groovy/groovy/console/ui/ObjectBrowser.groovy
+++ b/subprojects/groovy-console/src/main/groovy/groovy/console/ui/ObjectBrowser.groovy
@@ -22,6 +22,7 @@ import groovy.beans.Bindable
import groovy.inspect.Inspector
import groovy.swing.SwingBuilder
import groovy.swing.table.TableSorter
+import org.apache.groovy.lsp.internal.util.GroovyKeywords
import javax.swing.ToolTipManager
import javax.swing.WindowConstants
@@ -32,7 +33,6 @@ import java.awt.datatransfer.StringSelection
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
-import static groovy.console.ui.text.SmartDocumentFilter.HIGHLIGHTED_TOKEN_TYPE_LIST
import static groovy.inspect.Inspector.MEMBER_DECLARER_IDX
import static groovy.inspect.Inspector.MEMBER_EXCEPTIONS_IDX
import static groovy.inspect.Inspector.MEMBER_MODIFIER_IDX
@@ -42,7 +42,7 @@ import static groovy.inspect.Inspector.MEMBER_PARAMS_IDX
import static groovy.inspect.Inspector.MEMBER_TYPE_IDX
import static groovy.inspect.Inspector.MEMBER_VALUE_IDX
import static javax.swing.ListSelectionModel.SINGLE_SELECTION
-import static org.apache.groovy.parser.antlr4.GroovyLexer.VOCABULARY
+
/**
* A little GUI to show some of the Inspector capabilities.
* Starting this script opens the ObjectBrowser on "some String".
@@ -179,9 +179,7 @@ class ObjectBrowser {
return p
}.join('\n').trim()
- for (def ln in (HIGHLIGHTED_TOKEN_TYPE_LIST.collect {
- VOCABULARY.getLiteralName(it)?.replace("'", '')
- }.grep { it } + ['module', 'true', 'false'])) {
+ for (def ln in GroovyKeywords.KEYWORDS) {
content = content.replaceAll(/\b(${ln})\b/, '<b>$1</b>')
}
content = content.replace('\n', '<br/>').replace(',', '<b>,</b>').replace(':', '<b>:</b>')
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/console/ui/ThemeManager.groovy b/subprojects/groovy-console/src/main/groovy/groovy/console/ui/ThemeManager.groovy
index bad4210dbb..35ae630f5a 100644
--- a/subprojects/groovy-console/src/main/groovy/groovy/console/ui/ThemeManager.groovy
+++ b/subprojects/groovy-console/src/main/groovy/groovy/console/ui/ThemeManager.groovy
@@ -177,7 +177,7 @@ class ThemeManager {
/**
* Returns the attributes for a single theme style key as a plain map
* (foreground/background Colors plus bold/italic/underline Booleans).
- * Consumed by SmartDocumentFilter so ANTLR-token-driven highlighting
+ * Consumed by SmartDocumentFilter so lexer-driven highlighting
* picks up the same theme values as the regex-based GroovyFilter styles.
* Returns an empty map if the theme doesn't define the key.
*/
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/console/ui/language/ConsoleLanguageHost.groovy b/subprojects/groovy-console/src/main/groovy/groovy/console/ui/language/ConsoleLanguageHost.groovy
new file mode 100644
index 0000000000..8decab6467
--- /dev/null
+++ b/subprojects/groovy-console/src/main/groovy/groovy/console/ui/language/ConsoleLanguageHost.groovy
@@ -0,0 +1,397 @@
+/*
+ * 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 groovy.console.ui.language
+
+import groovy.transform.CompileStatic
+import groovy.transform.Internal
+import groovy.transform.PackageScope
+import org.apache.groovy.lsp.internal.engine.GroovyLanguageEngine
+import org.codehaus.groovy.control.CompilerConfiguration
+
+import javax.swing.JMenuItem
+import javax.swing.JPopupMenu
+import javax.swing.JTextPane
+import javax.swing.SwingUtilities
+import javax.swing.event.DocumentEvent
+import javax.swing.event.DocumentListener
+import javax.swing.text.BadLocationException
+import javax.swing.text.DefaultHighlighter
+import java.awt.Color
+import java.awt.Point
+import java.awt.event.InputEvent
+import java.awt.event.KeyAdapter
+import java.awt.event.KeyEvent
+import java.util.concurrent.Executors
+import java.util.concurrent.RejectedExecutionException
+import java.util.concurrent.ScheduledExecutorService
+import java.util.concurrent.ScheduledFuture
+import java.util.concurrent.TimeUnit
+import java.util.concurrent.atomic.AtomicInteger
+
+/**
+ * In-process language host for Groovy Console. Compiles the unsaved editor
+ * buffer through {@link GroovyLanguageEngine} (no class generation) and
+ * paints diagnostic highlights; Ctrl+Space offers completions.
+ * Implementation detail of Groovy Console, not an embedding API.
+ */
+@CompileStatic
+@Internal
+final class ConsoleLanguageHost implements AutoCloseable {
+
+ /** This editor's unsaved buffer. The engine does not assign the name. */
+ @PackageScope
+ static final URI BUFFER_URI = URI.create('groovy-buffer:console')
+
+ private static final int DEBOUNCE_MS = 150
+ private static final int MAX_COMPLETIONS = 20
+
+ private final GroovyLanguageEngine engine
+ private final JTextPane input
+ private final DocumentListener documentListener
+ private final KeyAdapter completionKeys
+ private final DefaultHighlighter.DefaultHighlightPainter errorPainter =
+ new DefaultHighlighter.DefaultHighlightPainter(new Color(255, 180, 180))
+ private final List<Object> highlights = []
+ private final AtomicInteger generation = new AtomicInteger()
+ private final ScheduledExecutorService debounce = Executors.newSingleThreadScheduledExecutor { Runnable r ->
+ Thread thread = new Thread(r, 'groovy-console-language')
+ thread.daemon = true
+ thread
+ }
+ private volatile boolean closed
+ private volatile ClassLoader parent
+ private volatile CompilerConfiguration configuration
+ private ScheduledFuture<?> pending
+
+ private ConsoleLanguageHost(JTextPane input, ClassLoader loader, CompilerConfiguration configuration) {
+ this.input = input
+ this.parent = loader
+ this.configuration = configuration
+ this.engine = new GroovyLanguageEngine()
+ engine.setParentLoader(loader)
+ engine.setHostConfiguration(configuration)
+ engine.openBuffer(BUFFER_URI, 'groovy', textOf(input))
+ this.documentListener = new DocumentListener() {
+ @Override
+ void insertUpdate(DocumentEvent e) { schedule() }
+
+ @Override
+ void removeUpdate(DocumentEvent e) { schedule() }
+
+ @Override
+ void changedUpdate(DocumentEvent e) { }
+ }
+ this.completionKeys = new KeyAdapter() {
+ @Override
+ void keyPressed(KeyEvent e) {
+ if (e.keyCode == KeyEvent.VK_SPACE && (e.modifiersEx & InputEvent.CTRL_DOWN_MASK) != 0) {
+ showCompletions()
+ e.consume()
+ }
+ }
+ }
+ if (input?.document != null) {
+ input.document.addDocumentListener(documentListener)
+ input.addKeyListener(completionKeys)
+ }
+ }
+
+ /**
+ * @param input editor pane
+ * @param loader GroovyShell class loader
+ * @return a host bound to {@code input}
+ */
+ static ConsoleLanguageHost attach(JTextPane input, ClassLoader loader) {
+ attach(input, loader, null)
+ }
+
+ /**
+ * @param input editor pane
+ * @param loader GroovyShell class loader
+ * @param configuration console compiler configuration
+ * @return a host bound to {@code input}
+ */
+ static ConsoleLanguageHost attach(JTextPane input, ClassLoader loader, CompilerConfiguration configuration) {
+ new ConsoleLanguageHost(input, loader, configuration)
+ }
+
+ /**
+ * Compiles {@code text} immediately and returns diagnostics.
+ *
+ * @param text buffer text
+ * @return hits in 0-based UTF-16 coordinates
+ */
+ @PackageScope
+ List<GroovyLanguageEngine.Hit> compileAndDiagnostics(String text) {
+ bindEngine()
+ engine.diagnostics(BUFFER_URI, text)
+ }
+
+ /**
+ * Completions at a 0-based UTF-16 position.
+ *
+ * @param text buffer text
+ * @param line 0-based line
+ * @param character 0-based character
+ * @return candidates
+ */
+ @PackageScope
+ List<GroovyLanguageEngine.Candidate> complete(String text, int line, int character) {
+ bindEngine()
+ engine.complete(BUFFER_URI, text, line, character)
+ }
+
+ /**
+ * Hover markdown at a 0-based UTF-16 position.
+ *
+ * @param text buffer text
+ * @param line 0-based line
+ * @param character 0-based character
+ * @return markdown
+ */
+ @PackageScope
+ String describe(String text, int line, int character) {
+ bindEngine()
+ engine.describe(BUFFER_URI, text, line, character)
+ }
+
+ /**
+ * Compiles the current editor text and paints diagnostic highlights
+ * on the calling thread. Production callers run this on the EDT
+ * after a file load; typing uses {@link #schedule()} instead.
+ */
+ void refresh() {
+ if (closed) {
+ return
+ }
+ generation.incrementAndGet()
+ pending?.cancel(false)
+ String text = textOf(input)
+ paint(text, compileAndDiagnostics(text))
+ }
+
+ /**
+ * Offers completions at the caret. Used by Ctrl+Space and tests.
+ */
+ @PackageScope
+ void completeAtCaret() {
+ showCompletions()
+ }
+
+ /**
+ * Records the GroovyShell class loader after classpath or shell changes
+ * and schedules a background recompile so highlights catch up without a
+ * keystroke.
+ *
+ * @param loader GroovyShell class loader
+ */
+ void setParentLoader(ClassLoader loader) {
+ bind(loader, configuration)
+ }
+
+ /**
+ * Records the console compiler configuration (imports, AST customizers)
+ * so query compiles match {@code GroovyShell}.
+ *
+ * @param configuration console configuration, or {@code null}
+ */
+ void setCompilerConfiguration(CompilerConfiguration configuration) {
+ bind(parent, configuration)
+ }
+
+ /**
+ * @param loader GroovyShell class loader
+ * @param configuration console compiler configuration
+ */
+ void bind(ClassLoader loader, CompilerConfiguration configuration) {
+ if (closed) {
+ return
+ }
+ this.parent = loader
+ this.configuration = configuration
+ bindEngine()
+ schedule()
+ }
+
+ private void bindEngine() {
+ engine.setParentLoader(parent)
+ engine.setHostConfiguration(configuration)
+ }
+
+ @Override
+ void close() {
+ if (closed) {
+ return
+ }
+ closed = true
+ generation.incrementAndGet()
+ pending?.cancel(false)
+ if (input != null) {
+ if (input.document != null) {
+ input.document.removeDocumentListener(documentListener)
+ }
+ input.removeKeyListener(completionKeys)
+ }
+ debounce.shutdownNow()
+ try {
+ debounce.awaitTermination(1, TimeUnit.SECONDS)
+ } catch (InterruptedException ignored) {
+ Thread.currentThread().interrupt()
+ }
+ engine.close()
+ }
+
+ private void schedule() {
+ if (closed || debounce.isShutdown()) {
+ return
+ }
+ int gen = generation.incrementAndGet()
+ String text = textOf(input)
+ pending?.cancel(false)
+ try {
+ pending = debounce.schedule({
+ try {
+ if (closed || gen != generation.get()) {
+ return
+ }
+ def hits = compileAndDiagnostics(text)
+ if (closed || gen != generation.get()) {
+ return
+ }
+ SwingUtilities.invokeLater {
+ if (!closed && gen == generation.get()) {
+ paint(text, hits)
+ }
+ }
+ } catch (RuntimeException ignored) {
+ }
+ }, DEBOUNCE_MS, TimeUnit.MILLISECONDS)
+ } catch (RejectedExecutionException ignored) {
+ }
+ }
+
+ private void paint(String text, List<GroovyLanguageEngine.Hit> hits) {
+ def highlighter = input?.highlighter
+ if (highlighter == null) {
+ return
+ }
+ highlights.each { highlighter.removeHighlight(it) }
+ highlights.clear()
+ hits?.each { hit ->
+ int[] span = GroovyLanguageEngine.spanOf(text, hit)
+ try {
+ highlights << highlighter.addHighlight(span[0], span[1], errorPainter)
+ } catch (BadLocationException ignored) {
+ }
+ }
+ if (hits) {
+ input.toolTipText = hits.take(3).collect { it.message() }.join('\n')
+ } else {
+ input.toolTipText = null
+ }
+ }
+
+ private void showCompletions() {
+ if (closed || input == null || debounce.isShutdown()) {
+ return
+ }
+ String text = textOf(input)
+ int caret = Math.min(Math.max(input.caretPosition, 0), text.length())
+ int[] position = GroovyLanguageEngine.positionOf(text, caret)
+ int gen = generation.get()
+ pending?.cancel(false)
+ try {
+ pending = debounce.schedule({
+ try {
+ if (closed || gen != generation.get()) {
+ return
+ }
+ def items = complete(text, position[0], position[1])
+ SwingUtilities.invokeLater {
+ if (!closed && gen == generation.get()) {
+ showMenu(items)
+ }
+ }
+ } catch (RuntimeException ignored) {
+ }
+ }, 0, TimeUnit.MILLISECONDS)
+ } catch (RejectedExecutionException ignored) {
+ }
+ }
+
+ private void showMenu(List<GroovyLanguageEngine.Candidate> items) {
+ if (input == null || !items) {
+ return
+ }
+ try {
+ def menu = new JPopupMenu()
+ items.take(MAX_COMPLETIONS).each { item ->
+ def entry = new JMenuItem(item.label() ?: item.insertText())
+ entry.addActionListener {
+ insertAtCaret(input, GroovyLanguageEngine.flattenSnippet(item.insertText() ?: item.label()))
+ }
+ menu.add(entry)
+ }
+ Point point = input.caret.magicCaretPosition ?: new Point(0, 0)
+ menu.show(input, (int) point.x, (int) point.y + 16)
+ } catch (RuntimeException ignored) {
+ }
+ }
+
+ @PackageScope
+ static void insertAtCaret(JTextPane pane, String insert) {
+ if (pane?.document == null) {
+ return
+ }
+ String text = textOf(pane)
+ String piece = insert ?: ''
+ if (piece.isEmpty()) {
+ return
+ }
+ int caret = Math.min(Math.max(pane.caretPosition, 0), text.length())
+ int start = caret
+ while (start > 0 && Character.isJavaIdentifierPart(text.charAt(start - 1))) {
+ start--
+ }
+ int end = caret
+ while (end < text.length() && Character.isJavaIdentifierPart(text.charAt(end))) {
+ end++
+ }
+ String prefix = text.substring(start, caret)
+ try {
+ if (prefix && piece.startsWith(prefix)) {
+ if (end > caret) {
+ pane.document.remove(caret, end - caret)
+ }
+ pane.document.insertString(caret, piece.substring(prefix.length()), null)
+ } else if (start < end) {
+ pane.document.remove(start, end - start)
+ pane.document.insertString(start, piece, null)
+ } else {
+ pane.document.insertString(caret, piece, null)
+ }
+ } catch (BadLocationException ignored) {
+ }
+ }
+
+ private static String textOf(JTextPane pane) {
+ pane == null ? '' : (pane.text ?: '')
+ }
+
+}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/console/ui/language/package.html b/subprojects/groovy-console/src/main/groovy/groovy/console/ui/language/package.html
new file mode 100644
index 0000000000..f4d203f7bf
--- /dev/null
+++ b/subprojects/groovy-console/src/main/groovy/groovy/console/ui/language/package.html
@@ -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.
+-->
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <title>package groovy.console.ui.language.*</title>
+ </head>
+ <body>
+ <p>In-process groovy-lsp host for the Swing console. Implementation detail of Groovy Console; not an embedding API.</p>
+ </body>
+</html>
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/console/ui/text/SmartDocumentFilter.java b/subprojects/groovy-console/src/main/groovy/groovy/console/ui/text/SmartDocumentFilter.java
index 9d639328ad..cfdd852a11 100644
--- a/subprojects/groovy-console/src/main/groovy/groovy/console/ui/text/SmartDocumentFilter.java
+++ b/subprojects/groovy-console/src/main/groovy/groovy/console/ui/text/SmartDocumentFilter.java
@@ -18,15 +18,11 @@
*/
package groovy.console.ui.text;
+import groovy.console.ui.ThemeManager;
import groovy.lang.Tuple2;
-import org.antlr.v4.runtime.CharStream;
-import org.antlr.v4.runtime.CharStreams;
-import org.antlr.v4.runtime.CommonTokenStream;
-import org.antlr.v4.runtime.ConsoleErrorListener;
-import org.antlr.v4.runtime.LexerNoViableAltException;
import org.antlr.v4.runtime.Token;
-import org.apache.groovy.parser.antlr4.GroovyLangLexer;
-import org.apache.groovy.parser.antlr4.GroovySyntaxError;
+import org.apache.groovy.lsp.internal.util.GroovyKeywords;
+import org.apache.groovy.lsp.internal.util.GroovySourceTokens;
import org.apache.groovy.parser.antlr4.util.PositionConfigureUtils;
import org.apache.groovy.parser.antlr4.util.StringUtils;
import org.apache.groovy.util.ReversedList;
@@ -39,111 +35,45 @@ import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import java.awt.Color;
-import java.io.IOException;
-import java.io.StringReader;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
-import groovy.console.ui.ThemeManager;
-
-import static org.apache.groovy.parser.antlr4.GroovyLexer.ABSTRACT;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.AS;
import static org.apache.groovy.parser.antlr4.GroovyLexer.AT;
+import static org.apache.groovy.parser.antlr4.GroovyLexer.COMMA;
import static org.apache.groovy.parser.antlr4.GroovyLexer.CapitalizedIdentifier;
import static org.apache.groovy.parser.antlr4.GroovyLexer.DOT;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.Identifier;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.ASSERT;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.ASYNC;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.AWAIT;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.BREAK;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.BooleanLiteral;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.BuiltInPrimitiveType;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.CASE;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.CATCH;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.CLASS;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.COMMA;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.CONST;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.CONTINUE;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.DEF;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.DEFAULT;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.DEFER;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.DO;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.ELSE;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.ENUM;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.EOF;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.EXTENDS;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.FINAL;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.FINALLY;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.FOR;
import static org.apache.groovy.parser.antlr4.GroovyLexer.FloatingPointLiteral;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.GOTO;
import static org.apache.groovy.parser.antlr4.GroovyLexer.GStringBegin;
import static org.apache.groovy.parser.antlr4.GroovyLexer.GStringEnd;
import static org.apache.groovy.parser.antlr4.GroovyLexer.GStringPart;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.IF;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.IMPLEMENTS;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.IMPORT;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.IN;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.INSTANCEOF;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.INTERFACE;
+import static org.apache.groovy.parser.antlr4.GroovyLexer.Identifier;
import static org.apache.groovy.parser.antlr4.GroovyLexer.IntegerLiteral;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.NATIVE;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.NEW;
import static org.apache.groovy.parser.antlr4.GroovyLexer.NL;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.NON_SEALED;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.NOT_IN;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.NOT_INSTANCEOF;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.NullLiteral;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.PACKAGE;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.PERMITS;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.PRIVATE;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.PROTECTED;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.PUBLIC;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.RECORD;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.RETURN;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.SEALED;
import static org.apache.groovy.parser.antlr4.GroovyLexer.SEMI;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.STATIC;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.STRICTFP;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.SUPER;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.SWITCH;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.SYNCHRONIZED;
import static org.apache.groovy.parser.antlr4.GroovyLexer.StringLiteral;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.THIS;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.THREADSAFE;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.THROW;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.THROWS;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.TRAIT;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.TRANSIENT;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.TRY;
import static org.apache.groovy.parser.antlr4.GroovyLexer.UNEXPECTED_CHAR;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.VAL;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.VAR;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.VOID;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.VOLATILE;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.WHILE;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.YIELD;
-
/**
- * The document filter based on Parrot's lexer is for highlighting the content of text editor
+ * Swing document filter that styles the editor from
+ * {@link GroovySourceTokens#tokenizeLenient(String)}. The walk is the
+ * same lexer groovy-lsp uses for lexical semantic tokens, with
+ * {@code errorIgnored} so incomplete input still highlights. Semantic
+ * tokens from a compiled snapshot stay on the language host (too slow
+ * for the EDT). Brace matching reads {@link #getLatestTokenList()}.
*
* @since 3.0.0
*/
public class SmartDocumentFilter extends DocumentFilter {
/**
- * Token types rendered with the reserved-word style.
+ * Token types rendered with the reserved-word style. Vocabulary-derived
+ * via {@link GroovyKeywords#KEYWORD_TOKEN_TYPES}.
*/
- public static final List<Integer> HIGHLIGHTED_TOKEN_TYPE_LIST =
- Arrays.asList(AS, ASYNC, AWAIT, DEF, DEFER, IN, TRAIT, THREADSAFE,
- VAL, VAR, BuiltInPrimitiveType, ABSTRACT, ASSERT, BREAK, CASE, CATCH, CLASS, CONST, CONTINUE, DEFAULT, DO,
- ELSE, ENUM, EXTENDS, FINAL, FINALLY, FOR, IF, GOTO, IMPLEMENTS, IMPORT, INSTANCEOF, INTERFACE,
- NATIVE, NEW, NON_SEALED, NOT_IN, NOT_INSTANCEOF, PACKAGE, PERMITS, PRIVATE, PROTECTED, PUBLIC,
- RECORD, RETURN, SEALED, STATIC, STRICTFP, SUPER, SWITCH, SYNCHRONIZED,
- THIS, THROW, THROWS, TRANSIENT, TRY, VOID, VOLATILE, WHILE, YIELD, NullLiteral, BooleanLiteral);
+ public static final List<Integer> HIGHLIGHTED_TOKEN_TYPE_LIST = GroovyKeywords.KEYWORD_TOKEN_TYPES;
+ /** Synthetic style key for slashy strings (not a lexer token type). */
+ private static final int SLASHY_STRING_STYLE = -2;
private static final String MONOSPACED = "Monospaced";
private final DefaultStyledDocument styledDocument;
private final StyleContext styleContext;
@@ -170,9 +100,7 @@ public class SmartDocumentFilter extends DocumentFilter {
@Override
public void insertString(DocumentFilter.FilterBypass fb, int offset,
String text, AttributeSet attrs) throws BadLocationException {
- // remove problem meta characters returns
text = replaceMetaCharacters(text);
-
fb.insertString(offset, text, attrs);
parseDocument();
}
@@ -183,7 +111,6 @@ public class SmartDocumentFilter extends DocumentFilter {
@Override
public void remove(DocumentFilter.FilterBypass fb, int offset, int length)
throws BadLocationException {
-
fb.remove(offset, length);
parseDocument();
}
@@ -195,49 +122,21 @@ public class SmartDocumentFilter extends DocumentFilter {
public void replace(DocumentFilter.FilterBypass fb, int offset,
int length, String text, AttributeSet attrs)
throws BadLocationException {
-
- // text might be null and indicates no replacement text
- if (text == null) text = "";
-
- // remove problem meta characters returns
+ if (text == null) {
+ text = "";
+ }
text = replaceMetaCharacters(text);
-
fb.replace(offset, length, text, attrs);
-
parseDocument();
}
private String replaceMetaCharacters(String string) {
- // just in case remove carriage returns
- string = string.replace("\r\n", "\n");
- return string;
+ return string.replace("\r\n", "\n");
}
private void parseDocument() throws BadLocationException {
- GroovyLangLexer lexer;
- try {
- lexer = createLexer(styledDocument.getText(0, styledDocument.getLength()));
- } catch (IOException e) {
- e.printStackTrace();
- this.latest = false;
- return;
- }
-
- CommonTokenStream tokenStream = new CommonTokenStream(lexer);
-
- try {
- tokenStream.fill();
- } catch (LexerNoViableAltException | GroovySyntaxError e) {
- // ignore
- this.latest = false;
- return;
- } catch (Exception e) {
- e.printStackTrace();
- this.latest = false;
- return;
- }
-
- List<Token> tokenList = tokenStream.getTokens();
+ String text = styledDocument.getText(0, styledDocument.getLength());
+ List<Token> tokenList = GroovySourceTokens.tokenizeLenient(text);
List<Token> tokenListToRender;
try {
tokenListToRender = findTokensToRender(tokenList);
@@ -248,8 +147,7 @@ public class SmartDocumentFilter extends DocumentFilter {
boolean inAnnotation = false;
for (Token token : tokenListToRender) {
int tokenType = token.getType();
-
- if (EOF == tokenType) {
+ if (Token.EOF == tokenType) {
continue;
}
@@ -257,22 +155,18 @@ public class SmartDocumentFilter extends DocumentFilter {
int tokenStopIndex = token.getStopIndex();
int tokenLength = tokenStopIndex - tokenStartIndex + 1;
- // color annotation names (identifier/dot tokens after @) with annotation style
- // handles @ToString, @groovy.transform.CompileStatic, etc.
boolean isAnnotationPart = inAnnotation
&& (tokenType == Identifier || tokenType == CapitalizedIdentifier || tokenType == DOT);
if (tokenType == AT) {
inAnnotation = true;
} else if (isAnnotationPart) {
- // stay in annotation for dotted names
inAnnotation = (tokenType == DOT);
} else {
inAnnotation = false;
}
- styledDocument.setCharacterAttributes(tokenStartIndex,
- tokenLength,
- isAnnotationPart ? findStyleByTokenType(AT) : findStyleByTokenType(tokenType),
+ styledDocument.setCharacterAttributes(tokenStartIndex, tokenLength,
+ isAnnotationPart ? findStyleByTokenType(AT) : findStyle(token),
true);
if (GStringBegin == tokenType || GStringPart == tokenType) {
@@ -288,13 +182,45 @@ public class SmartDocumentFilter extends DocumentFilter {
this.latest = true;
}
+ private Style findStyle(Token token) {
+ int tokenType = token.getType();
+ if (tokenType == StringLiteral) {
+ return findStyleByTokenType(stringStyleType(token.getText()));
+ }
+ if (tokenType == NL && isComment(token.getText())) {
+ return findStyleByTokenType(NL);
+ }
+ return findStyleByTokenType(tokenType);
+ }
+
+ /**
+ * Distinguishes slashy / dollar-slashy / double-quoted / single-quoted
+ * literals so they pick up the matching theme keys. The lexer emits
+ * every flavour as {@code StringLiteral}.
+ */
+ private static int stringStyleType(String text) {
+ if (text != null && (text.startsWith("$/") || text.startsWith("/"))) {
+ return SLASHY_STRING_STYLE;
+ }
+ if (text != null && text.startsWith("\"")) {
+ return GStringBegin;
+ }
+ return StringLiteral;
+ }
+
+ private static boolean isComment(String text) {
+ return text != null && (text.startsWith("//") || text.startsWith("/*"));
+ }
+
private List<Token> findTokensToRender(List<Token> tokenList) {
final Tuple2<Integer, Integer> renderRange = getRenderRange();
if (null != renderRange) {
long startLine = lineNumber(renderRange.getV1());
long stopLine = lineNumber(renderRange.getV2());
- if (startLine < 0 || stopLine < 0) return tokenList; // should never happen
+ if (startLine < 0 || stopLine < 0) {
+ return tokenList;
+ }
return tokenList.stream()
.filter(e -> e.getLine() >= startLine && PositionConfigureUtils.endPosition(e).getV1() <= stopLine)
@@ -357,7 +283,7 @@ public class SmartDocumentFilter extends DocumentFilter {
return tmpTokenList.subList(startTokenIndex, stopTokenIndex);
}
- return tokenList; // should never reach here. If unexpected error occurred, it's better to render all tokens
+ return tokenList;
}
/**
@@ -366,7 +292,9 @@ public class SmartDocumentFilter extends DocumentFilter {
private long lineNumber(int position) {
long result = -1;
- if (position < 0) return result;
+ if (position < 0) {
+ return result;
+ }
try {
String text = this.styledDocument.getText(0, position + 1);
@@ -386,7 +314,6 @@ public class SmartDocumentFilter extends DocumentFilter {
private Style findStyleByTokenType(int tokenType) {
Style style = styleContext.getStyle(String.valueOf(tokenType));
-
return null == style ? defaultStyle : style;
}
@@ -394,23 +321,13 @@ public class SmartDocumentFilter extends DocumentFilter {
return styleContext.addStyle(String.valueOf(tokenType), defaultStyle);
}
- private GroovyLangLexer createLexer(String text) throws IOException {
- CharStream charStream = CharStreams.fromReader(new StringReader(text));
- GroovyLangLexer lexer = new GroovyLangLexer(charStream);
-
- lexer.setErrorIgnored(true);
- lexer.removeErrorListener(ConsoleErrorListener.INSTANCE);
-
- return lexer;
- }
-
private void initStyles() {
- // create styles (ensures they exist in the StyleContext)
createDefaultStyleByTokenType(NL);
for (int t : Arrays.asList(GStringBegin, GStringPart, GStringEnd)) {
createDefaultStyleByTokenType(t);
}
createDefaultStyleByTokenType(StringLiteral);
+ createDefaultStyleByTokenType(SLASHY_STRING_STYLE);
for (int t : Arrays.asList(IntegerLiteral, FloatingPointLiteral)) {
createDefaultStyleByTokenType(t);
}
@@ -422,8 +339,9 @@ public class SmartDocumentFilter extends DocumentFilter {
}
createDefaultStyleByTokenType(AT);
createDefaultStyleByTokenType(UNEXPECTED_CHAR);
+ createDefaultStyleByTokenType(Identifier);
+ createDefaultStyleByTokenType(CapitalizedIdentifier);
- // apply theme colors
updateStyles();
}
@@ -446,7 +364,7 @@ public class SmartDocumentFilter extends DocumentFilter {
/**
* Updates all SmartDocumentFilter styles with current theme colors.
* Attribute values are sourced from ThemeManager so custom .theme files
- * feed both this (ANTLR-token-driven) path and the regex-driven GroovyFilter
+ * feed both this lexer-driven path and the regex-driven GroovyFilter
* path from one place. Called at init time and on theme switch.
*
* @since 6.0.0
@@ -460,6 +378,7 @@ public class SmartDocumentFilter extends DocumentFilter {
applyThemeStyle(sc.getStyle(String.valueOf(t)), "quotes");
}
applyThemeStyle(sc.getStyle(String.valueOf(StringLiteral)), "single_quotes");
+ applyThemeStyle(sc.getStyle(String.valueOf(SLASHY_STRING_STYLE)), "slashy_quotes");
for (int t : Arrays.asList(IntegerLiteral, FloatingPointLiteral)) {
applyThemeStyle(sc.getStyle(String.valueOf(t)), "digit");
@@ -469,14 +388,14 @@ public class SmartDocumentFilter extends DocumentFilter {
applyThemeStyle(sc.getStyle(String.valueOf(t)), "reserved_word");
}
- // commas and semicolons reuse the "operation" theme key — closest semantic match
for (int t : Arrays.asList(COMMA, SEMI)) {
applyThemeStyle(sc.getStyle(String.valueOf(t)), "operation");
}
applyThemeStyle(sc.getStyle(String.valueOf(AT)), "annotation");
+ applyThemeStyle(sc.getStyle(String.valueOf(Identifier)), "ident");
+ applyThemeStyle(sc.getStyle(String.valueOf(CapitalizedIdentifier)), "ident");
- // unexpected-char is a lexer-error indicator, not semantic syntax — stay hardcoded
Style unexpectedChar = sc.getStyle(String.valueOf(UNEXPECTED_CHAR));
if (unexpectedChar != null) {
StyleConstants.setForeground(unexpectedChar,
@@ -486,8 +405,9 @@ public class SmartDocumentFilter extends DocumentFilter {
@SuppressWarnings("rawtypes")
private static void applyThemeStyle(Style style, String themeKey) {
- if (style == null) return;
- // clear managed attributes so the previous theme's values don't linger
+ if (style == null) {
+ return;
+ }
style.removeAttribute(StyleConstants.Foreground);
style.removeAttribute(StyleConstants.Background);
style.removeAttribute(StyleConstants.Bold);
@@ -495,12 +415,22 @@ public class SmartDocumentFilter extends DocumentFilter {
style.removeAttribute(StyleConstants.Underline);
Map attrs = ThemeManager.getStyleAttrs(themeKey);
Object fg = attrs.get("foreground");
- if (fg instanceof Color) StyleConstants.setForeground(style, (Color) fg);
+ if (fg instanceof Color) {
+ StyleConstants.setForeground(style, (Color) fg);
+ }
Object bg = attrs.get("background");
- if (bg instanceof Color) StyleConstants.setBackground(style, (Color) bg);
- if (Boolean.TRUE.equals(attrs.get("bold"))) StyleConstants.setBold(style, true);
- if (Boolean.TRUE.equals(attrs.get("italic"))) StyleConstants.setItalic(style, true);
- if (Boolean.TRUE.equals(attrs.get("underline"))) StyleConstants.setUnderline(style, true);
+ if (bg instanceof Color) {
+ StyleConstants.setBackground(style, (Color) bg);
+ }
+ if (Boolean.TRUE.equals(attrs.get("bold"))) {
+ StyleConstants.setBold(style, true);
+ }
+ if (Boolean.TRUE.equals(attrs.get("italic"))) {
+ StyleConstants.setItalic(style, true);
+ }
+ if (Boolean.TRUE.equals(attrs.get("underline"))) {
+ StyleConstants.setUnderline(style, true);
+ }
}
private volatile boolean latest = false;
diff --git a/subprojects/groovy-console/src/spec/doc/groovy-console.adoc b/subprojects/groovy-console/src/spec/doc/groovy-console.adoc
index e8b19811b8..a8cdec44ad 100644
--- a/subprojects/groovy-console/src/spec/doc/groovy-console.adoc
+++ b/subprojects/groovy-console/src/spec/doc/groovy-console.adoc
@@ -161,12 +161,21 @@ follows your operating system's dark mode setting.
image:{reldir_console}/assets/img/gconsole-dark-theme.png[Dark Theme]
* Code is auto indented when you hit return
+* The editor highlights Groovy source from the same lexer groovy-lsp uses
+(`GroovySourceTokens`). A regex highlighter remains available from
+`View -> Smart Highlighter`.
* You can drag'n'drop a Groovy script over the text area to open a file
* You can modify the classpath with which the script in the console is
being run by adding a new JAR or a directory to the classpath from the
`Script` menu
* Error hyperlinking from the output area when a compilation error is
expected or when an exception is thrown
+* The editor compiles the unsaved buffer in the background and highlights
+compiler diagnostics. `Ctrl+Space` offers compiler-backed completions.
+Adding jars or directories to the classpath is picked up on the next
+background compile. The editor shares the console `CompilerConfiguration`
+(imports and AST customizers) with that compile. Scripts still run through
+`GroovyShell`. The language host answers questions about the buffer.
[[GroovyConsole-EmbeddingtheConsole]]
== Embedding the Console
diff --git a/subprojects/groovy-console/src/test/groovy/groovy/console/ui/language/ConsoleLanguageHostTest.groovy b/subprojects/groovy-console/src/test/groovy/groovy/console/ui/language/ConsoleLanguageHostTest.groovy
new file mode 100644
index 0000000000..75e5f67dd7
--- /dev/null
+++ b/subprojects/groovy-console/src/test/groovy/groovy/console/ui/language/ConsoleLanguageHostTest.groovy
@@ -0,0 +1,268 @@
+/*
+ * 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 groovy.console.ui.language
+
+import org.apache.groovy.lsp.internal.engine.GroovyLanguageEngine
+import org.codehaus.groovy.control.CompilerConfiguration
+import org.codehaus.groovy.control.customizers.ImportCustomizer
+import org.junit.jupiter.api.Test
+
+import javax.swing.JTextPane
+import javax.swing.SwingUtilities
+import java.awt.event.InputEvent
+import java.awt.event.KeyEvent
+
+final class ConsoleLanguageHostTest {
+
+ @Test
+ void diagnosticsHoverAndCompletionUseTheEngine() {
+ def pane = new JTextPane()
+ def host = ConsoleLanguageHost.attach(pane, ConsoleLanguageHostTest.classLoader)
+ try {
+ def broken = 'class Broken { def x = }\n'
+ def hits = host.compileAndDiagnostics(broken)
+ assert hits.any { it.message() }
+
+ def src = '''\
+ class Sample {
+ def ping() { ping() }
+ }
+ '''.stripIndent()
+ def hover = host.describe(src, 0, 6)
+ assert hover.contains('Sample')
+ def items = host.complete(src, 1, 16)
+ assert items.any { it.label() == 'ping' || it.insertText()?.contains('ping') }
+ host.setParentLoader(ConsoleLanguageHostTest.classLoader)
+ host.refresh()
+ } finally {
+ host.close()
+ }
+ }
+
+ @Test
+ void hostCompilerConfigurationImportsAreVisible() {
+ def configuration = new CompilerConfiguration()
+ def imports = new ImportCustomizer()
+ imports.addImports('java.util.concurrent.ConcurrentHashMap')
+ configuration.addCompilationCustomizers(imports)
+ def pane = new JTextPane()
+ def host = ConsoleLanguageHost.attach(pane, ConsoleLanguageHostTest.classLoader, configuration)
+ try {
+ def hits = host.compileAndDiagnostics('ConcurrentHashMap m\n')
+ assert !hits.any { (it.message() ?: '').contains('ConcurrentHashMap') }
+ host.setCompilerConfiguration(null)
+ def without = host.compileAndDiagnostics('ConcurrentHashMap m\n')
+ assert without.any { (it.message() ?: '').contains('ConcurrentHashMap') }
+ host.setCompilerConfiguration(configuration)
+ def again = host.compileAndDiagnostics('ConcurrentHashMap m\n')
+ assert !again.any { (it.message() ?: '').contains('ConcurrentHashMap') }
+ } finally {
+ host.close()
+ }
+ }
+
+ @Test
+ void offsetOfPositionOfAndPlainInsertCoverEdges() {
+ assert GroovyLanguageEngine.offsetOf(null, 0, 0) == 0
+ assert GroovyLanguageEngine.offsetOf('', 0, 0) == 0
+ assert GroovyLanguageEngine.offsetOf('ab\ncd', 0, 0) == 0
+ assert GroovyLanguageEngine.offsetOf('ab\ncd', 1, 1) == 4
+ assert GroovyLanguageEngine.offsetOf('ab\ncd', 9, 0) == 5
+ assert GroovyLanguageEngine.offsetOf('ab', -1, 99) == 2
+ assert GroovyLanguageEngine.offsetOf('ab\ncd', 1, -3) == 3
+ assert GroovyLanguageEngine.offsetOf('ab\ncd', 0, 99) == 2
+ assert GroovyLanguageEngine.positionOf(null, 0) == [0, 0] as int[]
+ assert GroovyLanguageEngine.positionOf('', 1) == [0, 0] as int[]
+ assert GroovyLanguageEngine.positionOf('ab\ncd', 0) == [0, 0] as int[]
+ assert GroovyLanguageEngine.positionOf('ab\ncd', 4) == [1, 1] as int[]
+ assert GroovyLanguageEngine.positionOf('ab\ncd', 99) == [1, 2] as int[]
+ assert GroovyLanguageEngine.positionOf('ab\r\ncd', 4) == [1, 0] as int[]
+ assert GroovyLanguageEngine.positionOf('ab\rcd', 3) == [1, 0] as int[]
+ assert GroovyLanguageEngine.offsetOf('ab\r\ncd', 1, 0) == 4
+ assert GroovyLanguageEngine.offsetOf('ab\rcd', 1, 0) == 3
+ assert GroovyLanguageEngine.flattenSnippet(null) == ''
+ assert GroovyLanguageEngine.flattenSnippet('') == ''
+ assert GroovyLanguageEngine.flattenSnippet('length') == 'length'
+ assert GroovyLanguageEngine.flattenSnippet('class ${1:Name} {\n $0\n}\n') == 'class Name {\n \n}\n'
+ assert GroovyLanguageEngine.flattenSnippet('$0') == ''
+ assert GroovyLanguageEngine.flattenSnippet('${1:foo}$2') == 'foo'
+ assert ConsoleLanguageHost.BUFFER_URI.toString() == 'groovy-buffer:console'
+ }
+
+ @Test
+ void highlightSpanClampsInvertedAndZeroWidth() {
+ assert GroovyLanguageEngine.spanOf('ab\ncd', 0, 2, 0, 0) == [2, 3] as int[]
+ assert GroovyLanguageEngine.spanOf('x', 0, 0, 0, 0) == [0, 1] as int[]
+ assert GroovyLanguageEngine.spanOf('', 0, 0, 0, 0) == [0, 0] as int[]
+ assert GroovyLanguageEngine.spanOf(null, 0, 0, 0, 0) == [0, 0] as int[]
+ assert GroovyLanguageEngine.spanOf('ab', 0, 0, 0, 2) == [0, 2] as int[]
+ assert GroovyLanguageEngine.spanOf('abc', 0, 3, 0, 3) == [2, 3] as int[]
+ assert GroovyLanguageEngine.spanOf('abc', 9, 0, 9, 0) == [2, 3] as int[]
+ def hit = new GroovyLanguageEngine.Hit(URI.create('groovy-buffer:t'), 0, 2, 0, 0, 'x', 'Error')
+ assert GroovyLanguageEngine.spanOf('ab\ncd', hit) == [2, 3] as int[]
+ assert GroovyLanguageEngine.spanOf('ab', null) == [0, 0] as int[]
+ }
+
+ @Test
+ void refreshPaintsAndClearsTooltipsSynchronously() {
+ def pane = new JTextPane()
+ pane.text = 'class Broken { def x = }\n'
+ def host = ConsoleLanguageHost.attach(pane, ConsoleLanguageHostTest.classLoader)
+ try {
+ host.refresh()
+ assert pane.highlighter.highlights.length > 0
+ assert pane.toolTipText
+ pane.caretPosition = pane.text.indexOf('Broken')
+ host.completeAtCaret()
+ pane.dispatchEvent(new KeyEvent(pane, KeyEvent.KEY_PRESSED, System.currentTimeMillis(),
+ InputEvent.CTRL_DOWN_MASK, KeyEvent.VK_SPACE, ' ' as char))
+ pane.text = 'class Ok {}\n'
+ host.refresh()
+ assert pane.highlighter.highlights.length == 0
+ assert pane.toolTipText == null
+ } finally {
+ host.close()
+ }
+ }
+
+ @Test
+ void closeThenEditDoesNotThrowAndCloseIsIdempotent() {
+ def pane = new JTextPane()
+ pane.text = 'class Broken { def x = }\n'
+ def host = ConsoleLanguageHost.attach(pane, ConsoleLanguageHostTest.classLoader)
+ try {
+ pane.text = 'class Ok {}\n'
+ host.completeAtCaret()
+ } finally {
+ host.close()
+ }
+ host.close()
+ pane.text = 'class Later {}\n'
+ pane.dispatchEvent(new KeyEvent(pane, KeyEvent.KEY_PRESSED, System.currentTimeMillis(),
+ InputEvent.CTRL_DOWN_MASK, KeyEvent.VK_SPACE, ' ' as char))
+ def detached = ConsoleLanguageHost.attach(null, null)
+ try {
+ detached.refresh()
+ detached.completeAtCaret()
+ detached.setParentLoader(null)
+ assert detached.compileAndDiagnostics(null) != null
+ } finally {
+ detached.close()
+ }
+ }
+
+ @Test
+ void attachWithEmptyPaneAndCloseIsIdempotentEnough() {
+ def host = ConsoleLanguageHost.attach(new JTextPane(), null)
+ try {
+ assert host.compileAndDiagnostics('') != null
+ assert host.complete('', 0, 0) != null
+ assert host.describe('class A {}', 0, 6) != null
+ } finally {
+ host.close()
+ }
+ }
+
+ @Test
+ void completeAtCaretFlushesMenuPath() {
+ def pane = new JTextPane()
+ pane.text = '''\
+ class Sample {
+ def ping() { 1 }
+ }
+ new Sample().
+ '''.stripIndent()
+ pane.caretPosition = pane.text.length()
+ def host = ConsoleLanguageHost.attach(pane, ConsoleLanguageHostTest.classLoader)
+ try {
+ host.completeAtCaret()
+ long deadline = System.currentTimeMillis() + 500
+ while (System.currentTimeMillis() < deadline) {
+ SwingUtilities.invokeAndWait {}
+ Thread.sleep(25)
+ }
+ } finally {
+ host.close()
+ }
+ }
+
+ @Test
+ void compilePicksUpInPlaceLoaderUrlChanges() {
+ def loader = new GroovyClassLoader()
+ def host = ConsoleLanguageHost.attach(new JTextPane(), loader)
+ try {
+ host.compileAndDiagnostics('1')
+ loader.addURL(URI.create('file:/tmp/extra-language-host.jar').toURL())
+ assert host.compileAndDiagnostics('1') != null
+ } finally {
+ host.close()
+ }
+ }
+
+ @Test
+ void setParentLoaderThenRefreshSeesNewClasses() {
+ def loader = new GroovyClassLoader()
+ loader.parseClass('class CpHit {}')
+ def host = ConsoleLanguageHost.attach(new JTextPane(), ConsoleLanguageHostTest.classLoader)
+ try {
+ def before = host.compileAndDiagnostics('CpHit x\n')
+ host.setParentLoader(loader)
+ def after = host.compileAndDiagnostics('CpHit x\n')
+ assert before.any { (it.message() ?: '').contains('CpHit') }
+ assert !after.any { (it.message() ?: '').contains('CpHit') }
+ } finally {
+ host.close()
+ }
+ }
+
+ @Test
+ void insertAtCaretReplacesPrefixOrInserts() {
+ def pane = new JTextPane()
+ pane.text = 'na'
+ pane.caretPosition = 2
+ ConsoleLanguageHost.insertAtCaret(pane, 'name')
+ assert pane.text == 'name'
+ pane.text = 'xy'
+ pane.caretPosition = 2
+ ConsoleLanguageHost.insertAtCaret(pane, 'name')
+ assert pane.text == 'name'
+ pane.text = ''
+ pane.caretPosition = 0
+ ConsoleLanguageHost.insertAtCaret(pane, 'x')
+ assert pane.text == 'x'
+ ConsoleLanguageHost.insertAtCaret(null, 'x')
+ ConsoleLanguageHost.insertAtCaret(pane, '')
+ pane.text = 'foo.'
+ pane.caretPosition = 4
+ ConsoleLanguageHost.insertAtCaret(pane, 'bar')
+ assert pane.text == 'foo.bar'
+ pane.text = 'name'
+ pane.caretPosition = 1
+ ConsoleLanguageHost.insertAtCaret(pane, 'name')
+ assert pane.text == 'name'
+ pane.text = 'ab\ncd'
+ pane.caretPosition = pane.text.length()
+ def host = ConsoleLanguageHost.attach(pane, ConsoleLanguageHostTest.classLoader)
+ try {
+ host.completeAtCaret()
+ } finally {
+ host.close()
+ }
+ }
+}
diff --git a/subprojects/groovy-console/src/test/groovy/groovy/console/ui/text/SmartDocumentFilterTest.groovy b/subprojects/groovy-console/src/test/groovy/groovy/console/ui/text/SmartDocumentFilterTest.groovy
index ec18a13695..c88a2a3156 100644
--- a/subprojects/groovy-console/src/test/groovy/groovy/console/ui/text/SmartDocumentFilterTest.groovy
+++ b/subprojects/groovy-console/src/test/groovy/groovy/console/ui/text/SmartDocumentFilterTest.groovy
@@ -18,6 +18,7 @@
*/
package groovy.console.ui.text
+import org.apache.groovy.parser.antlr4.GroovyLexer
import org.junit.jupiter.api.Test
import javax.swing.text.DefaultStyledDocument
@@ -153,8 +154,20 @@ class SmartDocumentFilterTest {
def list = SmartDocumentFilter.HIGHLIGHTED_TOKEN_TYPE_LIST
assert list != null
assert !list.isEmpty()
- // list should contain token type integers (all > 0)
assert list.every { it > 0 }
+ assert list.contains(GroovyLexer.DEF)
+ }
+
+ @Test
+ void testIncompleteInputStillTokenizes() {
+ def doc = new DefaultStyledDocument()
+ def filter = new SmartDocumentFilter(doc)
+ doc.setDocumentFilter(filter)
+
+ doc.insertString(0, 'def x =', null)
+
+ assert filter.isLatest()
+ assert filter.latestTokenList.any { it.text == 'def' }
}
@Test
diff --git a/subprojects/groovy-groovysh/ARCHITECTURE.md b/subprojects/groovy-groovysh/ARCHITECTURE.md
index be512c493c..e1f25f082c 100644
--- a/subprojects/groovy-groovysh/ARCHITECTURE.md
+++ b/subprojects/groovy-groovysh/ARCHITECTURE.md
@@ -238,6 +238,24 @@ the public seams rather than copying `Main`:
- `ExtraConsoleCommands` — public top-level class for `/clear`,
`/pwd`, `/cd`, the POSIX-style commands, and `/!`.
`Main.ExtraConsoleCommands` is a deprecated subclass.
+- `groovy-lsp`: groovysh takes an `implementation` dependency.
+ `GroovyshLanguageSession` is an `@Internal` adapter constructed
+ from `Main`. It implements JLine `Completer`, wraps
+ `scriptDescription`, and composes `GroovyEngine.getBuffer()` plus
+ binding type declarations plus the current line onto its own
+ buffer URI (`groovy-buffer:repl`). The engine does not assign
+ that name. Result records are JDK types; the adapter does not
+ import LSP4J. `SYNTAX` tail-tips return compiler diagnostics and
+ do not evaluate; `METHOD` signatures use the full line so an
+ unclosed `(` is visible. `/grab` is noticed because the engine
+ compile fingerprint includes the parent loader's URLs.
+ `GroovyEngine.getCompilerConfiguration()` is forwarded so embedder
+ import and AST customizers match evaluation. Binding
+ names already in the REPL buffer come from the compiled AST
+ (`GroovyLanguageEngine.declaredNames`). Queries use the engine's
+ text overloads. Snippet insert text is flattened with
+ `flattenSnippetLine`. Tests for it live at the engine layer (no
+ terminal).
Where a `GroovyshOptions` setting has an equivalent on JLine's
`ShellBuilder`, it uses the same name and parameter type on purpose.
diff --git a/subprojects/groovy-groovysh/build.gradle b/subprojects/groovy-groovysh/build.gradle
index f0b9134065..64263cf227 100644
--- a/subprojects/groovy-groovysh/build.gradle
+++ b/subprojects/groovy-groovysh/build.gradle
@@ -33,6 +33,7 @@ dependencies {
implementation projects.groovyXml
implementation projects.groovyJson
implementation projects.groovyNio
+ implementation projects.groovyLsp
testImplementation projects.groovyTest
testImplementation projects.groovyCsv // for /slurp .csv default coverage
testImplementation projects.groovyMarkdown // for /slurp .md default coverage
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Main.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Main.groovy
index cc2836b06e..3fb037f158 100644
--- a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Main.groovy
+++ b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/Main.groovy
@@ -27,6 +27,7 @@ import org.apache.groovy.groovysh.jline.GroovyConsoleEngine
import org.apache.groovy.groovysh.jline.GroovyEngine
import org.apache.groovy.groovysh.jline.GroovyPrinter
import org.apache.groovy.groovysh.jline.GroovySystemRegistry
+import org.apache.groovy.groovysh.language.GroovyshLanguageSession
import org.apache.groovy.groovysh.util.DocFinder
import org.apache.groovy.lang.annotation.Incubating
import org.codehaus.groovy.tools.shell.util.MessageSource
@@ -267,6 +268,7 @@ class Main {
return 0
}
String evaluate = options.e ?: null
+ GroovyshLanguageSession languageSession = null
try {
DefaultParser parser = new DefaultParser(
@@ -376,6 +378,7 @@ class Main {
invoke '/alias', '/h', '/help'
setConsoleOption "ignoreUnknownPipes", true
}
+ languageSession = installLanguageSession(scriptEngine, systemRegistry)
def highlighter = new SystemHighlighter(commandHighlighter, argsHighlighter, groovyHighlighter).tap {
if (!OSUtils.IS_WINDOWS) {
@@ -476,6 +479,8 @@ class Main {
} catch (Throwable t) {
t.printStackTrace()
return 1
+ } finally {
+ languageSession?.close()
}
return 0
}
@@ -492,6 +497,21 @@ class Main {
start(GroovyshOptions.builder().build(), args)
}
+ /**
+ * Attaches the in-process language session. groovysh depends on
+ * groovy-lsp, so the session is always constructed.
+ *
+ * @param scriptEngine REPL engine
+ * @param systemRegistry command registry
+ * @return the session
+ */
+ private static GroovyshLanguageSession installLanguageSession(GroovyEngine scriptEngine, GroovySystemRegistry systemRegistry) {
+ GroovyshLanguageSession session = new GroovyshLanguageSession(scriptEngine)
+ systemRegistry.addCompleter(session)
+ systemRegistry.setScriptDescription(session::scriptDescription)
+ return session
+ }
+
private static void emitResult(Printer printer, Object result, GroovyshOptions.ResultHandler handler) throws Exception {
if (handler != null) {
handler.handle(printer, result)
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/language/GroovyshLanguageSession.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/language/GroovyshLanguageSession.groovy
new file mode 100644
index 0000000000..14e5e1f5ba
--- /dev/null
+++ b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/language/GroovyshLanguageSession.groovy
@@ -0,0 +1,299 @@
+/*
+ * 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.apache.groovy.groovysh.language
+
+import groovy.transform.CompileStatic
+import groovy.transform.Internal
+import groovy.transform.PackageScope
+import org.apache.groovy.groovysh.jline.GroovyEngine
+import org.apache.groovy.lsp.internal.engine.GroovyLanguageEngine
+import org.jline.console.CmdDesc
+import org.jline.console.CmdLine
+import org.jline.reader.Candidate
+import org.jline.reader.Completer
+import org.jline.reader.LineReader
+import org.jline.reader.ParsedLine
+import org.jline.utils.AttributedString
+
+import java.lang.reflect.Modifier
+import java.util.regex.Pattern
+
+/**
+ * Compiler-backed session for groovysh. Does not import LSP4J. The adapter
+ * composes the REPL buffer, binding type declarations, and the current line;
+ * the engine compiles that synthetic script through semantic analysis.
+ * Implementation detail of groovysh, not an embedding API.
+ */
+@CompileStatic
+@Internal
+final class GroovyshLanguageSession implements AutoCloseable, Completer {
+
+ /** This session's unsaved buffer. The engine does not assign the name. */
+ @PackageScope
+ static final URI BUFFER_URI = URI.create('groovy-buffer:repl')
+
+ private static final Pattern SYSTEM_VAR = Pattern.compile('[A-Z]+[A-Z_]*')
+ private static final Pattern IDENTIFIER = Pattern.compile('[\\p{L}_$][\\p{L}\\p{N}_$]*')
+ private static final Set<String> SKIP = ['GROOVYSH_OPTIONS', 'GROOVY_OPTIONS', 'CONSOLE_OPTIONS',
+ 'ROOT', 'PWD', 'NANORC', '_args'] as Set
+
+ private final GroovyEngine groovy
+ private final GroovyLanguageEngine engine
+ private String namesPreamble
+ private Set<String> namesCache
+
+ GroovyshLanguageSession(GroovyEngine groovy) {
+ this.groovy = groovy
+ this.engine = new GroovyLanguageEngine()
+ bindEngine()
+ engine.openBuffer(BUFFER_URI, 'groovy', '')
+ }
+
+ /**
+ * Compiles the session buffer plus {@code line} and returns diagnostics.
+ *
+ * @param line current input
+ * @return hits
+ */
+ @PackageScope
+ List<GroovyLanguageEngine.Hit> diagnosticsFor(String line) {
+ bindEngine()
+ engine.diagnostics(BUFFER_URI, compose(line ?: ''))
+ }
+
+ /**
+ * Completions for the current line at end-of-buffer.
+ *
+ * @param line current input
+ * @return candidates
+ */
+ @PackageScope
+ List<GroovyLanguageEngine.Candidate> completeLine(String line) {
+ completeLine(line, -1)
+ }
+
+ /**
+ * Completions for {@code line} at {@code cursor} (0-based index into
+ * {@code line}). A negative cursor means end of the composed script.
+ *
+ * @param line current input
+ * @param cursor offset in {@code line}
+ * @return candidates
+ */
+ @PackageScope
+ List<GroovyLanguageEngine.Candidate> completeLine(String line, int cursor) {
+ bindEngine()
+ String current = line ?: ''
+ String script = compose(current)
+ int[] caret
+ if (cursor < 0 || cursor > current.length()) {
+ caret = GroovyLanguageEngine.positionOf(script, script.length())
+ } else {
+ int currentStart = script.length() - current.length()
+ caret = GroovyLanguageEngine.positionOf(script, currentStart + cursor)
+ }
+ engine.complete(BUFFER_URI, script, caret[0], caret[1])
+ }
+
+ /**
+ * Tail-tip description. {@code SYNTAX} reports compiler diagnostics and
+ * does not evaluate. {@code METHOD} asks for signatures on the full line
+ * (so an unclosed {@code (} is visible) and falls back to Inspector only
+ * when the compiler has none.
+ *
+ * @param line JLine command line
+ * @return description, or {@code null}
+ */
+ CmdDesc scriptDescription(CmdLine line) {
+ if (line != null && line.descriptionType == CmdLine.DescriptionType.SYNTAX) {
+ try {
+ def hits = diagnosticsFor(line.line ?: '')
+ if (hits) {
+ def desc = new CmdDesc()
+ desc.setMainDesc(hits.take(5).collect { new AttributedString(it.message() ?: '') })
+ return desc
+ }
+ } catch (Exception ignored) {
+ }
+ return null
+ }
+ try {
+ if (line != null && line.descriptionType == CmdLine.DescriptionType.METHOD) {
+ def set = signaturesFor(line.line ?: '')
+ if (set.signatures()) {
+ def desc = new CmdDesc()
+ desc.setMainDesc(set.signatures().collect { new AttributedString(it.label() ?: '') })
+ return desc
+ }
+ }
+ } catch (Exception ignored) {
+ }
+ try {
+ return groovy.scriptDescription(line)
+ } catch (Exception ignored) {
+ return null
+ }
+ }
+
+ @PackageScope
+ GroovyLanguageEngine.SignatureSet signaturesFor(String line) {
+ bindEngine()
+ String script = compose(line ?: '')
+ int[] caret = GroovyLanguageEngine.positionOf(script, script.length())
+ engine.signatures(BUFFER_URI, script, caret[0], caret[1])
+ }
+
+ @Override
+ void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
+ if (candidates == null || line == null) {
+ return
+ }
+ String raw = line.line() ?: ''
+ if (raw.startsWith('/')) {
+ return
+ }
+ try {
+ def items = completeLine(raw, line.cursor())
+ mapEngineCandidates(items, line, candidates)
+ } catch (RuntimeException ignored) {
+ }
+ }
+
+ @Override
+ void close() {
+ engine.close()
+ }
+
+ /**
+ * Synthetic script: remembered snippets, then binding declarations for
+ * names the buffer does not already introduce, then the current line.
+ *
+ * @param current current input
+ * @return script text
+ */
+ @PackageScope
+ String compose(String current) {
+ String preamble = groovy.buffer ?: ''
+ String decls = bindingDeclarations(namesIn(preamble))
+ def parts = []
+ if (preamble) {
+ parts << preamble
+ }
+ if (decls) {
+ parts << decls
+ }
+ parts << (current ?: '')
+ parts.join('\n')
+ }
+
+ private Set<String> namesIn(String preamble) {
+ if (!preamble) {
+ return [] as Set
+ }
+ if (preamble == namesPreamble) {
+ return namesCache
+ }
+ bindEngine()
+ namesCache = engine.declaredNames(BUFFER_URI, preamble)
+ namesPreamble = preamble
+ namesCache
+ }
+
+ private void bindEngine() {
+ engine.setParentLoader(groovy.classLoader)
+ engine.setHostConfiguration(groovy.compilerConfiguration)
+ }
+
+ private String bindingDeclarations(Set<String> already) {
+ Map variables
+ try {
+ def found = groovy.find(null)
+ if (!(found instanceof Map)) {
+ return ''
+ }
+ variables = new LinkedHashMap(found)
+ } catch (Exception ignored) {
+ return ''
+ }
+ def lines = []
+ variables.each { key, value ->
+ String name = String.valueOf(key)
+ if (SKIP.contains(name) || SYSTEM_VAR.matcher(name).matches() || value == null) {
+ return
+ }
+ if (!IDENTIFIER.matcher(name).matches() || already?.contains(name)) {
+ return
+ }
+ lines << "${typeLiteral(value)} ${name} = null"
+ }
+ lines.join('\n')
+ }
+
+ @PackageScope
+ static String typeLiteral(Object value) {
+ Class type = value.getClass()
+ if (type.isArray()) {
+ return type.canonicalName
+ }
+ if (type.isAnonymousClass() || type.isLocalClass() || type.isSynthetic()) {
+ return 'java.lang.Object'
+ }
+ if (!Modifier.isPublic(type.modifiers)) {
+ return 'java.lang.Object'
+ }
+ String canonical = type.canonicalName
+ canonical != null ? canonical : 'java.lang.Object'
+ }
+
+ /**
+ * Maps engine candidates onto JLine {@link Candidate} values using the
+ * current word as the replacement prefix.
+ */
+ @PackageScope
+ static void mapEngineCandidates(List<GroovyLanguageEngine.Candidate> items, ParsedLine line,
+ List<Candidate> candidates) {
+ if (items == null || line == null || candidates == null) {
+ return
+ }
+ String word = line.word() ?: ''
+ int cursor = Math.min(Math.max(line.wordCursor(), 0), word.length())
+ String buffer = word.substring(0, cursor)
+ int lastDelim = buffer.lastIndexOf('.')
+ String curBuf = lastDelim >= 0 ? buffer.substring(0, lastDelim + 1) : ''
+ for (GroovyLanguageEngine.Candidate item : items) {
+ if (item == null) {
+ continue
+ }
+ String insert = GroovyLanguageEngine.flattenSnippetLine(item.insertText() ?: item.label())
+ if (insert.isEmpty()) {
+ insert = item.label() ?: ''
+ }
+ if (insert.isEmpty()) {
+ continue
+ }
+ String value = insert.startsWith(curBuf) ? insert : curBuf + insert
+ String kind = item.kind()
+ if (kind == null || kind.isEmpty()) {
+ kind = 'other'
+ }
+ candidates.add(new Candidate(value, item.label() ?: insert, kind,
+ item.detail() ?: null, null, null, false))
+ }
+ }
+}
diff --git a/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/language/package-info.groovy b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/language/package-info.groovy
new file mode 100644
index 0000000000..984629ccc6
--- /dev/null
+++ b/subprojects/groovy-groovysh/src/main/groovy/org/apache/groovy/groovysh/language/package-info.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.
+ */
+
+/**
+ * Compiler-backed groovysh session. The adapter stays in this tree and talks
+ * to groovy-lsp through {@code GroovyLanguageEngine} JDK records, not LSP4J
+ * types. Implementation detail of groovysh, not an embedding API.
+ */
+package org.apache.groovy.groovysh.language;
diff --git a/subprojects/groovy-groovysh/src/spec/doc/groovysh.adoc b/subprojects/groovy-groovysh/src/spec/doc/groovysh.adoc
index 51085b77a0..966f764766 100644
--- a/subprojects/groovy-groovysh/src/spec/doc/groovysh.adoc
+++ b/subprojects/groovy-groovysh/src/spec/doc/groovysh.adoc
@@ -38,6 +38,15 @@ to https://github.com/jline/jline3[JLine3].
* ANSI colors (prompt, exception traces, etc).
* Simple, yet robust, command system with online help, user alias
support and more.
+* Tab completion and tail-tip descriptions also consult a compiler-backed
+session over the current buffer (imports, types, methods, and binding
+variables). `/grab` remains the way to add Maven artifacts; the next
+completion or tail-tip notices the loader change. Embedder
+`CompilerConfiguration` customizers (imports, AST transforms) apply to
+that session as well as to evaluation. Syntax tail-tips report
+compiler diagnostics and do not evaluate the line. Lines still evaluate
+through `GroovyEngine`. The language session answers questions about the
+buffer.
[[GroovyShell-Command-lineOptionsandArguments]]
=== Command-line Options and Arguments
diff --git a/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/language/GroovyshLanguageSessionTest.groovy b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/language/GroovyshLanguageSessionTest.groovy
new file mode 100644
index 0000000000..3908c97f95
--- /dev/null
+++ b/subprojects/groovy-groovysh/src/test/groovy/org/apache/groovy/groovysh/language/GroovyshLanguageSessionTest.groovy
@@ -0,0 +1,321 @@
+/*
+ * 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.apache.groovy.groovysh.language
+
+import org.apache.groovy.groovysh.jline.GroovyEngine
+import org.apache.groovy.lsp.internal.engine.GroovyLanguageEngine
+import org.codehaus.groovy.control.CompilerConfiguration
+import org.codehaus.groovy.control.customizers.ImportCustomizer
+import org.jline.console.CmdDesc
+import org.jline.console.CmdLine
+import org.jline.reader.ParsedLine
+import org.jline.utils.AttributedString
+import org.junit.jupiter.api.AfterEach
+import org.junit.jupiter.api.Test
+
+final class GroovyshLanguageSessionTest {
+
+ private GroovyEngine groovy
+ private GroovyshLanguageSession session
+
+ @AfterEach
+ void tearDown() {
+ session?.close()
+ }
+
+ @Test
+ void diagnosticsForBrokenInputReturnHits() {
+ groovy = new GroovyEngine()
+ session = new GroovyshLanguageSession(groovy)
+ def hits = session.diagnosticsFor('class Broken { def x = }')
+ assert hits.any { it.message() }
+ }
+
+ @Test
+ void diagnosticsHonourEngineCompilerConfiguration() {
+ def configuration = new CompilerConfiguration()
+ def imports = new ImportCustomizer()
+ imports.addImports('java.util.concurrent.ConcurrentHashMap')
+ configuration.addCompilationCustomizers(imports)
+ groovy = new GroovyEngine(configuration)
+ session = new GroovyshLanguageSession(groovy)
+ def hits = session.diagnosticsFor('ConcurrentHashMap m')
+ assert !hits.any { (it.message() ?: '').contains('ConcurrentHashMap') }
+ session.close()
+ groovy = new GroovyEngine()
+ session = new GroovyshLanguageSession(groovy)
+ def without = session.diagnosticsFor('ConcurrentHashMap m')
+ assert without.any { (it.message() ?: '').contains('ConcurrentHashMap') }
+ }
+
+ @Test
+ void composeDeclaresBindingVariablesAndSkipsInternals() {
+ groovy = new GroovyEngine()
+ groovy.put('answer', 42)
+ groovy.put('PWD', '/tmp')
+ groovy.put('FOO', 'skip')
+ groovy.put('1bad', 'skip')
+ groovy.put('GROOVY_OPTIONS', [:])
+ groovy.put('CONSOLE_OPTIONS', [:])
+ groovy.put('ROOT', '/')
+ groovy.put('NANORC', 'x')
+ groovy.put('_args', [])
+ groovy.put('gone', null)
+ groovy.put('nums', [1, 2] as int[])
+ groovy.put('run', new Runnable() {
+ @Override
+ void run() {
+ }
+ })
+ session = new GroovyshLanguageSession(groovy)
+ String script = session.compose('answer')
+ assert script.contains('java.lang.Integer answer = null')
+ assert !script.contains('PWD')
+ assert !script.contains('FOO')
+ assert !script.contains('1bad')
+ assert !script.contains('GROOVY_OPTIONS')
+ assert !script.contains('CONSOLE_OPTIONS')
+ assert !script.contains('ROOT')
+ assert !script.contains('NANORC')
+ assert !script.contains('_args')
+ assert !script.contains('gone')
+ assert script.contains('int[] nums = null')
+ assert script.contains('java.lang.Object run = null')
+ }
+
+ @Test
+ void composeDoesNotRedeclareBufferNames() {
+ groovy = new GroovyEngine()
+ groovy.put('GROOVYSH_OPTIONS', [interpreterMode: true])
+ groovy.execute('int kept = 7')
+ session = new GroovyshLanguageSession(groovy)
+ String script = session.compose('kept')
+ assert script.readLines().count { it ==~ /.*\bkept\s*=.*/ } == 1
+ }
+
+ @Test
+ void completeLineAndCompleterMapEngineCandidates() {
+ groovy = new GroovyEngine()
+ groovy.execute('class Box { String name }')
+ session = new GroovyshLanguageSession(groovy)
+ def items = session.completeLine('new Box().')
+ assert items != null
+ assert session.completeLine('new Box().', 9) != null
+ assert session.completeLine('new Box().', -1) != null
+ def candidates = []
+ session.complete(null, new Line('Box().'), candidates)
+ session.complete(null, new Line('/grab'), candidates)
+ session.complete(null, null, candidates)
+ session.complete(null, new Line(''), null)
+ assert GroovyLanguageEngine.flattenSnippetLine('class ${1:Name} {\n $0\n}') == 'class Name {'
+ assert GroovyLanguageEngine.flattenSnippetLine(null) == ''
+ assert GroovyLanguageEngine.flattenSnippetLine('') == ''
+ assert GroovyLanguageEngine.flattenSnippetLine('$0') == ''
+ assert GroovyLanguageEngine.flattenSnippetLine('${1:foo}$2bar') == 'foobar'
+ assert GroovyLanguageEngine.flattenSnippetLine('one\ntwo') == 'one'
+ assert GroovyshLanguageSession.BUFFER_URI.toString() == 'groovy-buffer:repl'
+ }
+
+ @Test
+ void mapEngineCandidatesPrefixesAndSkipsEmptyInsert() {
+ def out = []
+ def items = [
+ new GroovyLanguageEngine.Candidate('name', 'field', 'String', 'name', ''),
+ new GroovyLanguageEngine.Candidate('', 'method', '', '', ''),
+ new GroovyLanguageEngine.Candidate('ping', 'method', '', '${1:ping}', ''),
+ ]
+ GroovyshLanguageSession.mapEngineCandidates(items, new Line('Box().'), out)
+ assert out.size() == 2
+ assert out[0].value() == 'Box().name'
+ assert out[0].displ() == 'name'
+ assert out[0].group() == 'field'
+ assert out[1].value() == 'Box().ping'
+ out.clear()
+ GroovyshLanguageSession.mapEngineCandidates(
+ [new GroovyLanguageEngine.Candidate('println', 'method', '', 'println', '')],
+ new Line('pri', 3), out)
+ assert out[0].value() == 'println'
+ out.clear()
+ GroovyshLanguageSession.mapEngineCandidates(
+ [new GroovyLanguageEngine.Candidate('name', 'field', '', 'Box().name', '')],
+ new Line('Box().'), out)
+ assert out[0].value() == 'Box().name'
+ out.clear()
+ GroovyshLanguageSession.mapEngineCandidates(
+ [new GroovyLanguageEngine.Candidate('x', null, null, 'x', '')],
+ new Line('z'), out)
+ assert out[0].group() == 'other'
+ GroovyshLanguageSession.mapEngineCandidates(null, new Line('x'), out)
+ GroovyshLanguageSession.mapEngineCandidates(items, null, out)
+ GroovyshLanguageSession.mapEngineCandidates(items, new Line('x'), null)
+ GroovyshLanguageSession.mapEngineCandidates(
+ [null, new GroovyLanguageEngine.Candidate('ok', 'method', '', 'ok', '')],
+ new Line('z'), out)
+ assert out.any { it.value() == 'ok' || it.value().endsWith('ok') }
+ }
+
+ @Test
+ void scriptDescriptionUsesDiagnosticsThenFallsBack() {
+ groovy = new GroovyEngine()
+ session = new GroovyshLanguageSession(groovy)
+ def syntax = new CmdLine('class Broken { def x = }', 'class Broken { def x = }', '', [],
+ CmdLine.DescriptionType.SYNTAX)
+ def desc = session.scriptDescription(syntax)
+ assert desc?.mainDesc
+ def clean = new CmdLine('1', '1', '', [], CmdLine.DescriptionType.SYNTAX)
+ assert session.scriptDescription(clean) == null
+ def method = new CmdLine('println(', 'println', '', ['println'], CmdLine.DescriptionType.METHOD)
+ session.scriptDescription(method)
+ session.scriptDescription(null)
+ assert session.signaturesFor('') != null
+ def callLine = 'Box.ping('
+ def call = new CmdLine(callLine, 'Box.ping', '', ['Box'], CmdLine.DescriptionType.METHOD)
+ def withParen = session.signaturesFor(callLine)
+ def headOnly = session.signaturesFor('Box.ping')
+ session.scriptDescription(call)
+ assert withParen.signatures() != null
+ assert headOnly.signatures() != null
+ }
+
+ @Test
+ void helpersCoverEmptyCompletionsAndInspectorFallback() {
+ groovy = new GroovyEngine() {
+ @Override
+ CmdDesc scriptDescription(CmdLine line) {
+ throw new RuntimeException('boom')
+ }
+ }
+ session = new GroovyshLanguageSession(groovy)
+ def syntax = new CmdLine('1', '1', '', [], CmdLine.DescriptionType.SYNTAX)
+ assert session.scriptDescription(syntax) == null
+ def method = new CmdLine('zzz(', 'zzz', '', ['zzz'], CmdLine.DescriptionType.METHOD)
+ assert session.scriptDescription(method) == null
+ }
+
+ @Test
+ void typeLiteralMatrix() {
+ assert GroovyshLanguageSession.typeLiteral('x') == 'java.lang.String'
+ assert GroovyshLanguageSession.typeLiteral(1L) == 'java.lang.Long'
+ assert GroovyshLanguageSession.typeLiteral(new Object()) == 'java.lang.Object'
+ assert GroovyshLanguageSession.typeLiteral(new int[0]) == 'int[]'
+ assert GroovyshLanguageSession.typeLiteral(new String[0]) == 'java.lang.String[]'
+ assert GroovyshLanguageSession.typeLiteral(new Runnable() {
+ @Override
+ void run() {
+ }
+ }) == 'java.lang.Object'
+ assert GroovyshLanguageSession.typeLiteral(Nested.A) == Nested.canonicalName
+ Runnable lambda = () -> {}
+ assert GroovyshLanguageSession.typeLiteral(lambda) == 'java.lang.Object'
+ assert GroovyshLanguageSession.typeLiteral(new Hidden()) == 'java.lang.Object'
+ }
+
+ @Test
+ void bindingDeclarationsToleratesFindFailure() {
+ groovy = new GroovyEngine() {
+ @Override
+ Map<String, Object> find(String name) {
+ throw new IllegalStateException('boom')
+ }
+ }
+ session = new GroovyshLanguageSession(groovy)
+ assert session.compose('1').trim() == '1'
+ session.close()
+ groovy = new GroovyEngine() {
+ @Override
+ Map<String, Object> find(String name) {
+ null
+ }
+ }
+ session = new GroovyshLanguageSession(groovy)
+ assert session.compose('1').trim() == '1'
+ }
+
+ @Test
+ void completeSwallowsEngineFailureAfterClose() {
+ groovy = new GroovyEngine()
+ session = new GroovyshLanguageSession(groovy)
+ session.close()
+ def candidates = []
+ session.complete(null, new Line('x'), candidates)
+ assert candidates.isEmpty()
+ session = null
+ }
+
+ @Test
+ void closeAfterDiagnostics() {
+ groovy = new GroovyEngine()
+ session = new GroovyshLanguageSession(groovy)
+ assert session.diagnosticsFor('1') instanceof List
+ session.close()
+ session = null
+ }
+
+ @Test
+ void scriptDescriptionFallsBackWhenMethodHasNoSignatures() {
+ groovy = new GroovyEngine() {
+ @Override
+ CmdDesc scriptDescription(CmdLine line) {
+ def d = new CmdDesc()
+ d.setMainDesc([new AttributedString('fallback')])
+ return d
+ }
+ }
+ session = new GroovyshLanguageSession(groovy)
+ def method = new CmdLine('zzz(', 'zzz', '', ['zzz'], CmdLine.DescriptionType.METHOD)
+ def desc = session.scriptDescription(method)
+ assert desc?.mainDesc[0].toString().contains('fallback')
+ }
+
+ enum Nested { A }
+
+ private static final class Hidden {}
+
+ private static final class Line implements ParsedLine {
+ private final String text
+ private final int cursor
+
+ Line(String text) {
+ this(text, text.length())
+ }
+
+ Line(String text, int cursor) {
+ this.text = text
+ this.cursor = cursor
+ }
+
+ @Override
+ String word() { text }
+
+ @Override
+ int wordCursor() { Math.min(cursor, text.length()) }
+
+ @Override
+ int wordIndex() { 0 }
+
+ @Override
+ List<String> words() { [text] }
+
+ @Override
+ String line() { text }
+
+ @Override
+ int cursor() { cursor }
+ }
+}
diff --git a/subprojects/groovy-lsp/AGENTS.md b/subprojects/groovy-lsp/AGENTS.md
index 58ee24a0e3..1378638ecc 100644
--- a/subprojects/groovy-lsp/AGENTS.md
+++ b/subprojects/groovy-lsp/AGENTS.md
@@ -37,8 +37,8 @@ resolution lives in `MethodBinding`, shared by navigation, hover,
completion and rename. In-process callers use `GroovyLanguageEngine`
(`open(Path)` or a caller-chosen buffer URI; queries take that URI)
and JDK result records.
-The engine does not reserve buffer names. Hosts (console, groovysh)
-take a `compileOnly` dependency and load the engine with `Class.forName`.
+The engine does not reserve buffer names. Console and groovysh take an
+`implementation` dependency and construct their adapters directly.
Configuration is `workspace/didChangeConfiguration` and
`workspace/configuration` under the `groovy` section (see
`lsp-userguide.adoc`). Do not add OSGi, extra JSON-RPC methods, or a
diff --git a/subprojects/groovy-lsp/ARCHITECTURE.md b/subprojects/groovy-lsp/ARCHITECTURE.md
index 05c260fff3..a292922bce 100644
--- a/subprojects/groovy-lsp/ARCHITECTURE.md
+++ b/subprojects/groovy-lsp/ARCHITECTURE.md
@@ -189,9 +189,17 @@ call. Wrong edits are worse for an agent than a refused rename.
workspace folders, so constructing it never compiles a checkout root.
Completions, semantic tokens and signature help are URI queries on an
open buffer. Semantic tokens on that path are absolute spans; the
- protocol delta-encoding stays in `SemanticTokensService.encode`. `setParentLoader`, `setClasspath` and `putExtra` supply
- the parent `ClassLoader`, the compile classpath, and an opaque
- fingerprint input after that loader changes in place. Workspace symbol
+ protocol delta-encoding stays in `SemanticTokensService.encode`.
+ Console live highlighting (`SmartDocumentFilter`) consumes
+ `GroovySourceTokens.tokenizeLenient` — the same lexer walk as
+ lexical semantic tokens, with `errorIgnored` so incomplete input
+ still paints. It does not call `tokens()` on the EDT; those spans
+ need a compiled snapshot. Keyword token types come from
+ `GroovyKeywords.KEYWORD_TOKEN_TYPES`. `setParentLoader`, `setClasspath`, `setHostConfiguration` and `putExtra` supply
+ the parent `ClassLoader`, the compile classpath, Console/groovysh
+ `CompilerConfiguration` (import and AST customizers), and an opaque
+ fingerprint input. In-place `addURL` is visible because the fingerprint
+ includes that loader's URLs. Workspace symbol
search accepts CamelHumps (`ASF` → `AbstractServerFactory`) as well
as a case-insensitive substring. Hover Groovydoc is Markdown
(`{@code}`, `{@link}`, `@param`).
@@ -215,9 +223,9 @@ call. Wrong edits are worse for an agent than a refused rename.
supports it. References skip files that do not contain the
identifier as a word.
- **Compile cache.** A fingerprint of open buffers, extra-file mtimes,
- settings and parent-loader identity skips a full recompile when
- nothing changed. In-place `addURL` on the same loader still needs
- `putExtra`. Compile
+ settings, parent-loader identity and URLs, and host
+ `CompilerConfiguration` identity skips a full recompile when
+ nothing changed. Compile
runs off the session lock so document sync is not blocked; a
generation counter drops superseded compiles. When the client omits
classpath and source paths, `WorkspaceLayout` uses `src/main/groovy`
@@ -280,8 +288,16 @@ process working directory — that would compile the whole checkout.
JSON-RPC round-trips are not required to prove feature logic.
`GroovyLanguageEngine` tests use `openBuffer` with a caller-chosen
non-file URI (or a temp file) and never add workspace folders. Console and
-groovysh adapters live in those subprojects (`compileOnly` plus
-`Class.forName`) so groovy-all does not grow an LSP4J dependency.
+groovysh take an `implementation` dependency on groovy-lsp and construct
+their adapters directly. Hosts call `diagnostics(uri, text)` and the
+matching query-with-text overloads rather than `updateBuffer` plus a
+second call. Snippet flattening and UTF-16 span math live on the
+engine (`flattenSnippet`, `spanOf`). Result records are JDK types;
+those adapters do not import LSP4J. Feature services still use LSP4J
+types internally, so the engine jar still needs LSP4J at runtime;
+splitting a protocol-free engine module is a later cut. The compile
+fingerprint includes `URLClassLoader` URLs so in-place `addURL`
+(`/grab`, console classpath) does not need a host-side stamp.
## Related
diff --git a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/LanguageServerContext.java b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/LanguageServerContext.java
index b890205486..52bb8c18fd 100644
--- a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/LanguageServerContext.java
+++ b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/LanguageServerContext.java
@@ -31,6 +31,7 @@ import org.apache.groovy.lsp.internal.protocol.ClientFeatures;
import org.apache.groovy.lsp.internal.util.Uris;
import org.apache.groovy.lsp.internal.workspace.DocumentStore;
import org.apache.groovy.lsp.internal.workspace.TextDocument;
+import org.codehaus.groovy.control.CompilerConfiguration;
import org.eclipse.lsp4j.ApplyWorkspaceEditParams;
import org.eclipse.lsp4j.WorkspaceEdit;
@@ -45,6 +46,8 @@ import org.eclipse.lsp4j.jsonrpc.messages.Either;
import org.eclipse.lsp4j.services.LanguageClient;
import java.net.URI;
+import java.net.URL;
+import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
@@ -77,6 +80,7 @@ public final class LanguageServerContext {
private final AtomicReference<CompilerSettings> settings = new AtomicReference<>(CompilerSettings.defaults());
private final AtomicReference<CompilationSnapshot> snapshot = new AtomicReference<>(CompilationSnapshot.EMPTY);
private final AtomicReference<ClassLoader> parentLoader = new AtomicReference<>();
+ private final AtomicReference<CompilerConfiguration> hostConfiguration = new AtomicReference<>();
private volatile boolean initialized;
private volatile boolean shutdown;
private volatile Integer exitCode;
@@ -128,7 +132,7 @@ public final class LanguageServerContext {
extra = scanner.scan(folders, effective.getSourcePaths(), effective.getIgnoredDirectories());
open = documents.snapshot();
loader = compileParentLoader();
- fingerprint = fingerprint(open, extra, effective, loader);
+ fingerprint = fingerprint(open, extra, effective, loader, hostConfiguration.get());
if (fingerprint.equals(compileFingerprint) && snapshot.get() != CompilationSnapshot.EMPTY) {
// Another compile already committed this snapshot but may
// not have published yet. Fall through to publishDiagnostics.
@@ -144,7 +148,7 @@ public final class LanguageServerContext {
beginProgress(token, "Compiling Groovy");
CompilationSnapshot compiled;
try {
- compiled = compiler.compile(open, extra, effective, loader);
+ compiled = compiler.compile(open, extra, effective, loader, hostConfiguration.get());
} finally {
endProgress(token);
}
@@ -401,8 +405,9 @@ public final class LanguageServerContext {
/**
* Parent loader for the next compile. {@code null} uses this class's loader.
- * The compile fingerprint is cleared only when the loader identity changes,
- * so setting the same loader again does not force a recompile.
+ * The compile fingerprint is cleared when the loader identity changes.
+ * In-place {@code URLClassLoader#addURL} is visible on the next compile
+ * because the fingerprint includes that loader's URLs.
*
* @param parentLoader parent loader, or {@code null}
*/
@@ -420,6 +425,26 @@ public final class LanguageServerContext {
return parentLoader.get();
}
+ /**
+ * Compiler configuration from Console or groovysh. {@code null} uses
+ * a fresh tooling configuration. Identity changes clear the fingerprint.
+ *
+ * @param configuration host configuration, or {@code null}
+ */
+ public synchronized void setHostConfiguration(final CompilerConfiguration configuration) {
+ CompilerConfiguration previous = this.hostConfiguration.getAndSet(configuration);
+ if (previous != configuration) {
+ compileFingerprint = null;
+ }
+ }
+
+ /**
+ * @return the host configuration, or {@code null}
+ */
+ public synchronized CompilerConfiguration getHostConfiguration() {
+ return hostConfiguration.get();
+ }
+
private ClassLoader compileParentLoader() {
ClassLoader loader = parentLoader.get();
return loader == null ? getClass().getClassLoader() : loader;
@@ -497,8 +522,9 @@ public final class LanguageServerContext {
}
/**
- * Stable key including the parent loader identity. In-place
- * {@code addURL} on the same loader still needs {@code extra}.
+ * Stable key including the parent loader identity and, for a
+ * {@link URLClassLoader}, its URL list so in-place {@code addURL} is
+ * visible.
*
* @param open open documents
* @param extra workspace files
@@ -508,6 +534,19 @@ public final class LanguageServerContext {
*/
public static String fingerprint(final Collection<TextDocument> open, final Collection<Path> extra,
final CompilerSettings settings, final ClassLoader parentLoader) {
+ return fingerprint(open, extra, settings, parentLoader, null);
+ }
+
+ /**
+ * Stable key including loader identity, loader URLs, and host
+ * {@link CompilerConfiguration} identity.
+ *
+ * @param hostConfiguration console or groovysh configuration, or {@code null}
+ * @return a fingerprint
+ */
+ public static String fingerprint(final Collection<TextDocument> open, final Collection<Path> extra,
+ final CompilerSettings settings, final ClassLoader parentLoader,
+ final CompilerConfiguration hostConfiguration) {
StringBuilder builder = new StringBuilder();
builder.append(settings.getClasspath()).append('|')
.append(settings.getSourcePaths()).append('|')
@@ -516,7 +555,16 @@ public final class LanguageServerContext {
.append(settings.isAstTestEnabled()).append('|')
.append(settings.getThroughPhase()).append('|')
.append(settings.getExtra()).append('|')
- .append(System.identityHashCode(parentLoader));
+ .append(System.identityHashCode(parentLoader)).append('|')
+ .append(System.identityHashCode(hostConfiguration));
+ if (parentLoader instanceof URLClassLoader urls) {
+ URL[] listed = urls.getURLs();
+ if (listed != null) {
+ for (URL url : listed) {
+ builder.append('|').append(url == null ? "" : url.toExternalForm());
+ }
+ }
+ }
if (open != null) {
for (TextDocument document : open) {
builder.append('\n').append(document.getUri()).append(':')
diff --git a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/compile/CompilerSettings.java b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/compile/CompilerSettings.java
index 2c60e10ca4..155523cc0e 100644
--- a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/compile/CompilerSettings.java
+++ b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/compile/CompilerSettings.java
@@ -34,7 +34,6 @@ import java.util.Map;
import java.util.Objects;
import java.util.Set;
-
/**
* Compilation options for the language server. Grape and {@code @ASTTest}
* are off by default so opening a workspace does not execute or download
@@ -241,7 +240,21 @@ public record CompilerSettings(List<String> classpath, List<String> sourcePaths,
* @return the configuration
*/
public CompilerConfiguration toConfiguration() {
- CompilerConfiguration configuration = new CompilerConfiguration();
+ return toConfiguration(null);
+ }
+
+ /**
+ * Builds a tooling configuration, copying semantic customizers from
+ * {@code host} when present (imports, AST transforms, script base class).
+ * Grape and {@code @ASTTest} still follow these settings.
+ *
+ * @param host console or groovysh configuration, or {@code null}
+ * @return the configuration
+ */
+ public CompilerConfiguration toConfiguration(final CompilerConfiguration host) {
+ CompilerConfiguration configuration = host == null
+ ? new CompilerConfiguration()
+ : new CompilerConfiguration(host);
configuration.setTolerance(0);
configuration.setTargetBytecode(CompilerConfiguration.JDK17);
if (!classpath.isEmpty()) {
diff --git a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/compile/GroovyCompiler.java b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/compile/GroovyCompiler.java
index 1a626fc589..78cbdfc3bc 100644
--- a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/compile/GroovyCompiler.java
+++ b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/compile/GroovyCompiler.java
@@ -74,8 +74,21 @@ public final class GroovyCompiler implements AutoCloseable {
*/
public CompilationSnapshot compile(final Collection<TextDocument> openDocuments, final Collection<Path> extraFiles,
final CompilerSettings settings, final ClassLoader parentLoader) {
+ return compile(openDocuments, extraFiles, settings, parentLoader, null);
+ }
+
+ /**
+ * Compiles with an optional host {@link CompilerConfiguration} so import
+ * and AST customizers from Console or groovysh are visible.
+ *
+ * @param hostConfiguration console or groovysh configuration, or {@code null}
+ * @return an immutable snapshot
+ */
+ public CompilationSnapshot compile(final Collection<TextDocument> openDocuments, final Collection<Path> extraFiles,
+ final CompilerSettings settings, final ClassLoader parentLoader,
+ final CompilerConfiguration hostConfiguration) {
synchronized (this) {
- CompilerConfiguration configuration = settings.toConfiguration();
+ CompilerConfiguration configuration = settings.toConfiguration(hostConfiguration);
return withProcessFlags(settings, () ->
compileUnit(openDocuments, extraFiles, settings, parentLoader, configuration));
}
diff --git a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/engine/GroovyLanguageEngine.java b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/engine/GroovyLanguageEngine.java
index 37c845c896..977f77b53c 100644
--- a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/engine/GroovyLanguageEngine.java
+++ b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/engine/GroovyLanguageEngine.java
@@ -28,6 +28,20 @@ import org.apache.groovy.lsp.internal.position.PositionEncoding;
import org.apache.groovy.lsp.internal.position.Positions;
import org.apache.groovy.lsp.internal.util.Uris;
import org.apache.groovy.lsp.internal.workspace.TextDocument;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.ModuleNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
+import org.codehaus.groovy.ast.expr.DeclarationExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.TupleExpression;
+import org.codehaus.groovy.ast.expr.VariableExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.control.CompilerConfiguration;
+import org.codehaus.groovy.syntax.Types;
import org.eclipse.lsp4j.CompletionItem;
import org.eclipse.lsp4j.CompletionList;
import org.eclipse.lsp4j.Diagnostic;
@@ -52,9 +66,12 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.Set;
+import java.util.regex.Pattern;
/**
* In-process facade over the same compile snapshot the LSP handlers use.
@@ -69,6 +86,8 @@ public final class GroovyLanguageEngine implements AutoCloseable {
private static final int SNIPPET_CONTEXT_LINES = 3;
private static final String LANGUAGE_GROOVY = "groovy";
+ private static final Pattern SNIPPET_PLACEHOLDER = Pattern.compile("\\$\\{\\d+:([^}]*)}");
+ private static final Pattern SNIPPET_TABSTOP = Pattern.compile("\\$\\d+");
private final LanguageServerContext context;
private final LanguageFeatures features;
@@ -150,9 +169,9 @@ public final class GroovyLanguageEngine implements AutoCloseable {
}
/**
- * Replaces buffer text without compiling. The next query compiles when
- * the open version does not match the snapshot; {@link #compileNow()}
- * and {@link #scheduleCompile(long)} remain available for callers that
+ * Replaces buffer text without compiling. The next query compiles;
+ * unchanged inputs reuse the snapshot. {@link #compileNow()} and
+ * {@link #scheduleCompile(long)} remain available for callers that
* debounce.
*
* @param uri buffer identity
@@ -205,6 +224,16 @@ public final class GroovyLanguageEngine implements AutoCloseable {
context.setParentLoader(parentLoader);
}
+ /**
+ * Compiler configuration from Console or groovysh. Import customizers
+ * and AST transforms are copied into the tooling compile.
+ *
+ * @param configuration host configuration, or {@code null}
+ */
+ public void setHostConfiguration(final CompilerConfiguration configuration) {
+ context.setHostConfiguration(configuration);
+ }
+
/**
* Replaces the compile classpath. Empty or {@code null} clears it.
*
@@ -254,6 +283,65 @@ public final class GroovyLanguageEngine implements AutoCloseable {
.toList();
}
+ /**
+ * Replaces the buffer text, then returns diagnostics.
+ *
+ * @param uri buffer identity
+ * @param text source text
+ * @return diagnostics, never {@code null}
+ */
+ public List<Hit> diagnostics(final URI uri, final String text) {
+ updateBuffer(uri, text);
+ return diagnostics(uri);
+ }
+
+ /**
+ * Script-level names the compiler already introduced in an open buffer:
+ * non-script type simple names, script methods other than {@code run}/{@code main},
+ * and assignments in the script {@code run} body. Used by REPL hosts so
+ * binding declarations are not duplicated.
+ *
+ * @param uri buffer identity
+ * @return names, never {@code null}
+ */
+ public Set<String> declaredNames(final URI uri) {
+ TextDocument document = documentAt(uri);
+ CompiledDocument compiled = context.getSnapshot().get(document);
+ if (compiled == null || compiled.getModule() == null) {
+ return Set.of();
+ }
+ Set<String> names = new LinkedHashSet<>();
+ ModuleNode module = compiled.getModule();
+ for (ClassNode classNode : module.getClasses()) {
+ if (classNode.isScript()) {
+ for (MethodNode method : classNode.getMethods()) {
+ if (scriptLevelMethod(method)) {
+ names.add(method.getName());
+ }
+ }
+ addScriptAssignments(classNode, names);
+ } else {
+ String simple = classNode.getNameWithoutPackage();
+ if (simple != null && !simple.isEmpty()) {
+ names.add(simple);
+ }
+ }
+ }
+ return names;
+ }
+
+ /**
+ * Replaces the buffer text, then returns script-level names.
+ *
+ * @param uri buffer identity
+ * @param text source text
+ * @return names, never {@code null}
+ */
+ public Set<String> declaredNames(final URI uri, final String text) {
+ updateBuffer(uri, text);
+ return declaredNames(uri);
+ }
+
/**
* Hover markdown for an open buffer.
*
@@ -268,6 +356,20 @@ public final class GroovyLanguageEngine implements AutoCloseable {
new Position(line, character), encoding());
}
+ /**
+ * Replaces the buffer text, then returns hover markdown.
+ *
+ * @param uri buffer identity
+ * @param text source text
+ * @param line 0-based line
+ * @param character 0-based character
+ * @return markdown, never {@code null}
+ */
+ public String describe(final URI uri, final String text, final int line, final int character) {
+ updateBuffer(uri, text);
+ return describe(uri, line, character);
+ }
+
/**
* Definition targets in an open buffer.
*
@@ -393,6 +495,20 @@ public final class GroovyLanguageEngine implements AutoCloseable {
.toList();
}
+ /**
+ * Replaces the buffer text, then returns completions.
+ *
+ * @param uri buffer identity
+ * @param text source text
+ * @param line 0-based line
+ * @param character 0-based character
+ * @return candidates, never {@code null}
+ */
+ public List<Candidate> complete(final URI uri, final String text, final int line, final int character) {
+ updateBuffer(uri, text);
+ return complete(uri, line, character);
+ }
+
/**
* Semantic tokens as absolute spans (not LSP delta encoding).
*
@@ -435,6 +551,20 @@ public final class GroovyLanguageEngine implements AutoCloseable {
return new SignatureSet(activeSignature, activeParameter, List.copyOf(signatures));
}
+ /**
+ * Replaces the buffer text, then returns signatures.
+ *
+ * @param uri buffer identity
+ * @param text source text
+ * @param line 0-based line
+ * @param character 0-based character
+ * @return signatures, never {@code null}
+ */
+ public SignatureSet signatures(final URI uri, final String text, final int line, final int character) {
+ updateBuffer(uri, text);
+ return signatures(uri, line, character);
+ }
+
/**
* Indent-only format of an open buffer.
*
@@ -480,8 +610,9 @@ public final class GroovyLanguageEngine implements AutoCloseable {
}
private void ensureFresh(final TextDocument document) {
- CompiledDocument compiled = context.getSnapshot().get(document);
- if (compiled == null || compiled.getVersion() != document.getVersion()) {
+ if (document != null) {
+ // recompile() no-ops when the fingerprint (text, loader URLs,
+ // host CompilerConfiguration identity, settings) is unchanged.
context.recompile();
}
}
@@ -493,6 +624,177 @@ public final class GroovyLanguageEngine implements AutoCloseable {
return Uris.normalize(uri);
}
+ private static boolean scriptLevelMethod(final MethodNode method) {
+ if (method == null || method.isSynthetic()) {
+ return false;
+ }
+ String name = method.getName();
+ if (name == null || name.isEmpty() || "<init>".equals(name) || "<clinit>".equals(name)) {
+ return false;
+ }
+ if ("run".equals(name) && method.getParameters().length == 0) {
+ return false;
+ }
+ return !"main".equals(name);
+ }
+
+ private static void addScriptAssignments(final ClassNode script, final Set<String> names) {
+ MethodNode run = script.getMethod("run", Parameter.EMPTY_ARRAY);
+ if (run == null || run.getCode() == null) {
+ return;
+ }
+ collectAssignments(run.getCode(), names);
+ }
+
+ private static void collectAssignments(final Statement statement, final Set<String> names) {
+ if (statement instanceof BlockStatement block) {
+ for (Statement nested : block.getStatements()) {
+ collectAssignments(nested, names);
+ }
+ return;
+ }
+ if (!(statement instanceof ExpressionStatement expressionStatement)) {
+ return;
+ }
+ Expression expression = expressionStatement.getExpression();
+ if (expression instanceof DeclarationExpression declaration) {
+ addLeftNames(declaration.getLeftExpression(), names);
+ return;
+ }
+ if (expression instanceof BinaryExpression binary
+ && binary.getOperation() != null
+ && binary.getOperation().getType() == Types.ASSIGN) {
+ addLeftNames(binary.getLeftExpression(), names);
+ }
+ }
+
+ private static void addLeftNames(final Expression left, final Set<String> names) {
+ if (left instanceof VariableExpression variable) {
+ String name = variable.getName();
+ if (name != null && !name.isEmpty()) {
+ names.add(name);
+ }
+ } else if (left instanceof TupleExpression tuple) {
+ for (Expression element : tuple.getExpressions()) {
+ addLeftNames(element, names);
+ }
+ }
+ }
+
+ /**
+ * Maps a UTF-16 document offset to a 0-based line and character.
+ * CR, LF, and CRLF are line breaks.
+ *
+ * @param text document text
+ * @param offset UTF-16 offset
+ * @return {@code {line, character}}
+ */
+ public static int[] positionOf(final String text, final int offset) {
+ if (text == null || text.isEmpty() || offset <= 0) {
+ return new int[] {0, 0};
+ }
+ int capped = Math.min(offset, text.length());
+ int line = 0;
+ int character = 0;
+ for (int i = 0; i < capped; i++) {
+ char c = text.charAt(i);
+ if (c == '\n') {
+ line++;
+ character = 0;
+ } else if (c == '\r') {
+ if (i + 1 < text.length() && text.charAt(i + 1) == '\n') {
+ i++;
+ }
+ line++;
+ character = 0;
+ } else {
+ character++;
+ }
+ }
+ return new int[] {line, character};
+ }
+
+ /**
+ * Maps a 0-based line and character to a UTF-16 document offset.
+ * The character is clamped to the requested line. CR, LF, and CRLF
+ * are line breaks.
+ *
+ * @param text document text
+ * @param line 0-based line
+ * @param character 0-based character
+ * @return offset in {@code text}
+ */
+ public static int offsetOf(final String text, final int line, final int character) {
+ return TextDocument.offsetOf(text, new Position(Math.max(line, 0), Math.max(character, 0)),
+ PositionEncoding.UTF16);
+ }
+
+ /**
+ * Strips LSP snippet placeholders from completion insert text.
+ *
+ * @param insert snippet or plain insert text
+ * @return flattened text, never {@code null}
+ */
+ public static String flattenSnippet(final String insert) {
+ if (insert == null || insert.isEmpty()) {
+ return "";
+ }
+ return SNIPPET_TABSTOP.matcher(SNIPPET_PLACEHOLDER.matcher(insert).replaceAll("$1")).replaceAll("");
+ }
+
+ /**
+ * {@link #flattenSnippet(String)} truncated at the first newline.
+ * Line-oriented hosts (groovysh) use this.
+ *
+ * @param insert snippet or plain insert text
+ * @return one line, never {@code null}
+ */
+ public static String flattenSnippetLine(final String insert) {
+ String flattened = flattenSnippet(insert);
+ int nl = flattened.indexOf('\n');
+ return nl < 0 ? flattened : flattened.substring(0, nl);
+ }
+
+ /**
+ * Maps a diagnostic range onto UTF-16 offsets. A zero-width or inverted
+ * range becomes one character so a highlighter has something to paint.
+ * A range at EOF paints the last character of a non-empty document.
+ *
+ * @param text document text
+ * @param startLine 0-based start line
+ * @param startCharacter 0-based start character
+ * @param endLine 0-based end line
+ * @param endCharacter 0-based end character
+ * @return {@code {startOffset, endOffset}}
+ */
+ public static int[] spanOf(final String text, final int startLine, final int startCharacter,
+ final int endLine, final int endCharacter) {
+ int start = offsetOf(text, startLine, startCharacter);
+ int end = offsetOf(text, endLine, endCharacter);
+ int length = text == null ? 0 : text.length();
+ if (end <= start) {
+ if (length > 0 && start >= length) {
+ start = length - 1;
+ end = length;
+ } else {
+ end = Math.min(start + 1, length);
+ }
+ }
+ return new int[] {start, end};
+ }
+
+ /**
+ * @param text document text
+ * @param hit diagnostic
+ * @return {@code {startOffset, endOffset}}
+ */
+ public static int[] spanOf(final String text, final Hit hit) {
+ if (hit == null) {
+ return new int[] {0, 0};
+ }
+ return spanOf(text, hit.startLine(), hit.startCharacter(), hit.endLine(), hit.endCharacter());
+ }
+
private PositionEncoding encoding() {
return context.getPositionEncoding();
}
@@ -520,7 +822,7 @@ public final class GroovyLanguageEngine implements AutoCloseable {
String insert = item.getInsertText() == null ? item.getLabel() : item.getInsertText();
return new Candidate(item.getLabel() == null ? "" : item.getLabel(), kind,
item.getDetail() == null ? "" : item.getDetail(),
- insert == null ? "" : insert,
+ flattenSnippet(insert),
markupOrString(item.getDocumentation()));
}
diff --git a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/util/GroovyKeywords.java b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/util/GroovyKeywords.java
index 8019d187fc..acb795a20d 100644
--- a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/util/GroovyKeywords.java
+++ b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/util/GroovyKeywords.java
@@ -50,6 +50,13 @@ public final class GroovyKeywords {
return word != null && KEYWORDS.contains(word);
}
+ /**
+ * Lexer token types painted as reserved words: vocabulary word
+ * keywords, {@code !in}/{@code !instanceof}, primitives, {@code true},
+ * {@code false} and {@code null}.
+ */
+ public static final List<Integer> KEYWORD_TOKEN_TYPES = List.copyOf(keywordTokenTypes());
+
/**
* Declaration modifiers, using the lexer token types so the spelling
* still comes from the vocabulary.
@@ -63,6 +70,32 @@ public final class GroovyKeywords {
private GroovyKeywords() {
}
+ private static List<Integer> keywordTokenTypes() {
+ List<Integer> types = new ArrayList<>();
+ Vocabulary vocabulary = GroovyLexer.VOCABULARY;
+ for (int type = 1; type <= vocabulary.getMaxTokenType(); type++) {
+ if (isKeywordTokenType(vocabulary, type)) {
+ types.add(type);
+ }
+ }
+ return types;
+ }
+
+ private static boolean isKeywordTokenType(final Vocabulary vocabulary, final int type) {
+ if (type == GroovyLexer.NOT_IN || type == GroovyLexer.NOT_INSTANCEOF
+ || type == GroovyLexer.BuiltInPrimitiveType
+ || type == GroovyLexer.BooleanLiteral
+ || type == GroovyLexer.NullLiteral) {
+ return true;
+ }
+ String symbolic = vocabulary.getSymbolicName(type);
+ if ("BooleanLiteral".equals(symbolic) || "NullLiteral".equals(symbolic)
+ || "BuiltInPrimitiveType".equals(symbolic)) {
+ return true;
+ }
+ return isWordKeyword(unquote(vocabulary.getLiteralName(type)));
+ }
+
private static TreeSet<String> keywords() {
TreeSet<String> words = new TreeSet<>();
Vocabulary vocabulary = GroovyLexer.VOCABULARY;
diff --git a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/util/GroovySourceTokens.java b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/util/GroovySourceTokens.java
index d960b9c971..908eaa1bc2 100644
--- a/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/util/GroovySourceTokens.java
+++ b/subprojects/groovy-lsp/src/main/java/org/apache/groovy/lsp/internal/util/GroovySourceTokens.java
@@ -20,6 +20,7 @@ package org.apache.groovy.lsp.internal.util;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.Token;
+import org.apache.groovy.parser.antlr4.GroovyLangLexer;
import org.apache.groovy.parser.antlr4.GroovyLexer;
import org.apache.groovy.parser.antlr4.GroovySyntaxError;
@@ -27,9 +28,10 @@ import java.util.ArrayList;
import java.util.List;
/**
- * Live {@link GroovyLexer} walks over a buffer. Used as a fail-closed
- * gate for on-type {@code '}'}', comment-based folds, and lexical
- * semantic tokens (string / number / comment).
+ * Live {@link GroovyLexer} walks over a buffer. Strict walks are a
+ * fail-closed gate for on-type {@code '}'}', comment-based folds, and
+ * lexical semantic tokens. Lenient walks ({@link #tokenizeLenient})
+ * keep tokenising incomplete input for a host highlighter.
*/
public final class GroovySourceTokens {
@@ -48,7 +50,7 @@ public final class GroovySourceTokens {
return null;
}
try {
- GroovyLexer lexer = lexer(text);
+ GroovyLexer lexer = lexer(text, false);
for (Token token = lexer.nextToken(); token.getType() != Token.EOF; token = lexer.nextToken()) {
if (token.getStartIndex() <= utf16Offset && utf16Offset <= token.getStopIndex()) {
return token;
@@ -82,18 +84,34 @@ public final class GroovySourceTokens {
}
/**
- * Full token walk including hidden-channel tokens.
+ * Full token walk including hidden-channel tokens. Lexical errors
+ * abort the walk so on-type formatting can refuse to guess.
*
* @param text document text
* @return tokens, never {@code null}
*/
public static List<Token> tokenize(final String text) {
+ return tokenize(text, false);
+ }
+
+ /**
+ * Token walk for a live highlighter. Incomplete input still yields
+ * tokens ({@code errorIgnored}).
+ *
+ * @param text document text
+ * @return tokens, never {@code null}
+ */
+ public static List<Token> tokenizeLenient(final String text) {
+ return tokenize(text, true);
+ }
+
+ private static List<Token> tokenize(final String text, final boolean errorIgnored) {
List<Token> tokens = new ArrayList<>();
if (text == null || text.isEmpty()) {
return tokens;
}
try {
- GroovyLexer lexer = lexer(text);
+ GroovyLexer lexer = lexer(text, errorIgnored);
for (Token token = lexer.nextToken(); token.getType() != Token.EOF; token = lexer.nextToken()) {
tokens.add(token);
}
@@ -103,9 +121,12 @@ public final class GroovySourceTokens {
return tokens;
}
- private static GroovyLexer lexer(final String text) {
- GroovyLexer lexer = new GroovyLexer(CharStreams.fromString(text));
+ private static GroovyLexer lexer(final String text, final boolean errorIgnored) {
+ GroovyLexer lexer = errorIgnored
+ ? new GroovyLangLexer(CharStreams.fromString(text))
+ : new GroovyLexer(CharStreams.fromString(text));
lexer.removeErrorListeners();
+ lexer.setErrorIgnored(errorIgnored);
return lexer;
}
}
diff --git a/subprojects/groovy-lsp/src/spec/doc/lsp-userguide.adoc b/subprojects/groovy-lsp/src/spec/doc/lsp-userguide.adoc
index e1bfd93c67..08d4a817d8 100644
--- a/subprojects/groovy-lsp/src/spec/doc/lsp-userguide.adoc
+++ b/subprojects/groovy-lsp/src/spec/doc/lsp-userguide.adoc
@@ -480,7 +480,7 @@ Selection ranges grow from the caret through each enclosing AST node, so each re
[[lsp-in-process]]
== In-process use
-Console, groovysh, and tests can use the same snapshot without speaking JSON-RPC.
+Groovy Console and groovysh depend on this module and use the same snapshot without speaking JSON-RPC.
`GroovyLanguageEngine` is that facade.
Its results are JDK records.
They do not use LSP4J types.
@@ -529,13 +529,20 @@ It does not append the `_inferred_` line that the protocol hover adds.
`rename` returns edits and does not write them.
`format` and `organizeImports` also return edits.
`tokens` returns absolute semantic-token spans for a host highlighter.
+Those spans need a compiled snapshot, so a live editor highlighter uses `GroovySourceTokens.tokenizeLenient` instead — the same lexer, with incomplete input still tokenized.
`compileNow` compiles immediately.
`scheduleCompile` compiles after the delay you pass.
-`setParentLoader`, `setClasspath`, and `putExtra` are the session controls.
+`diagnostics`, `complete`, `describe`, `signatures`, and `declaredNames` each have a form that takes the buffer text, replaces it, then queries.
+`flattenSnippet` strips LSP snippet placeholders.
+`flattenSnippetLine` keeps the first line.
+`positionOf`, `offsetOf`, and `spanOf` convert 0-based UTF-16 positions.
+`setParentLoader`, `setClasspath`, `setHostConfiguration`, and `putExtra` are the session controls.
+`setParentLoader` records loader identity and, for a `URLClassLoader`, its URL list, so an in-place `addURL` is visible on the next compile.
+`setHostConfiguration` copies import and AST customizers from a Console or groovysh `CompilerConfiguration` into the tooling compile.
`putExtra` records one opaque string and, like a classpath change, forces the next compile onto a fresh loader.
-Hosts that must not put LSP4J on the Groovy classpath can depend on `groovy-lsp` as `compileOnly` and load the engine with `Class.forName`.
-Groovy Console and groovysh do that.
+Groovy Console and groovysh depend on `groovy-lsp` and construct `GroovyLanguageEngine` in-process.
+Hosts that must not put LSP4J on their own compile classpath can still depend on `groovy-lsp` as `compileOnly` and load the engine with `Class.forName`.
****
*Inferred results.*
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/engine/GroovyLanguageEngineBufferTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/engine/GroovyLanguageEngineBufferTest.groovy
index 6b38b347b8..e8455bffa4 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/engine/GroovyLanguageEngineBufferTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/engine/GroovyLanguageEngineBufferTest.groovy
@@ -21,6 +21,8 @@ package org.apache.groovy.lsp.internal.engine
import org.apache.groovy.lsp.internal.LanguageServerContext
import org.apache.groovy.lsp.internal.compile.CompilerSettings
import org.apache.groovy.lsp.internal.feature.LanguageFeatures
+import org.codehaus.groovy.control.CompilerConfiguration
+import org.codehaus.groovy.control.customizers.ImportCustomizer
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Test
@@ -120,6 +122,78 @@ final class GroovyLanguageEngineBufferTest {
def one = LanguageServerContext.fingerprint([], [], CompilerSettings.defaults(), new GroovyClassLoader())
def two = LanguageServerContext.fingerprint([], [], CompilerSettings.defaults(), new GroovyClassLoader())
assert one != two
+ def loader = new GroovyClassLoader()
+ def before = LanguageServerContext.fingerprint([], [], CompilerSettings.defaults(), loader)
+ loader.addURL(URI.create('file:/tmp/lsp-url-stamp.jar').toURL())
+ def afterUrls = LanguageServerContext.fingerprint([], [], CompilerSettings.defaults(), loader)
+ assert before != afterUrls
+ def host = new CompilerConfiguration()
+ def withHost = LanguageServerContext.fingerprint([], [], CompilerSettings.defaults(), loader, host)
+ def otherHost = LanguageServerContext.fingerprint([], [], CompilerSettings.defaults(), loader, new CompilerConfiguration())
+ assert withHost != otherHost
+ assert withHost == LanguageServerContext.fingerprint([], [], CompilerSettings.defaults(), loader, host)
+ }
+
+ @Test
+ void hostCompilerConfigurationImportsAreVisibleOnTheNextQuery() {
+ engine = new GroovyLanguageEngine()
+ engine.openBuffer(BUFFER, 'groovy', 'ConcurrentHashMap m\n')
+ def before = engine.diagnostics(BUFFER)
+ assert before.any { (it.message() ?: '').contains('ConcurrentHashMap') }
+ def configuration = new CompilerConfiguration()
+ def imports = new ImportCustomizer()
+ imports.addImports('java.util.concurrent.ConcurrentHashMap')
+ configuration.addCompilationCustomizers(imports)
+ engine.setHostConfiguration(configuration)
+ assert engine.context().hostConfiguration.is(configuration)
+ def copied = CompilerSettings.defaults().toConfiguration(configuration)
+ assert copied.compilationCustomizers.contains(imports)
+ assert copied.tolerance == 0
+ def after = engine.diagnostics(BUFFER)
+ assert !after.any { (it.message() ?: '').contains('ConcurrentHashMap') }
+ engine.setHostConfiguration(null)
+ def reset = engine.diagnostics(BUFFER)
+ assert reset.any { (it.message() ?: '').contains('ConcurrentHashMap') }
+ }
+
+ @Test
+ void declaredNamesReadsScriptMembersAndTypesFromTheAst() {
+ engine = new GroovyLanguageEngine()
+ engine.openBuffer(BUFFER, 'groovy', '''\
+ class Box {}
+ def ping() { 1 }
+ int kept = 7
+ x = 1
+ def outer() {
+ int inner = 1
+ }
+ '''.stripIndent())
+ def names = engine.declaredNames(BUFFER)
+ assert names.contains('Box')
+ assert names.contains('ping')
+ assert names.contains('kept')
+ assert names.contains('x')
+ assert names.contains('outer')
+ assert !names.contains('inner')
+ assert GroovyLanguageEngine.positionOf('ab\ncd', 4) == [1, 1] as int[]
+ assert GroovyLanguageEngine.offsetOf('ab\ncd', 1, 1) == 4
+ assert GroovyLanguageEngine.offsetOf('ab\ncd', 0, 99) == 2
+ assert GroovyLanguageEngine.positionOf('ab\r\ncd', 4) == [1, 0] as int[]
+ assert GroovyLanguageEngine.offsetOf('ab\r\ncd', 1, 0) == 4
+ assert GroovyLanguageEngine.positionOf(null, 1) == [0, 0] as int[]
+ assert GroovyLanguageEngine.offsetOf('', 0, 0) == 0
+ assert GroovyLanguageEngine.flattenSnippet('class ${1:Name} {\n $0\n}') == 'class Name {\n \n}'
+ assert GroovyLanguageEngine.flattenSnippetLine('class ${1:Name} {\n $0\n}') == 'class Name {'
+ assert GroovyLanguageEngine.spanOf('ab', 0, 0, 0, 0) == [0, 1] as int[]
+ assert GroovyLanguageEngine.spanOf('abc', 0, 3, 0, 3) == [2, 3] as int[]
+ assert GroovyLanguageEngine.spanOf('abc', 9, 0, 9, 0) == [2, 3] as int[]
+ assert GroovyLanguageEngine.spanOf('ab\r', 0, 3, 0, 3) == [2, 3] as int[]
+ engine.updateBuffer(BUFFER, 'class Broken { def x = }')
+ assert engine.diagnostics(BUFFER, 'class Broken { def x = }').any { it.message() }
+ assert engine.describe(BUFFER, 'class Sample {}', 0, 6).contains('Sample')
+ assert engine.complete(BUFFER, 'class Sample { def ping() { ping() } }', 0, 6) != null
+ assert engine.signatures(BUFFER, 'class Sample { def ping() { ping() } }', 0, 6) != null
+ assert engine.declaredNames(BUFFER, 'class Box {}').contains('Box')
}
@Test
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/LanguageQualityTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/LanguageQualityTest.groovy
index 3f983df952..31b55b1dab 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/LanguageQualityTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/feature/LanguageQualityTest.groovy
@@ -216,6 +216,11 @@ final class LanguageQualityTest {
def extra = LanguageServerContext.fingerprint([a], [],
new CompilerSettings([], [], CompilerSettings.defaults().throughPhase, false, false, [gdsl: 'x']))
assert extra != left
+ def loader = new GroovyClassLoader()
+ def before = LanguageServerContext.fingerprint([a], [], CompilerSettings.defaults(), loader)
+ loader.addURL(URI.create('file:/tmp/lsp-fingerprint.jar').toURL())
+ def after = LanguageServerContext.fingerprint([a], [], CompilerSettings.defaults(), loader)
+ assert before != after
}
@Test
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/GroovyKeywordsTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/GroovyKeywordsTest.groovy
index 0c1808e304..d028c70a7a 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/GroovyKeywordsTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/GroovyKeywordsTest.groovy
@@ -61,6 +61,20 @@ final class GroovyKeywordsTest {
assert !GroovyKeywords.isKeyword('notAKeyword')
}
+ @Test
+ void keywordTokenTypesCoverVocabularyWordsAndSpecials() {
+ def types = GroovyKeywords.KEYWORD_TOKEN_TYPES
+ assert types.contains(GroovyLexer.DEF)
+ assert types.contains(GroovyLexer.CLASS)
+ assert types.contains(GroovyLexer.NOT_IN)
+ assert types.contains(GroovyLexer.NOT_INSTANCEOF)
+ assert types.contains(GroovyLexer.BuiltInPrimitiveType)
+ assert types.contains(GroovyLexer.BooleanLiteral)
+ assert types.contains(GroovyLexer.NullLiteral)
+ assert types.every { it > 0 }
+ assert types.size() == types.toSet().size()
+ }
+
@Test
void privateConstructorCanBeInvoked() {
[GroovyKeywords].each { Class type ->
diff --git a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/GroovySourceTokensTest.groovy b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/GroovySourceTokensTest.groovy
index e4b15547b2..25b64c8135 100644
--- a/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/GroovySourceTokensTest.groovy
+++ b/subprojects/groovy-lsp/src/test/groovy/org/apache/groovy/lsp/internal/util/GroovySourceTokensTest.groovy
@@ -63,4 +63,13 @@ final class GroovySourceTokensTest {
assert GroovySourceTokens.tokenize('1_').isEmpty()
assert GroovySourceTokens.covering('1_', 0) == null
}
+
+ @Test
+ void tokenizeLenientKeepsTokensOnIncompleteInput() {
+ def tokens = GroovySourceTokens.tokenizeLenient('def x =')
+ assert tokens.any { it.text == 'def' }
+ assert GroovySourceTokens.tokenizeLenient('1_').any { it.text.contains('1') }
+ assert GroovySourceTokens.tokenizeLenient(null).isEmpty()
+ assert GroovySourceTokens.tokenizeLenient('').isEmpty()
+ }
}