Copilot commented on code in PR #4007:
URL: 
https://github.com/apache/incubator-kie-tools/pull/4007#discussion_r4284211451


##########
packages/drools-lsp/drools-lsp-server/src/main/java/org/drools/lsp/server/DroolsLspServer.java:
##########
@@ -246,12 +251,33 @@ boolean isDependencyClasspathResolved() {
         return dependencyClasspathResolved;
     }
 
+    /**
+     * Registers the custom operators declared on the project's own build 
output
+     * and on its dependencies, whenever either set may have changed. The
+     * dependency list from {@code mvn dependency:build-classpath} does not 
carry
+     * the project's own {@code target/classes}, which is where its
+     * {@code META-INF/kie.properties.conf} lives, so both sets are scanned.
+     * Dependency jars change only when the classpath resolves, so their ids 
are
+     * read there and only the class directories are rescanned here.
+     */
+    private void registerCustomOperators() {
+        Set<Path> scanned = filterDirectories(classpathEntries);
+        scanned.addAll(buildOutputDirs);
+        Set<String> operators = new TreeSet<>(jarCustomOperators);
+        operators.addAll(CustomOperators.register(scanned));
+        if (!operators.equals(registeredCustomOperators)) {
+            registeredCustomOperators = operators;
+            logger.info(() -> "Custom DRL operators: " + operators);
+        }
+    }

Review Comment:
   `filterDirectories(classpathEntries)` may return an immutable set (e.g., 
`Set.of(...)`). If so, `scanned.addAll(buildOutputDirs)` will throw 
`UnsupportedOperationException` at runtime. Make `scanned` explicitly mutable 
(e.g., copy into a new `HashSet`/`TreeSet`) before adding `buildOutputDirs`.



##########
packages/drools-lsp/drools-completion/src/main/java/org/drools/completion/CustomOperators.java:
##########
@@ -0,0 +1,140 @@
+/*
+ * 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.drools.completion;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Properties;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.drools.drl.parser.impl.Operator;
+
+/**
+ * The project's custom DRL operators, read from where the engine reads them:
+ * the {@code drools.evaluator.<id>} keys of {@code 
META-INF/kie.properties.conf}
+ * and {@code META-INF/kie.default.properties.conf} on its classpath
+ * ({@code org.kie.internal.utils.ChainedProperties}). The engine instantiates
+ * each configured class, whose static initializer registers the operator; only
+ * the keys are read here, so no project code runs in the server.
+ *
+ * <p>Each id is registered in the parser's {@link Operator} cache, which the
+ * DRL10 grammar consults through {@code isPluggableEvaluator} before accepting
+ * {@code ##id} — so a custom operator parses in the editor as it does in the
+ * engine. Operators registered from Java rather than configured, and ids a
+ * definition registers beyond its property key, are not seen.
+ */
+public final class CustomOperators {
+
+    private static final Logger logger = 
Logger.getLogger(CustomOperators.class.getName());
+
+    static final String PROPERTY_PREFIX = "drools.evaluator.";
+
+    static final String[] CONF_FILES = {
+        "META-INF/kie.properties.conf", 
"META-INF/kie.default.properties.conf"};
+
+    /** Legacy keys the engine's own configuration skips as well. */
+    private static final Set<String> IGNORED_IDS = Set.of("equality", 
"comparable");
+
+    private CustomOperators() {
+    }
+
+    /** Registers every operator id declared on {@code classpathEntries}; 
returns the ids found. */
+    public static Set<String> register(Set<Path> classpathEntries) {
+        Set<String> ids = discover(classpathEntries);
+        for (String id : ids) {
+            Operator.addOperatorToRegistry(id, false);
+            Operator.addOperatorToRegistry(id, true);
+        }
+        return ids;
+    }
+
+    /** Whether {@code id} is an operator the parser accepts after {@code ##}. 
*/
+    public static boolean isRegistered(String id) {
+        return id != null && Operator.determineOperator(id, false) != null;
+    }

Review Comment:
   `isRegistered` consults Drools’ global `Operator` registry, which (per the 
tests/docs) is JVM-wide and not cleared. This can cause false positives for the 
deprecated-syntax lint that claims “recognized only when the project declares 
it” (e.g., after removing an operator from config, or across workspace reloads 
within the same server process). To keep the lint accurate, maintain a separate 
“currently declared” id set (derived from the latest `discover(...)`) and use 
that for deprecated-construct recognition, while still registering with 
`Operator` for parser acceptance.



##########
packages/drools-lsp/drools-completion/src/main/java/org/drools/completion/DeprecatedConstructs.java:
##########
@@ -0,0 +1,339 @@
+/*
+ * 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.drools.completion;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.antlr.v4.runtime.CharStreams;
+import org.antlr.v4.runtime.CommonTokenStream;
+import org.antlr.v4.runtime.Token;
+import org.drools.drl.parser.antlr4.DRL10Lexer;
+import org.eclipse.lsp4j.Diagnostic;
+import org.eclipse.lsp4j.DiagnosticSeverity;
+import org.eclipse.lsp4j.Position;
+import org.eclipse.lsp4j.Range;
+
+/**
+ * Recognizes DRL constructs the engine's legacy parser still compiles but has
+ * deprecated for removal — the families {@code 
org.drools.drl.parser.lang.ParserHelper}
+ * warns about: half constraints, patterns joined with {@code &&}/{@code ||},
+ * annotations inside LHS patterns, {@code agenda-group}, and custom operators
+ * without the {@code ##} prefix DRL10 requires (apache/incubator-kie#6220). A
+ * custom operator is recognized only when the project declares it — see
+ * {@link CustomOperators}.
+ *
+ * <p>The engine's own warnings fire once per family per parse and carry no
+ * position, so they cannot drive a migration. Nor can this grammar's parse
+ * errors: it rejects some of these constructs ({@code age > 18 && < 65}),
+ * reads others as something else without an error
+ * ({@code ref.order > $ref.order && < $x}), and still accepts a third kind
+ * (pattern annotations). Detection therefore scans the token stream, which the
+ * lexer produces even where the parser fails, and relies on paren depth and
+ * section for precision. A recognized construct replaces the parse errors on
+ * its line, which describe the same thing less usefully; otherwise the
+ * deprecation is added.
+ *
+ * <p>Severity comes from {@value #PROP_DEPRECATED} (default {@code warning});
+ * {@code off} disables recognition, leaving the raw parse errors in place. At
+ * most one construct is reported per line; a second surfaces once the first is
+ * migrated, which keeps a sweep's output one finding per line rather than one
+ * per recovery attempt.
+ */
+final class DeprecatedConstructs {
+
+    /** System property: severity for deprecated-construct diagnostics. */
+    static final String PROP_DEPRECATED = "drools.lsp.lint.deprecated";
+
+    private static final String SOURCE = "drools-deprecated";
+
+    private static final String REMOVAL = " will be removed in a future 
version (LanguageLevel.DRL10)";
+
+    /**
+     * A recognized construct: the message to show and, when the migration is
+     * mechanical, the text that should replace the diagnostic's range. A
+     * {@code null} replacement means the construct needs a human decision
+     * (moving an annotation) or a rulebase-wide pass ({@code agenda-group}),
+     * so no quick fix is offered.
+     */
+    private static final class Finding {
+        final String message;
+        final String replacement;
+
+        Finding(String message, String replacement) {
+            this.message = message;
+            this.replacement = replacement;
+        }
+    }
+
+    /** Tokens that bound the left-hand operand when scanning back from an 
operator. */
+    private static final Set<Integer> OPERAND_BOUNDARY = Set.of(
+            DRL10Lexer.LPAREN, DRL10Lexer.COMMA, DRL10Lexer.AND, 
DRL10Lexer.OR, DRL10Lexer.SEMI);
+
+    /** Relational operators that, with no left operand, form a half 
constraint. */
+    private static final Set<Integer> RELATIONAL = Set.of(
+            DRL10Lexer.LT, DRL10Lexer.GT, DRL10Lexer.LE, DRL10Lexer.GE,
+            DRL10Lexer.EQUAL, DRL10Lexer.NOTEQUAL);
+
+    /** Tokens that can end the left-hand side of a custom-operator 
comparison. */
+    private static final Set<Integer> OPERAND_END = Set.of(
+            DRL10Lexer.IDENTIFIER, DRL10Lexer.RPAREN);
+
+    private DeprecatedConstructs() {
+    }
+
+    /**
+     * Returns {@code syntaxDiagnostics} with every error that marks a 
deprecated
+     * construct replaced by a diagnostic naming it, and the follow-on errors 
on
+     * those lines removed. Returns the input unchanged when recognition is off
+     * or nothing matches.
+     */
+    static List<Diagnostic> reclassify(String text, List<Diagnostic> 
syntaxDiagnostics) {
+        List<Diagnostic> syntax = syntaxDiagnostics == null ? List.of() : 
syntaxDiagnostics;
+        if (text == null || text.isEmpty()) {
+            return syntax;
+        }
+        DiagnosticSeverity severity = 
DRLLintHelper.severityFor(PROP_DEPRECATED, "warning");
+        if (severity == null) {
+            return syntax;
+        }
+        List<Token> tokens = defaultChannelTokens(text);
+        if (tokens.isEmpty()) {
+            return syntax;
+        }
+
+        List<Diagnostic> found = new ArrayList<>();
+        Set<Integer> claimedLines = new HashSet<>();
+        boolean inLhs = false;
+        int parenDepth = 0;
+        for (int i = 0; i < tokens.size(); i++) {
+            Token token = tokens.get(i);
+            int type = token.getType();
+            if (type == DRL10Lexer.DRL_WHEN) {
+                inLhs = true;
+                parenDepth = 0;
+            } else if (type == DRL10Lexer.DRL_QUERY && !inLhs && parenDepth == 
0) {
+                // A query's body is a left-hand side with no `when`; outside
+                // that position `query` is a field name, not a declaration.
+                inLhs = true;
+            } else if (type == DRL10Lexer.DRL_THEN || type == 
DRL10Lexer.DRL_END) {
+                inLhs = false;
+                parenDepth = 0;
+            }
+
+            Finding finding = describe(tokens, i, inLhs, parenDepth, text);
+            if (finding != null && claimedLines.add(token.getLine() - 1)) {
+                Diagnostic d = new Diagnostic();
+                d.setSeverity(severity);
+                d.setSource(SOURCE);
+                d.setMessage(finding.message);
+                d.setRange(rangeOf(token));
+                // The replacement rides in `data` for the quick fix, the same
+                // way the unknown-type lint carries its suggestion.
+                if (finding.replacement != null) {
+                    d.setData(finding.replacement);
+                }
+                found.add(d);
+            }
+
+            if (type == DRL10Lexer.LPAREN) {
+                parenDepth++;
+            } else if (type == DRL10Lexer.RPAREN && parenDepth > 0) {
+                parenDepth--;
+            }
+        }
+        if (found.isEmpty()) {
+            return syntax;
+        }
+        for (Diagnostic d : syntax) {
+            if (d.getRange() == null || d.getRange().getStart() == null
+                    || 
!claimedLines.contains(d.getRange().getStart().getLine())) {
+                found.add(d);
+            }
+        }
+        return found;
+    }
+
+    /**
+     * Names the deprecated construct at {@code index}, or {@code null} when 
the
+     * tokens there are an ordinary parse failure. Order matters: a {@code &&}
+     * before a relational operator is a half constraint, while the same token
+     * after a closing paren joins two patterns.
+     */
+    private static Finding describe(List<Token> tokens, int index, boolean 
inLhs,
+                                    int parenDepth, String text) {
+        Token token = tokens.get(index);
+        int type = token.getType();
+        Token next = index + 1 < tokens.size() ? tokens.get(index + 1) : null;
+        Token previous = index > 0 ? tokens.get(index - 1) : null;
+        boolean connective = type == DRL10Lexer.AND || type == DRL10Lexer.OR;
+        boolean insideConstraint = inLhs && parenDepth >= 1;
+
+        // Half constraint: `age > 18 && < 65`, inside a pattern's constraints.
+        // The fix repeats the operand the preceding comparison used, so
+        // `ref.order > $ref.order && < $x` becomes
+        // `ref.order > $ref.order && ref.order < $x`.
+        if (insideConstraint && connective && next != null && 
RELATIONAL.contains(next.getType())) {
+            String operand = leftOperandOfPreviousComparison(tokens, index, 
text);
+            return new Finding("Deprecated: half constraint '" + 
token.getText() + " " + next.getText()
+                    + "'" + REMOVAL + " — repeat the left operand.",
+                    operand == null ? null : token.getText() + " " + operand);
+        }
+
+        // Pattern connective: `Person( ... ) && Account( ... )`. Depth is the
+        // discriminator — the pattern's own ')' has already closed, so a
+        // pattern-level connective sits at depth 0, while the same tokens in
+        // `Person( (age > 1) && (age < 5) )` are still inside the constraint
+        // list and must not be flagged.
+        if (inLhs && parenDepth == 0 && connective
+                && previous != null && previous.getType() == 
DRL10Lexer.RPAREN) {
+            String replacement = type == DRL10Lexer.AND ? "and" : "or";
+            return new Finding("Deprecated: connecting patterns with '" + 
token.getText() + "'"
+                    + REMOVAL + " — use '" + replacement + "' instead.", 
replacement);
+        }
+
+        // Annotation inside a pattern: `Person( @watch(age) age > 1 )`. Moving
+        // or dropping it is a judgement call, so no fix is offered.
+        if (insideConstraint && type == DRL10Lexer.AT) {
+            return new Finding("Deprecated: annotations inside LHS patterns" + 
REMOVAL
+                    + "; annotations elsewhere remain supported.", null);
+        }
+
+        // `agenda-group "x"` in a rule's header or at package level — lexed as
+        // the identifier `agenda`, `-`, `group` because DRL10 has no such
+        // keyword. The string value tells it apart from `agenda - group` in a
+        // function body. No fix: the switch to ruleflow-group changes
+        // activation semantics and is all-or-nothing across a rulebase, so it
+        // belongs in one deliberate pass rather than per-occurrence clicks.
+        if (!inLhs && type == DRL10Lexer.IDENTIFIER && 
"agenda".equals(token.getText())
+                && next != null && next.getType() == DRL10Lexer.SUB
+                && index + 3 < tokens.size()
+                && "group".equals(tokens.get(index + 2).getText())
+                && isStringLiteral(tokens.get(index + 3))) {
+            return new Finding("Deprecated: 'agenda-group'" + REMOVAL
+                    + " — migrate to 'ruleflow-group' across the rulebase.", 
null);
+        }
+
+        // Custom operator used without its DRL10 prefix: `name supersetOf 
"x"`.
+        // Only an operator the project declares counts (see CustomOperators):
+        // an undeclared identifier between two operands is just as likely a
+        // typo, and stays the parse error it is.
+        if (insideConstraint && type == DRL10Lexer.IDENTIFIER
+                && previous != null && next != null
+                && OPERAND_END.contains(previous.getType())
+                && isOperandStart(next)
+                && CustomOperators.isRegistered(token.getText())) {
+            return new Finding("Deprecated: custom operator '" + 
token.getText()
+                    + "' requires a '##' prefix in DRL10 — write '##" + 
token.getText() + "'.",
+                    "##" + token.getText());
+        }
+
+        return null;
+    }
+
+    /**
+     * The source text of the operand on the left of the comparison preceding
+     * {@code connectiveIndex} — the operand a half constraint omitted. Scans
+     * back for that comparison's operator, then for the operand in front of 
it,
+     * stopping at a boundary ({@code (}, {@code ,}, {@code &&}, {@code ||},
+     * {@code ;}) so it never reaches into a neighbouring constraint. Returns
+     * {@code null} when the shape is not recognizable, leaving no quick fix
+     * rather than a wrong one.
+     */
+    private static String leftOperandOfPreviousComparison(List<Token> tokens, 
int connectiveIndex,
+                                                          String text) {
+        int operator = -1;
+        for (int i = connectiveIndex - 1; i >= 0; i--) {
+            int type = tokens.get(i).getType();
+            if (RELATIONAL.contains(type)) {
+                operator = i;
+                break;
+            }
+            if (OPERAND_BOUNDARY.contains(type)) {
+                return null;
+            }
+        }
+        if (operator <= 0) {
+            return null;
+        }
+        int end = operator - 1;
+        int start = end;
+        for (int i = end; i >= 0; i--) {
+            int type = tokens.get(i).getType();
+            if (OPERAND_BOUNDARY.contains(type) || RELATIONAL.contains(type)) {
+                break;
+            }
+            start = i;
+        }
+        Token first = tokens.get(start);
+        Token last = tokens.get(end);
+        int from = first.getStartIndex();
+        int to = last.getStopIndex() + 1;
+        if (from < 0 || to > text.length() || from >= to) {
+            return null;
+        }
+        // Sliced from the source so dotted paths and bindings keep their exact
+        // spelling rather than being rebuilt from token texts.
+        return text.substring(from, to).trim();
+    }
+
+    /** True when a token can begin the right-hand side of a comparison. */
+    private static boolean isOperandStart(Token token) {
+        int type = token.getType();
+        return type == DRL10Lexer.IDENTIFIER
+                || type == DRL10Lexer.DRL_STRING_LITERAL
+                || type == DRL10Lexer.STRING_LITERAL
+                || type == DRL10Lexer.DECIMAL_LITERAL
+                || type == DRL10Lexer.BOOL_LITERAL;
+    }
+
+    private static boolean isStringLiteral(Token token) {
+        int type = token.getType();
+        return type == DRL10Lexer.DRL_STRING_LITERAL || type == 
DRL10Lexer.STRING_LITERAL;
+    }
+
+    /** Tokens on the default channel; comments and whitespace are irrelevant 
here. */
+    private static List<Token> defaultChannelTokens(String text) {
+        List<Token> out = new ArrayList<>();
+        try {
+            DRL10Lexer lexer = new DRL10Lexer(CharStreams.fromString(text));
+            lexer.removeErrorListeners();
+            CommonTokenStream stream = new CommonTokenStream(lexer);
+            stream.fill();
+            for (Token token : stream.getTokens()) {
+                if (token.getChannel() == Token.DEFAULT_CHANNEL && 
token.getType() != Token.EOF) {
+                    out.add(token);
+                }
+            }
+        } catch (RuntimeException e) {
+            return List.of();
+        }

Review Comment:
   This re-lexes the entire document to get tokens, even though parsing already 
lexes the same input. For large files (or frequent validations), this doubles 
lexing cost. Consider refactoring 
`DRLDiagnosticHelper.parse(...)`/`DeprecatedConstructs.reclassify(...)` so 
`reclassify` can reuse the already-built `CommonTokenStream` (or its 
default-channel tokens) from the parse pipeline instead of creating a new 
`DRL10Lexer`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to