From 4b03019a33fb172682022038b39d78b47046f530 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Tue, 21 Jan 2025 17:53:11 +0900 Subject: [PATCH 1/8] [incubator-kie-drools-6220] Slim down DRL syntax with New Antlr4 Parser - Introduce DRL10 - WIP --- ...RLParserTest.java => DRL10ParserTest.java} | 10 +- .../drl/parser/antlr4/DRLExprParserTest.java | 2 +- .../drl/parser/antlr4/DescrDumperTest.java | 2 +- .../drl/parser/antlr4/ParserTestUtils.java | 20 ++- ...DRL6Expressions.g4 => DRL10Expressions.g4} | 22 +-- .../antlr4/{DRLLexer.g4 => DRL10Lexer.g4} | 2 +- .../antlr4/{DRLParser.g4 => DRL10Parser.g4} | 6 +- .../drl/parser/DrlExprParserFactory.java | 6 +- .../java/org/drools/drl/parser/DrlParser.java | 30 ++-- ...rserHelper.java => DRL10ParserHelper.java} | 28 ++-- ...erWrapper.java => DRL10ParserWrapper.java} | 18 +-- .../drl/parser/antlr4/DRLVisitorImpl.java | 141 +++++++++--------- .../drools/drl/parser/antlr4/DescrHelper.java | 2 +- ...ParserAntlr4.java => Drl10ExprParser.java} | 38 ++--- .../integrationtests/session/UpdateTest.java | 2 + .../builder/conf/LanguageLevelOption.java | 2 +- 16 files changed, 176 insertions(+), 155 deletions(-) rename drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/{DRLParserTest.java => DRL10ParserTest.java} (94%) rename drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/{DRL6Expressions.g4 => DRL10Expressions.g4} (97%) rename drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/{DRLLexer.g4 => DRL10Lexer.g4} (99%) rename drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/{DRLParser.g4 => DRL10Parser.g4} (99%) rename drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/{DRLParserHelper.java => DRL10ParserHelper.java} (84%) rename drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/{DRLParserWrapper.java => DRL10ParserWrapper.java} (82%) rename drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/{Drl6ExprParserAntlr4.java => Drl10ExprParser.java} (67%) diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRL10ParserTest.java similarity index 94% rename from drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLParserTest.java rename to drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRL10ParserTest.java index b760f5f75b4..598d18ddb8c 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLParserTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRL10ParserTest.java @@ -31,14 +31,14 @@ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.drools.drl.parser.antlr4.DRLParserHelper.computeTokenIndex; -import static org.drools.drl.parser.antlr4.DRLParserHelper.createDrlParser; -import static org.drools.drl.parser.antlr4.DRLParserHelper.parse; +import static org.drools.drl.parser.antlr4.DRL10ParserHelper.computeTokenIndex; +import static org.drools.drl.parser.antlr4.DRL10ParserHelper.createDrlParser; +import static org.drools.drl.parser.antlr4.DRL10ParserHelper.parse; /** * This test class is specific to new antlr4 parser. */ -class DRLParserTest { +class DRL10ParserTest { private static final String drl = "package org.test;\n" + @@ -94,7 +94,7 @@ void parse_basicRule() { @Test void computeTokenIndex_basicRule() { - DRLParser parser = createDrlParser(drl); + DRL10Parser parser = createDrlParser(drl); parser.compilationUnit(); assertThat((int) computeTokenIndex(parser, 1, 0)).isEqualTo(0); diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLExprParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLExprParserTest.java index 0baeac61ff1..24ab2cabe2a 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLExprParserTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLExprParserTest.java @@ -52,7 +52,7 @@ class DRLExprParserTest { @BeforeEach void setUp() { - this.parser = DrlExprParserFactory.getDrlExprParser(LanguageLevelOption.DRL6); + this.parser = ParserTestUtils.getExprParser(); } @AfterEach diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrDumperTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrDumperTest.java index 76f750ff215..4133e9f2594 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrDumperTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrDumperTest.java @@ -360,7 +360,7 @@ void processImplicitConstraints() { } public ConstraintConnectiveDescr parse(final String constraint) { - DrlExprParser parser = DrlExprParserFactory.getDrlExprParser(LanguageLevelOption.DRL6); + DrlExprParser parser = ParserTestUtils.getExprParser(); ConstraintConnectiveDescr result = parser.parse(constraint); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/ParserTestUtils.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/ParserTestUtils.java index 3419eab65e5..c7325329466 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/ParserTestUtils.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/ParserTestUtils.java @@ -21,7 +21,10 @@ import java.util.Arrays; import java.util.List; +import org.drools.drl.parser.DrlExprParser; +import org.drools.drl.parser.DrlExprParserFactory; import org.drools.drl.parser.DrlParser; +import org.kie.internal.builder.conf.LanguageLevelOption; public class ParserTestUtils { @@ -45,7 +48,22 @@ private ParserTestUtils() { * Returns a DrlParser which encapsulates an old or new parser depending on system property */ public static DrlParser getParser() { - return new DrlParser(); + if (DrlParser.ANTLR4_PARSER_ENABLED) { + return new DrlParser(LanguageLevelOption.DRL10); + } else { + return new DrlParser(LanguageLevelOption.DRL6); + } + } + + /** + * Returns a DrlExprParser which encapsulates an old or new parser depending on system property + */ + public static DrlExprParser getExprParser() { + if (DrlParser.ANTLR4_PARSER_ENABLED) { + return DrlExprParserFactory.getDrlExprParser(LanguageLevelOption.DRL10); + } else { + return DrlExprParserFactory.getDrlExprParser(LanguageLevelOption.DRL6); + } } /** diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL6Expressions.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Expressions.g4 similarity index 97% rename from drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL6Expressions.g4 rename to drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Expressions.g4 index 063e4ed48cf..b940e2e6d70 100644 --- a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL6Expressions.g4 +++ b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Expressions.g4 @@ -16,11 +16,11 @@ * specific language governing permissions and limitations * under the License. */ -parser grammar DRL6Expressions; +parser grammar DRL10Expressions; options { language = Java; - tokenVocab = DRLLexer; + tokenVocab = DRL10Lexer; superClass=DRLExpressions; } @@ -81,13 +81,13 @@ options { /*if (state.backtracking != 0){ return false; }*/ - if (_input.get( _input.index() - 1 ).getType() == DRLLexer.WS){ + if (_input.get( _input.index() - 1 ).getType() == DRL10Lexer.WS){ return true; } - if (_input.LA(-1) == DRLLexer.LPAREN){ + if (_input.LA(-1) == DRL10Lexer.LPAREN){ return true; } - return _input.get( _input.index() ).getType() != DRLLexer.EOF; + return _input.get( _input.index() ).getType() != DRL10Lexer.EOF; } private boolean notStartWithNewline() { @@ -126,7 +126,7 @@ literal operator returns [boolean negated, String opr] @init{ if ( isNotEOF() ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR ); helper.setHasOperator( true ); } // TODO verify that we can omit the backtracking check -@after{ if( /*state.backtracking == 0 &&*/ _input.LA( 1 ) != DRLLexer.EOF) { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } } +@after{ if( /*state.backtracking == 0 &&*/ _input.LA( 1 ) != DRL10Lexer.EOF) { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } } : x=TILDE? ( op=EQUAL { $negated = false; $opr=($x != null ? $x.text : "")+$op.text; helper.emit($op, DroolsEditorType.SYMBOL); } | op=NOTEQUAL { $negated = false; $opr=($x != null ? $x.text : "")+$op.text; helper.emit($op, DroolsEditorType.SYMBOL); } @@ -139,7 +139,7 @@ operator returns [boolean negated, String opr] relationalOp returns [boolean negated, String opr, java.util.List params] @init{ if ( isNotEOF() ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR ); helper.setHasOperator( true ); } // TODO verify that we can omit the backtracking check -@after{ if( /*state.backtracking == 0 &&*/ _input.LA( 1 ) != DRLLexer.EOF) { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } } +@after{ if( /*state.backtracking == 0 &&*/ _input.LA( 1 ) != DRL10Lexer.EOF) { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } } : ( op=LE { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} | op=GE { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} | op=LT { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} @@ -476,7 +476,7 @@ equalityExpression returns [BaseDescr result] : left=instanceOfExpression { if( buildDescr ) { $result = $left.result; } } ( ( op=EQUAL | op=NOTEQUAL ) { helper.setHasOperator( true ); - if( _input.LA( 1 ) != DRLLexer.EOF ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } + if( _input.LA( 1 ) != DRL10Lexer.EOF ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } right=instanceOfExpression { if( buildDescr ) { $result = new RelationalExprDescr( $op.text, false, null, $left.result, $right.result ); @@ -489,7 +489,7 @@ instanceOfExpression returns [BaseDescr result] : left=inExpression { if( buildDescr ) { $result = $left.result; } } ( op=instanceof_key { helper.setHasOperator( true ); - if( _input.LA( 1 ) != DRLLexer.EOF ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } + if( _input.LA( 1 ) != DRL10Lexer.EOF ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } right=type { if( buildDescr ) { $result = new RelationalExprDescr( $op.text, false, null, $left.result, new AtomicExprDescr($right.text) ); @@ -688,9 +688,9 @@ unaryExpressionNotPlusMinus returns [BaseDescr result] | castExpression | backReferenceExpression | { isLeft = helper.getLeftMostExpr() == null;} - ( ({inMap == 0 && ternOp == 0 && _input.LA(2) == DRLLexer.COLON}? (var=drlIdentifier COLON + ( ({inMap == 0 && ternOp == 0 && _input.LA(2) == DRL10Lexer.COLON}? (var=drlIdentifier COLON { hasBindings = true; helper.emit($var.token, DroolsEditorType.IDENTIFIER_VARIABLE); helper.emit($COLON, DroolsEditorType.SYMBOL); if( buildDescr ) { bind = new BindingDescr($var.text, null, false); helper.setStart( bind, $var.token ); } } )) - | ({inMap == 0 && ternOp == 0 && _input.LA(2) == DRLLexer.DRL_UNIFY}? (var=drlIdentifier DRL_UNIFY + | ({inMap == 0 && ternOp == 0 && _input.LA(2) == DRL10Lexer.DRL_UNIFY}? (var=drlIdentifier DRL_UNIFY { hasBindings = true; helper.emit($var.token, DroolsEditorType.IDENTIFIER_VARIABLE); helper.emit($DRL_UNIFY, DroolsEditorType.SYMBOL); if( buildDescr ) { bind = new BindingDescr($var.text, null, true); helper.setStart( bind, $var.token ); } } )) )? diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRLLexer.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Lexer.g4 similarity index 99% rename from drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRLLexer.g4 rename to drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Lexer.g4 index 2c05b4dc38b..22570d9b4a8 100644 --- a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRLLexer.g4 +++ b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Lexer.g4 @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -lexer grammar DRLLexer; +lexer grammar DRL10Lexer; import JavaLexer; diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRLParser.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Parser.g4 similarity index 99% rename from drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRLParser.g4 rename to drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Parser.g4 index 8ccaf9b4cd8..cc5080da384 100644 --- a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRLParser.g4 +++ b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Parser.g4 @@ -16,11 +16,11 @@ * specific language governing permissions and limitations * under the License. */ - parser grammar DRLParser; + parser grammar DRL10Parser; -options { tokenVocab=DRLLexer; } +options { tokenVocab=DRL10Lexer; } -import DRL6Expressions, JavaParser; +import DRL10Expressions, JavaParser; /* * statement := importStatement diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParserFactory.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParserFactory.java index 4ddbf289705..55259828e07 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParserFactory.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParserFactory.java @@ -18,7 +18,7 @@ */ package org.drools.drl.parser; -import org.drools.drl.parser.antlr4.Drl6ExprParserAntlr4; +import org.drools.drl.parser.antlr4.Drl10ExprParser; import org.kie.internal.builder.conf.LanguageLevelOption; public class DrlExprParserFactory { @@ -28,7 +28,9 @@ public static DrlExprParser getDrlExprParser(LanguageLevelOption languageLevel) case DRL5: case DRL6: case DRL6_STRICT: - return DrlParser.ANTLR4_PARSER_ENABLED ? new Drl6ExprParserAntlr4(languageLevel) : new Drl6ExprParser(languageLevel); + return new Drl6ExprParser(languageLevel); + case DRL10: + return new Drl10ExprParser(languageLevel); default: throw new RuntimeException("Unsupported language level: " + languageLevel); } diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlParser.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlParser.java index 714fd8a21c6..977232eb8cb 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlParser.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlParser.java @@ -19,7 +19,7 @@ package org.drools.drl.parser; import org.drools.drl.parser.antlr4.DRLParserError; -import org.drools.drl.parser.antlr4.DRLParserWrapper; +import org.drools.drl.parser.antlr4.DRL10ParserWrapper; import org.drools.io.InternalResource; import org.drools.drl.ast.descr.PackageDescr; import org.drools.drl.parser.lang.DRLLexer; @@ -53,7 +53,7 @@ public class DrlParser { // TODO: REMOVE THIS GENERIC MESSAGE ASAP private static final String GENERIC_ERROR_MESSAGE = "Unexpected exception raised while parsing. This is a bug. Please contact the Development team :\n"; - private static final String DEBUG_PARSER_LOG = "parse : ANTLR4_PARSER_ENABLED = {}"; + private static final String DEBUG_PARSER_LOG = "parse : ANTLR4_PARSER_ENABLED = {}, languageLevel = {}"; private final List results = new ArrayList<>(); private List editorSentences = null; private Location location = new Location( Location.LOCATION_UNKNOWN ); @@ -65,7 +65,7 @@ public class DrlParser { // temporarily removed 'final' for testing purposes. This should be final when the feature gets stable public static boolean ANTLR4_PARSER_ENABLED = Boolean.parseBoolean(System.getProperty(ANTLR4_PARSER_ENABLED_PROPERTY, "false")); // default is false - public static final LanguageLevelOption DEFAULT_LANGUAGE_LEVEL = LanguageLevelOption.DRL6; + public static final LanguageLevelOption DEFAULT_LANGUAGE_LEVEL = ANTLR4_PARSER_ENABLED ? LanguageLevelOption.DRL10 : LanguageLevelOption.DRL6; private final LanguageLevelOption languageLevel; public DrlParser() { @@ -84,9 +84,9 @@ public PackageDescr parse(final Resource resource, final String text) throws Dro public PackageDescr parse(final boolean isEditor, final String text) throws DroolsParserException { - LOG.debug(DEBUG_PARSER_LOG, ANTLR4_PARSER_ENABLED); - if (ANTLR4_PARSER_ENABLED) { - // new parser based on antlr4 + LOG.debug(DEBUG_PARSER_LOG, ANTLR4_PARSER_ENABLED, languageLevel); + if (languageLevel == LanguageLevelOption.DRL10) { + // DRL10 is handled by the new antlr4 parser return compileWithAntlr4Parser(parser -> parser.parse(new StringReader(text))); } else { lexer = DRLFactory.buildLexer(text, languageLevel); @@ -97,9 +97,9 @@ public PackageDescr parse(final boolean isEditor, public PackageDescr parse(final boolean isEditor, final Reader reader) throws DroolsParserException { - LOG.debug(DEBUG_PARSER_LOG, ANTLR4_PARSER_ENABLED); - if (ANTLR4_PARSER_ENABLED) { - // new parser based on antlr4 + LOG.debug(DEBUG_PARSER_LOG, ANTLR4_PARSER_ENABLED, languageLevel); + if (languageLevel == LanguageLevelOption.DRL10) { + // DRL10 is handled by the new antlr4 parser return compileWithAntlr4Parser(parser -> parser.parse(reader)); } else { lexer = DRLFactory.buildLexer(reader, languageLevel); @@ -186,9 +186,9 @@ public PackageDescr parse(final boolean isEditor, final InputStream is) throws DroolsParserException, IOException { this.resource = resource; String encoding = resource instanceof InternalResource ? ((InternalResource) resource).getEncoding() : null; - LOG.debug(DEBUG_PARSER_LOG, ANTLR4_PARSER_ENABLED); - if (ANTLR4_PARSER_ENABLED) { - // new parser based on antlr4 + LOG.debug(DEBUG_PARSER_LOG, ANTLR4_PARSER_ENABLED, languageLevel); + if (languageLevel == LanguageLevelOption.DRL10) { + // DRL10 is handled by the new antlr4 parser return compileWithAntlr4Parser(parser -> parser.parse(is, encoding)); } else { // old parsers based on antlr3 @@ -198,10 +198,10 @@ public PackageDescr parse(final boolean isEditor, } } - private PackageDescr compileWithAntlr4Parser(Function packageDescrFunction) throws DroolsParserException { + private PackageDescr compileWithAntlr4Parser(Function packageDescrFunction) throws DroolsParserException { try { - // we don't use languageLevel here, assuming DRL6 compatible - DRLParserWrapper parser = new DRLParserWrapper(resource); + // When DRL11 or higher is developed, languageLevel would be used to determine the parser to be used. + DRL10ParserWrapper parser = new DRL10ParserWrapper(resource); PackageDescr packageDescr = packageDescrFunction.apply(parser); for (final DRLParserError drlParserError : parser.getErrors()) { final ParserError err = new ParserError(resource, diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserHelper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRL10ParserHelper.java similarity index 84% rename from drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserHelper.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRL10ParserHelper.java index 131145b2d75..75994fc5a52 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserHelper.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRL10ParserHelper.java @@ -37,28 +37,28 @@ import org.kie.internal.builder.conf.LanguageLevelOption; /** - * Collection of static helper methods for DRLParser + * Collection of static helper methods for DRL10Parser */ -public class DRLParserHelper { +public class DRL10ParserHelper { - private DRLParserHelper() { + private DRL10ParserHelper() { } /** * Entry point for parsing DRL. - * Unlike DRLParserWrapper.parse(), this method does not collect errors. + * Unlike DRL10ParserWrapper.parse(), this method does not collect errors. */ public static PackageDescr parse(String drl) { - DRLParser drlParser = createDrlParser(drl); + DRL10Parser drlParser = createDrlParser(drl); return compilationUnitContext2PackageDescr(drlParser.compilationUnit(), drlParser.getTokenStream(), null); } - public static DRLParser createDrlParser(String drl) { + public static DRL10Parser createDrlParser(String drl) { CharStream charStream = CharStreams.fromString(drl); return createDrlParser(charStream); } - public static DRLParser createDrlParser(InputStream is, String encoding) { + public static DRL10Parser createDrlParser(InputStream is, String encoding) { try { CharStream charStream = encoding != null ? CharStreams.fromStream(is, Charset.forName(encoding)) @@ -69,7 +69,7 @@ public static DRLParser createDrlParser(InputStream is, String encoding) { } } - public static DRLParser createDrlParser(Reader reader) { + public static DRL10Parser createDrlParser(Reader reader) { try { CharStream charStream = CharStreams.fromReader(reader); return createDrlParser(charStream); @@ -78,11 +78,11 @@ public static DRLParser createDrlParser(Reader reader) { } } - private static DRLParser createDrlParser(CharStream charStream) { - DRLLexer drlLexer = new DRLLexer(charStream); + private static DRL10Parser createDrlParser(CharStream charStream) { + DRL10Lexer drlLexer = new DRL10Lexer(charStream); CommonTokenStream commonTokenStream = new CommonTokenStream(drlLexer); - DRLParser parser = new DRLParser(commonTokenStream); - ParserHelper helper = new ParserHelper(commonTokenStream, LanguageLevelOption.DRL6); + DRL10Parser parser = new DRL10Parser(commonTokenStream); + ParserHelper helper = new ParserHelper(commonTokenStream, LanguageLevelOption.DRL10); parser.setHelper(helper); return parser; } @@ -90,7 +90,7 @@ private static DRLParser createDrlParser(CharStream charStream) { /** * DRLVisitorImpl visits a parse tree and creates a PackageDescr */ - public static PackageDescr compilationUnitContext2PackageDescr(DRLParser.CompilationUnitContext ctx, TokenStream tokenStream, Resource resource) { + public static PackageDescr compilationUnitContext2PackageDescr(DRL10Parser.CompilationUnitContext ctx, TokenStream tokenStream, Resource resource) { DRLVisitorImpl visitor = new DRLVisitorImpl(tokenStream, resource); Object descr = visitor.visit(ctx); if (descr instanceof PackageDescr) { @@ -103,7 +103,7 @@ public static PackageDescr compilationUnitContext2PackageDescr(DRLParser.Compila /** * Given a row and column of the input DRL, return the index of the matched token */ - public static Integer computeTokenIndex(DRLParser parser, int row, int col) { + public static Integer computeTokenIndex(DRL10Parser parser, int row, int col) { for (int i = 0; i < parser.getInputStream().size(); i++) { Token token = parser.getInputStream().get(i); int start = token.getCharPositionInLine(); diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserWrapper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRL10ParserWrapper.java similarity index 82% rename from drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserWrapper.java rename to drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRL10ParserWrapper.java index e89ad669197..bc0f62c81ec 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserWrapper.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRL10ParserWrapper.java @@ -29,20 +29,20 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.drools.drl.parser.antlr4.DRLParserHelper.compilationUnitContext2PackageDescr; +import static org.drools.drl.parser.antlr4.DRL10ParserHelper.compilationUnitContext2PackageDescr; /** * Wrapper for DRLParser. Somewhat duplicated from DRLParserHelper, but this class is instantiated and holds errors. */ -public class DRLParserWrapper { +public class DRL10ParserWrapper { - private static final Logger LOGGER = LoggerFactory.getLogger(DRLParserWrapper.class); + private static final Logger LOGGER = LoggerFactory.getLogger(DRL10ParserWrapper.class); private final List errors = new ArrayList<>(); private final Resource resource; - public DRLParserWrapper(Resource resource) { + public DRL10ParserWrapper(Resource resource) { this.resource = resource; } @@ -50,7 +50,7 @@ public DRLParserWrapper(Resource resource) { * Main entry point for parsing DRL */ public PackageDescr parse(String drl) { - DRLParser drlParser = DRLParserHelper.createDrlParser(drl); + DRL10Parser drlParser = DRL10ParserHelper.createDrlParser(drl); return parse(drlParser); } @@ -58,7 +58,7 @@ public PackageDescr parse(String drl) { * Main entry point for parsing DRL */ public PackageDescr parse(InputStream is, String encoding) { - DRLParser drlParser = DRLParserHelper.createDrlParser(is, encoding); + DRL10Parser drlParser = DRL10ParserHelper.createDrlParser(is, encoding); return parse(drlParser); } @@ -66,15 +66,15 @@ public PackageDescr parse(InputStream is, String encoding) { * Main entry point for parsing DRL */ public PackageDescr parse(Reader reader) { - DRLParser drlParser = DRLParserHelper.createDrlParser(reader); + DRL10Parser drlParser = DRL10ParserHelper.createDrlParser(reader); return parse(drlParser); } - private PackageDescr parse(DRLParser drlParser) { + private PackageDescr parse(DRL10Parser drlParser) { DRLErrorListener errorListener = new DRLErrorListener(); drlParser.addErrorListener(errorListener); - DRLParser.CompilationUnitContext cxt = drlParser.compilationUnit(); + DRL10Parser.CompilationUnitContext cxt = drlParser.compilationUnit(); errors.addAll(errorListener.getErrors()); diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLVisitorImpl.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLVisitorImpl.java index 47d1b40bf9b..9d0cdf62a4e 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLVisitorImpl.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLVisitorImpl.java @@ -23,7 +23,6 @@ import java.util.stream.Collectors; import org.antlr.v4.runtime.ParserRuleContext; -import org.antlr.v4.runtime.RuleContext; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.tree.ParseTree; @@ -70,18 +69,18 @@ import static org.drools.drl.parser.antlr4.Antlr4ParserStringUtils.extractNamedConsequenceName; import static org.drools.drl.parser.antlr4.Antlr4ParserStringUtils.getTextPreservingWhitespace; import static org.drools.drl.parser.antlr4.Antlr4ParserStringUtils.getTokenTextPreservingWhitespace; -import static org.drools.drl.parser.antlr4.DRLParserHelper.getTextWithoutErrorNode; +import static org.drools.drl.parser.antlr4.DRL10ParserHelper.getTextWithoutErrorNode; import static org.drools.drl.parser.util.ParserStringUtils.appendPrefix; import static org.drools.drl.parser.util.ParserStringUtils.safeStripStringDelimiters; import static org.drools.util.StringUtils.unescapeJava; /** - * Visitor implementation for DRLParser. + * Visitor implementation for DRL10Parser. * Basically, each visit method creates and returns a Descr object traversing the parse tree. * Finally, visitCompilationUnit() returns a PackageDescr object. * Try not to depend on DRLVisitorImpl's internal state for clean maintainability */ -public class DRLVisitorImpl extends DRLParserBaseVisitor { +public class DRLVisitorImpl extends DRL10ParserBaseVisitor { private final TokenStream tokenStream; private final Resource resource; @@ -95,7 +94,7 @@ public DRLVisitorImpl(TokenStream tokenStream, Resource resource) { * Main entry point for creating PackageDescr from a parser tree. */ @Override - public PackageDescr visitCompilationUnit(DRLParser.CompilationUnitContext ctx) { + public PackageDescr visitCompilationUnit(DRL10Parser.CompilationUnitContext ctx) { PackageDescr packageDescr = BaseDescrFactory.builder(new PackageDescr()) .withParserRuleContext(ctx) .withResource(resource) @@ -159,7 +158,7 @@ private void applyChildrenDescrs(PackageDescr packageDescr, List desc } @Override - public UnitDescr visitUnitdef(DRLParser.UnitdefContext ctx) { + public UnitDescr visitUnitdef(DRL10Parser.UnitdefContext ctx) { return BaseDescrFactory.builder(new UnitDescr(ctx.name.getText())) .withParserRuleContext(ctx) .withResource(resource) @@ -167,12 +166,12 @@ public UnitDescr visitUnitdef(DRLParser.UnitdefContext ctx) { } @Override - public BaseDescr visitDrlStatementdef(DRLParser.DrlStatementdefContext ctx) { + public BaseDescr visitDrlStatementdef(DRL10Parser.DrlStatementdefContext ctx) { return visitDescrChildren(ctx).get(0); // only one child. Ignore SEMICOLON } @Override - public GlobalDescr visitGlobaldef(DRLParser.GlobaldefContext ctx) { + public GlobalDescr visitGlobaldef(DRL10Parser.GlobaldefContext ctx) { return BaseDescrFactory.builder(new GlobalDescr(ctx.drlIdentifier().getText(), ctx.type().getText())) .withParserRuleContext(ctx) .withResource(resource) @@ -180,7 +179,7 @@ public GlobalDescr visitGlobaldef(DRLParser.GlobaldefContext ctx) { } @Override - public ImportDescr visitImportStandardDef(DRLParser.ImportStandardDefContext ctx) { + public ImportDescr visitImportStandardDef(DRL10Parser.ImportStandardDefContext ctx) { String target = ctx.drlQualifiedName().getText() + (ctx.MUL() != null ? ".*" : ""); if (ctx.DRL_FUNCTION() != null || ctx.STATIC() != null) { FunctionImportDescr functionImportDescr = BaseDescrFactory.builder(new FunctionImportDescr()) @@ -200,7 +199,7 @@ public ImportDescr visitImportStandardDef(DRLParser.ImportStandardDefContext ctx } @Override - public AccumulateImportDescr visitImportAccumulateDef(DRLParser.ImportAccumulateDefContext ctx) { + public AccumulateImportDescr visitImportAccumulateDef(DRL10Parser.ImportAccumulateDefContext ctx) { AccumulateImportDescr accumulateImportDescr = BaseDescrFactory.builder(new AccumulateImportDescr()) .withParserRuleContext(ctx) .withResource(resource) @@ -211,7 +210,7 @@ public AccumulateImportDescr visitImportAccumulateDef(DRLParser.ImportAccumulate } @Override - public FunctionDescr visitFunctiondef(DRLParser.FunctiondefContext ctx) { + public FunctionDescr visitFunctiondef(DRL10Parser.FunctiondefContext ctx) { FunctionDescr functionDescr = BaseDescrFactory.builder(new FunctionDescr()) .withParserRuleContext(ctx) .withResource(resource) @@ -224,13 +223,13 @@ public FunctionDescr visitFunctiondef(DRLParser.FunctiondefContext ctx) { functionDescr.setName(ctx.drlIdentifier().getText()); // add function parameters - DRLParser.FormalParametersContext formalParametersContext = ctx.formalParameters(); - DRLParser.FormalParameterListContext formalParameterListContext = formalParametersContext.formalParameterList(); + DRL10Parser.FormalParametersContext formalParametersContext = ctx.formalParameters(); + DRL10Parser.FormalParameterListContext formalParameterListContext = formalParametersContext.formalParameterList(); if (formalParameterListContext != null) { - List formalParameterContexts = formalParameterListContext.formalParameter(); + List formalParameterContexts = formalParameterListContext.formalParameter(); formalParameterContexts.forEach(formalParameterContext -> { - DRLParser.TypeTypeContext typeTypeContext = formalParameterContext.typeType(); - DRLParser.VariableDeclaratorIdContext variableDeclaratorIdContext = formalParameterContext.variableDeclaratorId(); + DRL10Parser.TypeTypeContext typeTypeContext = formalParameterContext.typeType(); + DRL10Parser.VariableDeclaratorIdContext variableDeclaratorIdContext = formalParameterContext.variableDeclaratorId(); functionDescr.addParameter(typeTypeContext.getText(), variableDeclaratorIdContext.getText()); }); } @@ -239,12 +238,12 @@ public FunctionDescr visitFunctiondef(DRLParser.FunctiondefContext ctx) { } @Override - public BaseDescr visitDeclaredef(DRLParser.DeclaredefContext ctx) { + public BaseDescr visitDeclaredef(DRL10Parser.DeclaredefContext ctx) { return visitDescrChildren(ctx).get(0); // only one child } @Override - public TypeDeclarationDescr visitTypeDeclaration(DRLParser.TypeDeclarationContext ctx) { + public TypeDeclarationDescr visitTypeDeclaration(DRL10Parser.TypeDeclarationContext ctx) { TypeDeclarationDescr typeDeclarationDescr = BaseDescrFactory.builder(new TypeDeclarationDescr()) .withParserRuleContext(ctx) .withResource(resource) @@ -256,7 +255,7 @@ public TypeDeclarationDescr visitTypeDeclaration(DRLParser.TypeDeclarationContex typeDeclarationDescr.setTrait(true); } if (ctx.EXTENDS() != null) { - for (DRLParser.DrlQualifiedNameContext superType : ctx.superTypes) { + for (DRL10Parser.DrlQualifiedNameContext superType : ctx.superTypes) { typeDeclarationDescr.addSuperType(superType.getText()); } } @@ -270,7 +269,7 @@ public TypeDeclarationDescr visitTypeDeclaration(DRLParser.TypeDeclarationContex } @Override - public EnumDeclarationDescr visitEnumDeclaration(DRLParser.EnumDeclarationContext ctx) { + public EnumDeclarationDescr visitEnumDeclaration(DRL10Parser.EnumDeclarationContext ctx) { EnumDeclarationDescr enumDeclarationDescr = BaseDescrFactory.builder(new EnumDeclarationDescr()) .withParserRuleContext(ctx) .withResource(resource) @@ -295,7 +294,7 @@ public EnumDeclarationDescr visitEnumDeclaration(DRLParser.EnumDeclarationContex } @Override - public EnumLiteralDescr visitEnumerative(DRLParser.EnumerativeContext ctx) { + public EnumLiteralDescr visitEnumerative(DRL10Parser.EnumerativeContext ctx) { EnumLiteralDescr enumLiteralDescr = BaseDescrFactory.builder(new EnumLiteralDescr(ctx.drlIdentifier().getText())) .withParserRuleContext(ctx) .withResource(resource) @@ -307,7 +306,7 @@ public EnumLiteralDescr visitEnumerative(DRLParser.EnumerativeContext ctx) { } @Override - public EntryPointDeclarationDescr visitEntryPointDeclaration(DRLParser.EntryPointDeclarationContext ctx) { + public EntryPointDeclarationDescr visitEntryPointDeclaration(DRL10Parser.EntryPointDeclarationContext ctx) { EntryPointDeclarationDescr entryPointDeclarationDescr = BaseDescrFactory.builder(new EntryPointDeclarationDescr()) .withParserRuleContext(ctx) .withResource(resource) @@ -320,7 +319,7 @@ public EntryPointDeclarationDescr visitEntryPointDeclaration(DRLParser.EntryPoin } @Override - public WindowDeclarationDescr visitWindowDeclaration(DRLParser.WindowDeclarationContext ctx) { + public WindowDeclarationDescr visitWindowDeclaration(DRL10Parser.WindowDeclarationContext ctx) { WindowDeclarationDescr windowDeclarationDescr = BaseDescrFactory.builder(new WindowDeclarationDescr()) .withParserRuleContext(ctx) .withResource(resource) @@ -337,7 +336,7 @@ public WindowDeclarationDescr visitWindowDeclaration(DRLParser.WindowDeclaration * entry point for one rule */ @Override - public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { + public RuleDescr visitRuledef(DRL10Parser.RuledefContext ctx) { RuleDescr ruleDescr = BaseDescrFactory.builder(new RuleDescr(safeStripStringDelimiters(ctx.name.getText()))) .withParserRuleContext(ctx) .withResource(resource) @@ -398,15 +397,15 @@ public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { } @Override - public QueryDescr visitQuerydef(DRLParser.QuerydefContext ctx) { + public QueryDescr visitQuerydef(DRL10Parser.QuerydefContext ctx) { QueryDescr queryDescr = BaseDescrFactory.builder(new QueryDescr(safeStripStringDelimiters(ctx.name.getText()))) .withParserRuleContext(ctx) .withResource(resource) .build(); - DRLParser.ParametersContext parametersContext = ctx.parameters(); + DRL10Parser.ParametersContext parametersContext = ctx.parameters(); if (parametersContext != null) { - List parameterContexts = parametersContext.parameter(); + List parameterContexts = parametersContext.parameter(); parameterContexts.forEach(parameterContext -> { String type = parameterContext.type() != null ? parameterContext.type().getText() : "Object"; // default type is Object String name = parameterContext.drlIdentifier().getText(); @@ -425,7 +424,7 @@ public QueryDescr visitQuerydef(DRLParser.QuerydefContext ctx) { } @Override - public AnnotationDescr visitDrlAnnotation(DRLParser.DrlAnnotationContext ctx) { + public AnnotationDescr visitDrlAnnotation(DRL10Parser.DrlAnnotationContext ctx) { // Full Java-style annotation. if (ctx.anno != null) { if (ctx.anno.result == null) { @@ -449,7 +448,7 @@ public AnnotationDescr visitDrlAnnotation(DRLParser.DrlAnnotationContext ctx) { } @Override - public TypeFieldDescr visitField(DRLParser.FieldContext ctx) { + public TypeFieldDescr visitField(DRL10Parser.FieldContext ctx) { TypeFieldDescr typeFieldDescr = BaseDescrFactory.builder(new TypeFieldDescr()) .withParserRuleContext(ctx) .withResource(resource) @@ -466,7 +465,7 @@ public TypeFieldDescr visitField(DRLParser.FieldContext ctx) { } @Override - public AttributeDescr visitExpressionAttribute(DRLParser.ExpressionAttributeContext ctx) { + public AttributeDescr visitExpressionAttribute(DRL10Parser.ExpressionAttributeContext ctx) { AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) .withParserRuleContext(ctx) .withResource(resource) @@ -477,7 +476,7 @@ public AttributeDescr visitExpressionAttribute(DRLParser.ExpressionAttributeCont } @Override - public AttributeDescr visitBooleanAttribute(DRLParser.BooleanAttributeContext ctx) { + public AttributeDescr visitBooleanAttribute(DRL10Parser.BooleanAttributeContext ctx) { AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) .withParserRuleContext(ctx) .withResource(resource) @@ -488,7 +487,7 @@ public AttributeDescr visitBooleanAttribute(DRLParser.BooleanAttributeContext ct } @Override - public AttributeDescr visitStringAttribute(DRLParser.StringAttributeContext ctx) { + public AttributeDescr visitStringAttribute(DRL10Parser.StringAttributeContext ctx) { AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) .withParserRuleContext(ctx) .withResource(resource) @@ -499,7 +498,7 @@ public AttributeDescr visitStringAttribute(DRLParser.StringAttributeContext ctx) } @Override - public AttributeDescr visitStringListAttribute(DRLParser.StringListAttributeContext ctx) { + public AttributeDescr visitStringListAttribute(DRL10Parser.StringListAttributeContext ctx) { AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) .withParserRuleContext(ctx) .withResource(resource) @@ -526,7 +525,7 @@ private static String createStringList(List valueList) { } @Override - public AttributeDescr visitIntOrChunkAttribute(DRLParser.IntOrChunkAttributeContext ctx) { + public AttributeDescr visitIntOrChunkAttribute(DRL10Parser.IntOrChunkAttributeContext ctx) { AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) .withParserRuleContext(ctx) .withResource(resource) @@ -545,7 +544,7 @@ public AttributeDescr visitIntOrChunkAttribute(DRLParser.IntOrChunkAttributeCont * entry point for LHS */ @Override - public List visitLhs(DRLParser.LhsContext ctx) { + public List visitLhs(DRL10Parser.LhsContext ctx) { if (ctx.lhsExpression() != null) { return visitDescrChildren(ctx); } else { @@ -554,7 +553,7 @@ public List visitLhs(DRLParser.LhsContext ctx) { } @Override - public BaseDescr visitLhsPatternBind(DRLParser.LhsPatternBindContext ctx) { + public BaseDescr visitLhsPatternBind(DRL10Parser.LhsPatternBindContext ctx) { if (ctx.lhsPattern().size() == 1) { return getSinglePatternDescr(ctx); } else if (ctx.lhsPattern().size() > 1) { @@ -564,7 +563,7 @@ public BaseDescr visitLhsPatternBind(DRLParser.LhsPatternBindContext ctx) { } } - private PatternDescr getSinglePatternDescr(DRLParser.LhsPatternBindContext ctx) { + private PatternDescr getSinglePatternDescr(DRL10Parser.LhsPatternBindContext ctx) { List patternDescrList = visitDescrChildren(ctx); if (patternDescrList.isEmpty() || !(patternDescrList.get(0) instanceof PatternDescr)) { throw new IllegalStateException("lhsPatternBind must have at least one lhsPattern : " + ctx.getText()); @@ -581,7 +580,7 @@ private PatternDescr getSinglePatternDescr(DRLParser.LhsPatternBindContext ctx) return patternDescr; } - private OrDescr getOrDescrWithMultiplePatternDescr(DRLParser.LhsPatternBindContext ctx) { + private OrDescr getOrDescrWithMultiplePatternDescr(DRL10Parser.LhsPatternBindContext ctx) { OrDescr orDescr = BaseDescrFactory.builder(new OrDescr()) .withParserRuleContext(ctx) .withResource(resource) @@ -604,7 +603,7 @@ private OrDescr getOrDescrWithMultiplePatternDescr(DRLParser.LhsPatternBindConte * entry point for a Pattern */ @Override - public PatternDescr visitLhsPattern(DRLParser.LhsPatternContext ctx) { + public PatternDescr visitLhsPattern(DRL10Parser.LhsPatternContext ctx) { if (ctx.xpathPrimary() != null) { String constraint = visitConstraintChildren(ctx); ExprConstraintDescr constraintDescr = BaseDescrFactory.builder(new ExprConstraintDescr(constraint)) @@ -649,7 +648,7 @@ private void addToPatternDescr(PatternDescr patternDescr, ExprConstraintDescr ex } @Override - public NamedConsequenceDescr visitNamedConsequenceInvocation(DRLParser.NamedConsequenceInvocationContext ctx) { + public NamedConsequenceDescr visitNamedConsequenceInvocation(DRL10Parser.NamedConsequenceInvocationContext ctx) { NamedConsequenceDescr namedConsequenceDescr = BaseDescrFactory.builder(new NamedConsequenceDescr(ctx.drlIdentifier().getText())) .withParserRuleContext(ctx) .withResource(resource) @@ -658,7 +657,7 @@ public NamedConsequenceDescr visitNamedConsequenceInvocation(DRLParser.NamedCons } @Override - public NamedConsequenceDescr visitBreakingNamedConsequenceInvocation(DRLParser.BreakingNamedConsequenceInvocationContext ctx) { + public NamedConsequenceDescr visitBreakingNamedConsequenceInvocation(DRL10Parser.BreakingNamedConsequenceInvocationContext ctx) { NamedConsequenceDescr namedConsequenceDescr = BaseDescrFactory.builder(new NamedConsequenceDescr(ctx.drlIdentifier().getText())) .withParserRuleContext(ctx) .withResource(resource) @@ -675,7 +674,7 @@ public NamedConsequenceDescr visitBreakingNamedConsequenceInvocation(DRLParser.B * into a ConditionalBranchDescr */ @Override - public ConditionalBranchDescr visitConditionalBranch(DRLParser.ConditionalBranchContext ctx) { + public ConditionalBranchDescr visitConditionalBranch(DRL10Parser.ConditionalBranchContext ctx) { ConditionalBranchDescr conditionalBranchDescr = BaseDescrFactory.builder(new ConditionalBranchDescr()) .withParserRuleContext(ctx) .withResource(resource) @@ -723,7 +722,7 @@ public ConditionalBranchDescr visitConditionalBranch(DRLParser.ConditionalBranch } @Override - public ForallDescr visitLhsForall(DRLParser.LhsForallContext ctx) { + public ForallDescr visitLhsForall(DRL10Parser.LhsForallContext ctx) { ForallDescr forallDescr = BaseDescrFactory.builder(new ForallDescr()) .withParserRuleContext(ctx) .withResource(resource) @@ -733,7 +732,7 @@ public ForallDescr visitLhsForall(DRLParser.LhsForallContext ctx) { } @Override - public PatternDescr visitLhsAccumulate(DRLParser.LhsAccumulateContext ctx) { + public PatternDescr visitLhsAccumulate(DRL10Parser.LhsAccumulateContext ctx) { AccumulateDescr accumulateDescr = BaseDescrFactory.builder(new AccumulateDescr()) .withParserRuleContext(ctx) .withResource(resource) @@ -742,7 +741,7 @@ public PatternDescr visitLhsAccumulate(DRLParser.LhsAccumulateContext ctx) { accumulateDescr.setInput(wrapWithAndDescr(visitLhsAndDef(ctx.lhsAndDef()), ctx.lhsAndDef())); // accumulate function - for (DRLParser.AccumulateFunctionContext accumulateFunctionContext : ctx.accumulateFunction()) { + for (DRL10Parser.AccumulateFunctionContext accumulateFunctionContext : ctx.accumulateFunction()) { accumulateDescr.addFunction(visitAccumulateFunction(accumulateFunctionContext)); } @@ -769,7 +768,7 @@ private AndDescr wrapWithAndDescr(BaseDescr baseDescr, ParserRuleContext ctx) { } @Override - public Object visitLhsGroupBy(DRLParser.LhsGroupByContext ctx) { + public Object visitLhsGroupBy(DRL10Parser.LhsGroupByContext ctx) { GroupByDescr groupByDescr = BaseDescrFactory.builder(new GroupByDescr()) .withParserRuleContext(ctx) .withResource(resource) @@ -782,7 +781,7 @@ public Object visitLhsGroupBy(DRLParser.LhsGroupByContext ctx) { groupByDescr.setGroupingFunction(getTextPreservingWhitespace(ctx.groupByKeyBinding().conditionalExpression())); // accumulate function - for (DRLParser.AccumulateFunctionContext accumulateFunctionContext : ctx.accumulateFunction()) { + for (DRL10Parser.AccumulateFunctionContext accumulateFunctionContext : ctx.accumulateFunction()) { groupByDescr.addFunction(visitAccumulateFunction(accumulateFunctionContext)); } @@ -797,21 +796,21 @@ public Object visitLhsGroupBy(DRLParser.LhsGroupByContext ctx) { } @Override - public BehaviorDescr visitPatternFilter(DRLParser.PatternFilterContext ctx) { + public BehaviorDescr visitPatternFilter(DRL10Parser.PatternFilterContext ctx) { BehaviorDescr behaviorDescr = BaseDescrFactory.builder(new BehaviorDescr()) .withParserRuleContext(ctx) .withResource(resource) .build(); behaviorDescr.setType(ctx.DRL_WINDOW().getText()); behaviorDescr.setSubType(ctx.drlIdentifier().getText()); - List expressionContexts = ctx.expressionList().expression(); + List expressionContexts = ctx.expressionList().expression(); List parameters = expressionContexts.stream().map(Antlr4ParserStringUtils::getTextPreservingWhitespace).collect(Collectors.toList()); behaviorDescr.setParameters(parameters); return behaviorDescr; } @Override - public FromDescr visitFromExpression(DRLParser.FromExpressionContext ctx) { + public FromDescr visitFromExpression(DRL10Parser.FromExpressionContext ctx) { FromDescr fromDescr = BaseDescrFactory.builder(new FromDescr()) .withParserRuleContext(ctx) .withResource(resource) @@ -821,7 +820,7 @@ public FromDescr visitFromExpression(DRLParser.FromExpressionContext ctx) { } @Override - public CollectDescr visitFromCollect(DRLParser.FromCollectContext ctx) { + public CollectDescr visitFromCollect(DRL10Parser.FromCollectContext ctx) { CollectDescr collectDescr = BaseDescrFactory.builder(new CollectDescr()) .withParserRuleContext(ctx) .withResource(resource) @@ -831,7 +830,7 @@ public CollectDescr visitFromCollect(DRLParser.FromCollectContext ctx) { } @Override - public AccumulateDescr visitFromAccumulate(DRLParser.FromAccumulateContext ctx) { + public AccumulateDescr visitFromAccumulate(DRL10Parser.FromAccumulateContext ctx) { AccumulateDescr accumulateDescr = BaseDescrFactory.builder(new AccumulateDescr()) .withParserRuleContext(ctx) .withResource(resource) @@ -854,7 +853,7 @@ public AccumulateDescr visitFromAccumulate(DRLParser.FromAccumulateContext ctx) } @Override - public AccumulateDescr.AccumulateFunctionCallDescr visitAccumulateFunction(DRLParser.AccumulateFunctionContext ctx) { + public AccumulateDescr.AccumulateFunctionCallDescr visitAccumulateFunction(DRL10Parser.AccumulateFunctionContext ctx) { String function = ctx.drlIdentifier().getText(); String bind = null; boolean unify = false; @@ -872,7 +871,7 @@ public AccumulateDescr.AccumulateFunctionCallDescr visitAccumulateFunction(DRLPa } @Override - public EntryPointDescr visitFromEntryPoint(DRLParser.FromEntryPointContext ctx) { + public EntryPointDescr visitFromEntryPoint(DRL10Parser.FromEntryPointContext ctx) { return BaseDescrFactory.builder(new EntryPointDescr(safeStripStringDelimiters(ctx.stringId().getText()))) .withParserRuleContext(ctx) .withResource(resource) @@ -880,7 +879,7 @@ public EntryPointDescr visitFromEntryPoint(DRLParser.FromEntryPointContext ctx) } @Override - public WindowReferenceDescr visitFromWindow(DRLParser.FromWindowContext ctx) { + public WindowReferenceDescr visitFromWindow(DRL10Parser.FromWindowContext ctx) { return BaseDescrFactory.builder(new WindowReferenceDescr(ctx.drlIdentifier().getText())) .withParserRuleContext(ctx) .withResource(resource) @@ -891,7 +890,7 @@ public WindowReferenceDescr visitFromWindow(DRLParser.FromWindowContext ctx) { * Collect constraints in a Pattern */ @Override - public List visitConstraints(DRLParser.ConstraintsContext ctx) { + public List visitConstraints(DRL10Parser.ConstraintsContext ctx) { List exprConstraintDescrList = new ArrayList<>(); populateExprConstraintDescrList(ctx, exprConstraintDescrList); return exprConstraintDescrList; @@ -900,7 +899,7 @@ public List visitConstraints(DRLParser.ConstraintsContext c /** * Collect constraints in a Pattern. Positional constraints comes first with semicolon. */ - private List visitConstraints(DRLParser.PositionalConstraintsContext positionalCtx, DRLParser.ConstraintsContext ctx) { + private List visitConstraints(DRL10Parser.PositionalConstraintsContext positionalCtx, DRL10Parser.ConstraintsContext ctx) { List exprConstraintDescrList = new ArrayList<>(); populateExprConstraintDescrList(positionalCtx, exprConstraintDescrList); populateExprConstraintDescrList(ctx, exprConstraintDescrList); @@ -915,7 +914,7 @@ private void populateExprConstraintDescrList(ParserRuleContext ctx, List visitConstraint(DRLParser.ConstraintContext ctx) { + public List visitConstraint(DRL10Parser.ConstraintContext ctx) { List descrList = new ArrayList<>(); if (ctx.nestedConstraint() != null) { // nested constraint requires special string manipulation @@ -955,7 +954,7 @@ public List visitConstraint(DRLParser.ConstraintContext ctx * address.city.startsWith("I"), address.city.length() == 5 */ @Override - public List visitNestedConstraint(DRLParser.NestedConstraintContext ctx) { + public List visitNestedConstraint(DRL10Parser.NestedConstraintContext ctx) { Token prefixStartToken = ctx.start; Token prefixEndToken = tokenStream.get(ctx.LPAREN().getSymbol().getTokenIndex() - 1); String prefix = tokenStream.getText(prefixStartToken, prefixEndToken); @@ -965,12 +964,12 @@ public List visitNestedConstraint(DRLParser.NestedConstrain } @Override - public String visitDrlIdentifier(DRLParser.DrlIdentifierContext ctx) { + public String visitDrlIdentifier(DRL10Parser.DrlIdentifierContext ctx) { return ctx.getText(); } @Override - public ExistsDescr visitLhsExists(DRLParser.LhsExistsContext ctx) { + public ExistsDescr visitLhsExists(DRL10Parser.LhsExistsContext ctx) { ExistsDescr existsDescr = BaseDescrFactory.builder(new ExistsDescr()) .withParserRuleContext(ctx) .withResource(resource) @@ -992,7 +991,7 @@ public ExistsDescr visitLhsExists(DRLParser.LhsExistsContext ctx) { } @Override - public NotDescr visitLhsNot(DRLParser.LhsNotContext ctx) { + public NotDescr visitLhsNot(DRL10Parser.LhsNotContext ctx) { NotDescr notDescr = BaseDescrFactory.builder(new NotDescr()) .withParserRuleContext(ctx) .withResource(resource) @@ -1014,7 +1013,7 @@ public NotDescr visitLhsNot(DRLParser.LhsNotContext ctx) { } @Override - public EvalDescr visitLhsEval(DRLParser.LhsEvalContext ctx) { + public EvalDescr visitLhsEval(DRL10Parser.LhsEvalContext ctx) { return BaseDescrFactory.builder(new EvalDescr(getTextPreservingWhitespace(ctx.conditionalOrExpression()))) .withParserRuleContext(ctx) .withResource(resource) @@ -1022,13 +1021,13 @@ public EvalDescr visitLhsEval(DRLParser.LhsEvalContext ctx) { } @Override - public List visitLhsExpressionEnclosed(DRLParser.LhsExpressionEnclosedContext ctx) { + public List visitLhsExpressionEnclosed(DRL10Parser.LhsExpressionEnclosedContext ctx) { // enclosed expression is simply stripped because Descr itself is encapsulated return visitDescrChildren(ctx); } @Override - public BaseDescr visitLhsOr(DRLParser.LhsOrContext ctx) { + public BaseDescr visitLhsOr(DRL10Parser.LhsOrContext ctx) { // For flatten nested OrDescr logic, we call visitDescrChildrenForDescrNodePair instead of usual visitDescrChildren List descrList = visitDescrChildrenForDescrNodePair(ctx); if (descrList.size() == 1) { @@ -1064,7 +1063,7 @@ private List flattenOrDescr(List descrList) { for (DescrNodePair descrNodePair : descrList) { BaseDescr descr = descrNodePair.getDescr(); ParseTree node = descrNodePair.getNode(); // parser node corresponding to the descr - if (descr instanceof OrDescr orDescr && !(node instanceof DRLParser.LhsExpressionEnclosedContext)) { + if (descr instanceof OrDescr orDescr && !(node instanceof DRL10Parser.LhsExpressionEnclosedContext)) { // sibling OrDescr should be flattened unless it's explicitly enclosed by parenthesis flattenedDescrs.addAll(orDescr.getDescrs()); flattenedDescrs.addAll(orDescr.getAnnotations()); @@ -1076,7 +1075,7 @@ private List flattenOrDescr(List descrList) { } @Override - public BaseDescr visitLhsAnd(DRLParser.LhsAndContext ctx) { + public BaseDescr visitLhsAnd(DRL10Parser.LhsAndContext ctx) { return createAndDescr(ctx); } @@ -1116,7 +1115,7 @@ private List flattenAndDescr(List descrList) { for (DescrNodePair descrNodePair : descrList) { BaseDescr descr = descrNodePair.getDescr(); ParseTree node = descrNodePair.getNode(); // parser node corresponding to the descr - if (descr instanceof AndDescr andDescr && !(node instanceof DRLParser.LhsExpressionEnclosedContext)) { + if (descr instanceof AndDescr andDescr && !(node instanceof DRL10Parser.LhsExpressionEnclosedContext)) { // sibling AndDescr should be flattened unless it's explicitly enclosed by parenthesis flattenedDescrs.addAll(andDescr.getDescrs()); flattenedDescrs.addAll(andDescr.getAnnotations()); @@ -1128,12 +1127,12 @@ private List flattenAndDescr(List descrList) { } @Override - public BaseDescr visitLhsAndDef(DRLParser.LhsAndDefContext ctx) { + public BaseDescr visitLhsAndDef(DRL10Parser.LhsAndDefContext ctx) { return createAndDescr(ctx); } @Override - public BaseDescr visitLhsUnary(DRLParser.LhsUnaryContext ctx) { + public BaseDescr visitLhsUnary(DRL10Parser.LhsUnaryContext ctx) { List children = visitDescrChildren(ctx); if (children.size() > 1) { // lhsUnary may have multiple children e.g. consequenceInvocation, connect with AND diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DescrHelper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DescrHelper.java index 02a4f38d276..3add771b360 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DescrHelper.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DescrHelper.java @@ -81,7 +81,7 @@ public static T populateCommonProperties(T descr, List recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { - helper.reportError(offendingSymbol, line, charPositionInLine, msg, e); - } - }); - parser.setBuildDescr(true); - parser.setLeftMostExpr(null); // setting initial value just in case - BaseDescr expr = parser.conditionalOrExpressionDescr(); - if (expr != null && !parser.hasErrors()) { - constraint = ConstraintConnectiveDescr.newAnd(); - constraint.addOrMerge(expr); + DRL10Lexer lexer = new DRL10Lexer(CharStreams.fromString(text)); + CommonTokenStream input = new CommonTokenStream(lexer); + helper = new ParserHelper(input, languageLevel); + DRL10Expressions parser = new DRL10Expressions(input); + parser.setHelper(helper); + parser.addErrorListener(new BaseErrorListener() { + @Override + public void syntaxError(Recognizer recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { + helper.reportError(offendingSymbol, line, charPositionInLine, msg, e); } + }); + parser.setBuildDescr(true); + parser.setLeftMostExpr(null); // setting initial value just in case + BaseDescr expr = parser.conditionalOrExpressionDescr(); + if (expr != null && !parser.hasErrors()) { + constraint = ConstraintConnectiveDescr.newAnd(); + constraint.addOrMerge(expr); + } return constraint; } diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/session/UpdateTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/session/UpdateTest.java index 24a89fcf07d..32c7c8c794a 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/session/UpdateTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/session/UpdateTest.java @@ -23,6 +23,7 @@ import java.util.List; import java.util.stream.Stream; +import org.drools.drl.parser.DrlParser; import org.drools.mvel.compiler.Address; import org.drools.mvel.compiler.Asset; import org.drools.mvel.compiler.AssetCard; @@ -46,6 +47,7 @@ import org.kie.api.command.Setter; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; +import org.kie.internal.builder.conf.LanguageLevelOption; import org.kie.internal.command.CommandFactory; import static org.assertj.core.api.Assertions.assertThat; diff --git a/kie-internal/src/main/java/org/kie/internal/builder/conf/LanguageLevelOption.java b/kie-internal/src/main/java/org/kie/internal/builder/conf/LanguageLevelOption.java index ca8b96ee91a..86266a0f2d3 100644 --- a/kie-internal/src/main/java/org/kie/internal/builder/conf/LanguageLevelOption.java +++ b/kie-internal/src/main/java/org/kie/internal/builder/conf/LanguageLevelOption.java @@ -25,7 +25,7 @@ */ public enum LanguageLevelOption implements SingleValueRuleBuilderOption { - DRL5(false), DRL6(false), DRL6_STRICT(true); + DRL5(false), DRL6(false), DRL6_STRICT(true), DRL10(false); private final boolean useJavaAnnotations; From 5c771cc51ad1b57eedd5719985d316f082fb3c32 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Tue, 21 Jan 2025 18:17:16 +0900 Subject: [PATCH 2/8] - for GHA test --- .github/workflows/pr-downstream.yml | 1 + .github/workflows/pr-drools.yml | 2 +- .../src/test/resources/logback-test.xml | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pr-downstream.yml b/.github/workflows/pr-downstream.yml index 575f4ec6dfe..fbccd515f42 100644 --- a/.github/workflows/pr-downstream.yml +++ b/.github/workflows/pr-downstream.yml @@ -33,6 +33,7 @@ on: jobs: kogito-downstream-build: + if: false concurrency: group: pr-${{ matrix.job_name }}_${{ matrix.os }}_${{ matrix.java-version }}_${{ matrix.maven-version }}_${{ github.head_ref }} cancel-in-progress: true diff --git a/.github/workflows/pr-drools.yml b/.github/workflows/pr-drools.yml index d1f5f77b4f7..ed666b8d8a9 100644 --- a/.github/workflows/pr-drools.yml +++ b/.github/workflows/pr-drools.yml @@ -61,7 +61,7 @@ jobs: - name: Build Chain uses: apache/incubator-kie-kogito-pipelines/.ci/actions/build-chain@main env: - BUILD_MVN_OPTS_CURRENT: '-Dfull -Dreproducible' + BUILD_MVN_OPTS_CURRENT: '-Dfull -Dreproducible -DenableNewParser' MAVEN_OPTS: "-Dfile.encoding=UTF-8" with: definition-file: https://raw.githubusercontent.com/${GROUP:apache}/incubator-kie-kogito-pipelines/${BRANCH:main}/.ci/pull-request-config.yaml diff --git a/drools-test-coverage/test-compiler-integration/src/test/resources/logback-test.xml b/drools-test-coverage/test-compiler-integration/src/test/resources/logback-test.xml index 715224c2777..c9f0d046a07 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/resources/logback-test.xml +++ b/drools-test-coverage/test-compiler-integration/src/test/resources/logback-test.xml @@ -34,7 +34,7 @@ - + From 65a52d548668f397b12baef3a6c625ef8d2a2c46 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Wed, 22 Jan 2025 17:53:26 +0900 Subject: [PATCH 3/8] - a prefix for custom operator --- .../drools/drl/ast/descr/OperatorDescr.java | 13 +- .../drl/parser/antlr4/DRLExprParserTest.java | 2 +- .../drl/parser/antlr4/MiscDRLParserTest.java | 34 ++- .../drl/parser/antlr4/ParserTestUtils.java | 7 - .../drl/parser/antlr4/DRL10Expressions.g4 | 5 +- .../drools/drl/parser/antlr4/DRL10Lexer.g4 | 2 + .../java/org/drools/drl/parser/DrlParser.java | 4 +- .../org/drools/mvel/parser/TokenTypes.java | 1 + .../src/main/javacc/mvel.jj | 2 + .../CustomOperatorOnlyDrlTest.java | 5 +- .../integrationtests/CustomOperatorTest.java | 24 +- .../mvel/integrationtests/Misc2Test.java | 4 +- .../traits/compiler/CommonTraitTest.java | 44 +++- .../factmodel/traits/LegacyTraitTest.java | 13 +- .../factmodel/traits/LogicalTraitTest.java | 75 +----- .../TraitFieldsAndLegacyClassesTest.java | 2 +- .../compiler/factmodel/traits/TraitTest.java | 248 +++--------------- .../TraitTypeGenerationTest.java | 72 +---- 18 files changed, 176 insertions(+), 381 deletions(-) diff --git a/drools-drl/drools-drl-ast/src/main/java/org/drools/drl/ast/descr/OperatorDescr.java b/drools-drl/drools-drl-ast/src/main/java/org/drools/drl/ast/descr/OperatorDescr.java index 561bebe19a0..aa052e8632f 100644 --- a/drools-drl/drools-drl-ast/src/main/java/org/drools/drl/ast/descr/OperatorDescr.java +++ b/drools-drl/drools-drl-ast/src/main/java/org/drools/drl/ast/descr/OperatorDescr.java @@ -26,6 +26,9 @@ public class OperatorDescr extends BaseDescr { private static final long serialVersionUID = 520l; + // prefix for custom operators which are not built-in + public static final String CUSTOM_OPERATOR_PREFIX = "##"; + private String operator; private boolean negated; private List parameters; @@ -55,7 +58,15 @@ public String getOperator() { } public void setOperator( String operator ) { - this.operator = operator != null ? operator.trim() : null; + this.operator = operator != null ? trimOperator(operator) : null; + } + + private String trimOperator(String operator) { + operator = operator.trim(); + if (operator.startsWith(CUSTOM_OPERATOR_PREFIX)) { + operator = operator.substring(CUSTOM_OPERATOR_PREFIX.length()); + } + return operator; } public boolean isNegated() { diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLExprParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLExprParserTest.java index 24ab2cabe2a..8cbebe73e6d 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLExprParserTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLExprParserTest.java @@ -458,7 +458,7 @@ void noViableAlt() { assertThat(exception.getColumn()).isEqualTo(2); assertThat(exception.getOffset()).isEqualTo(2); assertThat(exception.getMessage()) - .isEqualToIgnoringCase("[ERR 101] Line 1:2 no viable alternative at input 'a'"); + .isEqualToIgnoringCase("[ERR 101] Line 1:2 no viable alternative at input '~a'"); } else { assertThat(parser.hasErrors()).isFalse(); } diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java index 3fc2cdbca39..56fbfe11152 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java @@ -74,8 +74,8 @@ import org.drools.drl.parser.DroolsParserException; import org.drools.drl.parser.impl.Operator; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIf; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -95,6 +95,14 @@ void setUp() { parser = ParserTestUtils.getParser(); } + private static boolean isNewParser() { + return DrlParser.ANTLR4_PARSER_ENABLED; + } + + private static boolean isOldParser() { + return !DrlParser.ANTLR4_PARSER_ENABLED; + } + private String readResource(final String filename) { Path path; try { @@ -4411,8 +4419,9 @@ void traitExtendsMultiple() { .containsExactlyInAnyOrder("com.sample.ParentTrait", "UncleTrait", "org.test.GrandParentTrait"); } + @EnabledIf("isOldParser") @Test - void pluggableEvaluator() { + void pluggableEvaluatorOldParser() { final String source = "package org.drools\n" + "rule R\n" + "when\n" + @@ -4431,6 +4440,27 @@ void pluggableEvaluator() { .containsExactly("$c : core", "this not isA t.x.E.class", "this isA t.x.D.class"); } + @EnabledIf("isNewParser") + @Test + void pluggableEvaluatorNewParser() { + final String source = "package org.drools\n" + + "rule R\n" + + "when\n" + + " $t : Thing( $c : core, this not ##isA t.x.E.class, this ##isA t.x.D.class )\n" + + "then\n" + + " list.add( \"E\" ); \n" + + " don( $t, E.class ); \n" + + "end\n"; + + Operator.addOperatorToRegistry("isA", false); + Operator.addOperatorToRegistry("isA", true); + + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(source).getLhs().getDescrs().get(0); + assertThat(pattern.getConstraint().getDescrs()) + .extracting(Object::toString) + .containsExactly("$c : core", "this not ##isA t.x.E.class", "this ##isA t.x.D.class"); + } + @Test void namedConsequenceDo() { final String text = diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/ParserTestUtils.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/ParserTestUtils.java index c7325329466..87e4de894a7 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/ParserTestUtils.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/ParserTestUtils.java @@ -66,13 +66,6 @@ public static DrlExprParser getExprParser() { } } - /** - * Enables the old parser. Just for quick testing purposes. - */ - public static void enableOldParser() { - DrlParser.ANTLR4_PARSER_ENABLED = false; - } - public static List javaKeywords() { return javaKeywords; } diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Expressions.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Expressions.g4 index b940e2e6d70..7a4c807fcb7 100644 --- a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Expressions.g4 +++ b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Expressions.g4 @@ -1000,12 +1000,11 @@ in_key ; operator_key - // IDENTIFIER is required to accept custom operators. We need to keep this semantic predicate for custom operators - : {(helper.isPluggableEvaluator(false))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + : DRL_CUSTOM_OPERATOR_PREFIX {(helper.isPluggableEvaluator(false))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } | op=builtInOperator { helper.emit($op.token, DroolsEditorType.KEYWORD); } ; neg_operator_key - : {(helper.isPluggableEvaluator(true))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + : DRL_CUSTOM_OPERATOR_PREFIX {(helper.isPluggableEvaluator(true))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } | op=builtInOperator { helper.emit($op.token, DroolsEditorType.KEYWORD); } ; diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Lexer.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Lexer.g4 index 22570d9b4a8..6ef44add5fd 100644 --- a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Lexer.g4 +++ b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Lexer.g4 @@ -125,6 +125,8 @@ DRL_CALENDARS : 'calendars'; DRL_TIMER : 'timer'; DRL_DURATION : 'duration'; +DRL_CUSTOM_OPERATOR_PREFIX : '##' ; + ///////////////// // LEXER ///////////////// diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlParser.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlParser.java index 977232eb8cb..1995b08668a 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlParser.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlParser.java @@ -62,8 +62,8 @@ public class DrlParser { public static final String ANTLR4_PARSER_ENABLED_PROPERTY = "drools.drl.antlr4.parser.enabled"; - // temporarily removed 'final' for testing purposes. This should be final when the feature gets stable - public static boolean ANTLR4_PARSER_ENABLED = Boolean.parseBoolean(System.getProperty(ANTLR4_PARSER_ENABLED_PROPERTY, "false")); // default is false + // for test purpose + public static final boolean ANTLR4_PARSER_ENABLED = Boolean.parseBoolean(System.getProperty(ANTLR4_PARSER_ENABLED_PROPERTY, "false")); // default is false public static final LanguageLevelOption DEFAULT_LANGUAGE_LEVEL = ANTLR4_PARSER_ENABLED ? LanguageLevelOption.DRL10 : LanguageLevelOption.DRL6; private final LanguageLevelOption languageLevel; diff --git a/drools-model/drools-mvel-parser/src/main/java/org/drools/mvel/parser/TokenTypes.java b/drools-model/drools-mvel-parser/src/main/java/org/drools/mvel/parser/TokenTypes.java index fc5805813d3..7a478ed270c 100644 --- a/drools-model/drools-mvel-parser/src/main/java/org/drools/mvel/parser/TokenTypes.java +++ b/drools-model/drools-mvel-parser/src/main/java/org/drools/mvel/parser/TokenTypes.java @@ -213,6 +213,7 @@ public static JavaToken.Category getCategory(int kind) { case COMMA: case DOT: case AT: + case CUSTOM_OPERATOR_PREFIX: return JavaToken.Category.SEPARATOR; case MVEL_STARTS_WITH: case MVEL_ENDS_WITH: diff --git a/drools-model/drools-mvel-parser/src/main/javacc/mvel.jj b/drools-model/drools-mvel-parser/src/main/javacc/mvel.jj index d4752e980d5..3312b597e06 100644 --- a/drools-model/drools-mvel-parser/src/main/javacc/mvel.jj +++ b/drools-model/drools-mvel-parser/src/main/javacc/mvel.jj @@ -425,6 +425,7 @@ TOKEN : | < MVEL_ENDS_WITH: "str[endsWith]" > | < MVEL_LENGTH: "str[length]" > | < DOT_DOT_SLASH: "../" > +| < CUSTOM_OPERATOR_PREFIX: "##" > | < HASHMARK: "#" > | < EXCL_DOT: "!." > | < PASSIVE_OOPATH: "?/" > @@ -6419,6 +6420,7 @@ Expression PointFreeExpr(): { negated = true; } )* ( + [ ] operator = SimpleName() temporalLiteralArguments = TemporalLiteralArguments() ( diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CustomOperatorOnlyDrlTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CustomOperatorOnlyDrlTest.java index d6835f92ab5..6f4404618a7 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CustomOperatorOnlyDrlTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CustomOperatorOnlyDrlTest.java @@ -26,6 +26,7 @@ import org.drools.base.base.ValueResolver; import org.drools.base.base.ValueType; import org.drools.compiler.rule.builder.EvaluatorDefinition; +import org.drools.drl.parser.DrlParser; import org.drools.drl.parser.impl.Operator; import org.drools.base.rule.accessor.Evaluator; import org.drools.base.rule.accessor.FieldValue; @@ -42,6 +43,8 @@ public class CustomOperatorOnlyDrlTest { + private static final String F_STR = DrlParser.ANTLR4_PARSER_ENABLED ? "##F_str" : "F_str"; + public static Stream parameters() { // TODO EM DROOLS-6302 return TestParametersUtil2.getKieBaseCloudConfigurations(false).stream(); @@ -74,7 +77,7 @@ public void testCustomOperatorCombiningConstraints(KieBaseTestConfiguration kieB "when\n" + " gnId : GN()\n" + " la : t547147( )\n" + - " v1717 : Tra48( gnId.gNo == gNo, name F_str[startsWith] la.c547148 || postCode F_str[contains] la.c547149 )\n" + + " v1717 : Tra48( gnId.gNo == gNo, name " + F_STR + "[startsWith] la.c547148 || postCode " + F_STR + "[contains] la.c547149 )\n" + "then\n" + "end\n"; diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CustomOperatorTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CustomOperatorTest.java index 0161f772935..5295b801e20 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CustomOperatorTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CustomOperatorTest.java @@ -27,6 +27,7 @@ import org.drools.base.base.ValueResolver; import org.drools.base.base.ValueType; import org.drools.compiler.rule.builder.EvaluatorDefinition; +import org.drools.drl.parser.DrlParser; import org.drools.drl.parser.impl.Operator; import org.drools.base.rule.accessor.Evaluator; import org.drools.base.rule.accessor.FieldValue; @@ -49,6 +50,8 @@ public class CustomOperatorTest { + private static final String SUPERSET_OF = DrlParser.ANTLR4_PARSER_ENABLED ? "##supersetOf" : "supersetOf"; + public static Stream parameters() { return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } @@ -58,7 +61,16 @@ public static Stream parameters() { public void testCustomOperatorUsingCollections(KieBaseTestConfiguration kieBaseTestConfiguration) { String constraints = " $alice : Person(name == \"Alice\")\n" + - " $bob : Person(name == \"Bob\", addresses supersetOf $alice.addresses)\n"; + " $bob : Person(name == \"Bob\", addresses " + SUPERSET_OF + " $alice.addresses)\n"; + customOperatorUsingCollections(kieBaseTestConfiguration, constraints); + } + + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCustomOperatorUsingCollectionsWithNot(KieBaseTestConfiguration kieBaseTestConfiguration) { + String constraints = + " $alice : Person(name == \"Alice\")\n" + + " $bob : Person(name == \"Bob\", $alice.addresses not " + SUPERSET_OF + " this.addresses)\n"; customOperatorUsingCollections(kieBaseTestConfiguration, constraints); } @@ -67,8 +79,8 @@ public void testCustomOperatorUsingCollections(KieBaseTestConfiguration kieBaseT public void testNoOperatorInstancesCreatedAtRuntime(KieBaseTestConfiguration kieBaseTestConfiguration) { String constraints = " $alice : Person(name == \"Alice\")\n" + - " $bob : Person(name == \"Bob\", addresses supersetOf $alice.addresses)\n" + - " Person(name == \"Bob\", addresses supersetOf $alice.addresses)\n"; + " $bob : Person(name == \"Bob\", addresses " + SUPERSET_OF + " $alice.addresses)\n" + + " Person(name == \"Bob\", addresses " + SUPERSET_OF + " $alice.addresses)\n"; customOperatorUsingCollections(kieBaseTestConfiguration, constraints); @@ -81,7 +93,7 @@ public void testCustomOperatorUsingCollectionsInverted(KieBaseTestConfiguration // DROOLS-6983 String constraints = " $bob : Person(name == \"Bob\")\n" + - " $alice : Person(name == \"Alice\", $bob.addresses supersetOf this.addresses)\n"; + " $alice : Person(name == \"Alice\", $bob.addresses " + SUPERSET_OF + " this.addresses)\n"; customOperatorUsingCollections(kieBaseTestConfiguration, constraints); } @@ -201,7 +213,7 @@ public boolean evaluateCachedRight(final ValueResolver reteEvaluator, final Vari } public boolean evaluateAll(final Collection leftCollection, final Collection rightCollection) { - return rightCollection.containsAll(leftCollection); + return getOperator().isNegated() ^ rightCollection.containsAll(leftCollection); } } @@ -212,7 +224,7 @@ public void testCustomOperatorOnKieModule(KieBaseTestConfiguration kieBaseTestCo "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + " $alice : Person(name == \"Alice\")\n" + - " $bob : Person(name == \"Bob\", addresses supersetOf $alice.addresses)\n" + + " $bob : Person(name == \"Bob\", addresses " + SUPERSET_OF + " $alice.addresses)\n" + "then\n" + "end\n"; diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/Misc2Test.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/Misc2Test.java index 3a91b6698dd..4d72e3b2bcb 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/Misc2Test.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/Misc2Test.java @@ -9050,6 +9050,8 @@ public void testKieHelperReleaseId(KieBaseTestConfiguration kieBaseTestConfigura assertThat(ksession.fireAllRules()).isEqualTo(1); } + private static final String SUPERSET_OF = DrlParser.ANTLR4_PARSER_ENABLED ? "##supersetOf" : "supersetOf"; + @ParameterizedTest(name = "KieBase type={0}") @MethodSource("parameters") public void testKieHelperKieModuleModel(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { @@ -9060,7 +9062,7 @@ public void testKieHelperKieModuleModel(KieBaseTestConfiguration kieBaseTestConf "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + " $alice : Person(name == \"Alice\")\n" + - " $bob : Person(name == \"Bob\", addresses supersetOf $alice.addresses)\n" + + " $bob : Person(name == \"Bob\", addresses " + SUPERSET_OF + " $alice.addresses)\n" + "then\n" + "end\n"; diff --git a/drools-traits/src/test/java/org/drools/traits/compiler/CommonTraitTest.java b/drools-traits/src/test/java/org/drools/traits/compiler/CommonTraitTest.java index efa4b0786d1..b3c69c325b6 100644 --- a/drools-traits/src/test/java/org/drools/traits/compiler/CommonTraitTest.java +++ b/drools-traits/src/test/java/org/drools/traits/compiler/CommonTraitTest.java @@ -18,16 +18,27 @@ */ package org.drools.traits.compiler; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; + +import org.drools.drl.parser.DrlParser; import org.drools.kiesession.rulebase.InternalKnowledgeBase; import org.drools.kiesession.rulebase.KnowledgeBaseFactory; import org.drools.traits.core.base.evaluators.IsAEvaluatorDefinition; import org.junit.jupiter.api.BeforeAll; import org.kie.api.KieBase; +import org.kie.api.conf.KieBaseOption; import org.kie.api.io.ResourceType; import org.kie.internal.builder.KnowledgeBuilder; import org.kie.internal.builder.KnowledgeBuilderFactory; import org.kie.internal.builder.conf.EvaluatorOption; +import org.kie.internal.builder.conf.KnowledgeBuilderOption; +import org.kie.internal.builder.conf.PropertySpecificOption; +import org.kie.internal.builder.conf.SingleValueKieBuilderOption; import org.kie.internal.io.ResourceFactory; +import org.kie.internal.utils.KieHelper; import static org.assertj.core.api.Assertions.fail; @@ -40,9 +51,9 @@ public static void beforeClass() { protected KieBase loadKnowledgeBaseFromString(String... drlContentStrings) { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - for (String drlContentString : drlContentStrings) { - kbuilder.add(ResourceFactory.newByteArrayResource(drlContentString - .getBytes()), ResourceType.DRL); + for (String drl : drlContentStrings) { + drl = replaceCustomOperatorIfRequired(drl); + kbuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL); } if (kbuilder.hasErrors()) { @@ -52,4 +63,31 @@ protected KieBase loadKnowledgeBaseFromString(String... drlContentStrings) { kbase.addPackages(kbuilder.getKnowledgePackages()); return kbase; } + + protected KieBase loadKnowledgeBaseFromDrlFile(String drlFilePath) { + try (InputStream is = getClass().getClassLoader().getResourceAsStream(drlFilePath)) { + String drl = replaceCustomOperatorIfRequired(new String(is.readAllBytes(), StandardCharsets.UTF_8)); + return loadKnowledgeBaseFromString(drl); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + protected KieBase loadKnowledgeBaseWithKnowledgeBuilderOption(String drl, KnowledgeBuilderOption... knowledgeBuilderOptions) { + drl = replaceCustomOperatorIfRequired(drl); + return new KieHelper(knowledgeBuilderOptions).addContent(drl, ResourceType.DRL ).build(); + } + + protected KieBase loadKnowledgeBaseWithKieBaseOption(String drl, KieBaseOption... kieBaseOption) { + drl = replaceCustomOperatorIfRequired(drl); + return new KieHelper().addContent(drl, ResourceType.DRL ).build(kieBaseOption); + } + + protected static String replaceCustomOperatorIfRequired(String drl) { + if (DrlParser.ANTLR4_PARSER_ENABLED) { + // new parser (DRL10) requires a prefix '##' for a custom operator + return drl.replaceAll(" isA ", " ##isA "); + } + return drl; + } } diff --git a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/LegacyTraitTest.java b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/LegacyTraitTest.java index 47f7e41b0d7..eef811d440a 100644 --- a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/LegacyTraitTest.java +++ b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/LegacyTraitTest.java @@ -56,18 +56,7 @@ public static Collection modes() { } private KieSession getSessionFromString(String drl) { - KnowledgeBuilder knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - knowledgeBuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()), - ResourceType.DRL); - if (knowledgeBuilder.hasErrors()) { - throw new RuntimeException(knowledgeBuilder.getErrors().toString()); - } - - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - kbase.addPackages(knowledgeBuilder.getKnowledgePackages()); - - KieSession session = kbase.newKieSession(); - return session; + return loadKnowledgeBaseFromString(drl).newKieSession(); } // Getters and setters are both needed. They should refer to an attribute with the same name diff --git a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/LogicalTraitTest.java b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/LogicalTraitTest.java index a500b0bb8fe..a15e4a3c51f 100644 --- a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/LogicalTraitTest.java +++ b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/LogicalTraitTest.java @@ -68,14 +68,7 @@ public static Stream parameters() { @MethodSource("parameters") public void testShadowAlias(VirtualPropertyMode mode) throws Exception { - KnowledgeBuilder kbuilderImpl = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilderImpl.add( ResourceFactory.newClassPathResource( "org/drools/compiler/factmodel/traits/testTraitedAliasing.drl" ), ResourceType.DRL ); - if ( kbuilderImpl.hasErrors() ) { - fail( kbuilderImpl.getErrors().toString() ); - } - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - kbase.addPackages( kbuilderImpl.getKnowledgePackages() ); - + KieBase kbase = loadKnowledgeBaseFromDrlFile( "org/drools/compiler/factmodel/traits/testTraitedAliasing.drl" ); TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); KieSession ks = kbase.newKieSession(); @@ -132,13 +125,7 @@ public void testShadowAliasTraitOnClass(VirtualPropertyMode mode) { " list.add( \"ok\" );" + "end \n"; - KnowledgeBuilder kbuilderImpl = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilderImpl.add( ResourceFactory.newByteArrayResource( drl.getBytes() ), ResourceType.DRL ); - if ( kbuilderImpl.hasErrors() ) { - fail( kbuilderImpl.getErrors().toString() ); - } - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - kbase.addPackages( kbuilderImpl.getKnowledgePackages() ); + KieBase kbase = loadKnowledgeBaseFromString( drl ); TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); @@ -208,13 +195,7 @@ public void testShadowAliasClassOnTrait(VirtualPropertyMode mode) { "" + ""; - KnowledgeBuilder kbuilderImpl = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilderImpl.add( ResourceFactory.newByteArrayResource( drl.getBytes() ), ResourceType.DRL ); - if ( kbuilderImpl.hasErrors() ) { - fail( kbuilderImpl.getErrors().toString() ); - } - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - kbase.addPackages( kbuilderImpl.getKnowledgePackages() ); + KieBase kbase = loadKnowledgeBaseFromString( drl ); TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); @@ -279,13 +260,7 @@ public void testShadowAliasTraitOnTrait(VirtualPropertyMode mode) { "" + ""; - KnowledgeBuilder kbuilderImpl = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilderImpl.add( ResourceFactory.newByteArrayResource( drl.getBytes() ), ResourceType.DRL ); - if ( kbuilderImpl.hasErrors() ) { - fail( kbuilderImpl.getErrors().toString() ); - } - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - kbase.addPackages( kbuilderImpl.getKnowledgePackages() ); + KieBase kbase = loadKnowledgeBaseFromString( drl ); TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); @@ -525,7 +500,7 @@ public void testHardGetSetOnLogicallyTraitedField(VirtualPropertyMode mode) { " modify( $o ) { getValue().setNum( 99 ); } " + "end "; - KieBase knowledgeBase = new KieHelper(PropertySpecificOption.ALLOWED).addContent( drl, ResourceType.DRL ).build(); + KieBase knowledgeBase = loadKnowledgeBaseWithKnowledgeBuilderOption( drl, PropertySpecificOption.ALLOWED ); TraitFactoryImpl.setMode(mode, knowledgeBase ); KieSession knowledgeSession = knowledgeBase.newKieSession(); @@ -736,13 +711,7 @@ public void shadowAliasSelf(VirtualPropertyMode mode) { "" + ""; - KnowledgeBuilder kbuilderImpl = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilderImpl.add( ResourceFactory.newByteArrayResource( drl.getBytes() ), ResourceType.DRL ); - if ( kbuilderImpl.hasErrors() ) { - fail( kbuilderImpl.getErrors().toString() ); - } - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - kbase.addPackages( kbuilderImpl.getKnowledgePackages() ); + KieBase kbase = loadKnowledgeBaseFromString( drl ); TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); @@ -825,13 +794,7 @@ public void traitOnSet(VirtualPropertyMode mode) { "" + ""; - KnowledgeBuilder kbuilderImpl = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilderImpl.add( ResourceFactory.newByteArrayResource( drl.getBytes() ), ResourceType.DRL ); - if ( kbuilderImpl.hasErrors() ) { - fail( kbuilderImpl.getErrors().toString() ); - } - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - kbase.addPackages( kbuilderImpl.getKnowledgePackages() ); + KieBase kbase = loadKnowledgeBaseFromString( drl ); TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); @@ -935,13 +898,7 @@ public void testShadowAliasTraitOnClassLogicalRetract(VirtualPropertyMode mode) "" + ""; - KnowledgeBuilder kbuilderImpl = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilderImpl.add( ResourceFactory.newByteArrayResource( drl.getBytes() ), ResourceType.DRL ); - if ( kbuilderImpl.hasErrors() ) { - fail( kbuilderImpl.getErrors().toString() ); - } - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - kbase.addPackages( kbuilderImpl.getKnowledgePackages() ); + KieBase kbase = loadKnowledgeBaseFromString( drl ); TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); @@ -1056,13 +1013,7 @@ public void testShadowAliasClassOnTraitLogicalRetract(VirtualPropertyMode mode) " list.add( $f2.getId() );" + "end \n"; - KnowledgeBuilder kbuilderImpl = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilderImpl.add( ResourceFactory.newByteArrayResource( drl.getBytes() ), ResourceType.DRL ); - if ( kbuilderImpl.hasErrors() ) { - fail( kbuilderImpl.getErrors().toString() ); - } - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - kbase.addPackages( kbuilderImpl.getKnowledgePackages() ); + KieBase kbase = loadKnowledgeBaseFromString( drl ); TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); @@ -1121,13 +1072,7 @@ public void testSerial(VirtualPropertyMode mode) { "" + ""; - KnowledgeBuilder kbuilderImpl = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilderImpl.add( ResourceFactory.newByteArrayResource( drl.getBytes() ), ResourceType.DRL ); - if ( kbuilderImpl.hasErrors() ) { - fail( kbuilderImpl.getErrors().toString() ); - } - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - kbase.addPackages( kbuilderImpl.getKnowledgePackages() ); + KieBase kbase = loadKnowledgeBaseFromString( drl ); TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); diff --git a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitFieldsAndLegacyClassesTest.java b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitFieldsAndLegacyClassesTest.java index 0ecf89bd251..c12828c4c2d 100644 --- a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitFieldsAndLegacyClassesTest.java +++ b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitFieldsAndLegacyClassesTest.java @@ -468,7 +468,7 @@ public void testTraitFieldUpdate4(VirtualPropertyMode mode) { "\n"; - KieBase kBase = new KieHelper(PropertySpecificOption.ALLOWED).addContent( drl, ResourceType.DRL ).build(); + KieBase kBase = loadKnowledgeBaseWithKnowledgeBuilderOption(drl, PropertySpecificOption.ALLOWED); TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); diff --git a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitTest.java b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitTest.java index ddfa9a038e2..451ebdf3c31 100644 --- a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitTest.java +++ b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitTest.java @@ -116,20 +116,16 @@ public static Stream parameters() { return Stream.of(VirtualPropertyMode.MAP, VirtualPropertyMode.TRIPLES); } - private KieSession getSession(String... ruleFiles) { - KieHelper kieHelper = new KieHelper(); - for (String file : ruleFiles) { - kieHelper.kfs.write(new ClassPathResource(file)); - } - return kieHelper.build().newKieSession(); + private KieSession getSession(String ruleFile) { + return loadKnowledgeBaseFromDrlFile(ruleFile).newKieSession(); } private KieSession getSessionFromString(String drl) { - return new KieHelper().addContent(drl, ResourceType.DRL).build().newKieSession(); + return loadKnowledgeBaseFromString(drl).newKieSession(); } private KieBase getKieBaseFromString(String drl, KieBaseOption... options) { - return new KieHelper().addContent(drl, ResourceType.DRL).build(options); + return loadKnowledgeBaseWithKieBaseOption(drl, options); } @ParameterizedTest() @@ -169,16 +165,8 @@ public void testRetract(VirtualPropertyMode mode) { public void testTraitWrapGetAndSet(VirtualPropertyMode mode) throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource(source); - assertThat(res).isNotNull(); - kbuilder.add(res, ResourceType.DRL); - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); + InternalRuleBase kb = (InternalRuleBase) loadKnowledgeBaseFromDrlFile(source); TraitFactoryImpl.setMode(mode, kb); - kb.addPackages(kbuilder.getKnowledgePackages()); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); @@ -334,15 +322,7 @@ public void testTraitProxy(VirtualPropertyMode mode) throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource(source); - assertThat(res).isNotNull(); - kbuilder.add(res, ResourceType.DRL); - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages(kbuilder.getKnowledgePackages()); + InternalRuleBase kb = (InternalRuleBase) loadKnowledgeBaseFromDrlFile(source); TraitFactoryImpl.setMode(mode, kb); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); @@ -383,15 +363,7 @@ public void testTraitProxy(VirtualPropertyMode mode) throws Exception { public void testWrapperSize(VirtualPropertyMode mode) throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource(source); - assertThat(res).isNotNull(); - kbuilder.add(res, ResourceType.DRL); - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages(kbuilder.getKnowledgePackages()); + InternalRuleBase kb = (InternalRuleBase) loadKnowledgeBaseFromDrlFile(source); TraitFactoryImpl.setMode(mode, kb); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); @@ -467,16 +439,7 @@ public void testWrapperSize(VirtualPropertyMode mode) throws Exception { public void testWrapperEmpty(VirtualPropertyMode mode) throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource(source); - assertThat(res).isNotNull(); - - kbuilder.add(res, ResourceType.DRL); - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages(kbuilder.getKnowledgePackages()); + InternalRuleBase kb = (InternalRuleBase) loadKnowledgeBaseFromDrlFile(source); TraitFactoryImpl.setMode(mode, kb); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); @@ -526,16 +489,7 @@ public void testWrapperEmpty(VirtualPropertyMode mode) throws Exception { public void testWrapperContainsKey(VirtualPropertyMode mode) throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource(source); - assertThat(res).isNotNull(); - kbuilder.add(res, ResourceType.DRL); - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages(kbuilder.getKnowledgePackages()); - + InternalRuleBase kb = (InternalRuleBase) loadKnowledgeBaseFromDrlFile(source); TraitFactoryImpl.setMode(mode, kb); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); @@ -621,15 +575,7 @@ public void testWrapperContainsKey(VirtualPropertyMode mode) throws Exception { public void testInternalComponents1(VirtualPropertyMode mode) throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource(source); - assertThat(res).isNotNull(); - kbuilder.add(res, ResourceType.DRL); - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages(kbuilder.getKnowledgePackages()); + InternalRuleBase kb = (InternalRuleBase) loadKnowledgeBaseFromDrlFile(source); TraitFactoryImpl.setMode(mode, kb); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); @@ -673,15 +619,7 @@ public void testInternalComponents1(VirtualPropertyMode mode) throws Exception { public void testWrapperKeySetAndValues(VirtualPropertyMode mode) throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource(source); - assertThat(res).isNotNull(); - kbuilder.add(res, ResourceType.DRL); - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages(kbuilder.getKnowledgePackages()); + InternalRuleBase kb = (InternalRuleBase) loadKnowledgeBaseFromDrlFile(source); TraitFactoryImpl.setMode(mode, kb); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); @@ -737,15 +675,7 @@ public int compare(Object o1, Object o2) { public void testWrapperClearAndRemove(VirtualPropertyMode mode) throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource(source); - assertThat(res).isNotNull(); - kbuilder.add(res, ResourceType.DRL); - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages(kbuilder.getKnowledgePackages()); + InternalRuleBase kb = (InternalRuleBase) loadKnowledgeBaseFromDrlFile(source); TraitFactoryImpl.setMode(mode, kb); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); @@ -1284,16 +1214,10 @@ public void traitsInBatchExecution(VirtualPropertyMode mode) { " list.add(2);\n" + "end"; - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add(new ByteArrayResource(str.getBytes()), ResourceType.DRL); - - if (kbuilder.hasErrors()) { - throw new RuntimeException(kbuilder.getErrors().toString()); - } + KieBase kbase = loadKnowledgeBaseFromString( str ); List list = new ArrayList<>(); - KieBase kbase = kbuilder.newKieBase(); TraitFactoryImpl.setMode(mode, kbase); StatelessKieSession ksession = kbase.newStatelessKieSession(); @@ -1555,13 +1479,7 @@ public void testTMSConsistencyWithNonTraitableBeans(VirtualPropertyMode mode) { "end\n"; - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - kbase.addPackages(kbuilder.getKnowledgePackages()); + KieBase kbase = loadKnowledgeBaseFromString( s1 ); KieSession ksession = kbase.newKieSession(); TraitFactoryImpl.setMode(mode, ksession.getKieBase()); @@ -1624,15 +1542,7 @@ public void testTraitsLegacyWrapperCoherence(VirtualPropertyMode mode) { " list.add(m); \n" + "end \n"; - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL); - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - - kbase.addPackages(kbuilder.getKnowledgePackages()); + KieBase kbase = loadKnowledgeBaseFromString( str ); KieSession ksession = kbase.newKieSession(); TraitFactoryImpl.setMode(mode, ksession.getKieBase()); @@ -1670,15 +1580,7 @@ public void testHasTypes(VirtualPropertyMode mode) throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource(source); - assertThat(res).isNotNull(); - kbuilder.add(res, ResourceType.DRL); - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages(kbuilder.getKnowledgePackages()); + InternalRuleBase kb = (InternalRuleBase) loadKnowledgeBaseFromDrlFile(source); TraitFactoryImpl traitBuilder = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); TraitFactoryImpl.setMode(mode, kb); @@ -1740,15 +1642,7 @@ public void testTraitRedundancy(VirtualPropertyMode mode) { " shed($p, IStudent.class);\n" + "end \n"; - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL); - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - - kbase.addPackages(kbuilder.getKnowledgePackages()); + KieBase kbase = loadKnowledgeBaseFromString( str ); KieSession ksession = kbase.newKieSession(); TraitFactoryImpl.setMode(mode, ksession.getKieBase()); @@ -1792,18 +1686,9 @@ public void traitSimpleTypes(VirtualPropertyMode mode) { "" + "rule \"Init\" when then insert(new ExamMark()); end \n"; - - - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); + KieBase kbase = loadKnowledgeBaseFromString( s1 ); TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); - kbase.addPackages(kbuilder.getKnowledgePackages()); - KieSession ksession = kbase.newKieSession(); ksession.fireAllRules(); @@ -1872,16 +1757,9 @@ public void testTraitEncoding(VirtualPropertyMode mode) { "end\n" ; - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); + InternalKnowledgeBase kbase = (InternalKnowledgeBase) loadKnowledgeBaseFromString( s1 ); TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); - kbase.addPackages(kbuilder.getKnowledgePackages()); - TraitRegistryImpl tr = (TraitRegistryImpl) ((TraitRuntimeComponentFactory) RuntimeComponentFactory.get()).getTraitRegistry(kbase); LOGGER.debug(tr.getHierarchy().toString()); @@ -1914,15 +1792,8 @@ public void testTraitActualTypeCodeWithCoreMap(VirtualPropertyMode mode) { void testTraitActualTypeCodeWithEntities(String trig, VirtualPropertyMode mode) { - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add(new ClassPathResource("org/drools/compiler/factmodel/traits/testComplexDonShed.drl"), ResourceType.DRL); - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - TraitFactoryImpl.setMode(mode, (KieBase) kbase); - - kbase.addPackages(kbuilder.getKnowledgePackages()); + KieBase kbase = loadKnowledgeBaseFromDrlFile("org/drools/compiler/factmodel/traits/testComplexDonShed.drl"); + TraitFactoryImpl.setMode(mode, kbase); KieSession ksession = kbase.newKieSession(); @@ -2026,16 +1897,9 @@ public void testTraitModifyCore(VirtualPropertyMode mode) { "end " + ""; - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); + KieBase kbase = loadKnowledgeBaseFromString( s1 ); TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); - kbase.addPackages(kbuilder.getKnowledgePackages()); - KieSession ksession = kbase.newKieSession(); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -2114,15 +1978,8 @@ public void testTraitModifyCore2(VirtualPropertyMode mode) { " modify ($p) { setName(\"alan\"); } " + "end "; - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - TraitFactoryImpl.setMode(mode, (KieBase) kbase); // not relevant - - kbase.addPackages(kbuilder.getKnowledgePackages()); + KieBase kbase = loadKnowledgeBaseFromString( s1 ); + TraitFactoryImpl.setMode(mode, kbase); // not relevant KieSession ksession = kbase.newKieSession(); int k = ksession.fireAllRules(); @@ -2177,15 +2034,9 @@ public void testTraitModifyCore2a(VirtualPropertyMode mode) { "then \n" + "end \n"; - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - TraitFactoryImpl.setMode(mode, (KieBase) kbase); // not relevant + KieBase kbase = loadKnowledgeBaseFromString( s1 ); + TraitFactoryImpl.setMode(mode, kbase); // not relevant - kbase.addPackages(kbuilder.getKnowledgePackages()); KieSession ksession = kbase.newKieSession(); List list = new ArrayList<>(); @@ -2279,15 +2130,8 @@ public void testTraitModifyCore3(VirtualPropertyMode mode) { "end \n" + ""; - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - TraitFactoryImpl.setMode(mode, (KieBase) kbase); // not relevant - - kbase.addPackages(kbuilder.getKnowledgePackages()); + KieBase kbase = loadKnowledgeBaseFromString( s1 ); + TraitFactoryImpl.setMode(mode, kbase); // not relevant List list = new ArrayList<>(); KieSession ksession = kbase.newKieSession(); @@ -2392,16 +2236,9 @@ public void testTraitModifyCoreWithPropertyReactivity(VirtualPropertyMode mode) " modify ($p) { setSchool(\"myschool\"), setAge(44), setName(\"alan\"); } " + "end \n"; - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); + KieBase kbase = loadKnowledgeBaseFromString( s1 ); TraitFactoryImpl.setMode(mode, (KieBase) kbase); // not relevant - kbase.addPackages(kbuilder.getKnowledgePackages()); - List list = new ArrayList(); KieSession ksession = kbase.newKieSession(); ksession.setGlobal("list", list); @@ -3403,16 +3240,9 @@ public void testShedThing(VirtualPropertyMode mode) { "end \n" + ""; - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); + KieBase kbase = loadKnowledgeBaseFromString( s1 ); TraitFactoryImpl.setMode(mode, (KieBase) kbase); // not relevant - kbase.addPackages(kbuilder.getKnowledgePackages()); - List list = new ArrayList(); KieSession ksession = kbase.newKieSession(); ksession.setGlobal("list", list); @@ -3475,16 +3305,9 @@ public void testdeleteThings(VirtualPropertyMode mode) { "end \n" + ""; - KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); - if (kbuilder.hasErrors()) { - fail(kbuilder.getErrors().toString()); - } - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); + KieBase kbase = loadKnowledgeBaseFromString( s1 ); TraitFactoryImpl.setMode(mode, (KieBase) kbase); // not relevant - kbase.addPackages(kbuilder.getKnowledgePackages()); - List list = new ArrayList(); KieSession ksession = kbase.newKieSession(); ksession.setGlobal("list", list); @@ -3985,7 +3808,7 @@ public void testPropagation(VirtualPropertyMode mode) { drl += ") then list.add(\"H" + x + "\"); end \n"; } - KieSession ks = new KieHelper().addContent(drl, ResourceType.DRL).build().newKieSession(); + KieSession ks = getSessionFromString(drl); TraitFactoryImpl.setMode(mode, ks.getKieBase()); List list = new ArrayList<>(); @@ -4870,7 +4693,7 @@ public void testClassLiteralsWithOr(VirtualPropertyMode mode) { ""; - KieBase kbase = new KieHelper(PropertySpecificOption.ALLOWED).addContent(drl, ResourceType.DRL).build(); + KieBase kbase = loadKnowledgeBaseWithKnowledgeBuilderOption(drl, PropertySpecificOption.ALLOWED); TraitFactoryImpl.setMode(mode, kbase); List list = new ArrayList<>(); @@ -5224,7 +5047,7 @@ public void testPartitionWithSiblingsOnDelete(VirtualPropertyMode mode) { "rule RC when C() then list.add('C'); end " + " "; - KieBase kbase = new KieHelper().addContent(drl, ResourceType.DRL).build(); + KieBase kbase = getKieBaseFromString(drl); TraitFactoryImpl.setMode(mode, kbase); KieSession ksession = kbase.newKieSession(); @@ -5819,8 +5642,7 @@ public void testPreserveAllSetBitMask(VirtualPropertyMode mode) { " modify ($y) {} " + "end "; - KieHelper helper = new KieHelper(); - KieBase kieBase = helper.addContent(drl, ResourceType.DRL).getKieContainer().getKieBase(); + KieBase kieBase = getKieBaseFromString(drl); TraitFactoryImpl.setMode(mode, kieBase); KieSession kSession = kieBase.newKieSession(); diff --git a/drools-traits/src/test/java/org/drools/traits/compiler/integrationtests/TraitTypeGenerationTest.java b/drools-traits/src/test/java/org/drools/traits/compiler/integrationtests/TraitTypeGenerationTest.java index 51d42a2f5c4..dfee3078074 100644 --- a/drools-traits/src/test/java/org/drools/traits/compiler/integrationtests/TraitTypeGenerationTest.java +++ b/drools-traits/src/test/java/org/drools/traits/compiler/integrationtests/TraitTypeGenerationTest.java @@ -186,6 +186,8 @@ public void testIsAWith2KContainers() { " students.add(student);\n" + "end"; + str = replaceCustomOperatorIfRequired(str); + KieServices ks = KieServices.Factory.get(); KieFileSystem kfs = ks.newKieFileSystem(); @@ -370,15 +372,7 @@ public void testMultipleInheritanceWithPosition1() throws Exception { " mfield1 : int = 201 @position(2)\n" + "end"; - KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kBuilder.add(new ByteArrayResource(drl.getBytes()), ResourceType.DRL); - if (kBuilder.hasErrors()) { - LOGGER.error(kBuilder.getErrors().toString()); - } - assertThat(kBuilder.hasErrors()).isFalse(); - - InternalKnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase(); - knowledgeBase.addPackages(kBuilder.getKnowledgePackages()); + KieBase knowledgeBase = loadKnowledgeBaseFromString( drl ); FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait"); assertThat(sw.getFields()).hasSize(5); @@ -406,15 +400,7 @@ public void testMultipleInheritanceWithPosition2() throws Exception { " mfield0 : int = 200 @position(0)\n" + " mfield1 : int = 201 @position(2)\n" + "end"; - KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kBuilder.add(new ByteArrayResource(drl.getBytes()), ResourceType.DRL); - if (kBuilder.hasErrors()) { - LOGGER.error(kBuilder.getErrors().toString()); - } - assertThat(kBuilder.hasErrors()).isFalse(); - - InternalKnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase(); - knowledgeBase.addPackages(kBuilder.getKnowledgePackages()); + KieBase knowledgeBase = loadKnowledgeBaseFromString( drl ); FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait"); assertThat(sw.getFields()).hasSize(5); @@ -442,15 +428,7 @@ public void testMultipleInheritanceWithPosition3() throws Exception { " mfield0 : int = 200 //@position(0)\n" + " mfield1 : int = 201 @position(2)\n" + "end"; - KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kBuilder.add(new ByteArrayResource(drl.getBytes()), ResourceType.DRL); - if (kBuilder.hasErrors()) { - LOGGER.error(kBuilder.getErrors().toString()); - } - assertThat(kBuilder.hasErrors()).isFalse(); - - InternalKnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase(); - knowledgeBase.addPackages(kBuilder.getKnowledgePackages()); + KieBase knowledgeBase = loadKnowledgeBaseFromString( drl ); FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait"); assertThat(sw.getFields()).hasSize(5); @@ -478,15 +456,7 @@ public void testMultipleInheritanceWithPosition4() throws Exception { " mfield0 : int = 200 @position(0)\n" + " mfield1 : int = 201 @position(2)\n" + "end"; - KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kBuilder.add(new ByteArrayResource(drl.getBytes()), ResourceType.DRL); - if (kBuilder.hasErrors()) { - LOGGER.error(kBuilder.getErrors().toString()); - } - assertThat(kBuilder.hasErrors()).isFalse(); - - InternalKnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase(); - knowledgeBase.addPackages(kBuilder.getKnowledgePackages()); + KieBase knowledgeBase = loadKnowledgeBaseFromString( drl ); FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait"); assertThat(sw.getFields()).hasSize(5); @@ -514,15 +484,7 @@ public void testMultipleInheritanceWithPosition5() throws Exception { " mfield0 : int = 200 @position(7)\n" + " mfield1 : int = 201 @position(2)\n" + "end"; - KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kBuilder.add(new ByteArrayResource(drl.getBytes()), ResourceType.DRL); - if (kBuilder.hasErrors()) { - LOGGER.error(kBuilder.getErrors().toString()); - } - assertThat(kBuilder.hasErrors()).isFalse(); - - InternalKnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase(); - knowledgeBase.addPackages(kBuilder.getKnowledgePackages()); + KieBase knowledgeBase = loadKnowledgeBaseFromString( drl ); FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait"); assertThat(sw.getFields()).hasSize(5); @@ -556,15 +518,7 @@ public void testMultipleInheritanceWithPosition6() throws Exception { " mfield0 : int = 200 //@position(0)\n" + " mfield1 : int = 201 //@position(2)\n" + "end"; - KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kBuilder.add(new ByteArrayResource(drl.getBytes()), ResourceType.DRL); - if (kBuilder.hasErrors()) { - LOGGER.error(kBuilder.getErrors().toString()); - } - assertThat(kBuilder.hasErrors()).isFalse(); - - InternalKnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase(); - knowledgeBase.addPackages(kBuilder.getKnowledgePackages()); + KieBase knowledgeBase = loadKnowledgeBaseFromString( drl ); FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait"); assertThat(sw.getFields()).hasSize(6); @@ -599,15 +553,7 @@ public void testMultipleInheritanceWithPosition7() throws Exception { " mfield0 : int = 200 @position(0)\n" + " mfield1 : int = 201 @position(2)\n" + "end"; - KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kBuilder.add(new ByteArrayResource(drl.getBytes()), ResourceType.DRL); - if (kBuilder.hasErrors()) { - LOGGER.error(kBuilder.getErrors().toString()); - } - assertThat(kBuilder.hasErrors()).isFalse(); - - InternalKnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase(); - knowledgeBase.addPackages(kBuilder.getKnowledgePackages()); + KieBase knowledgeBase = loadKnowledgeBaseFromString( drl ); FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait"); assertThat(sw.getFields()).hasSize(6); From b0a2f1c59c24034006cd70534f87bcbab24fd08a Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Thu, 23 Jan 2025 12:15:52 +0900 Subject: [PATCH 4/8] - drop half constraint - Disable drools-verifier test for DRL10 --- .../drl/parser/antlr4/DRLExprParserTest.java | 4 +-- .../drl/parser/antlr4/DescrDumperTest.java | 6 ++-- .../drl/parser/antlr4/MiscDRLParserTest.java | 24 ++++++------- .../antlr4/accumulate_with_nested_from.drl | 2 +- .../drl/parser/antlr4/in_operator_test.drl | 2 +- .../drl/parser/antlr4/notin_operator_test.drl | 2 +- .../drl/parser/antlr4/pluggable_operators.drl | 2 +- .../drl/parser/antlr4/DRL10Expressions.g4 | 33 +----------------- .../model/codegen/execmodel/CompilerTest.java | 3 ++ .../codegen/execmodel/HalfBinaryTest.java | 2 ++ .../codegen/execmodel/MvelOperatorsTest.java | 7 ++-- .../execmodel/NullSafeDereferencingTest.java | 2 ++ .../src/test/resources/logback-test.xml | 2 +- .../AlphaNodeRangeIndexingTest.java | 7 ++-- .../integrationtests/ConstraintsTest.java | 4 ++- .../integrationtests/IndexingTest.java | 4 +-- .../integrationtests/StreamsTest.java | 2 +- .../operators/ForAllTest.java | 2 +- .../integrationtests/operators/OrTest.java | 2 ++ .../compiler/beliefsystem/jtms/JTMSTest.java | 4 +-- .../mvel/integrationtests/JBRULESTest.java | 4 ++- .../NullSafeDereferencingTest.java | 4 ++- .../test_CEP_ComplexOperator.drl | 2 +- .../test_ConstraintConnectors.drl | 4 +-- .../integrationtests/strevaluator_test.drl | 2 +- .../functional/TemplatesTest.java | 14 ++++---- .../AbstractCompositeRestrictionTest.java | 2 ++ .../MultiRestrictionPatternTest.java | 2 ++ .../functional/template1_spreadsheet.drl.xls | Bin 7680 -> 7680 bytes .../testcoverage/functional/template_1.drl | 2 +- .../testcoverage/functional/template_2.drl | 6 ++-- .../sessionInsertMultithreadingTest.drl | 6 ++-- .../factmodel/traits/TraitMapCoreTest.java | 2 +- drools-verifier/drools-verifier-drl/pom.xml | 21 +++++++++++ .../builder/VerifierKnowledgeBaseBuilder.java | 7 ++++ 35 files changed, 105 insertions(+), 89 deletions(-) diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLExprParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLExprParserTest.java index 8cbebe73e6d..09aa20689e3 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLExprParserTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLExprParserTest.java @@ -27,7 +27,6 @@ import org.drools.drl.ast.descr.ConstraintConnectiveDescr; import org.drools.drl.ast.descr.RelationalExprDescr; import org.drools.drl.parser.DrlExprParser; -import org.drools.drl.parser.DrlExprParserFactory; import org.drools.drl.parser.DrlParser; import org.drools.drl.parser.DroolsParserException; import org.drools.drl.parser.impl.Operator; @@ -38,7 +37,6 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.ValueSource; -import org.kie.internal.builder.conf.LanguageLevelOption; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assumptions.assumeFalse; @@ -175,7 +173,7 @@ void bindingConstraint() { @Test void bindingWithRestrictions() { - String source = "$x : property > value && < 20"; + String source = "$x : property > value && property < 20"; ConstraintConnectiveDescr result = parser.parse( source ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrDumperTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrDumperTest.java index 4133e9f2594..a64b618c887 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrDumperTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrDumperTest.java @@ -24,13 +24,12 @@ import org.drools.drl.ast.descr.BindingDescr; import org.drools.drl.ast.descr.ConstraintConnectiveDescr; import org.drools.drl.parser.DrlExprParser; -import org.drools.drl.parser.DrlExprParserFactory; import org.drools.mvel.evaluators.MatchesEvaluatorsDefinition; import org.drools.mvel.evaluators.SetEvaluatorsDefinition; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import org.kie.internal.builder.conf.LanguageLevelOption; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; import static org.assertj.core.api.Assertions.assertThat; @@ -47,6 +46,7 @@ void setUp() { dumper = new DescrDumper(); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @Test void dump() { String input = "price > 10 && < 20 || == $val || == 30"; @@ -147,6 +147,7 @@ void dumpWithDateAttr() { assertThat(result).isEqualTo(expected); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @Test void dumpComplex() { String input = "a ( > 60 && < 70 ) || ( > 50 && < 55 ) && a3 == \"black\" || a == 40 && a3 == \"pink\" || a == 12 && a3 == \"yellow\" || a3 == \"blue\""; @@ -220,6 +221,7 @@ void dumpBindings4() { assertThat(result).isEqualTo(expected); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @Test void dumpBindingsWithRestriction() { String input = "$x : age > 10 && < 20 || > 30"; diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java index 56fbfe11152..40fb99d67fd 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java @@ -75,7 +75,8 @@ import org.drools.drl.parser.impl.Operator; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.condition.EnabledIf; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -95,14 +96,6 @@ void setUp() { parser = ParserTestUtils.getParser(); } - private static boolean isNewParser() { - return DrlParser.ANTLR4_PARSER_ENABLED; - } - - private static boolean isOldParser() { - return !DrlParser.ANTLR4_PARSER_ENABLED; - } - private String readResource(final String filename) { Path path; try { @@ -881,6 +874,7 @@ void simpleRuleWithBindings() { assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("if ( a == b ) { " + " assert( foo3 );" + "} else {" + " retract( foo4 );" + "}" + " System.out.println( a4 );"); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @Test void multipleRestrictionsConstraint() { RuleDescr rule = parseAndGetFirstRuleDescrFromFile("restrictions_test.drl"); @@ -2452,7 +2446,7 @@ void inOperator() { assertThat(pattern.getConstraint().getDescrs()).hasSize(1); ExprConstraintDescr fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); - assertThat(fld.getExpression()).isEqualTo("age > 30 && < 40"); + assertThat(fld.getExpression()).isEqualTo("age > 30 && age < 40"); // the second col, with 2 fields, the first with 2 restrictions, the // second field with one @@ -2486,7 +2480,7 @@ void notInOperator() { assertThat(pattern.getConstraint().getDescrs()).hasSize(1); ExprConstraintDescr fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); - assertThat(fld.getExpression()).isEqualTo("age > 30 && < 40"); + assertThat(fld.getExpression()).isEqualTo("age > 30 && age < 40"); // the second col, with 2 fields, the first with 2 restrictions, the // second field with one @@ -2536,6 +2530,7 @@ void constraintOrConnective() { assertThat(fcd.getExpression()).isEqualToIgnoringWhitespace("age < 42 || location==\"atlanta\""); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @Test void restrictions() { final String text = "rule X when Foo( bar > 1 || == 1 ) then end\n"; @@ -2987,7 +2982,7 @@ void pluggableOperators() { assertThat(eventE.getConstraint().getDescrs()).hasSize(1); ExprConstraintDescr fcdE = (ExprConstraintDescr) eventE.getConstraint().getDescrs().get(0); - assertThat(fcdE.getExpression()).isEqualTo("this not before[1, 10] $b || after[1, 10] $c && this after[1, 5] $d"); + assertThat(fcdE.getExpression()).isEqualTo("this not before[1, 10] $b || this after[1, 10] $c && this after[1, 5] $d"); } @Test @@ -3896,6 +3891,7 @@ void constraintOperators(String constraint) { assertThat(exprConstraintDescr.getExpression()).isEqualToIgnoringWhitespace(constraint); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @ParameterizedTest @ValueSource(strings = { "country matches \"[a-z]*\" || matches \"[A-Z]*\"", @@ -4419,7 +4415,7 @@ void traitExtendsMultiple() { .containsExactlyInAnyOrder("com.sample.ParentTrait", "UncleTrait", "org.test.GrandParentTrait"); } - @EnabledIf("isOldParser") + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @Test void pluggableEvaluatorOldParser() { final String source = "package org.drools\n" + @@ -4440,7 +4436,7 @@ void pluggableEvaluatorOldParser() { .containsExactly("$c : core", "this not isA t.x.E.class", "this isA t.x.D.class"); } - @EnabledIf("isNewParser") + @EnabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @Test void pluggableEvaluatorNewParser() { final String source = "package org.drools\n" + diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate_with_nested_from.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate_with_nested_from.drl index 3696836b1f2..5911bcadfb4 100755 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate_with_nested_from.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate_with_nested_from.drl @@ -18,7 +18,7 @@ rule "AccumulateParserTest" when // below statement makes no sense, but is useful to test parsing recursiveness - $personList : ArrayList() from accumulate( Person( $age : age > 21 || < 10 ) from collect( People() from $town.getPeople() ), + $personList : ArrayList() from accumulate( Person( $age : age > 21 || age < 10 ) from collect( People() from $town.getPeople() ), max( $age ) ); then end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/in_operator_test.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/in_operator_test.drl index 54f5225c3e8..7141a89d0d4 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/in_operator_test.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/in_operator_test.drl @@ -19,7 +19,7 @@ rule simple_rule when - Person(age > 30 && < 40) + Person(age > 30 && age < 40) Vehicle(type in ( "sedan", "wagon" ), age < 3) then consequence(); diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/notin_operator_test.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/notin_operator_test.drl index a2eae254405..8b054e0a4fb 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/notin_operator_test.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/notin_operator_test.drl @@ -19,7 +19,7 @@ rule simple_rule when - Person(age > 30 && < 40) + Person(age > 30 && age < 40) Vehicle(type not in ( "sedan", "wagon" ), age < 3) then consequence(); diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/pluggable_operators.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/pluggable_operators.drl index 59c31d2c8e7..a605648d783 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/pluggable_operators.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/pluggable_operators.drl @@ -23,6 +23,6 @@ when $b : EventB( this after[1,10] $a || this not after[15,20] $a ) $c : EventC( this finishes $b ) $d : EventD( this not starts $a ) - $e : EventE( this not before[1, 10] $b || after[1, 10] $c && this after[1, 5] $d ) + $e : EventE( this not before[1, 10] $b || this after[1, 10] $c && this after[1, 5] $d ) then end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Expressions.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Expressions.g4 index 7a4c807fcb7..e5030c2362c 100644 --- a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Expressions.g4 +++ b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Expressions.g4 @@ -571,7 +571,7 @@ locals [ BaseDescr lsd ] $relationalExpression::lsd = $result; } } - ( right=orRestriction + ( right=singleRestriction { if( buildDescr ) { $result = $right.result; // TODO access lsd directly instead of through dynamic context here @@ -581,36 +581,6 @@ locals [ BaseDescr lsd ] )* ; -orRestriction returns [BaseDescr result] - : left=andRestriction { if( buildDescr ) { $result = $left.result; } } - ( lop=OR args=fullAnnotation[null]? right=andRestriction - { if( buildDescr ) { - ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newOr(); - descr.addOrMerge( $result ); - descr.addOrMerge( $right.result ); - if ( $ctx.args != null ) { descr.addAnnotation( $args.result ); } - $result = descr; - } - } - )*? EOF? - ; - -andRestriction returns [BaseDescr result] - : left=singleRestriction { if( buildDescr ) { $result = $left.result; } } - ( lop=AND - { if ( isNotEOF() ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR ); } - args=fullAnnotation[null]?right=singleRestriction - { if( buildDescr ) { - ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newAnd(); - descr.addOrMerge( $result ); - descr.addOrMerge( $right.result ); - if ( $ctx.args != null ) { descr.addAnnotation( $args.result ); } - $result = descr; - } - } - )*? - ; - singleRestriction returns [BaseDescr result] : op=operator { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } @@ -630,7 +600,6 @@ singleRestriction returns [BaseDescr result] } helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_END ); } - | LPAREN or=orRestriction RPAREN { $result = $or.result; } ; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CompilerTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CompilerTest.java index abe40ca412c..f1fa582c60c 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CompilerTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CompilerTest.java @@ -45,6 +45,7 @@ import org.drools.model.codegen.execmodel.domain.Woman; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.definition.type.FactType; @@ -145,6 +146,7 @@ public void testEqualityCheckOnNull(RUN_TYPE runType) { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @ParameterizedTest @MethodSource("parameters") public void testOrWithFixedLeftOperand(RUN_TYPE runType) { @@ -2095,6 +2097,7 @@ public void testNumericLimits(RUN_TYPE runType) { } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @ParameterizedTest @MethodSource("parameters") public void testMapAbbreviatedComparison(RUN_TYPE runType) { diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/HalfBinaryTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/HalfBinaryTest.java index df52b350958..0050075db76 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/HalfBinaryTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/HalfBinaryTest.java @@ -23,12 +23,14 @@ import org.drools.model.codegen.execmodel.domain.Address; import org.drools.model.codegen.execmodel.domain.Person; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; +@DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") public class HalfBinaryTest extends BaseModelTest { @ParameterizedTest diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelOperatorsTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelOperatorsTest.java index 9986cba4046..134f4ca745a 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelOperatorsTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelOperatorsTest.java @@ -24,6 +24,7 @@ import java.util.Map; import org.drools.model.codegen.execmodel.domain.Person; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.builder.Message; @@ -82,6 +83,7 @@ public void testStrNot(RUN_TYPE runType) { assertThat(ksession.fireAllRules()).isEqualTo(2); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @ParameterizedTest @MethodSource("parameters") public void testStrHalf(RUN_TYPE runType) { @@ -100,6 +102,7 @@ public void testStrHalf(RUN_TYPE runType) { assertThat(ksession.fireAllRules()).isEqualTo(3); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @ParameterizedTest @MethodSource("parameters") public void testStrHalfOrAndAmpersand(RUN_TYPE runType) { @@ -125,7 +128,7 @@ public void testRange(RUN_TYPE runType) { "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + "rule R when\n" + - " Person( age > 30 && <= 40, $name : name )" + + " Person( age > 30 && age <= 40, $name : name )" + "then\n" + " list.add($name);" + "end "; @@ -152,7 +155,7 @@ public void testExcludedRange(RUN_TYPE runType) { "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + "rule R when\n" + - " Person( age <= 30 || > 40, $name : name )" + + " Person( age <= 30 || age > 40, $name : name )" + "then\n" + " list.add($name);" + "end "; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NullSafeDereferencingTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NullSafeDereferencingTest.java index a442f36b28c..daae50378b1 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NullSafeDereferencingTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NullSafeDereferencingTest.java @@ -26,6 +26,7 @@ import org.drools.model.codegen.execmodel.domain.MysteriousMan; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; @@ -253,6 +254,7 @@ public void testNullSafeDereferncingOnSecondField(RUN_TYPE runType) { assertThat(results.get(0).getValue()).isEqualTo("John2"); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @ParameterizedTest @MethodSource("parameters") public void testNullSafeDereferncingWithOrHalfBinary(RUN_TYPE runType) { diff --git a/drools-model/drools-model-codegen/src/test/resources/logback-test.xml b/drools-model/drools-model-codegen/src/test/resources/logback-test.xml index 25b6a1f4918..45cc9cf7290 100644 --- a/drools-model/drools-model-codegen/src/test/resources/logback-test.xml +++ b/drools-model/drools-model-codegen/src/test/resources/logback-test.xml @@ -36,7 +36,7 @@ - + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AlphaNodeRangeIndexingTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AlphaNodeRangeIndexingTest.java index 42820e0ee03..2ea5cda66ae 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AlphaNodeRangeIndexingTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AlphaNodeRangeIndexingTest.java @@ -475,17 +475,18 @@ public void testUnderThreshold(KieBaseTestConfiguration kieBaseTestConfiguration @ParameterizedTest(name = "KieBase type={0}") @MethodSource("parameters") public void testSurroundingRange(KieBaseTestConfiguration kieBaseTestConfiguration) { + // incubator-kie-drools#6228 : `age >= 0 && age < 20` doesn't enable range index in exec-model final String drl = "package org.drools.compiler.test\n" + "import " + Person.class.getCanonicalName() + "\n" + "rule test1\n when\n" + - " Person( age >= 0 && < 20 )\n" + + " Person( age >= 0, age < 20 )\n" + "then\n end\n" + "rule test2\n when\n" + - " Person( age >= 20 && < 40 )\n" + + " Person( age >= 20, age < 40 )\n" + "then\n end\n" + "rule test3\n when\n" + - " Person( age >= 40 && < 60 )\n" + + " Person( age >= 40, age < 60 )\n" + "then\n end\n"; final KieBase kbase = createKieBaseWithRangeIndexThresholdValue(kieBaseTestConfiguration, drl, 3); diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConstraintsTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConstraintsTest.java index ca9a368903e..67490e905fd 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConstraintsTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConstraintsTest.java @@ -33,6 +33,7 @@ import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; @@ -280,7 +281,7 @@ public void testConnectorsAndOperators(KieBaseTestConfiguration kieBaseTestConfi "rule \"operator\"\n" + " when\n" + " $t1 : StockTick( company == \"RHT\" )\n" + - " $t2 : StockTick( company == \"IBM\", this after $t1 || before $t1 )\n" + + " $t2 : StockTick( company == \"IBM\", this after $t1 || this before $t1 )\n" + " then\n" + " // do something\n" + "end "; @@ -373,6 +374,7 @@ public void testDeepNestedConstraints(KieBaseTestConfiguration kieBaseTestConfig } } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @ParameterizedTest(name = "KieBase type={0}") @MethodSource("parameters") public void testMultiRestrictionFieldConstraint(KieBaseTestConfiguration kieBaseTestConfiguration) { diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/IndexingTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/IndexingTest.java index 1d0e530e664..fc6200142af 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/IndexingTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/IndexingTest.java @@ -616,7 +616,7 @@ public void testRange(KieBaseTestConfiguration kieBaseTestConfiguration) { "import " + Person.class.getCanonicalName() + ";\n" + "rule R1 salience 10 when\n" + " Person( $age : age, $doubleAge : doubleAge )\n" + - " not Cheese( price > $age && < $doubleAge )\n" + + " not Cheese( price > $age && price < $doubleAge )\n" + "then\n" + "end\n" + "rule R3 salience 5 when\n" + @@ -654,7 +654,7 @@ public void testRange2(KieBaseTestConfiguration kieBaseTestConfiguration) throws "rule R1 when\n" + " A( $a : a )\n" + " B( $b : b )\n" + - " exists C( c > $a && < $b )\n" + + " exists C( c > $a && c < $b )\n" + "then\n" + "end"; diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/StreamsTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/StreamsTest.java index 82341ecac21..a0aa9b662a9 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/StreamsTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/StreamsTest.java @@ -206,7 +206,7 @@ public void testModifyRetracOnEntryPointFacts(KieBaseTestConfiguration kieBaseTe "\n" + "rule \"Test entry point 1\"\n" + "when\n" + - " $st : StockTick( company == \"ACME\", price > 10 && < 100 ) from entry-point \"stream1\"\n" + + " $st : StockTick( company == \"ACME\", price > 10 && price < 100 ) from entry-point \"stream1\"\n" + "then\n" + " results.add( Double.valueOf( $st.getPrice() ) );\n" + " modify( $st ) { setPrice( 110 ) }\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ForAllTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ForAllTest.java index 7b1a6f500bf..297f92d9610 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ForAllTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ForAllTest.java @@ -53,7 +53,7 @@ public void test1P1CFiring1(KieBaseTestConfiguration kieBaseTestConfiguration) { @ParameterizedTest(name = "KieBase type={0}") @MethodSource("parameters") public void test1P1CFiring2(KieBaseTestConfiguration kieBaseTestConfiguration) { - check(kieBaseTestConfiguration, "age == 8 || == 45", 1, new Person("Mario", 45), new Person("Sofia", 8)); + check(kieBaseTestConfiguration, "age == 8 || age == 45", 1, new Person("Mario", 45), new Person("Sofia", 8)); } @ParameterizedTest(name = "KieBase type={0}") diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/OrTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/OrTest.java index 16d6b7a28e3..6525dcd8a5e 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/OrTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/OrTest.java @@ -33,6 +33,7 @@ import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; @@ -351,6 +352,7 @@ public void testOrWithFrom(KieBaseTestConfiguration kieBaseTestConfiguration) { } } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @ParameterizedTest(name = "KieBase type={0}") @MethodSource("parameters") public void testOrWithReturnValueRestriction(KieBaseTestConfiguration kieBaseTestConfiguration) { diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/beliefsystem/jtms/JTMSTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/beliefsystem/jtms/JTMSTest.java index 9aa335b5e66..7ba4bd8b753 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/beliefsystem/jtms/JTMSTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/beliefsystem/jtms/JTMSTest.java @@ -113,7 +113,7 @@ public void testPosNegNonConflictingInsertions(KieBaseTestConfiguration kieBaseT "\n" + "rule \"Positive\"\n" + "when\n" + - " $n : String( this != 'go1' || == 'go2' ) \n" + + " $n : String( this != 'go1' || this == 'go2' ) \n" + "then\n" + " final String s = '+' + $n;" + " final List l = list;" + @@ -121,7 +121,7 @@ public void testPosNegNonConflictingInsertions(KieBaseTestConfiguration kieBaseT "end\n" + "rule \"Negative\"\n" + "when\n" + - " $n : String( _.neg, this != 'go1' || == 'go2' ) \n" + + " $n : String( _.neg, this != 'go1' || this == 'go2' ) \n" + "then\n" + " final String s = '-' + $n; \n" + " final List l = list; \n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/JBRULESTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/JBRULESTest.java index 81c339d50ac..e8baedadcf6 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/JBRULESTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/JBRULESTest.java @@ -40,6 +40,7 @@ import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; @@ -144,6 +145,7 @@ public void testJBRULES_2995(KieBaseTestConfiguration kieBaseTestConfiguration) assertThat(rules).isEqualTo(1); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @ParameterizedTest(name = "KieBase type={0}") @MethodSource("parameters") public void testJBRULES2872(KieBaseTestConfiguration kieBaseTestConfiguration) { @@ -252,7 +254,7 @@ public void testJBRULES3323(KieBaseTestConfiguration kieBaseTestConfiguration) t rule.append( "when\n" ); rule.append( "$foo : Foo($leftId : id, $leftBar : bar != null)\n" ); rule.append( "$fooSet : Set()\n" ); - rule.append( "from accumulate ( Foo(id > $leftId, bar != null && != $leftBar, $bar : bar),\n" ); + rule.append( "from accumulate ( Foo(id > $leftId, bar != null && bar != $leftBar, $bar : bar),\n" ); rule.append( "collectSet( $bar ) )\n" ); rule.append( "then\n" ); rule.append( "//System.out.println(\"ok\");\n" ); diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/NullSafeDereferencingTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/NullSafeDereferencingTest.java index edcdc2764f1..1184130fa56 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/NullSafeDereferencingTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/NullSafeDereferencingTest.java @@ -27,6 +27,7 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; @@ -235,6 +236,7 @@ public void testDoubleNullSafe(KieBaseTestConfiguration kieBaseTestConfiguration ksession.dispose(); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @ParameterizedTest(name = "KieBase type={0}") @MethodSource("parameters") public void testMixedNullSafes(KieBaseTestConfiguration kieBaseTestConfiguration) { @@ -316,7 +318,7 @@ public void testNullSafeInnerConstraint(KieBaseTestConfiguration kieBaseTestConf "rule \"Complex Type Attribute\"\n" + "when\n" + " $con : Content()\n" + - " Context( ctx == $con || == $con!.complexContent!.extension )\n" + + " Context( ctx == $con || ctx == $con!.complexContent!.extension )\n" + "then\n" + " System.out.println( $con ); \n" + "end\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/compiler/integrationtests/test_CEP_ComplexOperator.drl b/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/compiler/integrationtests/test_CEP_ComplexOperator.drl index 7c154a486ac..6b760f0e4c5 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/compiler/integrationtests/test_CEP_ComplexOperator.drl +++ b/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/compiler/integrationtests/test_CEP_ComplexOperator.drl @@ -32,7 +32,7 @@ end rule "before" when $a : StockTick( company == "DROO" ) - $b : StockTick( company != $a.company, this before[5,8] $a.time || after[20,22] $a ) + $b : StockTick( company != $a.company, this before[5,8] $a.time || this after[20,22] $a ) then list.add( new StockTick[] { $a, $b } ); end diff --git a/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/compiler/integrationtests/test_ConstraintConnectors.drl b/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/compiler/integrationtests/test_ConstraintConnectors.drl index 2028756d5e8..d87772c59c5 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/compiler/integrationtests/test_ConstraintConnectors.drl +++ b/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/compiler/integrationtests/test_ConstraintConnectors.drl @@ -26,7 +26,7 @@ global java.util.List results; rule "1. && operator" salience 10 when - $person : Person( age > 30 && < 40 && hair == "red" ) + $person : Person( age > 30 && age < 40 && hair == "red" ) then results.add( $person ); end @@ -34,7 +34,7 @@ end rule "2. || operator" salience 8 when - $person : Person( age > 70 && < 90 || hair == "green" ) + $person : Person( age > 70 && age < 90 || hair == "green" ) then results.add( $person ); end diff --git a/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/mvel/integrationtests/strevaluator_test.drl b/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/mvel/integrationtests/strevaluator_test.drl index 773af9402f4..bb4e660ab37 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/mvel/integrationtests/strevaluator_test.drl +++ b/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/mvel/integrationtests/strevaluator_test.drl @@ -68,7 +68,7 @@ end rule testmultiple when - $m : RoutingMessage( routingValue str[startsWith] "R1" && str[endsWith] "R2" && str[length] 17) + $m : RoutingMessage( routingValue str[startsWith] "R1" && routingValue str[endsWith] "R2" && routingValue str[length] 17) then list.add("Message starts with R1, ends with R2 and it's length is 17"); end diff --git a/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/functional/TemplatesTest.java b/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/functional/TemplatesTest.java index d08eaecd1af..1fd1be9f8f7 100644 --- a/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/functional/TemplatesTest.java +++ b/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/functional/TemplatesTest.java @@ -69,20 +69,20 @@ public static Stream parameters() { + "global java.util.List list;\n\n"; final String rule2_when = "rule \"is appropriate 2\"\n" + "\twhen\n" - + "\t\tVegetable( $name : name == \"carrot\", $field : weight >= 0 && <= 1000, $price : price <= 2, " + + "\t\tVegetable( $name : name == \"carrot\", $field : weight >= 0 && weight <= 1000, $price : price <= 2, " + "$taste : taste == Taste.HORRIBLE )\n"; final String rule2_then = "\tthen\n\t\tlist.add( $name );\nend\n\n"; final String rule1_when = "rule \"is appropriate 1\"\n" + "\twhen\n" - + "\t\tVegetable( $name : name == \"cucumber\", $field : length >= 20 && <= 40, $price : price <= 15, " + + "\t\tVegetable( $name : name == \"cucumber\", $field : length >= 20 && length <= 40, $price : price <= 15, " + "$taste : taste == Taste.EXCELENT )\n"; final String rule1_then = "\tthen\n\t\tlist.add( $name );\nend\n\n"; final String rule0_when = "rule \"is appropriate 0\"\n" + "\twhen\n" - + "\t\tVegetable( $name : name == \"tomato\", $field : weight >= 200 && <= 1000, $price : price <= 6, " - + "$taste : taste == Taste.GOOD || == Taste.EXCELENT )\n"; + + "\t\tVegetable( $name : name == \"tomato\", $field : weight >= 200 && weight <= 1000, $price : price <= 6, " + + "$taste : taste == Taste.GOOD || taste == Taste.EXCELENT )\n"; final String rule0_then = "\tthen\n\t\tlist.add( $name );\nend\n\n"; EXPECTED_RULES.append(head); @@ -135,7 +135,7 @@ public void loadingFromDLRMapsCorrectnessCheck(KieBaseTestConfiguration kieBaseT @MethodSource("parameters") public void loadingFromDLRArrayCorrectnessCheck(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { final String[][] rows = new String[3][6]; - rows[0] = new String[]{"tomato", "weight", "200", "1000", "6", "== Taste.GOOD || == Taste.EXCELENT"}; + rows[0] = new String[]{"tomato", "weight", "200", "1000", "6", "== Taste.GOOD || taste == Taste.EXCELENT"}; rows[1] = new String[]{"cucumber", "length", "20", "40", "15", "== Taste.EXCELENT"}; rows[2] = new String[]{"carrot", "weight", "0", "1000", "2", "== Taste.HORRIBLE"}; @@ -336,7 +336,7 @@ private Collection> getMapsParam() { mapTomato.put("fieldLower", 200); mapTomato.put("fieldUpper", 1000); mapTomato.put("price", 6); - mapTomato.put("tastes", "== Taste.GOOD || == Taste.EXCELENT"); + mapTomato.put("tastes", "== Taste.GOOD || taste == Taste.EXCELENT"); maps.add(mapTomato); final Map mapCucumber = new HashMap(); @@ -420,7 +420,7 @@ public String getTastes() { String conn = ""; for (Taste t : tasteSet) { sb.append(conn).append(" == Taste.").append(t); - conn = " ||"; + conn = " || taste"; } return sb.toString(); } diff --git a/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/regression/AbstractCompositeRestrictionTest.java b/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/regression/AbstractCompositeRestrictionTest.java index 9454031c660..bd03fe49e29 100644 --- a/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/regression/AbstractCompositeRestrictionTest.java +++ b/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/regression/AbstractCompositeRestrictionTest.java @@ -24,6 +24,7 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieUtil; import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieServices; @@ -42,6 +43,7 @@ public static Stream parameters() { return TestParametersUtil2.getKieBaseConfigurations().stream(); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @ParameterizedTest(name = "KieBase type={0}") @MethodSource("parameters") public void test(KieBaseTestConfiguration kieBaseTestConfiguration) { diff --git a/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/regression/MultiRestrictionPatternTest.java b/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/regression/MultiRestrictionPatternTest.java index 01fcb74a43c..e98774efd99 100644 --- a/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/regression/MultiRestrictionPatternTest.java +++ b/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/regression/MultiRestrictionPatternTest.java @@ -28,6 +28,7 @@ import org.drools.testcoverage.common.util.KieSessionTestConfiguration; import org.drools.testcoverage.common.util.KieUtil; import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -41,6 +42,7 @@ * Test to verify BRMS-364 (multi-restriction pattern throws UnsupportedOpEx) is * fixed */ +@DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") public class MultiRestrictionPatternTest extends KieSessionTest { private static final String DRL_FILE = "BRMS-364.drl"; diff --git a/drools-test-coverage/test-suite/src/test/resources/org/drools/testcoverage/functional/template1_spreadsheet.drl.xls b/drools-test-coverage/test-suite/src/test/resources/org/drools/testcoverage/functional/template1_spreadsheet.drl.xls index a5bea4dd27bec722301874271960db83226391c7..a271469e6c3c8acde483ab56ac9e67a35fe38773 100644 GIT binary patch delta 438 zcmZp$X|UOFgM;Y{M&a^Wn%yWHiqDg)YKBgRt7!>D=s7v zBanzB50Z#+4+9GWBM?sZ;;muaH2FBMj-&FzK#>xBmIhhzIO^y?uH2J)! z@@5kuc_cB_$w{I!CW(EpodMLx4%W-S-~gmqfY<|wIe|C^h(Y0%0mR%uTmr5x7DhH#Ki42fpUqD=b(pQ@voQbx8$)nLYHEpLD+3>c2^W%x z5lBRs2T8=Zhk=D*3F8vR$zHrQjB6$z=hYEbVqmbfRR~EeE=kpM_xE>EsHxe^!*__W z{*kySNGn4v0}lfu5cUfp_)H8;4267RaCv41W`;r@gggt-o)v-!J}Uz&Lm@wc&jxgL zA(A{h!yg72PKZ1M6CcRj&AtK$82NaC7BhhH|NjjCH%klIF>-T*odgn|GC4(f5(_RF z)yWy6GbaBM{pPv@sF(w4jt7ut0pb9tSPGEl1mYSX28CV+5OV|Z6d(qL-2x!y1>!Z6 zb;Xr6K~D25OH??z_wd5({IbIffqXe2W(Hy-Qw9bHAk8pA^M>K%L~(hJhEO*a`TVnt clNDJcHXjhTU}pTZ`KMGpBjbzBl``#&04C{IrT_o{ diff --git a/drools-test-coverage/test-suite/src/test/resources/org/drools/testcoverage/functional/template_1.drl b/drools-test-coverage/test-suite/src/test/resources/org/drools/testcoverage/functional/template_1.drl index 2a1764ba46f..164fe37cc31 100644 --- a/drools-test-coverage/test-suite/src/test/resources/org/drools/testcoverage/functional/template_1.drl +++ b/drools-test-coverage/test-suite/src/test/resources/org/drools/testcoverage/functional/template_1.drl @@ -36,7 +36,7 @@ template "appropriateToBuy" rule "is appropriate @{row.rowNumber}" when - Vegetable( $name : name == "@{name}", $field : @{field} >= @{fieldLower} && <= @{fieldUpper}, $price : price <= @{price}, $taste : taste @{tastes} ) + Vegetable( $name : name == "@{name}", $field : @{field} >= @{fieldLower} && @{field} <= @{fieldUpper}, $price : price <= @{price}, $taste : taste @{tastes} ) then list.add( $name ); end diff --git a/drools-test-coverage/test-suite/src/test/resources/org/drools/testcoverage/functional/template_2.drl b/drools-test-coverage/test-suite/src/test/resources/org/drools/testcoverage/functional/template_2.drl index cffa7054095..a4e94f2fe5d 100644 --- a/drools-test-coverage/test-suite/src/test/resources/org/drools/testcoverage/functional/template_2.drl +++ b/drools-test-coverage/test-suite/src/test/resources/org/drools/testcoverage/functional/template_2.drl @@ -36,7 +36,7 @@ template "appropriateToBuy" rule "is appropriate @{row.rowNumber}" when - Vegetable( $name : name == "@{name}", $field : @{field} >= @{fieldLower} && <= @{fieldUpper}, $price : price <= @{price}, $taste : taste @{tastes} ) + Vegetable( $name : name == "@{name}", $field : @{field} >= @{fieldLower} && @{field} <= @{fieldUpper}, $price : price <= @{price}, $taste : taste @{tastes} ) then list.add( $name ); end @@ -114,7 +114,7 @@ template "goodPriceAndSize" rule "is of good price and size @{row.rowNumber}" when - Vegetable( $name : name == "@{name}", $field : @{field} >= @{fieldLower} && <= @{fieldUpper}, $price : price <= @{price} ) + Vegetable( $name : name == "@{name}", $field : @{field} >= @{fieldLower} && @{field} <= @{fieldUpper}, $price : price <= @{price} ) then list.add( $name ); end @@ -136,7 +136,7 @@ end template rule "is of right size and taste @{row.rowNumber}" when - Vegetable( $name : name == "@{name}", $field : @{field} >= @{fieldLower} && <= @{fieldUpper}, $taste : taste @{tastes} ) + Vegetable( $name : name == "@{name}", $field : @{field} >= @{fieldLower} && @{field} <= @{fieldUpper}, $taste : taste @{tastes} ) then list.add( $name ); end diff --git a/drools-test-coverage/test-suite/src/test/resources/org/drools/testcoverage/regression/sessionInsertMultithreadingTest.drl b/drools-test-coverage/test-suite/src/test/resources/org/drools/testcoverage/regression/sessionInsertMultithreadingTest.drl index d6352282945..fc41fa64702 100644 --- a/drools-test-coverage/test-suite/src/test/resources/org/drools/testcoverage/regression/sessionInsertMultithreadingTest.drl +++ b/drools-test-coverage/test-suite/src/test/resources/org/drools/testcoverage/regression/sessionInsertMultithreadingTest.drl @@ -24,7 +24,7 @@ import org.drools.testcoverage.common.model.Message rule "Name" when - $p : Person ( name == "" || == null ) + $p : Person ( name == "" || name == null ) then modify ($p) { setName("Aquaman"); @@ -34,7 +34,7 @@ end rule "Message" no-loop when - $m : Message ( message == "" || == null ) + $m : Message ( message == "" || message == null ) then modify ($m) { setMessage("Hello world"); @@ -53,7 +53,7 @@ end rule "Message from" salience -10 when - $p : Person ( name != "" && != null && id != 0) + $p : Person ( name != "" && name != null && id != 0) $m : Message ( message == "Hello world" ) then modify ($m) { diff --git a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitMapCoreTest.java b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitMapCoreTest.java index d4d9cae880c..e7c59734353 100644 --- a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitMapCoreTest.java +++ b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitMapCoreTest.java @@ -298,7 +298,7 @@ public void testMapCoreAliasing( ) { "\n" + "rule Log \n" + "when \n" + - " $p : PersonMap( name == \"john\", age > 10 && < 35 )\n" + + " $p : PersonMap( name == \"john\", age > 10 && age < 35 )\n" + "then \n" + " modify ( $p ) { \n" + " setHeight( 184.0 ), \n" + diff --git a/drools-verifier/drools-verifier-drl/pom.xml b/drools-verifier/drools-verifier-drl/pom.xml index 2b93a9c78b1..474178b3a6b 100644 --- a/drools-verifier/drools-verifier-drl/pom.xml +++ b/drools-verifier/drools-verifier-drl/pom.xml @@ -179,5 +179,26 @@ + + + enableNewParser + + + enableNewParser + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + true + + + + + diff --git a/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/builder/VerifierKnowledgeBaseBuilder.java b/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/builder/VerifierKnowledgeBaseBuilder.java index 10410deba94..528932959cb 100644 --- a/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/builder/VerifierKnowledgeBaseBuilder.java +++ b/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/builder/VerifierKnowledgeBaseBuilder.java @@ -22,6 +22,7 @@ import java.util.Iterator; import java.util.List; +import org.drools.compiler.builder.impl.KnowledgeBuilderImpl; import org.drools.kiesession.rulebase.InternalKnowledgeBase; import org.drools.kiesession.rulebase.KnowledgeBaseFactory; import org.drools.verifier.VerifierConfiguration; @@ -31,6 +32,7 @@ import org.kie.internal.builder.KnowledgeBuilder; import org.kie.internal.builder.KnowledgeBuilderError; import org.kie.internal.builder.KnowledgeBuilderFactory; +import org.kie.internal.builder.conf.LanguageLevelOption; public class VerifierKnowledgeBaseBuilder { @@ -41,6 +43,11 @@ public KieBase newVerifierKnowledgeBase(VerifierConfiguration configuration) { InternalKnowledgeBase verifierKnowledgeBase = KnowledgeBaseFactory.newKnowledgeBase(); KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); + LanguageLevelOption option = ((KnowledgeBuilderImpl) kbuilder).getBuilderConfiguration().getOption(LanguageLevelOption.KEY); + if (option == LanguageLevelOption.DRL10) { + // Temporarily verifier rules can be migrated to DRL10 (= fix half constraint). Need to be discussed. + throw new UnsupportedOperationException("Verifier does not support DRL10"); + } if ( configuration.getVerifyingResources() != null ) { for ( Resource resource : configuration.getVerifyingResources().keySet() ) { From 85c2ab5c90bc88efb4a8d71c43747c6e187dd824 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Thu, 23 Jan 2025 18:17:45 +0900 Subject: [PATCH 5/8] - drop infix doubleAmpersand and doublePipe --- .gitignore | 1 + .../org/drools/drl/parser/antlr4/MiscDRLParserTest.java | 3 +++ .../main/antlr4/org/drools/drl/parser/antlr4/DRL10Parser.g4 | 6 +++--- .../java/org/drools/mvel/integrationtests/Misc2Test.java | 2 +- .../mvel/integrationtests/test_OrCEFollowedByCollect.drl | 2 +- 5 files changed, 9 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index 655baabbb2b..2d195d5f653 100644 --- a/.gitignore +++ b/.gitignore @@ -29,6 +29,7 @@ nbproject *.ipr *.iws *.iml +build.log # generated files dependency-reduced-pom.xml diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java index 40fb99d67fd..f51d7c76ebe 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java @@ -5140,6 +5140,7 @@ void accumulateEmptyChunks() { assertThat(accumulateDescr.getResultCode()).isEqualTo("null"); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @Test void doublePipeInfixOr() { final String text = @@ -5161,6 +5162,7 @@ void doublePipeInfixOr() { }); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @Test void doubleAmpersandInfixAnd() { final String text = @@ -5180,6 +5182,7 @@ void doubleAmpersandInfixAnd() { }); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @Test void doubleAmpersandInfixAndInAccumulate() { final String text = diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Parser.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Parser.g4 index cc5080da384..8e2734761fc 100644 --- a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Parser.g4 +++ b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Parser.g4 @@ -123,15 +123,15 @@ queryLhs : lhsExpression* ; lhsExpression : LPAREN lhsExpression RPAREN #lhsExpressionEnclosed | DRL_OR drlAnnotation* lhsExpression+ #lhsOr - | lhsExpression ((DRL_OR|OR) drlAnnotation* lhsExpression)+ #lhsOr + | lhsExpression ((DRL_OR) drlAnnotation* lhsExpression)+ #lhsOr | DRL_AND drlAnnotation* lhsExpression+ #lhsAnd - | lhsExpression ((DRL_AND|AND) drlAnnotation* lhsExpression)+ #lhsAnd + | lhsExpression ((DRL_AND) drlAnnotation* lhsExpression)+ #lhsAnd | lhsUnary #lhsUnarySingle ; // lhsAnd is used as a label in lhsExpression rule. But some other rules explicitly use the def, so lhsAndDef is declared. lhsAndDef : LPAREN lhsAndDef RPAREN - | lhsUnary ((DRL_AND|AND) lhsUnary)* + | lhsUnary ((DRL_AND) lhsUnary)* | LPAREN DRL_AND lhsUnary+ RPAREN ; diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/Misc2Test.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/Misc2Test.java index 4d72e3b2bcb..d37fd0bfc66 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/Misc2Test.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/Misc2Test.java @@ -8902,7 +8902,7 @@ public void testMergeMVELDialect(KieBaseTestConfiguration kieBaseTestConfigurati "rule rule1 \n" + " when\n" + " (PersonHolder($addresses : person.addresses))\n" + - " &&\n" + + " and\n" + " (Address (street == \"AAA\") from $addresses)\n" + " then\n" + "end"; diff --git a/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/mvel/integrationtests/test_OrCEFollowedByCollect.drl b/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/mvel/integrationtests/test_OrCEFollowedByCollect.drl index b22f6bc40f7..51d717f2cb7 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/mvel/integrationtests/test_OrCEFollowedByCollect.drl +++ b/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/mvel/integrationtests/test_OrCEFollowedByCollect.drl @@ -24,7 +24,7 @@ import java.util.ArrayList rule "collect after or'd evals" when $bonFromage : Cheesery() - (eval(true) || eval(true)) + (eval(true) or eval(true)) ArrayList( size > 1 ) from collect(Cheese( type == "cheddar") from $bonFromage.cheeses) then end \ No newline at end of file From c82a1086819710e9ce5e8233285ff228a9efb7b3 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Thu, 23 Jan 2025 18:39:35 +0900 Subject: [PATCH 6/8] - drop Annotation inside LHS --- .../org/drools/drl/parser/antlr4/MiscDRLParserTest.java | 4 ++++ .../antlr4/org/drools/drl/parser/antlr4/DRL10Parser.g4 | 8 ++++---- .../drools/compiler/integrationtests/AnnotationsTest.java | 2 ++ 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java index f51d7c76ebe..fd8397b5a65 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java @@ -4057,6 +4057,7 @@ void lhsPatternAnnotation() { assertThat(annotationDescr.getSingleValueAsString()).isEqualTo("!*, age"); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @Test void prefixAndDescrAnnotation() { final String text = @@ -4078,6 +4079,7 @@ void prefixAndDescrAnnotation() { assertThat(andDescr.getDescrs()).hasSize(2); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @Test void prefixOrDescrAnnotation() { final String text = @@ -4100,6 +4102,7 @@ void prefixOrDescrAnnotation() { assertThat(orDescr.getDescrs()).hasSize(2); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @Test void infixAndDescrAnnotation() { final String text = @@ -4120,6 +4123,7 @@ void infixAndDescrAnnotation() { assertThat(andDescr.getDescrs()).hasSize(3); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @Test void infixOrDescrAnnotation() { final String text = diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Parser.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Parser.g4 index 8e2734761fc..05f20df5eda 100644 --- a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Parser.g4 +++ b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Parser.g4 @@ -122,10 +122,10 @@ lhs : DRL_WHEN lhsExpression* ; queryLhs : lhsExpression* ; lhsExpression : LPAREN lhsExpression RPAREN #lhsExpressionEnclosed - | DRL_OR drlAnnotation* lhsExpression+ #lhsOr - | lhsExpression ((DRL_OR) drlAnnotation* lhsExpression)+ #lhsOr - | DRL_AND drlAnnotation* lhsExpression+ #lhsAnd - | lhsExpression ((DRL_AND) drlAnnotation* lhsExpression)+ #lhsAnd + | DRL_OR lhsExpression+ #lhsOr + | lhsExpression ((DRL_OR) lhsExpression)+ #lhsOr + | DRL_AND lhsExpression+ #lhsAnd + | lhsExpression ((DRL_AND) lhsExpression)+ #lhsAnd | lhsUnary #lhsUnarySingle ; diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsTest.java index 267e636c286..0ece362d7ee 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsTest.java @@ -30,6 +30,7 @@ import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; @@ -273,6 +274,7 @@ public void testAnnotationNameClashWithRegularClass(KieBaseTestConfiguration kie int[] numbers(); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @ParameterizedTest(name = "KieBase type={0}") @MethodSource("parameters") public void testAnnotationOnLHSAndMerging(KieBaseTestConfiguration kieBaseTestConfiguration) { From 45b58cc402c7a92a389afdaf441fbf46d06fc1b5 Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Fri, 24 Jan 2025 15:21:03 +0900 Subject: [PATCH 7/8] - additional test for end token --- .../drl/parser/antlr4/MiscDRLParserTest.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java index fd8397b5a65..9a1012d2077 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java @@ -3589,6 +3589,22 @@ void endTokenInRhs() { assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("int end = 10;"); } + @Test + void endTokenWithSemiInRhs() { + final String text = "package org.drools\n" + + "rule X\n" + + "when\n" + + " $s : String()\n" + + "then\n" + + " int end = 10;" + + " int a = end;\n" + + "end;\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("int end = 10; int a = end;"); + } + @Test void ruleTokenInRhs() { final String text = "package org.drools\n" + From 37a218d42453aade4119a639fbae5c6463709d0c Mon Sep 17 00:00:00 2001 From: Toshiya Kobayashi Date: Wed, 29 Jan 2025 18:10:48 +0900 Subject: [PATCH 8/8] - replace agenda-group with ruleflow-group - adjust unit tests --- .../antlr4/DescrCommonPropertyTest.java | 6 +- .../drl/parser/antlr4/MiscDRLParserTest.java | 22 ++-- .../drl/parser/antlr4/package_attributes.drl | 2 +- .../drl/parser/antlr4/rule_attributes.drl | 2 +- .../drl/parser/antlr4/rule_attributes2.drl | 2 +- .../drl/parser/antlr4/rule_attributes_alt.drl | 2 +- .../drl/parser/antlr4/DRL10Expressions.g4 | 1 - .../drools/drl/parser/antlr4/DRL10Lexer.g4 | 1 - .../drools/drl/parser/antlr4/DRL10Parser.g4 | 2 +- .../org/drools/mvel/CommonTestMethodBase.java | 10 ++ .../codegen/execmodel/BaseModelTest.java | 11 +- .../JpaPersistentStatefulSessionTest.java | 3 + .../session/AgendaRuleFlowGroupsTest.java | 8 +- .../JpaPersistentStatefulSessionTest.java | 5 +- .../impl/RuleUnitProviderImplTest.java | 2 + .../protobuf/MarshallingTest.java | 2 + .../protobuf/test_Serializable.drl | 6 +- .../DeclarativeAgendaTest.java | 6 +- .../testcoverage/common/util/KieUtil.java | 103 +++++++++++++++++- 19 files changed, 161 insertions(+), 35 deletions(-) diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrCommonPropertyTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrCommonPropertyTest.java index 2e1a0e8564e..ae374091b65 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrCommonPropertyTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrCommonPropertyTest.java @@ -245,7 +245,7 @@ void typeFieldDescr() { void attributeDescr() { final String source = "rule R1\n" + " salience 42\n" + - " agenda-group \"my_group\"\n" + + " ruleflow-group \"my_group\"\n" + " when\n" + " then\n" + "end"; @@ -257,10 +257,10 @@ void attributeDescr() { // Backward compatibility doesn't seem to be required in this case. (If do it, the code would be unnecessarily complicated.) if (DrlParser.ANTLR4_PARSER_ENABLED) { assertProperties(rule.getAttributes().get("salience"), 10, 21, 2, 2, 2, 12); - assertProperties(rule.getAttributes().get("agenda-group"), 24, 47, 3, 2, 3, 24); + assertProperties(rule.getAttributes().get("ruleflow-group"), 24, 49, 3, 2, 3, 26); } else { assertProperties(rule.getAttributes().get("salience"), 19, 21, 2, 11, 2, 12); - assertProperties(rule.getAttributes().get("agenda-group"), 37, 47, 3, 15, 3, 24); + assertProperties(rule.getAttributes().get("ruleflow-group"), 39, 49, 3, 17, 3, 26); } } diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java index 9a1012d2077..8f96434b385 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java @@ -1765,8 +1765,8 @@ void attributes() { assertThat(at.getName()).isEqualTo("salience"); assertThat(at.getValue()).isEqualTo("42"); - at = (AttributeDescr) attrs.get("agenda-group"); - assertThat(at.getName()).isEqualTo("agenda-group"); + at = (AttributeDescr) attrs.get("ruleflow-group"); + assertThat(at.getName()).isEqualTo("ruleflow-group"); assertThat(at.getValue()).isEqualTo("my_group"); at = (AttributeDescr) attrs.get("no-loop"); @@ -1801,8 +1801,8 @@ void attributes2() { AttributeDescr at = (AttributeDescr) attrs.get("salience"); assertThat(at.getName()).isEqualTo("salience"); assertThat(at.getValue()).isEqualTo("(42)"); - at = (AttributeDescr) attrs.get("agenda-group"); - assertThat(at.getName()).isEqualTo("agenda-group"); + at = (AttributeDescr) attrs.get("ruleflow-group"); + assertThat(at.getName()).isEqualTo("ruleflow-group"); assertThat(at.getValue()).isEqualTo("my_group"); rule = rules.get(1); @@ -1957,8 +1957,8 @@ void attributes_alternateSyntax() { assertThat(at.getName()).isEqualTo("salience"); assertThat(at.getValue()).isEqualTo("42"); - at = attrs.get("agenda-group"); - assertThat(at.getName()).isEqualTo("agenda-group"); + at = attrs.get("ruleflow-group"); + assertThat(at.getName()).isEqualTo("ruleflow-group"); assertThat(at.getValue()).isEqualTo("my_group"); at = attrs.get("no-loop"); @@ -2015,7 +2015,7 @@ void packageAttributes() { "package_attributes.drl"); AttributeDescr at = (AttributeDescr) pkg.getAttributes().get(0); - assertThat(at.getName()).isEqualTo("agenda-group"); + assertThat(at.getName()).isEqualTo("ruleflow-group"); assertThat(at.getValue()).isEqualTo("x"); at = (AttributeDescr) pkg.getAttributes().get(1); assertThat(at.getName()).isEqualTo("dialect"); @@ -2027,8 +2027,8 @@ void packageAttributes() { RuleDescr rule = (RuleDescr) pkg.getRules().get(0); assertThat(rule.getName()).isEqualTo("bar"); - at = (AttributeDescr) rule.getAttributes().get("agenda-group"); - assertThat(at.getName()).isEqualTo("agenda-group"); + at = (AttributeDescr) rule.getAttributes().get("ruleflow-group"); + assertThat(at.getName()).isEqualTo("ruleflow-group"); assertThat(at.getValue()).isEqualTo("x"); at = (AttributeDescr) rule.getAttributes().get("dialect"); assertThat(at.getName()).isEqualTo("dialect"); @@ -2039,8 +2039,8 @@ void packageAttributes() { at = (AttributeDescr) rule.getAttributes().get("dialect"); assertThat(at.getName()).isEqualTo("dialect"); assertThat(at.getValue()).isEqualTo("mvel"); - at = (AttributeDescr) rule.getAttributes().get("agenda-group"); - assertThat(at.getName()).isEqualTo("agenda-group"); + at = (AttributeDescr) rule.getAttributes().get("ruleflow-group"); + assertThat(at.getName()).isEqualTo("ruleflow-group"); assertThat(at.getValue()).isEqualTo("x"); } diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/package_attributes.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/package_attributes.drl index 156f5c58f6d..5f1cd1b5fd8 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/package_attributes.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/package_attributes.drl @@ -17,7 +17,7 @@ package com.foo; -agenda-group "x" +ruleflow-group "x" import goo.ber import wee.waa diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes.drl index faf0d0c3351..9b68c4f617a 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes.drl @@ -21,7 +21,7 @@ rule simple_rule // attributes keywork (and colon) is totally optional salience 42 - agenda-group "my_group" + ruleflow-group "my_group" no-loop duration 42 activation-group "my_activation_group" diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes2.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes2.drl index cece840aa59..279dc33963d 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes2.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes2.drl @@ -20,7 +20,7 @@ package foo.bar rule rule1 salience (42) - agenda-group "my_group" + ruleflow-group "my_group" when Foo() then diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes_alt.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes_alt.drl index fafc7032171..34a1baa5632 100644 --- a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes_alt.drl +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes_alt.drl @@ -20,7 +20,7 @@ rule simple_rule attributes: - salience 42, agenda-group "my_group", no-loop, lock-on-active, duration 42, activation-group "my_activation_group" + salience 42, ruleflow-group "my_group", no-loop, lock-on-active, duration 42, activation-group "my_activation_group" when Foo() then diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Expressions.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Expressions.g4 index e5030c2362c..a022c96c121 100644 --- a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Expressions.g4 +++ b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Expressions.g4 @@ -290,7 +290,6 @@ drlKeywords returns [Token token] | DRL_LOCK_ON_ACTIVE | DRL_REFRACT | DRL_DIRECT - | DRL_AGENDA_GROUP | DRL_ACTIVATION_GROUP | DRL_RULEFLOW_GROUP | DRL_DATE_EFFECTIVE diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Lexer.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Lexer.g4 index 6ef44add5fd..ed673f881b2 100644 --- a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Lexer.g4 +++ b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Lexer.g4 @@ -115,7 +115,6 @@ DRL_AUTO_FOCUS : 'auto-focus'; DRL_LOCK_ON_ACTIVE : 'lock-on-active'; DRL_REFRACT : 'refract'; DRL_DIRECT : 'direct'; -DRL_AGENDA_GROUP : 'agenda-group'; DRL_ACTIVATION_GROUP : 'activation-group'; DRL_RULEFLOW_GROUP : 'ruleflow-group'; DRL_DATE_EFFECTIVE : 'date-effective'; diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Parser.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Parser.g4 index 05f20df5eda..cca81800df4 100644 --- a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Parser.g4 +++ b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL10Parser.g4 @@ -462,7 +462,7 @@ drlAnnotation attributes : (DRL_ATTRIBUTES COLON?)? attribute ( COMMA? attribute )* ; attribute : name=( DRL_SALIENCE | DRL_ENABLED ) conditionalAttributeValue #expressionAttribute | name=( DRL_NO_LOOP | DRL_AUTO_FOCUS | DRL_LOCK_ON_ACTIVE | DRL_REFRACT | DRL_DIRECT ) BOOL_LITERAL? #booleanAttribute - | name=( DRL_AGENDA_GROUP | DRL_ACTIVATION_GROUP | DRL_RULEFLOW_GROUP | DRL_DATE_EFFECTIVE | DRL_DATE_EXPIRES | DRL_DIALECT ) DRL_STRING_LITERAL #stringAttribute + | name=( DRL_ACTIVATION_GROUP | DRL_RULEFLOW_GROUP | DRL_DATE_EFFECTIVE | DRL_DATE_EXPIRES | DRL_DIALECT ) DRL_STRING_LITERAL #stringAttribute | name=DRL_CALENDARS DRL_STRING_LITERAL ( COMMA DRL_STRING_LITERAL )* #stringListAttribute | name=DRL_TIMER ( DECIMAL_LITERAL | LPAREN chunk RPAREN ) #intOrChunkAttribute | name=DRL_DURATION ( DECIMAL_LITERAL | LPAREN chunk RPAREN ) #intOrChunkAttribute diff --git a/drools-legacy-test-util/src/test/java/org/drools/mvel/CommonTestMethodBase.java b/drools-legacy-test-util/src/test/java/org/drools/mvel/CommonTestMethodBase.java index 9a662471249..c0605331816 100644 --- a/drools-legacy-test-util/src/test/java/org/drools/mvel/CommonTestMethodBase.java +++ b/drools-legacy-test-util/src/test/java/org/drools/mvel/CommonTestMethodBase.java @@ -28,6 +28,7 @@ import org.drools.core.common.InternalAgenda; import org.drools.core.impl.RuleBaseFactory; import org.drools.core.integrationtests.SerializationHelper; +import org.drools.drl.parser.DrlParser; import org.drools.kiesession.rulebase.InternalKnowledgeBase; import org.drools.kiesession.rulebase.KnowledgeBaseFactory; import org.kie.api.KieBase; @@ -126,6 +127,7 @@ protected KieBase loadKnowledgeBaseFromString( protected KieBase loadKnowledgeBaseFromString( KnowledgeBuilderConfiguration config, KieBaseConfiguration kBaseConfig, String... drlContentStrings) { KnowledgeBuilder kbuilder = config == null ? KnowledgeBuilderFactory.newKnowledgeBuilder() : KnowledgeBuilderFactory.newKnowledgeBuilder(config); for (String drlContentString : drlContentStrings) { + drlContentString = replaceAgendaGroupIfRequired(drlContentString); kbuilder.add(ResourceFactory.newByteArrayResource(drlContentString .getBytes()), ResourceType.DRL); } @@ -141,6 +143,14 @@ protected KieBase loadKnowledgeBaseFromString( KnowledgeBuilderConfiguration con return kbase; } + public static String replaceAgendaGroupIfRequired(String drl) { + if (DrlParser.ANTLR4_PARSER_ENABLED) { + // new parser (DRL10) supports only ruleflow-group, dropping agenda-group + return drl.replaceAll("agenda-group", "ruleflow-group"); + } + return drl; + } + protected KieBase loadKnowledgeBase(KnowledgeBuilderConfiguration kbuilderConf, KieBaseConfiguration kbaseConf, String... classPathResources) { Collection knowledgePackages = loadKnowledgePackages(kbuilderConf, classPathResources); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BaseModelTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BaseModelTest.java index 20e3bfe6141..9a6dc9e0c0a 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BaseModelTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BaseModelTest.java @@ -27,6 +27,7 @@ import org.drools.compiler.kie.builder.impl.InternalKieModule; import org.drools.core.reteoo.EntryPointNode; import org.drools.core.reteoo.ObjectTypeNode; +import org.drools.drl.parser.DrlParser; import org.drools.kiesession.rulebase.InternalKnowledgeBase; import org.drools.model.codegen.ExecutableModelProject; import org.kie.api.KieServices; @@ -185,7 +186,15 @@ public KieFile( int index, String content ) { public KieFile( String path, String content ) { this.path = path; - this.content = content; + this.content = replaceAgendaGroupIfRequired(content); + } + + public static String replaceAgendaGroupIfRequired(String drl) { + if (DrlParser.ANTLR4_PARSER_ENABLED) { + // new parser (DRL10) supports only ruleflow-group, dropping agenda-group + return drl.replaceAll("agenda-group", "ruleflow-group"); + } + return drl; } } diff --git a/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/kie/persistence/session/JpaPersistentStatefulSessionTest.java b/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/kie/persistence/session/JpaPersistentStatefulSessionTest.java index 388844d6da8..c1f2ca0c131 100644 --- a/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/kie/persistence/session/JpaPersistentStatefulSessionTest.java +++ b/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/kie/persistence/session/JpaPersistentStatefulSessionTest.java @@ -34,6 +34,7 @@ import org.drools.commands.impl.CommandBasedStatefulKnowledgeSessionImpl; import org.drools.commands.impl.FireAllRulesInterceptor; import org.drools.commands.impl.LoggingInterceptor; +import org.drools.mvel.CommonTestMethodBase; import org.drools.mvel.compiler.Person; import org.drools.persistence.PersistableRunner; import org.drools.persistence.util.DroolsPersistenceUtil; @@ -329,6 +330,8 @@ public void testSetFocus(String locking) { str += "end\n"; str += "\n"; + str = CommonTestMethodBase.replaceAgendaGroupIfRequired(str); + KieServices ks = KieServices.Factory.get(); KieFileSystem kfs = ks.newKieFileSystem().write( "src/main/resources/r1.drl", str ); diff --git a/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/session/AgendaRuleFlowGroupsTest.java b/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/session/AgendaRuleFlowGroupsTest.java index d05f9bcacd4..153638511f8 100644 --- a/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/session/AgendaRuleFlowGroupsTest.java +++ b/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/session/AgendaRuleFlowGroupsTest.java @@ -31,6 +31,7 @@ import org.drools.persistence.util.DroolsPersistenceUtil; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.drools.io.ClassPathResource; @@ -98,7 +99,8 @@ public void testRuleFlowGroupOnly(boolean locking) throws Exception { assertThat(groups[0].getName()).isEqualTo("MAIN"); assertThat(groups[1].getName()).isEqualTo("ruleflow-group"); } - + + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @ParameterizedTest @MethodSource("parameters") public void testAgendaGroupOnly(boolean locking) throws Exception { @@ -126,7 +128,8 @@ public void testAgendaGroupOnly(boolean locking) throws Exception { assertThat(groups[1].getName()).isEqualTo("agenda-group"); } - + + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @ParameterizedTest @MethodSource("parameters") public void testAgendaGroupAndRuleFlowGroup(boolean locking) throws Exception { @@ -234,6 +237,7 @@ public Void execute(Context context) { } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @ParameterizedTest @MethodSource("parameters") public void testConflictingAgendaAndRuleflowGroups() throws Exception { diff --git a/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/session/JpaPersistentStatefulSessionTest.java b/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/session/JpaPersistentStatefulSessionTest.java index 5619f959a91..1579861195b 100644 --- a/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/session/JpaPersistentStatefulSessionTest.java +++ b/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/session/JpaPersistentStatefulSessionTest.java @@ -37,6 +37,7 @@ import org.drools.core.FlowSessionConfiguration; import org.drools.core.SessionConfiguration; import org.drools.core.impl.RuleBaseFactory; +import org.drools.mvel.CommonTestMethodBase; import org.drools.mvel.compiler.Address; import org.drools.mvel.compiler.Person; import org.drools.persistence.PersistableRunner; @@ -361,7 +362,7 @@ public void testSetFocusWithOOPath() { } private void testFocus(final boolean withOOPath) { - final String str = "package org.kie.test\n" + + String str = "package org.kie.test\n" + "global java.util.List list\n" + "rule rule1\n" + "agenda-group \"badfocus\"" + @@ -372,6 +373,8 @@ private void testFocus(final boolean withOOPath) { "end\n" + "\n"; + str = CommonTestMethodBase.replaceAgendaGroupIfRequired(str); + final KieBase kbase = new KieHelper().addContent(str, ResourceType.DRL).build(); final KieSession ksession = KieServices.get().getStoreServices().newKieSession(kbase, null, env); diff --git a/drools-ruleunits/drools-ruleunits-impl/src/test/java/org/drools/ruleunits/impl/RuleUnitProviderImplTest.java b/drools-ruleunits/drools-ruleunits-impl/src/test/java/org/drools/ruleunits/impl/RuleUnitProviderImplTest.java index 822ab51fb3d..d13f5782ba3 100644 --- a/drools-ruleunits/drools-ruleunits-impl/src/test/java/org/drools/ruleunits/impl/RuleUnitProviderImplTest.java +++ b/drools-ruleunits/drools-ruleunits-impl/src/test/java/org/drools/ruleunits/impl/RuleUnitProviderImplTest.java @@ -34,6 +34,7 @@ import org.drools.ruleunits.impl.listener.TestRuleEventListener; import org.drools.ruleunits.impl.listener.TestRuleRuntimeEventListener; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; import org.kie.api.builder.CompilationErrorsException; import org.kie.api.event.rule.ObjectDeletedEvent; import org.kie.api.event.rule.ObjectInsertedEvent; @@ -179,6 +180,7 @@ public void wrongType() { } } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @Test public void agendaGroup() { try { diff --git a/drools-serialization-protobuf/src/test/java/org/drools/serialization/protobuf/MarshallingTest.java b/drools-serialization-protobuf/src/test/java/org/drools/serialization/protobuf/MarshallingTest.java index f80c8a7ee42..e49c934cdc9 100644 --- a/drools-serialization-protobuf/src/test/java/org/drools/serialization/protobuf/MarshallingTest.java +++ b/drools-serialization-protobuf/src/test/java/org/drools/serialization/protobuf/MarshallingTest.java @@ -77,6 +77,7 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; import org.kie.api.KieBase; import org.kie.api.KieBaseConfiguration; import org.kie.api.KieServices; @@ -1560,6 +1561,7 @@ public void testActivationGroups() throws Exception { assertThat(list.get(1)).isEqualTo("rule4"); } + @DisabledIfSystemProperty(named = "drools.drl.antlr4.parser.enabled", matches = "true") @Test public void testAgendaGroups() throws Exception { String rule1 = "package org.drools.compiler.test;\n"; diff --git a/drools-serialization-protobuf/src/test/resources/org/drools/serialization/protobuf/test_Serializable.drl b/drools-serialization-protobuf/src/test/resources/org/drools/serialization/protobuf/test_Serializable.drl index bd4e757963a..c9e9c73503b 100644 --- a/drools-serialization-protobuf/src/test/resources/org/drools/serialization/protobuf/test_Serializable.drl +++ b/drools-serialization-protobuf/src/test/resources/org/drools/serialization/protobuf/test_Serializable.drl @@ -38,7 +38,7 @@ end rule "match Person 2" - agenda-group "xxx" + ruleflow-group "xxx" salience ($age2 - $age1) when $person : Person(name=="mark", $age1 : age ) @@ -53,7 +53,7 @@ rule "match Person 2" end rule "match Person 3" - agenda-group "xxx" + ruleflow-group "xxx" dialect "mvel" when not Person( name == "mark" ) @@ -62,7 +62,7 @@ rule "match Person 3" end rule "match Integer" - agenda-group "yyy" + ruleflow-group "yyy" auto-focus true when Person( name == "bob" ) diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/DeclarativeAgendaTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/DeclarativeAgendaTest.java index c1cf2398f5f..38ece70bb54 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/DeclarativeAgendaTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/DeclarativeAgendaTest.java @@ -919,7 +919,6 @@ public void testFiredRuleDoNotRefireAfterUnblock(KieBaseTestConfiguration kieBas "end\n"; final KieServices ks = KieServices.Factory.get(); - KieFileSystem kfs = ks.newKieFileSystem(); KieModuleModel kmodule = ks.newKieModuleModel(); KieBaseModel baseModel = kmodule.newKieBaseModel("defaultKBase") @@ -928,10 +927,7 @@ public void testFiredRuleDoNotRefireAfterUnblock(KieBaseTestConfiguration kieBas baseModel.newKieSessionModel("defaultKSession") .setDefault(true); - kfs.writeKModuleXML(kmodule.toXML()); - kfs.write("src/main/resources/block_rule.drl", drl); - final KieBuilder kieBuilder = KieUtil.getKieBuilderFromKieFileSystem(kieBaseTestConfiguration, kfs, false); - assertThat(kieBuilder.getResults().getMessages(org.kie.api.builder.Message.Level.ERROR).size()).isEqualTo(0); + KieUtil.getKieBuilderFromDrls(kieBaseTestConfiguration, kmodule, true, drl); KieSession ksession = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).newKieSession(); diff --git a/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/common/util/KieUtil.java b/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/common/util/KieUtil.java index 4cf82ef2b13..9339101870a 100644 --- a/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/common/util/KieUtil.java +++ b/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/common/util/KieUtil.java @@ -17,8 +17,12 @@ * under the License. */ package org.drools.testcoverage.common.util; - +; +import java.io.IOException; +import java.io.InputStream; import java.io.StringReader; +import java.io.UncheckedIOException; +import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -34,6 +38,11 @@ import org.drools.core.reteoo.JoinNode; import org.drools.core.impl.InternalRuleBase; import org.drools.core.reteoo.ObjectTypeNode; +import org.drools.decisiontable.InputType; +import org.drools.decisiontable.SpreadsheetCompiler; +import org.drools.drl.parser.DrlParser; +import org.drools.io.ClassPathResource; +import org.drools.io.InternalResource; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; @@ -46,7 +55,10 @@ import org.kie.api.command.KieCommands; import org.kie.api.io.KieResources; import org.kie.api.io.Resource; +import org.kie.api.io.ResourceConfiguration; +import org.kie.api.io.ResourceType; import org.kie.api.runtime.KieContainer; +import org.kie.internal.builder.DecisionTableConfiguration; import org.kie.internal.builder.conf.AlphaNetworkCompilerOption; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -94,19 +106,106 @@ public static KieFileSystem getKieFileSystemWithKieModule(final KieModuleModel k final ReleaseId releaseId, final Resource... resources) { final KieFileSystem fileSystem = KieServices.Factory.get().newKieFileSystem(); fileSystem.generateAndWritePomXML(releaseId); - for (final Resource resource : resources) { + for (Resource resource : resources) { + resource = newResourceForNewParserIfRequired(resource); fileSystem.write(resource); } fileSystem.writeKModuleXML(kieModuleModel.toXML()); return fileSystem; } + private static Resource newResourceForNewParserIfRequired(Resource resource) { + if (DrlParser.ANTLR4_PARSER_ENABLED && resource instanceof InternalResource internalResource) { + if (isDrl(internalResource)) { + String encoding = internalResource.getEncoding(); + String drl; + if (encoding != null) { + try { + drl = new String(internalResource.getBytes(), encoding); + } catch (UnsupportedEncodingException e) { + throw new UncheckedIOException(e); + } + } else { + drl = new String(internalResource.getBytes()); + } + return convertResourceForNewParser(internalResource, drl); + } if (internalResource.getResourceType() == ResourceType.DTABLE) { + ResourceConfiguration resourceConfiguration = internalResource.getConfiguration(); + SpreadsheetCompiler compiler = new SpreadsheetCompiler(); + try (InputStream is = internalResource.getInputStream()) { + String drl; + if (resourceConfiguration instanceof DecisionTableConfiguration decisionTableConfiguration && decisionTableConfiguration.getWorksheetName() != null) { + drl = compiler.compile(is, decisionTableConfiguration.getWorksheetName()); + } else { + drl = compiler.compile(is, getInputType(internalResource)); + } + Resource resourceForNewParser = convertResourceForNewParser(internalResource, drl); + // overwrite + resourceForNewParser.setSourcePath(internalResource.getSourcePath() + ".drl"); + resourceForNewParser.setTargetPath(internalResource.getTargetPath() + ".drl"); + resourceForNewParser.setResourceType(ResourceType.DRL); + return resourceForNewParser; + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + } + return resource; + } + + private static boolean isDrl(InternalResource internalResource) { + String sourcePath = internalResource.getSourcePath(); + String targetPath = internalResource.getTargetPath(); + return internalResource.getResourceType() == ResourceType.DRL || + (internalResource.getResourceType() == null && + ((sourcePath != null && sourcePath.endsWith(".drl")) || + (targetPath != null && targetPath.endsWith(".drl")))); + } + + private static Resource convertResourceForNewParser(InternalResource internalResource, String drl) { + Resource resourceForNewParserTest = getResources().newReaderResource(new StringReader(replaceAgendaGroupIfRequired(drl))); + resourceForNewParserTest.setSourcePath(internalResource.getSourcePath()); + resourceForNewParserTest.setTargetPath(internalResource.getTargetPath()); + resourceForNewParserTest.setResourceType(internalResource.getResourceType()); + return resourceForNewParserTest; + } + + public static String replaceAgendaGroupIfRequired(String drl) { + if (DrlParser.ANTLR4_PARSER_ENABLED) { + // new parser (DRL10) supports only ruleflow-group, dropping agenda-group + return drl.replaceAll("agenda-group", "ruleflow-group"); + } + return drl; + } + + private static InputType getInputType(InternalResource internalResource) { + if (!(internalResource instanceof ClassPathResource classPathResource)) { + return InputType.CSV; + } + String path = classPathResource.getPath(); + switch (path.substring(path.lastIndexOf('.') + 1)) { + case "xls", "xlsx": + return InputType.XLS; + case "csv": + return InputType.CSV; + default: + throw new IllegalArgumentException("Unsupported input type: " + path); + } + } + public static KieBuilder getKieBuilderFromDrls(final KieBaseTestConfiguration kieBaseTestConfiguration, final boolean failIfBuildError, final String... drls) { final List resources = getResourcesFromDrls(drls); return getKieBuilderFromResources(kieBaseTestConfiguration, failIfBuildError, resources.toArray(new Resource[]{})); } + public static KieBuilder getKieBuilderFromDrls(final KieBaseTestConfiguration kieBaseTestConfiguration, final KieModuleModel kieModuleModel, + final boolean failIfBuildError, final String... drls) { + final List resources = getResourcesFromDrls(drls); + final KieFileSystem kieFileSystem = getKieFileSystemWithKieModule(kieModuleModel, KieServices.get().getRepository().getDefaultReleaseId(), resources.toArray(new Resource[]{})); + return getKieBuilderFromKieFileSystem(kieBaseTestConfiguration, kieFileSystem, failIfBuildError); + } + public static KieBuilder getKieBuilderFromDrls(final KieBaseTestConfiguration kieBaseTestConfiguration,final Map kieModuleConfigurationProperties, final boolean failIfBuildError, final String... drls) { final List resources = getResourcesFromDrls(drls);